]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-878.260.1.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2018 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 #include "anonymous.h"
31
32 // Disable certain benign warnings with Microsoft compilers
33 #if (defined(_MSC_VER))
34 // Disable "conditional expression is constant" warning for debug macros.
35 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
36 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
37 #pragma warning(disable:4127)
38
39 // Disable "assignment within conditional expression".
40 // Other compilers understand the convention that if you place the assignment expression within an extra pair
41 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
42 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
43 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
44 #pragma warning(disable:4706)
45 #endif
46
47 #include "dns_sd.h" // for kDNSServiceFlags* definitions
48 #include "dns_sd_internal.h"
49
50 #if APPLE_OSX_mDNSResponder
51 #include <WebFilterDNS/WebFilterDNS.h>
52
53 // Delay in seconds before disabling multicast after there are no active queries or registrations.
54 #define BONJOUR_DISABLE_DELAY 60
55
56 #if !NO_WCF
57 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
58 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
59
60 // Do we really need to define a macro for "if"?
61 #define CHECK_WCF_FUNCTION(X) if (X)
62 #endif // ! NO_WCF
63
64 #else
65
66 #define NO_WCF 1
67 #endif // APPLE_OSX_mDNSResponder
68
69 #if AWD_METRICS
70 #include "Metrics.h"
71 #endif
72
73 #if USE_DNS64
74 #include "DNS64.h"
75 #endif
76
77 #ifdef UNIT_TEST
78 #include "unittest.h"
79 #endif
80
81 // Forward declarations
82 mDNSlocal void BeginSleepProcessing(mDNS *const m);
83 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
84 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly);
85 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
86 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
87 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q);
88 mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
89 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth,
90 mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
91
92 mDNSlocal void AdvertiseAllInterfaceRecords(mDNS *const m);
93 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m);
94 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords);
95 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
96 const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records);
97 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth);
98
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 #define NO_HINFO 1
109
110 // Any records bigger than this are considered 'large' records
111 #define SmallRecordLimit 1024
112
113 #define kMaxUpdateCredits 10
114 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
115
116 // define special NR_AnswerTo values
117 #define NR_AnswerMulticast (mDNSu8*)~0
118 #define NR_AnswerUnicast (mDNSu8*)~1
119
120 // Question default timeout values
121 #define DEFAULT_MCAST_TIMEOUT 5
122 #define DEFAULT_LO_OR_P2P_TIMEOUT 5
123
124 // The code (see SendQueries() and BuildQuestion()) needs to have the
125 // RequestUnicast value set to a value one greater than the number of times you want the query
126 // sent with the "request unicast response" (QU) bit set.
127 #define SET_QU_IN_FIRST_QUERY 2
128 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
129
130 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
131 #define DARK_WAKE_DELAY_SLEEP 5
132 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
133
134 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
135 #define MAX_CONFLICT_PROCESSING_DELAYS 3
136
137 // RFC 6762 defines Passive Observation Of Failures (POOF)
138 //
139 // A host observes the multicast queries issued by the other hosts on
140 // the network. One of the major benefits of also sending responses
141 // using multicast is that it allows all hosts to see the responses
142 // (or lack thereof) to those queries.
143 //
144 // If a host sees queries, for which a record in its cache would be
145 // expected to be given as an answer in a multicast response, but no
146 // such answer is seen, then the host may take this as an indication
147 // that the record may no longer be valid.
148 //
149 // After seeing two or more of these queries, and seeing no multicast
150 // response containing the expected answer within ten seconds, then even
151 // though its TTL may indicate that it is not yet due to expire, that
152 // record SHOULD be flushed from the cache.
153 //
154 // <https://tools.ietf.org/html/rfc6762#section-10.5>
155
156 #define POOF_ENABLED 1
157
158 mDNSexport const char *const mDNS_DomainTypeNames[] =
159 {
160 "b._dns-sd._udp.", // Browse
161 "db._dns-sd._udp.", // Default Browse
162 "lb._dns-sd._udp.", // Automatic Browse
163 "r._dns-sd._udp.", // Registration
164 "dr._dns-sd._udp." // Default Registration
165 };
166
167 #ifdef UNICAST_DISABLED
168 #define uDNS_IsActiveQuery(q, u) mDNSfalse
169 #endif
170
171 // ***************************************************************************
172 #if COMPILER_LIKES_PRAGMA_MARK
173 #pragma mark -
174 #pragma mark - General Utility Functions
175 #endif
176
177 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
178 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
179 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
180 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
181 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
182 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
183 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
184 (rr)->resrec.rrtype == kDNSType_CNAME || \
185 (rr)->resrec.rrtype == kDNSType_PTR))
186
187 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
188 {
189 mDNS_CheckLock(m);
190
191 if (m->NextScheduledStopTime - q->StopTime > 0)
192 m->NextScheduledStopTime = q->StopTime;
193 }
194
195 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
196 {
197 mDNS_CheckLock(m);
198
199 if (ActiveQuestion(q))
200 {
201 // Depending on whether this is a multicast or unicast question we want to set either:
202 // m->NextScheduledQuery = NextQSendTime(q) or
203 // m->NextuDNSEvent = NextQSendTime(q)
204 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
205 if (*timer - NextQSendTime(q) > 0)
206 *timer = NextQSendTime(q);
207 }
208 }
209
210 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
211 {
212 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
213 unsigned int i;
214 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
215 #endif
216 e->next = r->rrauth_free;
217 r->rrauth_free = e;
218 r->rrauth_totalused--;
219 }
220
221 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
222 {
223 AuthEntity *e = (AuthEntity *)(*cp);
224 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp)->name->c);
225 if ((*cp)->rrauth_tail != &(*cp)->members)
226 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
227 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
228 (*cp)->name = mDNSNULL;
229 *cp = (*cp)->next; // Cut record from list
230 ReleaseAuthEntity(r, e);
231 }
232
233 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
234 {
235 AuthEntity *e = mDNSNULL;
236
237 if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
238 r->rrauth_lock = 1;
239
240 if (!r->rrauth_free)
241 {
242 // We allocate just one AuthEntity at a time because we need to be able
243 // free them all individually which normally happens when we parse /etc/hosts into
244 // AuthHash where we add the "new" entries and discard (free) the already added
245 // entries. If we allocate as chunks, we can't free them individually.
246 AuthEntity *storage = mDNSPlatformMemAllocate(sizeof(AuthEntity));
247 storage->next = mDNSNULL;
248 r->rrauth_free = storage;
249 }
250
251 // If we still have no free records, recycle all the records we can.
252 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
253 if (!r->rrauth_free)
254 {
255 mDNSu32 oldtotalused = r->rrauth_totalused;
256 mDNSu32 slot;
257 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
258 {
259 AuthGroup **cp = &r->rrauth_hash[slot];
260 while (*cp)
261 {
262 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
263 else ReleaseAuthGroup(r, cp);
264 }
265 }
266 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
267 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
268 }
269
270 if (r->rrauth_free) // If there are records in the free list, take one
271 {
272 e = r->rrauth_free;
273 r->rrauth_free = e->next;
274 if (++r->rrauth_totalused >= r->rrauth_report)
275 {
276 LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
277 if (r->rrauth_report < 100) r->rrauth_report += 10;
278 else if (r->rrauth_report < 1000) r->rrauth_report += 100;
279 else r->rrauth_report += 1000;
280 }
281 mDNSPlatformMemZero(e, sizeof(*e));
282 }
283
284 r->rrauth_lock = 0;
285
286 return(e);
287 }
288
289 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name)
290 {
291 AuthGroup *ag;
292 const mDNSu32 slot = namehash % AUTH_HASH_SLOTS;
293
294 for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
295 if (ag->namehash == namehash && SameDomainName(ag->name, name))
296 break;
297 return(ag);
298 }
299
300 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr)
301 {
302 return(AuthGroupForName(r, rr->namehash, rr->name));
303 }
304
305 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const ResourceRecord *const rr)
306 {
307 mDNSu16 namelen = DomainNameLength(rr->name);
308 AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
309 const mDNSu32 slot = rr->namehash % AUTH_HASH_SLOTS;
310 if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
311 ag->next = r->rrauth_hash[slot];
312 ag->namehash = rr->namehash;
313 ag->members = mDNSNULL;
314 ag->rrauth_tail = &ag->members;
315 ag->NewLocalOnlyRecords = mDNSNULL;
316 if (namelen > sizeof(ag->namestorage))
317 ag->name = mDNSPlatformMemAllocate(namelen);
318 else
319 ag->name = (domainname*)ag->namestorage;
320 if (!ag->name)
321 {
322 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
323 ReleaseAuthEntity(r, (AuthEntity*)ag);
324 return(mDNSNULL);
325 }
326 AssignDomainName(ag->name, rr->name);
327
328 if (AuthGroupForRecord(r, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
329 r->rrauth_hash[slot] = ag;
330 if (AuthGroupForRecord(r, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
331
332 return(ag);
333 }
334
335 // Returns the AuthGroup in which the AuthRecord was inserted
336 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
337 {
338 AuthGroup *ag;
339
340 (void)m;
341 ag = AuthGroupForRecord(r, &rr->resrec);
342 if (!ag) ag = GetAuthGroup(r, &rr->resrec); // If we don't have a AuthGroup for this name, make one now
343 if (ag)
344 {
345 *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list
346 ag->rrauth_tail = &(rr->next); // Advance tail pointer
347 }
348 return ag;
349 }
350
351 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
352 {
353 AuthGroup *a;
354 AuthRecord **rp;
355
356 a = AuthGroupForRecord(r, &rr->resrec);
357 if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
358 rp = &a->members;
359 while (*rp)
360 {
361 if (*rp != rr)
362 rp=&(*rp)->next;
363 else
364 {
365 // We don't break here, so that we can set the tail below without tracking "prev" pointers
366
367 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
368 *rp = (*rp)->next; // Cut record from list
369 }
370 }
371 // TBD: If there are no more members, release authgroup ?
372 a->rrauth_tail = rp;
373 return a;
374 }
375
376 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name)
377 {
378 CacheGroup *cg;
379 mDNSu32 slot = HashSlotFromNameHash(namehash);
380 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
381 if (cg->namehash == namehash && SameDomainName(cg->name, name))
382 break;
383 return(cg);
384 }
385
386 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const ResourceRecord *const rr)
387 {
388 return(CacheGroupForName(m, rr->namehash, rr->name));
389 }
390
391 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
392 {
393 NetworkInterfaceInfo *intf;
394
395 if (addr->type == mDNSAddrType_IPv4)
396 {
397 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
398 if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
399 for (intf = m->HostInterfaces; intf; intf = intf->next)
400 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
401 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
402 return(mDNStrue);
403 }
404
405 if (addr->type == mDNSAddrType_IPv6)
406 {
407 if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
408 for (intf = m->HostInterfaces; intf; intf = intf->next)
409 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
410 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
411 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
412 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
413 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
414 return(mDNStrue);
415 }
416
417 return(mDNSfalse);
418 }
419
420 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
421 {
422 NetworkInterfaceInfo *intf = m->HostInterfaces;
423 while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
424 return(intf);
425 }
426
427 mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
428 {
429 NetworkInterfaceInfo *intf;
430
431 if (!InterfaceID)
432 return mDNSNULL;
433
434 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
435 // we still want to find the first IPv4 Link-Local interface
436 for (intf = m->HostInterfaces; intf; intf = intf->next)
437 {
438 if (intf->InterfaceID == InterfaceID &&
439 intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4))
440 {
441 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4);
442 return intf;
443 }
444 }
445 return (mDNSNULL);
446 }
447
448 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
449 {
450 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
451 return(intf ? intf->ifname : mDNSNULL);
452 }
453
454 // Caller should hold the lock
455 mDNSlocal void GenerateNegativeResponse(mDNS *const m, mDNSInterfaceID InterfaceID, QC_result qc)
456 {
457 DNSQuestion *q;
458 if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
459 q = m->CurrentQuestion;
460 LogInfo("GenerateNegativeResponse: Generating negative response for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
461
462 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, InterfaceID, mDNSNULL);
463
464 // We need to force the response through in the following cases
465 //
466 // a) SuppressUnusable questions that are suppressed
467 // b) Append search domains and retry the question
468 //
469 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
470 // through we use "QC_forceresponse".
471 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc);
472 if (m->CurrentQuestion == q) { q->ThisQInterval = 0; } // Deactivate this question
473 // Don't touch the question after this
474 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
475 }
476
477 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
478 {
479 const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
480 if (q->CNAMEReferrals >= 10 || selfref)
481 {
482 LogMsg("AnswerQuestionByFollowingCNAME: %p %##s (%s) NOT following CNAME referral %d%s for %s",
483 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
484 }
485 else
486 {
487 const mDNSu32 c = q->CNAMEReferrals + 1; // Stash a copy of the new q->CNAMEReferrals value
488 UDPSocket *sock = q->LocalSocket;
489 mDNSOpaque16 id = q->TargetQID;
490 #if AWD_METRICS
491 uDNSMetrics metrics;
492 #endif
493
494 q->LocalSocket = mDNSNULL;
495
496 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
497 // themselves. Without that check we can get into a case where we have two duplicate questions,
498 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
499 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
500 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
501 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
502 // for either of them. This is not a problem for CNAME loops of two or more records because in
503 // those cases the newly re-appended question A has a different target name and therefore cannot be
504 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
505
506 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
507 // and track CNAMEs coming and going, we should really create a subordinate query here,
508 // which we would subsequently cancel and retract if the CNAME referral record were removed.
509 // In reality this is such a corner case we'll ignore it until someone actually needs it.
510
511 LogInfo("AnswerQuestionByFollowingCNAME: %p %##s (%s) following CNAME referral %d for %s",
512 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, RRDisplayString(m, rr));
513
514 #if AWD_METRICS
515 if ((q->CNAMEReferrals == 0) && !q->metrics.originalQName)
516 {
517 domainname * qName;
518 mDNSu16 qNameLen;
519
520 qNameLen = DomainNameLength(&q->qname);
521 if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME))
522 {
523 qName = mDNSPlatformMemAllocate(qNameLen);
524 if (qName)
525 {
526 mDNSPlatformMemCopy(qName->c, q->qname.c, qNameLen);
527 q->metrics.originalQName = qName;
528 }
529 }
530 }
531 metrics = q->metrics;
532 mDNSPlatformMemZero(&q->metrics, sizeof(q->metrics));
533 #endif
534 mDNS_StopQuery_internal(m, q); // Stop old query
535 AssignDomainName(&q->qname, &rr->rdata->u.name); // Update qname
536 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
537 // If a unicast query results in a CNAME that points to a .local, we need to re-try
538 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
539 // to try this as unicast query even though it is a .local name
540 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
541 {
542 LogInfo("AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p %##s (%s) Record %s",
543 q, q->qname.c, DNSTypeName(q->qtype), RRDisplayString(m, rr));
544 q->InterfaceID = mDNSInterface_Unicast;
545 }
546 mDNS_StartQuery_internal(m, q); // start new query
547 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
548 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
549 q->CNAMEReferrals = c;
550 #if AWD_METRICS
551 metrics.expiredAnswerState = q->metrics.expiredAnswerState; // We want the newly initialized state for this value
552 q->metrics = metrics;
553 #endif
554 if (sock)
555 {
556 // 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.
557 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
558 else
559 {
560 // Transplant the old socket into the new question, and copy the query ID across too.
561 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
562 q->LocalSocket = sock;
563 q->TargetQID = id;
564 }
565 }
566 }
567 }
568
569 #ifdef USE_LIBIDN
570
571 #include <unicode/uidna.h>
572
573 // #define DEBUG_PUNYCODE 1
574
575 mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end)
576 {
577 UErrorCode errorCode = U_ZERO_ERROR;
578 UIDNAInfo info = UIDNA_INFO_INITIALIZER;
579 UIDNA *uts46 = uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE, &errorCode);
580 int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, end-(dst+1), &info, &errorCode);
581 uidna_close(uts46);
582 #if DEBUG_PUNYCODE
583 if (errorCode) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src, errorCode);
584 if (info.errors) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src, info.errors);
585 if (len > MAX_DOMAIN_LABEL) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src, len);
586 #endif
587 if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL;
588 *dst = len;
589 return(dst + 1 + len);
590 }
591
592 mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d)
593 {
594 int i;
595 for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue;
596 return mDNSfalse;
597 }
598
599 mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d)
600 {
601 const mDNSu8 *ptr = d->c;
602 const mDNSu8 *ans = mDNSNULL;
603 while (ptr[0])
604 {
605 const mDNSu8 *const next = ptr + 1 + ptr[0];
606 if (ptr[0] > MAX_DOMAIN_LABEL || next >= d->c + MAX_DOMAIN_NAME) return mDNSNULL;
607 if (IsHighASCIILabel(ptr)) ans = ptr;
608 ptr = next;
609 }
610 return ans;
611 }
612
613 mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname)
614 {
615 const mDNSu8 *h = FindLastHighASCIILabel(&q->qname);
616 #if DEBUG_PUNYCODE
617 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h);
618 #endif
619 if (!h) return mDNSfalse; // There are no high-ascii labels to convert
620
621 mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME);
622 if (!dst)
623 return mDNSfalse; // The label was not convertible to Punycode
624 else
625 {
626 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
627 const mDNSu8 *const src = h + 1 + h[0];
628 const mDNSu8 remainder = DomainNameLength((domainname*)src);
629 if (dst + remainder > newname->c + MAX_DOMAIN_NAME) return mDNSfalse; // Name too long -- cannot be converted to Punycode
630
631 mDNSPlatformMemCopy(newname->c, q->qname.c, h - q->qname.c); // Fill in the leading part
632 mDNSPlatformMemCopy(dst, src, remainder); // Fill in the trailing part
633 #if DEBUG_PUNYCODE
634 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c);
635 #endif
636 return mDNStrue;
637 }
638 }
639
640 #endif // USE_LIBIDN
641
642 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
643 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
644 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
645 {
646 DNSQuestion *q = m->CurrentQuestion;
647 mDNSBool followcname;
648
649 if (!q)
650 {
651 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
652 return;
653 }
654
655 followcname = FollowCNAME(q, &rr->resrec, AddRecord);
656
657 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
658 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
659 {
660 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
661 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
662 return;
663 }
664
665 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
666 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
667 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
668 if (q->QuestionCallback && !q->NoAnswer)
669 {
670 q->CurrentAnswers += AddRecord ? 1 : -1;
671 if (UniqueLocalOnlyRecord(rr))
672 {
673 if (!followcname || q->ReturnIntermed)
674 {
675 // Don't send this packet on the wire as we answered from /etc/hosts
676 q->ThisQInterval = 0;
677 q->LOAddressAnswers += AddRecord ? 1 : -1;
678 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
679 }
680 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
681 // The callback above could have caused the question to stop. Detect that
682 // using m->CurrentQuestion
683 if (followcname && m->CurrentQuestion == q)
684 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
685 return;
686 }
687 else
688 {
689 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
690 }
691 }
692 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
693 }
694
695 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
696 {
697 if (m->CurrentQuestion)
698 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
699 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
700 m->CurrentQuestion = m->Questions;
701 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
702 {
703 mDNSBool answered;
704 DNSQuestion *q = m->CurrentQuestion;
705 if (RRAny(rr))
706 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
707 else
708 answered = LocalOnlyRecordAnswersQuestion(rr, q);
709 if (answered)
710 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
711 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
712 m->CurrentQuestion = q->next;
713 }
714 m->CurrentQuestion = mDNSNULL;
715 }
716
717 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
718 // delivers the appropriate add/remove events to listening questions:
719 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
720 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
721 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
722 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
723 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
724 //
725 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
726 // and by mDNS_Deregister_internal()
727
728 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
729 {
730 if (m->CurrentQuestion)
731 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
732 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
733
734 m->CurrentQuestion = m->LocalOnlyQuestions;
735 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
736 {
737 mDNSBool answered;
738 DNSQuestion *q = m->CurrentQuestion;
739 // We are called with both LocalOnly/P2P record or a regular AuthRecord
740 if (RRAny(rr))
741 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
742 else
743 answered = LocalOnlyRecordAnswersQuestion(rr, q);
744 if (answered)
745 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
746 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
747 m->CurrentQuestion = q->next;
748 }
749
750 m->CurrentQuestion = mDNSNULL;
751
752 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
753 if (rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P)
754 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, rr, AddRecord);
755
756 }
757
758 // ***************************************************************************
759 #if COMPILER_LIKES_PRAGMA_MARK
760 #pragma mark -
761 #pragma mark - Resource Record Utility Functions
762 #endif
763
764 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
765
766 #define ResourceRecordIsValidAnswer(RR) ( ((RR)->resrec.RecordType & kDNSRecordTypeActiveMask) && \
767 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
768 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
769 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
770
771 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
772 (ResourceRecordIsValidAnswer(RR) && \
773 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
774
775 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
776 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
777
778 // See RFC 6762: "8.3 Announcing"
779 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
780 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
781 #define InitialAnnounceCount ((mDNSu8)4)
782
783 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
784 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
785 // and then if the machine fails to wake, 3 goodbye packets).
786 #define GoodbyeCount ((mDNSu8)3)
787 #define WakeupCount ((mDNSu8)18)
788 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
789 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week
790
791 // Number of wakeups we send if WakeOnResolve is set in the question
792 #define InitialWakeOnResolveCount ((mDNSu8)3)
793
794 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
795 // This means that because the announce interval is doubled after sending the first packet, the first
796 // observed on-the-wire inter-packet interval between announcements is actually one second.
797 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
798 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
799 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
800 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
801
802 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
803 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
804 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
805
806 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
807 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
808 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
809
810 // Adjustment factor to avoid race condition (used for unicast cache entries) :
811 // 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.
812 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
813 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
814 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
815 // We adjust the 100 second TTL to 127. This means that when we do our 80% query at 102 seconds,
816 // the cached copy at our local caching server will already have expired, so the server will be forced
817 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
818
819 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
820 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
821
822 #define MaxUnansweredQueries 4
823
824 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
825 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
826 // TTL and rdata may differ.
827 // This is used for cache flush management:
828 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
829 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
830
831 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
832
833 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
834
835 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
836 {
837 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
838 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
839 if (r1->resrec.InterfaceID &&
840 r2->resrec.InterfaceID &&
841 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
842 return (mDNSBool)(
843 r1->resrec.rrclass == r2->resrec.rrclass &&
844 r1->resrec.namehash == r2->resrec.namehash &&
845 SameDomainName(r1->resrec.name, r2->resrec.name));
846 }
847
848 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
849 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
850 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
851 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
852 // so a response of any type should match, even if it is not actually the type the client plans to use.
853
854 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
855 // and require the rrtypes to match for the rdata to be considered potentially conflicting
856 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
857 {
858 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
859 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
860 if (pktrr->resrec.InterfaceID &&
861 authrr->resrec.InterfaceID &&
862 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
863 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
864 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
865 if ((authrr->resrec.InterfaceID == mDNSInterface_Any) &&
866 !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse);
867 return (mDNSBool)(
868 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
869 pktrr->resrec.namehash == authrr->resrec.namehash &&
870 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
871 }
872
873 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
874 // This is the information that the requester believes to be correct.
875 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
876 // This is the information that we believe to be correct.
877 // We've already determined that we plan to give this answer on this interface
878 // (either the record is non-specific, or it is specific to this interface)
879 // so now we just need to check the name, type, class, rdata and TTL.
880 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
881 {
882 // If RR signature is different, or data is different, then don't suppress our answer
883 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
884
885 // If the requester's indicated TTL is less than half the real TTL,
886 // we need to give our answer before the requester's copy expires.
887 // If the requester's indicated TTL is at least half the real TTL,
888 // then we can suppress our answer this time.
889 // If the requester's indicated TTL is greater than the TTL we believe,
890 // then that's okay, and we don't need to do anything about it.
891 // (If two responders on the network are offering the same information,
892 // that's okay, and if they are offering the information with different TTLs,
893 // the one offering the lower TTL should defer to the one offering the higher TTL.)
894 return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
895 }
896
897 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
898 {
899 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
900 {
901 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
902 {
903 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
904 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
905 }
906 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
907 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
908 // Some defensive code:
909 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
910 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
911 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
912 if (m->NextScheduledProbe - m->timenow < 0)
913 m->NextScheduledProbe = m->timenow;
914 }
915 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
916 {
917 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
918 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
919 }
920 }
921
922 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
923 {
924 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
925 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
926
927 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
928 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
929 // records that are going to probe, then we delay its first announcement so that it will
930 // go out synchronized with the first announcement for the other records that *are* probing.
931 // This is a minor performance tweak that helps keep groups of related records synchronized together.
932 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
933 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
934 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
935 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
936 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
937
938 if (rr->ProbeCount)
939 {
940 // If we have no probe suppression time set, or it is in the past, set it now
941 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
942 {
943 // To allow us to aggregate probes when a group of services are registered together,
944 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
945 // This means the common-case behaviour is:
946 // randomized wait; probe
947 // 1/4 second wait; probe
948 // 1/4 second wait; probe
949 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
950 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
951
952 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
953 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
954 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
955 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
956 m->SuppressProbes = m->timenow;
957
958 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
959 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
960 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
961 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
962 m->SuppressProbes = m->timenow;
963
964 // except... don't expect to be able to send before the m->SuppressSending timer fires
965 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
966 m->SuppressProbes = NonZeroTime(m->SuppressSending);
967
968 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
969 {
970 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
971 m->SuppressProbes - m->timenow,
972 m->NextScheduledProbe - m->timenow,
973 m->NextScheduledQuery - m->timenow,
974 m->SuppressSending,
975 m->SuppressSending - m->timenow);
976 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
977 }
978 }
979 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
980 }
981 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
982 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
983 else if ((rr->resrec.RecordType != kDNSRecordTypeKnownUnique) && (rr->resrec.RecordType != kDNSRecordTypeShared) && m->SuppressProbes && (m->SuppressProbes - m->timenow >= 0))
984 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
985 else
986 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
987
988 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
989 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
990 // After three probes one second apart with no answer, we conclude the client is now sleeping
991 // and we can begin broadcasting our announcements to take over ownership of that IP address.
992 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
993 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
994 if (rr->AddressProxy.type)
995 rr->LastAPTime = m->timenow;
996
997 // Set LastMCTime to now, to inhibit multicast responses
998 // (no need to send additional multicast responses when we're announcing anyway)
999 rr->LastMCTime = m->timenow;
1000 rr->LastMCInterface = mDNSInterfaceMark;
1001
1002 SetNextAnnounceProbeTime(m, rr);
1003 }
1004
1005 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
1006 {
1007 const domainname *target;
1008 if (rr->AutoTarget)
1009 {
1010 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
1011 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
1012 // with the port number in our advertised SRV record automatically tracking the external mapped port.
1013 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
1014 if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
1015 }
1016
1017 target = GetServiceTarget(m, rr);
1018 if (!target || target->c[0] == 0)
1019 {
1020 // defer registration until we've got a target
1021 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
1022 rr->state = regState_NoTarget;
1023 return mDNSNULL;
1024 }
1025 else
1026 {
1027 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
1028 return target;
1029 }
1030 }
1031
1032 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1033 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1034 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
1035 {
1036 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
1037 const domainname *newname = &m->MulticastHostname;
1038
1039 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
1040
1041 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
1042 {
1043 const domainname *const n = SetUnicastTargetToHostName(m, rr);
1044 if (n) newname = n;
1045 else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
1046 }
1047
1048 if (target && SameDomainName(target, newname))
1049 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
1050
1051 if (target && !SameDomainName(target, newname))
1052 {
1053 AssignDomainName(target, newname);
1054 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
1055
1056 // If we're in the middle of probing this record, we need to start again,
1057 // because changing its rdata may change the outcome of the tie-breaker.
1058 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1059 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1060
1061 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1062 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1063 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1064 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
1065 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1066 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1067
1068 rr->AnnounceCount = InitialAnnounceCount;
1069 rr->RequireGoodbye = mDNSfalse;
1070 rr->ProbeRestartCount = 0;
1071 InitializeLastAPTime(m, rr);
1072 }
1073 }
1074
1075 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
1076 {
1077 if (rr->RecordCallback)
1078 {
1079 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1080 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1081 rr->Acknowledged = mDNStrue;
1082 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1083 rr->RecordCallback(m, rr, mStatus_NoError);
1084 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1085 }
1086 }
1087
1088 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
1089 {
1090 // Make sure that we don't activate the SRV record and associated service records, if it is in
1091 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1092 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1093 // the target becomes available, the records will be reregistered.
1094 if (rr->resrec.rrtype != kDNSType_SRV)
1095 {
1096 AuthRecord *srvRR = mDNSNULL;
1097 if (rr->resrec.rrtype == kDNSType_PTR)
1098 srvRR = rr->Additional1;
1099 else if (rr->resrec.rrtype == kDNSType_TXT)
1100 srvRR = rr->DependentOn;
1101 if (srvRR)
1102 {
1103 if (srvRR->resrec.rrtype != kDNSType_SRV)
1104 {
1105 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1106 }
1107 else
1108 {
1109 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1110 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1111 rr->state = srvRR->state;
1112 }
1113 }
1114 }
1115
1116 if (rr->state == regState_NoTarget)
1117 {
1118 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1119 return;
1120 }
1121 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1122 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1123 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1124 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1125 // 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.
1126 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1127 {
1128 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1129 rr->state = regState_DeregPending;
1130 }
1131 else
1132 {
1133 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1134 rr->state = regState_Pending;
1135 }
1136 rr->ProbeCount = 0;
1137 rr->ProbeRestartCount = 0;
1138 rr->AnnounceCount = 0;
1139 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1140 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1141 rr->expire = 0; // Forget about all the leases, start fresh
1142 rr->uselease = mDNStrue;
1143 rr->updateid = zeroID;
1144 rr->SRVChanged = mDNSfalse;
1145 rr->updateError = mStatus_NoError;
1146 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1147 // The records might already be registered with the server and hence could have NAT state.
1148 if (rr->NATinfo.clientContext)
1149 {
1150 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1151 rr->NATinfo.clientContext = mDNSNULL;
1152 }
1153 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1154 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1155 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1156 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1157 }
1158
1159 // Two records qualify to be local duplicates if:
1160 // (a) the RecordTypes are the same, or
1161 // (b) one is Unique and the other Verified
1162 // (c) either is in the process of deregistering
1163 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1164 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1165 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1166
1167 #define RecordIsLocalDuplicate(A,B) \
1168 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1169
1170 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1171 {
1172 const AuthGroup *a;
1173 AuthRecord *rp;
1174
1175 a = AuthGroupForRecord(r, &rr->resrec);
1176 if (!a) return mDNSNULL;
1177 rp = a->members;
1178 while (rp)
1179 {
1180 if (!RecordIsLocalDuplicate(rp, rr))
1181 rp = rp->next;
1182 else
1183 {
1184 if (rp->resrec.RecordType == kDNSRecordTypeDeregistering)
1185 {
1186 rp->AnnounceCount = 0;
1187 rp = rp->next;
1188 }
1189 else return rp;
1190 }
1191 }
1192 return (mDNSNULL);
1193 }
1194
1195 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1196 {
1197 const AuthGroup *a;
1198 const AuthRecord *rp;
1199
1200 a = AuthGroupForRecord(r, &rr->resrec);
1201 if (!a) return mDNSfalse;
1202 rp = a->members;
1203 while (rp)
1204 {
1205 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1206 const AuthRecord *s2 = rp->RRSet ? rp->RRSet : rp;
1207 if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec))
1208 return mDNStrue;
1209 else
1210 rp = rp->next;
1211 }
1212 return (mDNSfalse);
1213 }
1214
1215 // checks to see if "rr" is already present
1216 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1217 {
1218 const AuthGroup *a;
1219 AuthRecord *rp;
1220
1221 a = AuthGroupForRecord(r, &rr->resrec);
1222 if (!a) return mDNSNULL;
1223 rp = a->members;
1224 while (rp)
1225 {
1226 if (rp != rr)
1227 rp = rp->next;
1228 else
1229 {
1230 return rp;
1231 }
1232 }
1233 return (mDNSNULL);
1234 }
1235
1236
1237 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1238 {
1239 if (RRLocalOnly(rr))
1240 {
1241 // A sanity check, this should be prevented in calling code.
1242 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1243 return;
1244 }
1245
1246 if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1247 {
1248 // If about to get rid of the last advertised service
1249 if (m->AutoTargetServices == 1)
1250 DeadvertiseAllInterfaceRecords(m);
1251
1252 m->AutoTargetServices--;
1253 LogInfo("DecrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
1254 }
1255
1256 #if BONJOUR_ON_DEMAND
1257 if (!AuthRecord_uDNS(rr))
1258 {
1259 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1260 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
1261 m->NumAllInterfaceRecords--;
1262 LogInfo("DecrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1263 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1264 }
1265 #endif // BONJOUR_ON_DEMAND
1266 }
1267
1268 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1269 {
1270 mDNSBool enablingBonjour = 0;
1271
1272 if (RRLocalOnly(rr))
1273 {
1274 // A sanity check, this should be prevented in calling code.
1275 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1276 return;
1277 }
1278
1279 #if BONJOUR_ON_DEMAND
1280 if (!AuthRecord_uDNS(rr))
1281 {
1282 m->NumAllInterfaceRecords++;
1283 LogInfo("IncrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1284 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1285 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1286 {
1287 m->NextBonjourDisableTime = 0;
1288 if (m->BonjourEnabled == 0)
1289 {
1290 // Enable Bonjour immediately by scheduling network changed processing where
1291 // we will join the multicast group on each active interface.
1292 m->BonjourEnabled = 1;
1293 enablingBonjour = 1;
1294 m->NetworkChanged = m->timenow;
1295 }
1296 }
1297 }
1298 #endif // BONJOUR_ON_DEMAND
1299
1300 if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1301 {
1302 m->AutoTargetServices++;
1303 LogInfo("IncrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
1304
1305 // If this is the first advertised service and we did not just enable Bonjour above, then
1306 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1307 // be advertised during the network changed processing scheduled above, so no need
1308 // to do it here.
1309 if ((m->AutoTargetServices == 1) && (enablingBonjour == 0))
1310 AdvertiseAllInterfaceRecords(m);
1311 }
1312 }
1313
1314 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1315 {
1316 mDNSAddr laddr = zeroAddr;
1317 mDNSEthAddr eth = zeroEthAddr;
1318 mDNSIPPort lport = zeroIPPort;
1319 mDNSIPPort rport = zeroIPPort;
1320 mDNSu32 timeout = 0;
1321 mDNSu32 seq = 0;
1322 mDNSu32 ack = 0;
1323 mDNSu16 win = 0;
1324
1325 if (mDNS_KeepaliveRecord(&rr->resrec))
1326 {
1327 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, &eth, &seq, &ack, &lport, &rport, &win);
1328 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1329 {
1330 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1331 return;
1332 }
1333 }
1334 }
1335
1336 // Exported so uDNS.c can call this
1337 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1338 {
1339 domainname *target = GetRRDomainNameTarget(&rr->resrec);
1340 AuthRecord *r;
1341 AuthRecord **p = &m->ResourceRecords;
1342 AuthRecord **d = &m->DuplicateRecords;
1343
1344 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1345 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1346
1347 if (!rr->resrec.RecordType)
1348 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1349
1350 if (m->ShutdownTime)
1351 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1352
1353 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1354 {
1355 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1356 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1357 {
1358 rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1359 rr->ARType = AuthRecordLocalOnly;
1360 }
1361 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1362 {
1363 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1364 if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1365 }
1366 if (rr->resrec.InterfaceID != previousID)
1367 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1368 }
1369
1370 if (RRLocalOnly(rr))
1371 {
1372 if (CheckAuthSameRecord(&m->rrauth, rr))
1373 {
1374 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1375 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1376 return(mStatus_AlreadyRegistered);
1377 }
1378 }
1379 else
1380 {
1381 while (*p && *p != rr) p=&(*p)->next;
1382 if (*p)
1383 {
1384 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1385 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1386 return(mStatus_AlreadyRegistered);
1387 }
1388 }
1389
1390 while (*d && *d != rr) d=&(*d)->next;
1391 if (*d)
1392 {
1393 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1394 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1395 return(mStatus_AlreadyRegistered);
1396 }
1397
1398 if (rr->DependentOn)
1399 {
1400 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1401 rr->resrec.RecordType = kDNSRecordTypeVerified;
1402 else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique)
1403 {
1404 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1405 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1406 return(mStatus_Invalid);
1407 }
1408 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1409 {
1410 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1411 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1412 return(mStatus_Invalid);
1413 }
1414 }
1415
1416 rr->next = mDNSNULL;
1417
1418 // Field Group 1: The actual information pertaining to this resource record
1419 // Set up by client prior to call
1420
1421 // Field Group 2: Persistent metadata for Authoritative Records
1422 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1423 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1424 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1425 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1426 // rr->Callback = already set in mDNS_SetupResourceRecord
1427 // rr->Context = already set in mDNS_SetupResourceRecord
1428 // rr->RecordType = already set in mDNS_SetupResourceRecord
1429 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1430 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1431 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1432 if (rr->AutoTarget && target) target->c[0] = 0;
1433
1434 // Field Group 3: Transient state for Authoritative Records
1435 rr->Acknowledged = mDNSfalse;
1436 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1437 rr->ProbeRestartCount = 0;
1438 rr->AnnounceCount = InitialAnnounceCount;
1439 rr->RequireGoodbye = mDNSfalse;
1440 rr->AnsweredLocalQ = mDNSfalse;
1441 rr->IncludeInProbe = mDNSfalse;
1442 rr->ImmedUnicast = mDNSfalse;
1443 rr->SendNSECNow = mDNSNULL;
1444 rr->ImmedAnswer = mDNSNULL;
1445 rr->ImmedAdditional = mDNSNULL;
1446 rr->SendRNow = mDNSNULL;
1447 rr->v4Requester = zerov4Addr;
1448 rr->v6Requester = zerov6Addr;
1449 rr->NextResponse = mDNSNULL;
1450 rr->NR_AnswerTo = mDNSNULL;
1451 rr->NR_AdditionalTo = mDNSNULL;
1452 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1453 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1454 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1455 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1456 rr->NewRData = mDNSNULL;
1457 rr->newrdlength = 0;
1458 rr->UpdateCallback = mDNSNULL;
1459 rr->UpdateCredits = kMaxUpdateCredits;
1460 rr->NextUpdateCredit = 0;
1461 rr->UpdateBlocked = 0;
1462
1463 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1464 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1465
1466 // Field Group 4: Transient uDNS state for Authoritative Records
1467 rr->state = regState_Zero;
1468 rr->uselease = 0;
1469 rr->expire = 0;
1470 rr->Private = 0;
1471 rr->updateid = zeroID;
1472 rr->updateIntID = zeroOpaque64;
1473 rr->zone = rr->resrec.name;
1474 rr->nta = mDNSNULL;
1475 rr->tcp = mDNSNULL;
1476 rr->OrigRData = 0;
1477 rr->OrigRDLen = 0;
1478 rr->InFlightRData = 0;
1479 rr->InFlightRDLen = 0;
1480 rr->QueuedRData = 0;
1481 rr->QueuedRDLen = 0;
1482 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1483 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1484 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1485 // times with different values if the external NAT port changes during the lifetime of the service registration.
1486 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1487
1488 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1489 // rr->resrec.name->c = MUST be set by client
1490 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1491 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1492 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1493 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1494
1495 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1496 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1497 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1498 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1499
1500 if (rr->AutoTarget)
1501 {
1502 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1503 #ifndef UNICAST_DISABLED
1504 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1505 // 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.
1506 if (rr->state == regState_NoTarget)
1507 {
1508 // Initialize the target so that we don't crash while logging etc.
1509 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1510 if (tar) tar->c[0] = 0;
1511 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1512 }
1513 #endif
1514 }
1515 else
1516 {
1517 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
1518 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1519 }
1520
1521 if (!ValidateDomainName(rr->resrec.name))
1522 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1523
1524 // Don't do this until *after* we've set rr->resrec.rdlength
1525 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1526 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1527
1528 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
1529 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1530
1531 if (RRLocalOnly(rr))
1532 {
1533 // If this is supposed to be unique, make sure we don't have any name conflicts.
1534 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1535 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1536 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1537 // Hence, just bail out.
1538 // This comment is doesn’t make any sense. -- SC
1539 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1540 {
1541 if (CheckAuthRecordConflict(&m->rrauth, rr))
1542 {
1543 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1544 return mStatus_NameConflict;
1545 }
1546 }
1547 }
1548
1549 // For uDNS records, we don't support duplicate checks at this time.
1550 #ifndef UNICAST_DISABLED
1551 if (AuthRecord_uDNS(rr))
1552 {
1553 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1554 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1555 // 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.
1556 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1557 while (*p) p=&(*p)->next;
1558 *p = rr;
1559 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1560 rr->ProbeCount = 0;
1561 rr->ProbeRestartCount = 0;
1562 rr->AnnounceCount = 0;
1563 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1564 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
1565 }
1566 #endif
1567
1568 // Now that we've finished building our new record, make sure it's not identical to one we already have
1569 if (RRLocalOnly(rr))
1570 {
1571 rr->ProbeCount = 0;
1572 rr->ProbeRestartCount = 0;
1573 rr->AnnounceCount = 0;
1574 r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1575 }
1576 else
1577 {
1578 for (r = m->ResourceRecords; r; r=r->next)
1579 if (RecordIsLocalDuplicate(r, rr))
1580 {
1581 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1582 else break;
1583 }
1584 }
1585
1586 if (r)
1587 {
1588 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m,rr));
1589 *d = rr;
1590 // If the previous copy of this record is already verified unique,
1591 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1592 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1593 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1594 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1595 rr->ProbeCount = 0;
1596 }
1597 else
1598 {
1599 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1600 if (RRLocalOnly(rr))
1601 {
1602 AuthGroup *ag;
1603 ag = InsertAuthRecord(m, &m->rrauth, rr);
1604 if (ag && !ag->NewLocalOnlyRecords)
1605 {
1606 m->NewLocalOnlyRecords = mDNStrue;
1607 ag->NewLocalOnlyRecords = rr;
1608 }
1609 // No probing for LocalOnly records; acknowledge them right away
1610 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1611 AcknowledgeRecord(m, rr);
1612 return(mStatus_NoError);
1613 }
1614 else
1615 {
1616 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1617 *p = rr;
1618 }
1619 }
1620
1621 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
1622 {
1623 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1624 IncrementAutoTargetServices(m, rr);
1625
1626 // For records that are not going to probe, acknowledge them right away
1627 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1628 AcknowledgeRecord(m, rr);
1629
1630 // Adding a record may affect whether or not we should sleep
1631 mDNS_UpdateAllowSleep(m);
1632 }
1633
1634 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1635 // This is used by the in-NIC proxy to send the keepalive packets.
1636 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
1637 {
1638 mDNSAddr raddr;
1639 // Set the record type to known unique to prevent probing keep alive records.
1640 // Also make sure we do not announce the keepalive records.
1641 rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1642 rr->AnnounceCount = 0;
1643 getKeepaliveRaddr(m, rr, &raddr);
1644 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1645 // asynchronous task to update the resource record
1646 mDNSPlatformGetRemoteMacAddr(&raddr);
1647 }
1648
1649 return(mStatus_NoError);
1650 }
1651
1652 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1653 {
1654 m->ProbeFailTime = m->timenow;
1655 m->NumFailedProbes++;
1656 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1657 // If a bunch of hosts have all been configured with the same name, then they'll all
1658 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1659 // up to name-10. After that they'll start adding random increments in the range 1-100,
1660 // so they're more likely to branch out in the available namespace and settle on a set of
1661 // unique names quickly. If after five more tries the host is still conflicting, then we
1662 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1663 if (m->NumFailedProbes >= 15)
1664 {
1665 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1666 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1667 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1668 }
1669 }
1670
1671 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1672 {
1673 RData *OldRData = rr->resrec.rdata;
1674 mDNSu16 OldRDLen = rr->resrec.rdlength;
1675 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
1676 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
1677 if (rr->UpdateCallback)
1678 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
1679 }
1680
1681 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1682 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1683 // Exported so uDNS.c can call this
1684 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1685 {
1686 AuthRecord *r2;
1687 mDNSu8 RecordType = rr->resrec.RecordType;
1688 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
1689 mDNSBool dupList = mDNSfalse;
1690
1691 if (RRLocalOnly(rr))
1692 {
1693 AuthGroup *a;
1694 AuthRecord **rp;
1695
1696 a = AuthGroupForRecord(&m->rrauth, &rr->resrec);
1697 if (!a) return mDNSfalse;
1698 rp = &a->members;
1699 while (*rp && *rp != rr) rp=&(*rp)->next;
1700 p = rp;
1701 }
1702 else
1703 {
1704 while (*p && *p != rr) p=&(*p)->next;
1705 }
1706
1707 if (*p)
1708 {
1709 // We found our record on the main list. See if there are any duplicates that need special handling.
1710 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
1711 {
1712 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1713 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1714 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1715 }
1716 else
1717 {
1718 // Before we delete the record (and potentially send a goodbye packet)
1719 // first see if we have a record on the duplicate list ready to take over from it.
1720 AuthRecord **d = &m->DuplicateRecords;
1721 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1722 if (*d)
1723 {
1724 AuthRecord *dup = *d;
1725 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1726 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1727 *d = dup->next; // Cut replacement record from DuplicateRecords list
1728 if (RRLocalOnly(rr))
1729 {
1730 dup->next = mDNSNULL;
1731 if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1732 }
1733 else
1734 {
1735 dup->next = rr->next; // And then...
1736 rr->next = dup; // ... splice it in right after the record we're about to delete
1737 }
1738 dup->resrec.RecordType = rr->resrec.RecordType;
1739 dup->ProbeCount = rr->ProbeCount;
1740 dup->ProbeRestartCount = rr->ProbeRestartCount;
1741 dup->AnnounceCount = rr->AnnounceCount;
1742 dup->RequireGoodbye = rr->RequireGoodbye;
1743 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
1744 dup->ImmedAnswer = rr->ImmedAnswer;
1745 dup->ImmedUnicast = rr->ImmedUnicast;
1746 dup->ImmedAdditional = rr->ImmedAdditional;
1747 dup->v4Requester = rr->v4Requester;
1748 dup->v6Requester = rr->v6Requester;
1749 dup->ThisAPInterval = rr->ThisAPInterval;
1750 dup->LastAPTime = rr->LastAPTime;
1751 dup->LastMCTime = rr->LastMCTime;
1752 dup->LastMCInterface = rr->LastMCInterface;
1753 dup->Private = rr->Private;
1754 dup->state = rr->state;
1755 rr->RequireGoodbye = mDNSfalse;
1756 rr->AnsweredLocalQ = mDNSfalse;
1757 }
1758 }
1759 }
1760 else
1761 {
1762 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1763 p = &m->DuplicateRecords;
1764 while (*p && *p != rr) p=&(*p)->next;
1765 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1766 if (*p)
1767 {
1768 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1769 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1770 // also that have been marked above in this function. In that case, we come here and if we don't
1771 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1772 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1773 // details.
1774 rr->WakeUp.HMAC = zeroEthAddr;
1775 rr->RequireGoodbye = mDNSfalse;
1776 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1777 dupList = mDNStrue;
1778 }
1779 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1780 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1781 }
1782
1783 if (!*p)
1784 {
1785 // No need to log an error message if we already know this is a potentially repeated deregistration
1786 if (drt != mDNS_Dereg_repeat)
1787 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1788 return(mStatus_BadReferenceErr);
1789 }
1790
1791 // If this is a shared record and we've announced it at least once,
1792 // we need to retract that announcement before we delete the record
1793
1794 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1795 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1796 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1797 // mechanism to cope with the client callback modifying the question list while that's happening.
1798 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1799 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1800 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1801 // records, thereby invoking yet more callbacks, without limit.
1802 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1803 // actual goodbye packets.
1804
1805 #ifndef UNICAST_DISABLED
1806 if (AuthRecord_uDNS(rr))
1807 {
1808 if (rr->RequireGoodbye)
1809 {
1810 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1811 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1812 m->LocalRemoveEvents = mDNStrue;
1813 uDNS_DeregisterRecord(m, rr);
1814 // At this point unconditionally we bail out
1815 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1816 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1817 // process and will complete asynchronously. Either way we don't need to do anything more here.
1818 return(mStatus_NoError);
1819 }
1820 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1821 // from the server. In that case, if the records have been part of a group update, clear the
1822 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1823 rr->updateid = zeroID;
1824
1825 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1826 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1827 // This happens today when we turn on/off interface where we get multiple network transitions
1828 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1829 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1830 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1831 // NAT state here takes care of the case where we did not send goodbyes at all.
1832 if (rr->NATinfo.clientContext)
1833 {
1834 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1835 rr->NATinfo.clientContext = mDNSNULL;
1836 }
1837 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1838 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1839 }
1840 #endif // UNICAST_DISABLED
1841
1842 if (RecordType == kDNSRecordTypeUnregistered)
1843 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1844 else if (RecordType == kDNSRecordTypeDeregistering)
1845 {
1846 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1847 return(mStatus_BadReferenceErr);
1848 }
1849
1850 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1851 // We may want to consider changing this code so that we generate local-only question "rmv"
1852 // events (and maybe goodbye packets too) for unique records as well as for shared records
1853 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1854 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1855 // clause will execute here and the record will be cut from the list.
1856 if (rr->WakeUp.HMAC.l[0] ||
1857 (RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1858 {
1859 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1860 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1861 rr->resrec.rroriginalttl = 0;
1862 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1863 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
1864 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1865 m->LocalRemoveEvents = mDNStrue;
1866 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1867 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1868 }
1869 else
1870 {
1871 if (!dupList && RRLocalOnly(rr))
1872 {
1873 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1874 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1875 }
1876 else
1877 {
1878 *p = rr->next; // Cut this record from the list
1879 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1880 DecrementAutoTargetServices(m, rr);
1881 }
1882 // If someone is about to look at this, bump the pointer forward
1883 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
1884 rr->next = mDNSNULL;
1885
1886 // Should we generate local remove events here?
1887 // i.e. something like:
1888 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1889
1890 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1891 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1892
1893 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1894 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1895 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1896
1897 // If we have an update queued up which never executed, give the client a chance to free that memory
1898 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
1899
1900
1901 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1902 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1903 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1904 // so any attempt to touch rr after this is likely to lead to a crash.
1905 if (drt != mDNS_Dereg_conflict)
1906 {
1907 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1908 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m, rr));
1909 if (rr->RecordCallback)
1910 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
1911 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1912 }
1913 else
1914 {
1915 RecordProbeFailure(m, rr);
1916 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1917 if (rr->RecordCallback)
1918 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
1919 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1920 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1921 // Note that with all the client callbacks going on, by the time we get here all the
1922 // records we marked may have been explicitly deregistered by the client anyway.
1923 r2 = m->DuplicateRecords;
1924 while (r2)
1925 {
1926 if (r2->ProbeCount != 0xFF)
1927 {
1928 r2 = r2->next;
1929 }
1930 else
1931 {
1932 #if APPLE_OSX_mDNSResponder
1933 // See if this record was also registered with any D2D plugins.
1934 D2D_stop_advertising_record(r2);
1935 #endif
1936 mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
1937 // As this is a duplicate record, it will be unlinked from the list
1938 // immediately
1939 r2 = m->DuplicateRecords;
1940 }
1941 }
1942 }
1943 }
1944 mDNS_UpdateAllowSleep(m);
1945 return(mStatus_NoError);
1946 }
1947
1948 // ***************************************************************************
1949 #if COMPILER_LIKES_PRAGMA_MARK
1950 #pragma mark -
1951 #pragma mark - Packet Sending Functions
1952 #endif
1953
1954 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1955 {
1956 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1957 {
1958 **nrpp = rr;
1959 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1960 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1961 // The referenced record will definitely be acceptable (by recursive application of this rule)
1962 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1963 rr->NR_AdditionalTo = add;
1964 *nrpp = &rr->NextResponse;
1965 }
1966 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1967 }
1968
1969 mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID)
1970 {
1971 AuthRecord *rr2;
1972 if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask)
1973 {
1974 for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next)
1975 {
1976 if ((rr2->resrec.namehash == additional->resrec.namehash) &&
1977 (rr2->resrec.rrtype == additional->resrec.rrtype) &&
1978 (rr2 != additional) &&
1979 (rr2->resrec.RecordType & kDNSRecordTypeUniqueMask) &&
1980 (rr2->resrec.rrclass == additional->resrec.rrclass) &&
1981 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&
1982 SameDomainName(rr2->resrec.name, additional->resrec.name))
1983 {
1984 AddRecordToResponseList(nrpp, rr2, rr);
1985 }
1986 }
1987 }
1988 }
1989
1990 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1991 {
1992 AuthRecord *rr, *rr2;
1993 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
1994 {
1995 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1996 // later in the "for" loop, and we will follow further "additional" links then.)
1997 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1998 {
1999 AddRecordToResponseList(nrpp, rr->Additional1, rr);
2000 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID);
2001 }
2002
2003 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
2004 {
2005 AddRecordToResponseList(nrpp, rr->Additional2, rr);
2006 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID);
2007 }
2008
2009 // For SRV records, automatically add the Address record(s) for the target host
2010 if (rr->resrec.rrtype == kDNSType_SRV)
2011 {
2012 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2013 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2014 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2015 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
2016 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
2017 AddRecordToResponseList(nrpp, rr2, rr);
2018 }
2019 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
2020 {
2021 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2022 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2023 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2024 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
2025 SameDomainName(rr->resrec.name, rr2->resrec.name))
2026 AddRecordToResponseList(nrpp, rr2, rr);
2027 }
2028 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
2029 {
2030 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
2031 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2032 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
2033 }
2034 }
2035 }
2036
2037 mDNSlocal int AnonInfoSpace(AnonymousInfo *info)
2038 {
2039 ResourceRecord *rr = info->nsec3RR;
2040
2041 // 2 bytes for compressed name + type (2) class (2) TTL (4) rdlength (2) rdata (n)
2042 return (2 + 10 + rr->rdlength);
2043 }
2044
2045 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
2046 {
2047 AuthRecord *rr;
2048 AuthRecord *ResponseRecords = mDNSNULL;
2049 AuthRecord **nrp = &ResponseRecords;
2050 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
2051 int AnoninfoSpace = 0;
2052
2053 // Make a list of all our records that need to be unicast to this destination
2054 for (rr = m->ResourceRecords; rr; rr=rr->next)
2055 {
2056 // If we find we can no longer unicast this answer, clear ImmedUnicast
2057 if (rr->ImmedAnswer == mDNSInterfaceMark ||
2058 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
2059 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
2060 rr->ImmedUnicast = mDNSfalse;
2061
2062 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
2063 {
2064 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
2065 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
2066 {
2067 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
2068 rr->ImmedUnicast = mDNSfalse;
2069 rr->v4Requester = zerov4Addr;
2070 rr->v6Requester = zerov6Addr;
2071
2072 // Only sent records registered for P2P over P2P interfaces
2073 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))
2074 {
2075 continue;
2076 }
2077
2078 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
2079 {
2080 rr->NR_AnswerTo = NR_AnswerMulticast;
2081 *nrp = rr;
2082 nrp = &rr->NextResponse;
2083 }
2084 }
2085 }
2086 }
2087
2088 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
2089
2090 while (ResponseRecords)
2091 {
2092 mDNSu8 *responseptr = m->omsg.data;
2093 mDNSu8 *newptr;
2094 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2095
2096 // Put answers in the packet
2097 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
2098 {
2099 rr = ResponseRecords;
2100 if (rr->resrec.AnonInfo)
2101 {
2102 AnoninfoSpace += AnonInfoSpace(rr->resrec.AnonInfo);
2103 rr->resrec.AnonInfo->SendNow = mDNSInterfaceMark;
2104 }
2105 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2106 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2107
2108 // Retract the limit by AnoninfoSpace which we need to put the AnoInfo option.
2109 newptr = PutResourceRecordTTLWithLimit(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec, rr->resrec.rroriginalttl,
2110 m->omsg.data + (AllowedRRSpace(&m->omsg) - AnoninfoSpace));
2111
2112 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2113 if (!newptr && m->omsg.h.numAnswers)
2114 {
2115 break; // If packet full, send it now
2116 }
2117 if (newptr) responseptr = newptr;
2118 ResponseRecords = rr->NextResponse;
2119 rr->NextResponse = mDNSNULL;
2120 rr->NR_AnswerTo = mDNSNULL;
2121 rr->NR_AdditionalTo = mDNSNULL;
2122 rr->RequireGoodbye = mDNStrue;
2123 }
2124
2125 // We have reserved the space for AnonInfo option. PutResourceRecord uses the
2126 // standard limit (AllowedRRSpace) and we should have space now.
2127 for (rr = m->ResourceRecords; rr; rr=rr->next)
2128 {
2129 if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == mDNSInterfaceMark)
2130 {
2131 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
2132
2133 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAuthorities, nsec3RR);
2134 if (newptr)
2135 {
2136 responseptr = newptr;
2137 debugf("SendDelayedUnicastResponse: Added NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
2138 }
2139 else
2140 {
2141 // We allocated space and we should not fail. Don't break, we need to clear the SendNow flag.
2142 LogMsg("SendDelayedUnicastResponse: ERROR!! Cannot Add NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
2143 }
2144 rr->resrec.AnonInfo->SendNow = mDNSNULL;
2145 }
2146 }
2147
2148 // Add additionals, if there's space
2149 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
2150 {
2151 rr = ResponseRecords;
2152 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2153 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2154 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
2155 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2156
2157 if (newptr) responseptr = newptr;
2158 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
2159 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
2160 ResponseRecords = rr->NextResponse;
2161 rr->NextResponse = mDNSNULL;
2162 rr->NR_AnswerTo = mDNSNULL;
2163 rr->NR_AdditionalTo = mDNSNULL;
2164 }
2165
2166 if (m->omsg.h.numAnswers)
2167 mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2168 }
2169 }
2170
2171 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2172 // and the client's mStatus_MemFree callback will have been invoked
2173 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
2174 {
2175 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
2176 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2177 // it should go ahead and immediately dispose of this registration
2178 rr->resrec.RecordType = kDNSRecordTypeShared;
2179 rr->RequireGoodbye = mDNSfalse;
2180 rr->WakeUp.HMAC = zeroEthAddr;
2181 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
2182 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
2183 }
2184
2185 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2186 // any deregistering records that remain in the m->ResourceRecords list.
2187 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2188 // which may change the record list and/or question list.
2189 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2190 mDNSlocal void DiscardDeregistrations(mDNS *const m)
2191 {
2192 if (m->CurrentRecord)
2193 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2194 m->CurrentRecord = m->ResourceRecords;
2195
2196 while (m->CurrentRecord)
2197 {
2198 AuthRecord *rr = m->CurrentRecord;
2199 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2200 CompleteDeregistration(m, rr); // Don't touch rr after this
2201 else
2202 m->CurrentRecord = rr->next;
2203 }
2204 }
2205
2206 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2207 {
2208 int i, val = 0;
2209 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2210 for (i=1; i<=src[0]; i++)
2211 {
2212 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2213 val = val * 10 + src[i] - '0';
2214 }
2215 if (val > 255) return(mStatus_Invalid);
2216 *dst = (mDNSu8)val;
2217 return(mStatus_NoError);
2218 }
2219
2220 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2221 {
2222 int skip = CountLabels(name) - 6;
2223 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2224 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2225 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2226 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2227 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2228 a->type = mDNSAddrType_IPv4;
2229 return(mStatus_NoError);
2230 }
2231
2232 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2233 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2234 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2235
2236 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2237 {
2238 int i, h, l;
2239 const domainname *n;
2240
2241 int skip = CountLabels(name) - 34;
2242 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2243
2244 n = SkipLeadingLabels(name, skip);
2245 for (i=0; i<16; i++)
2246 {
2247 if (n->c[0] != 1) return mStatus_Invalid;
2248 l = HexVal(n->c[1]);
2249 n = (const domainname *)(n->c + 2);
2250
2251 if (n->c[0] != 1) return mStatus_Invalid;
2252 h = HexVal(n->c[1]);
2253 n = (const domainname *)(n->c + 2);
2254
2255 if (l<0 || h<0) return mStatus_Invalid;
2256 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2257 }
2258
2259 a->type = mDNSAddrType_IPv6;
2260 return(mStatus_NoError);
2261 }
2262
2263 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2264 {
2265 int skip = CountLabels(name) - 2;
2266 if (skip >= 0)
2267 {
2268 const domainname *suffix = SkipLeadingLabels(name, skip);
2269 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2270 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
2271 }
2272 return(mDNSAddrType_None);
2273 }
2274
2275 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2276 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2277 {
2278 int i;
2279 mDNSu8 *ptr = m->omsg.data;
2280 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2281 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2282
2283 // 0x00 Destination address
2284 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2285
2286 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2287 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2288
2289 // 0x0C ARP Ethertype (0x0806)
2290 *ptr++ = 0x08; *ptr++ = 0x06;
2291
2292 // 0x0E ARP header
2293 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
2294 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
2295 *ptr++ = 6; // Hardware address length
2296 *ptr++ = 4; // Protocol address length
2297 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
2298
2299 // 0x16 Sender hardware address (our MAC address)
2300 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2301
2302 // 0x1C Sender protocol address
2303 for (i=0; i<4; i++) *ptr++ = spa->b[i];
2304
2305 // 0x20 Target hardware address
2306 for (i=0; i<6; i++) *ptr++ = tha->b[i];
2307
2308 // 0x26 Target protocol address
2309 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2310
2311 // 0x2A Total ARP Packet length 42 bytes
2312 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2313 }
2314
2315 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2316 {
2317 const mDNSu16 *ptr = data;
2318 while (length > 0) { length -= 2; sum += *ptr++; }
2319 sum = (sum & 0xFFFF) + (sum >> 16);
2320 sum = (sum & 0xFFFF) + (sum >> 16);
2321 return(sum != 0xFFFF ? sum : 0);
2322 }
2323
2324 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2325 {
2326 IPv6PseudoHeader ph;
2327 ph.src = *src;
2328 ph.dst = *dst;
2329 ph.len.b[0] = length >> 24;
2330 ph.len.b[1] = length >> 16;
2331 ph.len.b[2] = length >> 8;
2332 ph.len.b[3] = length;
2333 ph.pro.b[0] = 0;
2334 ph.pro.b[1] = 0;
2335 ph.pro.b[2] = 0;
2336 ph.pro.b[3] = protocol;
2337 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2338 }
2339
2340 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2341 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2342 {
2343 int i;
2344 mDNSOpaque16 checksum;
2345 mDNSu8 *ptr = m->omsg.data;
2346 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2347 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2348 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2349 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] } };
2350 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2351 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2352 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2353
2354 // 0x00 Destination address
2355 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2356 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2357 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2358 // link with a pointless link-layer multicast.
2359 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2360 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2361 // *ptr++ = 0x33;
2362 // *ptr++ = 0x33;
2363 // *ptr++ = 0xFF;
2364 // *ptr++ = tpa->b[0xD];
2365 // *ptr++ = tpa->b[0xE];
2366 // *ptr++ = tpa->b[0xF];
2367
2368 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2369 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2370
2371 // 0x0C IPv6 Ethertype (0x86DD)
2372 *ptr++ = 0x86; *ptr++ = 0xDD;
2373
2374 // 0x0E IPv6 header
2375 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
2376 *ptr++ = 0x00; *ptr++ = 0x20; // Length
2377 *ptr++ = 0x3A; // Protocol == ICMPv6
2378 *ptr++ = 0xFF; // Hop Limit
2379
2380 // 0x16 Sender IPv6 address
2381 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2382
2383 // 0x26 Destination IPv6 address
2384 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2385
2386 // 0x36 NDP header
2387 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2388 *ptr++ = 0x00; // Code
2389 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
2390 *ptr++ = flags;
2391 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2392
2393 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
2394 {
2395 // 0x3E NDP target.
2396 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2397 // 0x4E Source Link-layer Address
2398 // <http://www.ietf.org/rfc/rfc2461.txt>
2399 // MUST NOT be included when the source IP address is the unspecified address.
2400 // Otherwise, on link layers that have addresses this option MUST be included
2401 // in multicast solicitations and SHOULD be included in unicast solicitations.
2402 if (!mDNSIPv6AddressIsZero(*spa))
2403 {
2404 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2405 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2406 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2407 }
2408 }
2409 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2410 {
2411 // 0x3E NDP target.
2412 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2413 // 0x4E Target Link-layer Address
2414 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2415 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2416 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2417 }
2418
2419 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2420 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
2421 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2422 m->omsg.data[0x38] = checksum.b[0];
2423 m->omsg.data[0x39] = checksum.b[1];
2424
2425 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2426 }
2427
2428 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2429 {
2430 mDNSu32 DNS_VERS = _DNS_SD_H;
2431 Trace->u.tracer.platf = m->mDNS_plat;
2432 Trace->u.tracer.mDNSv = DNS_VERS;
2433
2434 Trace->opt = kDNSOpt_Trace;
2435 Trace->optlen = DNSOpt_TraceData_Space - 4;
2436 }
2437
2438 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2439 {
2440 owner->u.owner.vers = 0;
2441 owner->u.owner.seq = m->SleepSeqNum;
2442 owner->u.owner.HMAC = m->PrimaryMAC;
2443 owner->u.owner.IMAC = intf->MAC;
2444 owner->u.owner.password = zeroEthAddr;
2445
2446 // Don't try to compute the optlen until *after* we've set up the data fields
2447 // 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
2448 owner->opt = kDNSOpt_Owner;
2449 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2450 }
2451
2452 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2453 {
2454 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2455 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2456 }
2457
2458 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2459 {
2460 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2461 // and hence there is no need to check for Transfering state. But if we have sleep
2462 // proxies and partially sending goodbyes for some records, we will be in Transfering
2463 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2464 // we are not awake handles both cases.
2465 if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2466 {
2467 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2468 return mDNStrue;
2469 }
2470
2471 if (m->SleepState != SleepState_Sleeping)
2472 return mDNSfalse;
2473
2474 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2475 // whether you can send goodbyes or not.
2476 if (!intf->SendGoodbyes)
2477 {
2478 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2479 return mDNSfalse;
2480 }
2481 else
2482 {
2483 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2484 return mDNStrue;
2485 }
2486 }
2487
2488 mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *ar, mDNSInterfaceID InterfaceID)
2489 {
2490 mDNSBool result;
2491
2492 if (ar->resrec.InterfaceID == mDNSInterface_Any)
2493 {
2494 result = mDNSPlatformValidRecordForInterface(ar, InterfaceID);
2495 }
2496 else
2497 {
2498 result = (ar->resrec.InterfaceID == InterfaceID);
2499 }
2500
2501 return(result);
2502 }
2503
2504 // Note about acceleration of announcements to facilitate automatic coalescing of
2505 // multiple independent threads of announcements into a single synchronized thread:
2506 // The announcements in the packet may be at different stages of maturity;
2507 // One-second interval, two-second interval, four-second interval, and so on.
2508 // After we've put in all the announcements that are due, we then consider
2509 // whether there are other nearly-due announcements that are worth accelerating.
2510 // To be eligible for acceleration, a record MUST NOT be older (further along
2511 // its timeline) than the most mature record we've already put in the packet.
2512 // In other words, younger records can have their timelines accelerated to catch up
2513 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2514 // Older records cannot have their timelines accelerated; this would just widen
2515 // the gap between them and their younger bretheren and get them even more out of sync.
2516
2517 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2518 // the record list and/or question list.
2519 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2520 mDNSlocal void SendResponses(mDNS *const m)
2521 {
2522 int pktcount = 0;
2523 AuthRecord *rr, *r2;
2524 mDNSs32 maxExistingAnnounceInterval = 0;
2525 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2526
2527 m->NextScheduledResponse = m->timenow + FutureTime;
2528
2529 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2530
2531 for (rr = m->ResourceRecords; rr; rr=rr->next)
2532 if (rr->ImmedUnicast)
2533 {
2534 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2535 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2536 v4.ip.v4 = rr->v4Requester;
2537 v6.ip.v6 = rr->v6Requester;
2538 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2539 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2540 if (rr->ImmedUnicast)
2541 {
2542 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2543 rr->ImmedUnicast = mDNSfalse;
2544 }
2545 }
2546
2547 // ***
2548 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2549 // ***
2550
2551 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2552 for (rr = m->ResourceRecords; rr; rr=rr->next)
2553 {
2554 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2555 if (TimeToAnnounceThisRecord(rr, m->timenow))
2556 {
2557 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2558 {
2559 if (!rr->WakeUp.HMAC.l[0])
2560 {
2561 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
2562 }
2563 else
2564 {
2565 mDNSBool unicastOnly;
2566 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2567 unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse;
2568 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly);
2569 for (r2 = rr; r2; r2=r2->next)
2570 if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
2571 mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2572 {
2573 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2574 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2575 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2576 {
2577 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2578 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2579 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2580 }
2581 r2->LastAPTime = m->timenow;
2582 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2583 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2584 }
2585 }
2586 }
2587 else if (ResourceRecordIsValidAnswer(rr))
2588 {
2589 if (rr->AddressProxy.type)
2590 {
2591 if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2592 {
2593 rr->AnnounceCount--;
2594 rr->ThisAPInterval *= 2;
2595 rr->LastAPTime = m->timenow;
2596 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2597 {
2598 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2599 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2600 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2601 }
2602 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2603 {
2604 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2605 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2606 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2607 }
2608 }
2609 }
2610 else
2611 {
2612 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2613 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2614 maxExistingAnnounceInterval = rr->ThisAPInterval;
2615 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2616 }
2617 }
2618 }
2619 }
2620
2621 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2622 // Eligible records that are more than half-way to their announcement time are accelerated
2623 for (rr = m->ResourceRecords; rr; rr=rr->next)
2624 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2625 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2626 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2627 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
2628 ResourceRecordIsValidAnswer(rr)))
2629 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2630
2631 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2632 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2633 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2634 // then all that means is that it won't get sent -- which would not be the end of the world.
2635 for (rr = m->ResourceRecords; rr; rr=rr->next)
2636 {
2637 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2638 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
2639 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
2640 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
2641 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
2642 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
2643 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2644 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2645 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
2646 // We also make sure we send the DeviceInfo TXT record too, if necessary
2647 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2648 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2649 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2650 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2651 {
2652 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2653 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2654 }
2655 }
2656
2657 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2658 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2659 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2660 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2661 // -- 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
2662 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2663 for (rr = m->ResourceRecords; rr; rr=rr->next)
2664 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2665 {
2666 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
2667 {
2668 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2669 {
2670 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2671 (r2->ImmedAnswer != mDNSInterfaceMark) && (r2->ImmedAnswer != rr->ImmedAnswer) &&
2672 SameResourceRecordSignature(r2, rr) &&
2673 ((rr->ImmedAnswer == mDNSInterfaceMark) || IsInterfaceValidForAuthRecord(r2, rr->ImmedAnswer)))
2674 {
2675 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2676 }
2677 }
2678 }
2679 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
2680 {
2681 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2682 {
2683 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2684 (r2->ImmedAdditional != rr->ImmedAdditional) &&
2685 SameResourceRecordSignature(r2, rr) &&
2686 IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional))
2687 {
2688 r2->ImmedAdditional = rr->ImmedAdditional;
2689 }
2690 }
2691 }
2692 }
2693
2694 // Now set SendRNow state appropriately
2695 for (rr = m->ResourceRecords; rr; rr=rr->next)
2696 {
2697 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
2698 {
2699 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2700 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
2701 rr->LastMCTime = m->timenow;
2702 rr->LastMCInterface = rr->ImmedAnswer;
2703 rr->ProbeRestartCount = 0; // Reset the probe restart count
2704 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2705 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2706 {
2707 rr->AnnounceCount--;
2708 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2709 rr->ThisAPInterval *= 2;
2710 rr->LastAPTime = m->timenow;
2711 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2712 }
2713 }
2714 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
2715 {
2716 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
2717 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
2718 rr->LastMCTime = m->timenow;
2719 rr->LastMCInterface = rr->ImmedAnswer;
2720 }
2721 SetNextAnnounceProbeTime(m, rr);
2722 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2723 }
2724
2725 // ***
2726 // *** 2. Loop through interface list, sending records as appropriate
2727 // ***
2728
2729 while (intf)
2730 {
2731 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2732 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2733 int numDereg = 0;
2734 int numAnnounce = 0;
2735 int numAnswer = 0;
2736 int AnoninfoSpace = 0;
2737 mDNSu8 *responseptr = m->omsg.data;
2738 mDNSu8 *newptr;
2739 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2740
2741 // First Pass. Look for:
2742 // 1. Deregistering records that need to send their goodbye packet
2743 // 2. Updated records that need to retract their old data
2744 // 3. Answers and announcements we need to send
2745 for (rr = m->ResourceRecords; rr; rr=rr->next)
2746 {
2747
2748 // Skip this interface if the record InterfaceID is *Any and the record is not
2749 // appropriate for the interface type.
2750 if ((rr->SendRNow == intf->InterfaceID) &&
2751 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)))
2752 {
2753 rr->SendRNow = GetNextActiveInterfaceID(intf);
2754 }
2755 else if (rr->SendRNow == intf->InterfaceID)
2756 {
2757 RData *OldRData = rr->resrec.rdata;
2758 mDNSu16 oldrdlength = rr->resrec.rdlength;
2759 mDNSu8 active = (mDNSu8)
2760 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2761 newptr = mDNSNULL;
2762 if (rr->NewRData && active)
2763 {
2764 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2765 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2766 {
2767 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2768 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2769 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
2770 }
2771 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2772 }
2773
2774 if (rr->resrec.AnonInfo)
2775 {
2776 int tmp = AnonInfoSpace(rr->resrec.AnonInfo);
2777
2778 AnoninfoSpace += tmp;
2779 // Adjust OwnerRecordSpace/TraceRecordSpace which is used by PutRR_OS_TTL below so that
2780 // we have space to put in the NSEC3 record in the authority section.
2781 OwnerRecordSpace += tmp;
2782 TraceRecordSpace += tmp;
2783 }
2784
2785 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2786 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2787 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2788 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2789 if (newptr)
2790 {
2791 responseptr = newptr;
2792 rr->RequireGoodbye = active;
2793 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2794 else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2795 }
2796
2797 if (rr->NewRData && active)
2798 SetNewRData(&rr->resrec, OldRData, oldrdlength);
2799
2800 // The first time through (pktcount==0), if this record is verified unique
2801 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2802 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2803 rr->SendNSECNow = mDNSInterfaceMark;
2804
2805 if (newptr) // If succeeded in sending, advance to next interface
2806 {
2807 if (rr->resrec.AnonInfo)
2808 {
2809 debugf("SendResponses: Marking %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2810 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2811 rr->resrec.AnonInfo->SendNow = intf->InterfaceID;
2812 }
2813
2814 // If sending on all interfaces, go to next interface; else we're finished now
2815 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2816 rr->SendRNow = GetNextActiveInterfaceID(intf);
2817 else
2818 rr->SendRNow = mDNSNULL;
2819 }
2820 }
2821 }
2822
2823 // Get the reserved space back
2824 OwnerRecordSpace -= AnoninfoSpace;
2825 TraceRecordSpace -= AnoninfoSpace;
2826 newptr = responseptr;
2827 for (rr = m->ResourceRecords; rr; rr=rr->next)
2828 {
2829 if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == intf->InterfaceID)
2830 {
2831 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
2832
2833 newptr = PutRR_OS_TTL(newptr, &m->omsg.h.numAuthorities, nsec3RR, nsec3RR->rroriginalttl);
2834 if (newptr)
2835 {
2836 responseptr = newptr;
2837 debugf("SendResponses: Added NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2838 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2839 }
2840 else
2841 {
2842 LogMsg("SendResponses: Cannot add NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2843 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2844 }
2845 rr->resrec.AnonInfo->SendNow = mDNSNULL;
2846 }
2847 }
2848 // Second Pass. Add additional records, if there's space.
2849 newptr = responseptr;
2850 for (rr = m->ResourceRecords; rr; rr=rr->next)
2851 if (rr->ImmedAdditional == intf->InterfaceID)
2852 if (ResourceRecordIsValidAnswer(rr))
2853 {
2854 // If we have at least one answer already in the packet, then plan to add additionals too
2855 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2856
2857 // If we're not planning to send any additionals, but this record is a unique one, then
2858 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2859 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2860 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2861 {
2862 const AuthRecord *a;
2863 for (a = m->ResourceRecords; a; a=a->next)
2864 if (a->LastMCTime == m->timenow &&
2865 a->LastMCInterface == intf->InterfaceID &&
2866 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2867 }
2868 if (!SendAdditional) // If we don't want to send this after all,
2869 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
2870 else if (newptr) // Else, try to add it if we can
2871 {
2872 // The first time through (pktcount==0), if this record is verified unique
2873 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2874 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2875 rr->SendNSECNow = mDNSInterfaceMark;
2876
2877 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2878 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2879 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2880 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2881 if (newptr)
2882 {
2883 responseptr = newptr;
2884 rr->ImmedAdditional = mDNSNULL;
2885 rr->RequireGoodbye = mDNStrue;
2886 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2887 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2888 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2889 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2890 rr->LastMCTime = m->timenow;
2891 rr->LastMCInterface = intf->InterfaceID;
2892 }
2893 }
2894 }
2895
2896 // Third Pass. Add NSEC records, if there's space.
2897 // When we're generating an NSEC record in response to a specify query for that type
2898 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2899 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2900 for (rr = m->ResourceRecords; rr; rr=rr->next)
2901 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2902 {
2903 AuthRecord nsec;
2904 mDNSu8 *ptr;
2905 int len;
2906 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2907 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2908 AssignDomainName(&nsec.namestorage, rr->resrec.name);
2909 ptr = nsec.rdatastorage.u.data;
2910 len = DomainNameLength(rr->resrec.name);
2911 // We have a nxt name followed by window number, window length and a window bitmap
2912 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
2913 if (nsec.resrec.rdlength <= StandardAuthRDSize)
2914 {
2915 mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
2916 AssignDomainName((domainname *)ptr, rr->resrec.name);
2917 ptr += len;
2918 *ptr++ = 0; // window number
2919 *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
2920 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2921 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2922 {
2923 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2924 else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2925 }
2926 newptr = responseptr;
2927 if (!r2) // If we successfully built our NSEC record, add it to the packet now
2928 {
2929 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2930 if (newptr) responseptr = newptr;
2931 }
2932 }
2933 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength);
2934
2935 // If we successfully put the NSEC record, clear the SendNSECNow flag
2936 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2937 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2938 {
2939 rr->SendNSECNow = mDNSNULL;
2940 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2941 for (r2 = rr->next; r2; r2=r2->next)
2942 if (SameResourceRecordNameClassInterface(r2, rr))
2943 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2944 r2->SendNSECNow = mDNSNULL;
2945 }
2946 }
2947
2948 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2949 {
2950 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
2951 if (OwnerRecordSpace || TraceRecordSpace)
2952 {
2953 AuthRecord opt;
2954 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2955 opt.resrec.rrclass = NormalMaxDNSMessageData;
2956 opt.resrec.rdlength = sizeof(rdataOPT);
2957 opt.resrec.rdestimate = sizeof(rdataOPT);
2958 if (OwnerRecordSpace && TraceRecordSpace)
2959 {
2960 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
2961 opt.resrec.rdestimate += sizeof(rdataOPT);
2962 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2963 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
2964 }
2965 else if (OwnerRecordSpace)
2966 {
2967 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2968 }
2969 else if (TraceRecordSpace)
2970 {
2971 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
2972 }
2973 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2974 if (newptr)
2975 {
2976 responseptr = newptr;
2977 }
2978 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2979 {
2980 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2981 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2982 }
2983 else
2984 {
2985 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2986 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2987 }
2988 }
2989
2990 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2991 numDereg, numDereg == 1 ? "" : "s",
2992 numAnnounce, numAnnounce == 1 ? "" : "s",
2993 numAnswer, numAnswer == 1 ? "" : "s",
2994 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2995
2996 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2997 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2998 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2999 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
3000 // There might be more things to send on this interface, so go around one more time and try again.
3001 }
3002 else // Nothing more to send on this interface; go to next
3003 {
3004 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3005 #if MDNS_DEBUGMSGS && 0
3006 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3007 debugf(msg, intf, next);
3008 #endif
3009 intf = next;
3010 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3011 }
3012 }
3013
3014 // ***
3015 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3016 // ***
3017
3018 if (m->CurrentRecord)
3019 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3020 m->CurrentRecord = m->ResourceRecords;
3021 while (m->CurrentRecord)
3022 {
3023 rr = m->CurrentRecord;
3024 m->CurrentRecord = rr->next;
3025
3026 if (rr->SendRNow)
3027 {
3028 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
3029 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3030 (uint32_t)rr->SendRNow, (uint32_t)rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
3031 rr->SendRNow = mDNSNULL;
3032 }
3033
3034 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3035 {
3036 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
3037
3038 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
3039 {
3040 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3041 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
3042 }
3043 else
3044 {
3045 rr->ImmedAnswer = mDNSNULL;
3046 rr->ImmedUnicast = mDNSfalse;
3047 rr->v4Requester = zerov4Addr;
3048 rr->v6Requester = zerov6Addr;
3049 }
3050 }
3051 }
3052 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
3053 }
3054
3055 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3056 // so we want to be lazy about how frequently we do it.
3057 // 1. If a cache record is currently referenced by *no* active questions,
3058 // then we don't mind expiring it up to a minute late (who will know?)
3059 // 2. Else, if a cache record is due for some of its final expiration queries,
3060 // we'll allow them to be late by up to 2% of the TTL
3061 // 3. Else, if a cache record has completed all its final expiration queries without success,
3062 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3063 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3064 // so allow at most 1/10 second lateness
3065 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3066 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3067 #define CacheCheckGracePeriod(RR) ( \
3068 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3069 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
3070 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3071 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3072
3073 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
3074
3075 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
3076 {
3077 if (m->rrcache_nextcheck[slot] - event > 0)
3078 m->rrcache_nextcheck[slot] = event;
3079 if (m->NextCacheCheck - event > 0)
3080 m->NextCacheCheck = event;
3081 }
3082
3083 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3084 // rr->TimeRcvd
3085 // rr->resrec.rroriginalttl
3086 // rr->UnansweredQueries
3087 // rr->CRActiveQuestion
3088 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
3089 {
3090 rr->NextRequiredQuery = RRExpireTime(rr);
3091
3092 // If we have an active question, then see if we want to schedule a refresher query for this record.
3093 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3094 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3095 {
3096 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
3097 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
3098 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3099 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
3100 }
3101 ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr));
3102 }
3103
3104 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3105 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3106 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3107
3108 // Delay before restarting questions on a flapping interface.
3109 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3)
3110 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3111 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3112 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7))
3113
3114 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
3115 {
3116 if (interval < kMinimumReconfirmTime)
3117 interval = kMinimumReconfirmTime;
3118 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3119 interval = 0x10000000;
3120
3121 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3122 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
3123 {
3124 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3125 // For all the reconfirmations in a given batch, we want to use the same random value
3126 // so that the reconfirmation questions can be grouped into a single query packet
3127 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime);
3128 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
3129 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
3130 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
3131 SetNextCacheCheckTimeForRecord(m, rr);
3132 }
3133 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3134 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
3135 return(mStatus_NoError);
3136 }
3137
3138 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3139 // It also appends to the list of known answer records that need to be included,
3140 // and updates the forcast for the size of the known answer section.
3141 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
3142 DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
3143 {
3144 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3145 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3146 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
3147 mDNSu8 anoninfo_space = q->AnonInfo ? AnonInfoSpace(q->AnonInfo) : 0;
3148 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast - anoninfo_space, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
3149 if (!newptr)
3150 {
3151 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3152 return(mDNSfalse);
3153 }
3154 else
3155 {
3156 mDNSu32 forecast = *answerforecast + anoninfo_space;
3157 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3158 CacheRecord *rr;
3159 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
3160
3161 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
3162 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
3163 !(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
3164 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not already in the known answer list
3165 rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3166 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
3167 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
3168 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
3169 {
3170 // We don't want to include unique records in the Known Answer section. The Known Answer section
3171 // is intended to suppress floods of shared-record replies from many other devices on the network.
3172 // That concept really does not apply to unique records, and indeed if we do send a query for
3173 // which we have a unique record already in our cache, then including that unique record as a
3174 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3175
3176 *ka = rr; // Link this record into our known answer chain
3177 ka = &rr->NextInKAList;
3178 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3179 forecast += 12 + rr->resrec.rdestimate;
3180 // If we're trying to put more than one question in this packet, and it doesn't fit
3181 // then undo that last question and try again next time
3182 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3183 {
3184 query->h.numQuestions--;
3185 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3186 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
3187 ka = *kalistptrptr; // Go back to where we started and retract these answer records
3188 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
3189 return(mDNSfalse); // Return false, so we'll try again in the next packet
3190 }
3191 }
3192
3193 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3194 *queryptr = newptr; // Update the packet pointer
3195 *answerforecast = forecast; // Update the forecast
3196 *kalistptrptr = ka; // Update the known answer list pointer
3197 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
3198
3199 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // For every resource record in our cache,
3200 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
3201 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not in the known answer list
3202 SameNameRecordAnswersQuestion(&rr->resrec, q)) // which answers our question
3203 {
3204 rr->UnansweredQueries++; // indicate that we're expecting a response
3205 rr->LastUnansweredTime = m->timenow;
3206 SetNextCacheCheckTimeForRecord(m, rr);
3207 }
3208
3209 return(mDNStrue);
3210 }
3211 }
3212
3213 // When we have a query looking for a specified name, but there appear to be no answers with
3214 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3215 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3216 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3217 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3218 // A typical reconfirmation scenario might go like this:
3219 // Depth 0: Name "myhost.local" has no address records
3220 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3221 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3222 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3223 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3224 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3225 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSInterfaceID InterfaceID, const int depth)
3226 {
3227 mDNSu32 slot;
3228 const CacheGroup *cg;
3229 CacheRecord *cr;
3230 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
3231 if (!InterfaceID) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3232 FORALL_CACHERECORDS(slot, cg, cr)
3233 {
3234 const domainname *crtarget;
3235 if (cr->resrec.InterfaceID != InterfaceID) continue; // Skip non-mDNS records and mDNS records from other interfaces.
3236 if (cr->resrec.rdatahash != namehash) continue; // Skip records whose rdata hash doesn't match the name hash.
3237 crtarget = GetRRDomainNameTarget(&cr->resrec);
3238 if (crtarget && SameDomainName(crtarget, name))
3239 {
3240 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth, InterfaceID, CRDisplayString(m, cr));
3241 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3242 if (depth < 5)
3243 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, InterfaceID, depth+1);
3244 }
3245 }
3246 }
3247
3248 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3249 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3250 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3251 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3252 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3253 {
3254 CacheGroup *const cg = CacheGroupForName(m, namehash, name);
3255 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3256 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3257 return(cr);
3258 }
3259
3260
3261 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3262 {
3263 #ifndef SPC_DISABLED
3264 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3265 const CacheRecord *cr, *bestcr = mDNSNULL;
3266 mDNSu32 bestmetric = 1000000;
3267 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3268 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
3269 if (cr != c0 && cr != c1) // that's not one we've seen before,
3270 if (SameNameRecordAnswersQuestion(&cr->resrec, q)) // and answers our browse query,
3271 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
3272 {
3273 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3274 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3275 }
3276 return(bestcr);
3277 #else // SPC_DISABLED
3278 (void) m;
3279 (void) q;
3280 (void) c0;
3281 (void) c1;
3282 (void) c1;
3283 return mDNSNULL;
3284 #endif // SPC_DISABLED
3285 }
3286
3287 mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
3288 {
3289 const CacheRecord *swap_sps;
3290 mDNSu32 metric1, metric2;
3291
3292 if (!(*sps1) || !(*sps2)) return;
3293 metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
3294 metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
3295 if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
3296 {
3297 swap_sps = *sps1;
3298 *sps1 = *sps2;
3299 *sps2 = swap_sps;
3300 }
3301 }
3302
3303 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3304 {
3305 CheckAndSwapSPS(&sps[0], &sps[1]);
3306 CheckAndSwapSPS(&sps[0], &sps[2]);
3307 CheckAndSwapSPS(&sps[1], &sps[2]);
3308 }
3309
3310
3311 // Finds the three best Sleep Proxies we currently have in our cache
3312 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3313 {
3314 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3315 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
3316 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
3317
3318 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3319 // only if they have equally good metric and support features.
3320 ReorderSPSByFeature(sps);
3321 }
3322
3323 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3324 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3325 {
3326 int i;
3327 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3328 }
3329
3330 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3331 {
3332 int i;
3333 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3334 }
3335
3336 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3337 {
3338 int i;
3339 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3340 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3341 for (i=0; i<DupSuppressInfoSize; i++)
3342 if (ds[i].InterfaceID == intf->InterfaceID)
3343 {
3344 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3345 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3346 if (v4 && v6) return(mDNStrue);
3347 }
3348 return(mDNSfalse);
3349 }
3350
3351 mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3352 {
3353 int i, j;
3354
3355 // See if we have this one in our list somewhere already
3356 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3357
3358 // If not, find a slot we can re-use
3359 if (i >= DupSuppressInfoSize)
3360 {
3361 i = 0;
3362 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3363 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3364 i = j;
3365 }
3366
3367 // Record the info about this query we saw
3368 ds[i].Time = Time;
3369 ds[i].InterfaceID = InterfaceID;
3370 ds[i].Type = Type;
3371 }
3372
3373 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3374 {
3375 int len, i, cnt;
3376 mDNSInterfaceID InterfaceID = q->InterfaceID;
3377 domainname *d = &q->qname;
3378
3379 // We can't send magic packets without knowing which interface to send it on.
3380 if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID))
3381 {
3382 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3383 return;
3384 }
3385
3386 // Split MAC@IPAddress and pass them separately
3387 len = d->c[0];
3388 cnt = 0;
3389 for (i = 1; i < len; i++)
3390 {
3391 if (d->c[i] == '@')
3392 {
3393 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3394 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3395 if (cnt != 5)
3396 {
3397 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3398 return;
3399 }
3400 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3401 {
3402 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3403 return;
3404 }
3405 if ((len - i) > (int)(sizeof(IPAddr) - 1))
3406 {
3407 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3408 return;
3409 }
3410 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3411 EthAddr[i - 1] = 0;
3412 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3413 IPAddr[len - i] = 0;
3414 m->mDNSStats.WakeOnResolves++;
3415 mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3416 return;
3417 }
3418 else if (d->c[i] == ':')
3419 cnt++;
3420 }
3421 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3422 }
3423
3424
3425 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3426 {
3427 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3428 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3429 return(mDNStrue);
3430
3431 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3432 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3433 {
3434 // We forecast: qname (n) type (2) class (2)
3435 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3436 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3437 const CacheRecord *rr;
3438 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
3439 if (rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3440 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
3441 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
3442 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3443 {
3444 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3445 forecast += 12 + rr->resrec.rdestimate;
3446 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3447 }
3448 return(mDNStrue);
3449 }
3450
3451 return(mDNSfalse);
3452 }
3453
3454 // How Standard Queries are generated:
3455 // 1. The Question Section contains the question
3456 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3457
3458 // How Probe Queries are generated:
3459 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3460 // if some other host is already using *any* records with this name, we want to know about it.
3461 // 2. The Authority Section contains the proposed values we intend to use for one or more
3462 // of our records with that name (analogous to the Update section of DNS Update packets)
3463 // because if some other host is probing at the same time, we each want to know what the other is
3464 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3465
3466 mDNSlocal void SendQueries(mDNS *const m)
3467 {
3468 mDNSu32 slot;
3469 CacheGroup *cg;
3470 CacheRecord *cr;
3471 AuthRecord *ar;
3472 int pktcount = 0;
3473 DNSQuestion *q;
3474 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3475 mDNSs32 maxExistingQuestionInterval = 0;
3476 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3477 CacheRecord *KnownAnswerList = mDNSNULL;
3478
3479 // 1. If time for a query, work out what we need to do
3480
3481 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3482 // to their NextRequiredQuery to be worth batching them together with this one
3483 FORALL_CACHERECORDS(slot, cg, cr)
3484 {
3485 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3486 {
3487 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3488 {
3489 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3490 q = cr->CRActiveQuestion;
3491 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3492 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3493 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3494 if (q->Target.type)
3495 {
3496 q->SendQNow = mDNSInterfaceMark; // If targeted query, mark it
3497 }
3498 else if (!mDNSOpaque16IsZero(q->TargetQID))
3499 {
3500 q->LastQTime = m->timenow - q->ThisQInterval;
3501 cr->UnansweredQueries++;
3502 m->mDNSStats.CacheRefreshQueries++;
3503 }
3504 else if (q->SendQNow == mDNSNULL)
3505 {
3506 q->SendQNow = cr->resrec.InterfaceID;
3507 }
3508 else if (q->SendQNow != cr->resrec.InterfaceID)
3509 {
3510 q->SendQNow = mDNSInterfaceMark;
3511 }
3512
3513 // Indicate that this question was marked for sending
3514 // to update an existing cached answer record.
3515 // The browse throttling logic below uses this to determine
3516 // if the query should be sent.
3517 if (mDNSOpaque16IsZero(q->TargetQID))
3518 q->CachedAnswerNeedsUpdate = mDNStrue;
3519 }
3520 }
3521 }
3522
3523 // Scan our list of questions to see which:
3524 // *WideArea* queries need to be sent
3525 // *unicast* queries need to be sent
3526 // *multicast* queries we're definitely going to send
3527 if (m->CurrentQuestion)
3528 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3529 m->CurrentQuestion = m->Questions;
3530 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3531 {
3532 q = m->CurrentQuestion;
3533 if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
3534 {
3535 mDNSu8 *qptr = m->omsg.data;
3536 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
3537
3538 // If we fail to get a new on-demand socket (should only happen cases of the most extreme resource exhaustion), we'll try again next time
3539 if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(zeroIPPort);
3540 if (q->LocalSocket)
3541 {
3542 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
3543 qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
3544 mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL, q->UseBackgroundTrafficClass);
3545 q->ThisQInterval *= QuestionIntervalStep;
3546 }
3547 if (q->ThisQInterval > MaxQuestionInterval)
3548 q->ThisQInterval = MaxQuestionInterval;
3549 q->LastQTime = m->timenow;
3550 q->LastQTxTime = m->timenow;
3551 q->RecentAnswerPkts = 0;
3552 q->SendQNow = mDNSNULL;
3553 q->ExpectUnicastResp = NonZeroTime(m->timenow);
3554 }
3555 else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
3556 {
3557 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3558 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3559 if (maxExistingQuestionInterval < q->ThisQInterval)
3560 maxExistingQuestionInterval = q->ThisQInterval;
3561 }
3562 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3563 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3564 // m->CurrentQuestion point to the right question
3565 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3566 }
3567 while (m->CurrentQuestion)
3568 {
3569 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3570 m->CurrentQuestion = m->CurrentQuestion->next;
3571 }
3572 m->CurrentQuestion = mDNSNULL;
3573
3574 // Scan our list of questions
3575 // (a) to see if there are any more that are worth accelerating, and
3576 // (b) to update the state variables for *all* the questions we're going to send
3577 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3578 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3579 // 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.
3580 m->NextScheduledQuery = m->timenow + FutureTime;
3581 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3582 {
3583 if (mDNSOpaque16IsZero(q->TargetQID)
3584 && (q->SendQNow || (!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3585 {
3586 // If at least halfway to next query time, advance to next interval
3587 // If less than halfway to next query time, then
3588 // treat this as logically a repeat of the last transmission, without advancing the interval
3589 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3590 {
3591 // If we have reached the answer threshold for this question,
3592 // don't send it again until MaxQuestionInterval unless:
3593 // one of its cached answers needs to be refreshed,
3594 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3595 if (q->BrowseThreshold
3596 && (q->CurrentAnswers >= q->BrowseThreshold)
3597 && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3598 && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3599 {
3600 q->SendQNow = mDNSNULL;
3601 q->ThisQInterval = MaxQuestionInterval;
3602 q->LastQTime = m->timenow;
3603 q->RequestUnicast = 0;
3604 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3605 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3606 }
3607 else
3608 {
3609 // Mark this question for sending on all interfaces
3610 q->SendQNow = mDNSInterfaceMark;
3611 q->ThisQInterval *= QuestionIntervalStep;
3612 }
3613
3614 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3615 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3616
3617 if (q->ThisQInterval > MaxQuestionInterval)
3618 {
3619 q->ThisQInterval = MaxQuestionInterval;
3620 }
3621 else if (mDNSOpaque16IsZero(q->TargetQID) && q->InterfaceID &&
3622 q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3623 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3624 {
3625 // Generally don't need to log this.
3626 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3627 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3628 // and when there simply happen to be no instances of the service the client is looking
3629 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3630 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3631 q->qname.c, DNSTypeName(q->qtype));
3632 // Sending third query, and no answers yet; time to begin doubting the source
3633 ReconfirmAntecedents(m, &q->qname, q->qnamehash, q->InterfaceID, 0);
3634 }
3635 }
3636
3637 // Mark for sending. (If no active interfaces, then don't even try.)
3638 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3639 if (q->SendOnAll)
3640 {
3641 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3642 q->LastQTime = m->timenow;
3643 }
3644
3645 // If we recorded a duplicate suppression for this question less than half an interval ago,
3646 // then we consider it recent enough that we don't need to do an identical query ourselves.
3647 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3648
3649 q->LastQTxTime = m->timenow;
3650 q->RecentAnswerPkts = 0;
3651 if (q->RequestUnicast) q->RequestUnicast--;
3652 }
3653 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3654 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3655 SetNextQueryTime(m,q);
3656 }
3657
3658 // 2. Scan our authoritative RR list to see what probes we might need to send
3659
3660 m->NextScheduledProbe = m->timenow + FutureTime;
3661
3662 if (m->CurrentRecord)
3663 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3664 m->CurrentRecord = m->ResourceRecords;
3665 while (m->CurrentRecord)
3666 {
3667 ar = m->CurrentRecord;
3668 m->CurrentRecord = ar->next;
3669 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
3670 {
3671 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3672 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3673 {
3674 SetNextAnnounceProbeTime(m, ar);
3675 }
3676 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3677 else if (ar->ProbeCount)
3678 {
3679 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3680 {
3681 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3682 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3683 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3684 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3685 // A similar concern may apply to the NDP Probe too. -- SC
3686 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3687 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3688 }
3689 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3690 {
3691 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3692 // IPv6 source = zero
3693 // No target hardware address
3694 // IPv6 target address is address we're probing
3695 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3696 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3697 }
3698 // Mark for sending. (If no active interfaces, then don't even try.)
3699 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3700 ar->LastAPTime = m->timenow;
3701 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3702 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3703 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3704 ar->ProbeCount = DefaultProbeCountForTypeUnique;
3705 ar->ProbeCount--;
3706 SetNextAnnounceProbeTime(m, ar);
3707 if (ar->ProbeCount == 0)
3708 {
3709 // If this is the last probe for this record, then see if we have any matching records
3710 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3711 AuthRecord *r2;
3712 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3713 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3714 r2->ProbeCount = 0;
3715 // ... then acknowledge this record to the client.
3716 // We do this optimistically, just as we're about to send the third probe.
3717 // This helps clients that both advertise and browse, and want to filter themselves
3718 // from the browse results list, because it helps ensure that the registration
3719 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3720 // A potential downside is that we could deliver a registration confirmation and then find out
3721 // moments later that there's a name conflict, but applications have to be prepared to handle
3722 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3723 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3724 }
3725 }
3726 // else, if it has now finished probing, move it to state Verified,
3727 // and update m->NextScheduledResponse so it will be announced
3728 else
3729 {
3730 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
3731 ar->resrec.RecordType = kDNSRecordTypeVerified;
3732 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3733 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3734 SetNextAnnounceProbeTime(m, ar);
3735 }
3736 }
3737 }
3738 m->CurrentRecord = m->DuplicateRecords;
3739 while (m->CurrentRecord)
3740 {
3741 ar = m->CurrentRecord;
3742 m->CurrentRecord = ar->next;
3743 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3744 AcknowledgeRecord(m, ar);
3745 }
3746
3747 // 3. Now we know which queries and probes we're sending,
3748 // go through our interface list sending the appropriate queries on each interface
3749 while (intf)
3750 {
3751 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3752 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3753 mDNSu8 *queryptr = m->omsg.data;
3754 mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class
3755
3756 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3757 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3758 if (!KnownAnswerList)
3759 {
3760 // Start a new known-answer list
3761 CacheRecord **kalistptr = &KnownAnswerList;
3762 mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3763
3764 // Put query questions in this packet
3765 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3766 {
3767 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3768 {
3769 mDNSBool Suppress = mDNSfalse;
3770 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3771 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
3772 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3773
3774 // If interface is P2P type, verify that query should be sent over it.
3775 if (!mDNSPlatformValidQuestionForInterface(q, intf))
3776 {
3777 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3778 }
3779 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3780 else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3781 BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3782 {
3783 // We successfully added the question to the packet. Make sure that
3784 // we also send the NSEC3 record if required. BuildQuestion accounted for
3785 // the space.
3786 //
3787 // Note: We don't suppress anonymous questions and hence Suppress should always
3788 // be zero.
3789
3790 if (Suppress)
3791 m->mDNSStats.DupQuerySuppressions++;
3792
3793 if (!Suppress && q->AnonInfo)
3794 {
3795 debugf("SendQueries: marking for question %##s, Suppress %d", q->qname.c, Suppress);
3796 q->AnonInfo->SendNow = intf->InterfaceID;
3797 }
3798 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3799 if (q->WakeOnResolveCount)
3800 {
3801 mDNSSendWakeOnResolve(m, q);
3802 q->WakeOnResolveCount--;
3803 }
3804
3805 // use background traffic class if any included question requires it
3806 if (q->UseBackgroundTrafficClass)
3807 {
3808 useBackgroundTrafficClass = mDNStrue;
3809 }
3810 }
3811 }
3812 }
3813
3814 // Put probe questions in this packet
3815 for (ar = m->ResourceRecords; ar; ar=ar->next)
3816 {
3817 if (ar->SendRNow != intf->InterfaceID)
3818 continue;
3819
3820 // If interface is a P2P variant, verify that the probe should be sent over it.
3821 if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID))
3822 {
3823 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3824 ar->IncludeInProbe = mDNSfalse;
3825 }
3826 else
3827 {
3828 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3829 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3830 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3831 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3832 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3833 mDNSBool putProbe = mDNStrue;
3834 mDNSu16 qclass = ar->resrec.rrclass | ucbit;
3835
3836 {// Determine if this probe question is already in packet's dns message
3837 const mDNSu8 *questionptr = m->omsg.data;
3838 DNSQuestion question;
3839 mDNSu16 n;
3840 for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++)
3841 {
3842 questionptr = getQuestion(&m->omsg, questionptr, limit, mDNSInterface_Any, &question);
3843 if (questionptr && (question.qtype == kDNSQType_ANY) && (question.qclass == qclass) &&
3844 (question.qnamehash == ar->resrec.namehash) && SameDomainName(&question.qname, ar->resrec.name))
3845 {
3846 putProbe = mDNSfalse; // set to false if already in message
3847 break;
3848 }
3849 }
3850 }
3851
3852 if (putProbe)
3853 {
3854 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass);
3855 if (newptr)
3856 {
3857 queryptr = newptr;
3858 answerforecast = forecast;
3859 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3860 ar->IncludeInProbe = mDNStrue;
3861 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3862 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount, ar->resrec.InterfaceID, ar->resrec.rdestimate, answerforecast);
3863 }
3864 }
3865 else
3866 {
3867 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3868 ar->IncludeInProbe = mDNStrue;
3869 }
3870 }
3871 }
3872 }
3873
3874 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3875 while (KnownAnswerList)
3876 {
3877 CacheRecord *ka = KnownAnswerList;
3878 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3879 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3880 m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3881 if (newptr)
3882 {
3883 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3884 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3885 queryptr = newptr;
3886 KnownAnswerList = ka->NextInKAList;
3887 ka->NextInKAList = mDNSNULL;
3888 }
3889 else
3890 {
3891 // If we ran out of space and we have more than one question in the packet, that's an error --
3892 // we shouldn't have put more than one question if there was a risk of us running out of space.
3893 if (m->omsg.h.numQuestions > 1)
3894 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3895 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3896 break;
3897 }
3898 }
3899
3900 for (ar = m->ResourceRecords; ar; ar=ar->next)
3901 {
3902 if (ar->IncludeInProbe)
3903 {
3904 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3905 ar->IncludeInProbe = mDNSfalse;
3906 if (newptr) queryptr = newptr;
3907 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3908 }
3909 }
3910
3911 for (q = m->Questions; q; q = q->next)
3912 {
3913 if (q->AnonInfo && q->AnonInfo->SendNow == intf->InterfaceID)
3914 {
3915 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, q->AnonInfo->nsec3RR);
3916 if (newptr)
3917 {
3918 debugf("SendQueries: Added NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3919 queryptr = newptr;
3920 }
3921 else
3922 {
3923 LogMsg("SendQueries: ERROR!! Cannot add NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3924 }
3925 q->AnonInfo->SendNow = mDNSNULL;
3926 }
3927 }
3928
3929 if (queryptr > m->omsg.data)
3930 {
3931 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3932 if (OwnerRecordSpace || TraceRecordSpace)
3933 {
3934 AuthRecord opt;
3935 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3936 opt.resrec.rrclass = NormalMaxDNSMessageData;
3937 opt.resrec.rdlength = sizeof(rdataOPT);
3938 opt.resrec.rdestimate = sizeof(rdataOPT);
3939 if (OwnerRecordSpace && TraceRecordSpace)
3940 {
3941 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
3942 opt.resrec.rdestimate += sizeof(rdataOPT);
3943 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3944 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3945 }
3946 else if (OwnerRecordSpace)
3947 {
3948 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3949 }
3950 else if (TraceRecordSpace)
3951 {
3952 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3953 }
3954 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3955 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3956 if (!queryptr)
3957 {
3958 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3959 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3960 }
3961 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3962 {
3963 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3964 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
3965 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
3966 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3967 }
3968 }
3969
3970 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3971 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3972 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
3973 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
3974 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
3975 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3976 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3977 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3978 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3979 if (++pktcount >= 1000)
3980 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3981 // There might be more records left in the known answer list, or more questions to send
3982 // on this interface, so go around one more time and try again.
3983 }
3984 else // Nothing more to send on this interface; go to next
3985 {
3986 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3987 #if MDNS_DEBUGMSGS && 0
3988 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
3989 debugf(msg, intf, next);
3990 #endif
3991 intf = next;
3992 }
3993 }
3994
3995 // 4. Final housekeeping
3996
3997 // 4a. Debugging check: Make sure we announced all our records
3998 for (ar = m->ResourceRecords; ar; ar=ar->next)
3999 if (ar->SendRNow)
4000 {
4001 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
4002 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4003 (uint32_t)ar->SendRNow, (uint32_t)ar->resrec.InterfaceID, ARDisplayString(m, ar));
4004 ar->SendRNow = mDNSNULL;
4005 }
4006
4007 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4008 // that their interface which went away might come back again, the logic will want to send queries
4009 // for those records, but we can't because their interface isn't here any more, so to keep the
4010 // state machine ticking over we just pretend we did so.
4011 // If the interface does not come back in time, the cache record will expire naturally
4012 FORALL_CACHERECORDS(slot, cg, cr)
4013 {
4014 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
4015 {
4016 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
4017 {
4018 cr->UnansweredQueries++;
4019 cr->CRActiveQuestion->SendQNow = mDNSNULL;
4020 SetNextCacheCheckTimeForRecord(m, cr);
4021 }
4022 }
4023 }
4024
4025 // 4c. Debugging check: Make sure we sent all our planned questions
4026 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4027 // we legitimately couldn't send because the interface is no longer available
4028 for (q = m->Questions; q; q=q->next)
4029 {
4030 if (q->SendQNow)
4031 {
4032 DNSQuestion *x;
4033 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
4034 // There will not be an active interface for questions applied to mDNSInterface_BLE
4035 // so don't log the warning in that case.
4036 if (q->InterfaceID != mDNSInterface_BLE)
4037 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4038 (uint32_t)q->SendQNow, x ? "new" : "old", (uint32_t)q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
4039 q->SendQNow = mDNSNULL;
4040 }
4041 q->CachedAnswerNeedsUpdate = mDNSfalse;
4042 }
4043 }
4044
4045 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly)
4046 {
4047 int i, j;
4048
4049 mDNSu8 *ptr = m->omsg.data;
4050 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
4051 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
4052
4053 // 0x00 Destination address
4054 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4055
4056 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4057 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
4058
4059 // 0x0C Ethertype (0x0842)
4060 *ptr++ = 0x08;
4061 *ptr++ = 0x42;
4062
4063 // 0x0E Wakeup sync sequence
4064 for (i=0; i<6; i++) *ptr++ = 0xFF;
4065
4066 // 0x14 Wakeup data
4067 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4068
4069 // 0x74 Password
4070 for (i=0; i<6; i++) *ptr++ = password->b[i];
4071
4072 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4073
4074 if (!unicastOnly)
4075 {
4076 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4077 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4078 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4079 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4080 // So, we send one of each, unicast first, then broadcast second.
4081 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
4082 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4083 }
4084 }
4085
4086 // ***************************************************************************
4087 #if COMPILER_LIKES_PRAGMA_MARK
4088 #pragma mark -
4089 #pragma mark - RR List Management & Task Management
4090 #endif
4091
4092 // Whenever a question is answered, reset its state so that we don't query
4093 // the network repeatedly. This happens first time when we answer the question and
4094 // and later when we refresh the cache.
4095 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
4096 {
4097 q->LastQTime = m->timenow;
4098 q->LastQTxTime = m->timenow;
4099 q->RecentAnswerPkts = 0;
4100 q->ThisQInterval = MaxQuestionInterval;
4101 q->RequestUnicast = 0;
4102 // Reset unansweredQueries so that we don't penalize this server later when we
4103 // start sending queries when the cache expires.
4104 q->unansweredQueries = 0;
4105 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4106 }
4107
4108 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4109 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4110 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4111 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4112 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
4113 {
4114 DNSQuestion *const q = m->CurrentQuestion;
4115 const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
4116
4117 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
4118 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", MortalityDisplayString(rr->resrec.mortality),
4119 rr->resrec.rroriginalttl, CRDisplayString(m, rr));
4120
4121 // When the response for the question was validated, the entire rrset was validated. If we deliver
4122 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
4123 // in the future, we will do the revalidation again.
4124 //
4125 // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
4126 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
4127 // negative response which can happen e.g., when disconnecting from network that leads to a negative response
4128 // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
4129 // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
4130 // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
4131 // a real negative response, we would reset the state here and validate the results at the end of this function.
4132 // or the real response again if we purge the cache.
4133 if (q->ValidationRequired && ((AddRecord == QC_rmv) ||
4134 (rr->resrec.RecordType == kDNSRecordTypePacketNegative && (AddRecord == QC_add))))
4135 {
4136 q->ValidationStatus = 0;
4137 q->ValidationState = DNSSECValRequired;
4138 }
4139
4140 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4141 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4142 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4143 // we check to see if that query already has a unique local answer.
4144 if (q->LOAddressAnswers)
4145 {
4146 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4147 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
4148 q->LOAddressAnswers);
4149 return;
4150 }
4151
4152 if (QuerySuppressed(q))
4153 {
4154 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4155 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4156 // that are timing out, which we know are answered with negative cache record when timing out.
4157 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
4158 return;
4159 }
4160
4161 // Set the record to immortal if appropriate
4162 if (AddRecord == QC_add && Question_uDNS(q) && rr->resrec.RecordType != kDNSRecordTypePacketNegative &&
4163 q->allowExpired != AllowExpired_None && rr->resrec.mortality == Mortality_Mortal ) rr->resrec.mortality = Mortality_Immortal; // Update a non-expired cache record to immortal if appropriate
4164
4165 #if AWD_METRICS
4166 if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname)
4167 {
4168 const domainname * queryName;
4169 mDNSu32 responseLatencyMs;
4170 mDNSBool isForCellular;
4171
4172 queryName = q->metrics.originalQName ? q->metrics.originalQName : &q->qname;
4173 isForCellular = (q->qDNSServer && q->qDNSServer->cellIntf);
4174 if (!q->metrics.answered)
4175 {
4176 if (q->metrics.querySendCount > 0)
4177 {
4178 responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
4179 }
4180 else
4181 {
4182 responseLatencyMs = 0;
4183 }
4184
4185 MetricsUpdateDNSQueryStats(queryName, q->qtype, &rr->resrec, q->metrics.querySendCount, q->metrics.expiredAnswerState, responseLatencyMs, isForCellular);
4186 q->metrics.answered = mDNStrue;
4187 }
4188 if (q->metrics.querySendCount > 0)
4189 {
4190 MetricsUpdateDNSResolveStats(queryName, &rr->resrec, isForCellular);
4191 }
4192 }
4193 #endif
4194 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4195 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4196 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4197
4198 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q && rr->resrec.mortality != Mortality_Ghost)
4199 {
4200 if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
4201 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4202 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
4203 rr->CRActiveQuestion = q; // We know q is non-null
4204 SetNextCacheCheckTimeForRecord(m, rr);
4205 }
4206
4207 // If this is:
4208 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4209 // (b) a normal add, where we have at least one unique-type answer,
4210 // then there's no need to keep polling the network.
4211 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4212 // We do this for mDNS questions and uDNS one-shot questions, but not for
4213 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4214 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
4215 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
4216 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
4217 {
4218 ResetQuestionState(m, q);
4219 }
4220
4221 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4222
4223 #if USE_DNS64
4224 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4225 if (!mDNSOpaque16IsZero(q->TargetQID) && DNS64StateMachine(m, q, &rr->resrec, AddRecord)) return;
4226 #endif
4227
4228 #ifdef USE_LIBIDN
4229 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) // If negative answer, check if we need to try Punycode conversion
4230 {
4231 domainname newname;
4232 if (PerformNextPunycodeConversion(q, &newname)) // Itertative Punycode conversion succeeded, so reissue question with new name
4233 {
4234 UDPSocket *const sock = q->LocalSocket; // Save old socket and transaction ID
4235 const mDNSOpaque16 id = q->TargetQID;
4236 q->LocalSocket = mDNSNULL;
4237 mDNS_StopQuery_internal(m, q); // Stop old query
4238 AssignDomainName(&q->qname, &newname); // Update qname
4239 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
4240 mDNS_StartQuery_internal(m, q); // Start new query
4241
4242 if (sock) // Transplant saved socket, if appropriate
4243 {
4244 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
4245 else { q->LocalSocket = sock; q->TargetQID = id; }
4246 }
4247 return; // All done for now; wait until we get the next answer
4248 }
4249 }
4250 #endif // USE_LIBIDN
4251
4252 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4253 // for the purpose of retrying search domains/timeout OR the question is suppressed
4254 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
4255 if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
4256
4257 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4258 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
4259 {
4260 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4261 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
4262 {
4263 CacheRecord neg;
4264 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
4265 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
4266 }
4267 else
4268 {
4269 #if USE_DNS64
4270 if (DNS64ShouldAnswerQuestion(q, &rr->resrec))
4271 {
4272 DNS64AnswerQuestion(m, q, &rr->resrec, AddRecord);
4273 }
4274 else
4275 #endif
4276 {
4277 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4278 }
4279 }
4280 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4281 }
4282 // If this is an "Add" operation and this question needs validation, validate the response.
4283 // In the case of negative responses, extra care should be taken. Negative cache records are
4284 // used for many purposes. For example,
4285 //
4286 // 1) Suppressing questions (SuppressUnusable)
4287 // 2) Timeout questions
4288 // 3) The name does not exist
4289 // 4) No DNS servers are available and we need a quick response for the application
4290 //
4291 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
4292 // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
4293 // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
4294 // signature for (4) and hence the explicit check for q->qDNSServer.
4295 //
4296 if (m->CurrentQuestion == q && (AddRecord == QC_add) && !q->ValidatingResponse && q->ValidationRequired &&
4297 q->ValidationState == DNSSECValRequired && q->qDNSServer)
4298 {
4299 q->ValidationState = DNSSECValInProgress;
4300 // Treat it as callback call as that's what dnssec code expects
4301 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4302 VerifySignature(m, mDNSNULL, q);
4303 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4304 return;
4305 }
4306
4307 if ((m->CurrentQuestion == q) && !ValidatingQuestion(q))
4308 {
4309 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4310 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4311 // first before following it
4312 if (followcname) AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
4313
4314 // If we are returning expired RRs, then remember the first expired qname we we can start the query again
4315 if (rr->resrec.mortality == Mortality_Ghost && !q->firstExpiredQname.c[0] && (q->allowExpired == AllowExpired_AllowExpiredAnswers) && rr->resrec.RecordType != kDNSRecordTypePacketNegative)
4316 {
4317 debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m,rr), q);
4318 // Note: question->qname is already changed at this point if following a CNAME
4319 AssignDomainName(&q->firstExpiredQname, rr->resrec.name); // Update firstExpiredQname
4320 }
4321 }
4322 }
4323
4324 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
4325 {
4326 rr->DelayDelivery = 0;
4327 if (m->CurrentQuestion)
4328 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4329 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4330 m->CurrentQuestion = m->Questions;
4331 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4332 {
4333 DNSQuestion *q = m->CurrentQuestion;
4334 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4335 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4336 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4337 m->CurrentQuestion = q->next;
4338 }
4339 m->CurrentQuestion = mDNSNULL;
4340 }
4341
4342 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
4343 {
4344 const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
4345 const mDNSs32 start = m->timenow - 0x10000000;
4346 mDNSs32 delay = start;
4347 CacheGroup *cg = CacheGroupForName(m, namehash, name);
4348 const CacheRecord *rr;
4349
4350 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4351 {
4352 if (threshold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
4353 {
4354 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
4355 delay = RRExpireTime(rr);
4356 }
4357 }
4358 if (delay - start > 0)
4359 return(NonZeroTime(delay));
4360 else
4361 return(0);
4362 }
4363
4364 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4365 // If new questions are created as a result of invoking client callbacks, they will be added to
4366 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4367 // rr is a new CacheRecord just received into our cache
4368 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4369 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4370 // which may change the record list and/or question list.
4371 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4372 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
4373 {
4374 DNSQuestion *q;
4375
4376 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4377 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4378 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4379 {
4380 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4381 {
4382 // If this question is one that's actively sending queries, and it's received ten answers within one
4383 // second of sending the last query packet, then that indicates some radical network topology change,
4384 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4385 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4386 // because we will anyway send another query within a few seconds. The first reset query is sent out
4387 // randomized over the next four seconds to reduce possible synchronization between machines.
4388 if (q->LastAnswerPktNum != m->PktNum)
4389 {
4390 q->LastAnswerPktNum = m->PktNum;
4391 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4392 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4393 {
4394 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4395 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4396 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4397 q->ThisQInterval = InitialQuestionInterval;
4398 SetNextQueryTime(m,q);
4399 }
4400 }
4401 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
4402 DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
4403 &rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
4404 rr->resrec.rDNSServer->port : zeroIPPort), q);
4405 q->CurrentAnswers++;
4406
4407 q->unansweredQueries = 0;
4408 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4409 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4410 if (q->CurrentAnswers > 4000)
4411 {
4412 static int msgcount = 0;
4413 if (msgcount++ < 10)
4414 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4415 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4416 rr->resrec.rroriginalttl = 0;
4417 rr->UnansweredQueries = MaxUnansweredQueries;
4418 }
4419 }
4420 }
4421
4422 if (!rr->DelayDelivery)
4423 {
4424 if (m->CurrentQuestion)
4425 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4426 m->CurrentQuestion = m->Questions;
4427 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4428 {
4429 q = m->CurrentQuestion;
4430 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4431 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4432 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4433 m->CurrentQuestion = q->next;
4434 }
4435 m->CurrentQuestion = mDNSNULL;
4436 }
4437
4438 SetNextCacheCheckTimeForRecord(m, rr);
4439 }
4440
4441 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4442 // If new questions are created as a result of invoking client callbacks, they will be added to
4443 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4444 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4445 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4446 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4447 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4448 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4449 // which may change the record list and/or question list.
4450 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4451 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
4452 {
4453 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4454 if (m->CurrentQuestion)
4455 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4456 m->CurrentQuestion = m->Questions;
4457 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4458 // since we're not caching the record and we'll get no opportunity to do this later
4459 while (m->CurrentQuestion)
4460 {
4461 DNSQuestion *q = m->CurrentQuestion;
4462 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4463 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
4464 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4465 m->CurrentQuestion = q->next;
4466 }
4467 m->CurrentQuestion = mDNSNULL;
4468 }
4469
4470 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4471 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4472 // If new questions are created as a result of invoking client callbacks, they will be added to
4473 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4474 // rr is an existing cache CacheRecord that just expired and is being deleted
4475 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4476 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4477 // which may change the record list and/or question list.
4478 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4479 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
4480 {
4481 if (m->CurrentQuestion)
4482 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4483 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4484 m->CurrentQuestion = m->Questions;
4485
4486 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4487 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4488 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4489 {
4490 DNSQuestion *q = m->CurrentQuestion;
4491 // When a question enters suppressed state, we generate RMV events and generate a negative
4492 // response. A cache may be present that answers this question e.g., cache entry generated
4493 // before the question became suppressed. We need to skip the suppressed questions here as
4494 // the RMV event has already been generated.
4495 if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q) &&
4496 (q->allowExpired == AllowExpired_None || rr->resrec.mortality == Mortality_Mortal))
4497 {
4498 verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
4499 q->FlappingInterface1 = mDNSNULL;
4500 q->FlappingInterface2 = mDNSNULL;
4501
4502 if (q->CurrentAnswers == 0)
4503 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4504 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4505 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
4506 else
4507 {
4508 q->CurrentAnswers--;
4509 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4510 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4511 }
4512
4513 // If we have dropped below the answer threshold for this mDNS question,
4514 // restart the queries at InitialQuestionInterval.
4515 if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4516 {
4517 q->ThisQInterval = InitialQuestionInterval;
4518 q->LastQTime = m->timenow - q->ThisQInterval;
4519 SetNextQueryTime(m,q);
4520 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4521 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4522 }
4523 if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4524 {
4525 if ((q->CurrentAnswers == 0) && mDNSOpaque16IsZero(q->TargetQID))
4526 {
4527 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4528 q->qname.c, DNSTypeName(q->qtype));
4529 ReconfirmAntecedents(m, &q->qname, q->qnamehash, rr->resrec.InterfaceID, 0);
4530 }
4531 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
4532 }
4533 }
4534 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4535 m->CurrentQuestion = q->next;
4536 }
4537 m->CurrentQuestion = mDNSNULL;
4538 }
4539
4540 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4541 {
4542 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
4543 unsigned int i;
4544 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4545 #endif
4546 e->next = m->rrcache_free;
4547 m->rrcache_free = e;
4548 m->rrcache_totalused--;
4549 }
4550
4551 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4552 {
4553 CacheEntity *e = (CacheEntity *)(*cp);
4554 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4555 if ((*cp)->rrcache_tail != &(*cp)->members)
4556 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4557 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4558 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4559 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4560 (*cp)->name = mDNSNULL;
4561 *cp = (*cp)->next; // Cut record from list
4562 ReleaseCacheEntity(m, e);
4563 }
4564
4565 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4566 {
4567 while (*rp)
4568 {
4569 CacheRecord *rr = *rp;
4570 *rp = (*rp)->next; // Cut record from list
4571 if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4572 {
4573 mDNSPlatformMemFree(rr->resrec.rdata);
4574 rr->resrec.rdata = mDNSNULL;
4575 }
4576 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4577 // of the CacheGroup.
4578 if (rr->resrec.name)
4579 {
4580 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4581 mDNSPlatformMemFree((void *)rr->resrec.name);
4582 rr->resrec.name = mDNSNULL;
4583 }
4584 // Don't count the NSEC3 records used by anonymous browse/reg
4585 if (!rr->resrec.InterfaceID)
4586 {
4587 m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4588 if (DNSSECRecordType(rr->resrec.rrtype))
4589 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
4590 }
4591 ReleaseCacheEntity(m, (CacheEntity *)rr);
4592 }
4593 }
4594
4595 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4596 {
4597 CacheGroup *cg;
4598
4599 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4600 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4601 r->resrec.rdata = mDNSNULL;
4602
4603 cg = CacheGroupForRecord(m, &r->resrec);
4604
4605 if (!cg)
4606 {
4607 // It is okay to have this printed for NSEC/NSEC3s
4608 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4609 }
4610 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4611 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4612 // (which is handled below) and in that case it should be freed here.
4613 if (r->resrec.name && cg && r->resrec.name != cg->name)
4614 {
4615 debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4616 mDNSPlatformMemFree((void *)r->resrec.name);
4617 }
4618 r->resrec.name = mDNSNULL;
4619
4620 if (r->resrec.AnonInfo)
4621 {
4622 debugf("ReleaseCacheRecord: freeing AnonInfo for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4623 FreeAnonInfo((void *)r->resrec.AnonInfo);
4624 }
4625 r->resrec.AnonInfo = mDNSNULL;
4626
4627 if (!r->resrec.InterfaceID)
4628 {
4629 m->rrcache_totalused_unicast -= r->resrec.rdlength;
4630 if (DNSSECRecordType(r->resrec.rrtype))
4631 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, r->resrec.rdlength);
4632 }
4633
4634 ReleaseAdditionalCacheRecords(m, &r->nsec);
4635 ReleaseAdditionalCacheRecords(m, &r->soa);
4636
4637 ReleaseCacheEntity(m, (CacheEntity *)r);
4638 }
4639
4640 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4641 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4642 // callbacks for old records are delivered before callbacks for newer records.
4643 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4644 {
4645 CacheRecord **rp = &cg->members;
4646
4647 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4648 m->lock_rrcache = 1;
4649
4650 while (*rp)
4651 {
4652 CacheRecord *const rr = *rp;
4653 mDNSBool recordReleased = mDNSfalse;
4654 mDNSs32 event = RRExpireTime(rr);
4655 if (m->timenow - event >= 0) // If expired, delete it
4656 {
4657 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
4658 {
4659 DNSQuestion *q = rr->CRActiveQuestion;
4660 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
4661 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4662 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4663 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4664 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4665 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4666 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4667 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4668 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4669 if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
4670 {
4671 q->ThisQInterval = InitialQuestionInterval;
4672 q->LastQTime = m->timenow - q->ThisQInterval;
4673 SetNextQueryTime(m, q);
4674 }
4675 CacheRecordRmv(m, rr);
4676 m->rrcache_active--;
4677 }
4678
4679 event += MAX_GHOST_TIME; // Adjust so we can check for a ghost expiration
4680 if (rr->resrec.mortality == Mortality_Mortal || // Normal expired mortal record that needs released
4681 (rr->resrec.mortality == Mortality_Ghost && m->timenow - event >= 0)) // A ghost record that expired more than MAX_GHOST_TIME ago
4682 { // Release as normal
4683 *rp = rr->next; // Cut it from the list before ReleaseCacheRecord
4684 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
4685 MortalityDisplayString(rr->resrec.mortality),
4686 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4687 ReleaseCacheRecord(m, rr);
4688 recordReleased = mDNStrue;
4689 }
4690 else // An immortal record needs to become a ghost when it expires
4691 { // Don't release this entry
4692 if (rr->resrec.mortality == Mortality_Immortal)
4693 {
4694 rr->resrec.mortality = Mortality_Ghost; // Expired immortal records become ghosts
4695 verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
4696 MortalityDisplayString(rr->resrec.mortality),
4697 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4698 }
4699 }
4700 }
4701 else // else, not expired; see if we need to query
4702 {
4703 // If waiting to delay delivery, do nothing until then
4704 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4705 event = rr->DelayDelivery;
4706 else
4707 {
4708 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4709 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4710 {
4711 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
4712 event = NextCacheCheckEvent(rr); // then just record when we want the next query
4713 else // else trigger our question to go out now
4714 {
4715 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4716 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4717 m->NextScheduledQuery = m->timenow;
4718 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4719 // which will correctly update m->NextCacheCheck for us.
4720 event = m->timenow + FutureTime;
4721 }
4722 }
4723 }
4724 }
4725
4726 if (!recordReleased) // Schedule if we did not release the record
4727 {
4728 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4729 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4730 if (m->rrcache_nextcheck[slot] - event > 0)
4731 m->rrcache_nextcheck[slot] = event;
4732 rp = &rr->next;
4733 }
4734 }
4735 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4736 cg->rrcache_tail = rp;
4737 m->lock_rrcache = 0;
4738 }
4739
4740 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4741 //
4742 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4743 // returns true if there is an answer.
4744 //
4745 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4746 // returns true to indicate the same.
4747 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4748 {
4749 AuthRecord *lr;
4750 AuthGroup *ag;
4751
4752 if (m->CurrentRecord)
4753 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4754
4755 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
4756 if (ag)
4757 {
4758 m->CurrentRecord = ag->members;
4759 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4760 {
4761 AuthRecord *rr = m->CurrentRecord;
4762 m->CurrentRecord = rr->next;
4763 //
4764 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4765 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4766 //
4767 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4768 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4769 // we handle both mDNSInterface_Any and scoped questions.
4770
4771 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE)))
4772 if (LocalOnlyRecordAnswersQuestion(rr, q))
4773 {
4774 if (checkOnly)
4775 {
4776 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4777 ARDisplayString(m, rr));
4778 m->CurrentRecord = mDNSNULL;
4779 return mDNStrue;
4780 }
4781 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4782 if (m->CurrentQuestion != q)
4783 break; // If callback deleted q, then we're finished here
4784 }
4785 }
4786 }
4787 m->CurrentRecord = mDNSNULL;
4788
4789 if (m->CurrentQuestion != q)
4790 {
4791 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4792 return mDNStrue;
4793 }
4794
4795 if (q->LOAddressAnswers)
4796 {
4797 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4798 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4799 return mDNStrue;
4800 }
4801
4802 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4803 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4804 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4805 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4806 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4807 if (ag)
4808 {
4809 lr = ag->NewLocalOnlyRecords;
4810 while (lr)
4811 {
4812 if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4813 {
4814 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4815 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4816 return mDNStrue;
4817 }
4818 lr = lr->next;
4819 }
4820 }
4821 return mDNSfalse;
4822 }
4823
4824 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4825 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4826 // DNS requests. We need to temporarily suspend the suppress status so that we can
4827 // deliver a negative response (AnswerCurrentQuestionWithResourceRecord does not answer
4828 // suppressed questions) and reset it back. In the future, if there are other
4829 // reasons for suppressing the query, this function should be updated.
4830 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4831 {
4832 mDNSBool SuppressQuery;
4833 mDNSBool DisallowPID;
4834
4835 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response, just
4836 // deactivate the DNSQuestion.
4837 if (!q->ReturnIntermed)
4838 {
4839 q->ThisQInterval = 0;
4840 return;
4841 }
4842
4843 SuppressQuery = q->SuppressQuery;
4844 DisallowPID = q->DisallowPID;
4845
4846 // make sure that QuerySuppressed() returns false
4847 q->SuppressQuery = mDNSfalse;
4848 q->DisallowPID = mDNSfalse;
4849
4850 GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed);
4851
4852 q->SuppressQuery = SuppressQuery;
4853 q->DisallowPID = DisallowPID;
4854 }
4855
4856 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4857 {
4858 mDNSBool ShouldQueryImmediately = mDNStrue;
4859 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
4860 #if USE_DNS64
4861 if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q);
4862 #endif
4863 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
4864 mDNSBool AnsweredFromCache = mDNSfalse;
4865
4866 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4867
4868 if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg);
4869 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4870 m->NewQuestions = q->next;
4871 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4872 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4873 //
4874 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4875 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4876 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4877 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4878 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4879 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4880 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4881 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4882 //
4883 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4884 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4885 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4886 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4887
4888 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4889 // This should be safe, because calling the client's question callback may cause the
4890 // question list to be modified, but should not ever cause the rrcache list to be modified.
4891 // If the client's question callback deletes the question, then m->CurrentQuestion will
4892 // be advanced, and we'll exit out of the loop
4893 m->lock_rrcache = 1;
4894 if (m->CurrentQuestion)
4895 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4896 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4897 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4898
4899 if (q->NoAnswer == NoAnswer_Fail)
4900 {
4901 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4902 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
4903 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
4904 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
4905 // Don't touch the question if it has been stopped already
4906 if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
4907 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
4908 }
4909
4910 if (m->CurrentQuestion != q)
4911 {
4912 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4913 goto exit;
4914 }
4915
4916 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4917 // or P2P record, then we are done.
4918 if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
4919 goto exit;
4920
4921 // If we are not supposed to answer this question, generate a negative response.
4922 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
4923 //
4924 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
4925 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
4926 // the question out.
4927 if (QuerySuppressed(q))
4928 {
4929 AnswerSuppressedQuestion(m, q);
4930 }
4931 else if (!q->ValidatingResponse)
4932 {
4933 CacheRecord *rr;
4934 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4935 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
4936 {
4937 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4938 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
4939 if (rr->resrec.rroriginalttl <= SecsSinceRcvd && q->allowExpired != AllowExpired_AllowExpiredAnswers) continue; // Go to next one in loop
4940
4941 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4942 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4943 if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
4944 ShouldQueryImmediately = mDNSfalse;
4945 q->CurrentAnswers++;
4946 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4947 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4948 AnsweredFromCache = mDNStrue;
4949 #if AWD_METRICS
4950 if (q->metrics.expiredAnswerState == ExpiredAnswer_Allowed) q->metrics.expiredAnswerState = ExpiredAnswer_AnsweredWithExpired;
4951 #endif
4952 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4953 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4954 }
4955 else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
4956 ShouldQueryImmediately = mDNSfalse;
4957 }
4958 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
4959 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
4960 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
4961
4962 // Neither a local record nor a cache entry could answer this question. If this question need to be retried
4963 // with search domains, generate a negative response which will now retry after appending search domains.
4964 // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
4965 // we will retry with search domains.
4966 if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
4967 {
4968 LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4969 GenerateNegativeResponse(m, mDNSInterface_Any, QC_forceresponse);
4970 }
4971
4972 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
4973
4974 if (q->allowExpired == AllowExpired_AllowExpiredAnswers)
4975 {
4976 q->allowExpired = AllowExpired_MakeAnswersImmortal; // After looking through the cache for an answer, demote to make immortal
4977 if (q->firstExpiredQname.c[0]) // If an original query name was saved on an expired answer, start it over in case it is updated
4978 {
4979 LogMsg("AnswerNewQuestion: Restarting original question %p firstExpiredQname %##s for allowExpiredAnswers question", q, &q->firstExpiredQname.c);
4980 mDNS_StopQuery_internal(m, q); // Stop old query
4981 AssignDomainName(&q->qname, &q->firstExpiredQname); // Update qname
4982 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
4983 mDNS_StartQuery_internal(m, q); // start new query
4984 q->CNAMEReferrals = 0; // Reset referral count
4985 q->firstExpiredQname.c[0] = 0; // Erase the domain name
4986 }
4987 }
4988
4989 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
4990 // Hence we don't execute the following block of code for those cases.
4991 if (ShouldQueryImmediately && ActiveQuestion(q))
4992 {
4993 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4994 q->ThisQInterval = InitialQuestionInterval;
4995 q->LastQTime = m->timenow - q->ThisQInterval;
4996 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
4997 {
4998 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
4999 if (!m->RandomQueryDelay)
5000 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
5001 q->LastQTime += m->RandomQueryDelay;
5002 }
5003 }
5004
5005 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5006 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5007 // answers for this question until *after* its scheduled transmission time, in which case
5008 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5009 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5010 SetNextQueryTime(m,q);
5011
5012 exit:
5013 m->CurrentQuestion = mDNSNULL;
5014 m->lock_rrcache = 0;
5015 }
5016
5017 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5018 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
5019 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
5020 {
5021 AuthGroup *ag;
5022 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
5023 mDNSBool retEv = mDNSfalse;
5024 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
5025
5026 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5027
5028 if (m->CurrentQuestion)
5029 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5030 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5031 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
5032
5033 if (m->CurrentRecord)
5034 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5035
5036 // 1. First walk the LocalOnly records answering the LocalOnly question
5037 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5038 // walk the ResourceRecords list delivering the answers
5039 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5040 if (ag)
5041 {
5042 m->CurrentRecord = ag->members;
5043 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
5044 {
5045 AuthRecord *rr = m->CurrentRecord;
5046 m->CurrentRecord = rr->next;
5047 if (LocalOnlyRecordAnswersQuestion(rr, q))
5048 {
5049 retEv = mDNStrue;
5050 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
5051 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5052 }
5053 }
5054 }
5055
5056 if (m->CurrentQuestion == q)
5057 {
5058 m->CurrentRecord = m->ResourceRecords;
5059
5060 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
5061 {
5062 AuthRecord *rr = m->CurrentRecord;
5063 m->CurrentRecord = rr->next;
5064 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
5065 {
5066 retEv = mDNStrue;
5067 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
5068 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5069 }
5070 }
5071 }
5072
5073 // The local host is the authoritative source for LocalOnly questions
5074 // so if no records exist and client requested intermediates, then generate a negative response
5075 if (!retEv && (m->CurrentQuestion == q) && q->ReturnIntermed)
5076 GenerateNegativeResponse(m, mDNSInterface_LocalOnly, QC_forceresponse);
5077
5078 m->CurrentQuestion = mDNSNULL;
5079 m->CurrentRecord = mDNSNULL;
5080 }
5081
5082 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
5083 {
5084 CacheEntity *e = mDNSNULL;
5085
5086 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
5087 m->lock_rrcache = 1;
5088
5089 // If we have no free records, ask the client layer to give us some more memory
5090 if (!m->rrcache_free && m->MainCallback)
5091 {
5092 if (m->rrcache_totalused != m->rrcache_size)
5093 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
5094 m->rrcache_totalused, m->rrcache_size);
5095
5096 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5097 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5098 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5099 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5100 // and recycle them, instead of allocating more memory.
5101 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
5102 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
5103 m->rrcache_size, m->rrcache_active);
5104 else
5105 {
5106 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5107 m->MainCallback(m, mStatus_GrowCache);
5108 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5109 }
5110 }
5111
5112 // If we still have no free records, recycle all the records we can.
5113 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5114 if (!m->rrcache_free)
5115 {
5116 mDNSu32 oldtotalused = m->rrcache_totalused;
5117 mDNSu32 slot;
5118 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5119 {
5120 CacheGroup **cp = &m->rrcache_hash[slot];
5121 while (*cp)
5122 {
5123 CacheRecord **rp = &(*cp)->members;
5124 while (*rp)
5125 {
5126 // Records that answer still-active questions are not candidates for recycling
5127 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5128 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
5129 rp=&(*rp)->next;
5130 else
5131 {
5132 CacheRecord *rr = *rp;
5133 *rp = (*rp)->next; // Cut record from list
5134 ReleaseCacheRecord(m, rr);
5135 }
5136 }
5137 if ((*cp)->rrcache_tail != rp)
5138 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
5139 (*cp)->rrcache_tail = rp;
5140 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
5141 else ReleaseCacheGroup(m, cp);
5142 }
5143 }
5144 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
5145 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
5146 }
5147
5148 if (m->rrcache_free) // If there are records in the free list, take one
5149 {
5150 e = m->rrcache_free;
5151 m->rrcache_free = e->next;
5152 if (++m->rrcache_totalused >= m->rrcache_report)
5153 {
5154 LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
5155 if (m->rrcache_report < 100) m->rrcache_report += 10;
5156 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
5157 else m->rrcache_report += 1000;
5158 }
5159 mDNSPlatformMemZero(e, sizeof(*e));
5160 }
5161
5162 m->lock_rrcache = 0;
5163
5164 return(e);
5165 }
5166
5167 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
5168 {
5169 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
5170 if (r)
5171 {
5172 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
5173 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
5174 {
5175 r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
5176 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
5177 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
5178 }
5179 }
5180 return(r);
5181 }
5182
5183 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
5184 {
5185 mDNSu16 namelen = DomainNameLength(rr->name);
5186 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
5187 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
5188 cg->next = m->rrcache_hash[slot];
5189 cg->namehash = rr->namehash;
5190 cg->members = mDNSNULL;
5191 cg->rrcache_tail = &cg->members;
5192 if (namelen > sizeof(cg->namestorage))
5193 cg->name = mDNSPlatformMemAllocate(namelen);
5194 else
5195 cg->name = (domainname*)cg->namestorage;
5196 if (!cg->name)
5197 {
5198 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
5199 ReleaseCacheEntity(m, (CacheEntity*)cg);
5200 return(mDNSNULL);
5201 }
5202 AssignDomainName(cg->name, rr->name);
5203
5204 if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
5205 m->rrcache_hash[slot] = cg;
5206 if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
5207
5208 return(cg);
5209 }
5210
5211 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
5212 {
5213 mDNS_CheckLock(m);
5214
5215 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5216 // a positive answer using an expired record (e.g. from an interface that has gone away).
5217 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5218 // summary deletion without giving the proper callback to any questions that are monitoring it.
5219 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5220 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
5221 rr->UnansweredQueries = MaxUnansweredQueries;
5222 rr->resrec.rroriginalttl = 0;
5223 SetNextCacheCheckTimeForRecord(m, rr);
5224 }
5225
5226 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
5227 {
5228 mDNSs32 time;
5229 mDNSPlatformLock(m);
5230 if (m->mDNS_busy)
5231 {
5232 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5233 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
5234 }
5235
5236 if (m->timenow) time = m->timenow;
5237 else time = mDNS_TimeNow_NoLock(m);
5238 mDNSPlatformUnlock(m);
5239 return(time);
5240 }
5241
5242 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5243 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5244 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5245 #define SetSPSProxyListChanged(X) do { \
5246 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5247 m->SPSProxyListChanged = (X); } while(0)
5248
5249 // Called from mDNS_Execute() to expire stale proxy records
5250 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
5251 {
5252 m->CurrentRecord = list;
5253 while (m->CurrentRecord)
5254 {
5255 AuthRecord *rr = m->CurrentRecord;
5256 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
5257 {
5258 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5259 // so we need to cease proxying for *all* records we may have, expired or not.
5260 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
5261 {
5262 if (m->NextScheduledSPS - rr->TimeExpire > 0)
5263 m->NextScheduledSPS = rr->TimeExpire;
5264 }
5265 else // else proxy record expired, so remove it
5266 {
5267 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5268 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
5269 SetSPSProxyListChanged(rr->resrec.InterfaceID);
5270 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5271 // Don't touch rr after this -- memory may have been free'd
5272 }
5273 }
5274 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5275 // new records could have been added to the end of the list as a result of that call.
5276 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5277 m->CurrentRecord = rr->next;
5278 }
5279 }
5280
5281 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
5282 {
5283 while (m->CurrentRecord)
5284 {
5285 AuthRecord *rr = m->CurrentRecord;
5286 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
5287 {
5288 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
5289 rr->resrec.RecordType = kDNSRecordTypeShared;
5290 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
5291 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
5292 {
5293 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
5294 rr->AnsweredLocalQ = mDNSfalse;
5295 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5296 // For LocalOnly records, we don't do that and hence we need to do that here.
5297 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
5298 }
5299 }
5300 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5301 m->CurrentRecord = rr->next;
5302 }
5303 }
5304
5305 mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID)
5306 {
5307 if (m->CurrentQuestion)
5308 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
5309 DNSTypeName(m->CurrentQuestion->qtype));
5310 m->CurrentQuestion = questions;
5311 while (m->CurrentQuestion)
5312 {
5313 DNSQuestion *const q = m->CurrentQuestion;
5314 if (q->StopTime)
5315 {
5316 if (!q->TimeoutQuestion)
5317 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5318
5319 if (m->timenow - q->StopTime >= 0)
5320 {
5321 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
5322 q->LOAddressAnswers = 0; // unset since timing out the question
5323 GenerateNegativeResponse(m, InterfaceID, QC_forceresponse);
5324 if (m->CurrentQuestion == q) q->StopTime = 0;
5325 }
5326 else
5327 {
5328 if (m->NextScheduledStopTime - q->StopTime > 0)
5329 m->NextScheduledStopTime = q->StopTime;
5330 }
5331 }
5332 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5333 // We can't do this at the start of the loop because GenerateNegativeResponse
5334 // depends on having m->CurrentQuestion point to the right question
5335 if (m->CurrentQuestion == q)
5336 m->CurrentQuestion = q->next;
5337 }
5338 m->CurrentQuestion = mDNSNULL;
5339 }
5340
5341 mDNSlocal void TimeoutQuestions(mDNS *const m)
5342 {
5343 m->NextScheduledStopTime = m->timenow + FutureTime; // push reschedule of TimeoutQuestions to way off into the future
5344 TimeoutQuestions_internal(m, m->Questions, mDNSInterface_Any);
5345 TimeoutQuestions_internal(m, m->LocalOnlyQuestions, mDNSInterface_LocalOnly);
5346 }
5347
5348 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
5349 {
5350 AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
5351 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
5352 while (rrPtr)
5353 {
5354 rrNext = rrPtr->next;
5355 mDNSPlatformMemFree(rrPtr);
5356 rrPtr = rrNext;
5357 }
5358 m->SPSRRSet = mDNSNULL;
5359 }
5360
5361 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
5362 {
5363 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
5364
5365 if (m->timenow - m->NextScheduledEvent >= 0)
5366 {
5367 int i;
5368 AuthRecord *head, *tail;
5369 mDNSu32 slot;
5370 AuthGroup *ag;
5371
5372 verbosedebugf("mDNS_Execute");
5373
5374 if (m->CurrentQuestion)
5375 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5376 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5377
5378 if (m->CurrentRecord)
5379 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5380
5381 // 1. If we're past the probe suppression time, we can clear it
5382 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5383
5384 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5385 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5386
5387 // 3. Purge our cache of stale old records
5388 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5389 {
5390 mDNSu32 numchecked = 0;
5391 m->NextCacheCheck = m->timenow + FutureTime;
5392 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5393 {
5394 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5395 {
5396 CacheGroup **cp = &m->rrcache_hash[slot];
5397 m->rrcache_nextcheck[slot] = m->timenow + FutureTime;
5398 while (*cp)
5399 {
5400 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5401 numchecked++;
5402 CheckCacheExpiration(m, slot, *cp);
5403 if ((*cp)->members) cp=&(*cp)->next;
5404 else ReleaseCacheGroup(m, cp);
5405 }
5406 }
5407 // Even if we didn't need to actually check this slot yet, still need to
5408 // factor its nextcheck time into our overall NextCacheCheck value
5409 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5410 m->NextCacheCheck = m->rrcache_nextcheck[slot];
5411 }
5412 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5413 }
5414
5415 if (m->timenow - m->NextScheduledSPS >= 0)
5416 {
5417 m->NextScheduledSPS = m->timenow + FutureTime;
5418 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
5419 CheckProxyRecords(m, m->ResourceRecords);
5420 }
5421
5422 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
5423
5424 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5425 // as records could have expired during that check
5426 if (m->timenow - m->NextScheduledKA >= 0)
5427 {
5428 m->NextScheduledKA = m->timenow + FutureTime;
5429 mDNS_SendKeepalives(m);
5430 }
5431
5432 #if BONJOUR_ON_DEMAND
5433 if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0))
5434 {
5435 // Schedule immediate network change processing to leave the multicast group
5436 // since the delay time has expired since the previous active registration or query.
5437 m->NetworkChanged = m->timenow;
5438 m->NextBonjourDisableTime = 0;
5439 m->BonjourEnabled = 0;
5440
5441 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5442 }
5443 #endif // BONJOUR_ON_DEMAND
5444
5445 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5446 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5447 {
5448 m->AnnounceOwner = 0;
5449
5450 // This is a good time to reset the delay counter used to prevent spurious conflicts
5451 m->DelayConflictProcessing = 0;
5452 }
5453
5454 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5455 {
5456 m->DelaySleep = 0;
5457 if (m->SleepState == SleepState_Transferring)
5458 {
5459 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5460 BeginSleepProcessing(m);
5461 }
5462 }
5463
5464 // 4. See if we can answer any of our new local questions from the cache
5465 for (i=0; m->NewQuestions && i<1000; i++)
5466 {
5467 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5468 AnswerNewQuestion(m);
5469 }
5470 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5471
5472 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5473 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5474 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5475 {
5476 m->LocalRemoveEvents = mDNSfalse;
5477 m->CurrentRecord = m->ResourceRecords;
5478 CheckRmvEventsForLocalRecords(m);
5479 // Walk the LocalOnly records and deliver the RMV events
5480 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5481 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5482 {
5483 m->CurrentRecord = ag->members;
5484 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5485 }
5486 }
5487
5488 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5489
5490 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5491 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5492
5493 head = tail = mDNSNULL;
5494 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5495 {
5496 AuthRecord *rr = m->NewLocalRecords;
5497 m->NewLocalRecords = m->NewLocalRecords->next;
5498 if (LocalRecordReady(rr))
5499 {
5500 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5501 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
5502 }
5503 else if (!rr->next)
5504 {
5505 // If we have just one record that is not ready, we don't have to unlink and
5506 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5507 // terminate and set the NewLocalRecords to rr.
5508 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5509 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5510 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5511
5512 head = rr;
5513 }
5514 else
5515 {
5516 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
5517 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5518 // if this is the first record we are skipping, move to the end of the list.
5519 // if we have already skipped records before, append it at the end.
5520 while (*p && *p != rr) p=&(*p)->next;
5521 if (*p) *p = rr->next; // Cut this record from the list
5522 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5523 if (!head)
5524 {
5525 while (*p) p=&(*p)->next;
5526 *p = rr;
5527 head = tail = rr;
5528 }
5529 else
5530 {
5531 tail->next = rr;
5532 tail = rr;
5533 }
5534 rr->next = mDNSNULL;
5535 }
5536 }
5537 m->NewLocalRecords = head;
5538 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5539
5540 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5541
5542 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5543 // to our local questions
5544 if (m->NewLocalOnlyRecords)
5545 {
5546 m->NewLocalOnlyRecords = mDNSfalse;
5547 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5548 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5549 {
5550 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5551 {
5552 AuthRecord *rr = ag->NewLocalOnlyRecords;
5553 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5554 // LocalOnly records should always be ready as they never probe
5555 if (LocalRecordReady(rr))
5556 {
5557 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5558 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
5559 }
5560 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5561 }
5562 // We limit about 100 per AuthGroup that can be serviced at a time
5563 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5564 }
5565 }
5566
5567 // 5. See what packets we need to send
5568 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5569 DiscardDeregistrations(m);
5570 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5571 {
5572 // If the platform code is ready, and we're not suppressing packet generation right now
5573 // then send our responses, probes, and questions.
5574 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5575 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5576 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5577 // Finally, we send responses, including the previously mentioned records that just completed probing.
5578 m->SuppressSending = 0;
5579
5580 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5581 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5582 if (m->timenow - m->NextScheduledQuery >= 0)
5583 {
5584 DNSQuestion *q;
5585 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5586 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5587 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5588 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5589 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5590 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5591 }
5592 if (m->timenow - m->NextScheduledProbe >= 0)
5593 {
5594 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5595 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5596 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5597 }
5598
5599 // 7. Send Response packets, including probing records just advanced to announcing state
5600 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5601 if (m->timenow - m->NextScheduledResponse >= 0)
5602 {
5603 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5604 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5605 }
5606 }
5607
5608 // Clear RandomDelay values, ready to pick a new different value next time
5609 m->RandomQueryDelay = 0;
5610 m->RandomReconfirmDelay = 0;
5611
5612 // See if any questions (or local-only questions) have timed out
5613 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5614 #ifndef UNICAST_DISABLED
5615 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5616 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5617 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5618 #endif
5619 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5620 extern void serviceBLE();
5621 if (m->NextBLEServiceTime && (m->timenow - m->NextBLEServiceTime >= 0)) serviceBLE();
5622 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5623 }
5624
5625 // Note about multi-threaded systems:
5626 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5627 // performing mDNS API operations that change our next scheduled event time.
5628 //
5629 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5630 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5631 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5632 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5633 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5634 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5635 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5636 // without blocking. This avoids the race condition between the signal from the other thread arriving
5637 // just *before* or just *after* the main thread enters the blocking primitive.
5638 //
5639 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5640 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5641 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5642 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5643 // by the time it gets to the timer callback function).
5644
5645 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5646 return(m->NextScheduledEvent);
5647 }
5648
5649 #ifndef UNICAST_DISABLED
5650 mDNSlocal void SuspendLLQs(mDNS *m)
5651 {
5652 DNSQuestion *q;
5653 for (q = m->Questions; q; q = q->next)
5654 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5655 { q->ReqLease = 0; sendLLQRefresh(m, q); }
5656 }
5657 #endif // UNICAST_DISABLED
5658
5659 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5660 {
5661 AuthRecord *rr;
5662 AuthGroup *ag;
5663
5664 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5665 if (ag)
5666 {
5667 for (rr = ag->members; rr; rr=rr->next)
5668 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5669 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5670 {
5671 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5672 return mDNStrue;
5673 }
5674 }
5675 return mDNSfalse;
5676 }
5677
5678 // ActivateUnicastQuery() is called from three places:
5679 // 1. When a new question is created
5680 // 2. On wake from sleep
5681 // 3. When the DNS configuration changes
5682 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5683 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5684 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5685 {
5686 // For now this AutoTunnel stuff is specific to Mac OS X.
5687 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
5688 #if APPLE_OSX_mDNSResponder
5689 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
5690 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
5691 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
5692 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
5693 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
5694 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
5695
5696 if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
5697 !SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
5698 {
5699 question->NoAnswer = NoAnswer_Suspended;
5700 AddNewClientTunnel(question);
5701 return;
5702 }
5703 #endif // APPLE_OSX_mDNSResponder
5704
5705 if (!question->DuplicateOf)
5706 {
5707 debugf("ActivateUnicastQuery: %##s %s%s%s",
5708 question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
5709 question->CNAMEReferrals = 0;
5710 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5711 if (question->LongLived)
5712 {
5713 question->state = LLQ_InitialRequest;
5714 question->id = zeroOpaque64;
5715 question->servPort = zeroIPPort;
5716 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5717 }
5718 // If the question has local answers, then we don't want answers from outside
5719 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5720 {
5721 question->ThisQInterval = InitialQuestionInterval;
5722 question->LastQTime = m->timenow - question->ThisQInterval;
5723 SetNextQueryTime(m, question);
5724 }
5725 }
5726 }
5727
5728 // Caller should hold the lock
5729 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5730 CallbackBeforeStartQuery BeforeStartCallback, void *context)
5731 {
5732 DNSQuestion *q;
5733 DNSQuestion *restart = mDNSNULL;
5734
5735 mDNS_CheckLock(m);
5736
5737 // 1. Flush the cache records
5738 if (flushCacheRecords) flushCacheRecords(m);
5739
5740 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5741 // we are going to stop the question. Hence we need to deliver the RMV event before we
5742 // stop the question.
5743 //
5744 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5745 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5746 // *any* other question which could be the next one that we may process here. RestartQuestion
5747 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5748 // if the "next" question is stopped while the CurrentQuestion is stopped
5749
5750 if (m->RestartQuestion)
5751 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5752 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5753
5754 m->RestartQuestion = m->Questions;
5755 while (m->RestartQuestion)
5756 {
5757 q = m->RestartQuestion;
5758 m->RestartQuestion = q->next;
5759 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5760 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5761 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5762 // question followed by the original query that refers to this GetZoneData question, we will end up
5763 // freeing the GetZoneData question and then start the "freed" question at the end.
5764
5765 if (IsGetZoneDataQuestion(q))
5766 {
5767 DNSQuestion *refq = q->next;
5768 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5769 // debug stuff, we just try to find the referencing question and don't do much with it
5770 while (refq)
5771 {
5772 if (q == &refq->nta->question)
5773 {
5774 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5775 }
5776 refq = refq->next;
5777 }
5778 continue;
5779 }
5780
5781 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5782 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5783
5784 // If the search domains did not change, then we restart all the queries. Otherwise, only
5785 // for queries for which we "might" have appended search domains ("might" because we may
5786 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5787 if (!SearchDomainsChanged || q->AppendSearchDomains)
5788 {
5789 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5790 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5791 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5792 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5793 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5794 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5795 // for the original query using these cache entries as ADDs were never delivered using these cache
5796 // entries and hence this order is needed.
5797
5798 // If the query is suppressed, the RMV events won't be delivered
5799 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5800
5801 // SuppressQuery status does not affect questions that are answered using local records
5802 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5803
5804 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
5805 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
5806 mDNS_StopQuery_internal(m, q);
5807 // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
5808 // and then search domains should be appended. At the beginning, qnameOrig was NULL.
5809 if (q->qnameOrig)
5810 {
5811 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
5812 AssignDomainName(&q->qname, q->qnameOrig);
5813 mDNSPlatformMemFree(q->qnameOrig);
5814 q->qnameOrig = mDNSNULL;
5815 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
5816 }
5817 q->SearchListIndex = 0;
5818 q->next = restart;
5819 restart = q;
5820 }
5821 }
5822
5823 // 3. Callback before we start the query
5824 if (BeforeStartCallback) BeforeStartCallback(m, context);
5825
5826 // 4. Restart all the stopped queries
5827 while (restart)
5828 {
5829 q = restart;
5830 restart = restart->next;
5831 q->next = mDNSNULL;
5832 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5833 mDNS_StartQuery_internal(m, q);
5834 }
5835 }
5836
5837 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5838 {
5839 DNSQuestion *q;
5840
5841 #ifndef UNICAST_DISABLED
5842 // Retrigger all our uDNS questions
5843 if (m->CurrentQuestion)
5844 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5845 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5846 m->CurrentQuestion = m->Questions;
5847 while (m->CurrentQuestion)
5848 {
5849 q = m->CurrentQuestion;
5850 m->CurrentQuestion = m->CurrentQuestion->next;
5851 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
5852 }
5853 #endif
5854
5855 // Retrigger all our mDNS questions
5856 for (q = m->Questions; q; q=q->next) // Scan our list of questions
5857 mDNSCoreRestartQuestion(m, q);
5858 }
5859
5860 // restart question if it's multicast and currently active
5861 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5862 {
5863 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5864 {
5865 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
5866 q->RequestUnicast = kDefaultRequestUnicastCount;
5867 q->LastQTime = m->timenow - q->ThisQInterval;
5868 q->RecentAnswerPkts = 0;
5869 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5870 m->NextScheduledQuery = m->timenow;
5871 }
5872 }
5873
5874 // restart the probe/announce cycle for multicast record
5875 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
5876 {
5877 if (!AuthRecord_uDNS(rr))
5878 {
5879 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5880 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5881
5882 if (mDNS_KeepaliveRecord(&rr->resrec))
5883 {
5884 rr->AnnounceCount = 0; // Do not announce keepalive records
5885 }
5886 else
5887 {
5888 // announceCount < 0 indicates default announce count should be used
5889 if (announceCount < 0)
5890 announceCount = InitialAnnounceCount;
5891 if (rr->AnnounceCount < (mDNSu8)announceCount)
5892 rr->AnnounceCount = (mDNSu8)announceCount;
5893 }
5894
5895 rr->SendNSECNow = mDNSNULL;
5896 InitializeLastAPTime(m, rr);
5897 }
5898 }
5899
5900 // ***************************************************************************
5901 #if COMPILER_LIKES_PRAGMA_MARK
5902 #pragma mark -
5903 #pragma mark - Power Management (Sleep/Wake)
5904 #endif
5905
5906 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
5907 {
5908 #ifndef IDLESLEEPCONTROL_DISABLED
5909 mDNSBool allowSleep = mDNStrue;
5910 char reason[128];
5911
5912 reason[0] = 0;
5913
5914 if (m->SystemSleepOnlyIfWakeOnLAN)
5915 {
5916 // Don't sleep if we are a proxy for any services
5917 if (m->ProxyRecords)
5918 {
5919 allowSleep = mDNSfalse;
5920 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
5921 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
5922 }
5923
5924 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
5925 {
5926 // Scan the list of active interfaces
5927 NetworkInterfaceInfo *intf;
5928 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5929 {
5930 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
5931 {
5932 // Disallow sleep if this interface doesn't support NetWake
5933 if (!intf->NetWake)
5934 {
5935 allowSleep = mDNSfalse;
5936 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
5937 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
5938 break;
5939 }
5940
5941 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
5942 // that will be offloaded. If not, we should prevent sleep.
5943 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
5944 #if APPLE_OSX_mDNSResponder
5945 if (!SupportsInNICProxy(intf))
5946 #endif
5947 {
5948 // Disallow sleep if there is no sleep proxy server
5949 const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
5950 if ( cr == mDNSNULL)
5951 {
5952 allowSleep = mDNSfalse;
5953 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
5954 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
5955 break;
5956 }
5957 else if (m->SPSType != 0)
5958 {
5959 mDNSu32 mymetric = LocalSPSMetric(m);
5960 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
5961 if (metric >= mymetric)
5962 {
5963 allowSleep = mDNSfalse;
5964 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
5965 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
5966 break;
5967 }
5968 }
5969 }
5970 }
5971 }
5972 }
5973 }
5974
5975 // Call the platform code to enable/disable sleep
5976 mDNSPlatformSetAllowSleep(allowSleep, reason);
5977 #else
5978 (void) m;
5979 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
5980 }
5981
5982 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
5983 {
5984 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
5985 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
5986 // to send.
5987 if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
5988 m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
5989 {
5990 return mDNSfalse;
5991 }
5992
5993 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
5994 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
5995 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
5996 // updateid and we should have returned from above.
5997 //
5998 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
5999 // platform function to extract the value from "intf" every time.
6000
6001 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6002 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6003 return mDNStrue;
6004
6005 return mDNSfalse;
6006 }
6007
6008 mDNSexport void UpdateRMAC(mDNS *const m, void *context)
6009 {
6010 IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
6011 m->CurrentRecord = m->ResourceRecords;
6012
6013 if (!addrmap)
6014 {
6015 LogMsg("UpdateRMAC: Address mapping is NULL");
6016 return;
6017 }
6018
6019 while (m->CurrentRecord)
6020 {
6021 AuthRecord *rr = m->CurrentRecord;
6022 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6023 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
6024 {
6025 mDNSAddr raddr;
6026 getKeepaliveRaddr(m, rr, &raddr);
6027 if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
6028 {
6029 // Update the MAC address only if it is not a zero MAC address
6030 mDNSEthAddr macAddr;
6031 mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
6032 if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
6033 {
6034 UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
6035 }
6036 }
6037 }
6038 m->CurrentRecord = rr->next;
6039 }
6040
6041 if (addrmap)
6042 mDNSPlatformMemFree(addrmap);
6043
6044 }
6045
6046 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
6047 {
6048 mDNSu16 newrdlength;
6049 mDNSAddr laddr = zeroAddr;
6050 mDNSAddr raddr = zeroAddr;
6051 mDNSEthAddr eth = zeroEthAddr;
6052 mDNSIPPort lport = zeroIPPort;
6053 mDNSIPPort rport = zeroIPPort;
6054 mDNSu32 timeout = 0;
6055 mDNSu32 seq = 0;
6056 mDNSu32 ack = 0;
6057 mDNSu16 win = 0;
6058 UTF8str255 txt;
6059 int rdsize;
6060 RData *newrd;
6061 mDNSTCPInfo mti;
6062 mStatus ret;
6063
6064 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
6065 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6066 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
6067 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
6068 {
6069 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
6070 return mStatus_UnknownErr;
6071 }
6072
6073 if (updateMac)
6074 {
6075 if (laddr.type == mDNSAddrType_IPv4)
6076 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);
6077 else
6078 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);
6079
6080 }
6081 else
6082 {
6083 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6084 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6085 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6086 mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
6087 ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti);
6088 if (ret != mStatus_NoError)
6089 {
6090 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
6091 return ret;
6092 }
6093 if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
6094 {
6095 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti.IntfId, intf->InterfaceID);
6096 return mStatus_BadParamErr;
6097 }
6098
6099 if (laddr.type == mDNSAddrType_IPv4)
6100 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);
6101 else
6102 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);
6103 }
6104
6105 // Did we insert a null byte at the end ?
6106 if (newrdlength == (sizeof(txt.c) - 1))
6107 {
6108 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
6109 return mStatus_NoMemoryErr;
6110 }
6111
6112 // Include the length for the null byte at the end
6113 txt.c[0] = newrdlength + 1;
6114 // Account for the first length byte and the null byte at the end
6115 newrdlength += 2;
6116
6117 rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
6118 newrd = mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
6119 if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
6120
6121 newrd->MaxRDLength = (mDNSu16) rdsize;
6122 mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
6123
6124 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6125 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6126 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6127 // free that memory here before copying in the new data.
6128 if ( rr->resrec.rdata != &rr->rdatastorage)
6129 {
6130 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
6131 mDNSPlatformMemFree(rr->resrec.rdata);
6132 }
6133 SetNewRData(&rr->resrec, newrd, newrdlength); // Update our rdata
6134
6135 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
6136 return mStatus_NoError;
6137 }
6138
6139 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
6140 {
6141 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
6142 const int sps = intf->NextSPSAttempt / 3;
6143 AuthRecord *rr;
6144 mDNSOpaque16 msgid;
6145 mDNSu32 scopeid;
6146
6147 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6148 if (!intf->SPSAddr[sps].type)
6149 {
6150 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6151 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6152 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6153 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
6154 goto exit;
6155 }
6156
6157 // Mark our mDNS records (not unicast records) for transfer to SPS
6158 if (mDNSOpaque16IsZero(id))
6159 {
6160 // We may have to register this record over multiple interfaces and we don't want to
6161 // overwrite the id. We send the registration over interface X with id "IDX" and before
6162 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6163 // for "IDX". Hence, we want to use the same ID across all interfaces.
6164 //
6165 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6166 // option check below will set the same ID across the records from the same owner. Records
6167 // with different owner option gets different ID.
6168 msgid = mDNS_NewMessageID(m);
6169 for (rr = m->ResourceRecords; rr; rr=rr->next)
6170 {
6171 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
6172 {
6173 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
6174 {
6175 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6176 {
6177 rr->SendRNow = mDNSInterfaceMark; // mark it now
6178 // When we are registering on the first interface, rr->updateid is zero in which case
6179 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6180 // At the end, all the updates sent across all the interfaces with the same ID.
6181 if (mDNSOpaque16IsZero(rr->updateid))
6182 rr->updateid = msgid;
6183 else
6184 msgid = rr->updateid;
6185 }
6186 }
6187 }
6188 }
6189 }
6190 else
6191 msgid = id;
6192
6193 while (1)
6194 {
6195 mDNSu8 *p = m->omsg.data;
6196 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6197 // For now we follow that same logic for SPS registrations too.
6198 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6199 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6200 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
6201
6202 for (rr = m->ResourceRecords; rr; rr=rr->next)
6203 if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
6204 {
6205 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6206 {
6207 mDNSu8 *newptr;
6208 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
6209
6210 // If we can't update the keepalive record, don't send it
6211 if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
6212 {
6213 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
6214 {
6215 bit_clr_opaque64(rr->updateIntID, scopeid);
6216 }
6217 rr->SendRNow = mDNSNULL;
6218 continue;
6219 }
6220
6221 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
6222 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6223 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
6224 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
6225 if (!newptr)
6226 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
6227 else
6228 {
6229 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));
6230 rr->SendRNow = mDNSNULL;
6231 rr->ThisAPInterval = mDNSPlatformOneSecond;
6232 rr->LastAPTime = m->timenow;
6233 // should be initialized above
6234 if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
6235 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6236 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
6237 p = newptr;
6238 }
6239 }
6240 }
6241
6242 if (!m->omsg.h.mDNS_numUpdates) break;
6243 else
6244 {
6245 AuthRecord opt;
6246 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
6247 opt.resrec.rrclass = NormalMaxDNSMessageData;
6248 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
6249 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
6250 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
6251 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
6252 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
6253 if (!owner->HMAC.l[0]) // If no owner data,
6254 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information
6255 else // otherwise, use the owner data we were given
6256 {
6257 opt.resrec.rdata->u.opt[1].u.owner = *owner;
6258 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner;
6259 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
6260 }
6261 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
6262 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
6263 if (!p)
6264 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
6265 else
6266 {
6267 mStatus err;
6268
6269 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
6270 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
6271 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6272 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL, mDNSfalse);
6273 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
6274 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
6275 {
6276 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
6277 intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
6278 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
6279 return;
6280 }
6281 }
6282 }
6283 }
6284
6285 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
6286
6287 exit:
6288 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
6289 }
6290
6291 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
6292 {
6293 AuthRecord *ar;
6294 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
6295 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
6296 return mDNStrue;
6297 }
6298
6299 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
6300 {
6301 AuthRecord *newRR = mDNSPlatformMemAllocate(sizeof(AuthRecord));
6302
6303 if (newRR == mDNSNULL)
6304 {
6305 LogSPS("%s : could not allocate memory for new resource record", __func__);
6306 return;
6307 }
6308
6309 mDNSPlatformMemZero(newRR, sizeof(AuthRecord));
6310 mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
6311 rr->resrec.rroriginalttl, rr->resrec.RecordType,
6312 rr->ARType, mDNSNULL, mDNSNULL);
6313
6314 AssignDomainName(&newRR->namestorage, &rr->namestorage);
6315 newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
6316 newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
6317 newRR->resrec.rrclass = rr->resrec.rrclass;
6318
6319 if (rr->resrec.rrtype == kDNSType_A)
6320 {
6321 newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4;
6322 }
6323 else if (rr->resrec.rrtype == kDNSType_AAAA)
6324 {
6325 newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
6326 }
6327 SetNewRData(&newRR->resrec, mDNSNULL, 0);
6328
6329 // Insert the new node at the head of the list.
6330 newRR->next = m->SPSRRSet;
6331 m->SPSRRSet = newRR;
6332 LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
6333 }
6334
6335 // Some records are interface specific and some are not. The ones that are supposed to be registered
6336 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6337 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6338 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6339 // registration on all the interfaces
6340 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
6341 {
6342 AuthRecord *ar;
6343 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
6344
6345 *WakeOnlyService = mDNSfalse;
6346
6347 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6348 // make sure that the old sleep proxy records are removed.
6349 mDNSCoreFreeProxyRR(m);
6350
6351 // For records that are registered only on a specific interface, mark only that bit as it will
6352 // never be registered on any other interface. For others, it should be sent on all interfaces.
6353 for (ar = m->ResourceRecords; ar; ar=ar->next)
6354 {
6355 ar->updateIntID = zeroOpaque64;
6356 ar->updateid = zeroID;
6357 if (AuthRecord_uDNS(ar))
6358 {
6359 continue;
6360 }
6361 if (ar->AuthFlags & AuthFlagsWakeOnly)
6362 {
6363 if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
6364 {
6365 ar->ImmedAnswer = mDNSInterfaceMark;
6366 *WakeOnlyService = mDNStrue;
6367 continue;
6368 }
6369 }
6370 if (!ar->resrec.InterfaceID)
6371 {
6372 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
6373 ar->updateIntID = updateIntID;
6374 }
6375 else
6376 {
6377 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6378 // exactly this.
6379 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
6380 if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
6381 {
6382 bit_set_opaque64(ar->updateIntID, scopeid);
6383 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
6384 ar->updateIntID.l[0], ARDisplayString(m, ar));
6385 }
6386 else
6387 {
6388 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
6389 }
6390 }
6391 // Store the A and AAAA records that we registered with the sleep proxy.
6392 // We will use this to prevent spurious name conflicts that may occur when we wake up
6393 if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
6394 {
6395 mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
6396 }
6397 }
6398 }
6399
6400 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
6401 {
6402 AuthRecord *ar;
6403 OwnerOptData owner = zeroOwner;
6404
6405 SendSPSRegistrationForOwner(m, intf, id, &owner);
6406
6407 for (ar = m->ResourceRecords; ar; ar=ar->next)
6408 {
6409 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6410 {
6411 owner = ar->WakeUp;
6412 SendSPSRegistrationForOwner(m, intf, id, &owner);
6413 }
6414 }
6415 }
6416
6417 // RetrySPSRegistrations is called from SendResponses, with the lock held
6418 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6419 {
6420 AuthRecord *rr;
6421 NetworkInterfaceInfo *intf;
6422
6423 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6424 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6425 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6426 intf->NextSPSAttemptTime++;
6427
6428 // Retry any record registrations that are due
6429 for (rr = m->ResourceRecords; rr; rr=rr->next)
6430 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6431 {
6432 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6433 {
6434 // If we still have registrations pending on this interface, send it now
6435 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6436 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6437 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6438 {
6439 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6440 SendSPSRegistration(m, intf, rr->updateid);
6441 }
6442 }
6443 }
6444
6445 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6446 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6447 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6448 intf->NextSPSAttempt++;
6449 }
6450
6451 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6452 {
6453 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6454 int sps = (int)(question - intf->NetWakeResolve);
6455 (void)m; // Unused
6456 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6457
6458 if (!AddRecord) return; // Don't care about REMOVE events
6459 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
6460
6461 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6462
6463 if (answer->rrtype == kDNSType_SRV)
6464 {
6465 // 1. Got the SRV record; now look up the target host's IP address
6466 mDNS_StopQuery(m, question);
6467 intf->SPSPort[sps] = answer->rdata->u.srv.port;
6468 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6469 question->qtype = kDNSType_A;
6470 mDNS_StartQuery(m, question);
6471 }
6472 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6473 {
6474 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6475 mDNS_StopQuery(m, question);
6476 question->ThisQInterval = -1;
6477 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6478 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6479 mDNS_Lock(m);
6480 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6481 mDNS_Unlock(m);
6482 }
6483 else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6484 {
6485 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6486 mDNS_StopQuery(m, question);
6487 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6488 question->qtype = kDNSType_AAAA;
6489 mDNS_StartQuery(m, question);
6490 }
6491 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6492 {
6493 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6494 mDNS_StopQuery(m, question);
6495 question->ThisQInterval = -1;
6496 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6497 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6498 mDNS_Lock(m);
6499 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6500 mDNS_Unlock(m);
6501 }
6502 }
6503
6504 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6505 {
6506 AuthRecord *rr;
6507 for (rr = m->ResourceRecords; rr; rr=rr->next)
6508 if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6509 return mDNStrue;
6510 return mDNSfalse;
6511 }
6512
6513 #define WAKE_ONLY_SERVICE 1
6514 #define AC_ONLY_SERVICE 2
6515
6516 #ifdef APPLE_OSX_mDNSResponder
6517 mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
6518 {
6519 AuthRecord *rr;
6520 *servicePresent = mDNSfalse;
6521
6522 // Mark all the records we need to deregister and send them
6523 for (rr = m->ResourceRecords; rr; rr=rr->next)
6524 {
6525 // If the service type is wake only service and the auth flags match and requires a goodbye
6526 // OR if the service type is AC only and it is not a keepalive record,
6527 // mark the records we need to deregister and send them
6528 if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
6529 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
6530 (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
6531 {
6532 rr->ImmedAnswer = mDNSInterfaceMark;
6533 *servicePresent = mDNStrue;
6534 }
6535 }
6536 }
6537 #endif
6538
6539 #ifdef APPLE_OSX_mDNSResponder
6540 // This function is used only in the case of local NIC proxy. For external
6541 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6542 // walk the resource records.
6543 mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6544 {
6545 return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
6546 }
6547 #endif // APPLE_OSX_mDNSResponder
6548
6549
6550 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6551 {
6552 AuthRecord *rr;
6553 m->SleepState = SleepState_Sleeping;
6554
6555 // If AllInterfaces is not set, the caller has already marked it appropriately
6556 // on which interfaces this should be sent.
6557 if (AllInterfaces)
6558 {
6559 NetworkInterfaceInfo *intf;
6560 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6561 {
6562 intf->SendGoodbyes = 1;
6563 }
6564 }
6565 if (unicast)
6566 {
6567 #ifndef UNICAST_DISABLED
6568 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
6569 #endif /* UNICAST_DISABLED */
6570 }
6571
6572 // Mark all the records we need to deregister and send them
6573 for (rr = m->ResourceRecords; rr; rr=rr->next)
6574 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6575 rr->ImmedAnswer = mDNSInterfaceMark;
6576 SendResponses(m);
6577 }
6578
6579 /*
6580 * This function attempts to detect if multiple interfaces are on the same subnet.
6581 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6582 * IPv6 link local addresses that are configured by default on all interfaces make
6583 * it hard to make this determination
6584 *
6585 * The 'real' fix for this would be to send out multicast packets over one interface
6586 * and conclude that multiple interfaces are on the same subnet only if these packets
6587 * are seen on other interfaces on the same system
6588 */
6589 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6590 {
6591 NetworkInterfaceInfo *intf;
6592 NetworkInterfaceInfo *newIntf;
6593 mDNSu32 i;
6594
6595 for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6596 {
6597 if ((newIntf->InterfaceID != intfid) ||
6598 (newIntf->ip.type != mDNSAddrType_IPv4))
6599 {
6600 continue;
6601 }
6602 for ( i = 0; i < count; i++)
6603 {
6604 for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6605 {
6606 if ((intf->InterfaceID != regID[i]) ||
6607 (intf->ip.type != mDNSAddrType_IPv4))
6608 {
6609 continue;
6610 }
6611 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6612 {
6613 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6614 return (mDNStrue);
6615 }
6616 }
6617 }
6618 }
6619 return (mDNSfalse);
6620 }
6621
6622 mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6623 {
6624 // Loop through the keepalive records and callback with an error
6625 m->CurrentRecord = m->ResourceRecords;
6626 while (m->CurrentRecord)
6627 {
6628 AuthRecord *const rr = m->CurrentRecord;
6629 if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6630 {
6631 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6632 if (rr->RecordCallback)
6633 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6634 }
6635 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6636 m->CurrentRecord = rr->next;
6637 }
6638 }
6639
6640 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6641 mDNSlocal void BeginSleepProcessing(mDNS *const m)
6642 {
6643 mDNSBool SendGoodbyes = mDNStrue;
6644 mDNSBool WakeOnlyService = mDNSfalse;
6645 mDNSBool invokeKACallback = mDNStrue;
6646 const CacheRecord *sps[3] = { mDNSNULL };
6647 mDNSOpaque64 updateIntID = zeroOpaque64;
6648 mDNSInterfaceID registeredIntfIDS[128] = { 0 };
6649 mDNSu32 registeredCount = 0;
6650 int skippedRegistrations = 0;
6651
6652 m->NextScheduledSPRetry = m->timenow;
6653
6654 // Clear out the SCDynamic entry that stores the external SPS information
6655 mDNSPlatformClearSPSData();
6656
6657 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6658 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6659 else // If we have at least one advertised service
6660 {
6661 NetworkInterfaceInfo *intf;
6662 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6663 {
6664 mDNSBool skipFullSleepProxyRegistration = mDNSfalse;
6665 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6666 intf->SendGoodbyes = 0;
6667
6668 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6669 // servers.
6670 if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6671 {
6672 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6673 continue;
6674 }
6675
6676 // If we are not capable of WOMP, then don't register with sleep proxy.
6677 //
6678 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6679 // We might find sleep proxy servers in the cache and start a resolve on them.
6680 // But then if the interface goes away, we won't stop these questions because
6681 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6682 // to stop both the browse and resolve questions.
6683 if (!intf->NetWake)
6684 {
6685 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6686 intf->SendGoodbyes = 1;
6687 skippedRegistrations++;
6688 continue;
6689 }
6690
6691 // Check if we have already registered with a sleep proxy for this subnet.
6692 // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
6693 // to the interface.
6694 if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6695 {
6696 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__, intf->ifname);
6697 skipFullSleepProxyRegistration = mDNStrue;
6698 }
6699
6700 #if APPLE_OSX_mDNSResponder
6701 if (SupportsInNICProxy(intf))
6702 {
6703 mDNSBool keepaliveOnly = mDNSfalse;
6704 const mStatus err = ActivateLocalProxy(intf, skipFullSleepProxyRegistration, &keepaliveOnly);
6705 if (!skipFullSleepProxyRegistration && !err)
6706 {
6707 SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6708
6709 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6710 SendGoodbyes = (keepaliveOnly) ? mDNStrue: mDNSfalse;
6711 invokeKACallback = mDNSfalse;
6712 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6713 // This will leave m->SleepState set to SleepState_Transferring,
6714 // which is okay because with no outstanding resolves, or updates in flight,
6715 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6716
6717 // Setting this flag activates the SleepLimit which delays sleep by 5 seconds and
6718 // will allow the system to deregister any BTMM records.
6719 m->NextScheduledSPRetry = m->timenow + (5 * mDNSPlatformOneSecond);
6720 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6721 registeredCount++;
6722 }
6723 continue;
6724 }
6725 #endif // APPLE_OSX_mDNSResponder
6726 if (!skipFullSleepProxyRegistration)
6727 {
6728 #if APPLE_OSX_mDNSResponder
6729 // If on battery, do not attempt to offload to external sleep proxies
6730 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6731 {
6732 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6733 return;
6734 }
6735 #endif // APPLE_OSX_mDNSResponder
6736 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6737 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6738 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6739 else
6740 {
6741 int i;
6742 mDNSu32 scopeid;
6743 SendGoodbyes = mDNSfalse;
6744 intf->NextSPSAttempt = 0;
6745 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6746
6747 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6748 // Now we know for sure that we have to wait for registration to complete on this interface.
6749 if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6750 bit_set_opaque64(updateIntID, scopeid);
6751
6752 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6753 for (i=0; i<3; i++)
6754 {
6755 #if ForceAlerts
6756 if (intf->SPSAddr[i].type)
6757 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
6758 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6759 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
6760 #endif
6761 intf->SPSAddr[i].type = mDNSAddrType_None;
6762 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6763 intf->NetWakeResolve[i].ThisQInterval = -1;
6764 if (sps[i])
6765 {
6766 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6767 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6768 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6769 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6770
6771 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6772 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6773 registeredCount++;
6774 }
6775 }
6776 }
6777 }
6778 }
6779 }
6780
6781 // If we have at least one interface on which we are registering with an external sleep proxy,
6782 // initialize all the records appropriately.
6783 if (!mDNSOpaque64IsZero(&updateIntID))
6784 SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6785
6786 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6787 // the records to a sleep proxy.
6788 if (invokeKACallback)
6789 {
6790 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6791 DoKeepaliveCallbacks(m);
6792 }
6793
6794 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6795 // interfaces and also deregister unicast registrations.
6796 //
6797 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6798 // for both multicast and unicast.
6799 //
6800 // - If we skipped registrations on some interfaces, then we have already marked
6801 // them appropriately above. We don't need to send goodbyes for unicast as
6802 // we have registered with at least one sleep proxy.
6803 //
6804 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6805 //
6806 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6807 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6808 // at WakeOnlyServices first.
6809 if (SendGoodbyes)
6810 {
6811 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6812 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6813 }
6814 else if (skippedRegistrations)
6815 {
6816 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6817 SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6818 }
6819 else if (WakeOnlyService)
6820 {
6821 // If we saw WakeOnly service above, send the goodbyes now.
6822 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6823 SendResponses(m);
6824 }
6825 }
6826
6827 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6828 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6829 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6830 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6831 {
6832 AuthRecord *rr;
6833
6834 LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6835
6836 if (sleep && !m->SleepState) // Going to sleep
6837 {
6838 mDNS_Lock(m);
6839 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6840 if (m->SPSSocket)
6841 {
6842 mDNSu8 oldstate = m->SPSState;
6843 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6844 m->SPSState = 2;
6845 #ifndef SPC_DISABLED
6846 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6847 #else
6848 (void)oldstate;
6849 #endif
6850 mDNS_ReclaimLockAfterCallback();
6851 }
6852 #ifdef _LEGACY_NAT_TRAVERSAL_
6853 if (m->SSDPSocket)
6854 {
6855 mDNSPlatformUDPClose(m->SSDPSocket);
6856 m->SSDPSocket = mDNSNULL;
6857 }
6858 #endif
6859 m->SleepState = SleepState_Transferring;
6860 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6861 {
6862 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6863 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6864 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6865 }
6866 else
6867 {
6868 m->DelaySleep = 0;
6869 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6870 m->mDNSStats.Sleeps++;
6871 BeginSleepProcessing(m);
6872 }
6873
6874 #ifndef UNICAST_DISABLED
6875 SuspendLLQs(m);
6876 #endif
6877 #if APPLE_OSX_mDNSResponder
6878 RemoveAutoTunnel6Record(m);
6879 #endif
6880 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
6881 m->SleepState == SleepState_Transferring ? "Transferring" :
6882 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
6883 mDNS_Unlock(m);
6884 }
6885 else if (!sleep) // Waking up
6886 {
6887 mDNSu32 slot;
6888 CacheGroup *cg;
6889 CacheRecord *cr;
6890 NetworkInterfaceInfo *intf;
6891 mDNSs32 currtime, diff;
6892
6893 mDNS_Lock(m);
6894 // Reset SleepLimit back to 0 now that we're awake again.
6895 m->SleepLimit = 0;
6896
6897 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6898 if (m->SleepState != SleepState_Awake)
6899 {
6900 m->SleepState = SleepState_Awake;
6901 m->SleepSeqNum++;
6902 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6903 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6904 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6905 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6906 m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep);
6907 }
6908
6909 if (m->SPSState == 3)
6910 {
6911 m->SPSState = 0;
6912 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
6913 }
6914 m->mDNSStats.Wakes++;
6915 m->DelayConflictProcessing = MAX_CONFLICT_PROCESSING_DELAYS;
6916 // ... and the same for NextSPSAttempt
6917 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
6918
6919 // Restart unicast and multicast queries
6920 mDNSCoreRestartQueries(m);
6921
6922 // and reactivtate service registrations
6923 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
6924 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
6925
6926 // 2. Re-validate our cache records
6927 currtime = mDNSPlatformUTC();
6928
6929 diff = currtime - m->TimeSlept;
6930 FORALL_CACHERECORDS(slot, cg, cr)
6931 {
6932 // Temporary fix: For unicast cache records, look at how much time we slept.
6933 // Adjust the RecvTime by the amount of time we slept so that we age the
6934 // cache record appropriately. If it is expired already, purge. If there
6935 // is a network change that happens after the wakeup, we might purge the
6936 // cache anyways and this helps only in the case where there are no network
6937 // changes across sleep/wakeup transition.
6938 //
6939 // Note: If there is a network/DNS server change that already happened and
6940 // these cache entries are already refreshed and we are getting a delayed
6941 // wake up notification, we might adjust the TimeRcvd based on the time slept
6942 // now which can cause the cache to purge pre-maturely. As this is not a very
6943 // common case, this should happen rarely.
6944 if (!cr->resrec.InterfaceID)
6945 {
6946 if (diff > 0)
6947 {
6948 mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
6949 const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
6950
6951 // -if we have slept longer than the remaining TTL, purge and start fresh.
6952 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6953 // a sufficiently big value which could cause the value to go into the future
6954 // because of the signed comparison of time. For this to happen, we should have been
6955 // sleeping really long (~24 days). For now, we want to be conservative and flush even
6956 // if we have slept for more than two days.
6957
6958 if (diff >= remain || diff > (2 * 24 * 3600))
6959 {
6960 LogInfo("mDNSCoreMachineSleep: %s: Purging cache entry SleptTime %d, Remaining TTL %d",
6961 CRDisplayString(m, cr), diff, remain);
6962 mDNS_PurgeCacheResourceRecord(m, cr);
6963 continue;
6964 }
6965 cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
6966 if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
6967 {
6968 LogInfo("mDNSCoreMachineSleep: %s: Purging after adjusting the remaining TTL %d by %d seconds",
6969 CRDisplayString(m, cr), remain, diff);
6970 mDNS_PurgeCacheResourceRecord(m, cr);
6971 }
6972 else
6973 {
6974 LogInfo("mDNSCoreMachineSleep: %s: Adjusted the remain ttl %u by %d seconds", CRDisplayString(m, cr), remain, diff);
6975 }
6976 }
6977 }
6978 else
6979 {
6980 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
6981 }
6982 }
6983
6984 // 3. Retrigger probing and announcing for all our authoritative records
6985 for (rr = m->ResourceRecords; rr; rr=rr->next)
6986 {
6987 if (AuthRecord_uDNS(rr))
6988 {
6989 ActivateUnicastRegistration(m, rr);
6990 }
6991 else
6992 {
6993 mDNSCoreRestartRegistration(m, rr, -1);
6994 }
6995 }
6996
6997 // 4. Refresh NAT mappings
6998 // We don't want to have to assume that all hardware can necessarily keep accurate
6999 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7000 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7001 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7002 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7003 // than five seconds from now.
7004 LogInfo("mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7005 RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
7006 mDNS_Unlock(m);
7007 }
7008 }
7009
7010 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
7011 {
7012 DNSQuestion *q;
7013 AuthRecord *rr;
7014 NetworkInterfaceInfo *intf;
7015
7016 mDNS_Lock(m);
7017
7018 if (m->DelaySleep) goto notready;
7019
7020 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7021 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
7022
7023 m->NextScheduledSPRetry = now + 0x40000000UL;
7024
7025 // See if we might need to retransmit any lost Sleep Proxy Registrations
7026 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7027 if (intf->NextSPSAttempt >= 0)
7028 {
7029 if (now - intf->NextSPSAttemptTime >= 0)
7030 {
7031 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7032 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
7033 SendSPSRegistration(m, intf, zeroID);
7034 // Don't need to "goto notready" here, because if we do still have record registrations
7035 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7036 }
7037 else
7038 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
7039 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
7040 }
7041
7042 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7043 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7044 {
7045 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
7046 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
7047 {
7048 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7049 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
7050 goto spsnotready;
7051 }
7052 }
7053
7054 // Scan list of registered records
7055 for (rr = m->ResourceRecords; rr; rr = rr->next)
7056 if (!AuthRecord_uDNS(rr))
7057 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7058 { 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; }
7059
7060 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7061 for (q = m->Questions; q; q = q->next)
7062 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
7063 {
7064 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7065 goto notready;
7066 }
7067
7068 // Scan list of registered records
7069 for (rr = m->ResourceRecords; rr; rr = rr->next)
7070 if (AuthRecord_uDNS(rr))
7071 {
7072 if (rr->state == regState_Refresh && rr->tcp)
7073 { 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; }
7074 #if APPLE_OSX_mDNSResponder
7075 if (!RecordReadyForSleep(rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
7076 #endif
7077 }
7078
7079 mDNS_Unlock(m);
7080 return mDNStrue;
7081
7082 spsnotready:
7083
7084 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7085 // and allow up to ten seconds more to complete wide-area deregistration instead
7086 if (now - m->SleepLimit >= 0)
7087 {
7088 LogMsg("Failed to register with SPS, now sending goodbyes");
7089
7090 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7091 if (intf->NetWakeBrowse.ThisQInterval >= 0)
7092 {
7093 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7094 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
7095 mDNS_DeactivateNetWake_internal(m, intf);
7096 }
7097
7098 for (rr = m->ResourceRecords; rr; rr = rr->next)
7099 if (!AuthRecord_uDNS(rr))
7100 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7101 {
7102 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));
7103 rr->updateIntID = zeroOpaque64;
7104 }
7105
7106 // We'd really like to allow up to ten seconds more here,
7107 // but if we don't respond to the sleep notification within 30 seconds
7108 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7109 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7110 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7111 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7112 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
7113
7114 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
7115 }
7116
7117 notready:
7118 mDNS_Unlock(m);
7119 return mDNSfalse;
7120 }
7121
7122 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
7123 {
7124 AuthRecord *ar;
7125
7126 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7127 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7128 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7129 // and if that happens we don't want to just give up and go back to sleep and never try again.
7130 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
7131
7132 NATTraversalInfo *nat;
7133 for (nat = m->NATTraversals; nat; nat=nat->next)
7134 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
7135 {
7136 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
7137 if (e - t > 0) e = t;
7138 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7139 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
7140 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
7141 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
7142 nat->retryInterval / mDNSPlatformOneSecond,
7143 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
7144 (t - now) / mDNSPlatformOneSecond);
7145 }
7146
7147 // This loop checks both the time we need to renew wide-area registrations,
7148 // and the time we need to renew Sleep Proxy registrations
7149 for (ar = m->ResourceRecords; ar; ar = ar->next)
7150 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
7151 {
7152 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
7153 if (e - t > 0) e = t;
7154 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7155 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
7156 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
7157 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
7158 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
7159 }
7160
7161 return(e - now);
7162 }
7163
7164 // ***************************************************************************
7165 #if COMPILER_LIKES_PRAGMA_MARK
7166 #pragma mark -
7167 #pragma mark - Packet Reception Functions
7168 #endif
7169
7170 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7171
7172 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
7173 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
7174 {
7175 mDNSu8 *responseptr = response->data;
7176 const mDNSu8 *const limit = response->data + sizeof(response->data);
7177 const mDNSu8 *ptr = query->data;
7178 AuthRecord *rr;
7179 mDNSu32 maxttl = mDNSMaximumTTLSeconds;
7180 int i;
7181
7182 // Initialize the response fields so we can answer the questions
7183 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
7184
7185 // ***
7186 // *** 1. Write out the list of questions we are actually going to answer with this packet
7187 // ***
7188 if (LegacyQuery)
7189 {
7190 maxttl = kStaticCacheTTL;
7191 for (i=0; i<query->h.numQuestions; i++) // For each question...
7192 {
7193 DNSQuestion q;
7194 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
7195 if (!ptr) return(mDNSNULL);
7196
7197 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
7198 {
7199 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
7200 { // then put the question in the question section
7201 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
7202 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
7203 break; // break out of the ResponseRecords loop, and go on to the next question
7204 }
7205 }
7206 }
7207
7208 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
7209 }
7210
7211 // ***
7212 // *** 2. Write Answers
7213 // ***
7214 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7215 if (rr->NR_AnswerTo)
7216 {
7217 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
7218 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7219 if (p) responseptr = p;
7220 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
7221 }
7222
7223 // ***
7224 // *** 3. Write Additionals
7225 // ***
7226 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7227 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
7228 {
7229 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
7230 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7231 if (p) responseptr = p;
7232 else debugf("GenerateUnicastResponse: No more space for additionals");
7233 }
7234
7235 return(responseptr);
7236 }
7237
7238 // AuthRecord *our is our Resource Record
7239 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7240 // Returns 0 if there is no conflict
7241 // Returns +1 if there was a conflict and we won
7242 // Returns -1 if there was a conflict and we lost and have to rename
7243 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
7244 {
7245 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
7246 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
7247 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7248 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7249
7250 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
7251 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
7252 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
7253 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
7254
7255 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
7256 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
7257 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
7258 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
7259
7260 LogMsg("CompareRData ERROR: Invalid state");
7261 return(-1);
7262 }
7263
7264 // See if we have an authoritative record that's identical to this packet record,
7265 // whose canonical DependentOn record is the specified master record.
7266 // The DependentOn pointer is typically used for the TXT record of service registrations
7267 // It indicates that there is no inherent conflict detection for the TXT record
7268 // -- it depends on the SRV record to resolve name conflicts
7269 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7270 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7271 // If the record has no DependentOn, then just return that record's pointer
7272 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7273 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
7274 {
7275 const AuthRecord *r1;
7276 for (r1 = m->ResourceRecords; r1; r1=r1->next)
7277 {
7278 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
7279 {
7280 const AuthRecord *r2 = r1;
7281 while (r2->DependentOn) r2 = r2->DependentOn;
7282 if (r2 == master) return(mDNStrue);
7283 }
7284 }
7285 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
7286 {
7287 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
7288 {
7289 const AuthRecord *r2 = r1;
7290 while (r2->DependentOn) r2 = r2->DependentOn;
7291 if (r2 == master) return(mDNStrue);
7292 }
7293 }
7294 return(mDNSfalse);
7295 }
7296
7297 // Find the canonical RRSet pointer for this RR received in a packet.
7298 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7299 // pointers (if any) to make sure we return the canonical member of this name/type/class
7300 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7301 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
7302 {
7303 const AuthRecord *rr;
7304 for (rr = m->ResourceRecords; rr; rr=rr->next)
7305 {
7306 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7307 {
7308 while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
7309 return(rr);
7310 }
7311 }
7312 return(mDNSNULL);
7313 }
7314
7315 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7316 // as one of our records (our) but different rdata.
7317 // 1. If our record is not a type that's supposed to be unique, we don't care.
7318 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7319 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7320 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7321 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7322 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7323 // are members of the same RRSet, then this is not a conflict.
7324 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
7325 {
7326 // If not supposed to be unique, not a conflict
7327 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
7328
7329 // If a dependent record, not a conflict
7330 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
7331 else
7332 {
7333 // If the pktrr matches a member of ourset, not a conflict
7334 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
7335 const AuthRecord *pktset = FindRRSet(m, pktrr);
7336 if (pktset == ourset) return(mDNSfalse);
7337
7338 // For records we're proxying, where we don't know the full
7339 // relationship between the records, having any matching record
7340 // in our AuthRecords list is sufficient evidence of non-conflict
7341 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
7342 }
7343
7344 // Okay, this is a conflict
7345 return(mDNStrue);
7346 }
7347
7348 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7349 // the record list and/or question list.
7350 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7351 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7352 DNSQuestion *q, AuthRecord *our)
7353 {
7354 int i;
7355 const mDNSu8 *ptr = LocateAuthorities(query, end);
7356 mDNSBool FoundUpdate = mDNSfalse;
7357
7358 for (i = 0; i < query->h.numAuthorities; i++)
7359 {
7360 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7361 if (!ptr) break;
7362 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
7363 {
7364 FoundUpdate = mDNStrue;
7365 if (PacketRRConflict(m, our, &m->rec.r))
7366 {
7367 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
7368 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
7369 if (!result) result = CompareRData(our, &m->rec.r);
7370 if (result)
7371 {
7372 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
7373 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7374 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
7375 }
7376 // 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.
7377 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7378 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7379 if (result < 0)
7380 {
7381 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7382 our->ProbeCount = DefaultProbeCountForTypeUnique;
7383 our->AnnounceCount = InitialAnnounceCount;
7384 InitializeLastAPTime(m, our);
7385 goto exit;
7386 }
7387 }
7388 #if 0
7389 else
7390 {
7391 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7392 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
7393 }
7394 #endif
7395 }
7396 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7397 }
7398 if (!FoundUpdate)
7399 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
7400 exit:
7401 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7402 }
7403
7404 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
7405 {
7406 CacheGroup *cg = CacheGroupForRecord(m, pktrr);
7407 CacheRecord *rr;
7408 mDNSBool match;
7409 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7410 {
7411 if (!pktrr->InterfaceID)
7412 {
7413 mDNSu16 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
7414 mDNSu16 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7415 match = (id1 == id2);
7416 }
7417 else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
7418
7419 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
7420 }
7421 return(rr);
7422 }
7423 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
7424 {
7425 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7426 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
7427 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7428 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7429 }
7430
7431 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
7432 {
7433 if (m->CurrentRecord)
7434 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7435 m->CurrentRecord = thelist;
7436
7437 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7438 // clean up the keepalive record.
7439 while (m->CurrentRecord)
7440 {
7441 AuthRecord *const rr = m->CurrentRecord;
7442 if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7443 {
7444 if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7445 {
7446 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7447 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7448 DeregisterProxyRecord(m, rr);
7449 }
7450 }
7451 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7452 // new records could have been added to the end of the list as a result of that call.
7453 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7454 m->CurrentRecord = rr->next;
7455 }
7456 }
7457
7458 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7459 // to check our lists and discard any stale duplicates of this record we already have
7460 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7461 {
7462 if (m->CurrentRecord)
7463 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7464 m->CurrentRecord = thelist;
7465 while (m->CurrentRecord)
7466 {
7467 AuthRecord *const rr = m->CurrentRecord;
7468 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7469 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7470 {
7471 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7472 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7473 DeregisterProxyRecord(m, rr);
7474 }
7475 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7476 // new records could have been added to the end of the list as a result of that call.
7477 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7478 m->CurrentRecord = rr->next;
7479 }
7480 }
7481
7482 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7483 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7484 {
7485 if (m->CurrentRecord)
7486 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7487 m->CurrentRecord = thelist;
7488 while (m->CurrentRecord)
7489 {
7490 AuthRecord *const rr = m->CurrentRecord;
7491 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7492 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7493 {
7494 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7495 {
7496 // We don't do this here because we know that the host is waking up at this point, so we don't send
7497 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7498 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7499 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7500 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7501 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7502 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7503 #endif
7504 }
7505 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7506 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7507 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7508 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7509 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7510 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7511 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7512 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7513 }
7514 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7515 // new records could have been added to the end of the list as a result of that call.
7516 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7517 m->CurrentRecord = rr->next;
7518 }
7519 }
7520
7521 // ProcessQuery examines a received query to see if we have any answers to give
7522 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7523 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7524 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7525 {
7526 mDNSBool FromLocalSubnet = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7527 AuthRecord *ResponseRecords = mDNSNULL;
7528 AuthRecord **nrp = &ResponseRecords;
7529
7530 #if POOF_ENABLED
7531 mDNSBool notD2D = !mDNSPlatformInterfaceIsD2D(InterfaceID); // We don't run the POOF algorithm on D2D interfaces.
7532 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
7533 CacheRecord **eap = &ExpectedAnswers;
7534 #endif // POOF_ENABLED
7535
7536 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
7537 DNSQuestion **dqp = &DupQuestions;
7538 mDNSs32 delayresponse = 0;
7539 mDNSBool SendLegacyResponse = mDNSfalse;
7540 const mDNSu8 *ptr;
7541 mDNSu8 *responseptr = mDNSNULL;
7542 AuthRecord *rr;
7543 int i;
7544 CacheRecord *McastNSEC3Records = mDNSNULL;
7545
7546 // ***
7547 // *** 1. Look in Additional Section for an OPT record
7548 // ***
7549 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7550 if (ptr)
7551 {
7552 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7553 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7554 {
7555 const rdataOPT *opt;
7556 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7557 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7558 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7559 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7560 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7561 {
7562 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7563 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7564 }
7565 }
7566 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7567 }
7568
7569 //
7570 // Look in Authority Section for NSEC3 record
7571 //
7572
7573 mDNSParseNSEC3Records(m, query, end, InterfaceID, &McastNSEC3Records);
7574
7575 // ***
7576 // *** 2. Parse Question Section and mark potential answers
7577 // ***
7578 ptr = query->data;
7579 for (i=0; i<query->h.numQuestions; i++) // For each question...
7580 {
7581 mDNSBool QuestionNeedsMulticastResponse;
7582 int NumAnswersForThisQuestion = 0;
7583 AuthRecord *NSECAnswer = mDNSNULL;
7584 DNSQuestion pktq, *q;
7585 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7586 if (!ptr) goto exit;
7587
7588 pktq.AnonInfo = mDNSNULL;
7589 if (McastNSEC3Records)
7590 InitializeAnonInfoForQuestion(m, &McastNSEC3Records, &pktq);
7591 // The only queries that *need* a multicast response are:
7592 // * Queries sent via multicast
7593 // * from port 5353
7594 // * that don't have the kDNSQClass_UnicastResponse bit set
7595 // These queries need multicast responses because other clients will:
7596 // * suppress their own identical questions when they see these questions, and
7597 // * expire their cache records if they don't see the expected responses
7598 // For other queries, we may still choose to send the occasional multicast response anyway,
7599 // to keep our neighbours caches warm, and for ongoing conflict detection.
7600 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7601
7602 if (pktq.qclass & kDNSQClass_UnicastResponse)
7603 m->mDNSStats.UnicastBitInQueries++;
7604 else
7605 m->mDNSStats.NormalQueries++;
7606
7607 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7608 pktq.qclass &= ~kDNSQClass_UnicastResponse;
7609
7610 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7611 // can result in user callbacks which may change the record list and/or question list.
7612 // Also note: we just mark potential answer records here, without trying to build the
7613 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7614 // from that list while we're in the middle of trying to build it.
7615 if (m->CurrentRecord)
7616 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7617 m->CurrentRecord = m->ResourceRecords;
7618 while (m->CurrentRecord)
7619 {
7620 rr = m->CurrentRecord;
7621 m->CurrentRecord = rr->next;
7622 if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7623 {
7624 m->mDNSStats.MatchingAnswersForQueries++;
7625 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7626 {
7627 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7628 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7629 else if (ResourceRecordIsValidAnswer(rr))
7630 {
7631 NumAnswersForThisQuestion++;
7632 // As we have verified this question to be part of the same subset,
7633 // set the anonymous data which is needed below when walk the cache
7634 // records to see what answers we should be expecting. The cache records
7635 // may cache only the nsec3RR and not the anonymous data itself.
7636 if (pktq.AnonInfo && rr->resrec.AnonInfo)
7637 SetAnonData(&pktq, &rr->resrec, mDNStrue);
7638
7639 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7640 // unicast answer back to the source, because timeliness in answering probes is important.
7641
7642 // Notes:
7643 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7644 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7645 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7646 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7647 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7648 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7649 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7650 {
7651 // We only mark this question for sending if it is at least one second since the last time we multicast it
7652 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7653 // This is to guard against the case where someone blasts us with queries as fast as they can.
7654 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond ||
7655 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7656 rr->NR_AnswerTo = NR_AnswerMulticast;
7657 }
7658 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7659 }
7660 }
7661 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7662 {
7663 // If we don't have any answers for this question, but we do own another record with the same name,
7664 // then we'll want to mark it to generate an NSEC record on this interface
7665 if (!NSECAnswer) NSECAnswer = rr;
7666 }
7667 }
7668 }
7669
7670 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7671 {
7672 NumAnswersForThisQuestion++;
7673 NSECAnswer->SendNSECNow = InterfaceID;
7674 m->NextScheduledResponse = m->timenow;
7675 }
7676
7677 // If we couldn't answer this question, someone else might be able to,
7678 // so use random delay on response to reduce collisions
7679 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7680
7681 if (query->h.flags.b[0] & kDNSFlag0_TC)
7682 m->mDNSStats.KnownAnswerMultiplePkts++;
7683 // We only do the following accelerated cache expiration and duplicate question suppression processing
7684 // for non-truncated multicast queries with multicast responses.
7685 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7686 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7687 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7688 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7689 {
7690 #if POOF_ENABLED
7691 if (notD2D)
7692 {
7693 CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname);
7694 CacheRecord *cr;
7695
7696 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7697 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7698 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7699 if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7700 if (!cr->NextInKAList && eap != &cr->NextInKAList)
7701 {
7702 *eap = cr;
7703 eap = &cr->NextInKAList;
7704 }
7705 }
7706 #endif // POOF_ENABLED
7707
7708 // Check if this question is the same as any of mine.
7709 // We only do this for non-truncated queries. Right now it would be too complicated to try
7710 // to keep track of duplicate suppression state between multiple packets, especially when we
7711 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7712 // For anonymous question, the duplicate suppressesion should happen if the
7713 // question belongs in the same group. As the group is expected to be
7714 // small, we don't do the optimization for now.
7715 if (!pktq.AnonInfo)
7716 {
7717 for (q = m->Questions; q; q=q->next)
7718 if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7719 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7720 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7721 if (q->qtype == pktq.qtype &&
7722 q->qclass == pktq.qclass &&
7723 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7724 { *dqp = q; dqp = &q->NextInDQList; }
7725 }
7726 }
7727 if (pktq.AnonInfo)
7728 {
7729 FreeAnonInfo(pktq.AnonInfo);
7730 }
7731 }
7732
7733 // ***
7734 // *** 3. Now we can safely build the list of marked answers
7735 // ***
7736 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
7737 if (rr->NR_AnswerTo) // If we marked the record...
7738 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
7739
7740 // ***
7741 // *** 4. Add additional records
7742 // ***
7743 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7744
7745 // ***
7746 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7747 // ***
7748 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
7749 {
7750 // Get the record...
7751 CacheRecord *ourcacherr;
7752 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7753 if (!ptr) goto exit;
7754 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7755 {
7756 // See if this Known-Answer suppresses any of our currently planned answers
7757 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7758 {
7759 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7760 {
7761 m->mDNSStats.KnownAnswerSuppressions++;
7762 rr->NR_AnswerTo = mDNSNULL;
7763 rr->NR_AdditionalTo = mDNSNULL;
7764 }
7765 }
7766
7767 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7768 for (rr=m->ResourceRecords; rr; rr=rr->next)
7769 {
7770 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7771 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7772 {
7773 if (srcaddr->type == mDNSAddrType_IPv4)
7774 {
7775 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7776 }
7777 else if (srcaddr->type == mDNSAddrType_IPv6)
7778 {
7779 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7780 }
7781 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7782 {
7783 m->mDNSStats.KnownAnswerSuppressions++;
7784 rr->ImmedAnswer = mDNSNULL;
7785 rr->ImmedUnicast = mDNSfalse;
7786 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7787 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7788 #endif
7789 }
7790 }
7791 }
7792
7793 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7794
7795 #if POOF_ENABLED
7796 if (notD2D)
7797 {
7798 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7799 // any records that are suppressed by the Known Answer list in this packet.
7800 eap = &ExpectedAnswers;
7801 while (*eap)
7802 {
7803 CacheRecord *cr = *eap;
7804 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7805 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7806 else eap = &cr->NextInKAList;
7807 }
7808 }
7809 #endif // POOF_ENABLED
7810
7811 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7812 if (!ourcacherr)
7813 {
7814 dqp = &DupQuestions;
7815 while (*dqp)
7816 {
7817 DNSQuestion *q = *dqp;
7818 if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
7819 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7820 else dqp = &q->NextInDQList;
7821 }
7822 }
7823 }
7824 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7825 }
7826
7827 // ***
7828 // *** 6. Cancel any additionals that were added because of now-deleted records
7829 // ***
7830 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7831 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7832 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7833
7834 // ***
7835 // *** 7. Mark the send flags on the records we plan to send
7836 // ***
7837 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7838 {
7839 if (rr->NR_AnswerTo)
7840 {
7841 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
7842 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
7843
7844 // If it's been one TTL/4 since we multicast this, then send a multicast response
7845 // for conflict detection, etc.
7846 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4)
7847 {
7848 SendMulticastResponse = mDNStrue;
7849 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7850 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7851 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7852 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7853 {
7854 m->mDNSStats.UnicastDemotedToMulticast++;
7855 rr->NR_AnswerTo = NR_AnswerMulticast;
7856 }
7857 }
7858
7859 // If the client insists on a multicast response, then we'd better send one
7860 if (rr->NR_AnswerTo == NR_AnswerMulticast)
7861 {
7862 m->mDNSStats.MulticastResponses++;
7863 SendMulticastResponse = mDNStrue;
7864 }
7865 else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7866 {
7867 m->mDNSStats.UnicastResponses++;
7868 SendUnicastResponse = mDNStrue;
7869 }
7870 else if (rr->NR_AnswerTo)
7871 {
7872 SendLegacyResponse = mDNStrue;
7873 }
7874
7875 if (SendMulticastResponse || SendUnicastResponse)
7876 {
7877 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7878 rr->ImmedAnswerMarkTime = m->timenow;
7879 #endif
7880 m->NextScheduledResponse = m->timenow;
7881 // If we're already planning to send this on another interface, just send it on all interfaces
7882 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7883 rr->ImmedAnswer = mDNSInterfaceMark;
7884 else
7885 {
7886 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
7887 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7888 if (srcaddr->type == mDNSAddrType_IPv4)
7889 {
7890 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7891 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
7892 }
7893 else if (srcaddr->type == mDNSAddrType_IPv6)
7894 {
7895 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
7896 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
7897 }
7898 }
7899 }
7900 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7901 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7902 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7903 // else, for a simple unique record reply, we can reply immediately; no need for delay
7904 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
7905 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7906 }
7907 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
7908 {
7909 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7910 // If two clients on different interfaces do queries that invoke the same optional additional answer,
7911 // then the earlier client is out of luck
7912 rr->ImmedAdditional = InterfaceID;
7913 // No need to set m->NextScheduledResponse here
7914 // We'll send these additional records when we send them, or not, as the case may be
7915 }
7916 }
7917
7918 // ***
7919 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7920 // ***
7921 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
7922 {
7923 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7924 mDNSs32 oldss = m->SuppressSending;
7925 if (oldss && delayresponse)
7926 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
7927 #endif
7928 // Pick a random delay:
7929 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7930 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7931 // This is an integer value, with resolution determined by the platform clock rate.
7932 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7933 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7934 // The +49 before dividing is to ensure we round up, not down, to ensure that even
7935 // on platforms where the native clock rate is less than fifty ticks per second,
7936 // we still guarantee that the final calculated delay is at least one platform tick.
7937 // We want to make sure we don't ever allow the delay to be zero ticks,
7938 // because if that happens we'll fail the Bonjour Conformance Test.
7939 // Our final computed delay is 20-120ms for normal delayed replies,
7940 // or 400-500ms in the case of multi-packet known-answer lists.
7941 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
7942 if (m->SuppressSending == 0) m->SuppressSending = 1;
7943 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7944 if (oldss && delayresponse)
7945 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
7946 #endif
7947 }
7948
7949 // ***
7950 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7951 // ***
7952 if (SendLegacyResponse)
7953 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
7954
7955 exit:
7956 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7957
7958 // ***
7959 // *** 10. Finally, clear our link chains ready for use next time
7960 // ***
7961 while (ResponseRecords)
7962 {
7963 rr = ResponseRecords;
7964 ResponseRecords = rr->NextResponse;
7965 rr->NextResponse = mDNSNULL;
7966 rr->NR_AnswerTo = mDNSNULL;
7967 rr->NR_AdditionalTo = mDNSNULL;
7968 }
7969
7970 #if POOF_ENABLED
7971 while (ExpectedAnswers && notD2D)
7972 {
7973 CacheRecord *cr = ExpectedAnswers;
7974 ExpectedAnswers = cr->NextInKAList;
7975 cr->NextInKAList = mDNSNULL;
7976
7977 // For non-truncated queries, we can definitively say that we should expect
7978 // to be seeing a response for any records still left in the ExpectedAnswers list
7979 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7980 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4)
7981 {
7982 cr->UnansweredQueries++;
7983 cr->LastUnansweredTime = m->timenow;
7984 if (cr->UnansweredQueries > 1)
7985 debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr));
7986 SetNextCacheCheckTimeForRecord(m, cr);
7987 }
7988
7989 // If we've seen multiple unanswered queries for this record,
7990 // then mark it to expire in five seconds if we don't get a response by then.
7991 if (cr->UnansweredQueries >= MaxUnansweredQueries)
7992 {
7993 // Only show debugging message if this record was not about to expire anyway
7994 if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond)
7995 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
7996 cr->UnansweredQueries, InterfaceID, (RRExpireTime(cr) - m->timenow + mDNSPlatformOneSecond-1) / mDNSPlatformOneSecond, CRDisplayString(m, cr));
7997
7998 m->mDNSStats.PoofCacheDeletions++;
7999 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8000 }
8001 }
8002 #endif // POOF_ENABLED
8003
8004 while (DupQuestions)
8005 {
8006 DNSQuestion *q = DupQuestions;
8007 DupQuestions = q->NextInDQList;
8008 q->NextInDQList = mDNSNULL;
8009 RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
8010 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
8011 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
8012 }
8013
8014 if (McastNSEC3Records)
8015 {
8016 debugf("ProcessQuery: McastNSEC3Records not used");
8017 FreeNSECRecords(m, McastNSEC3Records);
8018 }
8019
8020 return(responseptr);
8021 }
8022
8023 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
8024 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8025 const mDNSInterfaceID InterfaceID)
8026 {
8027 mDNSu8 *responseend = mDNSNULL;
8028 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
8029 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8030
8031 if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr)))
8032 {
8033 const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID";
8034 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8035 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8036 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8037 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
8038 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
8039 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
8040 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data, reason);
8041 return;
8042 }
8043
8044 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8045 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8046 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8047 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
8048 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
8049 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
8050 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
8051
8052 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
8053 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
8054
8055 if (responseend) // If responseend is non-null, that means we built a unicast response packet
8056 {
8057 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8058 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
8059 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
8060 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
8061 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
8062 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
8063 }
8064 }
8065
8066 #if 0
8067 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
8068 {
8069 DNSServer *s;
8070 (void)m; // Unused
8071 (void)srcaddr; // Unused
8072 for (s = m->DNSServers; s; s = s->next)
8073 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
8074 return(mDNSfalse);
8075 }
8076 #endif
8077
8078 struct UDPSocket_struct
8079 {
8080 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8081 };
8082
8083 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp, DNSQuestion ** suspiciousQ)
8084 {
8085 DNSQuestion *q;
8086 for (q = m->Questions; q; q=q->next)
8087 {
8088 if (!tcp && !q->LocalSocket) continue;
8089 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
8090 q->qtype == question->qtype &&
8091 q->qclass == question->qclass &&
8092 q->qnamehash == question->qnamehash &&
8093 SameDomainName(&q->qname, &question->qname))
8094 {
8095 if (mDNSSameOpaque16(q->TargetQID, id)) return(q);
8096 else
8097 {
8098 if (!tcp && suspiciousQ) *suspiciousQ = q;
8099 return(mDNSNULL);
8100 }
8101 }
8102 }
8103 return(mDNSNULL);
8104 }
8105
8106 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8107 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8108 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
8109 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
8110 {
8111 DNSQuestion *q;
8112 (void)id;
8113 (void)srcaddr;
8114
8115 for (q = m->Questions; q; q=q->next)
8116 {
8117 if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
8118 {
8119 if (!mDNSOpaque16IsZero(q->TargetQID))
8120 {
8121 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
8122
8123 if (mDNSSameOpaque16(q->TargetQID, id))
8124 {
8125 mDNSIPPort srcp;
8126 if (!tcp)
8127 {
8128 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
8129 }
8130 else
8131 {
8132 srcp = q->tcpSrcPort;
8133 }
8134 if (mDNSSameIPPort(srcp, port)) return(q);
8135
8136 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8137 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8138 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8139 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
8140 q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
8141 return(mDNSNULL);
8142 }
8143 }
8144 else
8145 {
8146 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
8147 return(q);
8148 }
8149 }
8150 }
8151 return(mDNSNULL);
8152 }
8153
8154 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8155 // Currently this applies only to rdata types containing more than one domainname,
8156 // or types where the domainname is not the last item in the structure.
8157 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
8158 {
8159 switch (rr->rrtype)
8160 {
8161 case kDNSType_SOA: return sizeof(rdataSOA);
8162 case kDNSType_RP: return sizeof(rdataRP);
8163 case kDNSType_PX: return sizeof(rdataPX);
8164 default: return rr->rdlength;
8165 }
8166 }
8167
8168 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
8169 {
8170 CacheRecord *rr = mDNSNULL;
8171 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
8172
8173 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
8174
8175 //if (RDLength > InlineCacheRDSize)
8176 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8177
8178 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
8179 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
8180 if (!rr) NoCacheAnswer(m, &m->rec.r);
8181 else
8182 {
8183 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
8184 *rr = m->rec.r; // Block copy the CacheRecord object
8185 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
8186 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
8187 rr->resrec.mortality = Mortality_Mortal;
8188
8189 // We need to add the anonymous info before we call CacheRecordAdd so that
8190 // if it finds a matching question with this record, it bumps up the counters like
8191 // CurrentAnswers etc. Otherwise, when a cache entry gets removed, CacheRecordRmv
8192 // will complain.
8193 if (m->rec.r.resrec.AnonInfo)
8194 {
8195 rr->resrec.AnonInfo = m->rec.r.resrec.AnonInfo;
8196 m->rec.r.resrec.AnonInfo = mDNSNULL;
8197 }
8198 rr->DelayDelivery = delay;
8199
8200 // If this is an oversized record with external storage allocated, copy rdata to external storage
8201 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
8202 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8203 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
8204 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8205 if (RDLength > InlineCacheRDSize)
8206 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
8207
8208 rr->next = mDNSNULL; // Clear 'next' pointer
8209 rr->nsec = mDNSNULL;
8210 rr->soa = mDNSNULL;
8211
8212 if (sourceAddress)
8213 rr->sourceAddress = *sourceAddress;
8214
8215 if (!rr->resrec.InterfaceID)
8216 {
8217 m->rrcache_totalused_unicast += rr->resrec.rdlength;
8218 if (DNSSECRecordType(rr->resrec.rrtype))
8219 BumpDNSSECStats(m, kStatsActionIncrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
8220 }
8221
8222 if (Add)
8223 {
8224 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
8225 cg->rrcache_tail = &(rr->next); // Advance tail pointer
8226 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8227 }
8228 else
8229 {
8230 // Can't use the "cg->name" if we are not adding to the cache as the
8231 // CacheGroup may be released anytime if it is empty
8232 domainname *name = mDNSPlatformMemAllocate(DomainNameLength(cg->name));
8233 if (name)
8234 {
8235 AssignDomainName(name, cg->name);
8236 rr->resrec.name = name;
8237 }
8238 else
8239 {
8240 ReleaseCacheRecord(m, rr);
8241 NoCacheAnswer(m, &m->rec.r);
8242 rr = mDNSNULL;
8243 }
8244 }
8245 }
8246 return(rr);
8247 }
8248
8249 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
8250 {
8251 rr->TimeRcvd = m->timenow;
8252 rr->resrec.rroriginalttl = ttl;
8253 rr->UnansweredQueries = 0;
8254 if (rr->resrec.mortality != Mortality_Mortal) rr->resrec.mortality = Mortality_Immortal;
8255 SetNextCacheCheckTimeForRecord(m, rr);
8256 }
8257
8258 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
8259 {
8260 CacheRecord *rr;
8261 CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname);
8262 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8263 if (rr->CRActiveQuestion == q)
8264 {
8265 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8266 RefreshCacheRecord(m, rr, lease);
8267 }
8268 }
8269
8270 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
8271 {
8272 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8273 else if (LLQType == uDNS_LLQ_Events)
8274 {
8275 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8276 if (ttl == 0xFFFFFFFF) ttl = 0;
8277 else ttl = kLLQ_DefLease;
8278 }
8279 else // else not LLQ (standard uDNS response)
8280 {
8281 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8282 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8283 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8284
8285 ttl = RRAdjustTTL(ttl);
8286
8287 // For mDNS, TTL zero means "delete this record"
8288 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8289 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8290 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8291 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8292 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8293 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8294 // (with the current code) result in the server having even less than three seconds to respond
8295 // before we deleted the record and reported a "remove" event to any active questions.
8296 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8297 // then things really break (e.g. we end up making a negative cache entry).
8298 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8299 if (ttl < 15) ttl = 15;
8300 }
8301
8302 return ttl;
8303 }
8304
8305 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8306 // in m->rec.
8307 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist, DNSQuestion *q, mDNSBool *nseclist)
8308 {
8309 CacheRecord *const newcr = &m->rec.r;
8310 ResourceRecord *rr = &newcr->resrec;
8311 const CacheRecord *cr;
8312
8313 *nseclist = mDNSfalse;
8314 for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8315 {
8316 domainname *target = GetRRDomainNameTarget(&cr->resrec);
8317 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8318 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8319 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8320 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8321 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8322
8323 if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8324 {
8325 LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8326 return (mDNStrue);
8327 }
8328 }
8329
8330 // Either the question requires validation or we are validating a response with DNSSEC in which case
8331 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8332 // we receive NSECs for our query which does not match the qname and we need to cache in that case
8333 // too. nseclist is set if they have to be cached as part of the negative cache record.
8334 if (q && DNSSECQuestion(q))
8335 {
8336 mDNSBool same = SameDomainName(&q->qname, rr->name);
8337 if (same && (q->qtype == rr->rrtype || rr->rrtype == kDNSType_CNAME))
8338 {
8339 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q->qtype),
8340 CRDisplayString(m, newcr));
8341 return mDNStrue;
8342 }
8343 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
8344 // "nseclist" is set
8345 if (rr->rrtype == kDNSType_RRSIG)
8346 {
8347 RDataBody2 *const rdb = (RDataBody2 *)newcr->smallrdatastorage.data;
8348 rdataRRSig *rrsig = &rdb->rrsig;
8349 mDNSu16 typeCovered = swap16(rrsig->typeCovered);
8350
8351 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8352 // would match the qtype and they are cached normally as they are not used to prove the
8353 // non-existence of any name. In that case, it is like any other normal dnssec validation
8354 // and hence nseclist should not be set.
8355
8356 if (same && ((typeCovered == q->qtype) || (typeCovered == kDNSType_CNAME)))
8357 {
8358 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m, newcr),
8359 DNSTypeName(q->qtype));
8360 return mDNStrue;
8361 }
8362 else if (typeCovered == kDNSType_NSEC || typeCovered == kDNSType_NSEC3)
8363 {
8364 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m, newcr), DNSTypeName(typeCovered));
8365 *nseclist = mDNStrue;
8366 return mDNStrue;
8367 }
8368 else if (typeCovered == kDNSType_SOA)
8369 {
8370 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m, newcr));
8371 *nseclist = mDNStrue;
8372 return mDNStrue;
8373 }
8374 else return mDNSfalse;
8375 }
8376 if (rr->rrtype == kDNSType_NSEC)
8377 {
8378 if (!UNICAST_NSEC(rr))
8379 {
8380 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m, newcr));
8381 return mDNSfalse;
8382 }
8383 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m, newcr));
8384 *nseclist = mDNStrue;
8385 return mDNStrue;
8386 }
8387 if (rr->rrtype == kDNSType_SOA)
8388 {
8389 LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m, newcr));
8390 *nseclist = mDNStrue;
8391 return mDNStrue;
8392 }
8393 else if (rr->rrtype == kDNSType_NSEC3)
8394 {
8395 LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m, newcr));
8396 *nseclist = mDNStrue;
8397 return mDNStrue;
8398 }
8399 }
8400 return mDNSfalse;
8401 }
8402
8403 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords)
8404 {
8405 CacheRecord *rp, *next;
8406
8407 for (rp = NSECRecords; rp; rp = next)
8408 {
8409 next = rp->next;
8410 ReleaseCacheRecord(m, rp);
8411 }
8412 }
8413
8414 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8415 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8416 mDNSlocal void mDNSCoreReceiveNoDNSSECAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8417 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID)
8418 {
8419 int i;
8420 const mDNSu8 *ptr = response->data;
8421
8422 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8423 {
8424 DNSQuestion pktq;
8425 DNSQuestion *qptr = mDNSNULL;
8426 ptr = getQuestion(response, ptr, end, InterfaceID, &pktq);
8427 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &pktq, !dstaddr, mDNSNULL)) &&
8428 qptr->ValidatingResponse)
8429 {
8430 DNSQuestion *next, *q;
8431
8432 if (qptr->DuplicateOf)
8433 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr->qname.c, DNSTypeName(qptr->qtype));
8434
8435 // Be careful to call the callback for duplicate questions first and then the original
8436 // question. If we called the callback on the original question, it could stop and
8437 // a duplicate question would become the original question.
8438 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
8439 for (q = qptr->next ; q && q != m->NewQuestions; q = next)
8440 {
8441 next = q->next;
8442 if (q->DuplicateOf == qptr)
8443 {
8444 if (q->ValidatingResponse)
8445 LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q->qname.c, DNSTypeName(q->qtype));
8446 else
8447 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q->qname.c, DNSTypeName(q->qtype));
8448 if (q->QuestionCallback)
8449 q->QuestionCallback(m, q, mDNSNULL, QC_nodnssec);
8450 }
8451 }
8452 if (qptr->QuestionCallback)
8453 qptr->QuestionCallback(m, qptr, mDNSNULL, QC_nodnssec);
8454 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8455 }
8456 }
8457 }
8458
8459 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8460 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, uDNS_LLQType LLQType, mDNSu8 rcode, CacheRecord *NSECRecords)
8461 {
8462 int i;
8463 const mDNSu8 *ptr = response->data;
8464 CacheRecord *SOARecord = mDNSNULL;
8465
8466 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8467 {
8468 DNSQuestion q;
8469 DNSQuestion *qptr = mDNSNULL;
8470 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8471 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr, mDNSNULL)))
8472 {
8473 CacheRecord *rr, *neg = mDNSNULL;
8474 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
8475 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8476 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
8477 {
8478 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8479 if (RRExpireTime(rr) - m->timenow > 0) break;
8480 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8481 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
8482 }
8483 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8484 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8485 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8486 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8487 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8488 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8489 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8490 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8491 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8492 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8493 //
8494 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8495 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8496 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8497 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8498 // do the appropriate thing. This negative response is also needed for appending new search domains.
8499 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8500 {
8501 if (!rr)
8502 {
8503 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8504 m->CurrentQuestion = qptr;
8505 // We are not creating a cache record in this case, we need to pass back
8506 // the error we got so that the proxy code can return the right one to
8507 // the application
8508 if (qptr->ProxyQuestion)
8509 qptr->responseFlags = response->h.flags;
8510 GenerateNegativeResponse(m, mDNSInterface_Any, QC_forceresponse);
8511 m->CurrentQuestion = mDNSNULL;
8512 }
8513 else
8514 {
8515 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8516 }
8517 }
8518 else
8519 {
8520 if (!rr)
8521 {
8522 // We start off assuming a negative caching TTL of 60 seconds
8523 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8524 mDNSu32 negttl = 60;
8525 int repeat = 0;
8526 const domainname *name = &q.qname;
8527 mDNSu32 hash = q.qnamehash;
8528
8529 // Special case for our special Microsoft Active Directory "local SOA" check.
8530 // Some cheap home gateways don't include an SOA record in the authority section when
8531 // they send negative responses, so we don't know how long to cache the negative result.
8532 // Because we don't want to keep hitting the root name servers with our query to find
8533 // if we're on a network using Microsoft Active Directory using "local" as a private
8534 // internal top-level domain, we make sure to cache the negative result for at least one day.
8535 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8536
8537 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8538 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8539 {
8540 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8541 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8542 {
8543 CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec);
8544 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8545 mDNSu32 ttl_s = soa->min;
8546 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8547 // for the SOA record for ".", where the record is reported as non-cacheable
8548 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8549 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8550 ttl_s = m->rec.r.resrec.rroriginalttl;
8551 if (negttl < ttl_s) negttl = ttl_s;
8552
8553 // Create the SOA record as we may have to return this to the questions
8554 // that we are acting as a proxy for currently or in the future.
8555 SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL);
8556
8557 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8558 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8559 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8560 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8561 //
8562 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8563 // along with the negative cache record. For simplicity, we don't create the additional records.
8564 if (!qptr->ProxyQuestion && q.qtype == kDNSType_SOA)
8565 {
8566 int qcount = CountLabels(&q.qname);
8567 int scount = CountLabels(m->rec.r.resrec.name);
8568 if (qcount - 1 > scount)
8569 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8570 repeat = qcount - 1 - scount;
8571 }
8572 }
8573 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8574 }
8575
8576 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8577 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8578 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8579 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8580 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8581 // so that we back off our polling rate and don't keep hitting the server continually.
8582 if (neg)
8583 {
8584 if (negttl < neg->resrec.rroriginalttl * 2)
8585 negttl = neg->resrec.rroriginalttl * 2;
8586 if (negttl > 3600)
8587 negttl = 3600;
8588 }
8589
8590 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
8591
8592 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8593 if (neg)
8594 {
8595 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8596 RefreshCacheRecord(m, neg, negttl);
8597 // When we created the cache for the first time and answered the question, the question's
8598 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8599 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8600 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8601 // we should reset its question interval here to MaxQuestionInterval.
8602 ResetQuestionState(m, qptr);
8603 if (DNSSECQuestion(qptr))
8604 neg->CRDNSSECQuestion = 1;
8605 // Update the NSEC records again.
8606 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8607 if (NSECRecords)
8608 {
8609 if (!AddNSECSForCacheRecord(m, NSECRecords, neg, rcode))
8610 {
8611 // We might just have an SOA record for zones that are not signed and hence don't log
8612 // this as an error
8613 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s during refresh", CRDisplayString(m, neg));
8614 FreeNSECRecords(m, NSECRecords);
8615 neg->CRDNSSECQuestion = 0;
8616 }
8617 NSECRecords = mDNSNULL;
8618 }
8619 if (SOARecord)
8620 {
8621 if (neg->soa)
8622 ReleaseCacheRecord(m, neg->soa);
8623 neg->soa = SOARecord;
8624 SOARecord = mDNSNULL;
8625 }
8626 }
8627 else while (1)
8628 {
8629 CacheRecord *negcr;
8630 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8631 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8632 m->rec.r.responseFlags = response->h.flags;
8633 // We create SOA records above which might create new cache groups. Earlier
8634 // in the function we looked up the cache group for the name and it could have
8635 // been NULL. If we pass NULL cg to new cache entries that we create below,
8636 // it will create additional cache groups for the same name. To avoid that,
8637 // look up the cache group again to re-initialize cg again.
8638 cg = CacheGroupForName(m, hash, name);
8639 if (NSECRecords && DNSSECQuestion(qptr))
8640 {
8641 // Create the cache entry with delay and then add the NSEC records
8642 // to it and add it immediately.
8643 negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8644 if (negcr)
8645 {
8646 negcr->CRDNSSECQuestion = 0;
8647 if (!AddNSECSForCacheRecord(m, NSECRecords, negcr, rcode))
8648 {
8649 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s",
8650 CRDisplayString(m, negcr));
8651 FreeNSECRecords(m, NSECRecords);
8652 }
8653 else
8654 {
8655 negcr->CRDNSSECQuestion = 1;
8656 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for %s", CRDisplayString(m, negcr));
8657 }
8658 NSECRecords = mDNSNULL;
8659 negcr->DelayDelivery = 0;
8660 CacheRecordDeferredAdd(m, negcr);
8661 }
8662 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8663 break;
8664 }
8665 else
8666 {
8667 // Need to add with a delay so that we can tag the SOA record
8668 negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8669 if (negcr)
8670 {
8671 negcr->CRDNSSECQuestion = 0;
8672 if (DNSSECQuestion(qptr))
8673 negcr->CRDNSSECQuestion = 1;
8674 negcr->DelayDelivery = 0;
8675
8676 if (SOARecord)
8677 {
8678 if (negcr->soa)
8679 ReleaseCacheRecord(m, negcr->soa);
8680 negcr->soa = SOARecord;
8681 SOARecord = mDNSNULL;
8682 }
8683 CacheRecordDeferredAdd(m, negcr);
8684 }
8685 }
8686 m->rec.r.responseFlags = zeroID;
8687 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8688 if (!repeat) break;
8689 repeat--;
8690 name = (const domainname *)(name->c + 1 + name->c[0]);
8691 hash = DomainNameHashValue(name);
8692 }
8693 }
8694 }
8695 }
8696 }
8697 if (NSECRecords) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used"); FreeNSECRecords(m, NSECRecords); }
8698 if (SOARecord) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: SOARecord not used"); ReleaseCacheRecord(m, SOARecord); }
8699 }
8700
8701 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8702 {
8703 AuthRecord *rrPtr = mDNSNULL;
8704 LogSPS("Stored Proxy records :");
8705 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8706 {
8707 LogSPS("%s", ARDisplayString(m, rrPtr));
8708 }
8709 }
8710
8711 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8712 {
8713 AuthRecord *rrPtr = mDNSNULL;
8714
8715 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8716 {
8717 if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8718 {
8719 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8720 return mDNStrue;
8721 }
8722 }
8723 mDNSCorePrintStoredProxyRecords(m);
8724 return mDNSfalse;
8725 }
8726
8727 mDNSlocal CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8728 const mDNSu32 slot, CacheGroup *cg, DNSQuestion *unicastQuestion, CacheRecord ***cfp, CacheRecord **NSECCachePtr,
8729 mDNSInterfaceID InterfaceID)
8730 {
8731 CacheRecord *rr;
8732 CacheRecord **cflocal = *cfp;
8733
8734 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8735 {
8736 mDNSBool match;
8737 // Resource record received via unicast, the resGroupID should match ?
8738 if (!InterfaceID)
8739 {
8740 mDNSu16 id1 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
8741 mDNSu16 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8742 match = (id1 == id2);
8743 }
8744 else
8745 match = (rr->resrec.InterfaceID == InterfaceID);
8746 // If we found this exact resource record, refresh its TTL
8747 if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
8748 {
8749 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8750 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8751 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8752
8753 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8754 {
8755 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8756 if (rr->NextInCFList == mDNSNULL && *cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
8757 {
8758 *cflocal = rr;
8759 cflocal = &rr->NextInCFList;
8760 *cflocal = (CacheRecord*)1;
8761 *cfp = &rr->NextInCFList;
8762 }
8763
8764 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8765 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8766 {
8767 DNSQuestion *q;
8768 for (q = m->Questions; q; q=q->next)
8769 {
8770 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
8771 q->UniqueAnswers++;
8772 }
8773 rr->resrec.RecordType = m->rec.r.resrec.RecordType;
8774 }
8775 }
8776
8777 if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
8778 {
8779 // If the rdata of the packet record differs in name capitalization from the record in our cache
8780 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8781 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8782 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8783 rr->resrec.rroriginalttl = 0;
8784 rr->TimeRcvd = m->timenow;
8785 rr->UnansweredQueries = MaxUnansweredQueries;
8786 SetNextCacheCheckTimeForRecord(m, rr);
8787 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: %s", CRDisplayString(m, rr));
8788 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: %s", CRDisplayString(m, &m->rec.r));
8789 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8790 NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8791 // DO NOT break out here -- we want to continue as if we never found it
8792 }
8793 else if (!IdenticalAnonInfo(m->rec.r.resrec.AnonInfo, rr->resrec.AnonInfo))
8794 {
8795 // If the NSEC3 record changed, a few possibilities
8796 //
8797 // 1) the peer reinitialized e.g., after network change and still part of the
8798 // same set.
8799 // 2) the peer went to a different set but we did not see the goodbyes. If we just
8800 // update the nsec3 record, it would be incorrect. Flush the cache so that we
8801 // can deliver a RMV followed by ADD.
8802 // 3) if the peer is ourselves and we see the goodbye when moving to a different set
8803 // and so we flush the cache and create a new cache record with the new set information.
8804 // Now we move back to the original set. In this case, we can't just update the
8805 // NSEC3 record alone. We need to flush so that we can deliver an RMV followed by ADD
8806 // when we create the new cache entry.
8807 //
8808 // Note: For case (1), we could avoid flushing the cache but we can't tell the difference
8809 // from the other cases.
8810 rr->resrec.rroriginalttl = 0;
8811 rr->TimeRcvd = m->timenow;
8812 rr->UnansweredQueries = MaxUnansweredQueries;
8813 SetNextCacheCheckTimeForRecord(m, rr);
8814 LogInfo("mDNSCoreReceiveCacheCheck: AnonInfo changed for %s", CRDisplayString(m, rr));
8815 // DO NOT break out here -- we want to continue as if we never found it. When we return
8816 // from this function, we will create a new cache entry with the new NSEC3 record
8817 }
8818 else if (m->rec.r.resrec.rroriginalttl > 0)
8819 {
8820 DNSQuestion *q;
8821
8822 m->mDNSStats.CacheRefreshed++;
8823
8824 if (rr->resrec.mortality == Mortality_Ghost && unicastQuestion && (unicastQuestion->allowExpired != AllowExpired_AllowExpiredAnswers) && !rr->DelayDelivery)
8825 {
8826 rr->DelayDelivery = NonZeroTime(m->timenow);
8827 debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m->timenow - RRExpireTime(rr), CRDisplayString(m, rr));
8828 }
8829
8830 if (rr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, rr));
8831 RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
8832 rr->responseFlags = response->h.flags;
8833
8834 // If we may have NSEC records returned with the answer (which we don't know yet as it
8835 // has not been processed), we need to cache them along with the first cache
8836 // record in the list that answers the question so that it can be used for validation
8837 // later. The "type" check below is to make sure that we cache on the cache record
8838 // that would answer the question. It is possible that we might cache additional things
8839 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8840 // the record that answers the question.
8841 if (response->h.numAnswers && unicastQuestion && unicastQuestion->qtype == rr->resrec.rrtype
8842 && !(*NSECCachePtr))
8843 {
8844 LogInfo("mDNSCoreReceiveCacheCheck: rescuing RR %s", CRDisplayString(m, rr));
8845 *NSECCachePtr = rr;
8846 }
8847 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8848 // polling the network once we get a valid response back. For the first time when a new
8849 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8850 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8851 // configuration changed, without flushing the cache, we reset the question interval here.
8852 // Currently, we do this for for both multicast and unicast questions as long as the record
8853 // type is unique. For unicast, resource record is always unique and for multicast it is
8854 // true for records like A etc. but not for PTR.
8855 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8856 {
8857 for (q = m->Questions; q; q=q->next)
8858 {
8859 if (!q->DuplicateOf && !q->LongLived &&
8860 ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
8861 {
8862 ResetQuestionState(m, q);
8863 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8864 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8865 }
8866 }
8867 }
8868 break;
8869 }
8870 else
8871 {
8872 // If the packet TTL is zero, that means we're deleting this record.
8873 // To give other hosts on the network a chance to protest, we push the deletion
8874 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8875 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8876 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8877 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8878 // If the record is already going to expire in less than one second anyway, we leave it alone --
8879 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8880 debugf("DE for %s", CRDisplayString(m, rr));
8881 if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
8882 {
8883 rr->resrec.rroriginalttl = 1;
8884 rr->TimeRcvd = m->timenow;
8885 rr->UnansweredQueries = MaxUnansweredQueries;
8886 SetNextCacheCheckTimeForRecord(m, rr);
8887 }
8888 break;
8889 }
8890 }
8891 }
8892 return rr;
8893 }
8894
8895 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8896 const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records)
8897 {
8898 const mDNSu8 *ptr;
8899 CacheRecord *rr;
8900 int i;
8901
8902 if (!response->h.numAuthorities)
8903 return;
8904 ptr = LocateAuthorities(response, end);
8905 if (!ptr)
8906 {
8907 LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8908 return;
8909 }
8910 for (i = 0; i < response->h.numAuthorities && ptr && ptr < end; i++)
8911 {
8912 CacheGroup *cg;
8913
8914 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8915 if (!ptr || m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative || m->rec.r.resrec.rrtype != kDNSType_NSEC3)
8916 {
8917 debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr, CRDisplayString(m, &m->rec.r));
8918 m->rec.r.resrec.RecordType = 0;
8919 continue;
8920 }
8921 cg = CacheGroupForRecord(m, &m->rec.r.resrec);
8922 // Create the cache entry but don't add it to the cache it. We need
8923 // to cache this along with the main cache record.
8924 rr = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cg, 0, mDNSfalse, mDNSNULL);
8925 if (rr)
8926 {
8927 debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m, rr));
8928 *NSEC3Records = rr;
8929 NSEC3Records = &rr->next;
8930 }
8931 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8932 }
8933 }
8934
8935 mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
8936 {
8937 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8938 if (m->rec.r.resrec.AnonInfo)
8939 {
8940 FreeAnonInfo(m->rec.r.resrec.AnonInfo);
8941 m->rec.r.resrec.AnonInfo = mDNSNULL;
8942 }
8943 }
8944
8945 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8946 // the record list and/or question list.
8947 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8948 // InterfaceID non-NULL tells us the interface this multicast response was received on
8949 // InterfaceID NULL tells us this was a unicast response
8950 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8951 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
8952 const DNSMessage *const response, const mDNSu8 *end,
8953 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8954 const mDNSInterfaceID InterfaceID)
8955 {
8956 int i;
8957 mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
8958 mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8959 DNSQuestion *llqMatch = mDNSNULL;
8960 DNSQuestion *unicastQuestion = mDNSNULL;
8961 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
8962
8963 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8964 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8965 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8966 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
8967 CacheRecord **cfp = &CacheFlushRecords;
8968 CacheRecord *NSECRecords = mDNSNULL;
8969 CacheRecord *NSECCachePtr = mDNSNULL;
8970 CacheRecord **nsecp = &NSECRecords;
8971 CacheRecord *McastNSEC3Records = mDNSNULL;
8972 mDNSBool nseclist;
8973 mDNSu8 rcode = '\0';
8974 mDNSBool rrsigsCreated = mDNSfalse;
8975 mDNSBool DNSSECQuestion = mDNSfalse;
8976 NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
8977 mDNSBool recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
8978
8979 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8980 // to guard against spoof responses, then the only credible protection against that is cryptographic
8981 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8982 int firstauthority = response->h.numAnswers;
8983 int firstadditional = firstauthority + response->h.numAuthorities;
8984 int totalrecords = firstadditional + response->h.numAdditionals;
8985 const mDNSu8 *ptr = response->data;
8986 DNSServer *uDNSServer = mDNSNULL;
8987
8988 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8989 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8990 srcaddr, dstaddr, InterfaceID,
8991 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
8992 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
8993 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
8994 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
8995
8996 #if AWD_METRICS
8997 if (mDNSSameIPPort(srcport, UnicastDNSPort))
8998 {
8999 MetricsUpdateDNSResponseSize((mDNSu32)(end - (mDNSu8 *)response));
9000 }
9001 #endif
9002
9003 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
9004 // When a DNS client receives a reply with TC
9005 // set, it should ignore that response, and query again, using a
9006 // mechanism, such as a TCP connection, that will permit larger replies.
9007 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
9008 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
9009 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
9010 // <rdar://problem/6690034> Can't bind to Active Directory
9011 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
9012 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
9013 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
9014 // and not even do the TCP query.
9015 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
9016 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
9017 // either the authority section or additional section, then that implies that truncation occurred beyond the answer
9018 // section, and the answer section is therefore assumed to be complete.
9019 //
9020 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
9021 // When a response is so long that truncation is required, the truncation
9022 // should start at the end of the response and work forward in the
9023 // datagram. Thus if there is any data for the authority section, the
9024 // answer section is guaranteed to be unique.
9025 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) &&
9026 ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) return;
9027
9028 if (LLQType == uDNS_LLQ_Ignore) return;
9029
9030 // 1. We ignore questions (if any) in mDNS response packets
9031 // 2. If this is an LLQ response, we handle it much the same
9032 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9033 if (ResponseMCast || LLQType == uDNS_LLQ_Events)
9034 ptr = LocateAnswers(response, end);
9035 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9036 // in this response packet are immediately deemed to be invalid.
9037 else
9038 {
9039 mDNSBool failure, returnEarly;
9040 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
9041 failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
9042 returnEarly = mDNSfalse;
9043 // We could possibly combine this with the similar loop at the end of this function --
9044 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9045 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9046 // which it was received (or refreshed), and then at the end if we find any cache records which
9047 // answer questions in this packet's question section, but which aren't tagged with this packet's
9048 // packet number, then we deduce they are old and delete them
9049 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
9050 {
9051 DNSQuestion q, *qptr = mDNSNULL, *suspiciousForQ = mDNSNULL;
9052 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
9053 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr, &suspiciousForQ)))
9054 {
9055 if (!failure)
9056 {
9057 CacheRecord *rr;
9058 // Remember the unicast question that we found, which we use to make caching
9059 // decisions later on in this function
9060 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
9061 if (!mDNSOpaque16IsZero(response->h.id))
9062 {
9063 unicastQuestion = qptr;
9064 if (qptr->qDNSServer && DNSSECQuestion(qptr))
9065 {
9066 LogInfo("mDNSCoreReceiveResponse: Setting aware for %##s (%s) on %#a", qptr->qname.c,
9067 DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr);
9068 qptr->qDNSServer->DNSSECAware = mDNStrue;
9069 qptr->qDNSServer->req_DO = mDNStrue;
9070 }
9071 if (qptr->ValidatingResponse)
9072 DNSSECQuestion = mDNStrue;
9073 }
9074 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
9075 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
9076 {
9077 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
9078 rr->resrec.InterfaceID, CRDisplayString(m, rr));
9079 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9080 rr->TimeRcvd = m->timenow - TicksTTL(rr) - 1;
9081 rr->UnansweredQueries = MaxUnansweredQueries;
9082 rr->CRDNSSECQuestion = 0;
9083 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9084 {
9085 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for record %s, question %##s (%s)", CRDisplayString(m, rr),
9086 unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
9087 rr->CRDNSSECQuestion = 1;
9088 }
9089 }
9090 }
9091 else
9092 {
9093 if (qptr)
9094 {
9095 // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
9096 // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
9097 // req_DO to false here, the next retransmission for this question will turn off validation
9098 // and hence retransmit without the EDNS0/DOK option.
9099 if (DNSSECOptionalQuestion(qptr) && qptr->qDNSServer && !qptr->qDNSServer->DNSSECAware)
9100 {
9101 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query %##s (%s), clear DO flag",
9102 qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
9103 qptr->qDNSServer->req_DO = mDNSfalse;
9104 }
9105 // For Unicast DNS Queries, penalize the DNSServer
9106 else
9107 {
9108 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)",
9109 qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
9110 PenalizeDNSServer(m, qptr, response->h.flags);
9111 }
9112 }
9113 returnEarly = mDNStrue;
9114 }
9115 }
9116 else if (!InterfaceID && suspiciousForQ)
9117 {
9118 // If a response is suspicious for a question, then reissue the question via TCP
9119 LogInfo("mDNSCoreReceiveResponse: Server %p responded suspiciously to query %##s (%s) qID %d != rID: %d",
9120 suspiciousForQ->qDNSServer, q.qname.c, DNSTypeName(q.qtype),
9121 mDNSVal16(suspiciousForQ->TargetQID), mDNSVal16(response->h.id));
9122 uDNS_RestartQuestionAsTCP(m, suspiciousForQ, srcaddr, srcport);
9123 return;
9124 }
9125 }
9126 if (returnEarly)
9127 {
9128 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
9129 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
9130 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
9131 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
9132 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9133 // generate negative cache entries (we want to query the next server)
9134 return;
9135 }
9136 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9137 {
9138 BumpDNSSECStats(m, kStatsActionSet, kStatsTypeMsgSize, (end - response->data));
9139 }
9140 }
9141
9142 // Parse the NSEC3 records from the Authority section before we process
9143 // the Answer section so that we can cache them along with the proper
9144 // cache records we create.
9145 if (mDNSOpaque16IsZero(response->h.id))
9146 mDNSParseNSEC3Records(m, response, end, InterfaceID, &McastNSEC3Records);
9147
9148 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
9149 {
9150 // All responses sent via LL multicast are acceptable for caching
9151 // All responses received over our outbound TCP connections are acceptable for caching
9152 // We accept all records in a unicast response to a multicast query once we find one that
9153 // answers an active question.
9154 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse;
9155 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9156 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9157
9158 const mDNSu8 RecordType =
9159 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
9160 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
9161 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
9162 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9163
9164 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
9165 {
9166 mDNSCoreResetRecord(m);
9167 continue;
9168 }
9169
9170 // We have already parsed the NSEC3 records and cached them approrpriately for
9171 // multicast responses.
9172 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype == kDNSType_NSEC3)
9173 {
9174 mDNSCoreResetRecord(m);
9175 continue;
9176 }
9177 // Don't want to cache OPT or TSIG pseudo-RRs
9178 if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
9179 {
9180 mDNSCoreResetRecord(m);
9181 continue;
9182 }
9183 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
9184 {
9185 const rdataOPT *opt;
9186 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
9187 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9188 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9189 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
9190 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
9191 {
9192 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
9193 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
9194 }
9195 mDNSCoreResetRecord(m);
9196 continue;
9197 }
9198 // if a CNAME record points to itself, then don't add it to the cache
9199 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
9200 {
9201 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
9202 mDNSCoreResetRecord(m);
9203 continue;
9204 }
9205
9206 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9207 // In the case of active LLQs, we'll get remove events when the records actually do go away
9208 // In the case of polling LLQs, we assume the record remains valid until the next poll
9209 if (!mDNSOpaque16IsZero(response->h.id))
9210 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
9211
9212 // If response was not sent via LL multicast,
9213 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9214 if (!ResponseMCast)
9215 {
9216 if (LLQType)
9217 {
9218 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9219 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9220 // queries to get ADD/RMV events. To lookup the question, we can't use
9221 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9222 // has already matched the question using the 64 bit Id in the packet and we use that here.
9223
9224 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
9225
9226 // If this is a DNSSEC question that is also LongLived, don't accept records from the
9227 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
9228 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
9229 // for both negative responses and wildcard expanded positive responses as both of come
9230 // back with NSEC/NSEC3s.
9231 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9232 AcceptableResponse = mDNSfalse;
9233 }
9234 else if (!AcceptableResponse || !dstaddr)
9235 {
9236 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9237 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9238 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9239 // we create.
9240
9241 DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
9242
9243 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9244 // this record.
9245 //
9246 // We could potentially lookup the DNS server based on the source address, but that may not work always
9247 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9248 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9249 // on the "id" and "source port", then this response answers the question and assume the response
9250 // came from the same DNS server that we sent the query to.
9251
9252 if (q != mDNSNULL)
9253 {
9254 AcceptableResponse = mDNStrue;
9255 if (!InterfaceID)
9256 {
9257 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
9258 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
9259 if (!unicastQuestion) unicastQuestion = q; // Acceptable responses to unicast questions need to have (unicastQuestion != nil)
9260 }
9261 else
9262 {
9263 // Accept all remaining records in this unicast response to an mDNS query.
9264 recordAcceptedInResponse = mDNStrue;
9265 LogInfo("mDNSCoreReceiveResponse: Accepting response for query: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
9266 }
9267 }
9268 else
9269 {
9270 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9271 // the question. The code below does that. So, make this record unacceptable for now
9272 if (!InterfaceID)
9273 {
9274 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9275 AcceptableResponse = mDNSfalse;
9276 }
9277 }
9278 }
9279 }
9280 else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9281 {
9282 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9283 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9284 // To work with these broken routers, client devices need to blacklist these broken
9285 // routers and ignore their bogus ARP responses. Some devices implement a technique
9286 // such as the one described in US Patent 7436783, which lets clients detect and
9287 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9288
9289 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9290 // approach of just detecting these broken routers and completely disabling IPv4
9291 // link-local communication on interfaces where a broken router is detected.
9292 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9293 // that are deemed “safe” for IPv4 link-local communication;
9294 // the flag is cleared on interfaces where a broken router is detected.
9295
9296 // OS X and iOS will not even try to communicate with an IPv4
9297 // link-local destination on an interface without the IFEF_ARPLL flag set.
9298 // This can cause some badly written applications to freeze for a long time if they
9299 // attempt to connect to an IPv4 link-local destination address and then wait for
9300 // that connection attempt to time out before trying other candidate addresses.
9301
9302 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9303 // records on interfaces where we know the OS will be unwilling even to attempt
9304 // communication with those IPv4 link-local destination addresses.
9305 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9306
9307 const CacheRecord *const rr = &m->rec.r;
9308 const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9309 if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9310 {
9311 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9312 mDNSCoreResetRecord(m);
9313 continue;
9314 }
9315 }
9316
9317 // 1. Check that this packet resource record does not conflict with any of ours
9318 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9319 {
9320 if (m->CurrentRecord)
9321 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9322 m->CurrentRecord = m->ResourceRecords;
9323 while (m->CurrentRecord)
9324 {
9325 AuthRecord *rr = m->CurrentRecord;
9326 m->CurrentRecord = rr->next;
9327 // We accept all multicast responses, and unicast responses resulting from queries we issued
9328 // For other unicast responses, this code accepts them only for responses with an
9329 // (apparently) local source address that pertain to a record of our own that's in probing state
9330 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9331
9332 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
9333 {
9334 // ... check to see if type and rdata are identical
9335 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9336 {
9337 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9338 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9339 {
9340 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9341 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9342 }
9343 else
9344 {
9345 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
9346 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9347 }
9348 }
9349 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9350 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9351 {
9352 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
9353 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9354
9355 // If this record is marked DependentOn another record for conflict detection purposes,
9356 // then *that* record has to be bumped back to probing state to resolve the conflict
9357 if (rr->DependentOn)
9358 {
9359 while (rr->DependentOn) rr = rr->DependentOn;
9360 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9361 }
9362
9363 // If we've just whacked this record's ProbeCount, don't need to do it again
9364 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9365 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9366 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9367 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9368 else
9369 {
9370 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9371 // If we'd previously verified this record, put it back to probing state and try again
9372 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9373 {
9374 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9375 rr->resrec.RecordType = kDNSRecordTypeUnique;
9376 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9377 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9378 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9379 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9380 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
9381 rr->AnnounceCount = InitialAnnounceCount;
9382 InitializeLastAPTime(m, rr);
9383 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
9384 }
9385 // If we're probing for this record, we just failed
9386 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9387 {
9388 // At this point in the code, we're probing for uniqueness.
9389 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9390 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9391 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9392 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9393 {
9394 // This may be a conflict due to stale packets on the network. Delay probing by a second.
9395 // If there are conflicts after 3 such attempts, then it is a true conflict.
9396 if (m->DelayConflictProcessing)
9397 {
9398 m->DelayConflictProcessing--;
9399 LogMsg("Possible spurious conflict for %s. Attempt %d at suppressing probes for one second",
9400 ARDisplayString(m, rr), (MAX_CONFLICT_PROCESSING_DELAYS - m->DelayConflictProcessing));
9401 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
9402 rr->AnnounceCount = InitialAnnounceCount;
9403 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9404 InitializeLastAPTime(m, rr);
9405 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
9406 }
9407 else
9408 {
9409 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
9410 m->mDNSStats.NameConflicts++;
9411 #if APPLE_OSX_mDNSResponder
9412 // See if this record was also registered with any D2D plugins.
9413 D2D_stop_advertising_record(rr);
9414 #endif
9415 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9416 }
9417
9418 }
9419 }
9420 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9421 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9422 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9423 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9424 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9425 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9426 {
9427 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9428 m->mDNSStats.KnownUniqueNameConflicts++;
9429 #if APPLE_OSX_mDNSResponder
9430 D2D_stop_advertising_record(rr);
9431 #endif
9432 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9433 }
9434 else
9435 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9436 }
9437 }
9438 // Else, matching signature, different type or rdata, but not a considered a conflict.
9439 // If the packet record has the cache-flush bit set, then we check to see if we
9440 // have any record(s) of the same type that we should re-assert to rescue them
9441 // (see note about "multi-homing and bridged networks" at the end of this function).
9442 else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
9443 if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (mDNSu32)(m->timenow - rr->LastMCTime) > (mDNSu32)mDNSPlatformOneSecond/2)
9444 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9445 }
9446 }
9447 }
9448
9449 nseclist = mDNSfalse;
9450 if (!AcceptableResponse)
9451 {
9452 AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords, unicastQuestion, &nseclist);
9453 if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9454 }
9455
9456 // 2. See if we want to add this packet resource record to our cache
9457 // We only try to cache answers if we have a cache to put them in
9458 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9459 if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
9460 if (m->rrcache_size && AcceptableResponse)
9461 {
9462 const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash);
9463 CacheGroup *cg = CacheGroupForRecord(m, &m->rec.r.resrec);
9464 CacheRecord *rr = mDNSNULL;
9465
9466 if (McastNSEC3Records)
9467 InitializeAnonInfoForCR(m, &McastNSEC3Records, &m->rec.r);
9468
9469 // 2a. Check if this packet resource record is already in our cache.
9470 //
9471 // If this record should go in the nseclist, don't look in the cache for updating it.
9472 // They are supposed to be cached under the "nsec" field of the cache record for
9473 // validation. Just create the cache record.
9474 if (!nseclist)
9475 {
9476 rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, unicastQuestion, &cfp, &NSECCachePtr, InterfaceID);
9477 }
9478
9479 // If packet resource record not in our cache, add it now
9480 // (unless it is just a deletion of a record we never had, in which case we don't care)
9481 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9482 {
9483 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9484 mDNSs32 delay;
9485
9486 if (AddToCFList)
9487 delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9488 else
9489 delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash);
9490
9491 // If unique, assume we may have to delay delivery of this 'add' event.
9492 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9493 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9494 // to schedule an mDNS_Execute task at the appropriate time.
9495 rr = CreateNewCacheEntry(m, slot, cg, delay, !nseclist, srcaddr);
9496 if (rr)
9497 {
9498 rr->responseFlags = response->h.flags;
9499 // If we are not creating signatures, then we need to inform DNSSEC so that
9500 // it does not wait forever. Don't do this if we got NSEC records
9501 // as it indicates that this name does not exist.
9502 if (rr->resrec.rrtype == kDNSType_RRSIG && !nseclist)
9503 {
9504 rrsigsCreated = mDNStrue;
9505 }
9506 // Remember whether we created a cache record in response to a DNSSEC question.
9507 // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9508 rr->CRDNSSECQuestion = 0;
9509 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9510 {
9511 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record %s, question %##s (%s)", CRDisplayString(m, rr),
9512 unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
9513 rr->CRDNSSECQuestion = 1;
9514 }
9515 // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9516 // which we should be creating below. It is also needed in the wildcard
9517 // expanded answer case and in that case it is cached along with the answer.
9518 if (nseclist)
9519 {
9520 rr->TimeRcvd = m->timenow;
9521 *nsecp = rr;
9522 nsecp = &rr->next;
9523 }
9524 else if (AddToCFList)
9525 {
9526 *cfp = rr;
9527 cfp = &rr->NextInCFList;
9528 *cfp = (CacheRecord*)1;
9529 }
9530 else if (rr->DelayDelivery)
9531 {
9532 ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9533 }
9534 }
9535 }
9536 else
9537 {
9538 if (rr && rr->resrec.AnonInfo && m->rec.r.resrec.AnonInfo)
9539 {
9540 CopyAnonInfoForCR(m, rr, &m->rec.r);
9541 }
9542 }
9543 }
9544 mDNSCoreResetRecord(m);
9545 }
9546
9547 exit:
9548 mDNSCoreResetRecord(m);
9549
9550 // If we've just received one or more records with their cache flush bits set,
9551 // then scan that cache slot to see if there are any old stale records we need to flush
9552 while (CacheFlushRecords != (CacheRecord*)1)
9553 {
9554 CacheRecord *r1 = CacheFlushRecords, *r2;
9555 const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash);
9556 const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec);
9557 mDNSBool purgedRecords = mDNSfalse;
9558 CacheFlushRecords = CacheFlushRecords->NextInCFList;
9559 r1->NextInCFList = mDNSNULL;
9560
9561 // Look for records in the cache with the same signature as this new one with the cache flush
9562 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9563 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9564 // We make these TTL adjustments *only* for records that still have *more* than one second
9565 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9566 // (and now has half a second remaining) could inadvertently get its life extended, by either
9567 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9568 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9569 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9570 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9571 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9572 // To avoid this, we need to ensure that the cache flushing operation will only act to
9573 // *decrease* a record's remaining lifetime, never *increase* it.
9574 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9575 {
9576 mDNSu16 id1;
9577 mDNSu16 id2;
9578 if (!r1->resrec.InterfaceID)
9579 {
9580 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9581 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9582 }
9583 else
9584 {
9585 id1 = id2 = 0;
9586 }
9587 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9588 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9589 // the new RRSIG that we received. Process only if the typeCovered matches.
9590 if ((r1->resrec.rrtype == r2->resrec.rrtype) && (r1->resrec.rrtype == kDNSType_RRSIG))
9591 {
9592 rdataRRSig *rrsig1 = (rdataRRSig *)(((RDataBody2 *)(r1->resrec.rdata->u.data))->data);
9593 rdataRRSig *rrsig2 = (rdataRRSig *)(((RDataBody2 *)(r2->resrec.rdata->u.data))->data);
9594 if (swap16(rrsig1->typeCovered) != swap16(rrsig2->typeCovered))
9595 {
9596 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9597 DNSTypeName(swap16(rrsig1->typeCovered)), DNSTypeName(swap16(rrsig2->typeCovered)));
9598 continue;
9599 }
9600 }
9601
9602 // For Unicast (null InterfaceID) the resolver IDs should also match
9603 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9604 (r1->resrec.InterfaceID || (id1 == id2)) &&
9605 r1->resrec.rrtype == r2->resrec.rrtype &&
9606 r1->resrec.rrclass == r2->resrec.rrclass)
9607 {
9608 if (r1->resrec.mortality == Mortality_Mortal && r2->resrec.mortality != Mortality_Mortal)
9609 {
9610 verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1, r2);
9611 r1->resrec.mortality = Mortality_Immortal; // Immortalize the replacement record
9612 }
9613
9614 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9615 // else, if record is old, mark it to be flushed
9616 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9617 {
9618 // If we find mismatched TTLs in an RRSet, correct them.
9619 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9620 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9621 // which we treat as a goodbye followed by an addition) and in that case it would be
9622 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9623
9624 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9625 // because certain early Bonjour devices are known to have this specific mismatch, and
9626 // there's no point filling syslog with messages about something we already know about.
9627 // We also don't log this for uDNS responses, since a caching name server is obliged
9628 // to give us an aged TTL to correct for how long it has held the record,
9629 // so our received TTLs are expected to vary in that case
9630
9631 // We also suppress log message in the case of SRV records that are received
9632 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9633 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9634 // GM builds.
9635 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9636 {
9637 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9638 !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
9639 mDNSOpaque16IsZero(response->h.id))
9640 LogInfo("Correcting TTL from %4d to %4d for %s",
9641 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9642 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9643 }
9644 r2->TimeRcvd = m->timenow;
9645 SetNextCacheCheckTimeForRecord(m, r2);
9646 }
9647 else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed
9648 {
9649 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9650 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9651 // We set stale records to expire in one second.
9652 // This gives the owner a chance to rescue it if necessary.
9653 // This is important in the case of multi-homing and bridged networks:
9654 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9655 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9656 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9657 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9658 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9659 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9660
9661 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9662 // final expiration queries for this record.
9663
9664 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9665 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9666 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9667 // <rdar://problem/5636422> Updating TXT records is too slow
9668 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9669 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9670 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9671 {
9672 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9673 r2->resrec.rroriginalttl = 0;
9674 }
9675 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9676 {
9677 // We only set a record to expire in one second if it currently has *more* than a second to live
9678 // If it's already due to expire in a second or less, we just leave it alone
9679 r2->resrec.rroriginalttl = 1;
9680 r2->UnansweredQueries = MaxUnansweredQueries;
9681 r2->TimeRcvd = m->timenow - 1;
9682 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9683 // that we marked for deletion via an explicit DE record
9684 }
9685 SetNextCacheCheckTimeForRecord(m, r2);
9686 }
9687 else
9688 {
9689 #if AWD_METRICS
9690 if (r2->resrec.mortality == Mortality_Ghost)
9691 {
9692 DNSQuestion * q;
9693 for (q = m->Questions; q; q=q->next)
9694 {
9695 if (!q->LongLived && ActiveQuestion(q) &&
9696 ResourceRecordAnswersQuestion(&r2->resrec, q) &&
9697 q->metrics.expiredAnswerState == ExpiredAnswer_AnsweredWithExpired)
9698 {
9699 q->metrics.expiredAnswerState = ExpiredAnswer_ExpiredAnswerChanged;
9700 }
9701 }
9702 }
9703 #endif
9704 // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9705 r2->resrec.mortality = Mortality_Mortal; // We want it purged, so remove any immortality
9706 mDNS_PurgeCacheResourceRecord(m, r2);
9707 purgedRecords = mDNStrue;
9708 }
9709 }
9710 }
9711
9712 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
9713 {
9714 // If we had a unicast question for this response with at least one positive answer and we
9715 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9716 // signatures along with the cache record which will be used for validation later. If
9717 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9718 // use that instead.
9719 if (response->h.numAnswers && unicastQuestion && NSECRecords)
9720 {
9721 if (!NSECCachePtr)
9722 {
9723 LogInfo("mDNSCoreReceiveResponse: Updating NSECCachePtr to %s", CRDisplayString(m, r1));
9724 NSECCachePtr = r1;
9725 }
9726 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9727 // might start the verification process which needs these NSEC records
9728 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9729 {
9730 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9731 FreeNSECRecords(m, NSECRecords);
9732 }
9733 NSECRecords = mDNSNULL;
9734 NSECCachePtr = mDNSNULL;
9735 }
9736 if (r1->resrec.InterfaceID)
9737 {
9738 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash);
9739 }
9740 else
9741 {
9742 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9743 // them to be deleted before any ADD events for this record.
9744 r1->DelayDelivery = purgedRecords ? NonZeroTime(m->timenow) : 0;
9745 }
9746 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9747 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9748 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9749 }
9750 }
9751
9752 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9753 // update them now for future validations.
9754 if (NSECRecords && NSECCachePtr)
9755 {
9756 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m, NSECCachePtr));
9757 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9758 {
9759 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9760 FreeNSECRecords(m, NSECRecords);
9761 }
9762 NSECRecords = mDNSNULL;
9763 NSECCachePtr = mDNSNULL;
9764 }
9765
9766 // If there is at least one answer and we did not create RRSIGs and there was a
9767 // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9768 // were created. We don't need to give a hint:
9769 //
9770 // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9771 // generate a negative response
9772 //
9773 // - if we have NSECRecords, it means we might have a potential proof for
9774 // non-existence of name that we are looking for
9775 //
9776 if (response->h.numAnswers && !rrsigsCreated && DNSSECQuestion && !NSECRecords)
9777 mDNSCoreReceiveNoDNSSECAnswers(m, response, end, dstaddr, dstport, InterfaceID);
9778
9779 // See if we need to generate negative cache entries for unanswered unicast questions
9780 mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, LLQType, rcode, NSECRecords);
9781
9782 if (McastNSEC3Records)
9783 {
9784 debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9785 FreeNSECRecords(m, McastNSEC3Records);
9786 }
9787 }
9788
9789 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9790 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9791 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9792 // that warrants waking the sleeping host.
9793 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9794
9795 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9796 {
9797 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9798 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9799 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9800 // simple, we use the same mechanism for both lists.
9801 if (!e->l[0])
9802 {
9803 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9804 return;
9805 }
9806 m->CurrentRecord = thelist;
9807 while (m->CurrentRecord)
9808 {
9809 AuthRecord *const rr = m->CurrentRecord;
9810 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9811 {
9812 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9813 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9814 }
9815 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9816 m->CurrentRecord = rr->next;
9817 }
9818 }
9819
9820 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9821 {
9822 if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9823 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9824 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9825 }
9826
9827 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9828 {
9829 if (result && result != mStatus_MemFree)
9830 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9831
9832 if (result == mStatus_NameConflict)
9833 {
9834 mDNS_Lock(m);
9835 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9836 if (ar->WakeUp.HMAC.l[0])
9837 {
9838 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password, mDNSfalse); // Send one wakeup magic packet
9839 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken
9840 }
9841 mDNS_Unlock(m);
9842 }
9843
9844 if (result == mStatus_NameConflict || result == mStatus_MemFree)
9845 {
9846 m->ProxyRecords--;
9847 mDNSPlatformMemFree(ar);
9848 mDNS_UpdateAllowSleep(m);
9849 }
9850 }
9851
9852 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9853 {
9854 int i;
9855 mDNSs8 hval = 0;
9856 int colons = 0;
9857 mDNSu8 val = 0;
9858
9859 for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9860 {
9861 hval = HexVal(*ptr);
9862 if (hval != -1)
9863 {
9864 val <<= 4;
9865 val |= hval;
9866 }
9867 else if (*ptr == ':')
9868 {
9869 if (colons >=5)
9870 {
9871 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
9872 return mDNSNULL;
9873 }
9874 eth->b[colons] = val;
9875 colons++;
9876 val = 0;
9877 }
9878 }
9879 if (colons != 5)
9880 {
9881 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9882 return mDNSNULL;
9883 }
9884 eth->b[colons] = val;
9885 return ptr;
9886 }
9887
9888 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9889 {
9890 int hval;
9891 int value;
9892 int numBytes;
9893 int digitsProcessed;
9894 int zeroFillStart;
9895 int numColons;
9896 mDNSu8 v6addr[16];
9897
9898 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9899 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9900 //
9901 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9902 // the result in "v6"
9903
9904 numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9905 while (ptr < limit && *ptr != ' ')
9906 {
9907 hval = HexVal(*ptr);
9908 if (hval != -1)
9909 {
9910 value <<= 4;
9911 value |= hval;
9912 digitsProcessed = 1;
9913 }
9914 else if (*ptr == ':')
9915 {
9916 if (!digitsProcessed)
9917 {
9918 // If we have already seen a "::", we should not see one more. Handle the special
9919 // case of "::"
9920 if (numColons)
9921 {
9922 // if we never filled any bytes and the next character is space (we have reached the end)
9923 // we are done
9924 if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
9925 {
9926 mDNSPlatformMemZero(v6->b, 16);
9927 return ptr + 1;
9928 }
9929 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
9930 return mDNSNULL;
9931 }
9932
9933 // We processed "::". We need to fill zeroes later. For now, mark the
9934 // point where we will start filling zeroes from.
9935 zeroFillStart = numBytes;
9936 numColons++;
9937 }
9938 else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
9939 {
9940 // We have a trailing ":" i.e., no more characters after ":"
9941 LogMsg("GetValueForIPv6Addr: Trailing colon");
9942 return mDNSNULL;
9943 }
9944 else
9945 {
9946 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9947 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9948 // filled here is 12 and 13.
9949 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
9950
9951 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9952 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9953 digitsProcessed = value = 0;
9954
9955 // Make sure that we did not fill the 13th and 14th byte above
9956 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
9957 }
9958 }
9959 ptr++;
9960 }
9961
9962 // We should be processing the last set of bytes following the last ":" here
9963 if (!digitsProcessed)
9964 {
9965 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
9966 return mDNSNULL;
9967 }
9968
9969 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
9970 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9971 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9972
9973 if (zeroFillStart)
9974 {
9975 int i, j, n;
9976 for (i = 0; i < zeroFillStart; i++)
9977 v6->b[i] = v6addr[i];
9978 for (j = i, n = 0; n < 16 - numBytes; j++, n++)
9979 v6->b[j] = 0;
9980 for (; j < 16; i++, j++)
9981 v6->b[j] = v6addr[i];
9982 }
9983 else if (numBytes == 16)
9984 mDNSPlatformMemCopy(v6->b, v6addr, 16);
9985 else
9986 {
9987 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
9988 return mDNSNULL;
9989 }
9990 return ptr;
9991 }
9992
9993 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
9994 {
9995 mDNSu32 val;
9996 int dots = 0;
9997 val = 0;
9998
9999 for ( ; ptr < limit && *ptr != ' '; ptr++)
10000 {
10001 if (*ptr >= '0' && *ptr <= '9')
10002 val = val * 10 + *ptr - '0';
10003 else if (*ptr == '.')
10004 {
10005 if (val > 255 || dots >= 3)
10006 {
10007 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
10008 return mDNSNULL;
10009 }
10010 v4->b[dots++] = val;
10011 val = 0;
10012 }
10013 else
10014 {
10015 // We have a zero at the end and if we reached that, then we are done.
10016 if (*ptr == 0 && ptr == limit - 1 && dots == 3)
10017 {
10018 v4->b[dots] = val;
10019 return ptr + 1;
10020 }
10021 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
10022 }
10023 }
10024 if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
10025 v4->b[dots] = val;
10026 return ptr;
10027 }
10028
10029 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
10030 {
10031 mDNSu32 val;
10032
10033 val = 0;
10034 for ( ; ptr < limit && *ptr != ' '; ptr++)
10035 {
10036 if (*ptr < '0' || *ptr > '9')
10037 {
10038 // We have a zero at the end and if we reached that, then we are done.
10039 if (*ptr == 0 && ptr == limit - 1)
10040 {
10041 *value = val;
10042 return ptr + 1;
10043 }
10044 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
10045 }
10046 val = val * 10 + *ptr - '0';
10047 }
10048 *value = val;
10049 return ptr;
10050 }
10051
10052 mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
10053 {
10054 mDNSAddr laddr, raddr;
10055 mDNSEthAddr eth;
10056 mDNSIPPort lport, rport;
10057 mDNSu32 timeout, seq, ack;
10058 mDNSu16 win;
10059
10060 if (!mDNS_KeepaliveRecord(&rr->resrec))
10061 {
10062 return mDNSfalse;
10063 }
10064
10065 timeout = seq = ack = 0;
10066 win = 0;
10067 laddr = raddr = zeroAddr;
10068 lport = rport = zeroIPPort;
10069 eth = zeroEthAddr;
10070
10071 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10072
10073 if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
10074 mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
10075 mDNSEthAddressIsZero(eth))
10076 {
10077 return mDNSfalse;
10078 }
10079
10080 return mDNStrue;
10081 }
10082
10083
10084 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
10085 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
10086 {
10087 if (ar->resrec.rrtype != kDNSType_NULL)
10088 return;
10089
10090 if (mDNS_KeepaliveRecord(&ar->resrec))
10091 {
10092 int len = ar->resrec.rdlength;
10093 mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
10094 mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
10095 mDNSu32 value = 0;
10096
10097 while (ptr < limit)
10098 {
10099 mDNSu8 param = *ptr;
10100 ptr += 2; // Skip the letter and the "="
10101 if (param == 'h')
10102 {
10103 laddr->type = mDNSAddrType_IPv4;
10104 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
10105 }
10106 else if (param == 'd')
10107 {
10108 raddr->type = mDNSAddrType_IPv4;
10109 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
10110 }
10111 else if (param == 'H')
10112 {
10113 laddr->type = mDNSAddrType_IPv6;
10114 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
10115 }
10116 else if (param == 'D')
10117 {
10118 raddr->type = mDNSAddrType_IPv6;
10119 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
10120 }
10121 else if (param == 'm')
10122 {
10123 ptr = GetValueForMACAddr(ptr, limit, eth);
10124 }
10125 else
10126 {
10127 ptr = GetValueForKeepalive(ptr, limit, &value);
10128 }
10129 if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10130
10131 // Extract everything in network order so that it is easy for sending a keepalive and also
10132 // for matching incoming TCP packets
10133 switch (param)
10134 {
10135 case 't':
10136 *timeout = value;
10137 //if (*timeout < 120) *timeout = 120;
10138 break;
10139 case 'h':
10140 case 'H':
10141 case 'd':
10142 case 'D':
10143 case 'm':
10144 case 'i':
10145 case 'c':
10146 break;
10147 case 'l':
10148 lport->NotAnInteger = swap16((mDNSu16)value);
10149 break;
10150 case 'r':
10151 rport->NotAnInteger = swap16((mDNSu16)value);
10152 break;
10153 case 's':
10154 *seq = swap32(value);
10155 break;
10156 case 'a':
10157 *ack = swap32(value);
10158 break;
10159 case 'w':
10160 *win = swap16((mDNSu16)value);
10161 break;
10162 default:
10163 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
10164 ptr = limit;
10165 break;
10166 }
10167 ptr++; // skip the space
10168 }
10169 }
10170 }
10171
10172 // 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
10173 // the clients need not retrieve this information from the auth record again.
10174 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
10175 const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
10176 {
10177 AuthRecord *ar;
10178 mDNSAddr laddr, raddr;
10179 mDNSEthAddr eth;
10180 mDNSIPPort lport, rport;
10181 mDNSu32 timeout, seq, ack;
10182 mDNSu16 win;
10183
10184 for (ar = m->ResourceRecords; ar; ar=ar->next)
10185 {
10186 timeout = seq = ack = 0;
10187 win = 0;
10188 laddr = raddr = zeroAddr;
10189 lport = rport = zeroIPPort;
10190
10191 if (!ar->WakeUp.HMAC.l[0]) continue;
10192
10193 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10194
10195 // Did we parse correctly ?
10196 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10197 {
10198 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
10199 continue;
10200 }
10201
10202 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10203 &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
10204
10205 // Does it match the incoming TCP packet ?
10206 if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
10207 {
10208 // returning in network order
10209 *rseq = seq;
10210 *rack = ack;
10211 return ar;
10212 }
10213 }
10214 return mDNSNULL;
10215 }
10216
10217 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
10218 {
10219 AuthRecord *ar;
10220
10221 for (ar = m->ResourceRecords; ar; ar=ar->next)
10222 {
10223 mDNSu32 timeout, seq, ack;
10224 mDNSu16 win;
10225 mDNSAddr laddr, raddr;
10226 mDNSEthAddr eth;
10227 mDNSIPPort lport, rport;
10228
10229 timeout = seq = ack = 0;
10230 win = 0;
10231
10232 laddr = raddr = zeroAddr;
10233 lport = rport = zeroIPPort;
10234
10235 if (!ar->WakeUp.HMAC.l[0]) continue;
10236
10237 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10238
10239 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10240 {
10241 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
10242 continue;
10243 }
10244 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10245
10246 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10247 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10248 if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
10249 {
10250 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10251 ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
10252 }
10253 if (m->NextScheduledKA - ar->KATimeExpire > 0)
10254 m->NextScheduledKA = ar->KATimeExpire;
10255 }
10256 }
10257
10258 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
10259 {
10260 mDNSu32 timeout, seq, ack, seqInc;
10261 mDNSu16 win;
10262 mDNSAddr laddr, raddr;
10263 mDNSEthAddr eth;
10264 mDNSIPPort lport, rport;
10265 mDNSu8 *ptr;
10266
10267 if (ar == mDNSNULL)
10268 {
10269 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10270 return;
10271 }
10272
10273 timeout = seq = ack = 0;
10274 win = 0;
10275
10276 laddr = raddr = zeroAddr;
10277 lport = rport = zeroIPPort;
10278
10279 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10280
10281 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10282 {
10283 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
10284 return;
10285 }
10286
10287 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10288 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10289 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10290 // it's converted to host byte order before incrementing it by one.
10291 ptr = (mDNSu8 *)&seq;
10292 seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
10293 ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
10294 ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
10295 ptr[2] = (mDNSu8)((seqInc >> 8) & 0xFF);
10296 ptr[3] = (mDNSu8)((seqInc ) & 0xFF);
10297 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10298 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10299 }
10300
10301 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
10302 const DNSMessage *const msg, const mDNSu8 *end,
10303 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
10304 const mDNSInterfaceID InterfaceID)
10305 {
10306 int i;
10307 AuthRecord opt;
10308 mDNSu8 *p = m->omsg.data;
10309 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10310 mDNSu32 updatelease = 0;
10311 const mDNSu8 *ptr;
10312
10313 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10314 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10315 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
10316 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
10317 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
10318 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
10319 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
10320
10321 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
10322
10323 if (mDNS_PacketLoggingEnabled)
10324 DumpPacket(mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
10325
10326 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
10327 if (ptr)
10328 {
10329 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10330 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10331 {
10332 const rdataOPT *o;
10333 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10334 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10335 {
10336 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
10337 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
10338 }
10339 }
10340 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10341 }
10342
10343 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
10344
10345 if (!updatelease || !owner.HMAC.l[0])
10346 {
10347 static int msgs = 0;
10348 if (msgs < 100)
10349 {
10350 msgs++;
10351 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
10352 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
10353 }
10354 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
10355 }
10356 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
10357 {
10358 static int msgs = 0;
10359 if (msgs < 100)
10360 {
10361 msgs++;
10362 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
10363 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
10364 }
10365 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10366 }
10367 else
10368 {
10369 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
10370
10371 if (updatelease > 24 * 60 * 60)
10372 updatelease = 24 * 60 * 60;
10373
10374 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
10375 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
10376
10377 ptr = LocateAuthorities(msg, end);
10378
10379 // Clear any stale TCP keepalive records that may exist
10380 ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
10381 ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
10382
10383 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10384 {
10385 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10386 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10387 {
10388 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10389 AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10390 if (!ar)
10391 {
10392 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10393 break;
10394 }
10395 else
10396 {
10397 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10398 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10399 // All stale keepalive records have been flushed prior to this loop.
10400 if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10401 {
10402 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10403 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10404 }
10405 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10406 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10407 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10408 ar->resrec.rdata->MaxRDLength = RDLengthMem;
10409 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10410 ar->ForceMCast = mDNStrue;
10411 ar->WakeUp = owner;
10412 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10413 {
10414 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10415 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10416 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10417 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10418 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10419 }
10420 ar->TimeRcvd = m->timenow;
10421 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10422 if (m->NextScheduledSPS - ar->TimeExpire > 0)
10423 m->NextScheduledSPS = ar->TimeExpire;
10424 ar->KATimeExpire = 0;
10425 mDNS_Register_internal(m, ar);
10426
10427 m->ProxyRecords++;
10428 mDNS_UpdateAllowSleep(m);
10429 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10430 }
10431 }
10432 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10433 }
10434
10435 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10436 {
10437 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10438 ClearProxyRecords(m, &owner, m->DuplicateRecords);
10439 ClearProxyRecords(m, &owner, m->ResourceRecords);
10440 }
10441 else
10442 {
10443 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10444 opt.resrec.rrclass = NormalMaxDNSMessageData;
10445 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
10446 opt.resrec.rdestimate = sizeof(rdataOPT);
10447 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
10448 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10449 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10450 }
10451 }
10452
10453 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
10454 mDNS_SendKeepalives(m);
10455 }
10456
10457 mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg)
10458 {
10459 mDNSu8 *ptr = msg->data;
10460 mDNSu8 *end = mDNSNULL;
10461 mDNSu32 length = 0;
10462 AuthRecord opt;
10463 NetworkInterfaceInfo *intf;
10464
10465 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10466 opt.resrec.rrclass = NormalMaxDNSMessageData;
10467 opt.resrec.rdlength = sizeof(rdataOPT);
10468 opt.resrec.rdestimate = sizeof(rdataOPT);
10469
10470 intf = FirstInterfaceForID(m, InterfaceID);
10471 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
10472
10473 LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt));
10474 end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec);
10475 if (end != mDNSNULL)
10476 {
10477 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10478 SwapDNSHeaderBytes(msg);
10479 length = (end - msg->data);
10480 }
10481 else
10482 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10483
10484 return length;
10485 }
10486
10487 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10488 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10489 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10490 // Really, both should be unified and handled in one place.
10491 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10492 {
10493 if (InterfaceID)
10494 {
10495 mDNSu32 pktlease = 0, spsupdates = 0;
10496 const mDNSBool gotlease = GetPktLease(m, msg, end, &pktlease);
10497 const mDNSu32 updatelease = gotlease ? pktlease : 60 * 60; // If SPS fails to indicate lease time, assume one hour
10498 if (gotlease) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10499
10500 if (m->CurrentRecord)
10501 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10502 m->CurrentRecord = m->ResourceRecords;
10503 while (m->CurrentRecord)
10504 {
10505 AuthRecord *const rr = m->CurrentRecord;
10506 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10507 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10508 {
10509 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10510 // Clear the updateid when we are done sending on all interfaces.
10511 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10512 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10513 bit_clr_opaque64(rr->updateIntID, scopeid);
10514 if (mDNSOpaque64IsZero(&rr->updateIntID))
10515 rr->updateid = zeroID;
10516 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10517 spsupdates++;
10518 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));
10519 if (rr->WakeUp.HMAC.l[0])
10520 {
10521 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10522 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10523 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10524 }
10525 }
10526 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10527 // new records could have been added to the end of the list as a result of that call.
10528 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10529 m->CurrentRecord = rr->next;
10530 }
10531 if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10532 {
10533 char *ifname;
10534 mDNSAddr spsaddr;
10535 DNSMessage optMsg;
10536 int length;
10537 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10538 ifname = InterfaceNameForID(m, InterfaceID);
10539 mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10540 mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10541
10542 // Store the Owner OPT record for this interface.
10543 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10544 InitializeDNSMessage(&optMsg.h, zeroID, ResponseFlags);
10545 length = mDNSGenerateOwnerOptForInterface(m, InterfaceID, &optMsg);
10546 if (length != 0)
10547 {
10548 length += sizeof(DNSMessageHeader);
10549 mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length);
10550 }
10551 }
10552 }
10553 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10554 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10555 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10556 }
10557
10558 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
10559 const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
10560 {
10561 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10562 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10563
10564 // Create empty resource record
10565 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
10566 cr->resrec.InterfaceID = InterfaceID;
10567 cr->resrec.rDNSServer = dnsserver;
10568 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10569 cr->resrec.rrtype = rrtype;
10570 cr->resrec.rrclass = rrclass;
10571 cr->resrec.rroriginalttl = ttl_seconds;
10572 cr->resrec.rdlength = 0;
10573 cr->resrec.rdestimate = 0;
10574 cr->resrec.namehash = namehash;
10575 cr->resrec.rdatahash = 0;
10576 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10577 cr->resrec.rdata->MaxRDLength = 0;
10578
10579 cr->NextInKAList = mDNSNULL;
10580 cr->TimeRcvd = m->timenow;
10581 cr->DelayDelivery = 0;
10582 cr->NextRequiredQuery = m->timenow;
10583 cr->CRActiveQuestion = mDNSNULL;
10584 cr->UnansweredQueries = 0;
10585 cr->LastUnansweredTime = 0;
10586 cr->NextInCFList = mDNSNULL;
10587 cr->nsec = mDNSNULL;
10588 cr->soa = mDNSNULL;
10589 cr->CRDNSSECQuestion = 0;
10590 // Initialize to the basic one and the caller can set it to more
10591 // specific based on the response if any
10592 cr->responseFlags = ResponseFlags;
10593 }
10594
10595 mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10596 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10597 const mDNSInterfaceID InterfaceID)
10598 {
10599 mDNSInterfaceID ifid = InterfaceID;
10600 const mDNSu8 *const pkt = (mDNSu8 *)msg;
10601 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
10602 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10603 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
10604 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10605 mDNSu8 QR_OP;
10606 mDNSu8 *ptr = mDNSNULL;
10607 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10608 if (TLS) dstaddr = mDNSNULL;
10609
10610 #ifndef UNICAST_DISABLED
10611 if (mDNSSameAddress(srcaddr, &m->Router))
10612 {
10613 #ifdef _LEGACY_NAT_TRAVERSAL_
10614 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10615 {
10616 mDNS_Lock(m);
10617 LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10618 mDNS_Unlock(m);
10619 return;
10620 }
10621 #endif
10622 if (mDNSSameIPPort(srcport, NATPMPPort))
10623 {
10624 mDNS_Lock(m);
10625 uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10626 mDNS_Unlock(m);
10627 return;
10628 }
10629 }
10630 #ifdef _LEGACY_NAT_TRAVERSAL_
10631 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10632 #endif
10633
10634 #endif
10635 if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader))
10636 {
10637 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt));
10638 return;
10639 }
10640 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10641 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10642 ptr = (mDNSu8 *)&msg->h.numQuestions;
10643 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10644 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10645 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10646 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10647
10648 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10649
10650 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10651 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10652 if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10653
10654 mDNS_Lock(m);
10655 m->PktNum++;
10656 if (mDNSOpaque16IsZero(msg->h.id))
10657 {
10658 m->MPktNum++;
10659 #if APPLE_OSX_mDNSResponder
10660 // Track the number of multicast packets received from a source outside our subnet.
10661 // Check the destination address to avoid accounting for spurious packets that
10662 // comes in with message id zero.
10663 if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) && dstaddr &&
10664 mDNSAddressIsAllDNSLinkGroup(dstaddr))
10665 {
10666 m->RemoteSubnet++;
10667 }
10668 #endif // #if APPLE_OSX_mDNSResponder
10669 }
10670
10671 #ifndef UNICAST_DISABLED
10672 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10673 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10674 {
10675 ifid = mDNSInterface_Any;
10676 if (mDNS_PacketLoggingEnabled)
10677 DumpPacket(mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
10678 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10679 // Note: mDNSCore also needs to get access to received unicast responses
10680 }
10681 #endif
10682 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10683 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10684 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10685 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr, InterfaceID);
10686 else
10687 {
10688 if (mDNS_LoggingEnabled)
10689 {
10690 static int msgCount = 0;
10691 if (msgCount < 1000) {
10692 int i = 0;
10693 msgCount++;
10694 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10695 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt), InterfaceID);
10696 while (i < (int)(end - pkt))
10697 {
10698 char buffer[128];
10699 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10700 do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15);
10701 LogInfo("%s", buffer);
10702 }
10703 }
10704 }
10705 }
10706 // Packet reception often causes a change to the task list:
10707 // 1. Inbound queries can cause us to need to send responses
10708 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10709 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10710 // 4. Response packets that answer questions may cause our client to issue new questions
10711 mDNS_Unlock(m);
10712 }
10713
10714 // ***************************************************************************
10715 #if COMPILER_LIKES_PRAGMA_MARK
10716 #pragma mark -
10717 #pragma mark - Searcher Functions
10718 #endif
10719
10720 // Targets are considered the same if both queries are untargeted, or
10721 // if both are targeted to the same address+port
10722 // (If Target address is zero, TargetPort is undefined)
10723 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
10724 (mDNSSameAddress(& (A)->Target, & (B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
10725
10726 // SameQuestionKind is true if *both* questions are either multicast or unicast
10727 // TargetQID is used for this determination.
10728 #define SameQuestionKind(A,B) ((mDNSOpaque16IsZero(A) && mDNSOpaque16IsZero(B)) || \
10729 ((!mDNSOpaque16IsZero(A)) && (!mDNSOpaque16IsZero(B))))
10730
10731 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10732 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10733 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10734 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10735 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10736 //
10737 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10738 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10739 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10740 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10741 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10742 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10743 // breaks this design principle.
10744 //
10745
10746 // If IsLLQ(Q) is true, it means the question is both:
10747 // (a) long-lived and
10748 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10749 // for multicast questions, we don't want to treat LongLived as anything special
10750 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10751 #define IsAWDLIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10752
10753 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10754 {
10755 DNSQuestion *q;
10756 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10757 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10758 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10759 // further in the list.
10760 for (q = m->Questions; q && q != question; q=q->next) // Scan our list for another question
10761 if (q->InterfaceID == question->InterfaceID && // with the same InterfaceID,
10762 SameQTarget(q, question) && // and same unicast/multicast target settings
10763 q->qtype == question->qtype && // type,
10764 q->qclass == question->qclass && // class,
10765 IsLLQ(q) == IsLLQ(question) && // and long-lived status matches
10766 (!q->AuthInfo || question->AuthInfo) && // to avoid deadlock, don't make public query dup of a private one
10767 (q->AnonInfo == question->AnonInfo) && // Anonymous query not a dup of normal query
10768 (q->SuppressQuery == question->SuppressQuery) && // Questions that are suppressed/not suppressed
10769 (q->ValidationRequired == question->ValidationRequired) && // Questions that require DNSSEC validation
10770 (q->ValidatingResponse == question->ValidatingResponse) && // Questions that are validating responses using DNSSEC
10771 (q->DisallowPID == question->DisallowPID) && // Disallowing a PID should not affect a PID that is allowed
10772 (q->BrowseThreshold == question->BrowseThreshold) && // browse thresholds must match
10773 q->qnamehash == question->qnamehash &&
10774 (IsAWDLIncluded(q) == IsAWDLIncluded(question)) && // Inclusion of AWDL interface must match
10775 SameQuestionKind(q->TargetQID, question->TargetQID) && // mDNS or uDNS must match
10776 SameDomainName(&q->qname, &question->qname)) // and name
10777 return(q);
10778 return(mDNSNULL);
10779 }
10780
10781 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10782 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10783 {
10784 DNSQuestion *q;
10785 DNSQuestion *first = mDNSNULL;
10786
10787 // This is referring to some other question as duplicate. No other question can refer to this
10788 // question as a duplicate.
10789 if (question->DuplicateOf)
10790 {
10791 LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
10792 question, question->qname.c, DNSTypeName(question->qtype),
10793 question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
10794 return;
10795 }
10796
10797 for (q = m->Questions; q; q=q->next) // Scan our list of questions
10798 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
10799 {
10800 q->DuplicateOf = first;
10801 if (!first)
10802 {
10803 first = q;
10804 // If q used to be a duplicate, but now is not,
10805 // then inherit the state from the question that's going away
10806 q->LastQTime = question->LastQTime;
10807 q->ThisQInterval = question->ThisQInterval;
10808 q->ExpectUnicastResp = question->ExpectUnicastResp;
10809 q->LastAnswerPktNum = question->LastAnswerPktNum;
10810 q->RecentAnswerPkts = question->RecentAnswerPkts;
10811 q->RequestUnicast = question->RequestUnicast;
10812 q->LastQTxTime = question->LastQTxTime;
10813 q->CNAMEReferrals = question->CNAMEReferrals;
10814 q->nta = question->nta;
10815 q->servAddr = question->servAddr;
10816 q->servPort = question->servPort;
10817 q->qDNSServer = question->qDNSServer;
10818 q->validDNSServers = question->validDNSServers;
10819 q->unansweredQueries = question->unansweredQueries;
10820 q->noServerResponse = question->noServerResponse;
10821 q->triedAllServersOnce = question->triedAllServersOnce;
10822
10823 q->TargetQID = question->TargetQID;
10824 q->LocalSocket = question->LocalSocket;
10825 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10826
10827 q->state = question->state;
10828 // q->tcp = question->tcp;
10829 q->ReqLease = question->ReqLease;
10830 q->expire = question->expire;
10831 q->ntries = question->ntries;
10832 q->id = question->id;
10833
10834 question->LocalSocket = mDNSNULL;
10835 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
10836 // question->tcp = mDNSNULL;
10837
10838 if (q->LocalSocket)
10839 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10840
10841 if (q->nta)
10842 {
10843 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10844 q->nta->ZoneDataContext = q;
10845 }
10846
10847 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10848 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10849
10850 if (question->state == LLQ_Established)
10851 {
10852 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10853 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10854 }
10855
10856 SetNextQueryTime(m,q);
10857 }
10858 }
10859 }
10860
10861 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10862 {
10863 McastResolver **p = &m->McastResolvers;
10864 McastResolver *tmp = mDNSNULL;
10865
10866 if (!d) d = (const domainname *)"";
10867
10868 LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
10869
10870 mDNS_CheckLock(m);
10871
10872 while (*p) // Check if we already have this {interface, domain} tuple registered
10873 {
10874 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10875 {
10876 if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10877 (*p)->flags &= ~McastResolver_FlagDelete;
10878 tmp = *p;
10879 *p = tmp->next;
10880 tmp->next = mDNSNULL;
10881 }
10882 else
10883 p=&(*p)->next;
10884 }
10885
10886 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10887 else
10888 {
10889 // allocate, add to list
10890 *p = mDNSPlatformMemAllocate(sizeof(**p));
10891 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10892 else
10893 {
10894 (*p)->interface = interface;
10895 (*p)->flags = McastResolver_FlagNew;
10896 (*p)->timeout = timeout;
10897 AssignDomainName(&(*p)->domain, d);
10898 (*p)->next = mDNSNULL;
10899 }
10900 }
10901 return(*p);
10902 }
10903
10904 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10905 {
10906 mDNSs32 ptime = 0;
10907 if (server->penaltyTime != 0)
10908 {
10909 ptime = server->penaltyTime - m->timenow;
10910 if (ptime < 0)
10911 {
10912 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10913 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10914 // here
10915 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10916 ptime, server->penaltyTime, m->timenow);
10917 server->penaltyTime = 0;
10918 ptime = 0;
10919 }
10920 }
10921 return ptime;
10922 }
10923
10924 //Checks to see whether the newname is a better match for the name, given the best one we have
10925 //seen so far (given in bestcount).
10926 //Returns -1 if the newname is not a better match
10927 //Returns 0 if the newname is the same as the old match
10928 //Returns 1 if the newname is a better match
10929 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
10930 int bestcount)
10931 {
10932 // If the name contains fewer labels than the new server's domain or the new name
10933 // contains fewer labels than the current best, then it can't possibly be a better match
10934 if (namecount < newcount || newcount < bestcount) return -1;
10935
10936 // If there is no match, return -1 and the caller will skip this newname for
10937 // selection
10938 //
10939 // If we find a match and the number of labels is the same as bestcount, then
10940 // we return 0 so that the caller can do additional logic to pick one of
10941 // the best based on some other factors e.g., penaltyTime
10942 //
10943 // If we find a match and the number of labels is more than bestcount, then we
10944 // return 1 so that the caller can pick this over the old one.
10945 //
10946 // Note: newcount can either be equal or greater than bestcount beause of the
10947 // check above.
10948
10949 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
10950 return bestcount == newcount ? 0 : 1;
10951 else
10952 return -1;
10953 }
10954
10955 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10956 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10957 // names. In that case, we give a default timeout of 5 seconds
10958 #define DEFAULT_MCAST_TIMEOUT 5
10959 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
10960 {
10961 McastResolver *curmatch = mDNSNULL;
10962 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10963 McastResolver *curr;
10964 int bettermatch, currcount;
10965 for (curr = m->McastResolvers; curr; curr = curr->next)
10966 {
10967 currcount = CountLabels(&curr->domain);
10968 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10969 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10970 // the timeout value from the first one
10971 if (bettermatch == 1)
10972 {
10973 curmatch = curr;
10974 bestmatchlen = currcount;
10975 }
10976 }
10977 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
10978 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10979 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10980 }
10981
10982 // Returns true if it is a Domain Enumeration Query
10983 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
10984 {
10985 const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
10986 (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
10987 const domainname *d = qname;
10988 const mDNSu8 *label;
10989 int i = 0;
10990
10991 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10992 if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
10993
10994 label = (const mDNSu8 *)d;
10995 while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
10996 {
10997 if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
10998 i++;
10999 }
11000 if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
11001 {
11002 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
11003 return mDNSfalse;
11004 }
11005 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
11006
11007 // CountLabels already verified the number of labels
11008 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label
11009 label = (const mDNSu8 *)d;
11010 if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
11011 {
11012 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
11013 return(mDNSfalse);
11014 }
11015 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
11016
11017 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label
11018 label = (const mDNSu8 *)d;
11019 if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
11020 {
11021 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
11022 return(mDNSfalse);
11023 }
11024 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
11025
11026 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
11027
11028 return mDNStrue;
11029 }
11030
11031 // Note: InterfaceID is the InterfaceID of the question
11032 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11033 {
11034 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11035 // with "scoped" set to kScopeNone)
11036 //
11037 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11038 // with "scoped" set to kScopeInterfaceId) and their InterfaceIDs should match.
11039 //
11040 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11041 // with "scoped" set to kScopeServiceID) and their ServiceIDs should match.
11042 //
11043 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11044 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11045 //
11046 // If the first condition fails, following are the possible cases (the notes below are using
11047 // InterfaceID for discussion and the same holds good for ServiceID):
11048 //
11049 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11050 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11051 //
11052 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11053 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11054 // would fail in this case.
11055 //
11056 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11057 // should match (Refer to (2) above).
11058 //
11059 // Note: mDNSInterface_Unicast is used only by .local unicast questions and are treated as unscoped.
11060 // If a question is scoped both to InterfaceID and ServiceID, the question will be scoped to InterfaceID.
11061
11062 if (((d->scoped == kScopeNone) && ((!InterfaceID && ServiceID == -1) || InterfaceID == mDNSInterface_Unicast)) ||
11063 ((d->scoped == kScopeInterfaceID) && d->interface == InterfaceID) ||
11064 ((d->scoped == kScopeServiceID) && d->serviceID == ServiceID))
11065 {
11066 return mDNStrue;
11067 }
11068 return mDNSfalse;
11069 }
11070
11071 // Sets all the Valid DNS servers for a question
11072 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
11073 {
11074 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
11075 DNSServer *curr;
11076 int bettermatch, currcount;
11077 int index = 0;
11078 mDNSu32 timeout = 0;
11079 mDNSBool DEQuery;
11080
11081 question->validDNSServers = zeroOpaque128;
11082 DEQuery = DomainEnumQuery(&question->qname);
11083 for (curr = m->DNSServers; curr; curr = curr->next)
11084 {
11085 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
11086 // skip servers that will soon be deleted
11087 if (curr->flags & DNSServer_FlagDelete)
11088 {
11089 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
11090 continue;
11091 }
11092
11093 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11094 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11095 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11096 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11097 // match the scoped entries by mistake.
11098 //
11099 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11100
11101 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11102 if ((curr->scoped == kScopeInterfaceID && curr->interface == mDNSInterface_Any) || (curr->scoped == kScopeServiceID && curr->serviceID <= 0))
11103 {
11104 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]", curr->scoped, &curr->addr, curr->domain.c, curr->interface, curr->serviceID);
11105 continue;
11106 }
11107
11108 currcount = CountLabels(&curr->domain);
11109 if ((!curr->cellIntf || (!DEQuery && !(question->flags & kDNSServiceFlagsDenyCellular))) &&
11110 (!curr->isExpensive || !(question->flags & kDNSServiceFlagsDenyExpensive)) &&
11111 DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
11112 {
11113 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
11114
11115 // If we found a better match (bettermatch == 1) then clear all the bits
11116 // corresponding to the old DNSServers that we have may set before and start fresh.
11117 // If we find an equal match, then include that DNSServer also by setting the corresponding
11118 // bit
11119 if ((bettermatch == 1) || (bettermatch == 0))
11120 {
11121 bestmatchlen = currcount;
11122 if (bettermatch)
11123 {
11124 debugf("SetValidDNSServers: Resetting all the bits");
11125 question->validDNSServers = zeroOpaque128;
11126 timeout = 0;
11127 }
11128 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11129 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
11130 curr->interface);
11131 timeout += curr->timeout;
11132 if (DEQuery)
11133 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->cellIntf);
11134 bit_set_opaque128(question->validDNSServers, index);
11135 }
11136 }
11137 index++;
11138 }
11139 question->noServerResponse = 0;
11140
11141 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x%x%x for question %p %##s (%s)",
11142 question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
11143 // If there are no matching resolvers, then use the default timeout value.
11144 // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
11145 return ((question->ProxyQuestion || question->ValidatingResponse) ? DEFAULT_UDNSSEC_TIMEOUT : timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
11146 }
11147
11148 // Get the Best server that matches a name. If you find penalized servers, look for the one
11149 // that will come out of the penalty box soon
11150 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits,
11151 int *selected, mDNSBool nameMatch)
11152 {
11153 DNSServer *curmatch = mDNSNULL;
11154 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
11155 DNSServer *curr;
11156 mDNSs32 bestPenaltyTime, currPenaltyTime;
11157 int bettermatch, currcount;
11158 int index = 0;
11159 int currindex = -1;
11160
11161 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
11162 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
11163 for (curr = m->DNSServers; curr; curr = curr->next)
11164 {
11165 // skip servers that will soon be deleted
11166 if (curr->flags & DNSServer_FlagDelete)
11167 {
11168 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
11169 continue;
11170 }
11171
11172 // Check if this is a valid DNSServer
11173 if (!bit_get_opaque64(validBits, index))
11174 {
11175 debugf("GetBestServer: continuing for index %d", index);
11176 index++;
11177 continue;
11178 }
11179
11180 currcount = CountLabels(&curr->domain);
11181 currPenaltyTime = PenaltyTimeForServer(m, curr);
11182
11183 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11184 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
11185
11186 // If there are multiple best servers for a given question, we will pick the first one
11187 // if none of them are penalized. If some of them are penalized in that list, we pick
11188 // the least penalized one. BetterMatchForName walks through all best matches and
11189 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11190 // in the list when there are no penalized servers and least one among them
11191 // when there are some penalized servers.
11192
11193 if (DNSServerMatch(curr, InterfaceID, ServiceID))
11194 {
11195
11196 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11197 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11198 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11199 // part and still do some redundant steps e.g., InterfaceID match
11200
11201 if (nameMatch)
11202 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
11203 else
11204 bettermatch = 0;
11205
11206 // If we found a better match (bettermatch == 1) then we don't need to
11207 // compare penalty times. But if we found an equal match, then we compare
11208 // the penalty times to pick a better match
11209
11210 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
11211 {
11212 currindex = index;
11213 curmatch = curr;
11214 bestmatchlen = currcount;
11215 bestPenaltyTime = currPenaltyTime;
11216 }
11217 }
11218 index++;
11219 }
11220 if (selected) *selected = currindex;
11221 return curmatch;
11222 }
11223
11224 // Look up a DNS Server, matching by name and InterfaceID
11225 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11226 {
11227 DNSServer *curmatch = mDNSNULL;
11228 char *ifname = mDNSNULL; // for logging purposes only
11229 mDNSOpaque128 allValid;
11230
11231 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
11232 InterfaceID = mDNSNULL;
11233
11234 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
11235
11236 // By passing in all ones, we make sure that every DNS server is considered
11237 allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF;
11238
11239 curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
11240
11241 if (curmatch != mDNSNULL)
11242 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch->addr,
11243 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11244 InterfaceID, name);
11245 else
11246 LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname ? ifname : "None", InterfaceID, name);
11247
11248 return(curmatch);
11249 }
11250
11251 // Look up a DNS Server for a question within its valid DNSServer bits
11252 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
11253 {
11254 DNSServer *curmatch = mDNSNULL;
11255 char *ifname = mDNSNULL; // for logging purposes only
11256 mDNSInterfaceID InterfaceID = question->InterfaceID;
11257 const domainname *name = &question->qname;
11258 int currindex;
11259
11260 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
11261 InterfaceID = mDNSNULL;
11262
11263 if (InterfaceID)
11264 ifname = InterfaceNameForID(m, InterfaceID);
11265
11266 if (!mDNSOpaque128IsZero(&question->validDNSServers))
11267 {
11268 curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
11269 if (currindex != -1)
11270 bit_clr_opaque128(question->validDNSServers, currindex);
11271 }
11272
11273 if (curmatch != mDNSNULL)
11274 {
11275 LogInfo("GetServerForQuestion: %p DNS server (%p) %#a:%d (Penalty Time Left %d) (Scope %s:%p:%d) for %##s (%s)",
11276 question, curmatch, &curmatch->addr, mDNSVal16(curmatch->port),
11277 (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11278 InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
11279 }
11280 else
11281 {
11282 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p:%d) for %##s (%s)",
11283 question, ifname ? ifname : "None", InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
11284 }
11285
11286 return(curmatch);
11287 }
11288
11289
11290 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
11291 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
11292
11293 // Called in normal client context (lock not held)
11294 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
11295 {
11296 DNSQuestion *q;
11297 mDNS_Lock(m);
11298 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
11299 n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
11300 for (q = m->Questions; q; q=q->next)
11301 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
11302 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
11303 #if APPLE_OSX_mDNSResponder
11304 UpdateAutoTunnelDomainStatuses(m);
11305 #endif
11306 mDNS_Unlock(m);
11307 }
11308
11309 mDNSlocal mDNSBool IsPrivateDomain(mDNS *const m, DNSQuestion *q)
11310 {
11311 DomainAuthInfo *AuthInfo;
11312 // Skip Private domains as we have special addresses to get the hosts in the Private domain
11313 AuthInfo = GetAuthInfoForName_internal(m, &q->qname);
11314 if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
11315 {
11316 debugf("IsPrivateDomain: %##s true", q->qname.c);
11317 return mDNStrue;
11318 }
11319 else
11320 {
11321 debugf("IsPrivateDomain: %##s false", q->qname.c);
11322 return mDNSfalse;
11323 }
11324 }
11325
11326 #define TrueFalseStr(X) ((X) ? "true" : "false")
11327
11328 // This function takes the DNSServer as a separate argument because sometimes the
11329 // caller has not yet assigned the DNSServer, but wants to evaluate the SuppressQuery
11330 // status before switching to it.
11331 mDNSlocal mDNSBool ShouldSuppressUnicastQuery(mDNS *const m, DNSQuestion *q, DNSServer *d)
11332 {
11333 // Some callers don't check for the qtype
11334 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
11335 {
11336 LogDebug("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
11337 return mDNSfalse;
11338 }
11339
11340 // Private domains are exempted irrespective of what the DNSServer says
11341 if (IsPrivateDomain(m, q))
11342 {
11343 LogDebug("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, Private Domain", q->qname.c, DNSTypeName(q->qtype));
11344 return mDNSfalse;
11345 }
11346
11347 if (!d)
11348 {
11349 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, as the DNS server is NULL", q->qname.c, DNSTypeName(q->qtype));
11350 return mDNStrue;
11351 }
11352
11353 // Check if the DNS Configuration allows A/AAAA queries to be sent
11354 if ((q->qtype == kDNSType_A) && d->req_A)
11355 {
11356 // The server's configuration allows A record queries, so don't suppress this query unless
11357 // 1. the interface associated with the server is CLAT46; and
11358 // 2. the query has the kDNSServiceFlagsPathEvaluationDone flag, which indicates that it came from libnetcore.
11359 // See <rdar://problem/42672030> for more info.
11360 if (!(d->isCLAT46 && (q->flags & kDNSServiceFlagsPathEvaluationDone)))
11361 {
11362 LogDebug("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows A queries", q->qname.c,
11363 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
11364 return mDNSfalse;
11365 }
11366 }
11367 if ((q->qtype == kDNSType_AAAA) && d->req_AAAA)
11368 {
11369 LogDebug("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows AAAA queries", q->qname.c,
11370 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
11371 return mDNSfalse;
11372 }
11373 #if USE_DNS64
11374 if (DNS64IsQueryingARecord(q->dns64.state))
11375 {
11376 LogDebug("ShouldSuppressUnicastQuery: DNS64 query not suppressed for %##s, qtype %s", q->qname.c, DNSTypeName(q->qtype));
11377 return mDNSfalse;
11378 }
11379 #endif
11380
11381 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, since DNS Configuration does not allow (req_A %s, req_AAAA %s, CLAT46 %s)",
11382 q->qname.c, DNSTypeName(q->qtype), TrueFalseStr(d->req_A), TrueFalseStr(d->req_AAAA), TrueFalseStr(d->isCLAT46));
11383
11384 return mDNStrue;
11385 }
11386
11387 mDNSlocal mDNSBool ShouldSuppressDotLocalQuery(mDNS *const m, DNSQuestion *q)
11388 {
11389 NetworkInterfaceInfo *intf;
11390 AuthRecord *rr;
11391 mDNSBool ret;
11392
11393 // Check to see if there is at least one interface other than loopback and don't suppress
11394 // .local questions if you find one. If we have at least one interface, it means that
11395 // we can send unicast queries for the .local name and we don't want to suppress
11396 // multicast in that case as upper layers don't know how to handle if we return a
11397 // negative response for multicast followed by a positive response for unicast.
11398 //
11399 // Note: we used to check for multicast capable interfaces instead of just any interface
11400 // present. That did not work in the case where we have a valid interface for unicast
11401 // but not multicast capable e.g., cellular, as we ended up delivering a negative response
11402 // first and the upper layer did not wait for the positive response that came later.
11403 for (intf = m->HostInterfaces; intf; intf = intf->next)
11404 {
11405 if (intf->InterfaceActive && !intf->Loopback)
11406 {
11407 LogInfo("ShouldSuppressDotLocalQuery: Found interface %s, not suppressing", intf->ifname);
11408 return mDNSfalse;
11409 }
11410 }
11411
11412 // 1. If we find a LocalOnly or P2P record answering this question, then don't suppress it.
11413 // Set m->CurrentQuestion as it is required by AnswerQuestionWithLORecord.
11414 m->CurrentQuestion = q;
11415 ret = AnswerQuestionWithLORecord(m, q, mDNStrue);
11416 m->CurrentQuestion = mDNSNULL;
11417
11418 if (ret)
11419 {
11420 LogInfo("ShouldSuppressDotLocalQuery: Found LocalOnly record for %##s (%s), not suppressing", q->qname.c,
11421 DNSTypeName(q->qtype));
11422 return mDNSfalse;
11423 }
11424
11425 // 2. If we find a local AuthRecord answering this question, then don't suppress it.
11426 for (rr = m->ResourceRecords; rr; rr = rr->next)
11427 {
11428 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
11429 {
11430 LogInfo("ShouldSuppressDotLocalQuery: Found resource record %s for %##s (%s) not suppressing", ARDisplayString(m, rr),
11431 q->qname.c, DNSTypeName(q->qtype));
11432 return mDNSfalse;
11433 }
11434 }
11435 return mDNStrue;
11436 }
11437
11438 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, DNSQuestion *q)
11439 {
11440 if (q->InterfaceID == mDNSInterface_LocalOnly)
11441 {
11442 LogInfo("ShouldSuppressQuery: LocalOnly query not suppressed for %##s, qtype %s", q->qname.c, DNSTypeName(q->qtype));
11443 return mDNSfalse;
11444 }
11445
11446 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
11447 {
11448 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
11449 return mDNSfalse;
11450 }
11451
11452 // We still want the ability to be able to listen to the local services and hence
11453 // don't fail .local query if we have local records that can potentially answer
11454 // the question.
11455 if (q->InterfaceID != mDNSInterface_Unicast && IsLocalDomain(&q->qname))
11456 {
11457 if (!ShouldSuppressDotLocalQuery(m, q))
11458 {
11459 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11460 return mDNSfalse;
11461 }
11462 else
11463 {
11464 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11465 return mDNStrue;
11466 }
11467 }
11468
11469 return (ShouldSuppressUnicastQuery(m, q, q->qDNSServer));
11470 }
11471
11472 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11473 {
11474 CacheRecord *rr;
11475 CacheGroup *cg;
11476
11477 cg = CacheGroupForName(m, q->qnamehash, &q->qname);
11478 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
11479 {
11480 // Don't deliver RMV events for negative records
11481 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
11482 {
11483 LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
11484 CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
11485 continue;
11486 }
11487
11488 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
11489 {
11490 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11491 q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
11492
11493 q->CurrentAnswers--;
11494 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11495 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11496
11497 if (rr->CRActiveQuestion == q)
11498 {
11499 DNSQuestion *qptr;
11500 // If this was the active question for this cache entry, it was the one that was
11501 // responsible for keeping the cache entry fresh when the cache entry was reaching
11502 // its expiry. We need to handover the responsibility to someone else. Otherwise,
11503 // when the cache entry is about to expire, we won't find an active question
11504 // (pointed by CRActiveQuestion) to refresh the cache.
11505 for (qptr = m->Questions; qptr; qptr=qptr->next)
11506 if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
11507 break;
11508
11509 if (qptr)
11510 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
11511 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
11512 qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
11513
11514 rr->CRActiveQuestion = qptr; // Question used to be active; new value may or may not be null
11515 if (!qptr) m->rrcache_active--; // If no longer active, decrement rrcache_active count
11516 }
11517 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
11518 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
11519 }
11520 }
11521 }
11522
11523 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11524 {
11525 DNSQuestion *q;
11526 for (q = m->NewQuestions; q; q = q->next)
11527 if (q == question) return mDNStrue;
11528 return mDNSfalse;
11529 }
11530
11531 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11532 {
11533 AuthRecord *rr;
11534 AuthGroup *ag;
11535
11536 if (m->CurrentQuestion)
11537 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11538 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11539
11540 if (IsQuestionNew(m, q))
11541 {
11542 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11543 return mDNStrue;
11544 }
11545 m->CurrentQuestion = q;
11546 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
11547 if (ag)
11548 {
11549 for (rr = ag->members; rr; rr=rr->next)
11550 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11551 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11552 {
11553 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11554 ARDisplayString(m, rr));
11555 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11556 {
11557 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11558 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11559 q->CurrentAnswers, q->LOAddressAnswers);
11560 continue;
11561 }
11562 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again
11563 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11564 }
11565 }
11566 m->CurrentQuestion = mDNSNULL;
11567 return mDNStrue;
11568 }
11569
11570 // Returns false if the question got deleted while delivering the RMV events
11571 // The caller should handle the case
11572 mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11573 {
11574 if (m->CurrentQuestion)
11575 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11576 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11577
11578 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11579 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11580 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11581 {
11582 m->CurrentQuestion = q;
11583 CacheRecordRmvEventsForCurrentQuestion(m, q);
11584 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11585 m->CurrentQuestion = mDNSNULL;
11586 }
11587 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11588 return mDNStrue;
11589 }
11590
11591 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11592 {
11593 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11594 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11595 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11596 if (q->SuppressQuery)
11597 {
11598 q->SuppressQuery = mDNSfalse;
11599 if (!CacheRecordRmvEventsForQuestion(m, q))
11600 {
11601 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from cache");
11602 return;
11603 }
11604 q->SuppressQuery = mDNStrue;
11605 }
11606
11607 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11608 // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
11609 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11610 // the restart will not be a duplicate ADD
11611 if (!LocalRecordRmvEventsForQuestion(m, q))
11612 {
11613 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords");
11614 return;
11615 }
11616
11617 // There are two cases here.
11618 //
11619 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11620 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11621 // because when we get the response, if we had entries in the cache already, it will not answer
11622 // this question if the cache entry did not change. Hence, we need to restart
11623 // the query so that it can be answered from the cache.
11624 //
11625 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11626 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11627 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
11628 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11629 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
11630 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11631 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11632 // This affects both efficiency and also the current design where there is only one active question
11633 // pointed to from a cache entry.
11634 //
11635 // We restart queries in a two step process by first calling stop and build a temporary list which we
11636 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11637 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11638 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11639 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11640 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11641 //
11642 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11643
11644 LogInfo("SuppressStatusChanged: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11645 mDNS_StopQuery_internal(m, q);
11646 q->next = *restart;
11647 *restart = q;
11648 }
11649
11650 // The caller should hold the lock
11651 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11652 {
11653 DNSQuestion *q;
11654 DNSQuestion *restart = mDNSNULL;
11655
11656 // We look through all questions including new questions. During network change events,
11657 // we potentially restart questions here in this function that ends up as new questions,
11658 // which may be suppressed at this instance. Before it is handled we get another network
11659 // event that changes the status e.g., address becomes available. If we did not process
11660 // new questions, we would never change its SuppressQuery status.
11661 //
11662 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11663 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11664 // *any* other question which could be the next one that we may process here. RestartQuestion
11665 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11666 // if the "next" question is stopped while the CurrentQuestion is stopped
11667 if (m->RestartQuestion)
11668 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11669 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11670 m->RestartQuestion = m->Questions;
11671 while (m->RestartQuestion)
11672 {
11673 q = m->RestartQuestion;
11674 m->RestartQuestion = q->next;
11675 if (q->SuppressUnusable)
11676 {
11677 mDNSBool old = q->SuppressQuery;
11678 q->SuppressQuery = ShouldSuppressQuery(m, q);
11679 if (q->SuppressQuery != old)
11680 {
11681 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11682 // followed by a negative cache response. Temporarily turn off suppression so that
11683 // AnswerCurrentQuestionWithResourceRecord can answer the question
11684 SuppressStatusChanged(m, q, &restart);
11685 }
11686 }
11687 }
11688 while (restart)
11689 {
11690 q = restart;
11691 restart = restart->next;
11692 q->next = mDNSNULL;
11693 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11694 mDNS_StartQuery_internal(m, q);
11695 }
11696 }
11697
11698 mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11699 {
11700 DNSQuestion *q;
11701 DNSQuestion *restart = mDNSNULL;
11702
11703 if (m->RestartQuestion)
11704 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11705 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11706 m->RestartQuestion = m->Questions;
11707 while (m->RestartQuestion)
11708 {
11709 q = m->RestartQuestion;
11710 m->RestartQuestion = q->next;
11711 if (q->Restart)
11712 {
11713 if (mDNSOpaque16IsZero(q->TargetQID))
11714 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11715
11716 q->Restart = 0;
11717 SuppressStatusChanged(m, q, &restart);
11718 }
11719 }
11720 while (restart)
11721 {
11722 q = restart;
11723 restart = restart->next;
11724 q->next = mDNSNULL;
11725 LogInfo("RestartUnicastQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11726 mDNS_StartQuery_internal(m, q);
11727 }
11728 }
11729
11730
11731 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11732 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11733 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11734 {
11735
11736 if (question->Target.type && !ValidQuestionTarget(question))
11737 {
11738 LogMsg("ValidateParameters: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
11739 question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
11740 question->Target.type = mDNSAddrType_None;
11741 }
11742
11743 // If no question->Target specified, clear TargetPort
11744 if (!question->Target.type)
11745 question->TargetPort = zeroIPPort;
11746
11747 if (!ValidateDomainName(&question->qname))
11748 {
11749 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11750 return(mStatus_Invalid);
11751 }
11752
11753 // If this question is referencing a specific interface, verify it exists
11754 if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID) && question->InterfaceID != mDNSInterface_Unicast)
11755 {
11756 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11757 if (!intf)
11758 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11759 (uint32_t)question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
11760 }
11761
11762 return(mStatus_NoError);
11763 }
11764
11765 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11766 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
11767 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11768 {
11769 // First reset all DNS Configuration
11770 question->qDNSServer = mDNSNULL;
11771 question->validDNSServers = zeroOpaque128;
11772 question->triedAllServersOnce = 0;
11773 question->noServerResponse = 0;
11774 question->StopTime = (question->TimeoutQuestion) ? question->StopTime : 0;
11775 #if AWD_METRICS
11776 mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
11777 question->metrics.expiredAnswerState = (question->allowExpired != AllowExpired_None) ? ExpiredAnswer_Allowed : ExpiredAnswer_None;
11778 #endif
11779
11780 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11781 if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion)
11782 return;
11783 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11784 if (!mDNSOpaque16IsZero(question->TargetQID))
11785 {
11786 mDNSu32 timeout = SetValidDNSServers(m, question);
11787 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11788 // So if a question is restarted when a network change occurs, the StopTime is not reset.
11789 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11790 // it gets a full timeout value even if the original question times out earlier.
11791 if (question->TimeoutQuestion && !question->StopTime)
11792 {
11793 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11794 LogInfo("InitDNSConfig: Setting StopTime on the uDNS question %p %##s (%s)", question, question->qname.c, DNSTypeName(question->qtype));
11795 }
11796
11797 question->qDNSServer = GetServerForQuestion(m, question);
11798 LogDebug("InitDNSConfig: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
11799 question, question->qname.c, DNSTypeName(question->qtype), timeout,
11800 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11801 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11802 }
11803 else if (question->TimeoutQuestion && !question->StopTime)
11804 {
11805 // If the question is to be timed out and its a multicast, local-only or P2P case,
11806 // then set it's stop time.
11807 mDNSu32 timeout = LocalOnlyOrP2PInterface(question->InterfaceID) ?
11808 DEFAULT_LO_OR_P2P_TIMEOUT : GetTimeoutForMcastQuestion(m, question);
11809 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11810 LogInfo("InitDNSConfig: Setting StopTime on question %p %##s (%s)", question, question->qname.c, DNSTypeName(question->qtype));
11811 }
11812 // Set StopTime here since it is a part of DNS Configuration
11813 if (question->StopTime)
11814 SetNextQueryStopTime(m, question);
11815 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11816 // will never be transmitted on the wire.
11817 if (!(LocalOnlyOrP2PInterface(question->InterfaceID)))
11818 SetNextQueryTime(m,question);
11819 }
11820
11821 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11822 // state fields of the DNS Question. These are independent of the Client layer.
11823 mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question)
11824 {
11825 int i;
11826 mDNSBool isBlocked = mDNSfalse;
11827
11828 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11829 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11830 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11831 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11832 // that to go out immediately.
11833 question->next = mDNSNULL;
11834 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11835 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11836 // the question list to check if ThisQInterval is negative which means the question has been
11837 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11838 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11839 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11840 // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11841 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
11842 question->qnamehash = DomainNameHashValue(&question->qname);
11843 question->DelayAnswering = mDNSOpaque16IsZero(question->TargetQID) ? CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash) : 0;
11844 question->LastQTime = m->timenow;
11845 question->ExpectUnicastResp = 0;
11846 question->LastAnswerPktNum = m->PktNum;
11847 question->RecentAnswerPkts = 0;
11848 question->CurrentAnswers = 0;
11849
11850 #if APPLE_OSX_mDNSResponder
11851
11852 // Initial browse threshold used by Finder.
11853 #define mDNSFinderBrowseThreshold 20
11854
11855 // Set the threshold at which we move to a passive browse state,
11856 // not actively sending queries.
11857 if (question->flags & kDNSServiceFlagsThresholdOne)
11858 question->BrowseThreshold = 1;
11859 else if (question->flags & kDNSServiceFlagsThresholdFinder)
11860 question->BrowseThreshold = mDNSFinderBrowseThreshold;
11861 else
11862 question->BrowseThreshold = 0;
11863
11864 #else // APPLE_OSX_mDNSResponder
11865 question->BrowseThreshold = 0;
11866 #endif // APPLE_OSX_mDNSResponder
11867 question->CachedAnswerNeedsUpdate = mDNSfalse;
11868
11869 question->LargeAnswers = 0;
11870 question->UniqueAnswers = 0;
11871 question->LOAddressAnswers = 0;
11872 question->FlappingInterface1 = mDNSNULL;
11873 question->FlappingInterface2 = mDNSNULL;
11874
11875 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11876 // since we would already have the question->ServiceID in that case.
11877 if (!(question->flags & kDNSServiceFlagsServiceIndex))
11878 {
11879 #if APPLE_OSX_mDNSResponder
11880 mDNSPlatformGetDNSRoutePolicy(question, &isBlocked);
11881 #else
11882 question->ServiceID = -1;
11883 #endif
11884 }
11885 else
11886 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
11887 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
11888
11889 InitDNSConfig(m, question);
11890
11891 question->AuthInfo = GetAuthInfoForQuestion(m, question);
11892 question->SuppressQuery = 0;
11893 if (question->SuppressUnusable)
11894 question->SuppressQuery = ShouldSuppressQuery(m, question);
11895
11896 // If ServiceID is 0 or the policy disallows making DNS requests,
11897 // set DisallowPID
11898 question->DisallowPID = (question->ServiceID == 0 || isBlocked);
11899 if (question->DisallowPID)
11900 LogInfo("InitCommonState: Query suppressed for %##s (%s), PID %d/ServiceID %d not allowed", question->qname.c,
11901 DNSTypeName(question->qtype), question->pid, question->ServiceID);
11902
11903 question->NextInDQList = mDNSNULL;
11904 question->SendQNow = mDNSNULL;
11905 question->SendOnAll = mDNSfalse;
11906 question->RequestUnicast = kDefaultRequestUnicastCount;
11907
11908 #if APPLE_OSX_mDNSResponder
11909 // Set the QU bit in the first query for the following options.
11910 if ((question->flags & kDNSServiceFlagsUnicastResponse) || (question->flags & kDNSServiceFlagsThresholdFinder))
11911 {
11912 question->RequestUnicast = SET_QU_IN_FIRST_QUERY;
11913 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11914 DNSTypeName(question->qtype));
11915 }
11916 #endif // APPLE_OSX_mDNSResponder
11917
11918 question->LastQTxTime = m->timenow;
11919 question->CNAMEReferrals = 0;
11920
11921 question->WakeOnResolveCount = 0;
11922 if (question->WakeOnResolve)
11923 {
11924 question->WakeOnResolveCount = InitialWakeOnResolveCount;
11925 }
11926
11927 for (i=0; i<DupSuppressInfoSize; i++)
11928 question->DupSuppress[i].InterfaceID = mDNSNULL;
11929
11930 question->Restart = 0;
11931
11932 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11933 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11934 NextQSendTime(question) - m->timenow,
11935 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11936 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11937
11938 if (question->DelayAnswering)
11939 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11940 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11941 }
11942
11943 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11944 mDNSlocal void InitWABState(DNSQuestion *const question)
11945 {
11946 // We'll create our question->LocalSocket on demand, if needed.
11947 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11948 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11949 // NAT mapping for receiving inbound add/remove events.
11950 question->LocalSocket = mDNSNULL;
11951 question->unansweredQueries = 0;
11952 question->nta = mDNSNULL;
11953 question->servAddr = zeroAddr;
11954 question->servPort = zeroIPPort;
11955 question->tcp = mDNSNULL;
11956 question->NoAnswer = NoAnswer_Normal;
11957 }
11958
11959 mDNSlocal void InitLLQNATState(mDNS *const m)
11960 {
11961 // If we don't have our NAT mapping active, start it now
11962 if (!m->LLQNAT.clientCallback)
11963 {
11964 m->LLQNAT.Protocol = NATOp_MapUDP;
11965 m->LLQNAT.IntPort = m->UnicastPort4;
11966 m->LLQNAT.RequestedPort = m->UnicastPort4;
11967 m->LLQNAT.clientCallback = LLQNATCallback;
11968 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal just started
11969 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11970 }
11971 }
11972
11973 mDNSlocal void InitLLQState(DNSQuestion *const question)
11974 {
11975 question->state = LLQ_InitialRequest;
11976 question->ReqLease = 0;
11977 question->expire = 0;
11978 question->ntries = 0;
11979 question->id = zeroOpaque64;
11980 }
11981
11982 #ifdef DNS_PUSH_ENABLED
11983 mDNSlocal void InitDNSPNState(DNSQuestion *const question)
11984 {
11985 question->dnsPushState = DNSPUSH_INIT;
11986 }
11987 #endif // DNS_PUSH_ENABLED
11988
11989 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11990 // DNSSEC & DNS Proxy fields of the DNS Question.
11991 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11992 {
11993 (void) m;
11994
11995 // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11996 // or the request is going over cellular interface.
11997 //
11998 // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11999 // at ValidationRequired setting also.
12000 if (question->qDNSServer)
12001 {
12002 if (question->qDNSServer->cellIntf)
12003 {
12004 debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question->qname.c, DNSTypeName(question->qtype));
12005 question->ValidationRequired = mDNSfalse;
12006 }
12007 if (DNSSECOptionalQuestion(question) && !(question->qDNSServer->req_DO))
12008 {
12009 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
12010 question->qname.c, DNSTypeName(question->qtype));
12011 question->ValidationRequired = DNSSEC_VALIDATION_NONE;
12012 }
12013 }
12014 question->ValidationState = (question->ValidationRequired ? DNSSECValRequired : DNSSECValNotRequired);
12015 question->ValidationStatus = 0;
12016 question->responseFlags = zeroID;
12017 }
12018
12019 // Once the question is completely initialized including the duplicate logic, this function
12020 // is called to finalize the unicast question which requires flushing the cache if needed,
12021 // activating the query etc.
12022 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question)
12023 {
12024 // Ensure DNS related info of duplicate question is same as the orig question
12025 if (question->DuplicateOf)
12026 {
12027 question->validDNSServers = question->DuplicateOf->validDNSServers;
12028 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
12029 // then we log a line as it could indicate an issue
12030 if (question->DuplicateOf->qDNSServer == mDNSNULL)
12031 {
12032 if (question->qDNSServer)
12033 LogInfo("FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(%#a:%d) but original question(%p) has no DNS Server! %##s (%s)",
12034 question, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
12035 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort),
12036 question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype));
12037 }
12038 question->qDNSServer = question->DuplicateOf->qDNSServer;
12039 LogInfo("FinalizeUnicastQuestion: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
12040 question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype),
12041 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
12042 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
12043 }
12044
12045 ActivateUnicastQuery(m, question, mDNSfalse);
12046
12047 if (!question->DuplicateOf && DNSSECQuestion(question))
12048 {
12049 // For DNSSEC questions, we need to have the RRSIGs also for verification.
12050 CheckForDNSSECRecords(m, question);
12051 }
12052 if (question->LongLived)
12053 {
12054 // Unlike other initializations, InitLLQNATState should be done after
12055 // we determine that it is a unicast question. LongLived is set for
12056 // both multicast and unicast browse questions but we should initialize
12057 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
12058 // start the NAT traversal that is not needed.
12059 InitLLQNATState(m);
12060 #if APPLE_OSX_mDNSResponder
12061 UpdateAutoTunnelDomainStatuses(m);
12062 #endif
12063 }
12064 }
12065
12066 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
12067 {
12068 DNSQuestion **q;
12069 mStatus vStatus;
12070
12071 // First check for cache space (can't do queries if there is no cache space allocated)
12072 if (m->rrcache_size == 0)
12073 return(mStatus_NoCache);
12074
12075 vStatus = ValidateParameters(m, question);
12076 if (vStatus)
12077 return(vStatus);
12078
12079 #ifdef USE_LIBIDN
12080 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12081 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12082 if (IsHighASCIILabel(LastLabel(&question->qname)))
12083 {
12084 domainname newname;
12085 if (PerformNextPunycodeConversion(question, &newname))
12086 AssignDomainName(&question->qname, &newname);
12087 }
12088 #endif // USE_LIBIDN
12089
12090 question->TargetQID =
12091 #ifndef UNICAST_DISABLED
12092 (question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
12093 #endif // UNICAST_DISABLED
12094 zeroID;
12095 debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12096
12097 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12098 q = &m->Questions;
12099 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12100 q = &m->LocalOnlyQuestions;
12101 while (*q && *q != question)
12102 q=&(*q)->next;
12103
12104 if (*q)
12105 {
12106 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12107 question->qname.c, DNSTypeName(question->qtype), question);
12108 return(mStatus_AlreadyRegistered);
12109 }
12110 *q = question;
12111
12112 // Intialize the question. The only ordering constraint we have today is that
12113 // InitDNSSECProxyState should be called after the DNS server is selected (in
12114 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12115 // validation.
12116
12117 InitCommonState(m, question);
12118 InitWABState(question);
12119 InitLLQState(question);
12120 #ifdef DNS_PUSH_ENABLED
12121 InitDNSPNState(question);
12122 #endif // DNS_PUSH_ENABLED
12123 InitDNSSECProxyState(m, question);
12124
12125 // FindDuplicateQuestion should be called last after all the intialization
12126 // as the duplicate logic could be potentially based on any field in the
12127 // question.
12128 question->DuplicateOf = FindDuplicateQuestion(m, question);
12129 if (question->DuplicateOf)
12130 question->AuthInfo = question->DuplicateOf->AuthInfo;
12131
12132 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12133 {
12134 if (!m->NewLocalOnlyQuestions)
12135 m->NewLocalOnlyQuestions = question;
12136 }
12137 else
12138 {
12139 if (!m->NewQuestions)
12140 m->NewQuestions = question;
12141
12142 // If the question's id is non-zero, then it's Wide Area
12143 // MUST NOT do this Wide Area setup until near the end of
12144 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12145 // NS, etc.) and if we haven't finished setting up our own question and setting
12146 // m->NewQuestions if necessary then we could end up recursively re-entering
12147 // this routine with the question list data structures in an inconsistent state.
12148 if (!mDNSOpaque16IsZero(question->TargetQID))
12149 {
12150 FinalizeUnicastQuestion(m, question);
12151 }
12152 else
12153 {
12154 #if BONJOUR_ON_DEMAND
12155 m->NumAllInterfaceQuestions++;
12156 LogInfo("mDNS_StartQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
12157 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
12158 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12159 {
12160 m->NextBonjourDisableTime = 0;
12161 if (m->BonjourEnabled == 0)
12162 {
12163 // Enable Bonjour immediately by scheduling network changed processing where
12164 // we will join the multicast group on each active interface.
12165 m->BonjourEnabled = 1;
12166 m->NetworkChanged = m->timenow;
12167 }
12168 }
12169 #endif // BONJOUR_ON_DEMAND
12170 if (question->WakeOnResolve)
12171 {
12172 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
12173 mDNS_PurgeBeforeResolve(m, question);
12174 }
12175 }
12176 }
12177
12178 return(mStatus_NoError);
12179 }
12180
12181 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12182 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
12183 {
12184 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
12185 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12186 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12187 // call it again
12188 if (nta->question.ThisQInterval != -1)
12189 {
12190 mDNS_StopQuery_internal(m, &nta->question);
12191 if (nta->question.ThisQInterval != -1)
12192 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
12193 }
12194 mDNSPlatformMemFree(nta);
12195 }
12196
12197 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
12198 {
12199 CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12200 CacheRecord *rr;
12201 DNSQuestion **qp = &m->Questions;
12202
12203 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12204
12205 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12206 qp = &m->LocalOnlyQuestions;
12207 while (*qp && *qp != question) qp=&(*qp)->next;
12208 if (*qp) *qp = (*qp)->next;
12209 else
12210 {
12211 #if !ForceAlerts
12212 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
12213 #endif
12214 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
12215 return(mStatus_BadReferenceErr);
12216 }
12217
12218 #if BONJOUR_ON_DEMAND
12219 if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID))
12220 {
12221 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12222 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
12223 m->NumAllInterfaceQuestions--;
12224 LogInfo("mDNS_StopQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
12225 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
12226 }
12227 #endif // BONJOUR_ON_DEMAND
12228
12229 #if AWD_METRICS
12230 if (Question_uDNS(question) && !question->metrics.answered && (question->metrics.querySendCount > 0))
12231 {
12232 const domainname * queryName;
12233 mDNSBool isForCell;
12234 mDNSu32 durationMs;
12235
12236 queryName = question->metrics.originalQName ? question->metrics.originalQName : &question->qname;
12237 isForCell = (question->qDNSServer && question->qDNSServer->cellIntf);
12238 durationMs = ((m->timenow - question->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
12239 MetricsUpdateDNSQueryStats(queryName, question->qtype, mDNSNULL, question->metrics.querySendCount, question->metrics.expiredAnswerState, durationMs, isForCell);
12240 }
12241 #endif
12242 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12243 UpdateQuestionDuplicates(m, question);
12244 // But don't trash ThisQInterval until afterwards.
12245 question->ThisQInterval = -1;
12246
12247 // If there are any cache records referencing this as their active question, then see if there is any
12248 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12249 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
12250 {
12251 if (rr->CRActiveQuestion == question)
12252 {
12253 DNSQuestion *q;
12254 DNSQuestion *replacement = mDNSNULL;
12255 // If we find an active question that is answered by this cached record, use it as the cache record's
12256 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12257 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12258 // via CacheRecordRmv() when the cache record expires.
12259 for (q = m->Questions; q && (q != m->NewQuestions); q = q->next)
12260 {
12261 if (!q->DuplicateOf && !QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
12262 {
12263 if (q->ThisQInterval > 0)
12264 {
12265 replacement = q;
12266 break;
12267 }
12268 else if (!replacement)
12269 {
12270 replacement = q;
12271 }
12272 }
12273 }
12274 if (replacement)
12275 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12276 "CurrentAnswers %d, SuppressQuery %d", replacement, CRDisplayString(m,rr), question->CurrentAnswers, replacement->CurrentAnswers, replacement->SuppressQuery);
12277 rr->CRActiveQuestion = replacement; // Question used to be active; new value may or may not be null
12278 if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count
12279 }
12280 }
12281
12282 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12283 // bump its pointer forward one question.
12284 if (m->CurrentQuestion == question)
12285 {
12286 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12287 question->qname.c, DNSTypeName(question->qtype));
12288 m->CurrentQuestion = question->next;
12289 }
12290
12291 if (m->NewQuestions == question)
12292 {
12293 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12294 question->qname.c, DNSTypeName(question->qtype));
12295 m->NewQuestions = question->next;
12296 }
12297
12298 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
12299
12300 if (m->RestartQuestion == question)
12301 {
12302 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12303 question->qname.c, DNSTypeName(question->qtype));
12304 m->RestartQuestion = question->next;
12305 }
12306
12307 if (m->ValidationQuestion == question)
12308 {
12309 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
12310 question->qname.c, DNSTypeName(question->qtype));
12311 m->ValidationQuestion = question->next;
12312 }
12313
12314 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12315 question->next = mDNSNULL;
12316
12317 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12318
12319 // And finally, cancel any associated GetZoneData operation that's still running.
12320 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12321 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12322 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12323 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12324 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
12325 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
12326 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
12327 {
12328 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12329 DNSQuestion *q;
12330 for (q = m->Questions; q; q=q->next)
12331 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
12332 if (!q)
12333 {
12334 if (!m->LLQNAT.clientCallback) // Should never happen, but just in case...
12335 {
12336 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12337 }
12338 else
12339 {
12340 LogInfo("Stopping LLQNAT");
12341 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
12342 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
12343 }
12344 }
12345
12346 // If necessary, tell server it can delete this LLQ state
12347 if (question->state == LLQ_Established)
12348 {
12349 question->ReqLease = 0;
12350 sendLLQRefresh(m, question);
12351 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12352 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12353 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12354 // we let that run out its natural course and complete asynchronously.
12355 if (question->tcp)
12356 {
12357 question->tcp->question = mDNSNULL;
12358 question->tcp = mDNSNULL;
12359 }
12360 }
12361 #ifdef DNS_PUSH_ENABLED
12362 else if (question->dnsPushState == DNSPUSH_ESTABLISHED)
12363 {
12364 if (question->tcp)
12365 {
12366 UnSubscribeToDNSPushNotificationServer(m, q);
12367 question->tcp->question = mDNSNULL;
12368 question->tcp = mDNSNULL;
12369 }
12370 }
12371 #endif // DNS_PUSH_ENABLED
12372 #if APPLE_OSX_mDNSResponder
12373 UpdateAutoTunnelDomainStatuses(m);
12374 #endif
12375 }
12376 // wait until we send the refresh above which needs the nta
12377 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
12378
12379 if (question->ValidationRequired && question->DNSSECAuthInfo)
12380 {
12381 LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question->qname.c);
12382 question->DAIFreeCallback(m, question->DNSSECAuthInfo);
12383 question->DNSSECAuthInfo = mDNSNULL;
12384 }
12385 if (question->AnonInfo)
12386 {
12387 FreeAnonInfo(question->AnonInfo);
12388 question->AnonInfo = mDNSNULL;
12389 }
12390 #if AWD_METRICS
12391 if (question->metrics.originalQName)
12392 {
12393 mDNSPlatformMemFree(question->metrics.originalQName);
12394 question->metrics.originalQName = mDNSNULL;
12395 }
12396 #endif
12397
12398 #if USE_DNS64
12399 DNS64ResetState(question);
12400 #endif
12401
12402 return(mStatus_NoError);
12403 }
12404
12405 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
12406 {
12407 mStatus status;
12408 mDNS_Lock(m);
12409 status = mDNS_StartQuery_internal(m, question);
12410 mDNS_Unlock(m);
12411 return(status);
12412 }
12413
12414 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
12415 {
12416 mStatus status;
12417 mDNS_Lock(m);
12418 status = mDNS_StopQuery_internal(m, question);
12419 mDNS_Unlock(m);
12420 return(status);
12421 }
12422
12423 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12424 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12425 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12426 // specifically to catch and report if the client callback does try to make API calls
12427 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
12428 {
12429 mStatus status;
12430 DNSQuestion *qq;
12431 mDNS_Lock(m);
12432
12433 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12434 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
12435
12436 status = mDNS_StopQuery_internal(m, question);
12437 if (status == mStatus_NoError && !qq)
12438 {
12439 const CacheRecord *rr;
12440 CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12441 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12442 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
12443 if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
12444 {
12445 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12446 if (question->QuestionCallback)
12447 question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
12448 }
12449 }
12450 mDNS_Unlock(m);
12451 return(status);
12452 }
12453
12454 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
12455 {
12456 mStatus status;
12457 mDNS_Lock(m);
12458 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12459 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12460 mDNS_Unlock(m);
12461 return(status);
12462 }
12463
12464 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
12465 {
12466 mStatus status = mStatus_BadReferenceErr;
12467 CacheRecord *cr;
12468 mDNS_Lock(m);
12469 cr = FindIdenticalRecordInCache(m, rr);
12470 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
12471 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12472 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12473 mDNS_Unlock(m);
12474 return(status);
12475 }
12476
12477 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
12478 const domainname *const srv, const domainname *const domain,
12479 const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12480 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12481 mDNSQuestionCallback *Callback, void *Context)
12482 {
12483 question->InterfaceID = InterfaceID;
12484 question->flags = flags;
12485 question->Target = zeroAddr;
12486 question->qtype = kDNSType_PTR;
12487 question->qclass = kDNSClass_IN;
12488 question->LongLived = mDNStrue;
12489 question->ExpectUnique = mDNSfalse;
12490 question->ForceMCast = ForceMCast;
12491 question->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
12492 question->SuppressUnusable = mDNSfalse;
12493 question->SearchListIndex = 0;
12494 question->AppendSearchDomains = 0;
12495 question->RetryWithSearchDomains = mDNSfalse;
12496 question->TimeoutQuestion = 0;
12497 question->WakeOnResolve = 0;
12498 question->UseBackgroundTrafficClass = useBackgroundTrafficClass;
12499 question->ValidationRequired = 0;
12500 question->ValidatingResponse = 0;
12501 question->ProxyQuestion = 0;
12502 question->qnameOrig = mDNSNULL;
12503 question->AnonInfo = mDNSNULL;
12504 question->QuestionCallback = Callback;
12505 question->QuestionContext = Context;
12506
12507 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
12508 return(mStatus_BadParamErr);
12509
12510 if (anondata)
12511 {
12512 question->AnonInfo = AllocateAnonInfo(&question->qname, anondata, mDNSPlatformStrLen(anondata), mDNSNULL);
12513 if (!question->AnonInfo)
12514 return(mStatus_BadParamErr);
12515 }
12516
12517 return(mDNS_StartQuery_internal(m, question));
12518 }
12519
12520 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
12521 const domainname *const srv, const domainname *const domain,
12522 const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12523 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12524 mDNSQuestionCallback *Callback, void *Context)
12525 {
12526 mStatus status;
12527 mDNS_Lock(m);
12528 status = mDNS_StartBrowse_internal(m, question, srv, domain, anondata, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12529 mDNS_Unlock(m);
12530 return(status);
12531 }
12532
12533
12534 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12535 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12536 {
12537 question->InterfaceID = InterfaceID;
12538 question->flags = 0;
12539 question->Target = zeroAddr;
12540 question->qtype = kDNSType_PTR;
12541 question->qclass = kDNSClass_IN;
12542 question->LongLived = mDNSfalse;
12543 question->ExpectUnique = mDNSfalse;
12544 question->ForceMCast = mDNSfalse;
12545 question->ReturnIntermed = mDNSfalse;
12546 question->SuppressUnusable = mDNSfalse;
12547 question->SearchListIndex = 0;
12548 question->AppendSearchDomains = 0;
12549 question->RetryWithSearchDomains = mDNSfalse;
12550 question->TimeoutQuestion = 0;
12551 question->WakeOnResolve = 0;
12552 question->UseBackgroundTrafficClass = mDNSfalse;
12553 question->ValidationRequired = 0;
12554 question->ValidatingResponse = 0;
12555 question->ProxyQuestion = 0;
12556 question->qnameOrig = mDNSNULL;
12557 question->AnonInfo = mDNSNULL;
12558 question->pid = mDNSPlatformGetPID();
12559 question->euid = 0;
12560 question->QuestionCallback = Callback;
12561 question->QuestionContext = Context;
12562 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12563 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12564 if (!dom) dom = &localdomain;
12565 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12566 return(mDNS_StartQuery(m, question));
12567 }
12568
12569 // ***************************************************************************
12570 #if COMPILER_LIKES_PRAGMA_MARK
12571 #pragma mark -
12572 #pragma mark - Responder Functions
12573 #endif
12574
12575 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12576 {
12577 mStatus status;
12578 mDNS_Lock(m);
12579 status = mDNS_Register_internal(m, rr);
12580 mDNS_Unlock(m);
12581 return(status);
12582 }
12583
12584 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12585 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12586 {
12587 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12588 {
12589 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12590 return(mStatus_Invalid);
12591 }
12592
12593 mDNS_Lock(m);
12594
12595 // If TTL is unspecified, leave TTL unchanged
12596 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12597
12598 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12599 if (rr->NewRData)
12600 {
12601 RData *n = rr->NewRData;
12602 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
12603 if (rr->UpdateCallback)
12604 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
12605 }
12606
12607 rr->NewRData = newrdata;
12608 rr->newrdlength = newrdlength;
12609 rr->UpdateCallback = Callback;
12610
12611 #ifndef UNICAST_DISABLED
12612 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12613 {
12614 mStatus status = uDNS_UpdateRecord(m, rr);
12615 // The caller frees the memory on error, don't retain stale pointers
12616 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12617 mDNS_Unlock(m);
12618 return(status);
12619 }
12620 #endif
12621
12622 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12623 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12624 CompleteRDataUpdate(m, rr);
12625 else
12626 {
12627 rr->AnnounceCount = InitialAnnounceCount;
12628 InitializeLastAPTime(m, rr);
12629 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12630 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12631 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12632 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12633 if (rr->UpdateCredits <= 5)
12634 {
12635 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12636 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12637 rr->ThisAPInterval *= 4;
12638 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12639 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12640 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12641 }
12642 rr->resrec.rroriginalttl = newttl;
12643 }
12644
12645 mDNS_Unlock(m);
12646 return(mStatus_NoError);
12647 }
12648
12649 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12650 // the record list and/or question list.
12651 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12652 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12653 {
12654 mStatus status;
12655 mDNS_Lock(m);
12656 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12657 mDNS_Unlock(m);
12658 return(status);
12659 }
12660
12661 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12662 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12663
12664 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
12665 {
12666 NetworkInterfaceInfo *intf;
12667 for (intf = m->HostInterfaces; intf; intf = intf->next)
12668 if (intf->Advertise) break;
12669 return(intf);
12670 }
12671
12672 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12673 // (It's a set of records, not a set of interfaces.)
12674 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12675 {
12676 char buffer[MAX_REVERSE_MAPPING_NAME];
12677 NetworkInterfaceInfo *primary;
12678 mDNSu8 recordType;
12679
12680 if (m->AutoTargetServices == 0)
12681 {
12682 LogInfo("AdvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
12683 return;
12684 }
12685
12686 primary = FindFirstAdvertisedInterface(m);
12687 if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
12688 // We should never have primary be NULL, because even if there is
12689 // no other interface yet, we should always find ourself in the list.
12690
12691 // If interface is marked as a direct link, we can assume the address record is unique
12692 // and does not need to go through the probe phase of the probe/announce packet sequence.
12693 recordType = (set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique);
12694
12695 if (set->DirectLink)
12696 LogInfo("AdvertiseInterface: Marking address record as kDNSRecordTypeKnownUnique for %s", set->ifname);
12697
12698 // Send dynamic update for non-linklocal IPv4 Addresses
12699 mDNS_SetupResourceRecord(&set->RR_A, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, recordType, AuthRecordAny, mDNS_HostNameCallback, set);
12700 mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12701 mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12702
12703 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12704 set->RR_A.AllowRemoteQuery = mDNStrue;
12705 set->RR_PTR.AllowRemoteQuery = mDNStrue;
12706 set->RR_HINFO.AllowRemoteQuery = mDNStrue;
12707 #endif
12708 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12709 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12710 AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
12711 if (set->ip.type == mDNSAddrType_IPv4)
12712 {
12713 set->RR_A.resrec.rrtype = kDNSType_A;
12714 set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
12715 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12716 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12717 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12718 }
12719 else if (set->ip.type == mDNSAddrType_IPv6)
12720 {
12721 int i;
12722 set->RR_A.resrec.rrtype = kDNSType_AAAA;
12723 set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
12724 for (i = 0; i < 16; i++)
12725 {
12726 static const char hexValues[] = "0123456789ABCDEF";
12727 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12728 buffer[i * 4 + 1] = '.';
12729 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12730 buffer[i * 4 + 3] = '.';
12731 }
12732 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12733 }
12734
12735 MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
12736 set->RR_PTR.AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12737 set->RR_PTR.ForceMCast = mDNStrue; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12738
12739 set->RR_A.RRSet = &primary->RR_A; // May refer to self
12740
12741 mDNS_Register_internal(m, &set->RR_A);
12742 mDNS_Register_internal(m, &set->RR_PTR);
12743
12744 #if APPLE_OSX_mDNSResponder
12745 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12746 D2D_start_advertising_interface(set);
12747 #endif // APPLE_OSX_mDNSResponder
12748
12749 if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
12750 {
12751 mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
12752 AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
12753 set->RR_HINFO.DependentOn = &set->RR_A;
12754 mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
12755 p += 1 + (int)p[0];
12756 mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
12757 mDNS_Register_internal(m, &set->RR_HINFO);
12758 }
12759 else
12760 {
12761 debugf("Not creating HINFO record: platform support layer provided no information");
12762 set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
12763 }
12764 }
12765
12766 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12767 {
12768 if (m->AutoTargetServices == 0)
12769 {
12770 LogInfo("DeadvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
12771 return;
12772 }
12773
12774 #if APPLE_OSX_mDNSResponder
12775 D2D_stop_advertising_interface(set);
12776 #endif // APPLE_OSX_mDNSResponder
12777
12778 // Unregister these records.
12779 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12780 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12781 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12782 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12783 if (set->RR_A .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
12784 if (set->RR_PTR .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
12785 if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
12786 }
12787
12788 mDNSlocal void AdvertiseAllInterfaceRecords(mDNS *const m)
12789 {
12790 NetworkInterfaceInfo *intf;
12791 for (intf = m->HostInterfaces; intf; intf = intf->next)
12792 {
12793 if (intf->Advertise)
12794 {
12795 LogInfo("AdvertiseInterface: Advertising for ifname %s", intf->ifname);
12796 AdvertiseInterface(m, intf);
12797 }
12798 }
12799 }
12800
12801 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m)
12802 {
12803 NetworkInterfaceInfo *intf;
12804 for (intf = m->HostInterfaces; intf; intf = intf->next)
12805 {
12806 if (intf->Advertise)
12807 {
12808 LogInfo("DeadvertiseInterface: Deadvertising for ifname %s", intf->ifname);
12809 DeadvertiseInterface(m, intf);
12810 }
12811 }
12812 }
12813
12814 // Change target host name for record.
12815 mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr)
12816 {
12817 #if APPLE_OSX_mDNSResponder
12818 // If this record was also registered with any D2D plugins, stop advertising
12819 // the version with the old host name.
12820 D2D_stop_advertising_record(rr);
12821 #endif
12822
12823 SetTargetToHostName(m, rr);
12824
12825 #if APPLE_OSX_mDNSResponder
12826 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12827 D2D_start_advertising_record(rr);
12828 #endif
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);
12847 AdvertiseAllInterfaceRecords(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 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12906 {
12907 NetworkInterfaceInfo *intf;
12908 active->IPv4Available = mDNSfalse;
12909 active->IPv6Available = mDNSfalse;
12910 for (intf = m->HostInterfaces; intf; intf = intf->next)
12911 if (intf->InterfaceID == active->InterfaceID)
12912 {
12913 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12914 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12915 }
12916 }
12917
12918 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12919 {
12920 AuthRecord *rr;
12921 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12922 for (rr = m->ResourceRecords; rr; rr=rr->next)
12923 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12924 {
12925 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12926 // Zero out the updateid so that if we have a pending response from the server, it won't
12927 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12928 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12929 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12930 }
12931 }
12932
12933 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12934 {
12935 int i;
12936 // We initialize ThisQInterval to -1 indicating that the question has not been started
12937 // yet. If the question (browse) is started later during interface registration, it will
12938 // be stopped during interface deregistration. We can't sanity check to see if the
12939 // question has been stopped or not before initializing it to -1 because we need to
12940 // initialize it to -1 the very first time.
12941
12942 set->NetWakeBrowse.ThisQInterval = -1;
12943 for (i=0; i<3; i++)
12944 {
12945 set->NetWakeResolve[i].ThisQInterval = -1;
12946 set->SPSAddr[i].type = mDNSAddrType_None;
12947 }
12948 set->NextSPSAttempt = -1;
12949 set->NextSPSAttemptTime = m->timenow;
12950 }
12951
12952 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12953 {
12954 NetworkInterfaceInfo *p = m->HostInterfaces;
12955 while (p && p != set) p=p->next;
12956 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12957
12958 if (set->InterfaceActive)
12959 {
12960 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12961 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, mDNSNULL, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
12962 }
12963 }
12964
12965 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12966 {
12967 NetworkInterfaceInfo *p = m->HostInterfaces;
12968 while (p && p != set) p=p->next;
12969 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12970
12971 // Note: We start the browse only if the interface is NetWake capable and we use this to
12972 // stop the resolves also. Hence, the resolves should not be started without the browse
12973 // being started i.e, resolves should not happen unless NetWake capable which is
12974 // guaranteed by BeginSleepProcessing.
12975 if (set->NetWakeBrowse.ThisQInterval >= 0)
12976 {
12977 int i;
12978 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
12979
12980 // Stop our browse and resolve operations
12981 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
12982 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
12983
12984 // Make special call to the browse callback to let it know it can to remove all records for this interface
12985 if (m->SPSBrowseCallback)
12986 {
12987 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12988 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
12989 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12990 }
12991
12992 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12993 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12994 InitializeNetWakeState(m, set);
12995 }
12996 }
12997
12998 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
12999 {
13000 AuthRecord *rr;
13001 mDNSBool FirstOfType = mDNStrue;
13002 NetworkInterfaceInfo **p = &m->HostInterfaces;
13003
13004 if (!set->InterfaceID)
13005 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
13006
13007 if (!mDNSAddressIsValidNonZero(&set->mask))
13008 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
13009
13010 mDNS_Lock(m);
13011
13012 // Assume this interface will be active now, unless we find a duplicate already in the list
13013 set->InterfaceActive = mDNStrue;
13014 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
13015 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
13016
13017 InitializeNetWakeState(m, set);
13018
13019 // Scan list to see if this InterfaceID is already represented
13020 while (*p)
13021 {
13022 if (*p == set)
13023 {
13024 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
13025 mDNS_Unlock(m);
13026 return(mStatus_AlreadyRegistered);
13027 }
13028
13029 if ((*p)->InterfaceID == set->InterfaceID)
13030 {
13031 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13032 set->InterfaceActive = mDNSfalse;
13033 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
13034 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
13035 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
13036 }
13037
13038 p=&(*p)->next;
13039 }
13040
13041 set->next = mDNSNULL;
13042 *p = set;
13043
13044 if (set->Advertise)
13045 AdvertiseInterface(m, set);
13046
13047 LogInfo("mDNS_RegisterInterface: InterfaceID %d %s (%#a) %s",
13048 (uint32_t)set->InterfaceID, set->ifname, &set->ip,
13049 set->InterfaceActive ?
13050 "not represented in list; marking active and retriggering queries" :
13051 "already represented in list; marking inactive for now");
13052
13053 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
13054
13055 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13056 // giving the false impression that there's an active representative of this interface when there really isn't.
13057 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13058 // even if we believe that we previously had an active representative of this interface.
13059 if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
13060 {
13061 DNSQuestion *q;
13062 // Normally, after an interface comes up, we pause half a second before beginning probing.
13063 // This is to guard against cases where there's rapid interface changes, where we could be confused by
13064 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13065 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13066 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13067 // and think it's a conflicting answer to our probe.
13068 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13069 mDNSs32 probedelay;
13070 mDNSu8 numannounce;
13071 switch (activationSpeed)
13072 {
13073 case FastActivation:
13074 probedelay = (mDNSs32)0;
13075 numannounce = InitialAnnounceCount;
13076 LogMsg("mDNS_RegisterInterface: Using fast activation for DirectLink interface %s (%#a)", set->ifname, &set->ip);
13077 break;
13078
13079 case SlowActivation:
13080 probedelay = mDNSPlatformOneSecond * 5;
13081 numannounce = (mDNSu8)1;
13082 LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a), doing slow activation", set->ifname, &set->ip);
13083 m->mDNSStats.InterfaceUpFlap++;
13084 break;
13085
13086 case NormalActivation:
13087 default:
13088 probedelay = mDNSPlatformOneSecond / 2;
13089 numannounce = InitialAnnounceCount;
13090 break;
13091 }
13092
13093 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
13094
13095 // No probe or sending suppression on DirectLink type interfaces.
13096 if (activationSpeed == FastActivation)
13097 {
13098 m->SuppressSending = 0;
13099 m->SuppressProbes = 0;
13100 }
13101 else
13102 {
13103 // Use a small amount of randomness:
13104 // In the case of a network administrator turning on an Ethernet hub so that all the
13105 // connected machines establish link at exactly the same time, we don't want them all
13106 // to go and hit the network with identical queries at exactly the same moment.
13107 // We set a random delay of up to InitialQuestionInterval (1/3 second).
13108 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13109 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13110 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13111 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13112 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13113 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
13114
13115 if (m->SuppressProbes == 0 ||
13116 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
13117 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
13118 }
13119
13120 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13121 // it here also handles the wake up case as the network link comes UP after waking causing
13122 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13123 // that the network link comes UP after 60 seconds and we never set the OWNER option
13124 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
13125 LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
13126
13127 m->mDNSStats.InterfaceUp++;
13128 for (q = m->Questions; q; q=q->next) // Scan our list of questions
13129 {
13130 if (mDNSOpaque16IsZero(q->TargetQID))
13131 {
13132 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
13133 { // then reactivate this question
13134 // If flapping, delay between first and second queries is nine seconds instead of one second
13135 mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
13136 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
13137 mDNSs32 qdelay = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0;
13138 if (dodelay) LogInfo("No cache records expired for %##s (%s); delaying questions by %d seconds", q->qname.c, DNSTypeName(q->qtype), qdelay);
13139
13140 if (!q->ThisQInterval || q->ThisQInterval > initial)
13141 {
13142 q->ThisQInterval = initial;
13143 q->RequestUnicast = kDefaultRequestUnicastCount;
13144 }
13145 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
13146 q->RecentAnswerPkts = 0;
13147 // Change the salt
13148 ReInitAnonInfo(&q->AnonInfo, &q->qname);
13149 SetNextQueryTime(m,q);
13150 }
13151 }
13152 }
13153
13154 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13155 // we now need them to re-probe if necessary, and then re-announce.
13156 for (rr = m->ResourceRecords; rr; rr=rr->next)
13157 {
13158 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
13159 {
13160 // Change the salt
13161 ReInitAnonInfo(&rr->resrec.AnonInfo, rr->resrec.name);
13162 mDNSCoreRestartRegistration(m, rr, numannounce);
13163 }
13164 }
13165 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
13166 DNSSECProbe(m);
13167 #endif
13168 }
13169
13170 RestartRecordGetZoneData(m);
13171
13172 mDNS_UpdateAllowSleep(m);
13173
13174 mDNS_Unlock(m);
13175 return(mStatus_NoError);
13176 }
13177
13178 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13179 // the record list and/or question list.
13180 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13181 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13182 {
13183 NetworkInterfaceInfo **p = &m->HostInterfaces;
13184 mDNSBool revalidate = mDNSfalse;
13185 NetworkInterfaceInfo *primary;
13186 NetworkInterfaceInfo *intf;
13187 AuthRecord *A;
13188
13189 mDNS_Lock(m);
13190
13191 // Find this record in our list
13192 while (*p && *p != set) p=&(*p)->next;
13193 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
13194
13195 mDNS_DeactivateNetWake_internal(m, set);
13196
13197 // Unlink this record from our list
13198 *p = (*p)->next;
13199 set->next = mDNSNULL;
13200
13201 if (!set->InterfaceActive)
13202 {
13203 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13204 for (intf = m->HostInterfaces; intf; intf = intf->next)
13205 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
13206 UpdateInterfaceProtocols(m, intf);
13207 }
13208 else
13209 {
13210 intf = FirstInterfaceForID(m, set->InterfaceID);
13211 if (intf)
13212 {
13213 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %d %s (%#a) exists;"
13214 " making it active", (uint32_t)set->InterfaceID, set->ifname, &set->ip);
13215 if (intf->InterfaceActive)
13216 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
13217 intf->InterfaceActive = mDNStrue;
13218 UpdateInterfaceProtocols(m, intf);
13219
13220 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
13221
13222 // See if another representative *of the same type* exists. If not, we mave have gone from
13223 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13224 for (intf = m->HostInterfaces; intf; intf = intf->next)
13225 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
13226 break;
13227 if (!intf) revalidate = mDNStrue;
13228 }
13229 else
13230 {
13231 mDNSu32 slot;
13232 CacheGroup *cg;
13233 CacheRecord *rr;
13234 DNSQuestion *q;
13235
13236 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %d %s (%#a) deregistered;"
13237 " marking questions etc. dormant", (uint32_t)set->InterfaceID, set->ifname, &set->ip);
13238
13239 m->mDNSStats.InterfaceDown++;
13240
13241 if (set->McastTxRx && (activationSpeed == SlowActivation))
13242 {
13243 LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
13244 m->mDNSStats.InterfaceDownFlap++;
13245 }
13246
13247 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13248 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13249 for (q = m->Questions; q; q=q->next)
13250 {
13251 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
13252 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
13253 {
13254 q->FlappingInterface2 = q->FlappingInterface1;
13255 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
13256 }
13257 }
13258
13259 // 2. Flush any cache records received on this interface
13260 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
13261 FORALL_CACHERECORDS(slot, cg, rr)
13262 {
13263 if (rr->resrec.InterfaceID == set->InterfaceID)
13264 {
13265 // If this interface is deemed flapping,
13266 // postpone deleting the cache records in case the interface comes back again
13267 if (set->McastTxRx && (activationSpeed == SlowActivation))
13268 {
13269 // For a flapping interface we want these records to go away after
13270 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13271 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13272 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13273 // if the interface does come back, any relevant questions will be reactivated anyway
13274 rr->UnansweredQueries = MaxUnansweredQueries;
13275 }
13276 else
13277 {
13278 rr->resrec.mortality = Mortality_Mortal;
13279 mDNS_PurgeCacheResourceRecord(m, rr);
13280 }
13281 }
13282 }
13283 }
13284 }
13285
13286 // If we still have address records referring to this one, update them.
13287 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13288 // so the call to FindFirstAdvertisedInterface() won’t accidentally find it.
13289 primary = FindFirstAdvertisedInterface(m);
13290 A = primary ? &primary->RR_A : mDNSNULL;
13291 for (intf = m->HostInterfaces; intf; intf = intf->next)
13292 if (intf->RR_A.RRSet == &set->RR_A)
13293 intf->RR_A.RRSet = A;
13294
13295 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13296 if (set->Advertise) DeadvertiseInterface(m, set);
13297
13298 // If we have any cache records received on this interface that went away, then re-verify them.
13299 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13300 // giving the false impression that there's an active representative of this interface when there really isn't.
13301 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13302 if (revalidate && !m->ShutdownTime)
13303 {
13304 mDNSu32 slot;
13305 CacheGroup *cg;
13306 CacheRecord *rr;
13307 FORALL_CACHERECORDS(slot, cg, rr)
13308 if (rr->resrec.InterfaceID == set->InterfaceID)
13309 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13310 }
13311
13312 mDNS_UpdateAllowSleep(m);
13313
13314 mDNS_Unlock(m);
13315 }
13316
13317 mDNSlocal void SetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13318 {
13319 int i, len;
13320
13321 if (!sr->AnonData)
13322 return;
13323
13324 len = mDNSPlatformStrLen(sr->AnonData);
13325 if (sr->RR_PTR.resrec.AnonInfo)
13326 {
13327 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for PTR record %##s, should have been freed already", sr->RR_PTR.resrec.name->c);
13328 FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13329 }
13330 sr->RR_PTR.resrec.AnonInfo = AllocateAnonInfo(sr->RR_PTR.resrec.name, sr->AnonData, len, mDNSNULL);
13331 for (i=0; i<NumSubTypes; i++)
13332 {
13333 if (sr->SubTypes[i].resrec.AnonInfo)
13334 {
13335 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for subtype record %##s, should have been freed already", sr->SubTypes[i].resrec.name->c);
13336 FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13337 }
13338 sr->SubTypes[i].resrec.AnonInfo = AllocateAnonInfo(sr->SubTypes[i].resrec.name, sr->AnonData, len, mDNSNULL);
13339 }
13340 }
13341
13342 mDNSlocal void ResetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13343 {
13344 int i;
13345
13346 if (!sr->AnonData)
13347 return;
13348 if (sr->RR_PTR.resrec.AnonInfo)
13349 {
13350 FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13351 sr->RR_PTR.resrec.AnonInfo = mDNSNULL;
13352 }
13353 for (i=0; i<NumSubTypes; i++)
13354 {
13355 if (sr->SubTypes[i].resrec.AnonInfo)
13356 {
13357 FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13358 sr->SubTypes[i].resrec.AnonInfo = mDNSNULL;
13359 }
13360 }
13361 }
13362
13363 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13364 {
13365 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13366 (void)m; // Unused parameter
13367
13368 #if MDNS_DEBUGMSGS
13369 {
13370 char *msg = "Unknown result";
13371 if (result == mStatus_NoError) msg = "Name Registered";
13372 else if (result == mStatus_NameConflict) msg = "Name Conflict";
13373 else if (result == mStatus_MemFree) msg = "Memory Free";
13374 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13375 }
13376 #endif
13377
13378 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13379 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13380
13381 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13382 if (result == mStatus_NameConflict)
13383 {
13384 sr->Conflict = mDNStrue; // Record that this service set had a conflict
13385 mDNS_DeregisterService(m, sr); // Unlink the records from our list
13386 return;
13387 }
13388
13389 if (result == mStatus_MemFree)
13390 {
13391 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13392 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13393 // every record is finished cleaning up.
13394 mDNSu32 i;
13395 ExtraResourceRecord *e = sr->Extras;
13396
13397 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13398 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13399 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13400 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13401 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13402
13403 while (e)
13404 {
13405 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13406 e = e->next;
13407 }
13408 ResetAnonInfoSRS(sr, sr->NumSubTypes);
13409
13410 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13411 // then we can now report the NameConflict to the client
13412 if (sr->Conflict) result = mStatus_NameConflict;
13413
13414 }
13415
13416 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13417 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13418 // function is allowed to do anything, including deregistering this service and freeing its memory.
13419 if (sr->ServiceCallback)
13420 sr->ServiceCallback(m, sr, result);
13421 }
13422
13423 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13424 {
13425 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13426 if (sr->ServiceCallback)
13427 sr->ServiceCallback(m, sr, result);
13428 }
13429
13430
13431 // Derive AuthRecType from the kDNSServiceFlags* values.
13432 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13433 {
13434 AuthRecType artype;
13435
13436 if (InterfaceID == mDNSInterface_LocalOnly)
13437 artype = AuthRecordLocalOnly;
13438 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13439 artype = AuthRecordP2P;
13440 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
13441 && (flags & kDNSServiceFlagsIncludeAWDL))
13442 artype = AuthRecordAnyIncludeAWDLandP2P;
13443 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
13444 artype = AuthRecordAnyIncludeP2P;
13445 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
13446 artype = AuthRecordAnyIncludeAWDL;
13447 else
13448 artype = AuthRecordAny;
13449
13450 return artype;
13451 }
13452
13453 // Used to derive the original D2D specific flags specified by the client in the registration
13454 // when we don't have access to the original flag (kDNSServiceFlags*) values.
13455 mDNSexport mDNSu32 deriveD2DFlagsFromAuthRecType(AuthRecType authRecType)
13456 {
13457 mDNSu32 flags = 0;
13458 if ((authRecType == AuthRecordAnyIncludeP2P) || (authRecType == AuthRecordAnyIncludeAWDLandP2P))
13459 flags |= kDNSServiceFlagsIncludeP2P;
13460 else if ((authRecType == AuthRecordAnyIncludeAWDL) || (authRecType == AuthRecordAnyIncludeAWDLandP2P))
13461 flags |= kDNSServiceFlagsIncludeAWDL;
13462 return flags;
13463 }
13464
13465 // Note:
13466 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13467 // Type is service type (e.g. "_ipp._tcp.")
13468 // Domain is fully qualified domain name (i.e. ending with a null label)
13469 // We always register a TXT, even if it is empty (so that clients are not
13470 // left waiting forever looking for a nonexistent record.)
13471 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13472 // then the default host name (m->MulticastHostname) is automatically used
13473 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13474 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13475 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13476 const domainname *const host, mDNSIPPort port, RData *const txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13477 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13478 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13479 {
13480 mStatus err;
13481 mDNSu32 i;
13482 mDNSu32 hostTTL;
13483 AuthRecType artype;
13484 mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13485
13486 sr->ServiceCallback = Callback;
13487 sr->ServiceContext = Context;
13488 sr->Conflict = mDNSfalse;
13489
13490 sr->Extras = mDNSNULL;
13491 sr->NumSubTypes = NumSubTypes;
13492 sr->SubTypes = SubTypes;
13493 sr->flags = flags;
13494
13495 artype = setAuthRecType(InterfaceID, flags);
13496
13497 // Initialize the AuthRecord objects to sane values
13498 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13499 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13500 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13501
13502 if (flags & kDNSServiceFlagsWakeOnlyService)
13503 {
13504 sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13505 }
13506
13507 if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
13508 hostTTL = kHostNameSmallTTL;
13509 else
13510 hostTTL = kHostNameTTL;
13511
13512 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
13513 mDNS_SetupResourceRecord(&sr->RR_TXT, txtrdata, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr);
13514
13515 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13516 if (mDNSIPPortIsZero(port))
13517 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13518
13519 // If the caller is registering an oversized TXT record,
13520 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13521 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13522 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13523
13524 // Set up the record names
13525 // For now we only create an advisory record for the main type, not for subtypes
13526 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13527 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13528 return(mStatus_BadParamErr);
13529 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13530 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13531 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13532
13533 // 1. Set up the ADV record rdata to advertise our service type
13534 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13535
13536 // 2. Set up the PTR record rdata to point to our service name
13537 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13538 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13539 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13540 sr->RR_PTR.Additional1 = &sr->RR_SRV;
13541 sr->RR_PTR.Additional2 = &sr->RR_TXT;
13542
13543 // 2a. Set up any subtype PTRs to point to our service name
13544 // If the client is using subtypes, it is the client's responsibility to have
13545 // already set the first label of the record name to the subtype being registered
13546 for (i=0; i<NumSubTypes; i++)
13547 {
13548 domainname st;
13549 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13550 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13551 AppendDomainName(&st, type);
13552 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13553 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13554 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13555 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13556 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13557 }
13558
13559 SetAnonInfoSRS(sr, NumSubTypes);
13560
13561 // 3. Set up the SRV record rdata.
13562 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13563 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
13564 sr->RR_SRV.resrec.rdata->u.srv.port = port;
13565
13566 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13567 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13568 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13569
13570 // 4. Set up the TXT record rdata,
13571 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13572 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13573 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13574 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13575 {
13576 sr->RR_TXT.resrec.rdlength = txtlen;
13577 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13578 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13579 }
13580 sr->RR_TXT.DependentOn = &sr->RR_SRV;
13581
13582 mDNS_Lock(m);
13583 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13584 // that if the SRV cannot find a target, rest of the records that belong to this service
13585 // will not be activated.
13586 err = mDNS_Register_internal(m, &sr->RR_SRV);
13587 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13588 // any list and hence no need to deregister. We could probably do similar checks for other
13589 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13590 if (err)
13591 {
13592 mDNS_Unlock(m);
13593 return err;
13594 }
13595 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13596 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13597 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13598 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13599 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13600 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13601 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13602 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13603 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13604
13605 mDNS_Unlock(m);
13606
13607 if (err) mDNS_DeregisterService(m, sr);
13608 return(err);
13609 }
13610
13611 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13612 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags)
13613 {
13614 ExtraResourceRecord **e;
13615 mStatus status;
13616 AuthRecType artype;
13617 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13618 ResourceRecord *rr;
13619
13620 artype = setAuthRecType(InterfaceID, flags);
13621
13622 extra->next = mDNSNULL;
13623 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13624 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13625 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13626
13627 mDNS_Lock(m);
13628 rr = mDNSNULL;
13629 if (extra->r.resrec.rrtype == kDNSType_TXT)
13630 {
13631 if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec;
13632 }
13633 else if (extra->r.resrec.rrtype == kDNSType_SRV)
13634 {
13635 if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec;
13636 }
13637
13638 if (!rr)
13639 {
13640 ExtraResourceRecord *srExtra;
13641
13642 for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next)
13643 {
13644 if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask))
13645 {
13646 rr = &srExtra->r.resrec;
13647 break;
13648 }
13649 }
13650 }
13651
13652 if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl))
13653 {
13654 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13655 extra->r.resrec.rroriginalttl, rr->rroriginalttl, RRDisplayString(m, &extra->r.resrec));
13656 extra->r.resrec.rroriginalttl = rr->rroriginalttl;
13657 }
13658
13659 e = &sr->Extras;
13660 while (*e) e = &(*e)->next;
13661
13662 extra->r.DependentOn = &sr->RR_SRV;
13663
13664 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13665 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13666
13667 status = mDNS_Register_internal(m, &extra->r);
13668 if (status == mStatus_NoError) *e = extra;
13669
13670 mDNS_Unlock(m);
13671 return(status);
13672 }
13673
13674 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13675 mDNSRecordCallback MemFreeCallback, void *Context)
13676 {
13677 ExtraResourceRecord **e;
13678 mStatus status;
13679
13680 mDNS_Lock(m);
13681 e = &sr->Extras;
13682 while (*e && *e != extra) e = &(*e)->next;
13683 if (!*e)
13684 {
13685 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13686 status = mStatus_BadReferenceErr;
13687 }
13688 else
13689 {
13690 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13691 extra->r.RecordCallback = MemFreeCallback;
13692 extra->r.RecordContext = Context;
13693 *e = (*e)->next;
13694 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13695 }
13696 mDNS_Unlock(m);
13697 return(status);
13698 }
13699
13700 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13701 {
13702 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13703 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13704 domainlabel name1, name2;
13705 domainname type, domain;
13706 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13707 ExtraResourceRecord *extras = sr->Extras;
13708 mStatus err;
13709
13710 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13711 if (!newname)
13712 {
13713 name2 = name1;
13714 IncrementLabelSuffix(&name2, mDNStrue);
13715 newname = &name2;
13716 }
13717
13718 if (SameDomainName(&domain, &localdomain))
13719 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13720 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13721
13722 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
13723 host, sr->RR_SRV.resrec.rdata->u.srv.port,
13724 (sr->RR_TXT.resrec.rdata != &sr->RR_TXT.rdatastorage) ? sr->RR_TXT.resrec.rdata : mDNSNULL,
13725 sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13726 sr->SubTypes, sr->NumSubTypes,
13727 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13728
13729 // mDNS_RegisterService() just reset sr->Extras to NULL.
13730 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13731 // through the old list of extra records, and re-add them to our freshly created service registration
13732 while (!err && extras)
13733 {
13734 ExtraResourceRecord *e = extras;
13735 extras = extras->next;
13736 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13737 }
13738
13739 return(err);
13740 }
13741
13742 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13743 // which may change the record list and/or question list.
13744 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13745 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13746 {
13747 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13748 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13749
13750 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13751 {
13752 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13753 return(mStatus_BadReferenceErr);
13754 }
13755 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13756 {
13757 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13758 // Avoid race condition:
13759 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13760 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13761 // If the client happens to deregister the service in the middle of that process, then
13762 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13763 // instead of incorrectly promoting it to mStatus_NameConflict.
13764 // This race condition is exposed particularly when the conformance test generates
13765 // a whole batch of simultaneous conflicts across a range of services all advertised
13766 // using the same system default name, and if we don't take this precaution then
13767 // we end up incrementing m->nicelabel multiple times instead of just once.
13768 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13769 sr->Conflict = mDNSfalse;
13770 return(mStatus_NoError);
13771 }
13772 else
13773 {
13774 mDNSu32 i;
13775 mStatus status;
13776 ExtraResourceRecord *e;
13777 mDNS_Lock(m);
13778 e = sr->Extras;
13779
13780 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13781 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13782 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13783 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13784
13785 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13786
13787 // We deregister all of the extra records, but we leave the sr->Extras list intact
13788 // in case the client wants to do a RenameAndReregister and reinstate the registration
13789 while (e)
13790 {
13791 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13792 e = e->next;
13793 }
13794
13795 for (i=0; i<sr->NumSubTypes; i++)
13796 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13797
13798 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13799 mDNS_Unlock(m);
13800 return(status);
13801 }
13802 }
13803
13804 // Create a registration that asserts that no such service exists with this name.
13805 // This can be useful where there is a given function is available through several protocols.
13806 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13807 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13808 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13809 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13810 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13811 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13812 const domainname *const host,
13813 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13814 {
13815 AuthRecType artype;
13816
13817 artype = setAuthRecType(InterfaceID, flags);
13818
13819 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13820 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13821 rr->resrec.rdata->u.srv.priority = 0;
13822 rr->resrec.rdata->u.srv.weight = 0;
13823 rr->resrec.rdata->u.srv.port = zeroIPPort;
13824 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13825 else rr->AutoTarget = Target_AutoHost;
13826 return(mDNS_Register(m, rr));
13827 }
13828
13829 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13830 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13831 {
13832 AuthRecType artype;
13833
13834 if (InterfaceID == mDNSInterface_LocalOnly)
13835 artype = AuthRecordLocalOnly;
13836 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13837 artype = AuthRecordP2P;
13838 else
13839 artype = AuthRecordAny;
13840 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13841 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13842 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13843 return(mDNS_Register(m, rr));
13844 }
13845
13846 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13847 {
13848 AuthRecord *r;
13849 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13850 return mDNSfalse;
13851 }
13852
13853 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13854 {
13855 DNSQuestion *q;
13856 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13857 return mDNSfalse;
13858 }
13859
13860 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13861 {
13862 mDNSOpaque16 id;
13863 int i;
13864
13865 for (i=0; i<10; i++)
13866 {
13867 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13868 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13869 }
13870
13871 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13872
13873 return id;
13874 }
13875
13876 // ***************************************************************************
13877 #if COMPILER_LIKES_PRAGMA_MARK
13878 #pragma mark -
13879 #pragma mark - Sleep Proxy Server
13880 #endif
13881
13882 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13883 {
13884 // If we see an ARP from a machine we think is sleeping, then either
13885 // (i) the machine has woken, or
13886 // (ii) it's just a stray old packet from before the machine slept
13887 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13888 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13889 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13890 // 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*
13891 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13892 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13893
13894 rr->resrec.RecordType = kDNSRecordTypeUnique;
13895 rr->ProbeCount = DefaultProbeCountForTypeUnique;
13896 rr->ProbeRestartCount++;
13897
13898 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13899 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13900 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13901 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13902 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13903 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13904 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13905 InitializeLastAPTime(m, rr);
13906 else
13907 {
13908 rr->AnnounceCount = InitialAnnounceCount;
13909 rr->ThisAPInterval = mDNSPlatformOneSecond;
13910 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13911 SetNextAnnounceProbeTime(m, rr);
13912 }
13913 }
13914
13915 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13916 {
13917 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13918 AuthRecord *rr;
13919 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13920 if (!intf) return;
13921
13922 mDNS_Lock(m);
13923
13924 // Pass 1:
13925 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13926 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13927 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13928 // The times we might need to react to an ARP Announcement are:
13929 // (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
13930 // (ii) if it's a conflicting Announcement from another host
13931 // -- and we check for these in Pass 2 below.
13932 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13933 {
13934 for (rr = m->ResourceRecords; rr; rr=rr->next)
13935 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13936 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13937 {
13938 static const char msg1[] = "ARP Req from owner -- re-probing";
13939 static const char msg2[] = "Ignoring ARP Request from ";
13940 static const char msg3[] = "Creating Local ARP Cache entry ";
13941 static const char msg4[] = "Answering ARP Request from ";
13942 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13943 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
13944 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
13945 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13946 intf->ifname, msg, arp->sha.b, arp->spa.b, arp->tpa.b,
13947 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13948 if (msg == msg1)
13949 {
13950 if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13951 RestartARPProbing(m, rr);
13952 else
13953 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13954 }
13955 else if (msg == msg3)
13956 {
13957 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13958 }
13959 else if (msg == msg4)
13960 {
13961 SendARP(m, 2, rr, (mDNSv4Addr *)arp->tpa.b, &arp->sha, (mDNSv4Addr *)arp->spa.b, &arp->sha);
13962 }
13963 }
13964 }
13965
13966 // Pass 2:
13967 // 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.
13968 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13969 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13970 // 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.
13971 // If we see an apparently conflicting ARP, we check the sender hardware address:
13972 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13973 // 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.
13974 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
13975 debugf("ARP from self for %.4a", arp->tpa.b);
13976 else
13977 {
13978 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
13979 for (rr = m->ResourceRecords; rr; rr=rr->next)
13980 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13981 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13982 {
13983 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13984 {
13985 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13986 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13987 }
13988 else
13989 {
13990 RestartARPProbing(m, rr);
13991 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
13992 {
13993 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
13994 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
13995 arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr));
13996 }
13997 else
13998 {
13999 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14000 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14001 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14002 }
14003 }
14004 }
14005 }
14006
14007 mDNS_Unlock(m);
14008 }
14009
14010 /*
14011 // Option 1 is Source Link Layer Address Option
14012 // Option 2 is Target Link Layer Address Option
14013 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
14014 {
14015 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
14016 while (options < end)
14017 {
14018 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
14019 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
14020 options += options[1] * 8;
14021 }
14022 return mDNSNULL;
14023 }
14024 */
14025
14026 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
14027 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14028 {
14029 AuthRecord *rr;
14030 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
14031 if (!intf) return;
14032
14033 mDNS_Lock(m);
14034
14035 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
14036 if (ndp->type == NDP_Sol)
14037 {
14038 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
14039 (void)end;
14040 for (rr = m->ResourceRecords; rr; rr=rr->next)
14041 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14042 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
14043 {
14044 static const char msg1[] = "NDP Req from owner -- re-probing";
14045 static const char msg2[] = "Ignoring NDP Request from ";
14046 static const char msg3[] = "Creating Local NDP Cache entry ";
14047 static const char msg4[] = "Answering NDP Request from ";
14048 static const char msg5[] = "Answering NDP Probe from ";
14049 const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
14050 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
14051 sha && mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
14052 spa && mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
14053 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
14054 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14055 if (msg == msg1)
14056 {
14057 if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
14058 RestartARPProbing(m, rr);
14059 else
14060 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
14061 }
14062 else if (msg == msg3)
14063 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
14064 else if (msg == msg4)
14065 SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
14066 else if (msg == msg5)
14067 SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
14068 }
14069 }
14070
14071 // 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.
14072 if (mDNSSameEthAddress(sha, &intf->MAC))
14073 debugf("NDP from self for %.16a", &ndp->target);
14074 else
14075 {
14076 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14077 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14078 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14079 // Hence it is the NDP target address we care about, not the actual packet source address.
14080 if (ndp->type == NDP_Adv) spa = &ndp->target;
14081 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
14082 for (rr = m->ResourceRecords; rr; rr=rr->next)
14083 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14084 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14085 {
14086 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14087 {
14088 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14089 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14090 }
14091 else
14092 {
14093 RestartARPProbing(m, rr);
14094 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
14095 {
14096 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
14097 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
14098 }
14099 else
14100 {
14101 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14102 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14103 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14104 }
14105 }
14106 }
14107 }
14108
14109 mDNS_Unlock(m);
14110 }
14111
14112 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
14113 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
14114 {
14115 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
14116 mDNSBool wake = mDNSfalse;
14117 mDNSBool kaWake = mDNSfalse;
14118
14119 switch (protocol)
14120 {
14121 #define XX wake ? "Received" : "Ignoring", end-p
14122 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
14123 break;
14124
14125 case 0x06: {
14126 AuthRecord *kr;
14127 mDNSu32 seq, ack;
14128 #define TH_FIN 0x01
14129 #define TH_SYN 0x02
14130 #define TH_RST 0x04
14131 #define TH_ACK 0x10
14132
14133 kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
14134 if (kr)
14135 {
14136 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
14137 // Plan to wake if
14138 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14139 // (b) packet that contains new data and acks a sequence number higher than the one
14140 // we have been sending in the keepalive
14141
14142 wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
14143 if (!wake)
14144 {
14145 mDNSu8 *ptr;
14146 mDNSu32 pseq, pack;
14147 mDNSBool data = mDNSfalse;
14148 mDNSu8 tcphlen;
14149
14150 // Convert to host order
14151 ptr = (mDNSu8 *)&seq;
14152 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14153
14154 ptr = (mDNSu8 *)&ack;
14155 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14156
14157 pseq = t->tcp.seq;
14158 ptr = (mDNSu8 *)&pseq;
14159 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14160
14161 pack = t->tcp.ack;
14162 ptr = (mDNSu8 *)&pack;
14163 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14164
14165 // If the other side is acking one more than our sequence number (keepalive is one
14166 // less than the last valid sequence sent) and it's sequence is more than what we
14167 // acked before
14168 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14169 tcphlen = ((t->tcp.offset >> 4) * 4);
14170 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
14171 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
14172
14173 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14174 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
14175 ((int)(ack - pseq) == 1))
14176 {
14177 // Send an ACK;
14178 mDNS_SendKeepaliveACK(m, kr);
14179 }
14180 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14181 end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
14182 }
14183 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
14184 kaWake = wake;
14185 }
14186 else
14187 {
14188 // Plan to wake if
14189 // (a) RST is not set, AND
14190 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14191 wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
14192
14193 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14194 // except for ssh connections, where we'll wake for plain data packets too
14195 if (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
14196
14197 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
14198 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
14199 (t->tcp.flags & 2) ? " SYN" : "",
14200 (t->tcp.flags & 1) ? " FIN" : "",
14201 (t->tcp.flags & 4) ? " RST" : "");
14202 }
14203 break;
14204 }
14205
14206 case 0x11: {
14207 #define ARD_AsNumber 3283
14208 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
14209 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
14210 if (udplen >= sizeof(UDPHeader))
14211 {
14212 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
14213 wake = mDNStrue;
14214
14215 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14216 if (mDNSSameIPPort(port, IPSECPort))
14217 {
14218 // Specifically ignore NAT keepalive packets
14219 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
14220 else
14221 {
14222 // Skip over the Non-ESP Marker if present
14223 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
14224 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
14225 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
14226 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
14227 if ((ike->Version & 0x10) == 0x10)
14228 {
14229 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14230 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14231 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
14232 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
14233 }
14234 }
14235 }
14236
14237 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14238 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14239 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14240 // UDP header (8 bytes)
14241 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14242 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
14243
14244 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
14245 }
14246 }
14247 break;
14248
14249 case 0x3A: if (&t->bytes[len] <= end)
14250 {
14251 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
14252 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
14253 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
14254 }
14255 break;
14256
14257 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
14258 break;
14259 }
14260
14261 if (wake)
14262 {
14263 AuthRecord *rr, *r2;
14264
14265 mDNS_Lock(m);
14266 for (rr = m->ResourceRecords; rr; rr=rr->next)
14267 if (rr->resrec.InterfaceID == InterfaceID &&
14268 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14269 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
14270 {
14271 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
14272 for (r2 = m->ResourceRecords; r2; r2=r2->next)
14273 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
14274 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
14275 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
14276 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
14277 break;
14278 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14279 if (!r2 && kaWake) r2 = rr; // So that we wake for keepalive packets, even without a matching SRV record
14280 if (r2)
14281 {
14282 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14283 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
14284 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14285 }
14286 else
14287 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14288 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
14289 }
14290 mDNS_Unlock(m);
14291 }
14292 }
14293
14294 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14295 {
14296 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14297 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14298 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14299 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14300 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14301
14302 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14303 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14304 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14305 // since it points to a an address 14 bytes before pkt.
14306 const EthernetHeader *const eth = (const EthernetHeader *)p;
14307 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
14308 mDNSAddr src, dst;
14309 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14310
14311 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14312 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
14313 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
14314 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14315 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
14316 {
14317 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
14318 const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
14319 if (transEnd > end) transEnd = end;
14320 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
14321 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
14322 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
14323 if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
14324 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
14325 }
14326 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14327 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
14328 {
14329 const mDNSu8 *const trans = p + 54;
14330 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
14331 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14332 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14333 if (end >= trans + RequiredCapLen(pkt->v6.pro))
14334 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14335 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14336 }
14337 }
14338
14339 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14340 {
14341 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14342 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14343 }
14344
14345 #ifndef SPC_DISABLED
14346 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14347 {
14348 if (result == mStatus_NameConflict)
14349 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14350 else if (result == mStatus_MemFree)
14351 {
14352 if (m->SleepState)
14353 m->SPSState = 3;
14354 else
14355 {
14356 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14357 if (m->SPSState)
14358 {
14359 domainlabel name;
14360 ConstructSleepProxyServerName(m, &name);
14361 mDNS_RegisterService(m, srs,
14362 &name, &SleepProxyServiceType, &localdomain,
14363 mDNSNULL, m->SPSSocket->port, // Host, port
14364 mDNSNULL,
14365 (mDNSu8 *)"", 1, // TXT data, length
14366 mDNSNULL, 0, // Subtypes (none)
14367 mDNSInterface_Any, // Interface ID
14368 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14369 }
14370 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14371 }
14372 }
14373 }
14374 #endif
14375
14376 // Called with lock held
14377 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14378 {
14379 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14380 mDNS_DropLockBeforeCallback();
14381
14382 // If turning off SPS, close our socket
14383 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14384 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14385
14386 // If turning off, or changing type, deregister old name
14387 #ifndef SPC_DISABLED
14388 if (m->SPSState == 1 && sps != m->SPSType)
14389 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14390 #endif // SPC_DISABLED
14391
14392 // Record our new SPS parameters
14393 m->SPSType = sps;
14394 m->SPSPortability = port;
14395 m->SPSMarginalPower = marginalpower;
14396 m->SPSTotalPower = totpower;
14397 m->SPSFeatureFlags = features;
14398 // If turning on, open socket and advertise service
14399 if (sps)
14400 {
14401 if (!m->SPSSocket)
14402 {
14403 m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort);
14404 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14405 }
14406 #ifndef SPC_DISABLED
14407 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14408 #endif // SPC_DISABLED
14409 }
14410 else if (m->SPSState)
14411 {
14412 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14413 m->NextScheduledSPS = m->timenow;
14414 }
14415 fail:
14416 mDNS_ReclaimLockAfterCallback();
14417 }
14418
14419 // ***************************************************************************
14420 #if COMPILER_LIKES_PRAGMA_MARK
14421 #pragma mark -
14422 #pragma mark - Startup and Shutdown
14423 #endif
14424
14425 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14426 {
14427 if (storage && numrecords)
14428 {
14429 mDNSu32 i;
14430 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14431 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14432 storage[numrecords-1].next = m->rrcache_free;
14433 m->rrcache_free = storage;
14434 m->rrcache_size += numrecords;
14435 }
14436 }
14437
14438 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14439 {
14440 mDNS_Lock(m);
14441 mDNS_GrowCache_internal(m, storage, numrecords);
14442 mDNS_Unlock(m);
14443 }
14444
14445 mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p,
14446 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14447 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14448 {
14449 mDNSu32 slot;
14450 mDNSs32 timenow;
14451 mStatus result;
14452
14453 if (!rrcachestorage) rrcachesize = 0;
14454
14455 m->p = p;
14456 m->NetworkChanged = 0;
14457 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14458 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
14459 m->DivertMulticastAdvertisements = mDNSfalse;
14460 m->mDNSPlatformStatus = mStatus_Waiting;
14461 m->UnicastPort4 = zeroIPPort;
14462 m->UnicastPort6 = zeroIPPort;
14463 m->PrimaryMAC = zeroEthAddr;
14464 m->MainCallback = Callback;
14465 m->MainContext = Context;
14466 m->rec.r.resrec.RecordType = 0;
14467 m->rec.r.resrec.AnonInfo = mDNSNULL;
14468
14469 // For debugging: To catch and report locking failures
14470 m->mDNS_busy = 0;
14471 m->mDNS_reentrancy = 0;
14472 m->ShutdownTime = 0;
14473 m->lock_rrcache = 0;
14474 m->lock_Questions = 0;
14475 m->lock_Records = 0;
14476
14477 // Task Scheduling variables
14478 result = mDNSPlatformTimeInit();
14479 if (result != mStatus_NoError) return(result);
14480 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14481 timenow = mDNS_TimeNow_NoLock(m);
14482
14483 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14484 m->timenow_last = timenow;
14485 m->NextScheduledEvent = timenow;
14486 m->SuppressSending = timenow;
14487 m->NextCacheCheck = timenow + FutureTime;
14488 m->NextScheduledQuery = timenow + FutureTime;
14489 m->NextScheduledProbe = timenow + FutureTime;
14490 m->NextScheduledResponse = timenow + FutureTime;
14491 m->NextScheduledNATOp = timenow + FutureTime;
14492 m->NextScheduledSPS = timenow + FutureTime;
14493 m->NextScheduledKA = timenow + FutureTime;
14494 m->NextScheduledStopTime = timenow + FutureTime;
14495 m->NextBLEServiceTime = 0; // zero indicates inactive
14496
14497 #if BONJOUR_ON_DEMAND
14498 m->NextBonjourDisableTime = 0; // Timer active when non zero.
14499 m->BonjourEnabled = 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14500 #endif // BONJOUR_ON_DEMAND
14501
14502 m->DelayConflictProcessing = MAX_CONFLICT_PROCESSING_DELAYS;
14503 m->RandomQueryDelay = 0;
14504 m->RandomReconfirmDelay = 0;
14505 m->PktNum = 0;
14506 m->MPktNum = 0;
14507 m->LocalRemoveEvents = mDNSfalse;
14508 m->SleepState = SleepState_Awake;
14509 m->SleepSeqNum = 0;
14510 m->SystemWakeOnLANEnabled = mDNSfalse;
14511 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14512 m->DelaySleep = 0;
14513 m->SleepLimit = 0;
14514
14515 #if APPLE_OSX_mDNSResponder
14516 m->UnicastPacketsSent = 0;
14517 m->MulticastPacketsSent = 0;
14518 m->RemoteSubnet = 0;
14519 #endif // APPLE_OSX_mDNSResponder
14520
14521 // These fields only required for mDNS Searcher...
14522 m->Questions = mDNSNULL;
14523 m->NewQuestions = mDNSNULL;
14524 m->CurrentQuestion = mDNSNULL;
14525 m->LocalOnlyQuestions = mDNSNULL;
14526 m->NewLocalOnlyQuestions = mDNSNULL;
14527 m->RestartQuestion = mDNSNULL;
14528 m->ValidationQuestion = mDNSNULL;
14529 m->rrcache_size = 0;
14530 m->rrcache_totalused = 0;
14531 m->rrcache_active = 0;
14532 m->rrcache_report = 10;
14533 m->rrcache_free = mDNSNULL;
14534
14535 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14536 {
14537 m->rrcache_hash[slot] = mDNSNULL;
14538 m->rrcache_nextcheck[slot] = timenow + FutureTime;;
14539 }
14540
14541 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14542 m->rrauth.rrauth_free = mDNSNULL;
14543
14544 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14545 m->rrauth.rrauth_hash[slot] = mDNSNULL;
14546
14547 // Fields below only required for mDNS Responder...
14548 m->hostlabel.c[0] = 0;
14549 m->nicelabel.c[0] = 0;
14550 m->MulticastHostname.c[0] = 0;
14551 m->HIHardware.c[0] = 0;
14552 m->HISoftware.c[0] = 0;
14553 m->ResourceRecords = mDNSNULL;
14554 m->DuplicateRecords = mDNSNULL;
14555 m->NewLocalRecords = mDNSNULL;
14556 m->NewLocalOnlyRecords = mDNSfalse;
14557 m->CurrentRecord = mDNSNULL;
14558 m->HostInterfaces = mDNSNULL;
14559 m->ProbeFailTime = 0;
14560 m->NumFailedProbes = 0;
14561 m->SuppressProbes = 0;
14562
14563 #ifndef UNICAST_DISABLED
14564 m->NextuDNSEvent = timenow + FutureTime;
14565 m->NextSRVUpdate = timenow + FutureTime;
14566
14567 m->DNSServers = mDNSNULL;
14568
14569 m->Router = zeroAddr;
14570 m->AdvertisedV4 = zeroAddr;
14571 m->AdvertisedV6 = zeroAddr;
14572
14573 m->AuthInfoList = mDNSNULL;
14574
14575 m->ReverseMap.ThisQInterval = -1;
14576 m->StaticHostname.c[0] = 0;
14577 m->FQDN.c[0] = 0;
14578 m->Hostnames = mDNSNULL;
14579 m->AutoTunnelNAT.clientContext = mDNSNULL;
14580
14581 m->WABBrowseQueriesCount = 0;
14582 m->WABLBrowseQueriesCount = 0;
14583 m->WABRegQueriesCount = 0;
14584 m->AutoTargetServices = 0;
14585
14586 #if BONJOUR_ON_DEMAND
14587 m->NumAllInterfaceRecords = 0;
14588 m->NumAllInterfaceQuestions = 0;
14589 #endif
14590 // NAT traversal fields
14591 m->LLQNAT.clientCallback = mDNSNULL;
14592 m->LLQNAT.clientContext = mDNSNULL;
14593 m->NATTraversals = mDNSNULL;
14594 m->CurrentNATTraversal = mDNSNULL;
14595 m->retryIntervalGetAddr = 0; // delta between time sent and retry
14596 m->retryGetAddr = timenow + FutureTime; // absolute time when we retry
14597 m->ExtAddress = zerov4Addr;
14598 m->PCPNonce[0] = mDNSRandom(-1);
14599 m->PCPNonce[1] = mDNSRandom(-1);
14600 m->PCPNonce[2] = mDNSRandom(-1);
14601
14602 m->NATMcastRecvskt = mDNSNULL;
14603 m->LastNATupseconds = 0;
14604 m->LastNATReplyLocalTime = timenow;
14605 m->LastNATMapResultCode = NATErr_None;
14606
14607 m->UPnPInterfaceID = 0;
14608 m->SSDPSocket = mDNSNULL;
14609 m->SSDPWANPPPConnection = mDNSfalse;
14610 m->UPnPRouterPort = zeroIPPort;
14611 m->UPnPSOAPPort = zeroIPPort;
14612 m->UPnPRouterURL = mDNSNULL;
14613 m->UPnPWANPPPConnection = mDNSfalse;
14614 m->UPnPSOAPURL = mDNSNULL;
14615 m->UPnPRouterAddressString = mDNSNULL;
14616 m->UPnPSOAPAddressString = mDNSNULL;
14617 m->SPSType = 0;
14618 m->SPSPortability = 0;
14619 m->SPSMarginalPower = 0;
14620 m->SPSTotalPower = 0;
14621 m->SPSFeatureFlags = 0;
14622 m->SPSState = 0;
14623 m->SPSProxyListChanged = mDNSNULL;
14624 m->SPSSocket = mDNSNULL;
14625 m->SPSBrowseCallback = mDNSNULL;
14626 m->ProxyRecords = 0;
14627
14628 m->DNSPushServers = mDNSNULL;
14629 m->DNSPushZones = mDNSNULL;
14630 #endif
14631
14632 #if APPLE_OSX_mDNSResponder
14633 m->TunnelClients = mDNSNULL;
14634
14635 #if !NO_WCF
14636 CHECK_WCF_FUNCTION(WCFConnectionNew)
14637 {
14638 m->WCF = WCFConnectionNew();
14639 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14640 }
14641 #endif
14642
14643 #endif
14644
14645 return(result);
14646 }
14647
14648 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14649 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14650 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14651 {
14652 mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context);
14653 if (result != mStatus_NoError)
14654 return(result);
14655
14656 result = mDNSPlatformInit(m);
14657
14658 #ifndef UNICAST_DISABLED
14659 // It's better to do this *after* the platform layer has set up the
14660 // interface list and security credentials
14661 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
14662 #endif
14663
14664 return(result);
14665 }
14666
14667 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14668 {
14669 if (m->SPSState == 1)
14670 {
14671 domainlabel name, newname;
14672 #ifndef SPC_DISABLED
14673 domainname type, domain;
14674 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14675 #endif // SPC_DISABLED
14676 ConstructSleepProxyServerName(m, &newname);
14677 if (!SameDomainLabelCS(name.c, newname.c))
14678 {
14679 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14680 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14681 // it will reregister the service under the new name
14682 m->SPSState = 2;
14683 #ifndef SPC_DISABLED
14684 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14685 #endif // SPC_DISABLED
14686 }
14687 }
14688
14689 if (m->MainCallback)
14690 m->MainCallback(m, mStatus_ConfigChanged);
14691 }
14692
14693 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14694 {
14695 (void)m; // unused
14696 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14697 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14698 }
14699
14700 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
14701 {
14702 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14703 cr->resrec.rrtype == kDNSType_A ||
14704 cr->resrec.rrtype == kDNSType_AAAA ||
14705 cr->resrec.rrtype == kDNSType_SRV ||
14706 cr->resrec.rrtype == kDNSType_CNAME;
14707
14708 (void) lameduck;
14709 (void) ptr;
14710 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
14711 purge ? "purging" : "reconfirming",
14712 lameduck ? "lame duck" : "new",
14713 ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
14714
14715 if (purge)
14716 {
14717 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14718 mDNS_PurgeCacheResourceRecord(m, cr);
14719 }
14720 else
14721 {
14722 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14723 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14724 }
14725 }
14726
14727 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
14728 {
14729 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14730 CacheRecord *rp;
14731 mDNSu8 validatingResponse = 0;
14732
14733 // For DNSSEC questions, purge the corresponding RRSIGs also.
14734 if (DNSSECQuestion(q))
14735 {
14736 validatingResponse = q->ValidatingResponse;
14737 q->ValidatingResponse = mDNStrue;
14738 }
14739 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14740 {
14741 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14742 {
14743 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
14744 mDNS_PurgeCacheResourceRecord(m, rp);
14745 }
14746 }
14747 if (DNSSECQuestion(q))
14748 {
14749 q->ValidatingResponse = validatingResponse;
14750 }
14751 }
14752
14753 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14754 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14755 // Just re-issuing the question for RRSIGs does not work in practice as the response
14756 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14757 //
14758 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14759 // have the cached NSECs, purge them. For positive responses, if we don't have the
14760 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14761 // them.
14762 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q)
14763 {
14764 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14765 CacheRecord *rp;
14766
14767 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14768 {
14769 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14770 {
14771 if (rp->resrec.RecordType != kDNSRecordTypePacketNegative || !rp->nsec)
14772 {
14773 if (!rp->CRDNSSECQuestion)
14774 {
14775 LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m, rp));
14776 mDNS_PurgeCacheResourceRecord(m, rp);
14777 }
14778 }
14779 }
14780 }
14781 }
14782
14783 // Check for a positive unicast response to the question but with qtype
14784 mDNSexport mDNSBool mDNS_CheckForCacheRecord(mDNS *const m, DNSQuestion *q, mDNSu16 qtype)
14785 {
14786 DNSQuestion question;
14787 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14788 CacheRecord *rp;
14789
14790 // Create an identical question but with qtype
14791 mDNS_SetupQuestion(&question, q->InterfaceID, &q->qname, qtype, mDNSNULL, mDNSNULL);
14792 question.qDNSServer = q->qDNSServer;
14793
14794 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14795 {
14796 if (!rp->resrec.InterfaceID && rp->resrec.RecordType != kDNSRecordTypePacketNegative &&
14797 SameNameRecordAnswersQuestion(&rp->resrec, &question))
14798 {
14799 LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m, rp));
14800 return mDNStrue;
14801 }
14802 }
14803 return mDNSfalse;
14804 }
14805
14806 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14807 {
14808 DNSQuestion *qptr;
14809
14810 (void) m;
14811
14812 if (q->DuplicateOf)
14813 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14814
14815 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14816 // of events for all of them are consistent. Duplicates for a question are always inserted
14817 // after in the list.
14818 q->qDNSServer = new;
14819 for (qptr = q->next ; qptr; qptr = qptr->next)
14820 {
14821 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14822 }
14823 }
14824
14825 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14826 {
14827 McastResolver *mr;
14828 DNSServer *ptr;
14829
14830 if (delete)
14831 {
14832 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14833 {
14834 ptr->penaltyTime = 0;
14835 NumUnicastDNSServers--;
14836 ptr->flags |= DNSServer_FlagDelete;
14837 #if APPLE_OSX_mDNSResponder
14838 if (ptr->flags & DNSServer_FlagUnreachable)
14839 NumUnreachableDNSServers--;
14840 #endif
14841 }
14842 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14843 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14844 // API
14845 for (mr = m->McastResolvers; mr; mr = mr->next)
14846 mr->flags |= McastResolver_FlagDelete;
14847 }
14848 else
14849 {
14850 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14851 {
14852 ptr->penaltyTime = 0;
14853 NumUnicastDNSServers++;
14854 ptr->flags &= ~DNSServer_FlagDelete;
14855 #if APPLE_OSX_mDNSResponder
14856 if (ptr->flags & DNSServer_FlagUnreachable)
14857 NumUnreachableDNSServers++;
14858 #endif
14859 }
14860 for (mr = m->McastResolvers; mr; mr = mr->next)
14861 mr->flags &= ~McastResolver_FlagDelete;
14862 }
14863 }
14864
14865 mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn)
14866 {
14867 // Did our FQDN change?
14868 if (!SameDomainName(fqdn, &m->FQDN))
14869 {
14870 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14871
14872 AssignDomainName(&m->FQDN, fqdn);
14873
14874 if (m->FQDN.c[0])
14875 {
14876 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14877 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14878 }
14879 }
14880 }
14881
14882 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14883 {
14884 mDNSu32 slot;
14885 CacheGroup *cg;
14886 CacheRecord *cr;
14887 mDNSBool Restart = mDNSfalse;
14888 mDNSAddr v4, v6, r;
14889 domainname fqdn;
14890 DNSServer *ptr, **p = &m->DNSServers;
14891 const DNSServer *oldServers = m->DNSServers;
14892 DNSQuestion *q;
14893 McastResolver *mr, **mres = &m->McastResolvers;
14894
14895 debugf("uDNS_SetupDNSConfig: entry");
14896
14897 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14898 uDNS_SetupWABQueries(m);
14899
14900 mDNS_Lock(m);
14901
14902 // We need to first mark all the entries to be deleted. If the configuration changed, then
14903 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14904 //
14905 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14906 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14907 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14908 // for the dns configuration change notification.
14909 SetConfigState(m, mDNStrue);
14910 if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14911 {
14912 SetDynDNSHostNameIfChanged(m, &fqdn);
14913 SetConfigState(m, mDNSfalse);
14914 mDNS_Unlock(m);
14915 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14916 return mStatus_NoError;
14917 }
14918
14919 // For now, we just delete the mcast resolvers. We don't deal with cache or
14920 // questions here. Neither question nor cache point to mcast resolvers. Questions
14921 // do inherit the timeout values from mcast resolvers. But we don't bother
14922 // affecting them as they never change.
14923 while (*mres)
14924 {
14925 if (((*mres)->flags & McastResolver_FlagDelete) != 0)
14926 {
14927 mr = *mres;
14928 *mres = (*mres)->next;
14929 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14930 mDNSPlatformMemFree(mr);
14931 }
14932 else
14933 {
14934 (*mres)->flags &= ~McastResolver_FlagNew;
14935 mres = &(*mres)->next;
14936 }
14937 }
14938
14939 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14940 //
14941 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14942 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14943 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14944 // DNSServers and flush the cache.
14945 //
14946 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14947 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14948 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14949 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14950 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14951 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14952 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14953 // the same resGroupID.
14954 //
14955 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14956 // of the old followed by ADD of the new records.
14957 //
14958 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14959 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14960 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14961 //
14962 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14963 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14964 // non-scoped question and vice versa.
14965 //
14966 #if USE_DNS64
14967 DNS64RestartQuestions(m);
14968 #endif
14969 for (q = m->Questions; q; q=q->next)
14970 {
14971 if (!mDNSOpaque16IsZero(q->TargetQID))
14972 {
14973 DNSServer *s, *t;
14974 DNSQuestion *qptr;
14975 if (q->DuplicateOf) continue;
14976 SetValidDNSServers(m, q);
14977 q->triedAllServersOnce = 0;
14978 s = GetServerForQuestion(m, q);
14979 t = q->qDNSServer;
14980 if (t != s)
14981 {
14982 mDNSBool old, new;
14983 // If DNS Server for this question has changed, reactivate it
14984 LogInfo("uDNS_SetupDNSConfig: Updating DNS Server from %#a:%d (%##s) to %#a:%d (%##s) for question %##s (%s) (scope:%p)",
14985 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
14986 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
14987 q->qname.c, DNSTypeName(q->qtype), q->InterfaceID);
14988
14989 old = q->SuppressQuery;
14990 new = ShouldSuppressUnicastQuery(m, q, s);
14991 if (old != new)
14992 {
14993 // Changing the DNS server affected the SuppressQuery status. We need to
14994 // deliver RMVs for the previous ADDs (if any) before switching to the new
14995 // DNSServer. To keep it simple, we walk all the questions and mark them
14996 // to be restarted and then handle all of them at once.
14997 q->Restart = 1;
14998 q->SuppressQuery = new;
14999 for (qptr = q->next ; qptr; qptr = qptr->next)
15000 {
15001 if (qptr->DuplicateOf == q)
15002 qptr->Restart = 1;
15003 }
15004 Restart = mDNStrue;
15005 }
15006 else
15007 {
15008 DNSServerChangeForQuestion(m, q, s);
15009 q->unansweredQueries = 0;
15010
15011 // If we had sent a query out to DNSServer "t" and we are changing to "s", we
15012 // need to ignore the responses coming back from "t" as the DNS configuration
15013 // has changed e.g., when a new interface is coming up and that becomes the primary
15014 // interface, we switch to the DNS servers configured for the primary interface. In
15015 // this case, we should not accept responses associated with the previous interface as
15016 // the "name" could resolve differently on this new primary interface. Hence, discard
15017 // in-flight responses.
15018 q->TargetQID = mDNS_NewMessageID(m);
15019
15020 if (!QuerySuppressed(q))
15021 {
15022 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
15023 ActivateUnicastQuery(m, q, mDNStrue);
15024 // ActivateUnicastQuery is called for duplicate questions also as it does something
15025 // special for AutoTunnel questions
15026 for (qptr = q->next ; qptr; qptr = qptr->next)
15027 {
15028 if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
15029 }
15030 }
15031 }
15032 }
15033 else
15034 {
15035 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
15036 q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
15037 for (qptr = q->next ; qptr; qptr = qptr->next)
15038 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
15039 }
15040 }
15041 }
15042 if (Restart)
15043 RestartUnicastQuestions(m);
15044
15045 FORALL_CACHERECORDS(slot, cg, cr)
15046 {
15047 if (cr->resrec.InterfaceID)
15048 continue;
15049
15050 // We already walked the questions and restarted/reactivated them if the dns server
15051 // change affected the question. That should take care of updating the cache. But
15052 // what if there is no active question at this point when the DNS server change
15053 // happened ? There could be old cache entries lying around and if we don't flush
15054 // them, a new question after the DNS server change could pick up these stale
15055 // entries and get a wrong answer.
15056 //
15057 // For cache entries that have active questions we might have skipped rescheduling
15058 // the questions if they were suppressed (see above). To keep it simple, we walk
15059 // all the cache entries to make sure that there are no stale entries. We use the
15060 // active question's InterfaceID/ServiceID for looking up the right DNS server.
15061 // Note that the unscoped value for ServiceID is -1.
15062 //
15063 // Note: If GetServerForName returns NULL, it could either mean that there are no
15064 // DNS servers or no matching DNS servers for this question. In either case,
15065 // the cache should get purged below when we process deleted DNS servers.
15066
15067 ptr = GetServerForName(m, cr->resrec.name,
15068 (cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL),
15069 (cr->CRActiveQuestion ? cr->CRActiveQuestion->ServiceID : -1));
15070
15071 // Purge or Reconfirm if this cache entry would use the new DNS server
15072 if (ptr && (ptr != cr->resrec.rDNSServer))
15073 {
15074 // As the DNSServers for this cache record is not the same anymore, we don't
15075 // want any new questions to pick this old value. If there is no active question,
15076 // we can't possibly re-confirm, so purge in that case. If it is a DNSSEC question,
15077 // purge the cache as the DNSSEC capabilities of the DNS server may have changed.
15078
15079 if (cr->CRActiveQuestion == mDNSNULL || DNSSECQuestion(cr->CRActiveQuestion))
15080 {
15081 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s, New DNS server %#a , Old DNS server %#a", CRDisplayString(m, cr),
15082 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
15083 cr->resrec.mortality = Mortality_Mortal;
15084 mDNS_PurgeCacheResourceRecord(m, cr);
15085 }
15086 else
15087 {
15088 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", CRDisplayString(m, cr),
15089 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
15090 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
15091 }
15092 }
15093
15094 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15095 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15096 if (!cr->resrec.rDNSServer && cr->CRActiveQuestion && cr->CRActiveQuestion->qDNSServer)
15097 {
15098 cr->resrec.rDNSServer = cr->CRActiveQuestion->qDNSServer;
15099 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr->resrec.rDNSServer->addr, CRDisplayString(m, cr));
15100 }
15101 }
15102
15103 while (*p)
15104 {
15105 if (((*p)->flags & DNSServer_FlagDelete) != 0)
15106 {
15107 // Scan our cache, looking for uDNS records that we would have queried this server for.
15108 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
15109 // different DNS servers can give different answers to the same question.
15110 ptr = *p;
15111 FORALL_CACHERECORDS(slot, cg, cr)
15112 {
15113 if (cr->resrec.InterfaceID) continue;
15114 if (cr->resrec.rDNSServer == ptr)
15115 {
15116 // If we don't have an active question for this cache record, neither Purge can
15117 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
15118 // pointer on the record NULL so that we don't point to freed memory (We might dereference
15119 // DNSServer pointers from resource record for logging purposes).
15120 //
15121 // If there is an active question, point to its DNSServer as long as it does not point to the
15122 // freed one. We already went through the questions above and made them point at either the
15123 // new server or NULL if there is no server.
15124
15125 if (cr->CRActiveQuestion)
15126 {
15127 DNSQuestion *qptr = cr->CRActiveQuestion;
15128
15129 if (qptr->qDNSServer == ptr)
15130 {
15131 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15132 " to be freed", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID, &ptr->addr);
15133 qptr->validDNSServers = zeroOpaque128;
15134 qptr->qDNSServer = mDNSNULL;
15135 cr->resrec.rDNSServer = mDNSNULL;
15136 }
15137 else
15138 {
15139 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15140 " resetting to question's DNSServer Address %#a", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype),
15141 qptr->InterfaceID, &ptr->addr, (qptr->qDNSServer) ? &qptr->qDNSServer->addr : mDNSNULL);
15142 cr->resrec.rDNSServer = qptr->qDNSServer;
15143 }
15144 }
15145 else
15146 {
15147 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
15148 cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
15149 cr->resrec.rDNSServer = mDNSNULL;
15150 }
15151
15152 cr->resrec.mortality = Mortality_Mortal;
15153 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
15154 }
15155 }
15156 *p = (*p)->next;
15157 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s) %d", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, NumUnicastDNSServers);
15158 mDNSPlatformMemFree(ptr);
15159 }
15160 else
15161 {
15162 (*p)->flags &= ~DNSServer_FlagNew;
15163 p = &(*p)->next;
15164 }
15165 }
15166
15167 // 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).
15168 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15169 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15170 // 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.
15171 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
15172 {
15173 int count = 0;
15174 FORALL_CACHERECORDS(slot, cg, cr)
15175 {
15176 if (!cr->resrec.InterfaceID)
15177 {
15178 mDNS_PurgeCacheResourceRecord(m, cr);
15179 count++;
15180 }
15181 }
15182 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15183 m->DNSServers ? "DNS server became" : "No DNS servers", count);
15184
15185 // Force anything that needs to get zone data to get that information again
15186 RestartRecordGetZoneData(m);
15187 }
15188
15189 SetDynDNSHostNameIfChanged(m, &fqdn);
15190
15191 mDNS_Unlock(m);
15192
15193 // handle router and primary interface changes
15194 v4 = v6 = r = zeroAddr;
15195 v4.type = r.type = mDNSAddrType_IPv4;
15196
15197 if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
15198 {
15199 mDNS_SetPrimaryInterfaceInfo(m,
15200 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
15201 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
15202 !mDNSIPv4AddressIsZero(r.ip.v4) ? &r : mDNSNULL);
15203 }
15204 else
15205 {
15206 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
15207 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
15208 }
15209
15210 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
15211 return mStatus_NoError;
15212 }
15213
15214 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
15215 {
15216 m->mDNSPlatformStatus = result;
15217 if (m->MainCallback)
15218 {
15219 mDNS_Lock(m);
15220 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15221 m->MainCallback(m, mStatus_NoError);
15222 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15223 mDNS_Unlock(m);
15224 }
15225 }
15226
15227 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
15228 {
15229 m->CurrentRecord = start;
15230 while (m->CurrentRecord)
15231 {
15232 AuthRecord *rr = m->CurrentRecord;
15233 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15234 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
15235 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15236 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
15237 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
15238 else if (rr->AnnounceCount > 1)
15239 {
15240 rr->AnnounceCount = 1;
15241 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
15242 }
15243 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15244 // new records could have been added to the end of the list as a result of that call.
15245 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
15246 m->CurrentRecord = rr->next;
15247 }
15248 }
15249
15250 mDNSexport void mDNS_StartExit(mDNS *const m)
15251 {
15252 AuthRecord *rr;
15253
15254 mDNS_Lock(m);
15255
15256 LogInfo("mDNS_StartExit");
15257 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
15258
15259 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
15260
15261 #if APPLE_OSX_mDNSResponder
15262 #if !NO_WCF
15263 CHECK_WCF_FUNCTION(WCFConnectionDealloc)
15264 {
15265 if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
15266 }
15267 #endif
15268 #endif
15269
15270 #ifndef UNICAST_DISABLED
15271 {
15272 SearchListElem *s;
15273 SuspendLLQs(m);
15274 // Don't need to do SleepRecordRegistrations() here
15275 // because we deregister all records and services later in this routine
15276 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
15277
15278 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15279 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15280 // and we may crash because the list still contains dangling pointers.
15281 for (s = SearchList; s; s = s->next)
15282 while (s->AuthRecs)
15283 {
15284 ARListElem *dereg = s->AuthRecs;
15285 s->AuthRecs = s->AuthRecs->next;
15286 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
15287 }
15288 }
15289 #endif
15290
15291 DeadvertiseAllInterfaceRecords(m);
15292
15293 // Shut down all our active NAT Traversals
15294 while (m->NATTraversals)
15295 {
15296 NATTraversalInfo *t = m->NATTraversals;
15297 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15298
15299 // After stopping the NAT Traversal, we zero out the fields.
15300 // This has particularly important implications for our AutoTunnel records --
15301 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15302 // handlers to just turn around and attempt to re-register those same records.
15303 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15304 // to not do this.
15305 t->ExternalAddress = zerov4Addr;
15306 t->NewAddress = zerov4Addr;
15307 t->ExternalPort = zeroIPPort;
15308 t->RequestedPort = zeroIPPort;
15309 t->Lifetime = 0;
15310 t->Result = mStatus_NoError;
15311 }
15312
15313 // Make sure there are nothing but deregistering records remaining in the list
15314 if (m->CurrentRecord)
15315 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
15316
15317 // We're in the process of shutting down, so queries, etc. are no longer available.
15318 // Consequently, determining certain information, e.g. the uDNS update server's IP
15319 // address, will not be possible. The records on the main list are more likely to
15320 // already contain such information, so we deregister the duplicate records first.
15321 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
15322 DeregLoop(m, m->DuplicateRecords);
15323 LogInfo("mDNS_StartExit: Deregistering resource records");
15324 DeregLoop(m, m->ResourceRecords);
15325
15326 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15327 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15328 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
15329 {
15330 m->NextScheduledResponse = m->timenow;
15331 m->SuppressSending = 0;
15332 }
15333
15334 if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
15335 else LogInfo("mDNS_StartExit: No deregistering records remain");
15336
15337 for (rr = m->DuplicateRecords; rr; rr = rr->next)
15338 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
15339
15340 // If any deregistering records remain, send their deregistration announcements before we exit
15341 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
15342
15343 mDNS_Unlock(m);
15344
15345 LogInfo("mDNS_StartExit: done");
15346 }
15347
15348 mDNSexport void mDNS_FinalExit(mDNS *const m)
15349 {
15350 mDNSu32 rrcache_active = 0;
15351 mDNSu32 rrcache_totalused = m->rrcache_totalused;
15352 mDNSu32 slot;
15353 AuthRecord *rr;
15354
15355 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
15356 mDNSPlatformClose(m);
15357
15358 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
15359 {
15360 while (m->rrcache_hash[slot])
15361 {
15362 CacheGroup *cg = m->rrcache_hash[slot];
15363 while (cg->members)
15364 {
15365 CacheRecord *cr = cg->members;
15366 cg->members = cg->members->next;
15367 if (cr->CRActiveQuestion) rrcache_active++;
15368 ReleaseCacheRecord(m, cr);
15369 }
15370 cg->rrcache_tail = &cg->members;
15371 ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
15372 }
15373 }
15374 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
15375 if (rrcache_active != m->rrcache_active)
15376 LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active);
15377
15378 for (rr = m->ResourceRecords; rr; rr = rr->next)
15379 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15380
15381 LogInfo("mDNS_FinalExit: done");
15382 }
15383
15384 #ifdef UNIT_TEST
15385 #include "../unittests/mdns_ut.c"
15386 #endif