]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-878.50.17.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2017 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 q->metrics = metrics;
552 #endif
553 if (sock)
554 {
555 // 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.
556 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
557 else
558 {
559 // Transplant the old socket into the new question, and copy the query ID across too.
560 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
561 q->LocalSocket = sock;
562 q->TargetQID = id;
563 }
564 }
565 }
566 }
567
568 #ifdef USE_LIBIDN
569
570 #include <unicode/uidna.h>
571
572 // #define DEBUG_PUNYCODE 1
573
574 mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end)
575 {
576 UErrorCode errorCode = U_ZERO_ERROR;
577 UIDNAInfo info = UIDNA_INFO_INITIALIZER;
578 UIDNA *uts46 = uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE, &errorCode);
579 int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, end-(dst+1), &info, &errorCode);
580 uidna_close(uts46);
581 #if DEBUG_PUNYCODE
582 if (errorCode) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src, errorCode);
583 if (info.errors) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src, info.errors);
584 if (len > MAX_DOMAIN_LABEL) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src, len);
585 #endif
586 if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL;
587 *dst = len;
588 return(dst + 1 + len);
589 }
590
591 mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d)
592 {
593 int i;
594 for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue;
595 return mDNSfalse;
596 }
597
598 mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d)
599 {
600 const mDNSu8 *ptr = d->c;
601 const mDNSu8 *ans = mDNSNULL;
602 while (ptr[0])
603 {
604 const mDNSu8 *const next = ptr + 1 + ptr[0];
605 if (ptr[0] > MAX_DOMAIN_LABEL || next >= d->c + MAX_DOMAIN_NAME) return mDNSNULL;
606 if (IsHighASCIILabel(ptr)) ans = ptr;
607 ptr = next;
608 }
609 return ans;
610 }
611
612 mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname)
613 {
614 const mDNSu8 *h = FindLastHighASCIILabel(&q->qname);
615 #if DEBUG_PUNYCODE
616 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h);
617 #endif
618 if (!h) return mDNSfalse; // There are no high-ascii labels to convert
619
620 mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME);
621 if (!dst)
622 return mDNSfalse; // The label was not convertible to Punycode
623 else
624 {
625 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
626 const mDNSu8 *const src = h + 1 + h[0];
627 const mDNSu8 remainder = DomainNameLength((domainname*)src);
628 if (dst + remainder > newname->c + MAX_DOMAIN_NAME) return mDNSfalse; // Name too long -- cannot be converted to Punycode
629
630 mDNSPlatformMemCopy(newname->c, q->qname.c, h - q->qname.c); // Fill in the leading part
631 mDNSPlatformMemCopy(dst, src, remainder); // Fill in the trailing part
632 #if DEBUG_PUNYCODE
633 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c);
634 #endif
635 return mDNStrue;
636 }
637 }
638
639 #endif // USE_LIBIDN
640
641 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
642 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
643 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
644 {
645 DNSQuestion *q = m->CurrentQuestion;
646 mDNSBool followcname;
647
648 if (!q)
649 {
650 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
651 return;
652 }
653
654 followcname = FollowCNAME(q, &rr->resrec, AddRecord);
655
656 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
657 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
658 {
659 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
660 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
661 return;
662 }
663
664 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
665 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
666 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
667 if (q->QuestionCallback && !q->NoAnswer)
668 {
669 q->CurrentAnswers += AddRecord ? 1 : -1;
670 if (UniqueLocalOnlyRecord(rr))
671 {
672 if (!followcname || q->ReturnIntermed)
673 {
674 // Don't send this packet on the wire as we answered from /etc/hosts
675 q->ThisQInterval = 0;
676 q->LOAddressAnswers += AddRecord ? 1 : -1;
677 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
678 }
679 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
680 // The callback above could have caused the question to stop. Detect that
681 // using m->CurrentQuestion
682 if (followcname && m->CurrentQuestion == q)
683 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
684 return;
685 }
686 else
687 {
688 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
689 }
690 }
691 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
692 }
693
694 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
695 {
696 if (m->CurrentQuestion)
697 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
698 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
699 m->CurrentQuestion = m->Questions;
700 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
701 {
702 mDNSBool answered;
703 DNSQuestion *q = m->CurrentQuestion;
704 if (RRAny(rr))
705 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
706 else
707 answered = LocalOnlyRecordAnswersQuestion(rr, q);
708 if (answered)
709 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
710 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
711 m->CurrentQuestion = q->next;
712 }
713 m->CurrentQuestion = mDNSNULL;
714 }
715
716 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
717 // delivers the appropriate add/remove events to listening questions:
718 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
719 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
720 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
721 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
722 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
723 //
724 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
725 // and by mDNS_Deregister_internal()
726
727 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
728 {
729 if (m->CurrentQuestion)
730 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
731 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
732
733 m->CurrentQuestion = m->LocalOnlyQuestions;
734 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
735 {
736 mDNSBool answered;
737 DNSQuestion *q = m->CurrentQuestion;
738 // We are called with both LocalOnly/P2P record or a regular AuthRecord
739 if (RRAny(rr))
740 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
741 else
742 answered = LocalOnlyRecordAnswersQuestion(rr, q);
743 if (answered)
744 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
745 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
746 m->CurrentQuestion = q->next;
747 }
748
749 m->CurrentQuestion = mDNSNULL;
750
751 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
752 if (rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P)
753 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, rr, AddRecord);
754
755 }
756
757 // ***************************************************************************
758 #if COMPILER_LIKES_PRAGMA_MARK
759 #pragma mark -
760 #pragma mark - Resource Record Utility Functions
761 #endif
762
763 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
764
765 #define ResourceRecordIsValidAnswer(RR) ( ((RR)->resrec.RecordType & kDNSRecordTypeActiveMask) && \
766 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
767 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
768 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
769
770 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
771 (ResourceRecordIsValidAnswer(RR) && \
772 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
773
774 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
775 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
776
777 // See RFC 6762: "8.3 Announcing"
778 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
779 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
780 #define InitialAnnounceCount ((mDNSu8)4)
781
782 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
783 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
784 // and then if the machine fails to wake, 3 goodbye packets).
785 #define GoodbyeCount ((mDNSu8)3)
786 #define WakeupCount ((mDNSu8)18)
787 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
788
789 // Number of wakeups we send if WakeOnResolve is set in the question
790 #define InitialWakeOnResolveCount ((mDNSu8)3)
791
792 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
793 // This means that because the announce interval is doubled after sending the first packet, the first
794 // observed on-the-wire inter-packet interval between announcements is actually one second.
795 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
796 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
797 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
798 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
799
800 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
801 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
802 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
803
804 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
805 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
806 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
807
808 // Adjustment factor to avoid race condition (used for unicast cache entries) :
809 // 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.
810 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
811 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
812 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
813 // We adjust the 100 second TTL to 127. This means that when we do our 80% query at 102 seconds,
814 // the cached copy at our local caching server will already have expired, so the server will be forced
815 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
816
817 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
818 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
819
820 #define MaxUnansweredQueries 4
821
822 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
823 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
824 // TTL and rdata may differ.
825 // This is used for cache flush management:
826 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
827 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
828
829 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
830
831 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
832
833 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
834 {
835 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
836 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
837 if (r1->resrec.InterfaceID &&
838 r2->resrec.InterfaceID &&
839 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
840 return (mDNSBool)(
841 r1->resrec.rrclass == r2->resrec.rrclass &&
842 r1->resrec.namehash == r2->resrec.namehash &&
843 SameDomainName(r1->resrec.name, r2->resrec.name));
844 }
845
846 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
847 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
848 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
849 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
850 // so a response of any type should match, even if it is not actually the type the client plans to use.
851
852 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
853 // and require the rrtypes to match for the rdata to be considered potentially conflicting
854 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
855 {
856 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
857 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
858 if (pktrr->resrec.InterfaceID &&
859 authrr->resrec.InterfaceID &&
860 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
861 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
862 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
863 if ((authrr->resrec.InterfaceID == mDNSInterface_Any) &&
864 !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse);
865 return (mDNSBool)(
866 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
867 pktrr->resrec.namehash == authrr->resrec.namehash &&
868 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
869 }
870
871 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
872 // This is the information that the requester believes to be correct.
873 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
874 // This is the information that we believe to be correct.
875 // We've already determined that we plan to give this answer on this interface
876 // (either the record is non-specific, or it is specific to this interface)
877 // so now we just need to check the name, type, class, rdata and TTL.
878 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
879 {
880 // If RR signature is different, or data is different, then don't suppress our answer
881 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
882
883 // If the requester's indicated TTL is less than half the real TTL,
884 // we need to give our answer before the requester's copy expires.
885 // If the requester's indicated TTL is at least half the real TTL,
886 // then we can suppress our answer this time.
887 // If the requester's indicated TTL is greater than the TTL we believe,
888 // then that's okay, and we don't need to do anything about it.
889 // (If two responders on the network are offering the same information,
890 // that's okay, and if they are offering the information with different TTLs,
891 // the one offering the lower TTL should defer to the one offering the higher TTL.)
892 return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
893 }
894
895 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
896 {
897 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
898 {
899 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
900 {
901 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
902 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
903 }
904 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
905 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
906 // Some defensive code:
907 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
908 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
909 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
910 if (m->NextScheduledProbe - m->timenow < 0)
911 m->NextScheduledProbe = m->timenow;
912 }
913 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
914 {
915 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
916 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
917 }
918 }
919
920 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
921 {
922 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
923 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
924
925 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
926 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
927 // records that are going to probe, then we delay its first announcement so that it will
928 // go out synchronized with the first announcement for the other records that *are* probing.
929 // This is a minor performance tweak that helps keep groups of related records synchronized together.
930 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
931 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
932 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
933 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
934 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
935
936 if (rr->ProbeCount)
937 {
938 // If we have no probe suppression time set, or it is in the past, set it now
939 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
940 {
941 // To allow us to aggregate probes when a group of services are registered together,
942 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
943 // This means the common-case behaviour is:
944 // randomized wait; probe
945 // 1/4 second wait; probe
946 // 1/4 second wait; probe
947 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
948 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
949
950 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
951 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
952 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
953 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
954 m->SuppressProbes = m->timenow;
955
956 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
957 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
958 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
959 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
960 m->SuppressProbes = m->timenow;
961
962 // except... don't expect to be able to send before the m->SuppressSending timer fires
963 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
964 m->SuppressProbes = NonZeroTime(m->SuppressSending);
965
966 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
967 {
968 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
969 m->SuppressProbes - m->timenow,
970 m->NextScheduledProbe - m->timenow,
971 m->NextScheduledQuery - m->timenow,
972 m->SuppressSending,
973 m->SuppressSending - m->timenow);
974 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
975 }
976 }
977 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
978 }
979 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
980 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
981 else if ((rr->resrec.RecordType != kDNSRecordTypeKnownUnique) && (rr->resrec.RecordType != kDNSRecordTypeShared) && m->SuppressProbes && (m->SuppressProbes - m->timenow >= 0))
982 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
983 else
984 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
985
986 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
987 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
988 // After three probes one second apart with no answer, we conclude the client is now sleeping
989 // and we can begin broadcasting our announcements to take over ownership of that IP address.
990 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
991 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
992 if (rr->AddressProxy.type)
993 rr->LastAPTime = m->timenow;
994
995 // Set LastMCTime to now, to inhibit multicast responses
996 // (no need to send additional multicast responses when we're announcing anyway)
997 rr->LastMCTime = m->timenow;
998 rr->LastMCInterface = mDNSInterfaceMark;
999
1000 SetNextAnnounceProbeTime(m, rr);
1001 }
1002
1003 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
1004 {
1005 const domainname *target;
1006 if (rr->AutoTarget)
1007 {
1008 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
1009 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
1010 // with the port number in our advertised SRV record automatically tracking the external mapped port.
1011 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
1012 if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
1013 }
1014
1015 target = GetServiceTarget(m, rr);
1016 if (!target || target->c[0] == 0)
1017 {
1018 // defer registration until we've got a target
1019 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
1020 rr->state = regState_NoTarget;
1021 return mDNSNULL;
1022 }
1023 else
1024 {
1025 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
1026 return target;
1027 }
1028 }
1029
1030 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1031 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1032 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
1033 {
1034 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
1035 const domainname *newname = &m->MulticastHostname;
1036
1037 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
1038
1039 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
1040 {
1041 const domainname *const n = SetUnicastTargetToHostName(m, rr);
1042 if (n) newname = n;
1043 else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
1044 }
1045
1046 if (target && SameDomainName(target, newname))
1047 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
1048
1049 if (target && !SameDomainName(target, newname))
1050 {
1051 AssignDomainName(target, newname);
1052 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
1053
1054 // If we're in the middle of probing this record, we need to start again,
1055 // because changing its rdata may change the outcome of the tie-breaker.
1056 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1057 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1058
1059 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1060 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1061 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1062 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
1063 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1064 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1065
1066 rr->AnnounceCount = InitialAnnounceCount;
1067 rr->RequireGoodbye = mDNSfalse;
1068 rr->ProbeRestartCount = 0;
1069 InitializeLastAPTime(m, rr);
1070 }
1071 }
1072
1073 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
1074 {
1075 if (rr->RecordCallback)
1076 {
1077 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1078 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1079 rr->Acknowledged = mDNStrue;
1080 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1081 rr->RecordCallback(m, rr, mStatus_NoError);
1082 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1083 }
1084 }
1085
1086 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
1087 {
1088 // Make sure that we don't activate the SRV record and associated service records, if it is in
1089 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1090 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1091 // the target becomes available, the records will be reregistered.
1092 if (rr->resrec.rrtype != kDNSType_SRV)
1093 {
1094 AuthRecord *srvRR = mDNSNULL;
1095 if (rr->resrec.rrtype == kDNSType_PTR)
1096 srvRR = rr->Additional1;
1097 else if (rr->resrec.rrtype == kDNSType_TXT)
1098 srvRR = rr->DependentOn;
1099 if (srvRR)
1100 {
1101 if (srvRR->resrec.rrtype != kDNSType_SRV)
1102 {
1103 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1104 }
1105 else
1106 {
1107 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1108 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1109 rr->state = srvRR->state;
1110 }
1111 }
1112 }
1113
1114 if (rr->state == regState_NoTarget)
1115 {
1116 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1117 return;
1118 }
1119 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1120 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1121 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1122 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1123 // 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.
1124 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1125 {
1126 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1127 rr->state = regState_DeregPending;
1128 }
1129 else
1130 {
1131 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1132 rr->state = regState_Pending;
1133 }
1134 rr->ProbeCount = 0;
1135 rr->ProbeRestartCount = 0;
1136 rr->AnnounceCount = 0;
1137 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1138 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1139 rr->expire = 0; // Forget about all the leases, start fresh
1140 rr->uselease = mDNStrue;
1141 rr->updateid = zeroID;
1142 rr->SRVChanged = mDNSfalse;
1143 rr->updateError = mStatus_NoError;
1144 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1145 // The records might already be registered with the server and hence could have NAT state.
1146 if (rr->NATinfo.clientContext)
1147 {
1148 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1149 rr->NATinfo.clientContext = mDNSNULL;
1150 }
1151 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1152 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1153 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1154 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1155 }
1156
1157 // Two records qualify to be local duplicates if:
1158 // (a) the RecordTypes are the same, or
1159 // (b) one is Unique and the other Verified
1160 // (c) either is in the process of deregistering
1161 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1162 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1163 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1164
1165 #define RecordIsLocalDuplicate(A,B) \
1166 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1167
1168 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1169 {
1170 const AuthGroup *a;
1171 AuthRecord *rp;
1172
1173 a = AuthGroupForRecord(r, &rr->resrec);
1174 if (!a) return mDNSNULL;
1175 rp = a->members;
1176 while (rp)
1177 {
1178 if (!RecordIsLocalDuplicate(rp, rr))
1179 rp = rp->next;
1180 else
1181 {
1182 if (rp->resrec.RecordType == kDNSRecordTypeDeregistering)
1183 {
1184 rp->AnnounceCount = 0;
1185 rp = rp->next;
1186 }
1187 else return rp;
1188 }
1189 }
1190 return (mDNSNULL);
1191 }
1192
1193 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1194 {
1195 const AuthGroup *a;
1196 const AuthRecord *rp;
1197
1198 a = AuthGroupForRecord(r, &rr->resrec);
1199 if (!a) return mDNSfalse;
1200 rp = a->members;
1201 while (rp)
1202 {
1203 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1204 const AuthRecord *s2 = rp->RRSet ? rp->RRSet : rp;
1205 if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec))
1206 return mDNStrue;
1207 else
1208 rp = rp->next;
1209 }
1210 return (mDNSfalse);
1211 }
1212
1213 // checks to see if "rr" is already present
1214 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1215 {
1216 const AuthGroup *a;
1217 AuthRecord *rp;
1218
1219 a = AuthGroupForRecord(r, &rr->resrec);
1220 if (!a) return mDNSNULL;
1221 rp = a->members;
1222 while (rp)
1223 {
1224 if (rp != rr)
1225 rp = rp->next;
1226 else
1227 {
1228 return rp;
1229 }
1230 }
1231 return (mDNSNULL);
1232 }
1233
1234
1235 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1236 {
1237 if (RRLocalOnly(rr))
1238 {
1239 // A sanity check, this should be prevented in calling code.
1240 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1241 return;
1242 }
1243
1244 if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1245 {
1246 // If about to get rid of the last advertised service
1247 if (m->AutoTargetServices == 1)
1248 DeadvertiseAllInterfaceRecords(m);
1249
1250 m->AutoTargetServices--;
1251 LogInfo("DecrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
1252 }
1253
1254 #if BONJOUR_ON_DEMAND
1255 if (!AuthRecord_uDNS(rr))
1256 {
1257 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1258 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
1259 m->NumAllInterfaceRecords--;
1260 LogInfo("DecrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1261 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1262 }
1263 #endif // BONJOUR_ON_DEMAND
1264 }
1265
1266 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1267 {
1268 mDNSBool enablingBonjour = 0;
1269
1270 if (RRLocalOnly(rr))
1271 {
1272 // A sanity check, this should be prevented in calling code.
1273 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1274 return;
1275 }
1276
1277 #if BONJOUR_ON_DEMAND
1278 if (!AuthRecord_uDNS(rr))
1279 {
1280 m->NumAllInterfaceRecords++;
1281 LogInfo("IncrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1282 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1283 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1284 {
1285 m->NextBonjourDisableTime = 0;
1286 if (m->BonjourEnabled == 0)
1287 {
1288 // Enable Bonjour immediately by scheduling network changed processing where
1289 // we will join the multicast group on each active interface.
1290 m->BonjourEnabled = 1;
1291 enablingBonjour = 1;
1292 m->NetworkChanged = m->timenow;
1293 }
1294 }
1295 }
1296 #endif // BONJOUR_ON_DEMAND
1297
1298 if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1299 {
1300 m->AutoTargetServices++;
1301 LogInfo("IncrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
1302
1303 // If this is the first advertised service and we did not just enable Bonjour above, then
1304 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1305 // be advertised during the network changed processing scheduled above, so no need
1306 // to do it here.
1307 if ((m->AutoTargetServices == 1) && (enablingBonjour == 0))
1308 AdvertiseAllInterfaceRecords(m);
1309 }
1310 }
1311
1312 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1313 {
1314 mDNSAddr laddr = zeroAddr;
1315 mDNSEthAddr eth = zeroEthAddr;
1316 mDNSIPPort lport = zeroIPPort;
1317 mDNSIPPort rport = zeroIPPort;
1318 mDNSu32 timeout = 0;
1319 mDNSu32 seq = 0;
1320 mDNSu32 ack = 0;
1321 mDNSu16 win = 0;
1322
1323 if (mDNS_KeepaliveRecord(&rr->resrec))
1324 {
1325 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, &eth, &seq, &ack, &lport, &rport, &win);
1326 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1327 {
1328 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1329 return;
1330 }
1331 }
1332 }
1333
1334 // Exported so uDNS.c can call this
1335 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1336 {
1337 domainname *target = GetRRDomainNameTarget(&rr->resrec);
1338 AuthRecord *r;
1339 AuthRecord **p = &m->ResourceRecords;
1340 AuthRecord **d = &m->DuplicateRecords;
1341
1342 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1343 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1344
1345 if (!rr->resrec.RecordType)
1346 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1347
1348 if (m->ShutdownTime)
1349 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1350
1351 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1352 {
1353 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1354 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1355 {
1356 rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1357 rr->ARType = AuthRecordLocalOnly;
1358 }
1359 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1360 {
1361 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1362 if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1363 }
1364 if (rr->resrec.InterfaceID != previousID)
1365 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1366 }
1367
1368 if (RRLocalOnly(rr))
1369 {
1370 if (CheckAuthSameRecord(&m->rrauth, rr))
1371 {
1372 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1373 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1374 return(mStatus_AlreadyRegistered);
1375 }
1376 }
1377 else
1378 {
1379 while (*p && *p != rr) p=&(*p)->next;
1380 if (*p)
1381 {
1382 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1383 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1384 return(mStatus_AlreadyRegistered);
1385 }
1386 }
1387
1388 while (*d && *d != rr) d=&(*d)->next;
1389 if (*d)
1390 {
1391 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1392 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1393 return(mStatus_AlreadyRegistered);
1394 }
1395
1396 if (rr->DependentOn)
1397 {
1398 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1399 rr->resrec.RecordType = kDNSRecordTypeVerified;
1400 else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique)
1401 {
1402 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1403 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1404 return(mStatus_Invalid);
1405 }
1406 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1407 {
1408 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1409 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1410 return(mStatus_Invalid);
1411 }
1412 }
1413
1414 rr->next = mDNSNULL;
1415
1416 // Field Group 1: The actual information pertaining to this resource record
1417 // Set up by client prior to call
1418
1419 // Field Group 2: Persistent metadata for Authoritative Records
1420 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1421 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1422 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1423 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1424 // rr->Callback = already set in mDNS_SetupResourceRecord
1425 // rr->Context = already set in mDNS_SetupResourceRecord
1426 // rr->RecordType = already set in mDNS_SetupResourceRecord
1427 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1428 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1429 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1430 if (rr->AutoTarget && target) target->c[0] = 0;
1431
1432 // Field Group 3: Transient state for Authoritative Records
1433 rr->Acknowledged = mDNSfalse;
1434 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1435 rr->ProbeRestartCount = 0;
1436 rr->AnnounceCount = InitialAnnounceCount;
1437 rr->RequireGoodbye = mDNSfalse;
1438 rr->AnsweredLocalQ = mDNSfalse;
1439 rr->IncludeInProbe = mDNSfalse;
1440 rr->ImmedUnicast = mDNSfalse;
1441 rr->SendNSECNow = mDNSNULL;
1442 rr->ImmedAnswer = mDNSNULL;
1443 rr->ImmedAdditional = mDNSNULL;
1444 rr->SendRNow = mDNSNULL;
1445 rr->v4Requester = zerov4Addr;
1446 rr->v6Requester = zerov6Addr;
1447 rr->NextResponse = mDNSNULL;
1448 rr->NR_AnswerTo = mDNSNULL;
1449 rr->NR_AdditionalTo = mDNSNULL;
1450 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1451 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1452 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1453 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1454 rr->NewRData = mDNSNULL;
1455 rr->newrdlength = 0;
1456 rr->UpdateCallback = mDNSNULL;
1457 rr->UpdateCredits = kMaxUpdateCredits;
1458 rr->NextUpdateCredit = 0;
1459 rr->UpdateBlocked = 0;
1460
1461 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1462 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1463
1464 // Field Group 4: Transient uDNS state for Authoritative Records
1465 rr->state = regState_Zero;
1466 rr->uselease = 0;
1467 rr->expire = 0;
1468 rr->Private = 0;
1469 rr->updateid = zeroID;
1470 rr->updateIntID = zeroOpaque64;
1471 rr->zone = rr->resrec.name;
1472 rr->nta = mDNSNULL;
1473 rr->tcp = mDNSNULL;
1474 rr->OrigRData = 0;
1475 rr->OrigRDLen = 0;
1476 rr->InFlightRData = 0;
1477 rr->InFlightRDLen = 0;
1478 rr->QueuedRData = 0;
1479 rr->QueuedRDLen = 0;
1480 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1481 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1482 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1483 // times with different values if the external NAT port changes during the lifetime of the service registration.
1484 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1485
1486 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1487 // rr->resrec.name->c = MUST be set by client
1488 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1489 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1490 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1491 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1492
1493 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1494 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1495 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1496 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1497
1498 if (rr->AutoTarget)
1499 {
1500 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1501 #ifndef UNICAST_DISABLED
1502 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1503 // 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.
1504 if (rr->state == regState_NoTarget)
1505 {
1506 // Initialize the target so that we don't crash while logging etc.
1507 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1508 if (tar) tar->c[0] = 0;
1509 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1510 }
1511 #endif
1512 }
1513 else
1514 {
1515 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
1516 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1517 }
1518
1519 if (!ValidateDomainName(rr->resrec.name))
1520 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1521
1522 // Don't do this until *after* we've set rr->resrec.rdlength
1523 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1524 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1525
1526 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
1527 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1528
1529 if (RRLocalOnly(rr))
1530 {
1531 // If this is supposed to be unique, make sure we don't have any name conflicts.
1532 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1533 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1534 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1535 // Hence, just bail out.
1536 // This comment is doesn’t make any sense. -- SC
1537 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1538 {
1539 if (CheckAuthRecordConflict(&m->rrauth, rr))
1540 {
1541 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1542 return mStatus_NameConflict;
1543 }
1544 }
1545 }
1546
1547 // For uDNS records, we don't support duplicate checks at this time.
1548 #ifndef UNICAST_DISABLED
1549 if (AuthRecord_uDNS(rr))
1550 {
1551 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1552 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1553 // 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.
1554 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1555 while (*p) p=&(*p)->next;
1556 *p = rr;
1557 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1558 rr->ProbeCount = 0;
1559 rr->ProbeRestartCount = 0;
1560 rr->AnnounceCount = 0;
1561 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1562 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
1563 }
1564 #endif
1565
1566 // Now that we've finished building our new record, make sure it's not identical to one we already have
1567 if (RRLocalOnly(rr))
1568 {
1569 rr->ProbeCount = 0;
1570 rr->ProbeRestartCount = 0;
1571 rr->AnnounceCount = 0;
1572 r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1573 }
1574 else
1575 {
1576 for (r = m->ResourceRecords; r; r=r->next)
1577 if (RecordIsLocalDuplicate(r, rr))
1578 {
1579 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1580 else break;
1581 }
1582 }
1583
1584 if (r)
1585 {
1586 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m,rr));
1587 *d = rr;
1588 // If the previous copy of this record is already verified unique,
1589 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1590 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1591 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1592 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1593 rr->ProbeCount = 0;
1594 }
1595 else
1596 {
1597 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1598 if (RRLocalOnly(rr))
1599 {
1600 AuthGroup *ag;
1601 ag = InsertAuthRecord(m, &m->rrauth, rr);
1602 if (ag && !ag->NewLocalOnlyRecords)
1603 {
1604 m->NewLocalOnlyRecords = mDNStrue;
1605 ag->NewLocalOnlyRecords = rr;
1606 }
1607 // No probing for LocalOnly records; acknowledge them right away
1608 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1609 AcknowledgeRecord(m, rr);
1610 return(mStatus_NoError);
1611 }
1612 else
1613 {
1614 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1615 *p = rr;
1616 }
1617 }
1618
1619 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
1620 {
1621 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1622 IncrementAutoTargetServices(m, rr);
1623
1624 // For records that are not going to probe, acknowledge them right away
1625 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1626 AcknowledgeRecord(m, rr);
1627
1628 // Adding a record may affect whether or not we should sleep
1629 mDNS_UpdateAllowSleep(m);
1630 }
1631
1632 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1633 // This is used by the in-NIC proxy to send the keepalive packets.
1634 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
1635 {
1636 mDNSAddr raddr;
1637 // Set the record type to known unique to prevent probing keep alive records.
1638 // Also make sure we do not announce the keepalive records.
1639 rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1640 rr->AnnounceCount = 0;
1641 getKeepaliveRaddr(m, rr, &raddr);
1642 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1643 // asynchronous task to update the resource record
1644 mDNSPlatformGetRemoteMacAddr(&raddr);
1645 }
1646
1647 return(mStatus_NoError);
1648 }
1649
1650 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1651 {
1652 m->ProbeFailTime = m->timenow;
1653 m->NumFailedProbes++;
1654 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1655 // If a bunch of hosts have all been configured with the same name, then they'll all
1656 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1657 // up to name-10. After that they'll start adding random increments in the range 1-100,
1658 // so they're more likely to branch out in the available namespace and settle on a set of
1659 // unique names quickly. If after five more tries the host is still conflicting, then we
1660 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1661 if (m->NumFailedProbes >= 15)
1662 {
1663 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1664 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1665 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1666 }
1667 }
1668
1669 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1670 {
1671 RData *OldRData = rr->resrec.rdata;
1672 mDNSu16 OldRDLen = rr->resrec.rdlength;
1673 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
1674 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
1675 if (rr->UpdateCallback)
1676 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
1677 }
1678
1679 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1680 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1681 // Exported so uDNS.c can call this
1682 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1683 {
1684 AuthRecord *r2;
1685 mDNSu8 RecordType = rr->resrec.RecordType;
1686 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
1687 mDNSBool dupList = mDNSfalse;
1688
1689 if (RRLocalOnly(rr))
1690 {
1691 AuthGroup *a;
1692 AuthRecord **rp;
1693
1694 a = AuthGroupForRecord(&m->rrauth, &rr->resrec);
1695 if (!a) return mDNSfalse;
1696 rp = &a->members;
1697 while (*rp && *rp != rr) rp=&(*rp)->next;
1698 p = rp;
1699 }
1700 else
1701 {
1702 while (*p && *p != rr) p=&(*p)->next;
1703 }
1704
1705 if (*p)
1706 {
1707 // We found our record on the main list. See if there are any duplicates that need special handling.
1708 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
1709 {
1710 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1711 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1712 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1713 }
1714 else
1715 {
1716 // Before we delete the record (and potentially send a goodbye packet)
1717 // first see if we have a record on the duplicate list ready to take over from it.
1718 AuthRecord **d = &m->DuplicateRecords;
1719 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1720 if (*d)
1721 {
1722 AuthRecord *dup = *d;
1723 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1724 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1725 *d = dup->next; // Cut replacement record from DuplicateRecords list
1726 if (RRLocalOnly(rr))
1727 {
1728 dup->next = mDNSNULL;
1729 if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1730 }
1731 else
1732 {
1733 dup->next = rr->next; // And then...
1734 rr->next = dup; // ... splice it in right after the record we're about to delete
1735 }
1736 dup->resrec.RecordType = rr->resrec.RecordType;
1737 dup->ProbeCount = rr->ProbeCount;
1738 dup->ProbeRestartCount = rr->ProbeRestartCount;
1739 dup->AnnounceCount = rr->AnnounceCount;
1740 dup->RequireGoodbye = rr->RequireGoodbye;
1741 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
1742 dup->ImmedAnswer = rr->ImmedAnswer;
1743 dup->ImmedUnicast = rr->ImmedUnicast;
1744 dup->ImmedAdditional = rr->ImmedAdditional;
1745 dup->v4Requester = rr->v4Requester;
1746 dup->v6Requester = rr->v6Requester;
1747 dup->ThisAPInterval = rr->ThisAPInterval;
1748 dup->LastAPTime = rr->LastAPTime;
1749 dup->LastMCTime = rr->LastMCTime;
1750 dup->LastMCInterface = rr->LastMCInterface;
1751 dup->Private = rr->Private;
1752 dup->state = rr->state;
1753 rr->RequireGoodbye = mDNSfalse;
1754 rr->AnsweredLocalQ = mDNSfalse;
1755 }
1756 }
1757 }
1758 else
1759 {
1760 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1761 p = &m->DuplicateRecords;
1762 while (*p && *p != rr) p=&(*p)->next;
1763 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1764 if (*p)
1765 {
1766 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1767 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1768 // also that have been marked above in this function. In that case, we come here and if we don't
1769 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1770 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1771 // details.
1772 rr->WakeUp.HMAC = zeroEthAddr;
1773 rr->RequireGoodbye = mDNSfalse;
1774 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1775 dupList = mDNStrue;
1776 }
1777 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1778 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1779 }
1780
1781 if (!*p)
1782 {
1783 // No need to log an error message if we already know this is a potentially repeated deregistration
1784 if (drt != mDNS_Dereg_repeat)
1785 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1786 return(mStatus_BadReferenceErr);
1787 }
1788
1789 // If this is a shared record and we've announced it at least once,
1790 // we need to retract that announcement before we delete the record
1791
1792 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1793 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1794 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1795 // mechanism to cope with the client callback modifying the question list while that's happening.
1796 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1797 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1798 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1799 // records, thereby invoking yet more callbacks, without limit.
1800 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1801 // actual goodbye packets.
1802
1803 #ifndef UNICAST_DISABLED
1804 if (AuthRecord_uDNS(rr))
1805 {
1806 if (rr->RequireGoodbye)
1807 {
1808 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1809 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1810 m->LocalRemoveEvents = mDNStrue;
1811 uDNS_DeregisterRecord(m, rr);
1812 // At this point unconditionally we bail out
1813 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1814 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1815 // process and will complete asynchronously. Either way we don't need to do anything more here.
1816 return(mStatus_NoError);
1817 }
1818 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1819 // from the server. In that case, if the records have been part of a group update, clear the
1820 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1821 rr->updateid = zeroID;
1822
1823 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1824 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1825 // This happens today when we turn on/off interface where we get multiple network transitions
1826 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1827 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1828 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1829 // NAT state here takes care of the case where we did not send goodbyes at all.
1830 if (rr->NATinfo.clientContext)
1831 {
1832 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1833 rr->NATinfo.clientContext = mDNSNULL;
1834 }
1835 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1836 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1837 }
1838 #endif // UNICAST_DISABLED
1839
1840 if (RecordType == kDNSRecordTypeUnregistered)
1841 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1842 else if (RecordType == kDNSRecordTypeDeregistering)
1843 {
1844 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1845 return(mStatus_BadReferenceErr);
1846 }
1847
1848 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1849 // We may want to consider changing this code so that we generate local-only question "rmv"
1850 // events (and maybe goodbye packets too) for unique records as well as for shared records
1851 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1852 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1853 // clause will execute here and the record will be cut from the list.
1854 if (rr->WakeUp.HMAC.l[0] ||
1855 (RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1856 {
1857 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1858 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1859 rr->resrec.rroriginalttl = 0;
1860 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1861 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
1862 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1863 m->LocalRemoveEvents = mDNStrue;
1864 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1865 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1866 }
1867 else
1868 {
1869 if (!dupList && RRLocalOnly(rr))
1870 {
1871 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1872 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1873 }
1874 else
1875 {
1876 *p = rr->next; // Cut this record from the list
1877 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1878 DecrementAutoTargetServices(m, rr);
1879 }
1880 // If someone is about to look at this, bump the pointer forward
1881 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
1882 rr->next = mDNSNULL;
1883
1884 // Should we generate local remove events here?
1885 // i.e. something like:
1886 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1887
1888 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1889 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1890
1891 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1892 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1893 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1894
1895 // If we have an update queued up which never executed, give the client a chance to free that memory
1896 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
1897
1898
1899 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1900 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1901 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1902 // so any attempt to touch rr after this is likely to lead to a crash.
1903 if (drt != mDNS_Dereg_conflict)
1904 {
1905 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1906 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m, rr));
1907 if (rr->RecordCallback)
1908 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
1909 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1910 }
1911 else
1912 {
1913 RecordProbeFailure(m, rr);
1914 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1915 if (rr->RecordCallback)
1916 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
1917 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1918 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1919 // Note that with all the client callbacks going on, by the time we get here all the
1920 // records we marked may have been explicitly deregistered by the client anyway.
1921 r2 = m->DuplicateRecords;
1922 while (r2)
1923 {
1924 if (r2->ProbeCount != 0xFF)
1925 {
1926 r2 = r2->next;
1927 }
1928 else
1929 {
1930 #if APPLE_OSX_mDNSResponder
1931 // See if this record was also registered with any D2D plugins.
1932 D2D_stop_advertising_record(r2);
1933 #endif
1934 mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
1935 // As this is a duplicate record, it will be unlinked from the list
1936 // immediately
1937 r2 = m->DuplicateRecords;
1938 }
1939 }
1940 }
1941 }
1942 mDNS_UpdateAllowSleep(m);
1943 return(mStatus_NoError);
1944 }
1945
1946 // ***************************************************************************
1947 #if COMPILER_LIKES_PRAGMA_MARK
1948 #pragma mark -
1949 #pragma mark - Packet Sending Functions
1950 #endif
1951
1952 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1953 {
1954 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1955 {
1956 **nrpp = rr;
1957 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1958 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1959 // The referenced record will definitely be acceptable (by recursive application of this rule)
1960 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1961 rr->NR_AdditionalTo = add;
1962 *nrpp = &rr->NextResponse;
1963 }
1964 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1965 }
1966
1967 mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID)
1968 {
1969 AuthRecord *rr2;
1970 if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask)
1971 {
1972 for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next)
1973 {
1974 if ((rr2->resrec.namehash == additional->resrec.namehash) &&
1975 (rr2->resrec.rrtype == additional->resrec.rrtype) &&
1976 (rr2 != additional) &&
1977 (rr2->resrec.RecordType & kDNSRecordTypeUniqueMask) &&
1978 (rr2->resrec.rrclass == additional->resrec.rrclass) &&
1979 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&
1980 SameDomainName(rr2->resrec.name, additional->resrec.name))
1981 {
1982 AddRecordToResponseList(nrpp, rr2, rr);
1983 }
1984 }
1985 }
1986 }
1987
1988 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1989 {
1990 AuthRecord *rr, *rr2;
1991 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
1992 {
1993 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1994 // later in the "for" loop, and we will follow further "additional" links then.)
1995 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1996 {
1997 AddRecordToResponseList(nrpp, rr->Additional1, rr);
1998 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID);
1999 }
2000
2001 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
2002 {
2003 AddRecordToResponseList(nrpp, rr->Additional2, rr);
2004 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID);
2005 }
2006
2007 // For SRV records, automatically add the Address record(s) for the target host
2008 if (rr->resrec.rrtype == kDNSType_SRV)
2009 {
2010 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2011 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2012 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2013 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
2014 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
2015 AddRecordToResponseList(nrpp, rr2, rr);
2016 }
2017 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
2018 {
2019 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2020 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2021 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2022 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
2023 SameDomainName(rr->resrec.name, rr2->resrec.name))
2024 AddRecordToResponseList(nrpp, rr2, rr);
2025 }
2026 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
2027 {
2028 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
2029 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2030 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
2031 }
2032 }
2033 }
2034
2035 mDNSlocal int AnonInfoSpace(AnonymousInfo *info)
2036 {
2037 ResourceRecord *rr = info->nsec3RR;
2038
2039 // 2 bytes for compressed name + type (2) class (2) TTL (4) rdlength (2) rdata (n)
2040 return (2 + 10 + rr->rdlength);
2041 }
2042
2043 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
2044 {
2045 AuthRecord *rr;
2046 AuthRecord *ResponseRecords = mDNSNULL;
2047 AuthRecord **nrp = &ResponseRecords;
2048 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
2049 int AnoninfoSpace = 0;
2050
2051 // Make a list of all our records that need to be unicast to this destination
2052 for (rr = m->ResourceRecords; rr; rr=rr->next)
2053 {
2054 // If we find we can no longer unicast this answer, clear ImmedUnicast
2055 if (rr->ImmedAnswer == mDNSInterfaceMark ||
2056 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
2057 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
2058 rr->ImmedUnicast = mDNSfalse;
2059
2060 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
2061 {
2062 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
2063 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
2064 {
2065 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
2066 rr->ImmedUnicast = mDNSfalse;
2067 rr->v4Requester = zerov4Addr;
2068 rr->v6Requester = zerov6Addr;
2069
2070 // Only sent records registered for P2P over P2P interfaces
2071 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))
2072 {
2073 continue;
2074 }
2075
2076 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
2077 {
2078 rr->NR_AnswerTo = NR_AnswerMulticast;
2079 *nrp = rr;
2080 nrp = &rr->NextResponse;
2081 }
2082 }
2083 }
2084 }
2085
2086 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
2087
2088 while (ResponseRecords)
2089 {
2090 mDNSu8 *responseptr = m->omsg.data;
2091 mDNSu8 *newptr;
2092 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2093
2094 // Put answers in the packet
2095 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
2096 {
2097 rr = ResponseRecords;
2098 if (rr->resrec.AnonInfo)
2099 {
2100 AnoninfoSpace += AnonInfoSpace(rr->resrec.AnonInfo);
2101 rr->resrec.AnonInfo->SendNow = mDNSInterfaceMark;
2102 }
2103 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2104 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2105
2106 // Retract the limit by AnoninfoSpace which we need to put the AnoInfo option.
2107 newptr = PutResourceRecordTTLWithLimit(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec, rr->resrec.rroriginalttl,
2108 m->omsg.data + (AllowedRRSpace(&m->omsg) - AnoninfoSpace));
2109
2110 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2111 if (!newptr && m->omsg.h.numAnswers)
2112 {
2113 break; // If packet full, send it now
2114 }
2115 if (newptr) responseptr = newptr;
2116 ResponseRecords = rr->NextResponse;
2117 rr->NextResponse = mDNSNULL;
2118 rr->NR_AnswerTo = mDNSNULL;
2119 rr->NR_AdditionalTo = mDNSNULL;
2120 rr->RequireGoodbye = mDNStrue;
2121 }
2122
2123 // We have reserved the space for AnonInfo option. PutResourceRecord uses the
2124 // standard limit (AllowedRRSpace) and we should have space now.
2125 for (rr = m->ResourceRecords; rr; rr=rr->next)
2126 {
2127 if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == mDNSInterfaceMark)
2128 {
2129 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
2130
2131 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAuthorities, nsec3RR);
2132 if (newptr)
2133 {
2134 responseptr = newptr;
2135 debugf("SendDelayedUnicastResponse: Added NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
2136 }
2137 else
2138 {
2139 // We allocated space and we should not fail. Don't break, we need to clear the SendNow flag.
2140 LogMsg("SendDelayedUnicastResponse: ERROR!! Cannot Add NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
2141 }
2142 rr->resrec.AnonInfo->SendNow = mDNSNULL;
2143 }
2144 }
2145
2146 // Add additionals, if there's space
2147 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
2148 {
2149 rr = ResponseRecords;
2150 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2151 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2152 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
2153 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2154
2155 if (newptr) responseptr = newptr;
2156 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
2157 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
2158 ResponseRecords = rr->NextResponse;
2159 rr->NextResponse = mDNSNULL;
2160 rr->NR_AnswerTo = mDNSNULL;
2161 rr->NR_AdditionalTo = mDNSNULL;
2162 }
2163
2164 if (m->omsg.h.numAnswers)
2165 mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2166 }
2167 }
2168
2169 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2170 // and the client's mStatus_MemFree callback will have been invoked
2171 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
2172 {
2173 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
2174 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2175 // it should go ahead and immediately dispose of this registration
2176 rr->resrec.RecordType = kDNSRecordTypeShared;
2177 rr->RequireGoodbye = mDNSfalse;
2178 rr->WakeUp.HMAC = zeroEthAddr;
2179 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
2180 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
2181 }
2182
2183 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2184 // any deregistering records that remain in the m->ResourceRecords list.
2185 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2186 // which may change the record list and/or question list.
2187 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2188 mDNSlocal void DiscardDeregistrations(mDNS *const m)
2189 {
2190 if (m->CurrentRecord)
2191 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2192 m->CurrentRecord = m->ResourceRecords;
2193
2194 while (m->CurrentRecord)
2195 {
2196 AuthRecord *rr = m->CurrentRecord;
2197 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2198 CompleteDeregistration(m, rr); // Don't touch rr after this
2199 else
2200 m->CurrentRecord = rr->next;
2201 }
2202 }
2203
2204 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2205 {
2206 int i, val = 0;
2207 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2208 for (i=1; i<=src[0]; i++)
2209 {
2210 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2211 val = val * 10 + src[i] - '0';
2212 }
2213 if (val > 255) return(mStatus_Invalid);
2214 *dst = (mDNSu8)val;
2215 return(mStatus_NoError);
2216 }
2217
2218 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2219 {
2220 int skip = CountLabels(name) - 6;
2221 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2222 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2223 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2224 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2225 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2226 a->type = mDNSAddrType_IPv4;
2227 return(mStatus_NoError);
2228 }
2229
2230 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2231 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2232 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2233
2234 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2235 {
2236 int i, h, l;
2237 const domainname *n;
2238
2239 int skip = CountLabels(name) - 34;
2240 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2241
2242 n = SkipLeadingLabels(name, skip);
2243 for (i=0; i<16; i++)
2244 {
2245 if (n->c[0] != 1) return mStatus_Invalid;
2246 l = HexVal(n->c[1]);
2247 n = (const domainname *)(n->c + 2);
2248
2249 if (n->c[0] != 1) return mStatus_Invalid;
2250 h = HexVal(n->c[1]);
2251 n = (const domainname *)(n->c + 2);
2252
2253 if (l<0 || h<0) return mStatus_Invalid;
2254 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2255 }
2256
2257 a->type = mDNSAddrType_IPv6;
2258 return(mStatus_NoError);
2259 }
2260
2261 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2262 {
2263 int skip = CountLabels(name) - 2;
2264 if (skip >= 0)
2265 {
2266 const domainname *suffix = SkipLeadingLabels(name, skip);
2267 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2268 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
2269 }
2270 return(mDNSAddrType_None);
2271 }
2272
2273 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2274 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2275 {
2276 int i;
2277 mDNSu8 *ptr = m->omsg.data;
2278 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2279 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2280
2281 // 0x00 Destination address
2282 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2283
2284 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2285 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2286
2287 // 0x0C ARP Ethertype (0x0806)
2288 *ptr++ = 0x08; *ptr++ = 0x06;
2289
2290 // 0x0E ARP header
2291 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
2292 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
2293 *ptr++ = 6; // Hardware address length
2294 *ptr++ = 4; // Protocol address length
2295 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
2296
2297 // 0x16 Sender hardware address (our MAC address)
2298 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2299
2300 // 0x1C Sender protocol address
2301 for (i=0; i<4; i++) *ptr++ = spa->b[i];
2302
2303 // 0x20 Target hardware address
2304 for (i=0; i<6; i++) *ptr++ = tha->b[i];
2305
2306 // 0x26 Target protocol address
2307 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2308
2309 // 0x2A Total ARP Packet length 42 bytes
2310 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2311 }
2312
2313 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2314 {
2315 const mDNSu16 *ptr = data;
2316 while (length > 0) { length -= 2; sum += *ptr++; }
2317 sum = (sum & 0xFFFF) + (sum >> 16);
2318 sum = (sum & 0xFFFF) + (sum >> 16);
2319 return(sum != 0xFFFF ? sum : 0);
2320 }
2321
2322 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2323 {
2324 IPv6PseudoHeader ph;
2325 ph.src = *src;
2326 ph.dst = *dst;
2327 ph.len.b[0] = length >> 24;
2328 ph.len.b[1] = length >> 16;
2329 ph.len.b[2] = length >> 8;
2330 ph.len.b[3] = length;
2331 ph.pro.b[0] = 0;
2332 ph.pro.b[1] = 0;
2333 ph.pro.b[2] = 0;
2334 ph.pro.b[3] = protocol;
2335 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2336 }
2337
2338 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2339 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2340 {
2341 int i;
2342 mDNSOpaque16 checksum;
2343 mDNSu8 *ptr = m->omsg.data;
2344 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2345 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2346 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2347 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] } };
2348 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2349 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2350 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2351
2352 // 0x00 Destination address
2353 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2354 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2355 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2356 // link with a pointless link-layer multicast.
2357 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2358 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2359 // *ptr++ = 0x33;
2360 // *ptr++ = 0x33;
2361 // *ptr++ = 0xFF;
2362 // *ptr++ = tpa->b[0xD];
2363 // *ptr++ = tpa->b[0xE];
2364 // *ptr++ = tpa->b[0xF];
2365
2366 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2367 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2368
2369 // 0x0C IPv6 Ethertype (0x86DD)
2370 *ptr++ = 0x86; *ptr++ = 0xDD;
2371
2372 // 0x0E IPv6 header
2373 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
2374 *ptr++ = 0x00; *ptr++ = 0x20; // Length
2375 *ptr++ = 0x3A; // Protocol == ICMPv6
2376 *ptr++ = 0xFF; // Hop Limit
2377
2378 // 0x16 Sender IPv6 address
2379 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2380
2381 // 0x26 Destination IPv6 address
2382 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2383
2384 // 0x36 NDP header
2385 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2386 *ptr++ = 0x00; // Code
2387 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
2388 *ptr++ = flags;
2389 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2390
2391 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
2392 {
2393 // 0x3E NDP target.
2394 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2395 // 0x4E Source Link-layer Address
2396 // <http://www.ietf.org/rfc/rfc2461.txt>
2397 // MUST NOT be included when the source IP address is the unspecified address.
2398 // Otherwise, on link layers that have addresses this option MUST be included
2399 // in multicast solicitations and SHOULD be included in unicast solicitations.
2400 if (!mDNSIPv6AddressIsZero(*spa))
2401 {
2402 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2403 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2404 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2405 }
2406 }
2407 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2408 {
2409 // 0x3E NDP target.
2410 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2411 // 0x4E Target Link-layer Address
2412 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2413 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2414 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2415 }
2416
2417 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2418 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
2419 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2420 m->omsg.data[0x38] = checksum.b[0];
2421 m->omsg.data[0x39] = checksum.b[1];
2422
2423 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2424 }
2425
2426 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2427 {
2428 mDNSu32 DNS_VERS = _DNS_SD_H;
2429 Trace->u.tracer.platf = m->mDNS_plat;
2430 Trace->u.tracer.mDNSv = DNS_VERS;
2431
2432 Trace->opt = kDNSOpt_Trace;
2433 Trace->optlen = DNSOpt_TraceData_Space - 4;
2434 }
2435
2436 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2437 {
2438 owner->u.owner.vers = 0;
2439 owner->u.owner.seq = m->SleepSeqNum;
2440 owner->u.owner.HMAC = m->PrimaryMAC;
2441 owner->u.owner.IMAC = intf->MAC;
2442 owner->u.owner.password = zeroEthAddr;
2443
2444 // Don't try to compute the optlen until *after* we've set up the data fields
2445 // 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
2446 owner->opt = kDNSOpt_Owner;
2447 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2448 }
2449
2450 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2451 {
2452 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2453 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2454 }
2455
2456 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2457 {
2458 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2459 // and hence there is no need to check for Transfering state. But if we have sleep
2460 // proxies and partially sending goodbyes for some records, we will be in Transfering
2461 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2462 // we are not awake handles both cases.
2463 if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2464 {
2465 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2466 return mDNStrue;
2467 }
2468
2469 if (m->SleepState != SleepState_Sleeping)
2470 return mDNSfalse;
2471
2472 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2473 // whether you can send goodbyes or not.
2474 if (!intf->SendGoodbyes)
2475 {
2476 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2477 return mDNSfalse;
2478 }
2479 else
2480 {
2481 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2482 return mDNStrue;
2483 }
2484 }
2485
2486 mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *ar, mDNSInterfaceID InterfaceID)
2487 {
2488 mDNSBool result;
2489
2490 if (ar->resrec.InterfaceID == mDNSInterface_Any)
2491 {
2492 result = mDNSPlatformValidRecordForInterface(ar, InterfaceID);
2493 }
2494 else
2495 {
2496 result = (ar->resrec.InterfaceID == InterfaceID);
2497 }
2498
2499 return(result);
2500 }
2501
2502 // Note about acceleration of announcements to facilitate automatic coalescing of
2503 // multiple independent threads of announcements into a single synchronized thread:
2504 // The announcements in the packet may be at different stages of maturity;
2505 // One-second interval, two-second interval, four-second interval, and so on.
2506 // After we've put in all the announcements that are due, we then consider
2507 // whether there are other nearly-due announcements that are worth accelerating.
2508 // To be eligible for acceleration, a record MUST NOT be older (further along
2509 // its timeline) than the most mature record we've already put in the packet.
2510 // In other words, younger records can have their timelines accelerated to catch up
2511 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2512 // Older records cannot have their timelines accelerated; this would just widen
2513 // the gap between them and their younger bretheren and get them even more out of sync.
2514
2515 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2516 // the record list and/or question list.
2517 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2518 mDNSlocal void SendResponses(mDNS *const m)
2519 {
2520 int pktcount = 0;
2521 AuthRecord *rr, *r2;
2522 mDNSs32 maxExistingAnnounceInterval = 0;
2523 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2524
2525 m->NextScheduledResponse = m->timenow + FutureTime;
2526
2527 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2528
2529 for (rr = m->ResourceRecords; rr; rr=rr->next)
2530 if (rr->ImmedUnicast)
2531 {
2532 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2533 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2534 v4.ip.v4 = rr->v4Requester;
2535 v6.ip.v6 = rr->v6Requester;
2536 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2537 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2538 if (rr->ImmedUnicast)
2539 {
2540 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2541 rr->ImmedUnicast = mDNSfalse;
2542 }
2543 }
2544
2545 // ***
2546 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2547 // ***
2548
2549 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2550 for (rr = m->ResourceRecords; rr; rr=rr->next)
2551 {
2552 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2553 if (TimeToAnnounceThisRecord(rr, m->timenow))
2554 {
2555 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2556 {
2557 if (!rr->WakeUp.HMAC.l[0])
2558 {
2559 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
2560 }
2561 else
2562 {
2563 mDNSBool unicastOnly;
2564 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2565 unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse;
2566 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly);
2567 for (r2 = rr; r2; r2=r2->next)
2568 if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
2569 mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2570 {
2571 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2572 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2573 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2574 {
2575 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2576 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2577 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2578 }
2579 r2->LastAPTime = m->timenow;
2580 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2581 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2582 }
2583 }
2584 }
2585 else if (ResourceRecordIsValidAnswer(rr))
2586 {
2587 if (rr->AddressProxy.type)
2588 {
2589 if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2590 {
2591 rr->AnnounceCount--;
2592 rr->ThisAPInterval *= 2;
2593 rr->LastAPTime = m->timenow;
2594 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2595 {
2596 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2597 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2598 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2599 }
2600 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2601 {
2602 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2603 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2604 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2605 }
2606 }
2607 }
2608 else
2609 {
2610 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2611 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2612 maxExistingAnnounceInterval = rr->ThisAPInterval;
2613 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2614 }
2615 }
2616 }
2617 }
2618
2619 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2620 // Eligible records that are more than half-way to their announcement time are accelerated
2621 for (rr = m->ResourceRecords; rr; rr=rr->next)
2622 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2623 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2624 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2625 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
2626 ResourceRecordIsValidAnswer(rr)))
2627 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2628
2629 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2630 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2631 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2632 // then all that means is that it won't get sent -- which would not be the end of the world.
2633 for (rr = m->ResourceRecords; rr; rr=rr->next)
2634 {
2635 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2636 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
2637 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
2638 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
2639 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
2640 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
2641 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2642 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2643 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
2644 // We also make sure we send the DeviceInfo TXT record too, if necessary
2645 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2646 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2647 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2648 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2649 {
2650 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2651 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2652 }
2653 }
2654
2655 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2656 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2657 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2658 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2659 // -- 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
2660 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2661 for (rr = m->ResourceRecords; rr; rr=rr->next)
2662 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2663 {
2664 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
2665 {
2666 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2667 {
2668 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2669 (r2->ImmedAnswer != mDNSInterfaceMark) && (r2->ImmedAnswer != rr->ImmedAnswer) &&
2670 SameResourceRecordSignature(r2, rr) &&
2671 ((rr->ImmedAnswer == mDNSInterfaceMark) || IsInterfaceValidForAuthRecord(r2, rr->ImmedAnswer)))
2672 {
2673 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2674 }
2675 }
2676 }
2677 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
2678 {
2679 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2680 {
2681 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2682 (r2->ImmedAdditional != rr->ImmedAdditional) &&
2683 SameResourceRecordSignature(r2, rr) &&
2684 IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional))
2685 {
2686 r2->ImmedAdditional = rr->ImmedAdditional;
2687 }
2688 }
2689 }
2690 }
2691
2692 // Now set SendRNow state appropriately
2693 for (rr = m->ResourceRecords; rr; rr=rr->next)
2694 {
2695 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
2696 {
2697 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2698 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
2699 rr->LastMCTime = m->timenow;
2700 rr->LastMCInterface = rr->ImmedAnswer;
2701 rr->ProbeRestartCount = 0; // Reset the probe restart count
2702 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2703 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2704 {
2705 rr->AnnounceCount--;
2706 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2707 rr->ThisAPInterval *= 2;
2708 rr->LastAPTime = m->timenow;
2709 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2710 }
2711 }
2712 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
2713 {
2714 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
2715 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
2716 rr->LastMCTime = m->timenow;
2717 rr->LastMCInterface = rr->ImmedAnswer;
2718 }
2719 SetNextAnnounceProbeTime(m, rr);
2720 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2721 }
2722
2723 // ***
2724 // *** 2. Loop through interface list, sending records as appropriate
2725 // ***
2726
2727 while (intf)
2728 {
2729 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2730 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2731 int numDereg = 0;
2732 int numAnnounce = 0;
2733 int numAnswer = 0;
2734 int AnoninfoSpace = 0;
2735 mDNSu8 *responseptr = m->omsg.data;
2736 mDNSu8 *newptr;
2737 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2738
2739 // First Pass. Look for:
2740 // 1. Deregistering records that need to send their goodbye packet
2741 // 2. Updated records that need to retract their old data
2742 // 3. Answers and announcements we need to send
2743 for (rr = m->ResourceRecords; rr; rr=rr->next)
2744 {
2745
2746 // Skip this interface if the record InterfaceID is *Any and the record is not
2747 // appropriate for the interface type.
2748 if ((rr->SendRNow == intf->InterfaceID) &&
2749 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)))
2750 {
2751 rr->SendRNow = GetNextActiveInterfaceID(intf);
2752 }
2753 else if (rr->SendRNow == intf->InterfaceID)
2754 {
2755 RData *OldRData = rr->resrec.rdata;
2756 mDNSu16 oldrdlength = rr->resrec.rdlength;
2757 mDNSu8 active = (mDNSu8)
2758 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2759 newptr = mDNSNULL;
2760 if (rr->NewRData && active)
2761 {
2762 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2763 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2764 {
2765 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2766 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2767 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
2768 }
2769 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2770 }
2771
2772 if (rr->resrec.AnonInfo)
2773 {
2774 int tmp = AnonInfoSpace(rr->resrec.AnonInfo);
2775
2776 AnoninfoSpace += tmp;
2777 // Adjust OwnerRecordSpace/TraceRecordSpace which is used by PutRR_OS_TTL below so that
2778 // we have space to put in the NSEC3 record in the authority section.
2779 OwnerRecordSpace += tmp;
2780 TraceRecordSpace += tmp;
2781 }
2782
2783 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2784 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2785 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2786 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2787 if (newptr)
2788 {
2789 responseptr = newptr;
2790 rr->RequireGoodbye = active;
2791 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2792 else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2793 }
2794
2795 if (rr->NewRData && active)
2796 SetNewRData(&rr->resrec, OldRData, oldrdlength);
2797
2798 // The first time through (pktcount==0), if this record is verified unique
2799 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2800 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2801 rr->SendNSECNow = mDNSInterfaceMark;
2802
2803 if (newptr) // If succeeded in sending, advance to next interface
2804 {
2805 if (rr->resrec.AnonInfo)
2806 {
2807 debugf("SendResponses: Marking %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2808 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2809 rr->resrec.AnonInfo->SendNow = intf->InterfaceID;
2810 }
2811
2812 // If sending on all interfaces, go to next interface; else we're finished now
2813 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2814 rr->SendRNow = GetNextActiveInterfaceID(intf);
2815 else
2816 rr->SendRNow = mDNSNULL;
2817 }
2818 }
2819 }
2820
2821 // Get the reserved space back
2822 OwnerRecordSpace -= AnoninfoSpace;
2823 TraceRecordSpace -= AnoninfoSpace;
2824 newptr = responseptr;
2825 for (rr = m->ResourceRecords; rr; rr=rr->next)
2826 {
2827 if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == intf->InterfaceID)
2828 {
2829 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
2830
2831 newptr = PutRR_OS_TTL(newptr, &m->omsg.h.numAuthorities, nsec3RR, nsec3RR->rroriginalttl);
2832 if (newptr)
2833 {
2834 responseptr = newptr;
2835 debugf("SendResponses: Added NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2836 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2837 }
2838 else
2839 {
2840 LogMsg("SendResponses: Cannot add NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2841 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2842 }
2843 rr->resrec.AnonInfo->SendNow = mDNSNULL;
2844 }
2845 }
2846 // Second Pass. Add additional records, if there's space.
2847 newptr = responseptr;
2848 for (rr = m->ResourceRecords; rr; rr=rr->next)
2849 if (rr->ImmedAdditional == intf->InterfaceID)
2850 if (ResourceRecordIsValidAnswer(rr))
2851 {
2852 // If we have at least one answer already in the packet, then plan to add additionals too
2853 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2854
2855 // If we're not planning to send any additionals, but this record is a unique one, then
2856 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2857 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2858 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2859 {
2860 const AuthRecord *a;
2861 for (a = m->ResourceRecords; a; a=a->next)
2862 if (a->LastMCTime == m->timenow &&
2863 a->LastMCInterface == intf->InterfaceID &&
2864 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2865 }
2866 if (!SendAdditional) // If we don't want to send this after all,
2867 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
2868 else if (newptr) // Else, try to add it if we can
2869 {
2870 // The first time through (pktcount==0), if this record is verified unique
2871 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2872 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2873 rr->SendNSECNow = mDNSInterfaceMark;
2874
2875 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2876 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2877 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2878 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2879 if (newptr)
2880 {
2881 responseptr = newptr;
2882 rr->ImmedAdditional = mDNSNULL;
2883 rr->RequireGoodbye = mDNStrue;
2884 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2885 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2886 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2887 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2888 rr->LastMCTime = m->timenow;
2889 rr->LastMCInterface = intf->InterfaceID;
2890 }
2891 }
2892 }
2893
2894 // Third Pass. Add NSEC records, if there's space.
2895 // When we're generating an NSEC record in response to a specify query for that type
2896 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2897 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2898 for (rr = m->ResourceRecords; rr; rr=rr->next)
2899 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2900 {
2901 AuthRecord nsec;
2902 mDNSu8 *ptr;
2903 int len;
2904 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2905 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2906 AssignDomainName(&nsec.namestorage, rr->resrec.name);
2907 ptr = nsec.rdatastorage.u.data;
2908 len = DomainNameLength(rr->resrec.name);
2909 // We have a nxt name followed by window number, window length and a window bitmap
2910 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
2911 if (nsec.resrec.rdlength <= StandardAuthRDSize)
2912 {
2913 mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
2914 AssignDomainName((domainname *)ptr, rr->resrec.name);
2915 ptr += len;
2916 *ptr++ = 0; // window number
2917 *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
2918 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2919 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2920 {
2921 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2922 else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2923 }
2924 newptr = responseptr;
2925 if (!r2) // If we successfully built our NSEC record, add it to the packet now
2926 {
2927 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2928 if (newptr) responseptr = newptr;
2929 }
2930 }
2931 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength);
2932
2933 // If we successfully put the NSEC record, clear the SendNSECNow flag
2934 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2935 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2936 {
2937 rr->SendNSECNow = mDNSNULL;
2938 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2939 for (r2 = rr->next; r2; r2=r2->next)
2940 if (SameResourceRecordNameClassInterface(r2, rr))
2941 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2942 r2->SendNSECNow = mDNSNULL;
2943 }
2944 }
2945
2946 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2947 {
2948 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
2949 if (OwnerRecordSpace || TraceRecordSpace)
2950 {
2951 AuthRecord opt;
2952 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2953 opt.resrec.rrclass = NormalMaxDNSMessageData;
2954 opt.resrec.rdlength = sizeof(rdataOPT);
2955 opt.resrec.rdestimate = sizeof(rdataOPT);
2956 if (OwnerRecordSpace && TraceRecordSpace)
2957 {
2958 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
2959 opt.resrec.rdestimate += sizeof(rdataOPT);
2960 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2961 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
2962 }
2963 else if (OwnerRecordSpace)
2964 {
2965 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2966 }
2967 else if (TraceRecordSpace)
2968 {
2969 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
2970 }
2971 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2972 if (newptr)
2973 {
2974 responseptr = newptr;
2975 }
2976 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2977 {
2978 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2979 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2980 }
2981 else
2982 {
2983 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2984 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2985 }
2986 }
2987
2988 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2989 numDereg, numDereg == 1 ? "" : "s",
2990 numAnnounce, numAnnounce == 1 ? "" : "s",
2991 numAnswer, numAnswer == 1 ? "" : "s",
2992 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2993
2994 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2995 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2996 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2997 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
2998 // There might be more things to send on this interface, so go around one more time and try again.
2999 }
3000 else // Nothing more to send on this interface; go to next
3001 {
3002 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3003 #if MDNS_DEBUGMSGS && 0
3004 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3005 debugf(msg, intf, next);
3006 #endif
3007 intf = next;
3008 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3009 }
3010 }
3011
3012 // ***
3013 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3014 // ***
3015
3016 if (m->CurrentRecord)
3017 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3018 m->CurrentRecord = m->ResourceRecords;
3019 while (m->CurrentRecord)
3020 {
3021 rr = m->CurrentRecord;
3022 m->CurrentRecord = rr->next;
3023
3024 if (rr->SendRNow)
3025 {
3026 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
3027 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3028 (uint32_t)rr->SendRNow, (uint32_t)rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
3029 rr->SendRNow = mDNSNULL;
3030 }
3031
3032 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3033 {
3034 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
3035
3036 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
3037 {
3038 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3039 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
3040 }
3041 else
3042 {
3043 rr->ImmedAnswer = mDNSNULL;
3044 rr->ImmedUnicast = mDNSfalse;
3045 rr->v4Requester = zerov4Addr;
3046 rr->v6Requester = zerov6Addr;
3047 }
3048 }
3049 }
3050 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
3051 }
3052
3053 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3054 // so we want to be lazy about how frequently we do it.
3055 // 1. If a cache record is currently referenced by *no* active questions,
3056 // then we don't mind expiring it up to a minute late (who will know?)
3057 // 2. Else, if a cache record is due for some of its final expiration queries,
3058 // we'll allow them to be late by up to 2% of the TTL
3059 // 3. Else, if a cache record has completed all its final expiration queries without success,
3060 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3061 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3062 // so allow at most 1/10 second lateness
3063 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3064 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3065 #define CacheCheckGracePeriod(RR) ( \
3066 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3067 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
3068 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3069 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3070
3071 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
3072
3073 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
3074 {
3075 if (m->rrcache_nextcheck[slot] - event > 0)
3076 m->rrcache_nextcheck[slot] = event;
3077 if (m->NextCacheCheck - event > 0)
3078 m->NextCacheCheck = event;
3079 }
3080
3081 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3082 // rr->TimeRcvd
3083 // rr->resrec.rroriginalttl
3084 // rr->UnansweredQueries
3085 // rr->CRActiveQuestion
3086 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
3087 {
3088 rr->NextRequiredQuery = RRExpireTime(rr);
3089
3090 // If we have an active question, then see if we want to schedule a refresher query for this record.
3091 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3092 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3093 {
3094 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
3095 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
3096 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3097 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
3098 }
3099 ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr));
3100 }
3101
3102 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3103 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3104 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3105
3106 // Delay before restarting questions on a flapping interface.
3107 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3)
3108 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3109 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3110 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7))
3111
3112 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
3113 {
3114 if (interval < kMinimumReconfirmTime)
3115 interval = kMinimumReconfirmTime;
3116 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3117 interval = 0x10000000;
3118
3119 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3120 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
3121 {
3122 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3123 // For all the reconfirmations in a given batch, we want to use the same random value
3124 // so that the reconfirmation questions can be grouped into a single query packet
3125 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime);
3126 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
3127 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
3128 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
3129 SetNextCacheCheckTimeForRecord(m, rr);
3130 }
3131 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3132 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
3133 return(mStatus_NoError);
3134 }
3135
3136 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3137 // It also appends to the list of known answer records that need to be included,
3138 // and updates the forcast for the size of the known answer section.
3139 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
3140 DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
3141 {
3142 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3143 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3144 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
3145 mDNSu8 anoninfo_space = q->AnonInfo ? AnonInfoSpace(q->AnonInfo) : 0;
3146 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast - anoninfo_space, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
3147 if (!newptr)
3148 {
3149 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3150 return(mDNSfalse);
3151 }
3152 else
3153 {
3154 mDNSu32 forecast = *answerforecast + anoninfo_space;
3155 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3156 CacheRecord *rr;
3157 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
3158
3159 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
3160 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
3161 !(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
3162 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not already in the known answer list
3163 rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3164 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
3165 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
3166 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
3167 {
3168 // We don't want to include unique records in the Known Answer section. The Known Answer section
3169 // is intended to suppress floods of shared-record replies from many other devices on the network.
3170 // That concept really does not apply to unique records, and indeed if we do send a query for
3171 // which we have a unique record already in our cache, then including that unique record as a
3172 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3173
3174 *ka = rr; // Link this record into our known answer chain
3175 ka = &rr->NextInKAList;
3176 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3177 forecast += 12 + rr->resrec.rdestimate;
3178 // If we're trying to put more than one question in this packet, and it doesn't fit
3179 // then undo that last question and try again next time
3180 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3181 {
3182 query->h.numQuestions--;
3183 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3184 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
3185 ka = *kalistptrptr; // Go back to where we started and retract these answer records
3186 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
3187 return(mDNSfalse); // Return false, so we'll try again in the next packet
3188 }
3189 }
3190
3191 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3192 *queryptr = newptr; // Update the packet pointer
3193 *answerforecast = forecast; // Update the forecast
3194 *kalistptrptr = ka; // Update the known answer list pointer
3195 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
3196
3197 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // For every resource record in our cache,
3198 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
3199 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not in the known answer list
3200 SameNameRecordAnswersQuestion(&rr->resrec, q)) // which answers our question
3201 {
3202 rr->UnansweredQueries++; // indicate that we're expecting a response
3203 rr->LastUnansweredTime = m->timenow;
3204 SetNextCacheCheckTimeForRecord(m, rr);
3205 }
3206
3207 return(mDNStrue);
3208 }
3209 }
3210
3211 // When we have a query looking for a specified name, but there appear to be no answers with
3212 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3213 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3214 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3215 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3216 // A typical reconfirmation scenario might go like this:
3217 // Depth 0: Name "myhost.local" has no address records
3218 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3219 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3220 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3221 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3222 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3223 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
3224 {
3225 mDNSu32 slot;
3226 CacheGroup *cg;
3227 CacheRecord *cr;
3228 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
3229 FORALL_CACHERECORDS(slot, cg, cr)
3230 {
3231 domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
3232 if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
3233 {
3234 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
3235 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3236 if (depth < 5)
3237 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
3238 }
3239 }
3240 }
3241
3242 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3243 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3244 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3245 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3246 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3247 {
3248 CacheGroup *const cg = CacheGroupForName(m, namehash, name);
3249 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3250 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3251 return(cr);
3252 }
3253
3254
3255 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3256 {
3257 #ifndef SPC_DISABLED
3258 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3259 const CacheRecord *cr, *bestcr = mDNSNULL;
3260 mDNSu32 bestmetric = 1000000;
3261 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3262 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
3263 if (cr != c0 && cr != c1) // that's not one we've seen before,
3264 if (SameNameRecordAnswersQuestion(&cr->resrec, q)) // and answers our browse query,
3265 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
3266 {
3267 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3268 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3269 }
3270 return(bestcr);
3271 #else // SPC_DISABLED
3272 (void) m;
3273 (void) q;
3274 (void) c0;
3275 (void) c1;
3276 (void) c1;
3277 return mDNSNULL;
3278 #endif // SPC_DISABLED
3279 }
3280
3281 mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
3282 {
3283 const CacheRecord *swap_sps;
3284 mDNSu32 metric1, metric2;
3285
3286 if (!(*sps1) || !(*sps2)) return;
3287 metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
3288 metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
3289 if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
3290 {
3291 swap_sps = *sps1;
3292 *sps1 = *sps2;
3293 *sps2 = swap_sps;
3294 }
3295 }
3296
3297 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3298 {
3299 CheckAndSwapSPS(&sps[0], &sps[1]);
3300 CheckAndSwapSPS(&sps[0], &sps[2]);
3301 CheckAndSwapSPS(&sps[1], &sps[2]);
3302 }
3303
3304
3305 // Finds the three best Sleep Proxies we currently have in our cache
3306 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3307 {
3308 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3309 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
3310 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
3311
3312 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3313 // only if they have equally good metric and support features.
3314 ReorderSPSByFeature(sps);
3315 }
3316
3317 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3318 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3319 {
3320 int i;
3321 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3322 }
3323
3324 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3325 {
3326 int i;
3327 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3328 }
3329
3330 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3331 {
3332 int i;
3333 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3334 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3335 for (i=0; i<DupSuppressInfoSize; i++)
3336 if (ds[i].InterfaceID == intf->InterfaceID)
3337 {
3338 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3339 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3340 if (v4 && v6) return(mDNStrue);
3341 }
3342 return(mDNSfalse);
3343 }
3344
3345 mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3346 {
3347 int i, j;
3348
3349 // See if we have this one in our list somewhere already
3350 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3351
3352 // If not, find a slot we can re-use
3353 if (i >= DupSuppressInfoSize)
3354 {
3355 i = 0;
3356 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3357 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3358 i = j;
3359 }
3360
3361 // Record the info about this query we saw
3362 ds[i].Time = Time;
3363 ds[i].InterfaceID = InterfaceID;
3364 ds[i].Type = Type;
3365 }
3366
3367 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3368 {
3369 int len, i, cnt;
3370 mDNSInterfaceID InterfaceID = q->InterfaceID;
3371 domainname *d = &q->qname;
3372
3373 // We can't send magic packets without knowing which interface to send it on.
3374 if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID))
3375 {
3376 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3377 return;
3378 }
3379
3380 // Split MAC@IPAddress and pass them separately
3381 len = d->c[0];
3382 cnt = 0;
3383 for (i = 1; i < len; i++)
3384 {
3385 if (d->c[i] == '@')
3386 {
3387 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3388 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3389 if (cnt != 5)
3390 {
3391 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3392 return;
3393 }
3394 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3395 {
3396 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3397 return;
3398 }
3399 if ((len - i) > (int)(sizeof(IPAddr) - 1))
3400 {
3401 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3402 return;
3403 }
3404 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3405 EthAddr[i - 1] = 0;
3406 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3407 IPAddr[len - i] = 0;
3408 m->mDNSStats.WakeOnResolves++;
3409 mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3410 return;
3411 }
3412 else if (d->c[i] == ':')
3413 cnt++;
3414 }
3415 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3416 }
3417
3418
3419 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3420 {
3421 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3422 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3423 return(mDNStrue);
3424
3425 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3426 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3427 {
3428 // We forecast: qname (n) type (2) class (2)
3429 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3430 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3431 const CacheRecord *rr;
3432 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
3433 if (rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3434 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
3435 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
3436 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3437 {
3438 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3439 forecast += 12 + rr->resrec.rdestimate;
3440 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3441 }
3442 return(mDNStrue);
3443 }
3444
3445 return(mDNSfalse);
3446 }
3447
3448 // How Standard Queries are generated:
3449 // 1. The Question Section contains the question
3450 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3451
3452 // How Probe Queries are generated:
3453 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3454 // if some other host is already using *any* records with this name, we want to know about it.
3455 // 2. The Authority Section contains the proposed values we intend to use for one or more
3456 // of our records with that name (analogous to the Update section of DNS Update packets)
3457 // because if some other host is probing at the same time, we each want to know what the other is
3458 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3459
3460 mDNSlocal void SendQueries(mDNS *const m)
3461 {
3462 mDNSu32 slot;
3463 CacheGroup *cg;
3464 CacheRecord *cr;
3465 AuthRecord *ar;
3466 int pktcount = 0;
3467 DNSQuestion *q;
3468 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3469 mDNSs32 maxExistingQuestionInterval = 0;
3470 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3471 CacheRecord *KnownAnswerList = mDNSNULL;
3472
3473 // 1. If time for a query, work out what we need to do
3474
3475 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3476 // to their NextRequiredQuery to be worth batching them together with this one
3477 FORALL_CACHERECORDS(slot, cg, cr)
3478 {
3479 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3480 {
3481 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3482 {
3483 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3484 q = cr->CRActiveQuestion;
3485 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3486 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3487 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3488 if (q->Target.type)
3489 {
3490 q->SendQNow = mDNSInterfaceMark; // If targeted query, mark it
3491 }
3492 else if (!mDNSOpaque16IsZero(q->TargetQID))
3493 {
3494 q->LastQTime = m->timenow - q->ThisQInterval;
3495 cr->UnansweredQueries++;
3496 m->mDNSStats.CacheRefreshQueries++;
3497 }
3498 else if (q->SendQNow == mDNSNULL)
3499 {
3500 q->SendQNow = cr->resrec.InterfaceID;
3501 }
3502 else if (q->SendQNow != cr->resrec.InterfaceID)
3503 {
3504 q->SendQNow = mDNSInterfaceMark;
3505 }
3506
3507 // Indicate that this question was marked for sending
3508 // to update an existing cached answer record.
3509 // The browse throttling logic below uses this to determine
3510 // if the query should be sent.
3511 if (mDNSOpaque16IsZero(q->TargetQID))
3512 q->CachedAnswerNeedsUpdate = mDNStrue;
3513 }
3514 }
3515 }
3516
3517 // Scan our list of questions to see which:
3518 // *WideArea* queries need to be sent
3519 // *unicast* queries need to be sent
3520 // *multicast* queries we're definitely going to send
3521 if (m->CurrentQuestion)
3522 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3523 m->CurrentQuestion = m->Questions;
3524 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3525 {
3526 q = m->CurrentQuestion;
3527 if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
3528 {
3529 mDNSu8 *qptr = m->omsg.data;
3530 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
3531
3532 // 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
3533 if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(zeroIPPort);
3534 if (q->LocalSocket)
3535 {
3536 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
3537 qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
3538 mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL, q->UseBackgroundTrafficClass);
3539 q->ThisQInterval *= QuestionIntervalStep;
3540 }
3541 if (q->ThisQInterval > MaxQuestionInterval)
3542 q->ThisQInterval = MaxQuestionInterval;
3543 q->LastQTime = m->timenow;
3544 q->LastQTxTime = m->timenow;
3545 q->RecentAnswerPkts = 0;
3546 q->SendQNow = mDNSNULL;
3547 q->ExpectUnicastResp = NonZeroTime(m->timenow);
3548 }
3549 else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
3550 {
3551 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3552 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3553 if (maxExistingQuestionInterval < q->ThisQInterval)
3554 maxExistingQuestionInterval = q->ThisQInterval;
3555 }
3556 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3557 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3558 // m->CurrentQuestion point to the right question
3559 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3560 }
3561 while (m->CurrentQuestion)
3562 {
3563 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3564 m->CurrentQuestion = m->CurrentQuestion->next;
3565 }
3566 m->CurrentQuestion = mDNSNULL;
3567
3568 // Scan our list of questions
3569 // (a) to see if there are any more that are worth accelerating, and
3570 // (b) to update the state variables for *all* the questions we're going to send
3571 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3572 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3573 // 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.
3574 m->NextScheduledQuery = m->timenow + FutureTime;
3575 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3576 {
3577 if (mDNSOpaque16IsZero(q->TargetQID)
3578 && (q->SendQNow || (!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3579 {
3580 // If at least halfway to next query time, advance to next interval
3581 // If less than halfway to next query time, then
3582 // treat this as logically a repeat of the last transmission, without advancing the interval
3583 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3584 {
3585 // If we have reached the answer threshold for this question,
3586 // don't send it again until MaxQuestionInterval unless:
3587 // one of its cached answers needs to be refreshed,
3588 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3589 if (q->BrowseThreshold
3590 && (q->CurrentAnswers >= q->BrowseThreshold)
3591 && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3592 && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3593 {
3594 q->SendQNow = mDNSNULL;
3595 q->ThisQInterval = MaxQuestionInterval;
3596 q->LastQTime = m->timenow;
3597 q->RequestUnicast = 0;
3598 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3599 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3600 }
3601 else
3602 {
3603 // Mark this question for sending on all interfaces
3604 q->SendQNow = mDNSInterfaceMark;
3605 q->ThisQInterval *= QuestionIntervalStep;
3606 }
3607
3608 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3609 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3610
3611 if (q->ThisQInterval > MaxQuestionInterval)
3612 {
3613 q->ThisQInterval = MaxQuestionInterval;
3614 }
3615 else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3616 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3617 {
3618 // Generally don't need to log this.
3619 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3620 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3621 // and when there simply happen to be no instances of the service the client is looking
3622 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3623 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3624 q->qname.c, DNSTypeName(q->qtype));
3625 // Sending third query, and no answers yet; time to begin doubting the source
3626 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3627 }
3628 }
3629
3630 // Mark for sending. (If no active interfaces, then don't even try.)
3631 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3632 if (q->SendOnAll)
3633 {
3634 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3635 q->LastQTime = m->timenow;
3636 }
3637
3638 // If we recorded a duplicate suppression for this question less than half an interval ago,
3639 // then we consider it recent enough that we don't need to do an identical query ourselves.
3640 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3641
3642 q->LastQTxTime = m->timenow;
3643 q->RecentAnswerPkts = 0;
3644 if (q->RequestUnicast) q->RequestUnicast--;
3645 }
3646 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3647 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3648 SetNextQueryTime(m,q);
3649 }
3650
3651 // 2. Scan our authoritative RR list to see what probes we might need to send
3652
3653 m->NextScheduledProbe = m->timenow + FutureTime;
3654
3655 if (m->CurrentRecord)
3656 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3657 m->CurrentRecord = m->ResourceRecords;
3658 while (m->CurrentRecord)
3659 {
3660 ar = m->CurrentRecord;
3661 m->CurrentRecord = ar->next;
3662 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
3663 {
3664 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3665 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3666 {
3667 SetNextAnnounceProbeTime(m, ar);
3668 }
3669 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3670 else if (ar->ProbeCount)
3671 {
3672 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3673 {
3674 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3675 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3676 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3677 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3678 // A similar concern may apply to the NDP Probe too. -- SC
3679 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3680 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3681 }
3682 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3683 {
3684 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3685 // IPv6 source = zero
3686 // No target hardware address
3687 // IPv6 target address is address we're probing
3688 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3689 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3690 }
3691 // Mark for sending. (If no active interfaces, then don't even try.)
3692 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3693 ar->LastAPTime = m->timenow;
3694 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3695 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3696 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3697 ar->ProbeCount = DefaultProbeCountForTypeUnique;
3698 ar->ProbeCount--;
3699 SetNextAnnounceProbeTime(m, ar);
3700 if (ar->ProbeCount == 0)
3701 {
3702 // If this is the last probe for this record, then see if we have any matching records
3703 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3704 AuthRecord *r2;
3705 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3706 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3707 r2->ProbeCount = 0;
3708 // ... then acknowledge this record to the client.
3709 // We do this optimistically, just as we're about to send the third probe.
3710 // This helps clients that both advertise and browse, and want to filter themselves
3711 // from the browse results list, because it helps ensure that the registration
3712 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3713 // A potential downside is that we could deliver a registration confirmation and then find out
3714 // moments later that there's a name conflict, but applications have to be prepared to handle
3715 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3716 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3717 }
3718 }
3719 // else, if it has now finished probing, move it to state Verified,
3720 // and update m->NextScheduledResponse so it will be announced
3721 else
3722 {
3723 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
3724 ar->resrec.RecordType = kDNSRecordTypeVerified;
3725 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3726 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3727 SetNextAnnounceProbeTime(m, ar);
3728 }
3729 }
3730 }
3731 m->CurrentRecord = m->DuplicateRecords;
3732 while (m->CurrentRecord)
3733 {
3734 ar = m->CurrentRecord;
3735 m->CurrentRecord = ar->next;
3736 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3737 AcknowledgeRecord(m, ar);
3738 }
3739
3740 // 3. Now we know which queries and probes we're sending,
3741 // go through our interface list sending the appropriate queries on each interface
3742 while (intf)
3743 {
3744 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3745 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3746 mDNSu8 *queryptr = m->omsg.data;
3747 mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class
3748
3749 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3750 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3751 if (!KnownAnswerList)
3752 {
3753 // Start a new known-answer list
3754 CacheRecord **kalistptr = &KnownAnswerList;
3755 mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3756
3757 // Put query questions in this packet
3758 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3759 {
3760 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3761 {
3762 mDNSBool Suppress = mDNSfalse;
3763 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3764 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
3765 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3766
3767 // If interface is P2P type, verify that query should be sent over it.
3768 if (!mDNSPlatformValidQuestionForInterface(q, intf))
3769 {
3770 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3771 }
3772 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3773 else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3774 BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3775 {
3776 // We successfully added the question to the packet. Make sure that
3777 // we also send the NSEC3 record if required. BuildQuestion accounted for
3778 // the space.
3779 //
3780 // Note: We don't suppress anonymous questions and hence Suppress should always
3781 // be zero.
3782
3783 if (Suppress)
3784 m->mDNSStats.DupQuerySuppressions++;
3785
3786 if (!Suppress && q->AnonInfo)
3787 {
3788 debugf("SendQueries: marking for question %##s, Suppress %d", q->qname.c, Suppress);
3789 q->AnonInfo->SendNow = intf->InterfaceID;
3790 }
3791 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3792 if (q->WakeOnResolveCount)
3793 {
3794 mDNSSendWakeOnResolve(m, q);
3795 q->WakeOnResolveCount--;
3796 }
3797
3798 // use background traffic class if any included question requires it
3799 if (q->UseBackgroundTrafficClass)
3800 {
3801 useBackgroundTrafficClass = mDNStrue;
3802 }
3803 }
3804 }
3805 }
3806
3807 // Put probe questions in this packet
3808 for (ar = m->ResourceRecords; ar; ar=ar->next)
3809 {
3810 if (ar->SendRNow != intf->InterfaceID)
3811 continue;
3812
3813 // If interface is a P2P variant, verify that the probe should be sent over it.
3814 if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID))
3815 {
3816 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3817 ar->IncludeInProbe = mDNSfalse;
3818 }
3819 else
3820 {
3821 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3822 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3823 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3824 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3825 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3826 mDNSBool putProbe = mDNStrue;
3827 mDNSu16 qclass = ar->resrec.rrclass | ucbit;
3828
3829 {// Determine if this probe question is already in packet's dns message
3830 const mDNSu8 *questionptr = m->omsg.data;
3831 DNSQuestion question;
3832 mDNSu16 n;
3833 for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++)
3834 {
3835 questionptr = getQuestion(&m->omsg, questionptr, limit, mDNSInterface_Any, &question);
3836 if (questionptr && (question.qtype == kDNSQType_ANY) && (question.qclass == qclass) &&
3837 (question.qnamehash == ar->resrec.namehash) && SameDomainName(&question.qname, ar->resrec.name))
3838 {
3839 putProbe = mDNSfalse; // set to false if already in message
3840 break;
3841 }
3842 }
3843 }
3844
3845 if (putProbe)
3846 {
3847 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass);
3848 if (newptr)
3849 {
3850 queryptr = newptr;
3851 answerforecast = forecast;
3852 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3853 ar->IncludeInProbe = mDNStrue;
3854 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3855 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount, ar->resrec.InterfaceID, ar->resrec.rdestimate, answerforecast);
3856 }
3857 }
3858 else
3859 {
3860 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3861 ar->IncludeInProbe = mDNStrue;
3862 }
3863 }
3864 }
3865 }
3866
3867 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3868 while (KnownAnswerList)
3869 {
3870 CacheRecord *ka = KnownAnswerList;
3871 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3872 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3873 m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3874 if (newptr)
3875 {
3876 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3877 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3878 queryptr = newptr;
3879 KnownAnswerList = ka->NextInKAList;
3880 ka->NextInKAList = mDNSNULL;
3881 }
3882 else
3883 {
3884 // If we ran out of space and we have more than one question in the packet, that's an error --
3885 // we shouldn't have put more than one question if there was a risk of us running out of space.
3886 if (m->omsg.h.numQuestions > 1)
3887 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3888 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3889 break;
3890 }
3891 }
3892
3893 for (ar = m->ResourceRecords; ar; ar=ar->next)
3894 {
3895 if (ar->IncludeInProbe)
3896 {
3897 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3898 ar->IncludeInProbe = mDNSfalse;
3899 if (newptr) queryptr = newptr;
3900 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3901 }
3902 }
3903
3904 for (q = m->Questions; q; q = q->next)
3905 {
3906 if (q->AnonInfo && q->AnonInfo->SendNow == intf->InterfaceID)
3907 {
3908 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, q->AnonInfo->nsec3RR);
3909 if (newptr)
3910 {
3911 debugf("SendQueries: Added NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3912 queryptr = newptr;
3913 }
3914 else
3915 {
3916 LogMsg("SendQueries: ERROR!! Cannot add NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3917 }
3918 q->AnonInfo->SendNow = mDNSNULL;
3919 }
3920 }
3921
3922 if (queryptr > m->omsg.data)
3923 {
3924 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3925 if (OwnerRecordSpace || TraceRecordSpace)
3926 {
3927 AuthRecord opt;
3928 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3929 opt.resrec.rrclass = NormalMaxDNSMessageData;
3930 opt.resrec.rdlength = sizeof(rdataOPT);
3931 opt.resrec.rdestimate = sizeof(rdataOPT);
3932 if (OwnerRecordSpace && TraceRecordSpace)
3933 {
3934 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
3935 opt.resrec.rdestimate += sizeof(rdataOPT);
3936 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3937 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3938 }
3939 else if (OwnerRecordSpace)
3940 {
3941 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3942 }
3943 else if (TraceRecordSpace)
3944 {
3945 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3946 }
3947 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3948 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3949 if (!queryptr)
3950 {
3951 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3952 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3953 }
3954 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3955 {
3956 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3957 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
3958 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
3959 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3960 }
3961 }
3962
3963 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3964 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3965 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
3966 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
3967 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
3968 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3969 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3970 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3971 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3972 if (++pktcount >= 1000)
3973 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3974 // There might be more records left in the known answer list, or more questions to send
3975 // on this interface, so go around one more time and try again.
3976 }
3977 else // Nothing more to send on this interface; go to next
3978 {
3979 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3980 #if MDNS_DEBUGMSGS && 0
3981 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
3982 debugf(msg, intf, next);
3983 #endif
3984 intf = next;
3985 }
3986 }
3987
3988 // 4. Final housekeeping
3989
3990 // 4a. Debugging check: Make sure we announced all our records
3991 for (ar = m->ResourceRecords; ar; ar=ar->next)
3992 if (ar->SendRNow)
3993 {
3994 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
3995 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
3996 (uint32_t)ar->SendRNow, (uint32_t)ar->resrec.InterfaceID, ARDisplayString(m, ar));
3997 ar->SendRNow = mDNSNULL;
3998 }
3999
4000 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4001 // that their interface which went away might come back again, the logic will want to send queries
4002 // for those records, but we can't because their interface isn't here any more, so to keep the
4003 // state machine ticking over we just pretend we did so.
4004 // If the interface does not come back in time, the cache record will expire naturally
4005 FORALL_CACHERECORDS(slot, cg, cr)
4006 {
4007 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
4008 {
4009 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
4010 {
4011 cr->UnansweredQueries++;
4012 cr->CRActiveQuestion->SendQNow = mDNSNULL;
4013 SetNextCacheCheckTimeForRecord(m, cr);
4014 }
4015 }
4016 }
4017
4018 // 4c. Debugging check: Make sure we sent all our planned questions
4019 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4020 // we legitimately couldn't send because the interface is no longer available
4021 for (q = m->Questions; q; q=q->next)
4022 {
4023 if (q->SendQNow)
4024 {
4025 DNSQuestion *x;
4026 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
4027 // There will not be an active interface for questions applied to mDNSInterface_BLE
4028 // so don't log the warning in that case.
4029 if (q->InterfaceID != mDNSInterface_BLE)
4030 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4031 (uint32_t)q->SendQNow, x ? "new" : "old", (uint32_t)q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
4032 q->SendQNow = mDNSNULL;
4033 }
4034 q->CachedAnswerNeedsUpdate = mDNSfalse;
4035 }
4036 }
4037
4038 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly)
4039 {
4040 int i, j;
4041
4042 mDNSu8 *ptr = m->omsg.data;
4043 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
4044 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
4045
4046 // 0x00 Destination address
4047 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4048
4049 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4050 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
4051
4052 // 0x0C Ethertype (0x0842)
4053 *ptr++ = 0x08;
4054 *ptr++ = 0x42;
4055
4056 // 0x0E Wakeup sync sequence
4057 for (i=0; i<6; i++) *ptr++ = 0xFF;
4058
4059 // 0x14 Wakeup data
4060 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4061
4062 // 0x74 Password
4063 for (i=0; i<6; i++) *ptr++ = password->b[i];
4064
4065 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4066
4067 if (!unicastOnly)
4068 {
4069 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4070 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4071 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4072 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4073 // So, we send one of each, unicast first, then broadcast second.
4074 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
4075 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4076 }
4077 }
4078
4079 // ***************************************************************************
4080 #if COMPILER_LIKES_PRAGMA_MARK
4081 #pragma mark -
4082 #pragma mark - RR List Management & Task Management
4083 #endif
4084
4085 // Whenever a question is answered, reset its state so that we don't query
4086 // the network repeatedly. This happens first time when we answer the question and
4087 // and later when we refresh the cache.
4088 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
4089 {
4090 q->LastQTime = m->timenow;
4091 q->LastQTxTime = m->timenow;
4092 q->RecentAnswerPkts = 0;
4093 q->ThisQInterval = MaxQuestionInterval;
4094 q->RequestUnicast = 0;
4095 // Reset unansweredQueries so that we don't penalize this server later when we
4096 // start sending queries when the cache expires.
4097 q->unansweredQueries = 0;
4098 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4099 }
4100
4101 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4102 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4103 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4104 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4105 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
4106 {
4107 DNSQuestion *const q = m->CurrentQuestion;
4108 const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
4109
4110 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
4111 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
4112
4113 // When the response for the question was validated, the entire rrset was validated. If we deliver
4114 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
4115 // in the future, we will do the revalidation again.
4116 //
4117 // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
4118 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
4119 // negative response which can happen e.g., when disconnecting from network that leads to a negative response
4120 // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
4121 // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
4122 // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
4123 // a real negative response, we would reset the state here and validate the results at the end of this function.
4124 // or the real response again if we purge the cache.
4125 if (q->ValidationRequired && ((AddRecord == QC_rmv) ||
4126 (rr->resrec.RecordType == kDNSRecordTypePacketNegative && (AddRecord == QC_add))))
4127 {
4128 q->ValidationStatus = 0;
4129 q->ValidationState = DNSSECValRequired;
4130 }
4131
4132 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4133 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4134 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4135 // we check to see if that query already has a unique local answer.
4136 if (q->LOAddressAnswers)
4137 {
4138 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4139 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
4140 q->LOAddressAnswers);
4141 return;
4142 }
4143
4144 if (QuerySuppressed(q))
4145 {
4146 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4147 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4148 // that are timing out, which we know are answered with negative cache record when timing out.
4149 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
4150 return;
4151 }
4152
4153 #if AWD_METRICS
4154 if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname)
4155 {
4156 const domainname * queryName;
4157 mDNSu32 responseLatencyMs;
4158 mDNSBool isForCellular;
4159
4160 queryName = q->metrics.originalQName ? q->metrics.originalQName : &q->qname;
4161 isForCellular = (q->qDNSServer && q->qDNSServer->cellIntf);
4162 if (!q->metrics.answered)
4163 {
4164 if (q->metrics.querySendCount > 0)
4165 {
4166 responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
4167 }
4168 else
4169 {
4170 responseLatencyMs = 0;
4171 }
4172
4173 MetricsUpdateDNSQueryStats(queryName, q->qtype, &rr->resrec, q->metrics.querySendCount, responseLatencyMs, isForCellular);
4174 q->metrics.answered = mDNStrue;
4175 }
4176 if (q->metrics.querySendCount > 0)
4177 {
4178 MetricsUpdateDNSResolveStats(queryName, &rr->resrec, isForCellular);
4179 }
4180 }
4181 #endif
4182 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4183 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4184 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4185
4186 rr->LastUsed = m->timenow;
4187 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
4188 {
4189 if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
4190 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4191 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
4192 rr->CRActiveQuestion = q; // We know q is non-null
4193 SetNextCacheCheckTimeForRecord(m, rr);
4194 }
4195
4196 // If this is:
4197 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4198 // (b) a normal add, where we have at least one unique-type answer,
4199 // then there's no need to keep polling the network.
4200 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4201 // We do this for mDNS questions and uDNS one-shot questions, but not for
4202 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4203 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
4204 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
4205 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
4206 {
4207 ResetQuestionState(m, q);
4208 }
4209
4210 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4211
4212 #if USE_DNS64
4213 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4214 if (!mDNSOpaque16IsZero(q->TargetQID) && DNS64StateMachine(m, q, &rr->resrec, AddRecord)) return;
4215 #endif
4216
4217 #ifdef USE_LIBIDN
4218 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) // If negative answer, check if we need to try Punycode conversion
4219 {
4220 domainname newname;
4221 if (PerformNextPunycodeConversion(q, &newname)) // Itertative Punycode conversion succeeded, so reissue question with new name
4222 {
4223 UDPSocket *const sock = q->LocalSocket; // Save old socket and transaction ID
4224 const mDNSOpaque16 id = q->TargetQID;
4225 q->LocalSocket = mDNSNULL;
4226 mDNS_StopQuery_internal(m, q); // Stop old query
4227 AssignDomainName(&q->qname, &newname); // Update qname
4228 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
4229 mDNS_StartQuery_internal(m, q); // Start new query
4230
4231 if (sock) // Transplant saved socket, if appropriate
4232 {
4233 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
4234 else { q->LocalSocket = sock; q->TargetQID = id; }
4235 }
4236 return; // All done for now; wait until we get the next answer
4237 }
4238 }
4239 #endif // USE_LIBIDN
4240
4241 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4242 // for the purpose of retrying search domains/timeout OR the question is suppressed
4243 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
4244 if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
4245
4246 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4247 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
4248 {
4249 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4250 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
4251 {
4252 CacheRecord neg;
4253 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
4254 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
4255 }
4256 else
4257 {
4258 #if USE_DNS64
4259 if (DNS64ShouldAnswerQuestion(q, &rr->resrec))
4260 {
4261 DNS64AnswerQuestion(m, q, &rr->resrec, AddRecord);
4262 }
4263 else
4264 #endif
4265 {
4266 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4267 }
4268 }
4269 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4270 }
4271 // If this is an "Add" operation and this question needs validation, validate the response.
4272 // In the case of negative responses, extra care should be taken. Negative cache records are
4273 // used for many purposes. For example,
4274 //
4275 // 1) Suppressing questions (SuppressUnusable)
4276 // 2) Timeout questions
4277 // 3) The name does not exist
4278 // 4) No DNS servers are available and we need a quick response for the application
4279 //
4280 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
4281 // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
4282 // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
4283 // signature for (4) and hence the explicit check for q->qDNSServer.
4284 //
4285 if (m->CurrentQuestion == q && (AddRecord == QC_add) && !q->ValidatingResponse && q->ValidationRequired &&
4286 q->ValidationState == DNSSECValRequired && q->qDNSServer)
4287 {
4288 q->ValidationState = DNSSECValInProgress;
4289 // Treat it as callback call as that's what dnssec code expects
4290 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4291 VerifySignature(m, mDNSNULL, q);
4292 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4293 return;
4294 }
4295
4296 // Note: Proceed with caution here because client callback function is allowed to do anything,
4297 // including starting/stopping queries, registering/deregistering records, etc.
4298 //
4299 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4300 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4301 // first before following it
4302 if ((m->CurrentQuestion == q) && followcname && !ValidatingQuestion(q))
4303 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
4304 }
4305
4306 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
4307 {
4308 rr->DelayDelivery = 0;
4309 if (m->CurrentQuestion)
4310 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4311 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4312 m->CurrentQuestion = m->Questions;
4313 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4314 {
4315 DNSQuestion *q = m->CurrentQuestion;
4316 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4317 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4318 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4319 m->CurrentQuestion = q->next;
4320 }
4321 m->CurrentQuestion = mDNSNULL;
4322 }
4323
4324 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
4325 {
4326 const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
4327 const mDNSs32 start = m->timenow - 0x10000000;
4328 mDNSs32 delay = start;
4329 CacheGroup *cg = CacheGroupForName(m, namehash, name);
4330 const CacheRecord *rr;
4331
4332 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4333 {
4334 if (threshold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
4335 {
4336 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
4337 delay = RRExpireTime(rr);
4338 }
4339 }
4340 if (delay - start > 0)
4341 return(NonZeroTime(delay));
4342 else
4343 return(0);
4344 }
4345
4346 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4347 // If new questions are created as a result of invoking client callbacks, they will be added to
4348 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4349 // rr is a new CacheRecord just received into our cache
4350 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4351 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4352 // which may change the record list and/or question list.
4353 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4354 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
4355 {
4356 DNSQuestion *q;
4357
4358 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4359 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4360 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4361 {
4362 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4363 {
4364 // If this question is one that's actively sending queries, and it's received ten answers within one
4365 // second of sending the last query packet, then that indicates some radical network topology change,
4366 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4367 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4368 // because we will anyway send another query within a few seconds. The first reset query is sent out
4369 // randomized over the next four seconds to reduce possible synchronization between machines.
4370 if (q->LastAnswerPktNum != m->PktNum)
4371 {
4372 q->LastAnswerPktNum = m->PktNum;
4373 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4374 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4375 {
4376 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4377 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4378 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4379 q->ThisQInterval = InitialQuestionInterval;
4380 SetNextQueryTime(m,q);
4381 }
4382 }
4383 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
4384 DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
4385 &rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
4386 rr->resrec.rDNSServer->port : zeroIPPort), q);
4387 q->CurrentAnswers++;
4388
4389 q->unansweredQueries = 0;
4390 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4391 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4392 if (q->CurrentAnswers > 4000)
4393 {
4394 static int msgcount = 0;
4395 if (msgcount++ < 10)
4396 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4397 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4398 rr->resrec.rroriginalttl = 0;
4399 rr->UnansweredQueries = MaxUnansweredQueries;
4400 }
4401 }
4402 }
4403
4404 if (!rr->DelayDelivery)
4405 {
4406 if (m->CurrentQuestion)
4407 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4408 m->CurrentQuestion = m->Questions;
4409 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4410 {
4411 q = m->CurrentQuestion;
4412 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4413 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4414 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4415 m->CurrentQuestion = q->next;
4416 }
4417 m->CurrentQuestion = mDNSNULL;
4418 }
4419
4420 SetNextCacheCheckTimeForRecord(m, rr);
4421 }
4422
4423 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4424 // If new questions are created as a result of invoking client callbacks, they will be added to
4425 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4426 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4427 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4428 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4429 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4430 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4431 // which may change the record list and/or question list.
4432 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4433 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
4434 {
4435 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4436 if (m->CurrentQuestion)
4437 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4438 m->CurrentQuestion = m->Questions;
4439 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4440 // since we're not caching the record and we'll get no opportunity to do this later
4441 while (m->CurrentQuestion)
4442 {
4443 DNSQuestion *q = m->CurrentQuestion;
4444 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4445 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
4446 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4447 m->CurrentQuestion = q->next;
4448 }
4449 m->CurrentQuestion = mDNSNULL;
4450 }
4451
4452 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4453 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4454 // If new questions are created as a result of invoking client callbacks, they will be added to
4455 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4456 // rr is an existing cache CacheRecord that just expired and is being deleted
4457 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4458 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4459 // which may change the record list and/or question list.
4460 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4461 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
4462 {
4463 if (m->CurrentQuestion)
4464 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4465 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4466 m->CurrentQuestion = m->Questions;
4467
4468 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4469 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4470 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4471 {
4472 DNSQuestion *q = m->CurrentQuestion;
4473 // When a question enters suppressed state, we generate RMV events and generate a negative
4474 // response. A cache may be present that answers this question e.g., cache entry generated
4475 // before the question became suppressed. We need to skip the suppressed questions here as
4476 // the RMV event has already been generated.
4477 if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
4478 {
4479 verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
4480 q->FlappingInterface1 = mDNSNULL;
4481 q->FlappingInterface2 = mDNSNULL;
4482
4483 if (q->CurrentAnswers == 0)
4484 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4485 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4486 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
4487 else
4488 {
4489 q->CurrentAnswers--;
4490 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4491 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4492 }
4493
4494 // If we have dropped below the answer threshold for this mDNS question,
4495 // restart the queries at InitialQuestionInterval.
4496 if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4497 {
4498 q->ThisQInterval = InitialQuestionInterval;
4499 q->LastQTime = m->timenow - q->ThisQInterval;
4500 SetNextQueryTime(m,q);
4501 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4502 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4503 }
4504 if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4505 {
4506 if (q->CurrentAnswers == 0)
4507 {
4508 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4509 q->qname.c, DNSTypeName(q->qtype));
4510 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
4511 }
4512 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
4513 }
4514 }
4515 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4516 m->CurrentQuestion = q->next;
4517 }
4518 m->CurrentQuestion = mDNSNULL;
4519 }
4520
4521 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4522 {
4523 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
4524 unsigned int i;
4525 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4526 #endif
4527 e->next = m->rrcache_free;
4528 m->rrcache_free = e;
4529 m->rrcache_totalused--;
4530 }
4531
4532 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4533 {
4534 CacheEntity *e = (CacheEntity *)(*cp);
4535 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4536 if ((*cp)->rrcache_tail != &(*cp)->members)
4537 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4538 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4539 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4540 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4541 (*cp)->name = mDNSNULL;
4542 *cp = (*cp)->next; // Cut record from list
4543 ReleaseCacheEntity(m, e);
4544 }
4545
4546 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4547 {
4548 while (*rp)
4549 {
4550 CacheRecord *rr = *rp;
4551 *rp = (*rp)->next; // Cut record from list
4552 if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4553 {
4554 mDNSPlatformMemFree(rr->resrec.rdata);
4555 rr->resrec.rdata = mDNSNULL;
4556 }
4557 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4558 // of the CacheGroup.
4559 if (rr->resrec.name)
4560 {
4561 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4562 mDNSPlatformMemFree((void *)rr->resrec.name);
4563 rr->resrec.name = mDNSNULL;
4564 }
4565 // Don't count the NSEC3 records used by anonymous browse/reg
4566 if (!rr->resrec.InterfaceID)
4567 {
4568 m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4569 if (DNSSECRecordType(rr->resrec.rrtype))
4570 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
4571 }
4572 ReleaseCacheEntity(m, (CacheEntity *)rr);
4573 }
4574 }
4575
4576 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4577 {
4578 CacheGroup *cg;
4579
4580 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4581 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4582 r->resrec.rdata = mDNSNULL;
4583
4584 cg = CacheGroupForRecord(m, &r->resrec);
4585
4586 if (!cg)
4587 {
4588 // It is okay to have this printed for NSEC/NSEC3s
4589 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4590 }
4591 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4592 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4593 // (which is handled below) and in that case it should be freed here.
4594 if (r->resrec.name && cg && r->resrec.name != cg->name)
4595 {
4596 debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4597 mDNSPlatformMemFree((void *)r->resrec.name);
4598 }
4599 r->resrec.name = mDNSNULL;
4600
4601 if (r->resrec.AnonInfo)
4602 {
4603 debugf("ReleaseCacheRecord: freeing AnonInfo for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4604 FreeAnonInfo((void *)r->resrec.AnonInfo);
4605 }
4606 r->resrec.AnonInfo = mDNSNULL;
4607
4608 if (!r->resrec.InterfaceID)
4609 {
4610 m->rrcache_totalused_unicast -= r->resrec.rdlength;
4611 if (DNSSECRecordType(r->resrec.rrtype))
4612 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, r->resrec.rdlength);
4613 }
4614
4615 ReleaseAdditionalCacheRecords(m, &r->nsec);
4616 ReleaseAdditionalCacheRecords(m, &r->soa);
4617
4618 ReleaseCacheEntity(m, (CacheEntity *)r);
4619 }
4620
4621 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4622 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4623 // callbacks for old records are delivered before callbacks for newer records.
4624 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4625 {
4626 CacheRecord **rp = &cg->members;
4627
4628 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4629 m->lock_rrcache = 1;
4630
4631 while (*rp)
4632 {
4633 CacheRecord *const rr = *rp;
4634 mDNSs32 event = RRExpireTime(rr);
4635 if (m->timenow - event >= 0) // If expired, delete it
4636 {
4637 *rp = rr->next; // Cut it from the list
4638
4639 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
4640 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4641 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
4642 {
4643 DNSQuestion *q = rr->CRActiveQuestion;
4644 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4645 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4646 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4647 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4648 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4649 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4650 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4651 if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
4652 {
4653 q->ThisQInterval = InitialQuestionInterval;
4654 q->LastQTime = m->timenow - q->ThisQInterval;
4655 SetNextQueryTime(m, q);
4656 }
4657 CacheRecordRmv(m, rr);
4658 m->rrcache_active--;
4659 }
4660 ReleaseCacheRecord(m, rr);
4661 }
4662 else // else, not expired; see if we need to query
4663 {
4664 // If waiting to delay delivery, do nothing until then
4665 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4666 event = rr->DelayDelivery;
4667 else
4668 {
4669 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4670 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4671 {
4672 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
4673 event = NextCacheCheckEvent(rr); // then just record when we want the next query
4674 else // else trigger our question to go out now
4675 {
4676 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4677 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4678 m->NextScheduledQuery = m->timenow;
4679 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4680 // which will correctly update m->NextCacheCheck for us.
4681 event = m->timenow + FutureTime;
4682 }
4683 }
4684 }
4685 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4686 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4687 if (m->rrcache_nextcheck[slot] - event > 0)
4688 m->rrcache_nextcheck[slot] = event;
4689 rp = &rr->next;
4690 }
4691 }
4692 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4693 cg->rrcache_tail = rp;
4694 m->lock_rrcache = 0;
4695 }
4696
4697 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4698 //
4699 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4700 // returns true if there is an answer.
4701 //
4702 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4703 // returns true to indicate the same.
4704 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4705 {
4706 AuthRecord *lr;
4707 AuthGroup *ag;
4708
4709 if (m->CurrentRecord)
4710 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4711
4712 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
4713 if (ag)
4714 {
4715 m->CurrentRecord = ag->members;
4716 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4717 {
4718 AuthRecord *rr = m->CurrentRecord;
4719 m->CurrentRecord = rr->next;
4720 //
4721 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4722 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4723 //
4724 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4725 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4726 // we handle both mDNSInterface_Any and scoped questions.
4727
4728 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE)))
4729 if (LocalOnlyRecordAnswersQuestion(rr, q))
4730 {
4731 if (checkOnly)
4732 {
4733 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4734 ARDisplayString(m, rr));
4735 m->CurrentRecord = mDNSNULL;
4736 return mDNStrue;
4737 }
4738 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4739 if (m->CurrentQuestion != q)
4740 break; // If callback deleted q, then we're finished here
4741 }
4742 }
4743 }
4744 m->CurrentRecord = mDNSNULL;
4745
4746 if (m->CurrentQuestion != q)
4747 {
4748 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4749 return mDNStrue;
4750 }
4751
4752 if (q->LOAddressAnswers)
4753 {
4754 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4755 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4756 return mDNStrue;
4757 }
4758
4759 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4760 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4761 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4762 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4763 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4764 if (ag)
4765 {
4766 lr = ag->NewLocalOnlyRecords;
4767 while (lr)
4768 {
4769 if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4770 {
4771 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4772 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4773 return mDNStrue;
4774 }
4775 lr = lr->next;
4776 }
4777 }
4778 return mDNSfalse;
4779 }
4780
4781 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4782 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4783 // DNS requests. We need to temporarily suspend the suppress status so that we can
4784 // deliver a negative response (AnswerCurrentQuestionWithResourceRecord does not answer
4785 // suppressed questions) and reset it back. In the future, if there are other
4786 // reasons for suppressing the query, this function should be updated.
4787 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4788 {
4789 mDNSBool SuppressQuery;
4790 mDNSBool DisallowPID;
4791
4792 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response, just
4793 // deactivate the DNSQuestion.
4794 if (!q->ReturnIntermed)
4795 {
4796 q->ThisQInterval = 0;
4797 return;
4798 }
4799
4800 SuppressQuery = q->SuppressQuery;
4801 DisallowPID = q->DisallowPID;
4802
4803 // make sure that QuerySuppressed() returns false
4804 q->SuppressQuery = mDNSfalse;
4805 q->DisallowPID = mDNSfalse;
4806
4807 GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed);
4808
4809 q->SuppressQuery = SuppressQuery;
4810 q->DisallowPID = DisallowPID;
4811 }
4812
4813 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4814 {
4815 mDNSBool ShouldQueryImmediately = mDNStrue;
4816 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
4817 #if USE_DNS64
4818 if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q);
4819 #endif
4820 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
4821 mDNSBool AnsweredFromCache = mDNSfalse;
4822
4823 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4824
4825 if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg);
4826 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4827 m->NewQuestions = q->next;
4828 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4829 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4830 //
4831 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4832 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4833 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4834 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4835 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4836 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4837 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4838 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4839 //
4840 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4841 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4842 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4843 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4844
4845 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4846 // This should be safe, because calling the client's question callback may cause the
4847 // question list to be modified, but should not ever cause the rrcache list to be modified.
4848 // If the client's question callback deletes the question, then m->CurrentQuestion will
4849 // be advanced, and we'll exit out of the loop
4850 m->lock_rrcache = 1;
4851 if (m->CurrentQuestion)
4852 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4853 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4854 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4855
4856 if (q->NoAnswer == NoAnswer_Fail)
4857 {
4858 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4859 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
4860 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
4861 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
4862 // Don't touch the question if it has been stopped already
4863 if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
4864 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
4865 }
4866
4867 if (m->CurrentQuestion != q)
4868 {
4869 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4870 goto exit;
4871 }
4872
4873 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4874 // or P2P record, then we are done.
4875 if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
4876 goto exit;
4877
4878 // If we are not supposed to answer this question, generate a negative response.
4879 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
4880 //
4881 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
4882 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
4883 // the question out.
4884 if (QuerySuppressed(q))
4885 {
4886 AnswerSuppressedQuestion(m, q);
4887 }
4888 else if (!q->ValidatingResponse)
4889 {
4890 CacheRecord *rr;
4891 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4892 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
4893 {
4894 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4895 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
4896 if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
4897 {
4898 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
4899 rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
4900 continue; // Go to next one in loop
4901 }
4902
4903 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4904 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4905 if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
4906 ShouldQueryImmediately = mDNSfalse;
4907 q->CurrentAnswers++;
4908 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4909 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4910 AnsweredFromCache = mDNStrue;
4911 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4912 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4913 }
4914 else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
4915 ShouldQueryImmediately = mDNSfalse;
4916 }
4917 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
4918 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
4919 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
4920
4921 // Neither a local record nor a cache entry could answer this question. If this question need to be retried
4922 // with search domains, generate a negative response which will now retry after appending search domains.
4923 // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
4924 // we will retry with search domains.
4925 if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
4926 {
4927 LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4928 GenerateNegativeResponse(m, mDNSInterface_Any, QC_forceresponse);
4929 }
4930
4931 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
4932
4933 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
4934 // Hence we don't execute the following block of code for those cases.
4935 if (ShouldQueryImmediately && ActiveQuestion(q))
4936 {
4937 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4938 q->ThisQInterval = InitialQuestionInterval;
4939 q->LastQTime = m->timenow - q->ThisQInterval;
4940 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
4941 {
4942 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
4943 if (!m->RandomQueryDelay)
4944 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
4945 q->LastQTime += m->RandomQueryDelay;
4946 }
4947 }
4948
4949 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
4950 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
4951 // answers for this question until *after* its scheduled transmission time, in which case
4952 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
4953 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
4954 SetNextQueryTime(m,q);
4955
4956 exit:
4957 m->CurrentQuestion = mDNSNULL;
4958 m->lock_rrcache = 0;
4959 }
4960
4961 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
4962 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
4963 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
4964 {
4965 AuthGroup *ag;
4966 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
4967 mDNSBool retEv = mDNSfalse;
4968 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
4969
4970 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4971
4972 if (m->CurrentQuestion)
4973 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4974 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4975 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4976
4977 if (m->CurrentRecord)
4978 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4979
4980 // 1. First walk the LocalOnly records answering the LocalOnly question
4981 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
4982 // walk the ResourceRecords list delivering the answers
4983 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
4984 if (ag)
4985 {
4986 m->CurrentRecord = ag->members;
4987 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4988 {
4989 AuthRecord *rr = m->CurrentRecord;
4990 m->CurrentRecord = rr->next;
4991 if (LocalOnlyRecordAnswersQuestion(rr, q))
4992 {
4993 retEv = mDNStrue;
4994 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4995 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4996 }
4997 }
4998 }
4999
5000 if (m->CurrentQuestion == q)
5001 {
5002 m->CurrentRecord = m->ResourceRecords;
5003
5004 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
5005 {
5006 AuthRecord *rr = m->CurrentRecord;
5007 m->CurrentRecord = rr->next;
5008 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
5009 {
5010 retEv = mDNStrue;
5011 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
5012 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5013 }
5014 }
5015 }
5016
5017 // The local host is the authoritative source for LocalOnly questions
5018 // so if no records exist and client requested intermediates, then generate a negative response
5019 if (!retEv && (m->CurrentQuestion == q) && q->ReturnIntermed)
5020 GenerateNegativeResponse(m, mDNSInterface_LocalOnly, QC_forceresponse);
5021
5022 m->CurrentQuestion = mDNSNULL;
5023 m->CurrentRecord = mDNSNULL;
5024 }
5025
5026 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
5027 {
5028 CacheEntity *e = mDNSNULL;
5029
5030 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
5031 m->lock_rrcache = 1;
5032
5033 // If we have no free records, ask the client layer to give us some more memory
5034 if (!m->rrcache_free && m->MainCallback)
5035 {
5036 if (m->rrcache_totalused != m->rrcache_size)
5037 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
5038 m->rrcache_totalused, m->rrcache_size);
5039
5040 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5041 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5042 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5043 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5044 // and recycle them, instead of allocating more memory.
5045 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
5046 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
5047 m->rrcache_size, m->rrcache_active);
5048 else
5049 {
5050 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5051 m->MainCallback(m, mStatus_GrowCache);
5052 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5053 }
5054 }
5055
5056 // If we still have no free records, recycle all the records we can.
5057 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5058 if (!m->rrcache_free)
5059 {
5060 mDNSu32 oldtotalused = m->rrcache_totalused;
5061 mDNSu32 slot;
5062 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5063 {
5064 CacheGroup **cp = &m->rrcache_hash[slot];
5065 while (*cp)
5066 {
5067 CacheRecord **rp = &(*cp)->members;
5068 while (*rp)
5069 {
5070 // Records that answer still-active questions are not candidates for recycling
5071 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5072 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
5073 rp=&(*rp)->next;
5074 else
5075 {
5076 CacheRecord *rr = *rp;
5077 *rp = (*rp)->next; // Cut record from list
5078 ReleaseCacheRecord(m, rr);
5079 }
5080 }
5081 if ((*cp)->rrcache_tail != rp)
5082 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
5083 (*cp)->rrcache_tail = rp;
5084 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
5085 else ReleaseCacheGroup(m, cp);
5086 }
5087 }
5088 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
5089 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
5090 }
5091
5092 if (m->rrcache_free) // If there are records in the free list, take one
5093 {
5094 e = m->rrcache_free;
5095 m->rrcache_free = e->next;
5096 if (++m->rrcache_totalused >= m->rrcache_report)
5097 {
5098 LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
5099 if (m->rrcache_report < 100) m->rrcache_report += 10;
5100 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
5101 else m->rrcache_report += 1000;
5102 }
5103 mDNSPlatformMemZero(e, sizeof(*e));
5104 }
5105
5106 m->lock_rrcache = 0;
5107
5108 return(e);
5109 }
5110
5111 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
5112 {
5113 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
5114 if (r)
5115 {
5116 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
5117 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
5118 {
5119 r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
5120 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
5121 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
5122 }
5123 }
5124 return(r);
5125 }
5126
5127 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
5128 {
5129 mDNSu16 namelen = DomainNameLength(rr->name);
5130 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
5131 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
5132 cg->next = m->rrcache_hash[slot];
5133 cg->namehash = rr->namehash;
5134 cg->members = mDNSNULL;
5135 cg->rrcache_tail = &cg->members;
5136 if (namelen > sizeof(cg->namestorage))
5137 cg->name = mDNSPlatformMemAllocate(namelen);
5138 else
5139 cg->name = (domainname*)cg->namestorage;
5140 if (!cg->name)
5141 {
5142 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
5143 ReleaseCacheEntity(m, (CacheEntity*)cg);
5144 return(mDNSNULL);
5145 }
5146 AssignDomainName(cg->name, rr->name);
5147
5148 if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
5149 m->rrcache_hash[slot] = cg;
5150 if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
5151
5152 return(cg);
5153 }
5154
5155 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
5156 {
5157 mDNS_CheckLock(m);
5158
5159 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5160 // a positive answer using an expired record (e.g. from an interface that has gone away).
5161 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5162 // summary deletion without giving the proper callback to any questions that are monitoring it.
5163 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5164 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
5165 rr->UnansweredQueries = MaxUnansweredQueries;
5166 rr->resrec.rroriginalttl = 0;
5167 SetNextCacheCheckTimeForRecord(m, rr);
5168 }
5169
5170 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
5171 {
5172 mDNSs32 time;
5173 mDNSPlatformLock(m);
5174 if (m->mDNS_busy)
5175 {
5176 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5177 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
5178 }
5179
5180 if (m->timenow) time = m->timenow;
5181 else time = mDNS_TimeNow_NoLock(m);
5182 mDNSPlatformUnlock(m);
5183 return(time);
5184 }
5185
5186 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5187 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5188 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5189 #define SetSPSProxyListChanged(X) do { \
5190 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5191 m->SPSProxyListChanged = (X); } while(0)
5192
5193 // Called from mDNS_Execute() to expire stale proxy records
5194 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
5195 {
5196 m->CurrentRecord = list;
5197 while (m->CurrentRecord)
5198 {
5199 AuthRecord *rr = m->CurrentRecord;
5200 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
5201 {
5202 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5203 // so we need to cease proxying for *all* records we may have, expired or not.
5204 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
5205 {
5206 if (m->NextScheduledSPS - rr->TimeExpire > 0)
5207 m->NextScheduledSPS = rr->TimeExpire;
5208 }
5209 else // else proxy record expired, so remove it
5210 {
5211 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5212 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
5213 SetSPSProxyListChanged(rr->resrec.InterfaceID);
5214 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5215 // Don't touch rr after this -- memory may have been free'd
5216 }
5217 }
5218 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5219 // new records could have been added to the end of the list as a result of that call.
5220 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5221 m->CurrentRecord = rr->next;
5222 }
5223 }
5224
5225 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
5226 {
5227 while (m->CurrentRecord)
5228 {
5229 AuthRecord *rr = m->CurrentRecord;
5230 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
5231 {
5232 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
5233 rr->resrec.RecordType = kDNSRecordTypeShared;
5234 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
5235 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
5236 {
5237 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
5238 rr->AnsweredLocalQ = mDNSfalse;
5239 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5240 // For LocalOnly records, we don't do that and hence we need to do that here.
5241 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
5242 }
5243 }
5244 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5245 m->CurrentRecord = rr->next;
5246 }
5247 }
5248
5249 mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID)
5250 {
5251 if (m->CurrentQuestion)
5252 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
5253 DNSTypeName(m->CurrentQuestion->qtype));
5254 m->CurrentQuestion = questions;
5255 while (m->CurrentQuestion)
5256 {
5257 DNSQuestion *const q = m->CurrentQuestion;
5258 if (q->StopTime)
5259 {
5260 if (!q->TimeoutQuestion)
5261 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5262
5263 if (m->timenow - q->StopTime >= 0)
5264 {
5265 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
5266 q->LOAddressAnswers = 0; // unset since timing out the question
5267 GenerateNegativeResponse(m, InterfaceID, QC_forceresponse);
5268 if (m->CurrentQuestion == q) q->StopTime = 0;
5269 }
5270 else
5271 {
5272 if (m->NextScheduledStopTime - q->StopTime > 0)
5273 m->NextScheduledStopTime = q->StopTime;
5274 }
5275 }
5276 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5277 // We can't do this at the start of the loop because GenerateNegativeResponse
5278 // depends on having m->CurrentQuestion point to the right question
5279 if (m->CurrentQuestion == q)
5280 m->CurrentQuestion = q->next;
5281 }
5282 m->CurrentQuestion = mDNSNULL;
5283 }
5284
5285 mDNSlocal void TimeoutQuestions(mDNS *const m)
5286 {
5287 m->NextScheduledStopTime = m->timenow + FutureTime; // push reschedule of TimeoutQuestions to way off into the future
5288 TimeoutQuestions_internal(m, m->Questions, mDNSInterface_Any);
5289 TimeoutQuestions_internal(m, m->LocalOnlyQuestions, mDNSInterface_LocalOnly);
5290 }
5291
5292 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
5293 {
5294 AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
5295 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
5296 while (rrPtr)
5297 {
5298 rrNext = rrPtr->next;
5299 mDNSPlatformMemFree(rrPtr);
5300 rrPtr = rrNext;
5301 }
5302 m->SPSRRSet = mDNSNULL;
5303 }
5304
5305 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
5306 {
5307 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
5308
5309 if (m->timenow - m->NextScheduledEvent >= 0)
5310 {
5311 int i;
5312 AuthRecord *head, *tail;
5313 mDNSu32 slot;
5314 AuthGroup *ag;
5315
5316 verbosedebugf("mDNS_Execute");
5317
5318 if (m->CurrentQuestion)
5319 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5320 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5321
5322 if (m->CurrentRecord)
5323 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5324
5325 // 1. If we're past the probe suppression time, we can clear it
5326 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5327
5328 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5329 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5330
5331 // 3. Purge our cache of stale old records
5332 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5333 {
5334 mDNSu32 numchecked = 0;
5335 m->NextCacheCheck = m->timenow + FutureTime;
5336 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5337 {
5338 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5339 {
5340 CacheGroup **cp = &m->rrcache_hash[slot];
5341 m->rrcache_nextcheck[slot] = m->timenow + FutureTime;
5342 while (*cp)
5343 {
5344 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5345 numchecked++;
5346 CheckCacheExpiration(m, slot, *cp);
5347 if ((*cp)->members) cp=&(*cp)->next;
5348 else ReleaseCacheGroup(m, cp);
5349 }
5350 }
5351 // Even if we didn't need to actually check this slot yet, still need to
5352 // factor its nextcheck time into our overall NextCacheCheck value
5353 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5354 m->NextCacheCheck = m->rrcache_nextcheck[slot];
5355 }
5356 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5357 }
5358
5359 if (m->timenow - m->NextScheduledSPS >= 0)
5360 {
5361 m->NextScheduledSPS = m->timenow + FutureTime;
5362 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
5363 CheckProxyRecords(m, m->ResourceRecords);
5364 }
5365
5366 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
5367
5368 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5369 // as records could have expired during that check
5370 if (m->timenow - m->NextScheduledKA >= 0)
5371 {
5372 m->NextScheduledKA = m->timenow + FutureTime;
5373 mDNS_SendKeepalives(m);
5374 }
5375
5376 #if BONJOUR_ON_DEMAND
5377 if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0))
5378 {
5379 // Schedule immediate network change processing to leave the multicast group
5380 // since the delay time has expired since the previous active registration or query.
5381 m->NetworkChanged = m->timenow;
5382 m->NextBonjourDisableTime = 0;
5383 m->BonjourEnabled = 0;
5384
5385 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5386 }
5387 #endif // BONJOUR_ON_DEMAND
5388
5389 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5390 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5391 {
5392 m->AnnounceOwner = 0;
5393
5394 // This is a good time to reset the delay counter used to prevent spurious conflicts
5395 m->DelayConflictProcessing = 0;
5396 }
5397
5398 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5399 {
5400 m->DelaySleep = 0;
5401 if (m->SleepState == SleepState_Transferring)
5402 {
5403 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5404 BeginSleepProcessing(m);
5405 }
5406 }
5407
5408 // 4. See if we can answer any of our new local questions from the cache
5409 for (i=0; m->NewQuestions && i<1000; i++)
5410 {
5411 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5412 AnswerNewQuestion(m);
5413 }
5414 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5415
5416 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5417 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5418 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5419 {
5420 m->LocalRemoveEvents = mDNSfalse;
5421 m->CurrentRecord = m->ResourceRecords;
5422 CheckRmvEventsForLocalRecords(m);
5423 // Walk the LocalOnly records and deliver the RMV events
5424 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5425 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5426 {
5427 m->CurrentRecord = ag->members;
5428 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5429 }
5430 }
5431
5432 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5433
5434 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5435 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5436
5437 head = tail = mDNSNULL;
5438 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5439 {
5440 AuthRecord *rr = m->NewLocalRecords;
5441 m->NewLocalRecords = m->NewLocalRecords->next;
5442 if (LocalRecordReady(rr))
5443 {
5444 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5445 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
5446 }
5447 else if (!rr->next)
5448 {
5449 // If we have just one record that is not ready, we don't have to unlink and
5450 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5451 // terminate and set the NewLocalRecords to rr.
5452 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5453 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5454 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5455
5456 head = rr;
5457 }
5458 else
5459 {
5460 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
5461 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5462 // if this is the first record we are skipping, move to the end of the list.
5463 // if we have already skipped records before, append it at the end.
5464 while (*p && *p != rr) p=&(*p)->next;
5465 if (*p) *p = rr->next; // Cut this record from the list
5466 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5467 if (!head)
5468 {
5469 while (*p) p=&(*p)->next;
5470 *p = rr;
5471 head = tail = rr;
5472 }
5473 else
5474 {
5475 tail->next = rr;
5476 tail = rr;
5477 }
5478 rr->next = mDNSNULL;
5479 }
5480 }
5481 m->NewLocalRecords = head;
5482 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5483
5484 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5485
5486 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5487 // to our local questions
5488 if (m->NewLocalOnlyRecords)
5489 {
5490 m->NewLocalOnlyRecords = mDNSfalse;
5491 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5492 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5493 {
5494 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5495 {
5496 AuthRecord *rr = ag->NewLocalOnlyRecords;
5497 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5498 // LocalOnly records should always be ready as they never probe
5499 if (LocalRecordReady(rr))
5500 {
5501 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5502 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
5503 }
5504 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5505 }
5506 // We limit about 100 per AuthGroup that can be serviced at a time
5507 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5508 }
5509 }
5510
5511 // 5. See what packets we need to send
5512 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5513 DiscardDeregistrations(m);
5514 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5515 {
5516 // If the platform code is ready, and we're not suppressing packet generation right now
5517 // then send our responses, probes, and questions.
5518 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5519 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5520 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5521 // Finally, we send responses, including the previously mentioned records that just completed probing.
5522 m->SuppressSending = 0;
5523
5524 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5525 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5526 if (m->timenow - m->NextScheduledQuery >= 0)
5527 {
5528 DNSQuestion *q;
5529 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5530 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5531 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5532 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5533 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5534 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5535 }
5536 if (m->timenow - m->NextScheduledProbe >= 0)
5537 {
5538 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5539 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5540 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5541 }
5542
5543 // 7. Send Response packets, including probing records just advanced to announcing state
5544 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5545 if (m->timenow - m->NextScheduledResponse >= 0)
5546 {
5547 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5548 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5549 }
5550 }
5551
5552 // Clear RandomDelay values, ready to pick a new different value next time
5553 m->RandomQueryDelay = 0;
5554 m->RandomReconfirmDelay = 0;
5555
5556 // See if any questions (or local-only questions) have timed out
5557 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5558 #ifndef UNICAST_DISABLED
5559 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5560 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5561 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5562 #endif
5563 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5564 extern void serviceBLE();
5565 if (m->NextBLEServiceTime && (m->timenow - m->NextBLEServiceTime >= 0)) serviceBLE();
5566 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5567 }
5568
5569 // Note about multi-threaded systems:
5570 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5571 // performing mDNS API operations that change our next scheduled event time.
5572 //
5573 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5574 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5575 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5576 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5577 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5578 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5579 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5580 // without blocking. This avoids the race condition between the signal from the other thread arriving
5581 // just *before* or just *after* the main thread enters the blocking primitive.
5582 //
5583 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5584 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5585 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5586 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5587 // by the time it gets to the timer callback function).
5588
5589 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5590 return(m->NextScheduledEvent);
5591 }
5592
5593 #ifndef UNICAST_DISABLED
5594 mDNSlocal void SuspendLLQs(mDNS *m)
5595 {
5596 DNSQuestion *q;
5597 for (q = m->Questions; q; q = q->next)
5598 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5599 { q->ReqLease = 0; sendLLQRefresh(m, q); }
5600 }
5601 #endif // UNICAST_DISABLED
5602
5603 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5604 {
5605 AuthRecord *rr;
5606 AuthGroup *ag;
5607
5608 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5609 if (ag)
5610 {
5611 for (rr = ag->members; rr; rr=rr->next)
5612 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5613 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5614 {
5615 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5616 return mDNStrue;
5617 }
5618 }
5619 return mDNSfalse;
5620 }
5621
5622 // ActivateUnicastQuery() is called from three places:
5623 // 1. When a new question is created
5624 // 2. On wake from sleep
5625 // 3. When the DNS configuration changes
5626 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5627 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5628 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5629 {
5630 // For now this AutoTunnel stuff is specific to Mac OS X.
5631 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
5632 #if APPLE_OSX_mDNSResponder
5633 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
5634 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
5635 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
5636 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
5637 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
5638 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
5639
5640 if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
5641 !SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
5642 {
5643 question->NoAnswer = NoAnswer_Suspended;
5644 AddNewClientTunnel(question);
5645 return;
5646 }
5647 #endif // APPLE_OSX_mDNSResponder
5648
5649 if (!question->DuplicateOf)
5650 {
5651 debugf("ActivateUnicastQuery: %##s %s%s%s",
5652 question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
5653 question->CNAMEReferrals = 0;
5654 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5655 if (question->LongLived)
5656 {
5657 question->state = LLQ_InitialRequest;
5658 question->id = zeroOpaque64;
5659 question->servPort = zeroIPPort;
5660 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5661 }
5662 // If the question has local answers, then we don't want answers from outside
5663 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5664 {
5665 question->ThisQInterval = InitialQuestionInterval;
5666 question->LastQTime = m->timenow - question->ThisQInterval;
5667 SetNextQueryTime(m, question);
5668 }
5669 }
5670 }
5671
5672 // Caller should hold the lock
5673 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5674 CallbackBeforeStartQuery BeforeStartCallback, void *context)
5675 {
5676 DNSQuestion *q;
5677 DNSQuestion *restart = mDNSNULL;
5678
5679 mDNS_CheckLock(m);
5680
5681 // 1. Flush the cache records
5682 if (flushCacheRecords) flushCacheRecords(m);
5683
5684 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5685 // we are going to stop the question. Hence we need to deliver the RMV event before we
5686 // stop the question.
5687 //
5688 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5689 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5690 // *any* other question which could be the next one that we may process here. RestartQuestion
5691 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5692 // if the "next" question is stopped while the CurrentQuestion is stopped
5693
5694 if (m->RestartQuestion)
5695 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5696 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5697
5698 m->RestartQuestion = m->Questions;
5699 while (m->RestartQuestion)
5700 {
5701 q = m->RestartQuestion;
5702 m->RestartQuestion = q->next;
5703 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5704 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5705 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5706 // question followed by the original query that refers to this GetZoneData question, we will end up
5707 // freeing the GetZoneData question and then start the "freed" question at the end.
5708
5709 if (IsGetZoneDataQuestion(q))
5710 {
5711 DNSQuestion *refq = q->next;
5712 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5713 // debug stuff, we just try to find the referencing question and don't do much with it
5714 while (refq)
5715 {
5716 if (q == &refq->nta->question)
5717 {
5718 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5719 }
5720 refq = refq->next;
5721 }
5722 continue;
5723 }
5724
5725 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5726 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5727
5728 // If the search domains did not change, then we restart all the queries. Otherwise, only
5729 // for queries for which we "might" have appended search domains ("might" because we may
5730 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5731 if (!SearchDomainsChanged || q->AppendSearchDomains)
5732 {
5733 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5734 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5735 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5736 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5737 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5738 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5739 // for the original query using these cache entries as ADDs were never delivered using these cache
5740 // entries and hence this order is needed.
5741
5742 // If the query is suppressed, the RMV events won't be delivered
5743 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5744
5745 // SuppressQuery status does not affect questions that are answered using local records
5746 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5747
5748 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
5749 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
5750 mDNS_StopQuery_internal(m, q);
5751 // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
5752 // and then search domains should be appended. At the beginning, qnameOrig was NULL.
5753 if (q->qnameOrig)
5754 {
5755 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
5756 AssignDomainName(&q->qname, q->qnameOrig);
5757 mDNSPlatformMemFree(q->qnameOrig);
5758 q->qnameOrig = mDNSNULL;
5759 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
5760 }
5761 q->SearchListIndex = 0;
5762 q->next = restart;
5763 restart = q;
5764 }
5765 }
5766
5767 // 3. Callback before we start the query
5768 if (BeforeStartCallback) BeforeStartCallback(m, context);
5769
5770 // 4. Restart all the stopped queries
5771 while (restart)
5772 {
5773 q = restart;
5774 restart = restart->next;
5775 q->next = mDNSNULL;
5776 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5777 mDNS_StartQuery_internal(m, q);
5778 }
5779 }
5780
5781 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5782 {
5783 DNSQuestion *q;
5784
5785 #ifndef UNICAST_DISABLED
5786 // Retrigger all our uDNS questions
5787 if (m->CurrentQuestion)
5788 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5789 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5790 m->CurrentQuestion = m->Questions;
5791 while (m->CurrentQuestion)
5792 {
5793 q = m->CurrentQuestion;
5794 m->CurrentQuestion = m->CurrentQuestion->next;
5795 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
5796 }
5797 #endif
5798
5799 // Retrigger all our mDNS questions
5800 for (q = m->Questions; q; q=q->next) // Scan our list of questions
5801 mDNSCoreRestartQuestion(m, q);
5802 }
5803
5804 // restart question if it's multicast and currently active
5805 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5806 {
5807 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5808 {
5809 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
5810 q->RequestUnicast = kDefaultRequestUnicastCount;
5811 q->LastQTime = m->timenow - q->ThisQInterval;
5812 q->RecentAnswerPkts = 0;
5813 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5814 m->NextScheduledQuery = m->timenow;
5815 }
5816 }
5817
5818 // restart the probe/announce cycle for multicast record
5819 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
5820 {
5821 if (!AuthRecord_uDNS(rr))
5822 {
5823 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5824 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5825
5826 if (mDNS_KeepaliveRecord(&rr->resrec))
5827 {
5828 rr->AnnounceCount = 0; // Do not announce keepalive records
5829 }
5830 else
5831 {
5832 // announceCount < 0 indicates default announce count should be used
5833 if (announceCount < 0)
5834 announceCount = InitialAnnounceCount;
5835 if (rr->AnnounceCount < (mDNSu8)announceCount)
5836 rr->AnnounceCount = (mDNSu8)announceCount;
5837 }
5838
5839 rr->SendNSECNow = mDNSNULL;
5840 InitializeLastAPTime(m, rr);
5841 }
5842 }
5843
5844 // ***************************************************************************
5845 #if COMPILER_LIKES_PRAGMA_MARK
5846 #pragma mark -
5847 #pragma mark - Power Management (Sleep/Wake)
5848 #endif
5849
5850 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
5851 {
5852 #ifndef IDLESLEEPCONTROL_DISABLED
5853 mDNSBool allowSleep = mDNStrue;
5854 char reason[128];
5855
5856 reason[0] = 0;
5857
5858 if (m->SystemSleepOnlyIfWakeOnLAN)
5859 {
5860 // Don't sleep if we are a proxy for any services
5861 if (m->ProxyRecords)
5862 {
5863 allowSleep = mDNSfalse;
5864 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
5865 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
5866 }
5867
5868 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
5869 {
5870 // Scan the list of active interfaces
5871 NetworkInterfaceInfo *intf;
5872 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5873 {
5874 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
5875 {
5876 // Disallow sleep if this interface doesn't support NetWake
5877 if (!intf->NetWake)
5878 {
5879 allowSleep = mDNSfalse;
5880 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
5881 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
5882 break;
5883 }
5884
5885 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
5886 // that will be offloaded. If not, we should prevent sleep.
5887 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
5888 #if APPLE_OSX_mDNSResponder
5889 if (!SupportsInNICProxy(intf))
5890 #endif
5891 {
5892 // Disallow sleep if there is no sleep proxy server
5893 const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
5894 if ( cr == mDNSNULL)
5895 {
5896 allowSleep = mDNSfalse;
5897 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
5898 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
5899 break;
5900 }
5901 else if (m->SPSType != 0)
5902 {
5903 mDNSu32 mymetric = LocalSPSMetric(m);
5904 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
5905 if (metric >= mymetric)
5906 {
5907 allowSleep = mDNSfalse;
5908 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
5909 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
5910 break;
5911 }
5912 }
5913 }
5914 }
5915 }
5916 }
5917 }
5918
5919 // Call the platform code to enable/disable sleep
5920 mDNSPlatformSetAllowSleep(allowSleep, reason);
5921 #else
5922 (void) m;
5923 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
5924 }
5925
5926 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
5927 {
5928 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
5929 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
5930 // to send.
5931 if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
5932 m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
5933 {
5934 return mDNSfalse;
5935 }
5936
5937 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
5938 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
5939 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
5940 // updateid and we should have returned from above.
5941 //
5942 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
5943 // platform function to extract the value from "intf" every time.
5944
5945 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
5946 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
5947 return mDNStrue;
5948
5949 return mDNSfalse;
5950 }
5951
5952 mDNSexport void UpdateRMAC(mDNS *const m, void *context)
5953 {
5954 IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
5955 m->CurrentRecord = m->ResourceRecords;
5956
5957 if (!addrmap)
5958 {
5959 LogMsg("UpdateRMAC: Address mapping is NULL");
5960 return;
5961 }
5962
5963 while (m->CurrentRecord)
5964 {
5965 AuthRecord *rr = m->CurrentRecord;
5966 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
5967 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
5968 {
5969 mDNSAddr raddr;
5970 getKeepaliveRaddr(m, rr, &raddr);
5971 if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
5972 {
5973 // Update the MAC address only if it is not a zero MAC address
5974 mDNSEthAddr macAddr;
5975 mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
5976 if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
5977 {
5978 UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
5979 }
5980 }
5981 }
5982 m->CurrentRecord = rr->next;
5983 }
5984
5985 if (addrmap)
5986 mDNSPlatformMemFree(addrmap);
5987
5988 }
5989
5990 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
5991 {
5992 mDNSu16 newrdlength;
5993 mDNSAddr laddr = zeroAddr;
5994 mDNSAddr raddr = zeroAddr;
5995 mDNSEthAddr eth = zeroEthAddr;
5996 mDNSIPPort lport = zeroIPPort;
5997 mDNSIPPort rport = zeroIPPort;
5998 mDNSu32 timeout = 0;
5999 mDNSu32 seq = 0;
6000 mDNSu32 ack = 0;
6001 mDNSu16 win = 0;
6002 UTF8str255 txt;
6003 int rdsize;
6004 RData *newrd;
6005 mDNSTCPInfo mti;
6006 mStatus ret;
6007
6008 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
6009 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6010 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
6011 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
6012 {
6013 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
6014 return mStatus_UnknownErr;
6015 }
6016
6017 if (updateMac)
6018 {
6019 if (laddr.type == mDNSAddrType_IPv4)
6020 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);
6021 else
6022 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);
6023
6024 }
6025 else
6026 {
6027 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6028 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6029 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6030 mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
6031 ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti);
6032 if (ret != mStatus_NoError)
6033 {
6034 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
6035 return ret;
6036 }
6037 if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
6038 {
6039 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti.IntfId, intf->InterfaceID);
6040 return mStatus_BadParamErr;
6041 }
6042
6043 if (laddr.type == mDNSAddrType_IPv4)
6044 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);
6045 else
6046 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);
6047 }
6048
6049 // Did we insert a null byte at the end ?
6050 if (newrdlength == (sizeof(txt.c) - 1))
6051 {
6052 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
6053 return mStatus_NoMemoryErr;
6054 }
6055
6056 // Include the length for the null byte at the end
6057 txt.c[0] = newrdlength + 1;
6058 // Account for the first length byte and the null byte at the end
6059 newrdlength += 2;
6060
6061 rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
6062 newrd = mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
6063 if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
6064
6065 newrd->MaxRDLength = (mDNSu16) rdsize;
6066 mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
6067
6068 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6069 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6070 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6071 // free that memory here before copying in the new data.
6072 if ( rr->resrec.rdata != &rr->rdatastorage)
6073 {
6074 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
6075 mDNSPlatformMemFree(rr->resrec.rdata);
6076 }
6077 SetNewRData(&rr->resrec, newrd, newrdlength); // Update our rdata
6078
6079 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
6080 return mStatus_NoError;
6081 }
6082
6083 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
6084 {
6085 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
6086 const int sps = intf->NextSPSAttempt / 3;
6087 AuthRecord *rr;
6088 mDNSOpaque16 msgid;
6089 mDNSu32 scopeid;
6090
6091 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6092 if (!intf->SPSAddr[sps].type)
6093 {
6094 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6095 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6096 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6097 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
6098 goto exit;
6099 }
6100
6101 // Mark our mDNS records (not unicast records) for transfer to SPS
6102 if (mDNSOpaque16IsZero(id))
6103 {
6104 // We may have to register this record over multiple interfaces and we don't want to
6105 // overwrite the id. We send the registration over interface X with id "IDX" and before
6106 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6107 // for "IDX". Hence, we want to use the same ID across all interfaces.
6108 //
6109 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6110 // option check below will set the same ID across the records from the same owner. Records
6111 // with different owner option gets different ID.
6112 msgid = mDNS_NewMessageID(m);
6113 for (rr = m->ResourceRecords; rr; rr=rr->next)
6114 {
6115 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
6116 {
6117 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
6118 {
6119 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6120 {
6121 rr->SendRNow = mDNSInterfaceMark; // mark it now
6122 // When we are registering on the first interface, rr->updateid is zero in which case
6123 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6124 // At the end, all the updates sent across all the interfaces with the same ID.
6125 if (mDNSOpaque16IsZero(rr->updateid))
6126 rr->updateid = msgid;
6127 else
6128 msgid = rr->updateid;
6129 }
6130 }
6131 }
6132 }
6133 }
6134 else
6135 msgid = id;
6136
6137 while (1)
6138 {
6139 mDNSu8 *p = m->omsg.data;
6140 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6141 // For now we follow that same logic for SPS registrations too.
6142 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6143 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6144 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
6145
6146 for (rr = m->ResourceRecords; rr; rr=rr->next)
6147 if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
6148 {
6149 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6150 {
6151 mDNSu8 *newptr;
6152 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
6153
6154 // If we can't update the keepalive record, don't send it
6155 if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
6156 {
6157 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
6158 {
6159 bit_clr_opaque64(rr->updateIntID, scopeid);
6160 }
6161 rr->SendRNow = mDNSNULL;
6162 continue;
6163 }
6164
6165 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
6166 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6167 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
6168 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
6169 if (!newptr)
6170 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
6171 else
6172 {
6173 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));
6174 rr->SendRNow = mDNSNULL;
6175 rr->ThisAPInterval = mDNSPlatformOneSecond;
6176 rr->LastAPTime = m->timenow;
6177 // should be initialized above
6178 if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
6179 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6180 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
6181 p = newptr;
6182 }
6183 }
6184 }
6185
6186 if (!m->omsg.h.mDNS_numUpdates) break;
6187 else
6188 {
6189 AuthRecord opt;
6190 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
6191 opt.resrec.rrclass = NormalMaxDNSMessageData;
6192 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
6193 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
6194 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
6195 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
6196 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
6197 if (!owner->HMAC.l[0]) // If no owner data,
6198 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information
6199 else // otherwise, use the owner data we were given
6200 {
6201 opt.resrec.rdata->u.opt[1].u.owner = *owner;
6202 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner;
6203 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
6204 }
6205 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
6206 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
6207 if (!p)
6208 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
6209 else
6210 {
6211 mStatus err;
6212
6213 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
6214 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
6215 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6216 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL, mDNSfalse);
6217 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
6218 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
6219 {
6220 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
6221 intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
6222 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
6223 return;
6224 }
6225 }
6226 }
6227 }
6228
6229 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
6230
6231 exit:
6232 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
6233 }
6234
6235 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
6236 {
6237 AuthRecord *ar;
6238 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
6239 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
6240 return mDNStrue;
6241 }
6242
6243 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
6244 {
6245 AuthRecord *newRR = mDNSPlatformMemAllocate(sizeof(AuthRecord));
6246
6247 if (newRR == mDNSNULL)
6248 {
6249 LogSPS("%s : could not allocate memory for new resource record", __func__);
6250 return;
6251 }
6252
6253 mDNSPlatformMemZero(newRR, sizeof(AuthRecord));
6254 mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
6255 rr->resrec.rroriginalttl, rr->resrec.RecordType,
6256 rr->ARType, mDNSNULL, mDNSNULL);
6257
6258 AssignDomainName(&newRR->namestorage, &rr->namestorage);
6259 newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
6260 newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
6261 newRR->resrec.rrclass = rr->resrec.rrclass;
6262
6263 if (rr->resrec.rrtype == kDNSType_A)
6264 {
6265 newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4;
6266 }
6267 else if (rr->resrec.rrtype == kDNSType_AAAA)
6268 {
6269 newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
6270 }
6271 SetNewRData(&newRR->resrec, mDNSNULL, 0);
6272
6273 // Insert the new node at the head of the list.
6274 newRR->next = m->SPSRRSet;
6275 m->SPSRRSet = newRR;
6276 LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
6277 }
6278
6279 // Some records are interface specific and some are not. The ones that are supposed to be registered
6280 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6281 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6282 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6283 // registration on all the interfaces
6284 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
6285 {
6286 AuthRecord *ar;
6287 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
6288
6289 *WakeOnlyService = mDNSfalse;
6290
6291 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6292 // make sure that the old sleep proxy records are removed.
6293 mDNSCoreFreeProxyRR(m);
6294
6295 // For records that are registered only on a specific interface, mark only that bit as it will
6296 // never be registered on any other interface. For others, it should be sent on all interfaces.
6297 for (ar = m->ResourceRecords; ar; ar=ar->next)
6298 {
6299 ar->updateIntID = zeroOpaque64;
6300 ar->updateid = zeroID;
6301 if (AuthRecord_uDNS(ar))
6302 {
6303 continue;
6304 }
6305 if (ar->AuthFlags & AuthFlagsWakeOnly)
6306 {
6307 if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
6308 {
6309 ar->ImmedAnswer = mDNSInterfaceMark;
6310 *WakeOnlyService = mDNStrue;
6311 continue;
6312 }
6313 }
6314 if (!ar->resrec.InterfaceID)
6315 {
6316 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
6317 ar->updateIntID = updateIntID;
6318 }
6319 else
6320 {
6321 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6322 // exactly this.
6323 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
6324 if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
6325 {
6326 bit_set_opaque64(ar->updateIntID, scopeid);
6327 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
6328 ar->updateIntID.l[0], ARDisplayString(m, ar));
6329 }
6330 else
6331 {
6332 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
6333 }
6334 }
6335 // Store the A and AAAA records that we registered with the sleep proxy.
6336 // We will use this to prevent spurious name conflicts that may occur when we wake up
6337 if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
6338 {
6339 mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
6340 }
6341 }
6342 }
6343
6344 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
6345 {
6346 AuthRecord *ar;
6347 OwnerOptData owner = zeroOwner;
6348
6349 SendSPSRegistrationForOwner(m, intf, id, &owner);
6350
6351 for (ar = m->ResourceRecords; ar; ar=ar->next)
6352 {
6353 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6354 {
6355 owner = ar->WakeUp;
6356 SendSPSRegistrationForOwner(m, intf, id, &owner);
6357 }
6358 }
6359 }
6360
6361 // RetrySPSRegistrations is called from SendResponses, with the lock held
6362 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6363 {
6364 AuthRecord *rr;
6365 NetworkInterfaceInfo *intf;
6366
6367 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6368 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6369 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6370 intf->NextSPSAttemptTime++;
6371
6372 // Retry any record registrations that are due
6373 for (rr = m->ResourceRecords; rr; rr=rr->next)
6374 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6375 {
6376 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6377 {
6378 // If we still have registrations pending on this interface, send it now
6379 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6380 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6381 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6382 {
6383 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6384 SendSPSRegistration(m, intf, rr->updateid);
6385 }
6386 }
6387 }
6388
6389 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6390 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6391 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6392 intf->NextSPSAttempt++;
6393 }
6394
6395 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6396 {
6397 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6398 int sps = (int)(question - intf->NetWakeResolve);
6399 (void)m; // Unused
6400 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6401
6402 if (!AddRecord) return; // Don't care about REMOVE events
6403 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
6404
6405 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6406
6407 if (answer->rrtype == kDNSType_SRV)
6408 {
6409 // 1. Got the SRV record; now look up the target host's IP address
6410 mDNS_StopQuery(m, question);
6411 intf->SPSPort[sps] = answer->rdata->u.srv.port;
6412 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6413 question->qtype = kDNSType_A;
6414 mDNS_StartQuery(m, question);
6415 }
6416 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6417 {
6418 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6419 mDNS_StopQuery(m, question);
6420 question->ThisQInterval = -1;
6421 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6422 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6423 mDNS_Lock(m);
6424 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6425 mDNS_Unlock(m);
6426 }
6427 else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6428 {
6429 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6430 mDNS_StopQuery(m, question);
6431 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6432 question->qtype = kDNSType_AAAA;
6433 mDNS_StartQuery(m, question);
6434 }
6435 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6436 {
6437 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6438 mDNS_StopQuery(m, question);
6439 question->ThisQInterval = -1;
6440 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6441 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6442 mDNS_Lock(m);
6443 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6444 mDNS_Unlock(m);
6445 }
6446 }
6447
6448 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6449 {
6450 AuthRecord *rr;
6451 for (rr = m->ResourceRecords; rr; rr=rr->next)
6452 if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6453 return mDNStrue;
6454 return mDNSfalse;
6455 }
6456
6457 #define WAKE_ONLY_SERVICE 1
6458 #define AC_ONLY_SERVICE 2
6459
6460 #ifdef APPLE_OSX_mDNSResponder
6461 mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
6462 {
6463 AuthRecord *rr;
6464 *servicePresent = mDNSfalse;
6465
6466 // Mark all the records we need to deregister and send them
6467 for (rr = m->ResourceRecords; rr; rr=rr->next)
6468 {
6469 // If the service type is wake only service and the auth flags match and requires a goodbye
6470 // OR if the service type is AC only and it is not a keepalive record,
6471 // mark the records we need to deregister and send them
6472 if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
6473 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
6474 (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
6475 {
6476 rr->ImmedAnswer = mDNSInterfaceMark;
6477 *servicePresent = mDNStrue;
6478 }
6479 }
6480 }
6481 #endif
6482
6483 #ifdef APPLE_OSX_mDNSResponder
6484 // This function is used only in the case of local NIC proxy. For external
6485 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6486 // walk the resource records.
6487 mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6488 {
6489 return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
6490 }
6491 #endif // APPLE_OSX_mDNSResponder
6492
6493
6494 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6495 {
6496 AuthRecord *rr;
6497 m->SleepState = SleepState_Sleeping;
6498
6499 // If AllInterfaces is not set, the caller has already marked it appropriately
6500 // on which interfaces this should be sent.
6501 if (AllInterfaces)
6502 {
6503 NetworkInterfaceInfo *intf;
6504 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6505 {
6506 intf->SendGoodbyes = 1;
6507 }
6508 }
6509 if (unicast)
6510 {
6511 #ifndef UNICAST_DISABLED
6512 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
6513 #endif /* UNICAST_DISABLED */
6514 }
6515
6516 // Mark all the records we need to deregister and send them
6517 for (rr = m->ResourceRecords; rr; rr=rr->next)
6518 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6519 rr->ImmedAnswer = mDNSInterfaceMark;
6520 SendResponses(m);
6521 }
6522
6523 /*
6524 * This function attempts to detect if multiple interfaces are on the same subnet.
6525 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6526 * IPv6 link local addresses that are configured by default on all interfaces make
6527 * it hard to make this determination
6528 *
6529 * The 'real' fix for this would be to send out multicast packets over one interface
6530 * and conclude that multiple interfaces are on the same subnet only if these packets
6531 * are seen on other interfaces on the same system
6532 */
6533 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6534 {
6535 NetworkInterfaceInfo *intf;
6536 NetworkInterfaceInfo *newIntf;
6537 mDNSu32 i;
6538
6539 for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6540 {
6541 if ((newIntf->InterfaceID != intfid) ||
6542 (newIntf->ip.type != mDNSAddrType_IPv4))
6543 {
6544 continue;
6545 }
6546 for ( i = 0; i < count; i++)
6547 {
6548 for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6549 {
6550 if ((intf->InterfaceID != regID[i]) ||
6551 (intf->ip.type != mDNSAddrType_IPv4))
6552 {
6553 continue;
6554 }
6555 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6556 {
6557 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6558 return (mDNStrue);
6559 }
6560 }
6561 }
6562 }
6563 return (mDNSfalse);
6564 }
6565
6566 mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6567 {
6568 // Loop through the keepalive records and callback with an error
6569 m->CurrentRecord = m->ResourceRecords;
6570 while (m->CurrentRecord)
6571 {
6572 AuthRecord *const rr = m->CurrentRecord;
6573 if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6574 {
6575 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6576 if (rr->RecordCallback)
6577 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6578 }
6579 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6580 m->CurrentRecord = rr->next;
6581 }
6582 }
6583
6584 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6585 mDNSlocal void BeginSleepProcessing(mDNS *const m)
6586 {
6587 mDNSBool SendGoodbyes = mDNStrue;
6588 mDNSBool WakeOnlyService = mDNSfalse;
6589 mDNSBool invokeKACallback = mDNStrue;
6590 const CacheRecord *sps[3] = { mDNSNULL };
6591 mDNSOpaque64 updateIntID = zeroOpaque64;
6592 mDNSInterfaceID registeredIntfIDS[128] = { 0 };
6593 mDNSu32 registeredCount = 0;
6594 int skippedRegistrations = 0;
6595
6596 m->NextScheduledSPRetry = m->timenow;
6597
6598 // Clear out the SCDynamic entry that stores the external SPS information
6599 mDNSPlatformClearSPSData();
6600
6601 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6602 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6603 else // If we have at least one advertised service
6604 {
6605 NetworkInterfaceInfo *intf;
6606 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6607 {
6608 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6609 intf->SendGoodbyes = 0;
6610
6611 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6612 // servers.
6613 if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6614 {
6615 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6616 continue;
6617 }
6618
6619 // If we are not capable of WOMP, then don't register with sleep proxy.
6620 //
6621 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6622 // We might find sleep proxy servers in the cache and start a resolve on them.
6623 // But then if the interface goes away, we won't stop these questions because
6624 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6625 // to stop both the browse and resolve questions.
6626 if (!intf->NetWake)
6627 {
6628 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6629 intf->SendGoodbyes = 1;
6630 skippedRegistrations++;
6631 continue;
6632 }
6633
6634 // Check if we have already registered with a sleep proxy for this subnet
6635 if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6636 {
6637 LogSPS("%s : Skipping sleep proxy registration on %s", __func__, intf->ifname);
6638 continue;
6639 }
6640
6641 #if APPLE_OSX_mDNSResponder
6642 else if (SupportsInNICProxy(intf))
6643 {
6644 mDNSBool keepaliveOnly = mDNSfalse;
6645 if (ActivateLocalProxy(intf, &keepaliveOnly) == mStatus_NoError)
6646 {
6647 SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6648
6649 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6650 SendGoodbyes = (keepaliveOnly) ? mDNStrue: mDNSfalse;
6651 invokeKACallback = mDNSfalse;
6652 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6653 // This will leave m->SleepState set to SleepState_Transferring,
6654 // which is okay because with no outstanding resolves, or updates in flight,
6655 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6656
6657 // Setting this flag activates the SleepLimit which delays sleep by 5 seconds and
6658 // will allow the system to deregister any BTMM records.
6659 m->NextScheduledSPRetry = m->timenow + (5 * mDNSPlatformOneSecond);
6660 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6661 registeredCount++;
6662 }
6663 }
6664 #endif // APPLE_OSX_mDNSResponder
6665 else
6666 {
6667 #if APPLE_OSX_mDNSResponder
6668 // If on battery, do not attempt to offload to external sleep proxies
6669 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6670 {
6671 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6672 return;
6673 }
6674 #endif // APPLE_OSX_mDNSResponder
6675 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6676 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6677 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6678 else
6679 {
6680 int i;
6681 mDNSu32 scopeid;
6682 SendGoodbyes = mDNSfalse;
6683 intf->NextSPSAttempt = 0;
6684 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6685
6686 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6687 // Now we know for sure that we have to wait for registration to complete on this interface.
6688 if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6689 bit_set_opaque64(updateIntID, scopeid);
6690
6691 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6692 for (i=0; i<3; i++)
6693 {
6694 #if ForceAlerts
6695 if (intf->SPSAddr[i].type)
6696 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
6697 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6698 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
6699 #endif
6700 intf->SPSAddr[i].type = mDNSAddrType_None;
6701 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6702 intf->NetWakeResolve[i].ThisQInterval = -1;
6703 if (sps[i])
6704 {
6705 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6706 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6707 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6708 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6709
6710 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6711 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6712 registeredCount++;
6713 }
6714 }
6715 }
6716 }
6717 }
6718 }
6719
6720 // If we have at least one interface on which we are registering with an external sleep proxy,
6721 // initialize all the records appropriately.
6722 if (!mDNSOpaque64IsZero(&updateIntID))
6723 SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6724
6725 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6726 // the records to a sleep proxy.
6727 if (invokeKACallback)
6728 {
6729 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6730 DoKeepaliveCallbacks(m);
6731 }
6732
6733 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6734 // interfaces and also deregister unicast registrations.
6735 //
6736 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6737 // for both multicast and unicast.
6738 //
6739 // - If we skipped registrations on some interfaces, then we have already marked
6740 // them appropriately above. We don't need to send goodbyes for unicast as
6741 // we have registered with at least one sleep proxy.
6742 //
6743 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6744 //
6745 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6746 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6747 // at WakeOnlyServices first.
6748 if (SendGoodbyes)
6749 {
6750 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6751 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6752 }
6753 else if (skippedRegistrations)
6754 {
6755 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6756 SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6757 }
6758 else if (WakeOnlyService)
6759 {
6760 // If we saw WakeOnly service above, send the goodbyes now.
6761 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6762 SendResponses(m);
6763 }
6764 }
6765
6766 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6767 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6768 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6769 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6770 {
6771 AuthRecord *rr;
6772
6773 LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6774
6775 if (sleep && !m->SleepState) // Going to sleep
6776 {
6777 mDNS_Lock(m);
6778 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6779 if (m->SPSSocket)
6780 {
6781 mDNSu8 oldstate = m->SPSState;
6782 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6783 m->SPSState = 2;
6784 #ifndef SPC_DISABLED
6785 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6786 #else
6787 (void)oldstate;
6788 #endif
6789 mDNS_ReclaimLockAfterCallback();
6790 }
6791 #ifdef _LEGACY_NAT_TRAVERSAL_
6792 if (m->SSDPSocket)
6793 {
6794 mDNSPlatformUDPClose(m->SSDPSocket);
6795 m->SSDPSocket = mDNSNULL;
6796 }
6797 #endif
6798 m->SleepState = SleepState_Transferring;
6799 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6800 {
6801 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6802 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6803 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6804 }
6805 else
6806 {
6807 m->DelaySleep = 0;
6808 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6809 m->mDNSStats.Sleeps++;
6810 BeginSleepProcessing(m);
6811 }
6812
6813 #ifndef UNICAST_DISABLED
6814 SuspendLLQs(m);
6815 #endif
6816 #if APPLE_OSX_mDNSResponder
6817 RemoveAutoTunnel6Record(m);
6818 #endif
6819 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
6820 m->SleepState == SleepState_Transferring ? "Transferring" :
6821 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
6822 mDNS_Unlock(m);
6823 }
6824 else if (!sleep) // Waking up
6825 {
6826 mDNSu32 slot;
6827 CacheGroup *cg;
6828 CacheRecord *cr;
6829 NetworkInterfaceInfo *intf;
6830 mDNSs32 currtime, diff;
6831
6832 mDNS_Lock(m);
6833 // Reset SleepLimit back to 0 now that we're awake again.
6834 m->SleepLimit = 0;
6835
6836 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6837 if (m->SleepState != SleepState_Awake)
6838 {
6839 m->SleepState = SleepState_Awake;
6840 m->SleepSeqNum++;
6841 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6842 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6843 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6844 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6845 m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep);
6846 }
6847
6848 if (m->SPSState == 3)
6849 {
6850 m->SPSState = 0;
6851 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
6852 }
6853 m->mDNSStats.Wakes++;
6854 m->DelayConflictProcessing = MAX_CONFLICT_PROCESSING_DELAYS;
6855 // ... and the same for NextSPSAttempt
6856 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
6857
6858 // Restart unicast and multicast queries
6859 mDNSCoreRestartQueries(m);
6860
6861 // and reactivtate service registrations
6862 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
6863 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
6864
6865 // 2. Re-validate our cache records
6866 currtime = mDNSPlatformUTC();
6867
6868 diff = currtime - m->TimeSlept;
6869 FORALL_CACHERECORDS(slot, cg, cr)
6870 {
6871 // Temporary fix: For unicast cache records, look at how much time we slept.
6872 // Adjust the RecvTime by the amount of time we slept so that we age the
6873 // cache record appropriately. If it is expired already, purge. If there
6874 // is a network change that happens after the wakeup, we might purge the
6875 // cache anyways and this helps only in the case where there are no network
6876 // changes across sleep/wakeup transition.
6877 //
6878 // Note: If there is a network/DNS server change that already happened and
6879 // these cache entries are already refreshed and we are getting a delayed
6880 // wake up notification, we might adjust the TimeRcvd based on the time slept
6881 // now which can cause the cache to purge pre-maturely. As this is not a very
6882 // common case, this should happen rarely.
6883 if (!cr->resrec.InterfaceID)
6884 {
6885 if (diff > 0)
6886 {
6887 mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
6888 const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
6889
6890 // -if we have slept longer than the remaining TTL, purge and start fresh.
6891 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6892 // a sufficiently big value which could cause the value to go into the future
6893 // because of the signed comparison of time. For this to happen, we should have been
6894 // sleeping really long (~24 days). For now, we want to be conservative and flush even
6895 // if we have slept for more than two days.
6896
6897 if (diff >= remain || diff > (2 * 24 * 3600))
6898 {
6899 LogInfo("mDNSCoreMachineSleep: %s: Purging cache entry SleptTime %d, Remaining TTL %d",
6900 CRDisplayString(m, cr), diff, remain);
6901 mDNS_PurgeCacheResourceRecord(m, cr);
6902 continue;
6903 }
6904 cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
6905 if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
6906 {
6907 LogInfo("mDNSCoreMachineSleep: %s: Purging after adjusting the remaining TTL %d by %d seconds",
6908 CRDisplayString(m, cr), remain, diff);
6909 mDNS_PurgeCacheResourceRecord(m, cr);
6910 }
6911 else
6912 {
6913 LogInfo("mDNSCoreMachineSleep: %s: Adjusted the remain ttl %u by %d seconds", CRDisplayString(m, cr), remain, diff);
6914 }
6915 }
6916 }
6917 else
6918 {
6919 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
6920 }
6921 }
6922
6923 // 3. Retrigger probing and announcing for all our authoritative records
6924 for (rr = m->ResourceRecords; rr; rr=rr->next)
6925 {
6926 if (AuthRecord_uDNS(rr))
6927 {
6928 ActivateUnicastRegistration(m, rr);
6929 }
6930 else
6931 {
6932 mDNSCoreRestartRegistration(m, rr, -1);
6933 }
6934 }
6935
6936 // 4. Refresh NAT mappings
6937 // We don't want to have to assume that all hardware can necessarily keep accurate
6938 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
6939 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
6940 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
6941 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
6942 // than five seconds from now.
6943 LogInfo("mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
6944 RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
6945 mDNS_Unlock(m);
6946 }
6947 }
6948
6949 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
6950 {
6951 DNSQuestion *q;
6952 AuthRecord *rr;
6953 NetworkInterfaceInfo *intf;
6954
6955 mDNS_Lock(m);
6956
6957 if (m->DelaySleep) goto notready;
6958
6959 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
6960 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
6961
6962 m->NextScheduledSPRetry = now + 0x40000000UL;
6963
6964 // See if we might need to retransmit any lost Sleep Proxy Registrations
6965 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6966 if (intf->NextSPSAttempt >= 0)
6967 {
6968 if (now - intf->NextSPSAttemptTime >= 0)
6969 {
6970 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
6971 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
6972 SendSPSRegistration(m, intf, zeroID);
6973 // Don't need to "goto notready" here, because if we do still have record registrations
6974 // that have not been acknowledged yet, we'll catch that in the record list scan below.
6975 }
6976 else
6977 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6978 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6979 }
6980
6981 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
6982 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6983 {
6984 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
6985 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
6986 {
6987 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
6988 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
6989 goto spsnotready;
6990 }
6991 }
6992
6993 // Scan list of registered records
6994 for (rr = m->ResourceRecords; rr; rr = rr->next)
6995 if (!AuthRecord_uDNS(rr))
6996 if (!mDNSOpaque64IsZero(&rr->updateIntID))
6997 { 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; }
6998
6999 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7000 for (q = m->Questions; q; q = q->next)
7001 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
7002 {
7003 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7004 goto notready;
7005 }
7006
7007 // Scan list of registered records
7008 for (rr = m->ResourceRecords; rr; rr = rr->next)
7009 if (AuthRecord_uDNS(rr))
7010 {
7011 if (rr->state == regState_Refresh && rr->tcp)
7012 { 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; }
7013 #if APPLE_OSX_mDNSResponder
7014 if (!RecordReadyForSleep(rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
7015 #endif
7016 }
7017
7018 mDNS_Unlock(m);
7019 return mDNStrue;
7020
7021 spsnotready:
7022
7023 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7024 // and allow up to ten seconds more to complete wide-area deregistration instead
7025 if (now - m->SleepLimit >= 0)
7026 {
7027 LogMsg("Failed to register with SPS, now sending goodbyes");
7028
7029 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7030 if (intf->NetWakeBrowse.ThisQInterval >= 0)
7031 {
7032 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7033 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
7034 mDNS_DeactivateNetWake_internal(m, intf);
7035 }
7036
7037 for (rr = m->ResourceRecords; rr; rr = rr->next)
7038 if (!AuthRecord_uDNS(rr))
7039 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7040 {
7041 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));
7042 rr->updateIntID = zeroOpaque64;
7043 }
7044
7045 // We'd really like to allow up to ten seconds more here,
7046 // but if we don't respond to the sleep notification within 30 seconds
7047 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7048 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7049 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7050 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7051 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
7052
7053 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
7054 }
7055
7056 notready:
7057 mDNS_Unlock(m);
7058 return mDNSfalse;
7059 }
7060
7061 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
7062 {
7063 AuthRecord *ar;
7064
7065 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7066 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7067 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7068 // and if that happens we don't want to just give up and go back to sleep and never try again.
7069 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
7070
7071 NATTraversalInfo *nat;
7072 for (nat = m->NATTraversals; nat; nat=nat->next)
7073 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
7074 {
7075 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
7076 if (e - t > 0) e = t;
7077 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7078 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
7079 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
7080 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
7081 nat->retryInterval / mDNSPlatformOneSecond,
7082 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
7083 (t - now) / mDNSPlatformOneSecond);
7084 }
7085
7086 // This loop checks both the time we need to renew wide-area registrations,
7087 // and the time we need to renew Sleep Proxy registrations
7088 for (ar = m->ResourceRecords; ar; ar = ar->next)
7089 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
7090 {
7091 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
7092 if (e - t > 0) e = t;
7093 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7094 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
7095 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
7096 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
7097 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
7098 }
7099
7100 return(e - now);
7101 }
7102
7103 // ***************************************************************************
7104 #if COMPILER_LIKES_PRAGMA_MARK
7105 #pragma mark -
7106 #pragma mark - Packet Reception Functions
7107 #endif
7108
7109 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7110
7111 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
7112 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
7113 {
7114 mDNSu8 *responseptr = response->data;
7115 const mDNSu8 *const limit = response->data + sizeof(response->data);
7116 const mDNSu8 *ptr = query->data;
7117 AuthRecord *rr;
7118 mDNSu32 maxttl = 0x70000000;
7119 int i;
7120
7121 // Initialize the response fields so we can answer the questions
7122 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
7123
7124 // ***
7125 // *** 1. Write out the list of questions we are actually going to answer with this packet
7126 // ***
7127 if (LegacyQuery)
7128 {
7129 maxttl = kStaticCacheTTL;
7130 for (i=0; i<query->h.numQuestions; i++) // For each question...
7131 {
7132 DNSQuestion q;
7133 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
7134 if (!ptr) return(mDNSNULL);
7135
7136 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
7137 {
7138 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
7139 { // then put the question in the question section
7140 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
7141 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
7142 break; // break out of the ResponseRecords loop, and go on to the next question
7143 }
7144 }
7145 }
7146
7147 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
7148 }
7149
7150 // ***
7151 // *** 2. Write Answers
7152 // ***
7153 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7154 if (rr->NR_AnswerTo)
7155 {
7156 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
7157 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7158 if (p) responseptr = p;
7159 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
7160 }
7161
7162 // ***
7163 // *** 3. Write Additionals
7164 // ***
7165 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7166 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
7167 {
7168 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
7169 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7170 if (p) responseptr = p;
7171 else debugf("GenerateUnicastResponse: No more space for additionals");
7172 }
7173
7174 return(responseptr);
7175 }
7176
7177 // AuthRecord *our is our Resource Record
7178 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7179 // Returns 0 if there is no conflict
7180 // Returns +1 if there was a conflict and we won
7181 // Returns -1 if there was a conflict and we lost and have to rename
7182 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
7183 {
7184 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
7185 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
7186 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7187 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7188
7189 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
7190 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
7191 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
7192 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
7193
7194 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
7195 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
7196 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
7197 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
7198
7199 LogMsg("CompareRData ERROR: Invalid state");
7200 return(-1);
7201 }
7202
7203 // See if we have an authoritative record that's identical to this packet record,
7204 // whose canonical DependentOn record is the specified master record.
7205 // The DependentOn pointer is typically used for the TXT record of service registrations
7206 // It indicates that there is no inherent conflict detection for the TXT record
7207 // -- it depends on the SRV record to resolve name conflicts
7208 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7209 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7210 // If the record has no DependentOn, then just return that record's pointer
7211 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7212 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
7213 {
7214 const AuthRecord *r1;
7215 for (r1 = m->ResourceRecords; r1; r1=r1->next)
7216 {
7217 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
7218 {
7219 const AuthRecord *r2 = r1;
7220 while (r2->DependentOn) r2 = r2->DependentOn;
7221 if (r2 == master) return(mDNStrue);
7222 }
7223 }
7224 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
7225 {
7226 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
7227 {
7228 const AuthRecord *r2 = r1;
7229 while (r2->DependentOn) r2 = r2->DependentOn;
7230 if (r2 == master) return(mDNStrue);
7231 }
7232 }
7233 return(mDNSfalse);
7234 }
7235
7236 // Find the canonical RRSet pointer for this RR received in a packet.
7237 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7238 // pointers (if any) to make sure we return the canonical member of this name/type/class
7239 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7240 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
7241 {
7242 const AuthRecord *rr;
7243 for (rr = m->ResourceRecords; rr; rr=rr->next)
7244 {
7245 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7246 {
7247 while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
7248 return(rr);
7249 }
7250 }
7251 return(mDNSNULL);
7252 }
7253
7254 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7255 // as one of our records (our) but different rdata.
7256 // 1. If our record is not a type that's supposed to be unique, we don't care.
7257 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7258 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7259 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7260 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7261 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7262 // are members of the same RRSet, then this is not a conflict.
7263 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
7264 {
7265 // If not supposed to be unique, not a conflict
7266 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
7267
7268 // If a dependent record, not a conflict
7269 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
7270 else
7271 {
7272 // If the pktrr matches a member of ourset, not a conflict
7273 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
7274 const AuthRecord *pktset = FindRRSet(m, pktrr);
7275 if (pktset == ourset) return(mDNSfalse);
7276
7277 // For records we're proxying, where we don't know the full
7278 // relationship between the records, having any matching record
7279 // in our AuthRecords list is sufficient evidence of non-conflict
7280 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
7281 }
7282
7283 // Okay, this is a conflict
7284 return(mDNStrue);
7285 }
7286
7287 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7288 // the record list and/or question list.
7289 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7290 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7291 DNSQuestion *q, AuthRecord *our)
7292 {
7293 int i;
7294 const mDNSu8 *ptr = LocateAuthorities(query, end);
7295 mDNSBool FoundUpdate = mDNSfalse;
7296
7297 for (i = 0; i < query->h.numAuthorities; i++)
7298 {
7299 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7300 if (!ptr) break;
7301 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
7302 {
7303 FoundUpdate = mDNStrue;
7304 if (PacketRRConflict(m, our, &m->rec.r))
7305 {
7306 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
7307 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
7308 if (!result) result = CompareRData(our, &m->rec.r);
7309 if (result)
7310 {
7311 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
7312 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7313 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
7314 }
7315 // 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.
7316 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7317 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7318 if (result < 0)
7319 {
7320 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7321 our->ProbeCount = DefaultProbeCountForTypeUnique;
7322 our->AnnounceCount = InitialAnnounceCount;
7323 InitializeLastAPTime(m, our);
7324 goto exit;
7325 }
7326 }
7327 #if 0
7328 else
7329 {
7330 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7331 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
7332 }
7333 #endif
7334 }
7335 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7336 }
7337 if (!FoundUpdate)
7338 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
7339 exit:
7340 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7341 }
7342
7343 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
7344 {
7345 CacheGroup *cg = CacheGroupForRecord(m, pktrr);
7346 CacheRecord *rr;
7347 mDNSBool match;
7348 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7349 {
7350 if (!pktrr->InterfaceID)
7351 {
7352 mDNSu16 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
7353 mDNSu16 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7354 match = (id1 == id2);
7355 }
7356 else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
7357
7358 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
7359 }
7360 return(rr);
7361 }
7362 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
7363 {
7364 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7365 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
7366 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7367 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7368 }
7369
7370 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
7371 {
7372 if (m->CurrentRecord)
7373 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7374 m->CurrentRecord = thelist;
7375
7376 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7377 // clean up the keepalive record.
7378 while (m->CurrentRecord)
7379 {
7380 AuthRecord *const rr = m->CurrentRecord;
7381 if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7382 {
7383 if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7384 {
7385 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7386 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7387 DeregisterProxyRecord(m, rr);
7388 }
7389 }
7390 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7391 // new records could have been added to the end of the list as a result of that call.
7392 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7393 m->CurrentRecord = rr->next;
7394 }
7395 }
7396
7397 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7398 // to check our lists and discard any stale duplicates of this record we already have
7399 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7400 {
7401 if (m->CurrentRecord)
7402 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7403 m->CurrentRecord = thelist;
7404 while (m->CurrentRecord)
7405 {
7406 AuthRecord *const rr = m->CurrentRecord;
7407 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7408 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7409 {
7410 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7411 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7412 DeregisterProxyRecord(m, rr);
7413 }
7414 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7415 // new records could have been added to the end of the list as a result of that call.
7416 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7417 m->CurrentRecord = rr->next;
7418 }
7419 }
7420
7421 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7422 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7423 {
7424 if (m->CurrentRecord)
7425 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7426 m->CurrentRecord = thelist;
7427 while (m->CurrentRecord)
7428 {
7429 AuthRecord *const rr = m->CurrentRecord;
7430 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7431 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7432 {
7433 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7434 {
7435 // We don't do this here because we know that the host is waking up at this point, so we don't send
7436 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7437 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7438 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7439 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7440 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7441 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7442 #endif
7443 }
7444 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7445 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7446 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7447 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7448 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7449 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7450 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7451 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7452 }
7453 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7454 // new records could have been added to the end of the list as a result of that call.
7455 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7456 m->CurrentRecord = rr->next;
7457 }
7458 }
7459
7460 // ProcessQuery examines a received query to see if we have any answers to give
7461 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7462 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7463 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7464 {
7465 mDNSBool FromLocalSubnet = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7466 AuthRecord *ResponseRecords = mDNSNULL;
7467 AuthRecord **nrp = &ResponseRecords;
7468
7469 #if POOF_ENABLED
7470 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
7471 CacheRecord **eap = &ExpectedAnswers;
7472 #endif // POOF_ENABLED
7473
7474 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
7475 DNSQuestion **dqp = &DupQuestions;
7476 mDNSs32 delayresponse = 0;
7477 mDNSBool SendLegacyResponse = mDNSfalse;
7478 const mDNSu8 *ptr;
7479 mDNSu8 *responseptr = mDNSNULL;
7480 AuthRecord *rr;
7481 int i;
7482 CacheRecord *McastNSEC3Records = mDNSNULL;
7483
7484 // ***
7485 // *** 1. Look in Additional Section for an OPT record
7486 // ***
7487 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7488 if (ptr)
7489 {
7490 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7491 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7492 {
7493 const rdataOPT *opt;
7494 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7495 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7496 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7497 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7498 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7499 {
7500 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7501 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7502 }
7503 }
7504 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7505 }
7506
7507 //
7508 // Look in Authority Section for NSEC3 record
7509 //
7510
7511 mDNSParseNSEC3Records(m, query, end, InterfaceID, &McastNSEC3Records);
7512
7513 // ***
7514 // *** 2. Parse Question Section and mark potential answers
7515 // ***
7516 ptr = query->data;
7517 for (i=0; i<query->h.numQuestions; i++) // For each question...
7518 {
7519 mDNSBool QuestionNeedsMulticastResponse;
7520 int NumAnswersForThisQuestion = 0;
7521 AuthRecord *NSECAnswer = mDNSNULL;
7522 DNSQuestion pktq, *q;
7523 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7524 if (!ptr) goto exit;
7525
7526 pktq.AnonInfo = mDNSNULL;
7527 if (McastNSEC3Records)
7528 InitializeAnonInfoForQuestion(m, &McastNSEC3Records, &pktq);
7529 // The only queries that *need* a multicast response are:
7530 // * Queries sent via multicast
7531 // * from port 5353
7532 // * that don't have the kDNSQClass_UnicastResponse bit set
7533 // These queries need multicast responses because other clients will:
7534 // * suppress their own identical questions when they see these questions, and
7535 // * expire their cache records if they don't see the expected responses
7536 // For other queries, we may still choose to send the occasional multicast response anyway,
7537 // to keep our neighbours caches warm, and for ongoing conflict detection.
7538 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7539
7540 if (pktq.qclass & kDNSQClass_UnicastResponse)
7541 m->mDNSStats.UnicastBitInQueries++;
7542 else
7543 m->mDNSStats.NormalQueries++;
7544
7545 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7546 pktq.qclass &= ~kDNSQClass_UnicastResponse;
7547
7548 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7549 // can result in user callbacks which may change the record list and/or question list.
7550 // Also note: we just mark potential answer records here, without trying to build the
7551 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7552 // from that list while we're in the middle of trying to build it.
7553 if (m->CurrentRecord)
7554 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7555 m->CurrentRecord = m->ResourceRecords;
7556 while (m->CurrentRecord)
7557 {
7558 rr = m->CurrentRecord;
7559 m->CurrentRecord = rr->next;
7560 if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7561 {
7562 m->mDNSStats.MatchingAnswersForQueries++;
7563 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7564 {
7565 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7566 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7567 else if (ResourceRecordIsValidAnswer(rr))
7568 {
7569 NumAnswersForThisQuestion++;
7570 // As we have verified this question to be part of the same subset,
7571 // set the anonymous data which is needed below when walk the cache
7572 // records to see what answers we should be expecting. The cache records
7573 // may cache only the nsec3RR and not the anonymous data itself.
7574 if (pktq.AnonInfo && rr->resrec.AnonInfo)
7575 SetAnonData(&pktq, &rr->resrec, mDNStrue);
7576
7577 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7578 // unicast answer back to the source, because timeliness in answering probes is important.
7579
7580 // Notes:
7581 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7582 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7583 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7584 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7585 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7586 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7587 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7588 {
7589 // We only mark this question for sending if it is at least one second since the last time we multicast it
7590 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7591 // This is to guard against the case where someone blasts us with queries as fast as they can.
7592 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond ||
7593 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7594 rr->NR_AnswerTo = NR_AnswerMulticast;
7595 }
7596 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7597 }
7598 }
7599 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7600 {
7601 // If we don't have any answers for this question, but we do own another record with the same name,
7602 // then we'll want to mark it to generate an NSEC record on this interface
7603 if (!NSECAnswer) NSECAnswer = rr;
7604 }
7605 }
7606 }
7607
7608 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7609 {
7610 NumAnswersForThisQuestion++;
7611 NSECAnswer->SendNSECNow = InterfaceID;
7612 m->NextScheduledResponse = m->timenow;
7613 }
7614
7615 // If we couldn't answer this question, someone else might be able to,
7616 // so use random delay on response to reduce collisions
7617 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7618
7619 if (query->h.flags.b[0] & kDNSFlag0_TC)
7620 m->mDNSStats.KnownAnswerMultiplePkts++;
7621 // We only do the following accelerated cache expiration and duplicate question suppression processing
7622 // for non-truncated multicast queries with multicast responses.
7623 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7624 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7625 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7626 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7627 {
7628 #if POOF_ENABLED
7629 CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname);
7630 CacheRecord *cr;
7631
7632 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7633 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7634 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7635 if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7636 if (!cr->NextInKAList && eap != &cr->NextInKAList)
7637 {
7638 *eap = cr;
7639 eap = &cr->NextInKAList;
7640 }
7641 #endif // POOF_ENABLED
7642
7643 // Check if this question is the same as any of mine.
7644 // We only do this for non-truncated queries. Right now it would be too complicated to try
7645 // to keep track of duplicate suppression state between multiple packets, especially when we
7646 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7647 // For anonymous question, the duplicate suppressesion should happen if the
7648 // question belongs in the same group. As the group is expected to be
7649 // small, we don't do the optimization for now.
7650 if (!pktq.AnonInfo)
7651 {
7652 for (q = m->Questions; q; q=q->next)
7653 if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7654 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7655 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7656 if (q->qtype == pktq.qtype &&
7657 q->qclass == pktq.qclass &&
7658 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7659 { *dqp = q; dqp = &q->NextInDQList; }
7660 }
7661 }
7662 if (pktq.AnonInfo)
7663 {
7664 FreeAnonInfo(pktq.AnonInfo);
7665 }
7666 }
7667
7668 // ***
7669 // *** 3. Now we can safely build the list of marked answers
7670 // ***
7671 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
7672 if (rr->NR_AnswerTo) // If we marked the record...
7673 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
7674
7675 // ***
7676 // *** 4. Add additional records
7677 // ***
7678 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7679
7680 // ***
7681 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7682 // ***
7683 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
7684 {
7685 // Get the record...
7686 CacheRecord *ourcacherr;
7687 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7688 if (!ptr) goto exit;
7689 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7690 {
7691 // See if this Known-Answer suppresses any of our currently planned answers
7692 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7693 {
7694 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7695 {
7696 m->mDNSStats.KnownAnswerSuppressions++;
7697 rr->NR_AnswerTo = mDNSNULL;
7698 rr->NR_AdditionalTo = mDNSNULL;
7699 }
7700 }
7701
7702 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7703 for (rr=m->ResourceRecords; rr; rr=rr->next)
7704 {
7705 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7706 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7707 {
7708 if (srcaddr->type == mDNSAddrType_IPv4)
7709 {
7710 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7711 }
7712 else if (srcaddr->type == mDNSAddrType_IPv6)
7713 {
7714 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7715 }
7716 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7717 {
7718 m->mDNSStats.KnownAnswerSuppressions++;
7719 rr->ImmedAnswer = mDNSNULL;
7720 rr->ImmedUnicast = mDNSfalse;
7721 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7722 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7723 #endif
7724 }
7725 }
7726 }
7727
7728 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7729
7730 #if POOF_ENABLED
7731 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7732 // any records that are suppressed by the Known Answer list in this packet.
7733 eap = &ExpectedAnswers;
7734 while (*eap)
7735 {
7736 CacheRecord *cr = *eap;
7737 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7738 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7739 else eap = &cr->NextInKAList;
7740 }
7741 #endif // POOF_ENABLED
7742
7743 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7744 if (!ourcacherr)
7745 {
7746 dqp = &DupQuestions;
7747 while (*dqp)
7748 {
7749 DNSQuestion *q = *dqp;
7750 if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
7751 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7752 else dqp = &q->NextInDQList;
7753 }
7754 }
7755 }
7756 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7757 }
7758
7759 // ***
7760 // *** 6. Cancel any additionals that were added because of now-deleted records
7761 // ***
7762 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7763 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7764 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7765
7766 // ***
7767 // *** 7. Mark the send flags on the records we plan to send
7768 // ***
7769 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7770 {
7771 if (rr->NR_AnswerTo)
7772 {
7773 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
7774 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
7775
7776 // If it's been one TTL/4 since we multicast this, then send a multicast response
7777 // for conflict detection, etc.
7778 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4)
7779 {
7780 SendMulticastResponse = mDNStrue;
7781 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7782 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7783 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7784 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7785 {
7786 m->mDNSStats.UnicastDemotedToMulticast++;
7787 rr->NR_AnswerTo = NR_AnswerMulticast;
7788 }
7789 }
7790
7791 // If the client insists on a multicast response, then we'd better send one
7792 if (rr->NR_AnswerTo == NR_AnswerMulticast)
7793 {
7794 m->mDNSStats.MulticastResponses++;
7795 SendMulticastResponse = mDNStrue;
7796 }
7797 else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7798 {
7799 m->mDNSStats.UnicastResponses++;
7800 SendUnicastResponse = mDNStrue;
7801 }
7802 else if (rr->NR_AnswerTo)
7803 {
7804 SendLegacyResponse = mDNStrue;
7805 }
7806
7807 if (SendMulticastResponse || SendUnicastResponse)
7808 {
7809 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7810 rr->ImmedAnswerMarkTime = m->timenow;
7811 #endif
7812 m->NextScheduledResponse = m->timenow;
7813 // If we're already planning to send this on another interface, just send it on all interfaces
7814 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7815 rr->ImmedAnswer = mDNSInterfaceMark;
7816 else
7817 {
7818 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
7819 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7820 if (srcaddr->type == mDNSAddrType_IPv4)
7821 {
7822 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7823 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
7824 }
7825 else if (srcaddr->type == mDNSAddrType_IPv6)
7826 {
7827 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
7828 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
7829 }
7830 }
7831 }
7832 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7833 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7834 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7835 // else, for a simple unique record reply, we can reply immediately; no need for delay
7836 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
7837 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7838 }
7839 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
7840 {
7841 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7842 // If two clients on different interfaces do queries that invoke the same optional additional answer,
7843 // then the earlier client is out of luck
7844 rr->ImmedAdditional = InterfaceID;
7845 // No need to set m->NextScheduledResponse here
7846 // We'll send these additional records when we send them, or not, as the case may be
7847 }
7848 }
7849
7850 // ***
7851 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7852 // ***
7853 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
7854 {
7855 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7856 mDNSs32 oldss = m->SuppressSending;
7857 if (oldss && delayresponse)
7858 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
7859 #endif
7860 // Pick a random delay:
7861 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7862 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7863 // This is an integer value, with resolution determined by the platform clock rate.
7864 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7865 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7866 // The +49 before dividing is to ensure we round up, not down, to ensure that even
7867 // on platforms where the native clock rate is less than fifty ticks per second,
7868 // we still guarantee that the final calculated delay is at least one platform tick.
7869 // We want to make sure we don't ever allow the delay to be zero ticks,
7870 // because if that happens we'll fail the Bonjour Conformance Test.
7871 // Our final computed delay is 20-120ms for normal delayed replies,
7872 // or 400-500ms in the case of multi-packet known-answer lists.
7873 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
7874 if (m->SuppressSending == 0) m->SuppressSending = 1;
7875 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7876 if (oldss && delayresponse)
7877 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
7878 #endif
7879 }
7880
7881 // ***
7882 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7883 // ***
7884 if (SendLegacyResponse)
7885 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
7886
7887 exit:
7888 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7889
7890 // ***
7891 // *** 10. Finally, clear our link chains ready for use next time
7892 // ***
7893 while (ResponseRecords)
7894 {
7895 rr = ResponseRecords;
7896 ResponseRecords = rr->NextResponse;
7897 rr->NextResponse = mDNSNULL;
7898 rr->NR_AnswerTo = mDNSNULL;
7899 rr->NR_AdditionalTo = mDNSNULL;
7900 }
7901
7902 #if POOF_ENABLED
7903 while (ExpectedAnswers)
7904 {
7905 CacheRecord *cr = ExpectedAnswers;
7906 ExpectedAnswers = cr->NextInKAList;
7907 cr->NextInKAList = mDNSNULL;
7908
7909 // For non-truncated queries, we can definitively say that we should expect
7910 // to be seeing a response for any records still left in the ExpectedAnswers list
7911 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7912 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4)
7913 {
7914 cr->UnansweredQueries++;
7915 cr->LastUnansweredTime = m->timenow;
7916 if (cr->UnansweredQueries > 1)
7917 debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr));
7918 SetNextCacheCheckTimeForRecord(m, cr);
7919 }
7920
7921 // If we've seen multiple unanswered queries for this record,
7922 // then mark it to expire in five seconds if we don't get a response by then.
7923 if (cr->UnansweredQueries >= MaxUnansweredQueries)
7924 {
7925 // Only show debugging message if this record was not about to expire anyway
7926 if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond)
7927 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
7928 cr->UnansweredQueries, InterfaceID, (RRExpireTime(cr) - m->timenow + mDNSPlatformOneSecond-1) / mDNSPlatformOneSecond, CRDisplayString(m, cr));
7929
7930 m->mDNSStats.PoofCacheDeletions++;
7931 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
7932 }
7933 }
7934 #endif // POOF_ENABLED
7935
7936 while (DupQuestions)
7937 {
7938 DNSQuestion *q = DupQuestions;
7939 DupQuestions = q->NextInDQList;
7940 q->NextInDQList = mDNSNULL;
7941 RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
7942 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
7943 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
7944 }
7945
7946 if (McastNSEC3Records)
7947 {
7948 debugf("ProcessQuery: McastNSEC3Records not used");
7949 FreeNSECRecords(m, McastNSEC3Records);
7950 }
7951
7952 return(responseptr);
7953 }
7954
7955 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
7956 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
7957 const mDNSInterfaceID InterfaceID)
7958 {
7959 mDNSu8 *responseend = mDNSNULL;
7960 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
7961 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7962
7963 if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr)))
7964 {
7965 const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID";
7966 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7967 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
7968 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7969 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
7970 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
7971 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
7972 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data, reason);
7973 return;
7974 }
7975
7976 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7977 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
7978 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7979 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
7980 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
7981 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
7982 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
7983
7984 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
7985 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
7986
7987 if (responseend) // If responseend is non-null, that means we built a unicast response packet
7988 {
7989 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
7990 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
7991 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
7992 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
7993 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
7994 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
7995 }
7996 }
7997
7998 #if 0
7999 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
8000 {
8001 DNSServer *s;
8002 (void)m; // Unused
8003 (void)srcaddr; // Unused
8004 for (s = m->DNSServers; s; s = s->next)
8005 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
8006 return(mDNSfalse);
8007 }
8008 #endif
8009
8010 struct UDPSocket_struct
8011 {
8012 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8013 };
8014
8015 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
8016 {
8017 DNSQuestion *q;
8018 for (q = m->Questions; q; q=q->next)
8019 {
8020 if (!tcp && !q->LocalSocket) continue;
8021 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
8022 mDNSSameOpaque16(q->TargetQID, id) &&
8023 q->qtype == question->qtype &&
8024 q->qclass == question->qclass &&
8025 q->qnamehash == question->qnamehash &&
8026 SameDomainName(&q->qname, &question->qname))
8027 return(q);
8028 }
8029 return(mDNSNULL);
8030 }
8031
8032 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8033 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8034 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
8035 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
8036 {
8037 DNSQuestion *q;
8038 (void)id;
8039 (void)srcaddr;
8040
8041 for (q = m->Questions; q; q=q->next)
8042 {
8043 if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
8044 {
8045 if (!mDNSOpaque16IsZero(q->TargetQID))
8046 {
8047 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
8048
8049 if (mDNSSameOpaque16(q->TargetQID, id))
8050 {
8051 mDNSIPPort srcp;
8052 if (!tcp)
8053 {
8054 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
8055 }
8056 else
8057 {
8058 srcp = q->tcpSrcPort;
8059 }
8060 if (mDNSSameIPPort(srcp, port)) return(q);
8061
8062 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8063 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8064 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8065 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
8066 q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
8067 return(mDNSNULL);
8068 }
8069 }
8070 else
8071 {
8072 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
8073 return(q);
8074 }
8075 }
8076 }
8077 return(mDNSNULL);
8078 }
8079
8080 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8081 // Currently this applies only to rdata types containing more than one domainname,
8082 // or types where the domainname is not the last item in the structure.
8083 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
8084 {
8085 switch (rr->rrtype)
8086 {
8087 case kDNSType_SOA: return sizeof(rdataSOA);
8088 case kDNSType_RP: return sizeof(rdataRP);
8089 case kDNSType_PX: return sizeof(rdataPX);
8090 default: return rr->rdlength;
8091 }
8092 }
8093
8094 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
8095 {
8096 CacheRecord *rr = mDNSNULL;
8097 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
8098
8099 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
8100
8101 //if (RDLength > InlineCacheRDSize)
8102 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8103
8104 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
8105 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
8106 if (!rr) NoCacheAnswer(m, &m->rec.r);
8107 else
8108 {
8109 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
8110 *rr = m->rec.r; // Block copy the CacheRecord object
8111 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
8112 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
8113
8114 // We need to add the anonymous info before we call CacheRecordAdd so that
8115 // if it finds a matching question with this record, it bumps up the counters like
8116 // CurrentAnswers etc. Otherwise, when a cache entry gets removed, CacheRecordRmv
8117 // will complain.
8118 if (m->rec.r.resrec.AnonInfo)
8119 {
8120 rr->resrec.AnonInfo = m->rec.r.resrec.AnonInfo;
8121 m->rec.r.resrec.AnonInfo = mDNSNULL;
8122 }
8123 rr->DelayDelivery = delay;
8124
8125 // If this is an oversized record with external storage allocated, copy rdata to external storage
8126 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
8127 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8128 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
8129 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8130 if (RDLength > InlineCacheRDSize)
8131 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
8132
8133 rr->next = mDNSNULL; // Clear 'next' pointer
8134 rr->nsec = mDNSNULL;
8135 rr->soa = mDNSNULL;
8136
8137 if (sourceAddress)
8138 rr->sourceAddress = *sourceAddress;
8139
8140 if (!rr->resrec.InterfaceID)
8141 {
8142 m->rrcache_totalused_unicast += rr->resrec.rdlength;
8143 if (DNSSECRecordType(rr->resrec.rrtype))
8144 BumpDNSSECStats(m, kStatsActionIncrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
8145 }
8146
8147 if (Add)
8148 {
8149 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
8150 cg->rrcache_tail = &(rr->next); // Advance tail pointer
8151 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8152 }
8153 else
8154 {
8155 // Can't use the "cg->name" if we are not adding to the cache as the
8156 // CacheGroup may be released anytime if it is empty
8157 domainname *name = mDNSPlatformMemAllocate(DomainNameLength(cg->name));
8158 if (name)
8159 {
8160 AssignDomainName(name, cg->name);
8161 rr->resrec.name = name;
8162 }
8163 else
8164 {
8165 ReleaseCacheRecord(m, rr);
8166 NoCacheAnswer(m, &m->rec.r);
8167 rr = mDNSNULL;
8168 }
8169 }
8170 }
8171 return(rr);
8172 }
8173
8174 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
8175 {
8176 rr->TimeRcvd = m->timenow;
8177 rr->resrec.rroriginalttl = ttl;
8178 rr->UnansweredQueries = 0;
8179 SetNextCacheCheckTimeForRecord(m, rr);
8180 }
8181
8182 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
8183 {
8184 CacheRecord *rr;
8185 CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname);
8186 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8187 if (rr->CRActiveQuestion == q)
8188 {
8189 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8190 RefreshCacheRecord(m, rr, lease);
8191 }
8192 }
8193
8194 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
8195 {
8196 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8197 else if (LLQType == uDNS_LLQ_Events)
8198 {
8199 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8200 if (ttl == 0xFFFFFFFF) ttl = 0;
8201 else ttl = kLLQ_DefLease;
8202 }
8203 else // else not LLQ (standard uDNS response)
8204 {
8205 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8206 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8207 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8208
8209 ttl = RRAdjustTTL(ttl);
8210
8211 // For mDNS, TTL zero means "delete this record"
8212 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8213 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8214 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8215 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8216 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8217 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8218 // (with the current code) result in the server having even less than three seconds to respond
8219 // before we deleted the record and reported a "remove" event to any active questions.
8220 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8221 // then things really break (e.g. we end up making a negative cache entry).
8222 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8223 if (ttl < 15) ttl = 15;
8224 }
8225
8226 return ttl;
8227 }
8228
8229 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8230 // in m->rec.
8231 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist, DNSQuestion *q, mDNSBool *nseclist)
8232 {
8233 CacheRecord *const newcr = &m->rec.r;
8234 ResourceRecord *rr = &newcr->resrec;
8235 const CacheRecord *cr;
8236
8237 *nseclist = mDNSfalse;
8238 for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8239 {
8240 domainname *target = GetRRDomainNameTarget(&cr->resrec);
8241 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8242 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8243 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8244 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8245 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8246
8247 if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8248 {
8249 LogInfo("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8250 return (mDNStrue);
8251 }
8252 }
8253
8254 // Either the question requires validation or we are validating a response with DNSSEC in which case
8255 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8256 // we receive NSECs for our query which does not match the qname and we need to cache in that case
8257 // too. nseclist is set if they have to be cached as part of the negative cache record.
8258 if (q && DNSSECQuestion(q))
8259 {
8260 mDNSBool same = SameDomainName(&q->qname, rr->name);
8261 if (same && (q->qtype == rr->rrtype || rr->rrtype == kDNSType_CNAME))
8262 {
8263 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q->qtype),
8264 CRDisplayString(m, newcr));
8265 return mDNStrue;
8266 }
8267 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
8268 // "nseclist" is set
8269 if (rr->rrtype == kDNSType_RRSIG)
8270 {
8271 RDataBody2 *const rdb = (RDataBody2 *)newcr->smallrdatastorage.data;
8272 rdataRRSig *rrsig = &rdb->rrsig;
8273 mDNSu16 typeCovered = swap16(rrsig->typeCovered);
8274
8275 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8276 // would match the qtype and they are cached normally as they are not used to prove the
8277 // non-existence of any name. In that case, it is like any other normal dnssec validation
8278 // and hence nseclist should not be set.
8279
8280 if (same && ((typeCovered == q->qtype) || (typeCovered == kDNSType_CNAME)))
8281 {
8282 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m, newcr),
8283 DNSTypeName(q->qtype));
8284 return mDNStrue;
8285 }
8286 else if (typeCovered == kDNSType_NSEC || typeCovered == kDNSType_NSEC3)
8287 {
8288 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m, newcr), DNSTypeName(typeCovered));
8289 *nseclist = mDNStrue;
8290 return mDNStrue;
8291 }
8292 else if (typeCovered == kDNSType_SOA)
8293 {
8294 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m, newcr));
8295 *nseclist = mDNStrue;
8296 return mDNStrue;
8297 }
8298 else return mDNSfalse;
8299 }
8300 if (rr->rrtype == kDNSType_NSEC)
8301 {
8302 if (!UNICAST_NSEC(rr))
8303 {
8304 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m, newcr));
8305 return mDNSfalse;
8306 }
8307 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m, newcr));
8308 *nseclist = mDNStrue;
8309 return mDNStrue;
8310 }
8311 if (rr->rrtype == kDNSType_SOA)
8312 {
8313 LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m, newcr));
8314 *nseclist = mDNStrue;
8315 return mDNStrue;
8316 }
8317 else if (rr->rrtype == kDNSType_NSEC3)
8318 {
8319 LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m, newcr));
8320 *nseclist = mDNStrue;
8321 return mDNStrue;
8322 }
8323 }
8324 return mDNSfalse;
8325 }
8326
8327 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords)
8328 {
8329 CacheRecord *rp, *next;
8330
8331 for (rp = NSECRecords; rp; rp = next)
8332 {
8333 next = rp->next;
8334 ReleaseCacheRecord(m, rp);
8335 }
8336 }
8337
8338 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8339 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8340 mDNSlocal void mDNSCoreReceiveNoDNSSECAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8341 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID)
8342 {
8343 int i;
8344 const mDNSu8 *ptr = response->data;
8345
8346 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8347 {
8348 DNSQuestion pktq;
8349 DNSQuestion *qptr = mDNSNULL;
8350 ptr = getQuestion(response, ptr, end, InterfaceID, &pktq);
8351 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &pktq, !dstaddr)) &&
8352 qptr->ValidatingResponse)
8353 {
8354 DNSQuestion *next, *q;
8355
8356 if (qptr->DuplicateOf)
8357 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr->qname.c, DNSTypeName(qptr->qtype));
8358
8359 // Be careful to call the callback for duplicate questions first and then the original
8360 // question. If we called the callback on the original question, it could stop and
8361 // a duplicate question would become the original question.
8362 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
8363 for (q = qptr->next ; q && q != m->NewQuestions; q = next)
8364 {
8365 next = q->next;
8366 if (q->DuplicateOf == qptr)
8367 {
8368 if (q->ValidatingResponse)
8369 LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q->qname.c, DNSTypeName(q->qtype));
8370 else
8371 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q->qname.c, DNSTypeName(q->qtype));
8372 if (q->QuestionCallback)
8373 q->QuestionCallback(m, q, mDNSNULL, QC_nodnssec);
8374 }
8375 }
8376 if (qptr->QuestionCallback)
8377 qptr->QuestionCallback(m, qptr, mDNSNULL, QC_nodnssec);
8378 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8379 }
8380 }
8381 }
8382
8383 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8384 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, uDNS_LLQType LLQType, mDNSu8 rcode, CacheRecord *NSECRecords)
8385 {
8386 int i;
8387 const mDNSu8 *ptr = response->data;
8388 CacheRecord *SOARecord = mDNSNULL;
8389
8390 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8391 {
8392 DNSQuestion q;
8393 DNSQuestion *qptr = mDNSNULL;
8394 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8395 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
8396 {
8397 CacheRecord *rr, *neg = mDNSNULL;
8398 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
8399 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8400 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
8401 {
8402 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8403 if (RRExpireTime(rr) - m->timenow > 0) break;
8404 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8405 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
8406 }
8407 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8408 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8409 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8410 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8411 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8412 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8413 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8414 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8415 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8416 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8417 //
8418 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8419 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8420 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8421 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8422 // do the appropriate thing. This negative response is also needed for appending new search domains.
8423 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8424 {
8425 if (!rr)
8426 {
8427 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8428 m->CurrentQuestion = qptr;
8429 // We are not creating a cache record in this case, we need to pass back
8430 // the error we got so that the proxy code can return the right one to
8431 // the application
8432 if (qptr->ProxyQuestion)
8433 qptr->responseFlags = response->h.flags;
8434 GenerateNegativeResponse(m, mDNSInterface_Any, QC_forceresponse);
8435 m->CurrentQuestion = mDNSNULL;
8436 }
8437 else
8438 {
8439 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8440 }
8441 }
8442 else
8443 {
8444 if (!rr)
8445 {
8446 // We start off assuming a negative caching TTL of 60 seconds
8447 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8448 mDNSu32 negttl = 60;
8449 int repeat = 0;
8450 const domainname *name = &q.qname;
8451 mDNSu32 hash = q.qnamehash;
8452
8453 // Special case for our special Microsoft Active Directory "local SOA" check.
8454 // Some cheap home gateways don't include an SOA record in the authority section when
8455 // they send negative responses, so we don't know how long to cache the negative result.
8456 // Because we don't want to keep hitting the root name servers with our query to find
8457 // if we're on a network using Microsoft Active Directory using "local" as a private
8458 // internal top-level domain, we make sure to cache the negative result for at least one day.
8459 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8460
8461 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8462 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8463 {
8464 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8465 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8466 {
8467 CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec);
8468 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8469 mDNSu32 ttl_s = soa->min;
8470 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8471 // for the SOA record for ".", where the record is reported as non-cacheable
8472 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8473 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8474 ttl_s = m->rec.r.resrec.rroriginalttl;
8475 if (negttl < ttl_s) negttl = ttl_s;
8476
8477 // Create the SOA record as we may have to return this to the questions
8478 // that we are acting as a proxy for currently or in the future.
8479 SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL);
8480
8481 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8482 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8483 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8484 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8485 //
8486 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8487 // along with the negative cache record. For simplicity, we don't create the additional records.
8488 if (!qptr->ProxyQuestion && q.qtype == kDNSType_SOA)
8489 {
8490 int qcount = CountLabels(&q.qname);
8491 int scount = CountLabels(m->rec.r.resrec.name);
8492 if (qcount - 1 > scount)
8493 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8494 repeat = qcount - 1 - scount;
8495 }
8496 }
8497 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8498 }
8499
8500 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8501 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8502 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8503 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8504 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8505 // so that we back off our polling rate and don't keep hitting the server continually.
8506 if (neg)
8507 {
8508 if (negttl < neg->resrec.rroriginalttl * 2)
8509 negttl = neg->resrec.rroriginalttl * 2;
8510 if (negttl > 3600)
8511 negttl = 3600;
8512 }
8513
8514 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
8515
8516 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8517 if (neg)
8518 {
8519 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8520 RefreshCacheRecord(m, neg, negttl);
8521 // When we created the cache for the first time and answered the question, the question's
8522 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8523 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8524 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8525 // we should reset its question interval here to MaxQuestionInterval.
8526 ResetQuestionState(m, qptr);
8527 if (DNSSECQuestion(qptr))
8528 neg->CRDNSSECQuestion = 1;
8529 // Update the NSEC records again.
8530 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8531 if (NSECRecords)
8532 {
8533 if (!AddNSECSForCacheRecord(m, NSECRecords, neg, rcode))
8534 {
8535 // We might just have an SOA record for zones that are not signed and hence don't log
8536 // this as an error
8537 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s during refresh", CRDisplayString(m, neg));
8538 FreeNSECRecords(m, NSECRecords);
8539 neg->CRDNSSECQuestion = 0;
8540 }
8541 NSECRecords = mDNSNULL;
8542 }
8543 if (SOARecord)
8544 {
8545 if (neg->soa)
8546 ReleaseCacheRecord(m, neg->soa);
8547 neg->soa = SOARecord;
8548 SOARecord = mDNSNULL;
8549 }
8550 }
8551 else while (1)
8552 {
8553 CacheRecord *negcr;
8554 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8555 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8556 m->rec.r.responseFlags = response->h.flags;
8557 // We create SOA records above which might create new cache groups. Earlier
8558 // in the function we looked up the cache group for the name and it could have
8559 // been NULL. If we pass NULL cg to new cache entries that we create below,
8560 // it will create additional cache groups for the same name. To avoid that,
8561 // look up the cache group again to re-initialize cg again.
8562 cg = CacheGroupForName(m, hash, name);
8563 if (NSECRecords && DNSSECQuestion(qptr))
8564 {
8565 // Create the cache entry with delay and then add the NSEC records
8566 // to it and add it immediately.
8567 negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8568 if (negcr)
8569 {
8570 negcr->CRDNSSECQuestion = 0;
8571 if (!AddNSECSForCacheRecord(m, NSECRecords, negcr, rcode))
8572 {
8573 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s",
8574 CRDisplayString(m, negcr));
8575 FreeNSECRecords(m, NSECRecords);
8576 }
8577 else
8578 {
8579 negcr->CRDNSSECQuestion = 1;
8580 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for %s", CRDisplayString(m, negcr));
8581 }
8582 NSECRecords = mDNSNULL;
8583 negcr->DelayDelivery = 0;
8584 CacheRecordDeferredAdd(m, negcr);
8585 }
8586 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8587 break;
8588 }
8589 else
8590 {
8591 // Need to add with a delay so that we can tag the SOA record
8592 negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8593 if (negcr)
8594 {
8595 negcr->CRDNSSECQuestion = 0;
8596 if (DNSSECQuestion(qptr))
8597 negcr->CRDNSSECQuestion = 1;
8598 negcr->DelayDelivery = 0;
8599
8600 if (SOARecord)
8601 {
8602 if (negcr->soa)
8603 ReleaseCacheRecord(m, negcr->soa);
8604 negcr->soa = SOARecord;
8605 SOARecord = mDNSNULL;
8606 }
8607 CacheRecordDeferredAdd(m, negcr);
8608 }
8609 }
8610 m->rec.r.responseFlags = zeroID;
8611 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8612 if (!repeat) break;
8613 repeat--;
8614 name = (const domainname *)(name->c + 1 + name->c[0]);
8615 hash = DomainNameHashValue(name);
8616 }
8617 }
8618 }
8619 }
8620 }
8621 if (NSECRecords) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used"); FreeNSECRecords(m, NSECRecords); }
8622 if (SOARecord) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: SOARecord not used"); ReleaseCacheRecord(m, SOARecord); }
8623 }
8624
8625 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8626 {
8627 AuthRecord *rrPtr = mDNSNULL;
8628 LogSPS("Stored Proxy records :");
8629 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8630 {
8631 LogSPS("%s", ARDisplayString(m, rrPtr));
8632 }
8633 }
8634
8635 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8636 {
8637 AuthRecord *rrPtr = mDNSNULL;
8638
8639 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8640 {
8641 if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8642 {
8643 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8644 return mDNStrue;
8645 }
8646 }
8647 mDNSCorePrintStoredProxyRecords(m);
8648 return mDNSfalse;
8649 }
8650
8651 mDNSlocal CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8652 const mDNSu32 slot, CacheGroup *cg, DNSQuestion *unicastQuestion, CacheRecord ***cfp, CacheRecord **NSECCachePtr,
8653 mDNSInterfaceID InterfaceID)
8654 {
8655 CacheRecord *rr;
8656 CacheRecord **cflocal = *cfp;
8657
8658 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8659 {
8660 mDNSBool match;
8661 // Resource record received via unicast, the resGroupID should match ?
8662 if (!InterfaceID)
8663 {
8664 mDNSu16 id1 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
8665 mDNSu16 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8666 match = (id1 == id2);
8667 }
8668 else
8669 match = (rr->resrec.InterfaceID == InterfaceID);
8670 // If we found this exact resource record, refresh its TTL
8671 if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
8672 {
8673 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8674 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8675 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8676
8677 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8678 {
8679 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8680 if (rr->NextInCFList == mDNSNULL && *cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
8681 {
8682 *cflocal = rr;
8683 cflocal = &rr->NextInCFList;
8684 *cflocal = (CacheRecord*)1;
8685 *cfp = &rr->NextInCFList;
8686 }
8687
8688 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8689 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8690 {
8691 DNSQuestion *q;
8692 for (q = m->Questions; q; q=q->next)
8693 {
8694 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
8695 q->UniqueAnswers++;
8696 }
8697 rr->resrec.RecordType = m->rec.r.resrec.RecordType;
8698 }
8699 }
8700
8701 if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
8702 {
8703 // If the rdata of the packet record differs in name capitalization from the record in our cache
8704 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8705 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8706 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8707 rr->resrec.rroriginalttl = 0;
8708 rr->TimeRcvd = m->timenow;
8709 rr->UnansweredQueries = MaxUnansweredQueries;
8710 SetNextCacheCheckTimeForRecord(m, rr);
8711 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: %s", CRDisplayString(m, rr));
8712 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: %s", CRDisplayString(m, &m->rec.r));
8713 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8714 NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8715 // DO NOT break out here -- we want to continue as if we never found it
8716 }
8717 else if (!IdenticalAnonInfo(m->rec.r.resrec.AnonInfo, rr->resrec.AnonInfo))
8718 {
8719 // If the NSEC3 record changed, a few possibilities
8720 //
8721 // 1) the peer reinitialized e.g., after network change and still part of the
8722 // same set.
8723 // 2) the peer went to a different set but we did not see the goodbyes. If we just
8724 // update the nsec3 record, it would be incorrect. Flush the cache so that we
8725 // can deliver a RMV followed by ADD.
8726 // 3) if the peer is ourselves and we see the goodbye when moving to a different set
8727 // and so we flush the cache and create a new cache record with the new set information.
8728 // Now we move back to the original set. In this case, we can't just update the
8729 // NSEC3 record alone. We need to flush so that we can deliver an RMV followed by ADD
8730 // when we create the new cache entry.
8731 //
8732 // Note: For case (1), we could avoid flushing the cache but we can't tell the difference
8733 // from the other cases.
8734 rr->resrec.rroriginalttl = 0;
8735 rr->TimeRcvd = m->timenow;
8736 rr->UnansweredQueries = MaxUnansweredQueries;
8737 SetNextCacheCheckTimeForRecord(m, rr);
8738 LogInfo("mDNSCoreReceiveCacheCheck: AnonInfo changed for %s", CRDisplayString(m, rr));
8739 // DO NOT break out here -- we want to continue as if we never found it. When we return
8740 // from this function, we will create a new cache entry with the new NSEC3 record
8741 }
8742 else if (m->rec.r.resrec.rroriginalttl > 0)
8743 {
8744 DNSQuestion *q;
8745
8746 m->mDNSStats.CacheRefreshed++;
8747
8748 if (rr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, rr));
8749 RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
8750 rr->responseFlags = response->h.flags;
8751
8752 // If we may have NSEC records returned with the answer (which we don't know yet as it
8753 // has not been processed), we need to cache them along with the first cache
8754 // record in the list that answers the question so that it can be used for validation
8755 // later. The "type" check below is to make sure that we cache on the cache record
8756 // that would answer the question. It is possible that we might cache additional things
8757 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8758 // the record that answers the question.
8759 if (response->h.numAnswers && unicastQuestion && unicastQuestion->qtype == rr->resrec.rrtype
8760 && !(*NSECCachePtr))
8761 {
8762 LogInfo("mDNSCoreReceiveCacheCheck: rescuing RR %s", CRDisplayString(m, rr));
8763 *NSECCachePtr = rr;
8764 }
8765 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8766 // polling the network once we get a valid response back. For the first time when a new
8767 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8768 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8769 // configuration changed, without flushing the cache, we reset the question interval here.
8770 // Currently, we do this for for both multicast and unicast questions as long as the record
8771 // type is unique. For unicast, resource record is always unique and for multicast it is
8772 // true for records like A etc. but not for PTR.
8773 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8774 {
8775 for (q = m->Questions; q; q=q->next)
8776 {
8777 if (!q->DuplicateOf && !q->LongLived &&
8778 ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
8779 {
8780 ResetQuestionState(m, q);
8781 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8782 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8783 }
8784 }
8785 }
8786 break;
8787 }
8788 else
8789 {
8790 // If the packet TTL is zero, that means we're deleting this record.
8791 // To give other hosts on the network a chance to protest, we push the deletion
8792 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8793 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8794 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8795 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8796 // If the record is already going to expire in less than one second anyway, we leave it alone --
8797 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8798 debugf("DE for %s", CRDisplayString(m, rr));
8799 if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
8800 {
8801 rr->resrec.rroriginalttl = 1;
8802 rr->TimeRcvd = m->timenow;
8803 rr->UnansweredQueries = MaxUnansweredQueries;
8804 SetNextCacheCheckTimeForRecord(m, rr);
8805 }
8806 break;
8807 }
8808 }
8809 }
8810 return rr;
8811 }
8812
8813 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8814 const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records)
8815 {
8816 const mDNSu8 *ptr;
8817 CacheRecord *rr;
8818 int i;
8819
8820 if (!response->h.numAuthorities)
8821 return;
8822 ptr = LocateAuthorities(response, end);
8823 if (!ptr)
8824 {
8825 LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8826 return;
8827 }
8828 for (i = 0; i < response->h.numAuthorities && ptr && ptr < end; i++)
8829 {
8830 CacheGroup *cg;
8831
8832 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8833 if (!ptr || m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative || m->rec.r.resrec.rrtype != kDNSType_NSEC3)
8834 {
8835 debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr, CRDisplayString(m, &m->rec.r));
8836 m->rec.r.resrec.RecordType = 0;
8837 continue;
8838 }
8839 cg = CacheGroupForRecord(m, &m->rec.r.resrec);
8840 // Create the cache entry but don't add it to the cache it. We need
8841 // to cache this along with the main cache record.
8842 rr = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cg, 0, mDNSfalse, mDNSNULL);
8843 if (rr)
8844 {
8845 debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m, rr));
8846 *NSEC3Records = rr;
8847 NSEC3Records = &rr->next;
8848 }
8849 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8850 }
8851 }
8852
8853 mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
8854 {
8855 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8856 if (m->rec.r.resrec.AnonInfo)
8857 {
8858 FreeAnonInfo(m->rec.r.resrec.AnonInfo);
8859 m->rec.r.resrec.AnonInfo = mDNSNULL;
8860 }
8861 }
8862
8863 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8864 // the record list and/or question list.
8865 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8866 // InterfaceID non-NULL tells us the interface this multicast response was received on
8867 // InterfaceID NULL tells us this was a unicast response
8868 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8869 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
8870 const DNSMessage *const response, const mDNSu8 *end,
8871 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8872 const mDNSInterfaceID InterfaceID)
8873 {
8874 int i;
8875 mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
8876 mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8877 DNSQuestion *llqMatch = mDNSNULL;
8878 DNSQuestion *unicastQuestion = mDNSNULL;
8879 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
8880
8881 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8882 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8883 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8884 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
8885 CacheRecord **cfp = &CacheFlushRecords;
8886 CacheRecord *NSECRecords = mDNSNULL;
8887 CacheRecord *NSECCachePtr = mDNSNULL;
8888 CacheRecord **nsecp = &NSECRecords;
8889 CacheRecord *McastNSEC3Records = mDNSNULL;
8890 mDNSBool nseclist;
8891 mDNSu8 rcode = '\0';
8892 mDNSBool rrsigsCreated = mDNSfalse;
8893 mDNSBool DNSSECQuestion = mDNSfalse;
8894 NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
8895 mDNSBool recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
8896
8897 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8898 // to guard against spoof responses, then the only credible protection against that is cryptographic
8899 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8900 int firstauthority = response->h.numAnswers;
8901 int firstadditional = firstauthority + response->h.numAuthorities;
8902 int totalrecords = firstadditional + response->h.numAdditionals;
8903 const mDNSu8 *ptr = response->data;
8904 DNSServer *uDNSServer = mDNSNULL;
8905
8906 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8907 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8908 srcaddr, dstaddr, InterfaceID,
8909 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
8910 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
8911 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
8912 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
8913
8914 #if AWD_METRICS
8915 if (mDNSSameIPPort(srcport, UnicastDNSPort))
8916 {
8917 MetricsUpdateDNSResponseSize((mDNSu32)(end - (mDNSu8 *)response));
8918 }
8919 #endif
8920
8921 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8922 // When a DNS client receives a reply with TC
8923 // set, it should ignore that response, and query again, using a
8924 // mechanism, such as a TCP connection, that will permit larger replies.
8925 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8926 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8927 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8928 // <rdar://problem/6690034> Can't bind to Active Directory
8929 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8930 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8931 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
8932 // and not even do the TCP query.
8933 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
8934 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
8935 // either the authority section or additional section, then that implies that truncation occurred beyond the answer
8936 // section, and the answer section is therefore assumed to be complete.
8937 //
8938 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
8939 // When a response is so long that truncation is required, the truncation
8940 // should start at the end of the response and work forward in the
8941 // datagram. Thus if there is any data for the authority section, the
8942 // answer section is guaranteed to be unique.
8943 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) &&
8944 ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) return;
8945
8946 if (LLQType == uDNS_LLQ_Ignore) return;
8947
8948 // 1. We ignore questions (if any) in mDNS response packets
8949 // 2. If this is an LLQ response, we handle it much the same
8950 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
8951 if (ResponseMCast || LLQType == uDNS_LLQ_Events)
8952 ptr = LocateAnswers(response, end);
8953 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
8954 // in this response packet are immediately deemed to be invalid.
8955 else
8956 {
8957 mDNSBool failure, returnEarly;
8958 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
8959 failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
8960 returnEarly = mDNSfalse;
8961 // We could possibly combine this with the similar loop at the end of this function --
8962 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
8963 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
8964 // which it was received (or refreshed), and then at the end if we find any cache records which
8965 // answer questions in this packet's question section, but which aren't tagged with this packet's
8966 // packet number, then we deduce they are old and delete them
8967 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8968 {
8969 DNSQuestion q, *qptr = mDNSNULL;
8970 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8971 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
8972 {
8973 if (!failure)
8974 {
8975 CacheRecord *rr;
8976 // Remember the unicast question that we found, which we use to make caching
8977 // decisions later on in this function
8978 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
8979 if (!mDNSOpaque16IsZero(response->h.id))
8980 {
8981 unicastQuestion = qptr;
8982 if (qptr->qDNSServer && DNSSECQuestion(qptr))
8983 {
8984 LogInfo("mDNSCoreReceiveResponse: Setting aware for %##s (%s) on %#a", qptr->qname.c,
8985 DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr);
8986 qptr->qDNSServer->DNSSECAware = mDNStrue;
8987 qptr->qDNSServer->req_DO = mDNStrue;
8988 }
8989 if (qptr->ValidatingResponse)
8990 DNSSECQuestion = mDNStrue;
8991 }
8992 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8993 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
8994 {
8995 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
8996 rr->resrec.InterfaceID, CRDisplayString(m, rr));
8997 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
8998 rr->TimeRcvd = m->timenow - TicksTTL(rr) - 1;
8999 rr->UnansweredQueries = MaxUnansweredQueries;
9000 rr->CRDNSSECQuestion = 0;
9001 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9002 {
9003 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for record %s, question %##s (%s)", CRDisplayString(m, rr),
9004 unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
9005 rr->CRDNSSECQuestion = 1;
9006 }
9007 }
9008 }
9009 else
9010 {
9011 if (qptr)
9012 {
9013 // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
9014 // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
9015 // req_DO to false here, the next retransmission for this question will turn off validation
9016 // and hence retransmit without the EDNS0/DOK option.
9017 if (DNSSECOptionalQuestion(qptr) && qptr->qDNSServer && !qptr->qDNSServer->DNSSECAware)
9018 {
9019 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query %##s (%s), clear DO flag",
9020 qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
9021 qptr->qDNSServer->req_DO = mDNSfalse;
9022 }
9023 // For Unicast DNS Queries, penalize the DNSServer
9024 else
9025 {
9026 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)",
9027 qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
9028 PenalizeDNSServer(m, qptr, response->h.flags);
9029 }
9030 }
9031 returnEarly = mDNStrue;
9032 }
9033 }
9034 }
9035 if (returnEarly)
9036 {
9037 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
9038 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
9039 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
9040 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
9041 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9042 // generate negative cache entries (we want to query the next server)
9043 return;
9044 }
9045 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9046 {
9047 BumpDNSSECStats(m, kStatsActionSet, kStatsTypeMsgSize, (end - response->data));
9048 }
9049 }
9050
9051 // Parse the NSEC3 records from the Authority section before we process
9052 // the Answer section so that we can cache them along with the proper
9053 // cache records we create.
9054 if (mDNSOpaque16IsZero(response->h.id))
9055 mDNSParseNSEC3Records(m, response, end, InterfaceID, &McastNSEC3Records);
9056
9057 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
9058 {
9059 // All responses sent via LL multicast are acceptable for caching
9060 // All responses received over our outbound TCP connections are acceptable for caching
9061 // We accept all records in a unicast response to a multicast query once we find one that
9062 // answers an active question.
9063 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse;
9064 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9065 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9066
9067 const mDNSu8 RecordType =
9068 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
9069 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
9070 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
9071 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9072
9073 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
9074 {
9075 mDNSCoreResetRecord(m);
9076 continue;
9077 }
9078
9079 // We have already parsed the NSEC3 records and cached them approrpriately for
9080 // multicast responses.
9081 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype == kDNSType_NSEC3)
9082 {
9083 mDNSCoreResetRecord(m);
9084 continue;
9085 }
9086 // Don't want to cache OPT or TSIG pseudo-RRs
9087 if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
9088 {
9089 mDNSCoreResetRecord(m);
9090 continue;
9091 }
9092 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
9093 {
9094 const rdataOPT *opt;
9095 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
9096 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9097 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9098 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
9099 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
9100 {
9101 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
9102 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
9103 }
9104 mDNSCoreResetRecord(m);
9105 continue;
9106 }
9107 // if a CNAME record points to itself, then don't add it to the cache
9108 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
9109 {
9110 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
9111 mDNSCoreResetRecord(m);
9112 continue;
9113 }
9114
9115 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9116 // In the case of active LLQs, we'll get remove events when the records actually do go away
9117 // In the case of polling LLQs, we assume the record remains valid until the next poll
9118 if (!mDNSOpaque16IsZero(response->h.id))
9119 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
9120
9121 // If response was not sent via LL multicast,
9122 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9123 if (!ResponseMCast)
9124 {
9125 if (LLQType)
9126 {
9127 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9128 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9129 // queries to get ADD/RMV events. To lookup the question, we can't use
9130 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9131 // has already matched the question using the 64 bit Id in the packet and we use that here.
9132
9133 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
9134
9135 // If this is a DNSSEC question that is also LongLived, don't accept records from the
9136 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
9137 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
9138 // for both negative responses and wildcard expanded positive responses as both of come
9139 // back with NSEC/NSEC3s.
9140 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9141 AcceptableResponse = mDNSfalse;
9142 }
9143 else if (!AcceptableResponse || !dstaddr)
9144 {
9145 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9146 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9147 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9148 // we create.
9149
9150 DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
9151
9152 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9153 // this record.
9154 //
9155 // We could potentially lookup the DNS server based on the source address, but that may not work always
9156 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9157 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9158 // on the "id" and "source port", then this response answers the question and assume the response
9159 // came from the same DNS server that we sent the query to.
9160
9161 if (q != mDNSNULL)
9162 {
9163 AcceptableResponse = mDNStrue;
9164 if (!InterfaceID)
9165 {
9166 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
9167 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
9168 }
9169 else
9170 {
9171 // Accept all remaining records in this unicast response to an mDNS query.
9172 recordAcceptedInResponse = mDNStrue;
9173 LogInfo("mDNSCoreReceiveResponse: Accepting response for query: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
9174 }
9175 }
9176 else
9177 {
9178 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9179 // the question. The code below does that. So, make this record unacceptable for now
9180 if (!InterfaceID)
9181 {
9182 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9183 AcceptableResponse = mDNSfalse;
9184 }
9185 }
9186 }
9187 }
9188 else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9189 {
9190 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9191 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9192 // To work with these broken routers, client devices need to blacklist these broken
9193 // routers and ignore their bogus ARP responses. Some devices implement a technique
9194 // such as the one described in US Patent 7436783, which lets clients detect and
9195 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9196
9197 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9198 // approach of just detecting these broken routers and completely disabling IPv4
9199 // link-local communication on interfaces where a broken router is detected.
9200 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9201 // that are deemed “safe” for IPv4 link-local communication;
9202 // the flag is cleared on interfaces where a broken router is detected.
9203
9204 // OS X and iOS will not even try to communicate with an IPv4
9205 // link-local destination on an interface without the IFEF_ARPLL flag set.
9206 // This can cause some badly written applications to freeze for a long time if they
9207 // attempt to connect to an IPv4 link-local destination address and then wait for
9208 // that connection attempt to time out before trying other candidate addresses.
9209
9210 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9211 // records on interfaces where we know the OS will be unwilling even to attempt
9212 // communication with those IPv4 link-local destination addresses.
9213 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9214
9215 const CacheRecord *const rr = &m->rec.r;
9216 const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9217 if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9218 {
9219 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9220 mDNSCoreResetRecord(m);
9221 continue;
9222 }
9223 }
9224
9225 // 1. Check that this packet resource record does not conflict with any of ours
9226 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9227 {
9228 if (m->CurrentRecord)
9229 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9230 m->CurrentRecord = m->ResourceRecords;
9231 while (m->CurrentRecord)
9232 {
9233 AuthRecord *rr = m->CurrentRecord;
9234 m->CurrentRecord = rr->next;
9235 // We accept all multicast responses, and unicast responses resulting from queries we issued
9236 // For other unicast responses, this code accepts them only for responses with an
9237 // (apparently) local source address that pertain to a record of our own that's in probing state
9238 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9239
9240 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
9241 {
9242 // ... check to see if type and rdata are identical
9243 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9244 {
9245 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9246 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9247 {
9248 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9249 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9250 }
9251 else
9252 {
9253 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
9254 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9255 }
9256 }
9257 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9258 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9259 {
9260 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
9261 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9262
9263 // If this record is marked DependentOn another record for conflict detection purposes,
9264 // then *that* record has to be bumped back to probing state to resolve the conflict
9265 if (rr->DependentOn)
9266 {
9267 while (rr->DependentOn) rr = rr->DependentOn;
9268 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9269 }
9270
9271 // If we've just whacked this record's ProbeCount, don't need to do it again
9272 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9273 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9274 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9275 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9276 else
9277 {
9278 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9279 // If we'd previously verified this record, put it back to probing state and try again
9280 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9281 {
9282 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9283 rr->resrec.RecordType = kDNSRecordTypeUnique;
9284 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9285 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9286 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9287 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9288 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
9289 rr->AnnounceCount = InitialAnnounceCount;
9290 InitializeLastAPTime(m, rr);
9291 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
9292 }
9293 // If we're probing for this record, we just failed
9294 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9295 {
9296 // At this point in the code, we're probing for uniqueness.
9297 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9298 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9299 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9300 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9301 {
9302 // This may be a conflict due to stale packets on the network. Delay probing by a second.
9303 // If there are conflicts after 3 such attempts, then it is a true conflict.
9304 if (m->DelayConflictProcessing)
9305 {
9306 m->DelayConflictProcessing--;
9307 LogMsg("Possible spurious conflict for %s. Attempt %d at suppressing probes for one second",
9308 ARDisplayString(m, rr), (MAX_CONFLICT_PROCESSING_DELAYS - m->DelayConflictProcessing));
9309 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
9310 rr->AnnounceCount = InitialAnnounceCount;
9311 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9312 InitializeLastAPTime(m, rr);
9313 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
9314 }
9315 else
9316 {
9317 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
9318 m->mDNSStats.NameConflicts++;
9319 #if APPLE_OSX_mDNSResponder
9320 // See if this record was also registered with any D2D plugins.
9321 D2D_stop_advertising_record(rr);
9322 #endif
9323 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9324 }
9325
9326 }
9327 }
9328 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9329 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9330 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9331 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9332 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9333 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9334 {
9335 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9336 m->mDNSStats.KnownUniqueNameConflicts++;
9337 #if APPLE_OSX_mDNSResponder
9338 D2D_stop_advertising_record(rr);
9339 #endif
9340 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9341 }
9342 else
9343 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9344 }
9345 }
9346 // Else, matching signature, different type or rdata, but not a considered a conflict.
9347 // If the packet record has the cache-flush bit set, then we check to see if we
9348 // have any record(s) of the same type that we should re-assert to rescue them
9349 // (see note about "multi-homing and bridged networks" at the end of this function).
9350 else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
9351 if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (mDNSu32)(m->timenow - rr->LastMCTime) > (mDNSu32)mDNSPlatformOneSecond/2)
9352 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9353 }
9354 }
9355 }
9356
9357 nseclist = mDNSfalse;
9358 if (!AcceptableResponse)
9359 {
9360 AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords, unicastQuestion, &nseclist);
9361 if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9362 }
9363
9364 // 2. See if we want to add this packet resource record to our cache
9365 // We only try to cache answers if we have a cache to put them in
9366 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9367 if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
9368 if (m->rrcache_size && AcceptableResponse)
9369 {
9370 const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash);
9371 CacheGroup *cg = CacheGroupForRecord(m, &m->rec.r.resrec);
9372 CacheRecord *rr = mDNSNULL;
9373
9374 if (McastNSEC3Records)
9375 InitializeAnonInfoForCR(m, &McastNSEC3Records, &m->rec.r);
9376
9377 // 2a. Check if this packet resource record is already in our cache.
9378 //
9379 // If this record should go in the nseclist, don't look in the cache for updating it.
9380 // They are supposed to be cached under the "nsec" field of the cache record for
9381 // validation. Just create the cache record.
9382 if (!nseclist)
9383 {
9384 rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, unicastQuestion, &cfp, &NSECCachePtr, InterfaceID);
9385 }
9386
9387 // If packet resource record not in our cache, add it now
9388 // (unless it is just a deletion of a record we never had, in which case we don't care)
9389 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9390 {
9391 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9392 mDNSs32 delay;
9393
9394 if (AddToCFList)
9395 delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9396 else
9397 delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash);
9398
9399 // If unique, assume we may have to delay delivery of this 'add' event.
9400 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9401 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9402 // to schedule an mDNS_Execute task at the appropriate time.
9403 rr = CreateNewCacheEntry(m, slot, cg, delay, !nseclist, srcaddr);
9404 if (rr)
9405 {
9406 rr->responseFlags = response->h.flags;
9407 // If we are not creating signatures, then we need to inform DNSSEC so that
9408 // it does not wait forever. Don't do this if we got NSEC records
9409 // as it indicates that this name does not exist.
9410 if (rr->resrec.rrtype == kDNSType_RRSIG && !nseclist)
9411 {
9412 rrsigsCreated = mDNStrue;
9413 }
9414 // Remember whether we created a cache record in response to a DNSSEC question.
9415 // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9416 rr->CRDNSSECQuestion = 0;
9417 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9418 {
9419 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record %s, question %##s (%s)", CRDisplayString(m, rr),
9420 unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
9421 rr->CRDNSSECQuestion = 1;
9422 }
9423 // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9424 // which we should be creating below. It is also needed in the wildcard
9425 // expanded answer case and in that case it is cached along with the answer.
9426 if (nseclist)
9427 {
9428 rr->TimeRcvd = m->timenow;
9429 *nsecp = rr;
9430 nsecp = &rr->next;
9431 }
9432 else if (AddToCFList)
9433 {
9434 *cfp = rr;
9435 cfp = &rr->NextInCFList;
9436 *cfp = (CacheRecord*)1;
9437 }
9438 else if (rr->DelayDelivery)
9439 {
9440 ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9441 }
9442 }
9443 }
9444 else
9445 {
9446 if (rr && rr->resrec.AnonInfo && m->rec.r.resrec.AnonInfo)
9447 {
9448 CopyAnonInfoForCR(m, rr, &m->rec.r);
9449 }
9450 }
9451 }
9452 mDNSCoreResetRecord(m);
9453 }
9454
9455 exit:
9456 mDNSCoreResetRecord(m);
9457
9458 // If we've just received one or more records with their cache flush bits set,
9459 // then scan that cache slot to see if there are any old stale records we need to flush
9460 while (CacheFlushRecords != (CacheRecord*)1)
9461 {
9462 CacheRecord *r1 = CacheFlushRecords, *r2;
9463 const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash);
9464 const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec);
9465 mDNSBool purgedRecords = mDNSfalse;
9466 CacheFlushRecords = CacheFlushRecords->NextInCFList;
9467 r1->NextInCFList = mDNSNULL;
9468
9469 // Look for records in the cache with the same signature as this new one with the cache flush
9470 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9471 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9472 // We make these TTL adjustments *only* for records that still have *more* than one second
9473 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9474 // (and now has half a second remaining) could inadvertently get its life extended, by either
9475 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9476 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9477 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9478 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9479 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9480 // To avoid this, we need to ensure that the cache flushing operation will only act to
9481 // *decrease* a record's remaining lifetime, never *increase* it.
9482 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9483 {
9484 mDNSu16 id1;
9485 mDNSu16 id2;
9486 if (!r1->resrec.InterfaceID)
9487 {
9488 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9489 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9490 }
9491 else
9492 {
9493 id1 = id2 = 0;
9494 }
9495 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9496 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9497 // the new RRSIG that we received. Process only if the typeCovered matches.
9498 if ((r1->resrec.rrtype == r2->resrec.rrtype) && (r1->resrec.rrtype == kDNSType_RRSIG))
9499 {
9500 rdataRRSig *rrsig1 = (rdataRRSig *)(((RDataBody2 *)(r1->resrec.rdata->u.data))->data);
9501 rdataRRSig *rrsig2 = (rdataRRSig *)(((RDataBody2 *)(r2->resrec.rdata->u.data))->data);
9502 if (swap16(rrsig1->typeCovered) != swap16(rrsig2->typeCovered))
9503 {
9504 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9505 DNSTypeName(swap16(rrsig1->typeCovered)), DNSTypeName(swap16(rrsig2->typeCovered)));
9506 continue;
9507 }
9508 }
9509
9510 // For Unicast (null InterfaceID) the resolver IDs should also match
9511 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9512 (r1->resrec.InterfaceID || (id1 == id2)) &&
9513 r1->resrec.rrtype == r2->resrec.rrtype &&
9514 r1->resrec.rrclass == r2->resrec.rrclass)
9515 {
9516 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9517 // else, if record is old, mark it to be flushed
9518 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9519 {
9520 // If we find mismatched TTLs in an RRSet, correct them.
9521 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9522 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9523 // which we treat as a goodbye followed by an addition) and in that case it would be
9524 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9525
9526 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9527 // because certain early Bonjour devices are known to have this specific mismatch, and
9528 // there's no point filling syslog with messages about something we already know about.
9529 // We also don't log this for uDNS responses, since a caching name server is obliged
9530 // to give us an aged TTL to correct for how long it has held the record,
9531 // so our received TTLs are expected to vary in that case
9532
9533 // We also suppress log message in the case of SRV records that are received
9534 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9535 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9536 // GM builds.
9537 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9538 {
9539 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9540 !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
9541 mDNSOpaque16IsZero(response->h.id))
9542 LogInfo("Correcting TTL from %4d to %4d for %s",
9543 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9544 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9545 }
9546 r2->TimeRcvd = m->timenow;
9547 SetNextCacheCheckTimeForRecord(m, r2);
9548 }
9549 else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed
9550 {
9551 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9552 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9553 // We set stale records to expire in one second.
9554 // This gives the owner a chance to rescue it if necessary.
9555 // This is important in the case of multi-homing and bridged networks:
9556 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9557 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9558 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9559 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9560 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9561 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9562
9563 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9564 // final expiration queries for this record.
9565
9566 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9567 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9568 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9569 // <rdar://problem/5636422> Updating TXT records is too slow
9570 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9571 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9572 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9573 {
9574 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9575 r2->resrec.rroriginalttl = 0;
9576 }
9577 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9578 {
9579 // We only set a record to expire in one second if it currently has *more* than a second to live
9580 // If it's already due to expire in a second or less, we just leave it alone
9581 r2->resrec.rroriginalttl = 1;
9582 r2->UnansweredQueries = MaxUnansweredQueries;
9583 r2->TimeRcvd = m->timenow - 1;
9584 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9585 // that we marked for deletion via an explicit DE record
9586 }
9587 SetNextCacheCheckTimeForRecord(m, r2);
9588 }
9589 else
9590 {
9591 // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9592 mDNS_PurgeCacheResourceRecord(m, r2);
9593 purgedRecords = mDNStrue;
9594 }
9595 }
9596 }
9597
9598 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
9599 {
9600 // If we had a unicast question for this response with at least one positive answer and we
9601 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9602 // signatures along with the cache record which will be used for validation later. If
9603 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9604 // use that instead.
9605 if (response->h.numAnswers && unicastQuestion && NSECRecords)
9606 {
9607 if (!NSECCachePtr)
9608 {
9609 LogInfo("mDNSCoreReceiveResponse: Updating NSECCachePtr to %s", CRDisplayString(m, r1));
9610 NSECCachePtr = r1;
9611 }
9612 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9613 // might start the verification process which needs these NSEC records
9614 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9615 {
9616 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9617 FreeNSECRecords(m, NSECRecords);
9618 }
9619 NSECRecords = mDNSNULL;
9620 NSECCachePtr = mDNSNULL;
9621 }
9622 if (r1->resrec.InterfaceID)
9623 {
9624 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash);
9625 }
9626 else
9627 {
9628 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9629 // them to be deleted before any ADD events for this record.
9630 r1->DelayDelivery = purgedRecords ? NonZeroTime(m->timenow) : 0;
9631 }
9632 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9633 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9634 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9635 }
9636 }
9637
9638 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9639 // update them now for future validations.
9640 if (NSECRecords && NSECCachePtr)
9641 {
9642 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m, NSECCachePtr));
9643 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9644 {
9645 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9646 FreeNSECRecords(m, NSECRecords);
9647 }
9648 NSECRecords = mDNSNULL;
9649 NSECCachePtr = mDNSNULL;
9650 }
9651
9652 // If there is at least one answer and we did not create RRSIGs and there was a
9653 // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9654 // were created. We don't need to give a hint:
9655 //
9656 // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9657 // generate a negative response
9658 //
9659 // - if we have NSECRecords, it means we might have a potential proof for
9660 // non-existence of name that we are looking for
9661 //
9662 if (response->h.numAnswers && !rrsigsCreated && DNSSECQuestion && !NSECRecords)
9663 mDNSCoreReceiveNoDNSSECAnswers(m, response, end, dstaddr, dstport, InterfaceID);
9664
9665 // See if we need to generate negative cache entries for unanswered unicast questions
9666 mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, LLQType, rcode, NSECRecords);
9667
9668 if (McastNSEC3Records)
9669 {
9670 debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9671 FreeNSECRecords(m, McastNSEC3Records);
9672 }
9673 }
9674
9675 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9676 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9677 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9678 // that warrants waking the sleeping host.
9679 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9680
9681 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9682 {
9683 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9684 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9685 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9686 // simple, we use the same mechanism for both lists.
9687 if (!e->l[0])
9688 {
9689 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9690 return;
9691 }
9692 m->CurrentRecord = thelist;
9693 while (m->CurrentRecord)
9694 {
9695 AuthRecord *const rr = m->CurrentRecord;
9696 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9697 {
9698 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9699 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9700 }
9701 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9702 m->CurrentRecord = rr->next;
9703 }
9704 }
9705
9706 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9707 {
9708 if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9709 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9710 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9711 }
9712
9713 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9714 {
9715 if (result && result != mStatus_MemFree)
9716 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9717
9718 if (result == mStatus_NameConflict)
9719 {
9720 mDNS_Lock(m);
9721 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9722 if (ar->WakeUp.HMAC.l[0])
9723 {
9724 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password, mDNSfalse); // Send one wakeup magic packet
9725 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken
9726 }
9727 mDNS_Unlock(m);
9728 }
9729
9730 if (result == mStatus_NameConflict || result == mStatus_MemFree)
9731 {
9732 m->ProxyRecords--;
9733 mDNSPlatformMemFree(ar);
9734 mDNS_UpdateAllowSleep(m);
9735 }
9736 }
9737
9738 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9739 {
9740 int i;
9741 mDNSs8 hval = 0;
9742 int colons = 0;
9743 mDNSu8 val = 0;
9744
9745 for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9746 {
9747 hval = HexVal(*ptr);
9748 if (hval != -1)
9749 {
9750 val <<= 4;
9751 val |= hval;
9752 }
9753 else if (*ptr == ':')
9754 {
9755 if (colons >=5)
9756 {
9757 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
9758 return mDNSNULL;
9759 }
9760 eth->b[colons] = val;
9761 colons++;
9762 val = 0;
9763 }
9764 }
9765 if (colons != 5)
9766 {
9767 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9768 return mDNSNULL;
9769 }
9770 eth->b[colons] = val;
9771 return ptr;
9772 }
9773
9774 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9775 {
9776 int hval;
9777 int value;
9778 int numBytes;
9779 int digitsProcessed;
9780 int zeroFillStart;
9781 int numColons;
9782 mDNSu8 v6addr[16];
9783
9784 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9785 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9786 //
9787 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9788 // the result in "v6"
9789
9790 numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9791 while (ptr < limit && *ptr != ' ')
9792 {
9793 hval = HexVal(*ptr);
9794 if (hval != -1)
9795 {
9796 value <<= 4;
9797 value |= hval;
9798 digitsProcessed = 1;
9799 }
9800 else if (*ptr == ':')
9801 {
9802 if (!digitsProcessed)
9803 {
9804 // If we have already seen a "::", we should not see one more. Handle the special
9805 // case of "::"
9806 if (numColons)
9807 {
9808 // if we never filled any bytes and the next character is space (we have reached the end)
9809 // we are done
9810 if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
9811 {
9812 mDNSPlatformMemZero(v6->b, 16);
9813 return ptr + 1;
9814 }
9815 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
9816 return mDNSNULL;
9817 }
9818
9819 // We processed "::". We need to fill zeroes later. For now, mark the
9820 // point where we will start filling zeroes from.
9821 zeroFillStart = numBytes;
9822 numColons++;
9823 }
9824 else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
9825 {
9826 // We have a trailing ":" i.e., no more characters after ":"
9827 LogMsg("GetValueForIPv6Addr: Trailing colon");
9828 return mDNSNULL;
9829 }
9830 else
9831 {
9832 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9833 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9834 // filled here is 12 and 13.
9835 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
9836
9837 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9838 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9839 digitsProcessed = value = 0;
9840
9841 // Make sure that we did not fill the 13th and 14th byte above
9842 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
9843 }
9844 }
9845 ptr++;
9846 }
9847
9848 // We should be processing the last set of bytes following the last ":" here
9849 if (!digitsProcessed)
9850 {
9851 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
9852 return mDNSNULL;
9853 }
9854
9855 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
9856 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9857 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9858
9859 if (zeroFillStart)
9860 {
9861 int i, j, n;
9862 for (i = 0; i < zeroFillStart; i++)
9863 v6->b[i] = v6addr[i];
9864 for (j = i, n = 0; n < 16 - numBytes; j++, n++)
9865 v6->b[j] = 0;
9866 for (; j < 16; i++, j++)
9867 v6->b[j] = v6addr[i];
9868 }
9869 else if (numBytes == 16)
9870 mDNSPlatformMemCopy(v6->b, v6addr, 16);
9871 else
9872 {
9873 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
9874 return mDNSNULL;
9875 }
9876 return ptr;
9877 }
9878
9879 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
9880 {
9881 mDNSu32 val;
9882 int dots = 0;
9883 val = 0;
9884
9885 for ( ; ptr < limit && *ptr != ' '; ptr++)
9886 {
9887 if (*ptr >= '0' && *ptr <= '9')
9888 val = val * 10 + *ptr - '0';
9889 else if (*ptr == '.')
9890 {
9891 if (val > 255 || dots >= 3)
9892 {
9893 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
9894 return mDNSNULL;
9895 }
9896 v4->b[dots++] = val;
9897 val = 0;
9898 }
9899 else
9900 {
9901 // We have a zero at the end and if we reached that, then we are done.
9902 if (*ptr == 0 && ptr == limit - 1 && dots == 3)
9903 {
9904 v4->b[dots] = val;
9905 return ptr + 1;
9906 }
9907 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
9908 }
9909 }
9910 if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
9911 v4->b[dots] = val;
9912 return ptr;
9913 }
9914
9915 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
9916 {
9917 mDNSu32 val;
9918
9919 val = 0;
9920 for ( ; ptr < limit && *ptr != ' '; ptr++)
9921 {
9922 if (*ptr < '0' || *ptr > '9')
9923 {
9924 // We have a zero at the end and if we reached that, then we are done.
9925 if (*ptr == 0 && ptr == limit - 1)
9926 {
9927 *value = val;
9928 return ptr + 1;
9929 }
9930 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
9931 }
9932 val = val * 10 + *ptr - '0';
9933 }
9934 *value = val;
9935 return ptr;
9936 }
9937
9938 mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
9939 {
9940 mDNSAddr laddr, raddr;
9941 mDNSEthAddr eth;
9942 mDNSIPPort lport, rport;
9943 mDNSu32 timeout, seq, ack;
9944 mDNSu16 win;
9945
9946 if (!mDNS_KeepaliveRecord(&rr->resrec))
9947 {
9948 return mDNSfalse;
9949 }
9950
9951 timeout = seq = ack = 0;
9952 win = 0;
9953 laddr = raddr = zeroAddr;
9954 lport = rport = zeroIPPort;
9955 eth = zeroEthAddr;
9956
9957 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9958
9959 if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
9960 mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
9961 mDNSEthAddressIsZero(eth))
9962 {
9963 return mDNSfalse;
9964 }
9965
9966 return mDNStrue;
9967 }
9968
9969
9970 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
9971 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
9972 {
9973 if (ar->resrec.rrtype != kDNSType_NULL)
9974 return;
9975
9976 if (mDNS_KeepaliveRecord(&ar->resrec))
9977 {
9978 int len = ar->resrec.rdlength;
9979 mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
9980 mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
9981 mDNSu32 value = 0;
9982
9983 while (ptr < limit)
9984 {
9985 mDNSu8 param = *ptr;
9986 ptr += 2; // Skip the letter and the "="
9987 if (param == 'h')
9988 {
9989 laddr->type = mDNSAddrType_IPv4;
9990 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
9991 }
9992 else if (param == 'd')
9993 {
9994 raddr->type = mDNSAddrType_IPv4;
9995 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
9996 }
9997 else if (param == 'H')
9998 {
9999 laddr->type = mDNSAddrType_IPv6;
10000 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
10001 }
10002 else if (param == 'D')
10003 {
10004 raddr->type = mDNSAddrType_IPv6;
10005 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
10006 }
10007 else if (param == 'm')
10008 {
10009 ptr = GetValueForMACAddr(ptr, limit, eth);
10010 }
10011 else
10012 {
10013 ptr = GetValueForKeepalive(ptr, limit, &value);
10014 }
10015 if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10016
10017 // Extract everything in network order so that it is easy for sending a keepalive and also
10018 // for matching incoming TCP packets
10019 switch (param)
10020 {
10021 case 't':
10022 *timeout = value;
10023 //if (*timeout < 120) *timeout = 120;
10024 break;
10025 case 'h':
10026 case 'H':
10027 case 'd':
10028 case 'D':
10029 case 'm':
10030 case 'i':
10031 case 'c':
10032 break;
10033 case 'l':
10034 lport->NotAnInteger = swap16((mDNSu16)value);
10035 break;
10036 case 'r':
10037 rport->NotAnInteger = swap16((mDNSu16)value);
10038 break;
10039 case 's':
10040 *seq = swap32(value);
10041 break;
10042 case 'a':
10043 *ack = swap32(value);
10044 break;
10045 case 'w':
10046 *win = swap16((mDNSu16)value);
10047 break;
10048 default:
10049 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
10050 ptr = limit;
10051 break;
10052 }
10053 ptr++; // skip the space
10054 }
10055 }
10056 }
10057
10058 // 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
10059 // the clients need not retrieve this information from the auth record again.
10060 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
10061 const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
10062 {
10063 AuthRecord *ar;
10064 mDNSAddr laddr, raddr;
10065 mDNSEthAddr eth;
10066 mDNSIPPort lport, rport;
10067 mDNSu32 timeout, seq, ack;
10068 mDNSu16 win;
10069
10070 for (ar = m->ResourceRecords; ar; ar=ar->next)
10071 {
10072 timeout = seq = ack = 0;
10073 win = 0;
10074 laddr = raddr = zeroAddr;
10075 lport = rport = zeroIPPort;
10076
10077 if (!ar->WakeUp.HMAC.l[0]) continue;
10078
10079 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10080
10081 // Did we parse correctly ?
10082 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10083 {
10084 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
10085 continue;
10086 }
10087
10088 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10089 &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
10090
10091 // Does it match the incoming TCP packet ?
10092 if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
10093 {
10094 // returning in network order
10095 *rseq = seq;
10096 *rack = ack;
10097 return ar;
10098 }
10099 }
10100 return mDNSNULL;
10101 }
10102
10103 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
10104 {
10105 AuthRecord *ar;
10106
10107 for (ar = m->ResourceRecords; ar; ar=ar->next)
10108 {
10109 mDNSu32 timeout, seq, ack;
10110 mDNSu16 win;
10111 mDNSAddr laddr, raddr;
10112 mDNSEthAddr eth;
10113 mDNSIPPort lport, rport;
10114
10115 timeout = seq = ack = 0;
10116 win = 0;
10117
10118 laddr = raddr = zeroAddr;
10119 lport = rport = zeroIPPort;
10120
10121 if (!ar->WakeUp.HMAC.l[0]) continue;
10122
10123 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10124
10125 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10126 {
10127 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
10128 continue;
10129 }
10130 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10131
10132 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10133 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10134 if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
10135 {
10136 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10137 ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
10138 }
10139 if (m->NextScheduledKA - ar->KATimeExpire > 0)
10140 m->NextScheduledKA = ar->KATimeExpire;
10141 }
10142 }
10143
10144 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
10145 {
10146 mDNSu32 timeout, seq, ack, seqInc;
10147 mDNSu16 win;
10148 mDNSAddr laddr, raddr;
10149 mDNSEthAddr eth;
10150 mDNSIPPort lport, rport;
10151 mDNSu8 *ptr;
10152
10153 if (ar == mDNSNULL)
10154 {
10155 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10156 return;
10157 }
10158
10159 timeout = seq = ack = 0;
10160 win = 0;
10161
10162 laddr = raddr = zeroAddr;
10163 lport = rport = zeroIPPort;
10164
10165 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10166
10167 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10168 {
10169 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
10170 return;
10171 }
10172
10173 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10174 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10175 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10176 // it's converted to host byte order before incrementing it by one.
10177 ptr = (mDNSu8 *)&seq;
10178 seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
10179 ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
10180 ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
10181 ptr[2] = (mDNSu8)((seqInc >> 8) & 0xFF);
10182 ptr[3] = (mDNSu8)((seqInc ) & 0xFF);
10183 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10184 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10185 }
10186
10187 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
10188 const DNSMessage *const msg, const mDNSu8 *end,
10189 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
10190 const mDNSInterfaceID InterfaceID)
10191 {
10192 int i;
10193 AuthRecord opt;
10194 mDNSu8 *p = m->omsg.data;
10195 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10196 mDNSu32 updatelease = 0;
10197 const mDNSu8 *ptr;
10198
10199 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10200 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10201 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
10202 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
10203 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
10204 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
10205 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
10206
10207 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
10208
10209 if (mDNS_PacketLoggingEnabled)
10210 DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
10211
10212 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
10213 if (ptr)
10214 {
10215 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10216 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10217 {
10218 const rdataOPT *o;
10219 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10220 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10221 {
10222 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
10223 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
10224 }
10225 }
10226 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10227 }
10228
10229 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
10230
10231 if (!updatelease || !owner.HMAC.l[0])
10232 {
10233 static int msgs = 0;
10234 if (msgs < 100)
10235 {
10236 msgs++;
10237 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
10238 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
10239 }
10240 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
10241 }
10242 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
10243 {
10244 static int msgs = 0;
10245 if (msgs < 100)
10246 {
10247 msgs++;
10248 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
10249 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
10250 }
10251 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10252 }
10253 else
10254 {
10255 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
10256
10257 if (updatelease > 24 * 60 * 60)
10258 updatelease = 24 * 60 * 60;
10259
10260 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
10261 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
10262
10263 ptr = LocateAuthorities(msg, end);
10264
10265 // Clear any stale TCP keepalive records that may exist
10266 ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
10267 ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
10268
10269 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10270 {
10271 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10272 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10273 {
10274 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10275 AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10276 if (!ar)
10277 {
10278 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10279 break;
10280 }
10281 else
10282 {
10283 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10284 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10285 // All stale keepalive records have been flushed prior to this loop.
10286 if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10287 {
10288 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10289 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10290 }
10291 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10292 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10293 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10294 ar->resrec.rdata->MaxRDLength = RDLengthMem;
10295 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10296 ar->ForceMCast = mDNStrue;
10297 ar->WakeUp = owner;
10298 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10299 {
10300 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10301 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10302 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10303 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10304 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10305 }
10306 ar->TimeRcvd = m->timenow;
10307 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10308 if (m->NextScheduledSPS - ar->TimeExpire > 0)
10309 m->NextScheduledSPS = ar->TimeExpire;
10310 ar->KATimeExpire = 0;
10311 mDNS_Register_internal(m, ar);
10312
10313 m->ProxyRecords++;
10314 mDNS_UpdateAllowSleep(m);
10315 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10316 }
10317 }
10318 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10319 }
10320
10321 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10322 {
10323 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10324 ClearProxyRecords(m, &owner, m->DuplicateRecords);
10325 ClearProxyRecords(m, &owner, m->ResourceRecords);
10326 }
10327 else
10328 {
10329 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10330 opt.resrec.rrclass = NormalMaxDNSMessageData;
10331 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
10332 opt.resrec.rdestimate = sizeof(rdataOPT);
10333 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
10334 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10335 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10336 }
10337 }
10338
10339 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
10340 mDNS_SendKeepalives(m);
10341 }
10342
10343 mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg)
10344 {
10345 mDNSu8 *ptr = msg->data;
10346 mDNSu8 *end = mDNSNULL;
10347 mDNSu32 length = 0;
10348 AuthRecord opt;
10349 NetworkInterfaceInfo *intf;
10350
10351 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10352 opt.resrec.rrclass = NormalMaxDNSMessageData;
10353 opt.resrec.rdlength = sizeof(rdataOPT);
10354 opt.resrec.rdestimate = sizeof(rdataOPT);
10355
10356 intf = FirstInterfaceForID(m, InterfaceID);
10357 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
10358
10359 LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt));
10360 end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec);
10361 if (end != mDNSNULL)
10362 {
10363 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10364 SwapDNSHeaderBytes(msg);
10365 length = (end - msg->data);
10366 }
10367 else
10368 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10369
10370 return length;
10371 }
10372
10373 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10374 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10375 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10376 // Really, both should be unified and handled in one place.
10377 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10378 {
10379 if (InterfaceID)
10380 {
10381 mDNSu32 pktlease = 0, spsupdates = 0;
10382 const mDNSBool gotlease = GetPktLease(m, msg, end, &pktlease);
10383 const mDNSu32 updatelease = gotlease ? pktlease : 60 * 60; // If SPS fails to indicate lease time, assume one hour
10384 if (gotlease) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10385
10386 if (m->CurrentRecord)
10387 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10388 m->CurrentRecord = m->ResourceRecords;
10389 while (m->CurrentRecord)
10390 {
10391 AuthRecord *const rr = m->CurrentRecord;
10392 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10393 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10394 {
10395 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10396 // Clear the updateid when we are done sending on all interfaces.
10397 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10398 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10399 bit_clr_opaque64(rr->updateIntID, scopeid);
10400 if (mDNSOpaque64IsZero(&rr->updateIntID))
10401 rr->updateid = zeroID;
10402 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10403 spsupdates++;
10404 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));
10405 if (rr->WakeUp.HMAC.l[0])
10406 {
10407 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10408 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10409 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10410 }
10411 }
10412 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10413 // new records could have been added to the end of the list as a result of that call.
10414 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10415 m->CurrentRecord = rr->next;
10416 }
10417 if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10418 {
10419 char *ifname;
10420 mDNSAddr spsaddr;
10421 DNSMessage optMsg;
10422 int length;
10423 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10424 ifname = InterfaceNameForID(m, InterfaceID);
10425 mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10426 mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10427
10428 // Store the Owner OPT record for this interface.
10429 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10430 InitializeDNSMessage(&optMsg.h, zeroID, ResponseFlags);
10431 length = mDNSGenerateOwnerOptForInterface(m, InterfaceID, &optMsg);
10432 if (length != 0)
10433 {
10434 length += sizeof(DNSMessageHeader);
10435 mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length);
10436 }
10437 }
10438 }
10439 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10440 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10441 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10442 }
10443
10444 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
10445 const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
10446 {
10447 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10448 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10449
10450 // Create empty resource record
10451 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
10452 cr->resrec.InterfaceID = InterfaceID;
10453 cr->resrec.rDNSServer = dnsserver;
10454 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10455 cr->resrec.rrtype = rrtype;
10456 cr->resrec.rrclass = rrclass;
10457 cr->resrec.rroriginalttl = ttl_seconds;
10458 cr->resrec.rdlength = 0;
10459 cr->resrec.rdestimate = 0;
10460 cr->resrec.namehash = namehash;
10461 cr->resrec.rdatahash = 0;
10462 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10463 cr->resrec.rdata->MaxRDLength = 0;
10464
10465 cr->NextInKAList = mDNSNULL;
10466 cr->TimeRcvd = m->timenow;
10467 cr->DelayDelivery = 0;
10468 cr->NextRequiredQuery = m->timenow;
10469 cr->LastUsed = m->timenow;
10470 cr->CRActiveQuestion = mDNSNULL;
10471 cr->UnansweredQueries = 0;
10472 cr->LastUnansweredTime = 0;
10473 cr->NextInCFList = mDNSNULL;
10474 cr->nsec = mDNSNULL;
10475 cr->soa = mDNSNULL;
10476 cr->CRDNSSECQuestion = 0;
10477 // Initialize to the basic one and the caller can set it to more
10478 // specific based on the response if any
10479 cr->responseFlags = ResponseFlags;
10480 }
10481
10482 mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10483 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10484 const mDNSInterfaceID InterfaceID)
10485 {
10486 mDNSInterfaceID ifid = InterfaceID;
10487 const mDNSu8 *const pkt = (mDNSu8 *)msg;
10488 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
10489 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10490 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
10491 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10492 mDNSu8 QR_OP;
10493 mDNSu8 *ptr = mDNSNULL;
10494 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10495 if (TLS) dstaddr = mDNSNULL;
10496
10497 #ifndef UNICAST_DISABLED
10498 if (mDNSSameAddress(srcaddr, &m->Router))
10499 {
10500 #ifdef _LEGACY_NAT_TRAVERSAL_
10501 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10502 {
10503 mDNS_Lock(m);
10504 LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10505 mDNS_Unlock(m);
10506 return;
10507 }
10508 #endif
10509 if (mDNSSameIPPort(srcport, NATPMPPort))
10510 {
10511 mDNS_Lock(m);
10512 uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10513 mDNS_Unlock(m);
10514 return;
10515 }
10516 }
10517 #ifdef _LEGACY_NAT_TRAVERSAL_
10518 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10519 #endif
10520
10521 #endif
10522 if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader))
10523 {
10524 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt));
10525 return;
10526 }
10527 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10528 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10529 ptr = (mDNSu8 *)&msg->h.numQuestions;
10530 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10531 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10532 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10533 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10534
10535 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10536
10537 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10538 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10539 if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10540
10541 mDNS_Lock(m);
10542 m->PktNum++;
10543 if (mDNSOpaque16IsZero(msg->h.id))
10544 {
10545 m->MPktNum++;
10546 #if APPLE_OSX_mDNSResponder
10547 // Track the number of multicast packets received from a source outside our subnet.
10548 // Check the destination address to avoid accounting for spurious packets that
10549 // comes in with message id zero.
10550 if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) && dstaddr &&
10551 mDNSAddressIsAllDNSLinkGroup(dstaddr))
10552 {
10553 m->RemoteSubnet++;
10554 }
10555 #endif // #if APPLE_OSX_mDNSResponder
10556 }
10557
10558 #ifndef UNICAST_DISABLED
10559 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10560 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10561 {
10562 ifid = mDNSInterface_Any;
10563 if (mDNS_PacketLoggingEnabled)
10564 DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
10565 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10566 // Note: mDNSCore also needs to get access to received unicast responses
10567 }
10568 #endif
10569 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10570 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10571 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10572 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr, InterfaceID);
10573 else
10574 {
10575 if (mDNS_LoggingEnabled)
10576 {
10577 static int msgCount = 0;
10578 if (msgCount < 1000) {
10579 int i = 0;
10580 msgCount++;
10581 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10582 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt), InterfaceID);
10583 while (i < (int)(end - pkt))
10584 {
10585 char buffer[128];
10586 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10587 do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15);
10588 LogInfo("%s", buffer);
10589 }
10590 }
10591 }
10592 }
10593 // Packet reception often causes a change to the task list:
10594 // 1. Inbound queries can cause us to need to send responses
10595 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10596 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10597 // 4. Response packets that answer questions may cause our client to issue new questions
10598 mDNS_Unlock(m);
10599 }
10600
10601 // ***************************************************************************
10602 #if COMPILER_LIKES_PRAGMA_MARK
10603 #pragma mark -
10604 #pragma mark - Searcher Functions
10605 #endif
10606
10607 // Targets are considered the same if both queries are untargeted, or
10608 // if both are targeted to the same address+port
10609 // (If Target address is zero, TargetPort is undefined)
10610 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
10611 (mDNSSameAddress(& (A)->Target, & (B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
10612
10613 // SameQuestionKind is true if *both* questions are either multicast or unicast
10614 // TargetQID is used for this determination.
10615 #define SameQuestionKind(A,B) ((mDNSOpaque16IsZero(A) && mDNSOpaque16IsZero(B)) || \
10616 ((!mDNSOpaque16IsZero(A)) && (!mDNSOpaque16IsZero(B))))
10617
10618 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10619 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10620 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10621 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10622 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10623 //
10624 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10625 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10626 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10627 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10628 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10629 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10630 // breaks this design principle.
10631 //
10632
10633 // If IsLLQ(Q) is true, it means the question is both:
10634 // (a) long-lived and
10635 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10636 // for multicast questions, we don't want to treat LongLived as anything special
10637 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10638 #define IsAWDLIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10639
10640 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10641 {
10642 DNSQuestion *q;
10643 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10644 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10645 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10646 // further in the list.
10647 for (q = m->Questions; q && q != question; q=q->next) // Scan our list for another question
10648 if (q->InterfaceID == question->InterfaceID && // with the same InterfaceID,
10649 SameQTarget(q, question) && // and same unicast/multicast target settings
10650 q->qtype == question->qtype && // type,
10651 q->qclass == question->qclass && // class,
10652 IsLLQ(q) == IsLLQ(question) && // and long-lived status matches
10653 (!q->AuthInfo || question->AuthInfo) && // to avoid deadlock, don't make public query dup of a private one
10654 (q->AnonInfo == question->AnonInfo) && // Anonymous query not a dup of normal query
10655 (q->SuppressQuery == question->SuppressQuery) && // Questions that are suppressed/not suppressed
10656 (q->ValidationRequired == question->ValidationRequired) && // Questions that require DNSSEC validation
10657 (q->ValidatingResponse == question->ValidatingResponse) && // Questions that are validating responses using DNSSEC
10658 (q->DisallowPID == question->DisallowPID) && // Disallowing a PID should not affect a PID that is allowed
10659 (q->BrowseThreshold == question->BrowseThreshold) && // browse thresholds must match
10660 q->qnamehash == question->qnamehash &&
10661 (IsAWDLIncluded(q) == IsAWDLIncluded(question)) && // Inclusion of AWDL interface must match
10662 SameQuestionKind(q->TargetQID, question->TargetQID) && // mDNS or uDNS must match
10663 SameDomainName(&q->qname, &question->qname)) // and name
10664 return(q);
10665 return(mDNSNULL);
10666 }
10667
10668 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10669 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10670 {
10671 DNSQuestion *q;
10672 DNSQuestion *first = mDNSNULL;
10673
10674 // This is referring to some other question as duplicate. No other question can refer to this
10675 // question as a duplicate.
10676 if (question->DuplicateOf)
10677 {
10678 LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
10679 question, question->qname.c, DNSTypeName(question->qtype),
10680 question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
10681 return;
10682 }
10683
10684 for (q = m->Questions; q; q=q->next) // Scan our list of questions
10685 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
10686 {
10687 q->DuplicateOf = first;
10688 if (!first)
10689 {
10690 first = q;
10691 // If q used to be a duplicate, but now is not,
10692 // then inherit the state from the question that's going away
10693 q->LastQTime = question->LastQTime;
10694 q->ThisQInterval = question->ThisQInterval;
10695 q->ExpectUnicastResp = question->ExpectUnicastResp;
10696 q->LastAnswerPktNum = question->LastAnswerPktNum;
10697 q->RecentAnswerPkts = question->RecentAnswerPkts;
10698 q->RequestUnicast = question->RequestUnicast;
10699 q->LastQTxTime = question->LastQTxTime;
10700 q->CNAMEReferrals = question->CNAMEReferrals;
10701 q->nta = question->nta;
10702 q->servAddr = question->servAddr;
10703 q->servPort = question->servPort;
10704 q->qDNSServer = question->qDNSServer;
10705 q->validDNSServers = question->validDNSServers;
10706 q->unansweredQueries = question->unansweredQueries;
10707 q->noServerResponse = question->noServerResponse;
10708 q->triedAllServersOnce = question->triedAllServersOnce;
10709
10710 q->TargetQID = question->TargetQID;
10711 q->LocalSocket = question->LocalSocket;
10712 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10713
10714 q->state = question->state;
10715 // q->tcp = question->tcp;
10716 q->ReqLease = question->ReqLease;
10717 q->expire = question->expire;
10718 q->ntries = question->ntries;
10719 q->id = question->id;
10720
10721 question->LocalSocket = mDNSNULL;
10722 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
10723 // question->tcp = mDNSNULL;
10724
10725 if (q->LocalSocket)
10726 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10727
10728 if (q->nta)
10729 {
10730 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10731 q->nta->ZoneDataContext = q;
10732 }
10733
10734 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10735 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10736
10737 if (question->state == LLQ_Established)
10738 {
10739 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10740 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10741 }
10742
10743 SetNextQueryTime(m,q);
10744 }
10745 }
10746 }
10747
10748 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10749 {
10750 McastResolver **p = &m->McastResolvers;
10751 McastResolver *tmp = mDNSNULL;
10752
10753 if (!d) d = (const domainname *)"";
10754
10755 LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
10756
10757 mDNS_CheckLock(m);
10758
10759 while (*p) // Check if we already have this {interface, domain} tuple registered
10760 {
10761 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10762 {
10763 if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10764 (*p)->flags &= ~McastResolver_FlagDelete;
10765 tmp = *p;
10766 *p = tmp->next;
10767 tmp->next = mDNSNULL;
10768 }
10769 else
10770 p=&(*p)->next;
10771 }
10772
10773 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10774 else
10775 {
10776 // allocate, add to list
10777 *p = mDNSPlatformMemAllocate(sizeof(**p));
10778 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10779 else
10780 {
10781 (*p)->interface = interface;
10782 (*p)->flags = McastResolver_FlagNew;
10783 (*p)->timeout = timeout;
10784 AssignDomainName(&(*p)->domain, d);
10785 (*p)->next = mDNSNULL;
10786 }
10787 }
10788 return(*p);
10789 }
10790
10791 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10792 {
10793 mDNSs32 ptime = 0;
10794 if (server->penaltyTime != 0)
10795 {
10796 ptime = server->penaltyTime - m->timenow;
10797 if (ptime < 0)
10798 {
10799 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10800 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10801 // here
10802 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10803 ptime, server->penaltyTime, m->timenow);
10804 server->penaltyTime = 0;
10805 ptime = 0;
10806 }
10807 }
10808 return ptime;
10809 }
10810
10811 //Checks to see whether the newname is a better match for the name, given the best one we have
10812 //seen so far (given in bestcount).
10813 //Returns -1 if the newname is not a better match
10814 //Returns 0 if the newname is the same as the old match
10815 //Returns 1 if the newname is a better match
10816 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
10817 int bestcount)
10818 {
10819 // If the name contains fewer labels than the new server's domain or the new name
10820 // contains fewer labels than the current best, then it can't possibly be a better match
10821 if (namecount < newcount || newcount < bestcount) return -1;
10822
10823 // If there is no match, return -1 and the caller will skip this newname for
10824 // selection
10825 //
10826 // If we find a match and the number of labels is the same as bestcount, then
10827 // we return 0 so that the caller can do additional logic to pick one of
10828 // the best based on some other factors e.g., penaltyTime
10829 //
10830 // If we find a match and the number of labels is more than bestcount, then we
10831 // return 1 so that the caller can pick this over the old one.
10832 //
10833 // Note: newcount can either be equal or greater than bestcount beause of the
10834 // check above.
10835
10836 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
10837 return bestcount == newcount ? 0 : 1;
10838 else
10839 return -1;
10840 }
10841
10842 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10843 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10844 // names. In that case, we give a default timeout of 5 seconds
10845 #define DEFAULT_MCAST_TIMEOUT 5
10846 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
10847 {
10848 McastResolver *curmatch = mDNSNULL;
10849 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10850 McastResolver *curr;
10851 int bettermatch, currcount;
10852 for (curr = m->McastResolvers; curr; curr = curr->next)
10853 {
10854 currcount = CountLabels(&curr->domain);
10855 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10856 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10857 // the timeout value from the first one
10858 if (bettermatch == 1)
10859 {
10860 curmatch = curr;
10861 bestmatchlen = currcount;
10862 }
10863 }
10864 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
10865 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10866 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10867 }
10868
10869 // Returns true if it is a Domain Enumeration Query
10870 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
10871 {
10872 const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
10873 (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
10874 const domainname *d = qname;
10875 const mDNSu8 *label;
10876 int i = 0;
10877
10878 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10879 if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
10880
10881 label = (const mDNSu8 *)d;
10882 while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
10883 {
10884 if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
10885 i++;
10886 }
10887 if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
10888 {
10889 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
10890 return mDNSfalse;
10891 }
10892 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
10893
10894 // CountLabels already verified the number of labels
10895 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label
10896 label = (const mDNSu8 *)d;
10897 if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
10898 {
10899 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
10900 return(mDNSfalse);
10901 }
10902 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
10903
10904 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label
10905 label = (const mDNSu8 *)d;
10906 if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
10907 {
10908 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
10909 return(mDNSfalse);
10910 }
10911 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
10912
10913 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
10914
10915 return mDNStrue;
10916 }
10917
10918 // Note: InterfaceID is the InterfaceID of the question
10919 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
10920 {
10921 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
10922 // with "scoped" set to kScopeNone)
10923 //
10924 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
10925 // with "scoped" set to kScopeInterfaceId) and their InterfaceIDs should match.
10926 //
10927 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
10928 // with "scoped" set to kScopeServiceID) and their ServiceIDs should match.
10929 //
10930 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
10931 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
10932 //
10933 // If the first condition fails, following are the possible cases (the notes below are using
10934 // InterfaceID for discussion and the same holds good for ServiceID):
10935 //
10936 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
10937 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
10938 //
10939 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
10940 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
10941 // would fail in this case.
10942 //
10943 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
10944 // should match (Refer to (2) above).
10945 //
10946 // Note: mDNSInterface_Unicast is used only by .local unicast questions and are treated as unscoped.
10947 // If a question is scoped both to InterfaceID and ServiceID, the question will be scoped to InterfaceID.
10948
10949 if (((d->scoped == kScopeNone) && ((!InterfaceID && ServiceID == -1) || InterfaceID == mDNSInterface_Unicast)) ||
10950 ((d->scoped == kScopeInterfaceID) && d->interface == InterfaceID) ||
10951 ((d->scoped == kScopeServiceID) && d->serviceID == ServiceID))
10952 {
10953 return mDNStrue;
10954 }
10955 return mDNSfalse;
10956 }
10957
10958 // Sets all the Valid DNS servers for a question
10959 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
10960 {
10961 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10962 DNSServer *curr;
10963 int bettermatch, currcount;
10964 int index = 0;
10965 mDNSu32 timeout = 0;
10966 mDNSBool DEQuery;
10967
10968 question->validDNSServers = zeroOpaque128;
10969 DEQuery = DomainEnumQuery(&question->qname);
10970 for (curr = m->DNSServers; curr; curr = curr->next)
10971 {
10972 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
10973 // skip servers that will soon be deleted
10974 if (curr->flags & DNSServer_FlagDelete)
10975 {
10976 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
10977 continue;
10978 }
10979
10980 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
10981 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
10982 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
10983 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
10984 // match the scoped entries by mistake.
10985 //
10986 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
10987
10988 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
10989 if ((curr->scoped == kScopeInterfaceID && curr->interface == mDNSInterface_Any) || (curr->scoped == kScopeServiceID && curr->serviceID <= 0))
10990 {
10991 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);
10992 continue;
10993 }
10994
10995 currcount = CountLabels(&curr->domain);
10996 if ((!curr->cellIntf || (!DEQuery && !(question->flags & kDNSServiceFlagsDenyCellular))) &&
10997 (!curr->isExpensive || !(question->flags & kDNSServiceFlagsDenyExpensive)) &&
10998 DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
10999 {
11000 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
11001
11002 // If we found a better match (bettermatch == 1) then clear all the bits
11003 // corresponding to the old DNSServers that we have may set before and start fresh.
11004 // If we find an equal match, then include that DNSServer also by setting the corresponding
11005 // bit
11006 if ((bettermatch == 1) || (bettermatch == 0))
11007 {
11008 bestmatchlen = currcount;
11009 if (bettermatch)
11010 {
11011 debugf("SetValidDNSServers: Resetting all the bits");
11012 question->validDNSServers = zeroOpaque128;
11013 timeout = 0;
11014 }
11015 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11016 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
11017 curr->interface);
11018 timeout += curr->timeout;
11019 if (DEQuery)
11020 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->cellIntf);
11021 bit_set_opaque128(question->validDNSServers, index);
11022 }
11023 }
11024 index++;
11025 }
11026 question->noServerResponse = 0;
11027
11028 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x%x%x for question %p %##s (%s)",
11029 question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
11030 // If there are no matching resolvers, then use the default timeout value.
11031 // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
11032 return ((question->ProxyQuestion || question->ValidatingResponse) ? DEFAULT_UDNSSEC_TIMEOUT : timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
11033 }
11034
11035 // Get the Best server that matches a name. If you find penalized servers, look for the one
11036 // that will come out of the penalty box soon
11037 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits,
11038 int *selected, mDNSBool nameMatch)
11039 {
11040 DNSServer *curmatch = mDNSNULL;
11041 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
11042 DNSServer *curr;
11043 mDNSs32 bestPenaltyTime, currPenaltyTime;
11044 int bettermatch, currcount;
11045 int index = 0;
11046 int currindex = -1;
11047
11048 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
11049 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
11050 for (curr = m->DNSServers; curr; curr = curr->next)
11051 {
11052 // skip servers that will soon be deleted
11053 if (curr->flags & DNSServer_FlagDelete)
11054 {
11055 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
11056 continue;
11057 }
11058
11059 // Check if this is a valid DNSServer
11060 if (!bit_get_opaque64(validBits, index))
11061 {
11062 debugf("GetBestServer: continuing for index %d", index);
11063 index++;
11064 continue;
11065 }
11066
11067 currcount = CountLabels(&curr->domain);
11068 currPenaltyTime = PenaltyTimeForServer(m, curr);
11069
11070 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11071 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
11072
11073 // If there are multiple best servers for a given question, we will pick the first one
11074 // if none of them are penalized. If some of them are penalized in that list, we pick
11075 // the least penalized one. BetterMatchForName walks through all best matches and
11076 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11077 // in the list when there are no penalized servers and least one among them
11078 // when there are some penalized servers.
11079
11080 if (DNSServerMatch(curr, InterfaceID, ServiceID))
11081 {
11082
11083 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11084 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11085 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11086 // part and still do some redundant steps e.g., InterfaceID match
11087
11088 if (nameMatch)
11089 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
11090 else
11091 bettermatch = 0;
11092
11093 // If we found a better match (bettermatch == 1) then we don't need to
11094 // compare penalty times. But if we found an equal match, then we compare
11095 // the penalty times to pick a better match
11096
11097 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
11098 {
11099 currindex = index;
11100 curmatch = curr;
11101 bestmatchlen = currcount;
11102 bestPenaltyTime = currPenaltyTime;
11103 }
11104 }
11105 index++;
11106 }
11107 if (selected) *selected = currindex;
11108 return curmatch;
11109 }
11110
11111 // Look up a DNS Server, matching by name and InterfaceID
11112 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11113 {
11114 DNSServer *curmatch = mDNSNULL;
11115 char *ifname = mDNSNULL; // for logging purposes only
11116 mDNSOpaque128 allValid;
11117
11118 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
11119 InterfaceID = mDNSNULL;
11120
11121 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
11122
11123 // By passing in all ones, we make sure that every DNS server is considered
11124 allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF;
11125
11126 curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
11127
11128 if (curmatch != mDNSNULL)
11129 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
11130 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11131 InterfaceID, name);
11132 else
11133 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
11134
11135 return(curmatch);
11136 }
11137
11138 // Look up a DNS Server for a question within its valid DNSServer bits
11139 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
11140 {
11141 DNSServer *curmatch = mDNSNULL;
11142 char *ifname = mDNSNULL; // for logging purposes only
11143 mDNSInterfaceID InterfaceID = question->InterfaceID;
11144 const domainname *name = &question->qname;
11145 int currindex;
11146
11147 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
11148 InterfaceID = mDNSNULL;
11149
11150 if (InterfaceID)
11151 ifname = InterfaceNameForID(m, InterfaceID);
11152
11153 if (!mDNSOpaque128IsZero(&question->validDNSServers))
11154 {
11155 curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
11156 if (currindex != -1)
11157 bit_clr_opaque128(question->validDNSServers, currindex);
11158 }
11159
11160 if (curmatch != mDNSNULL)
11161 {
11162 LogInfo("GetServerForQuestion: %p DNS server (%p) %#a:%d (Penalty Time Left %d) (Scope %s:%p:%d) found for name %##s (%s)",
11163 question, curmatch, &curmatch->addr, mDNSVal16(curmatch->port),
11164 (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11165 InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
11166 }
11167 else
11168 {
11169 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p:%d) found for name %##s (%s)",
11170 question, ifname ? ifname : "None", InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
11171 }
11172
11173 return(curmatch);
11174 }
11175
11176
11177 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
11178 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
11179
11180 // Called in normal client context (lock not held)
11181 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
11182 {
11183 DNSQuestion *q;
11184 mDNS_Lock(m);
11185 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
11186 n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
11187 for (q = m->Questions; q; q=q->next)
11188 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
11189 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
11190 #if APPLE_OSX_mDNSResponder
11191 UpdateAutoTunnelDomainStatuses(m);
11192 #endif
11193 mDNS_Unlock(m);
11194 }
11195
11196 mDNSlocal mDNSBool IsPrivateDomain(mDNS *const m, DNSQuestion *q)
11197 {
11198 DomainAuthInfo *AuthInfo;
11199 // Skip Private domains as we have special addresses to get the hosts in the Private domain
11200 AuthInfo = GetAuthInfoForName_internal(m, &q->qname);
11201 if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
11202 {
11203 debugf("IsPrivateDomain: %##s true", q->qname.c);
11204 return mDNStrue;
11205 }
11206 else
11207 {
11208 debugf("IsPrivateDomain: %##s false", q->qname.c);
11209 return mDNSfalse;
11210 }
11211 }
11212
11213 // This function takes the DNSServer as a separate argument because sometimes the
11214 // caller has not yet assigned the DNSServer, but wants to evaluate the SuppressQuery
11215 // status before switching to it.
11216 mDNSlocal mDNSBool ShouldSuppressUnicastQuery(mDNS *const m, DNSQuestion *q, DNSServer *d)
11217 {
11218 // Some callers don't check for the qtype
11219 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
11220 {
11221 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
11222 return mDNSfalse;
11223 }
11224
11225 // Private domains are exempted irrespective of what the DNSServer says
11226 if (IsPrivateDomain(m, q))
11227 {
11228 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, Private Domain", q->qname.c, DNSTypeName(q->qtype));
11229 return mDNSfalse;
11230 }
11231
11232 if (!d)
11233 {
11234 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, as the DNS server is NULL", q->qname.c, DNSTypeName(q->qtype));
11235 return mDNStrue;
11236 }
11237
11238 // Check if the DNS Configuration allows A/AAAA queries to be sent
11239 if ((q->qtype == kDNSType_A) && (d->req_A))
11240 {
11241 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows A queries", q->qname.c,
11242 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
11243 return mDNSfalse;
11244 }
11245 if ((q->qtype == kDNSType_AAAA) && (d->req_AAAA))
11246 {
11247 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows AAAA queries", q->qname.c,
11248 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
11249 return mDNSfalse;
11250 }
11251 #if USE_DNS64
11252 if (DNS64IsQueryingARecord(q->dns64.state))
11253 {
11254 LogInfo("ShouldSuppressUnicastQuery: DNS64 query not suppressed for %##s, qtype %s", q->qname.c, DNSTypeName(q->qtype));
11255 return mDNSfalse;
11256 }
11257 #endif
11258
11259 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, since DNS Configuration does not allow (req_A is %s and req_AAAA is %s)",
11260 q->qname.c, DNSTypeName(q->qtype), d->req_A ? "true" : "false", d->req_AAAA ? "true" : "false");
11261
11262 return mDNStrue;
11263 }
11264
11265 mDNSlocal mDNSBool ShouldSuppressDotLocalQuery(mDNS *const m, DNSQuestion *q)
11266 {
11267 NetworkInterfaceInfo *intf;
11268 AuthRecord *rr;
11269 mDNSBool ret;
11270
11271 // Check to see if there is at least one interface other than loopback and don't suppress
11272 // .local questions if you find one. If we have at least one interface, it means that
11273 // we can send unicast queries for the .local name and we don't want to suppress
11274 // multicast in that case as upper layers don't know how to handle if we return a
11275 // negative response for multicast followed by a positive response for unicast.
11276 //
11277 // Note: we used to check for multicast capable interfaces instead of just any interface
11278 // present. That did not work in the case where we have a valid interface for unicast
11279 // but not multicast capable e.g., cellular, as we ended up delivering a negative response
11280 // first and the upper layer did not wait for the positive response that came later.
11281 for (intf = m->HostInterfaces; intf; intf = intf->next)
11282 {
11283 if (intf->InterfaceActive && !intf->Loopback)
11284 {
11285 LogInfo("ShouldSuppressDotLocalQuery: Found interface %s, not suppressing", intf->ifname);
11286 return mDNSfalse;
11287 }
11288 }
11289
11290 // 1. If we find a LocalOnly or P2P record answering this question, then don't suppress it.
11291 // Set m->CurrentQuestion as it is required by AnswerQuestionWithLORecord.
11292 m->CurrentQuestion = q;
11293 ret = AnswerQuestionWithLORecord(m, q, mDNStrue);
11294 m->CurrentQuestion = mDNSNULL;
11295
11296 if (ret)
11297 {
11298 LogInfo("ShouldSuppressDotLocalQuery: Found LocalOnly record for %##s (%s), not suppressing", q->qname.c,
11299 DNSTypeName(q->qtype));
11300 return mDNSfalse;
11301 }
11302
11303 // 2. If we find a local AuthRecord answering this question, then don't suppress it.
11304 for (rr = m->ResourceRecords; rr; rr = rr->next)
11305 {
11306 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
11307 {
11308 LogInfo("ShouldSuppressDotLocalQuery: Found resource record %s for %##s (%s) not suppressing", ARDisplayString(m, rr),
11309 q->qname.c, DNSTypeName(q->qtype));
11310 return mDNSfalse;
11311 }
11312 }
11313 return mDNStrue;
11314 }
11315
11316 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, DNSQuestion *q)
11317 {
11318 if (q->InterfaceID == mDNSInterface_LocalOnly)
11319 {
11320 LogInfo("ShouldSuppressQuery: LocalOnly query not suppressed for %##s, qtype %s", q->qname.c, DNSTypeName(q->qtype));
11321 return mDNSfalse;
11322 }
11323
11324 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
11325 {
11326 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
11327 return mDNSfalse;
11328 }
11329
11330 // We still want the ability to be able to listen to the local services and hence
11331 // don't fail .local query if we have local records that can potentially answer
11332 // the question.
11333 if (q->InterfaceID != mDNSInterface_Unicast && IsLocalDomain(&q->qname))
11334 {
11335 if (!ShouldSuppressDotLocalQuery(m, q))
11336 {
11337 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11338 return mDNSfalse;
11339 }
11340 else
11341 {
11342 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11343 return mDNStrue;
11344 }
11345 }
11346
11347 return (ShouldSuppressUnicastQuery(m, q, q->qDNSServer));
11348 }
11349
11350 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11351 {
11352 CacheRecord *rr;
11353 CacheGroup *cg;
11354
11355 cg = CacheGroupForName(m, q->qnamehash, &q->qname);
11356 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
11357 {
11358 // Don't deliver RMV events for negative records
11359 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
11360 {
11361 LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
11362 CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
11363 continue;
11364 }
11365
11366 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
11367 {
11368 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11369 q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
11370
11371 q->CurrentAnswers--;
11372 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11373 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11374
11375 if (rr->CRActiveQuestion == q)
11376 {
11377 DNSQuestion *qptr;
11378 // If this was the active question for this cache entry, it was the one that was
11379 // responsible for keeping the cache entry fresh when the cache entry was reaching
11380 // its expiry. We need to handover the responsibility to someone else. Otherwise,
11381 // when the cache entry is about to expire, we won't find an active question
11382 // (pointed by CRActiveQuestion) to refresh the cache.
11383 for (qptr = m->Questions; qptr; qptr=qptr->next)
11384 if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
11385 break;
11386
11387 if (qptr)
11388 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
11389 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
11390 qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
11391
11392 rr->CRActiveQuestion = qptr; // Question used to be active; new value may or may not be null
11393 if (!qptr) m->rrcache_active--; // If no longer active, decrement rrcache_active count
11394 }
11395 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
11396 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
11397 }
11398 }
11399 }
11400
11401 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11402 {
11403 DNSQuestion *q;
11404 for (q = m->NewQuestions; q; q = q->next)
11405 if (q == question) return mDNStrue;
11406 return mDNSfalse;
11407 }
11408
11409 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11410 {
11411 AuthRecord *rr;
11412 AuthGroup *ag;
11413
11414 if (m->CurrentQuestion)
11415 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11416 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11417
11418 if (IsQuestionNew(m, q))
11419 {
11420 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11421 return mDNStrue;
11422 }
11423 m->CurrentQuestion = q;
11424 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
11425 if (ag)
11426 {
11427 for (rr = ag->members; rr; rr=rr->next)
11428 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11429 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11430 {
11431 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11432 ARDisplayString(m, rr));
11433 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11434 {
11435 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11436 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11437 q->CurrentAnswers, q->LOAddressAnswers);
11438 continue;
11439 }
11440 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again
11441 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11442 }
11443 }
11444 m->CurrentQuestion = mDNSNULL;
11445 return mDNStrue;
11446 }
11447
11448 // Returns false if the question got deleted while delivering the RMV events
11449 // The caller should handle the case
11450 mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11451 {
11452 if (m->CurrentQuestion)
11453 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11454 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11455
11456 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11457 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11458 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11459 {
11460 m->CurrentQuestion = q;
11461 CacheRecordRmvEventsForCurrentQuestion(m, q);
11462 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11463 m->CurrentQuestion = mDNSNULL;
11464 }
11465 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11466 return mDNStrue;
11467 }
11468
11469 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11470 {
11471 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11472 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11473 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11474 if (q->SuppressQuery)
11475 {
11476 q->SuppressQuery = mDNSfalse;
11477 if (!CacheRecordRmvEventsForQuestion(m, q))
11478 {
11479 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from cache");
11480 return;
11481 }
11482 q->SuppressQuery = mDNStrue;
11483 }
11484
11485 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11486 // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
11487 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11488 // the restart will not be a duplicate ADD
11489 if (!LocalRecordRmvEventsForQuestion(m, q))
11490 {
11491 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords");
11492 return;
11493 }
11494
11495 // There are two cases here.
11496 //
11497 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11498 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11499 // because when we get the response, if we had entries in the cache already, it will not answer
11500 // this question if the cache entry did not change. Hence, we need to restart
11501 // the query so that it can be answered from the cache.
11502 //
11503 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11504 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11505 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
11506 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11507 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
11508 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11509 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11510 // This affects both efficiency and also the current design where there is only one active question
11511 // pointed to from a cache entry.
11512 //
11513 // We restart queries in a two step process by first calling stop and build a temporary list which we
11514 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11515 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11516 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11517 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11518 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11519 //
11520 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11521
11522 LogInfo("SuppressStatusChanged: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11523 mDNS_StopQuery_internal(m, q);
11524 q->next = *restart;
11525 *restart = q;
11526 }
11527
11528 // The caller should hold the lock
11529 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11530 {
11531 DNSQuestion *q;
11532 DNSQuestion *restart = mDNSNULL;
11533
11534 // We look through all questions including new questions. During network change events,
11535 // we potentially restart questions here in this function that ends up as new questions,
11536 // which may be suppressed at this instance. Before it is handled we get another network
11537 // event that changes the status e.g., address becomes available. If we did not process
11538 // new questions, we would never change its SuppressQuery status.
11539 //
11540 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11541 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11542 // *any* other question which could be the next one that we may process here. RestartQuestion
11543 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11544 // if the "next" question is stopped while the CurrentQuestion is stopped
11545 if (m->RestartQuestion)
11546 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11547 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11548 m->RestartQuestion = m->Questions;
11549 while (m->RestartQuestion)
11550 {
11551 q = m->RestartQuestion;
11552 m->RestartQuestion = q->next;
11553 if (q->SuppressUnusable)
11554 {
11555 mDNSBool old = q->SuppressQuery;
11556 q->SuppressQuery = ShouldSuppressQuery(m, q);
11557 if (q->SuppressQuery != old)
11558 {
11559 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11560 // followed by a negative cache response. Temporarily turn off suppression so that
11561 // AnswerCurrentQuestionWithResourceRecord can answer the question
11562 SuppressStatusChanged(m, q, &restart);
11563 }
11564 }
11565 }
11566 while (restart)
11567 {
11568 q = restart;
11569 restart = restart->next;
11570 q->next = mDNSNULL;
11571 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11572 mDNS_StartQuery_internal(m, q);
11573 }
11574 }
11575
11576 mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11577 {
11578 DNSQuestion *q;
11579 DNSQuestion *restart = mDNSNULL;
11580
11581 if (m->RestartQuestion)
11582 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11583 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11584 m->RestartQuestion = m->Questions;
11585 while (m->RestartQuestion)
11586 {
11587 q = m->RestartQuestion;
11588 m->RestartQuestion = q->next;
11589 if (q->Restart)
11590 {
11591 if (mDNSOpaque16IsZero(q->TargetQID))
11592 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11593
11594 q->Restart = 0;
11595 SuppressStatusChanged(m, q, &restart);
11596 }
11597 }
11598 while (restart)
11599 {
11600 q = restart;
11601 restart = restart->next;
11602 q->next = mDNSNULL;
11603 LogInfo("RestartUnicastQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11604 mDNS_StartQuery_internal(m, q);
11605 }
11606 }
11607
11608
11609 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11610 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11611 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11612 {
11613
11614 if (question->Target.type && !ValidQuestionTarget(question))
11615 {
11616 LogMsg("ValidateParameters: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
11617 question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
11618 question->Target.type = mDNSAddrType_None;
11619 }
11620
11621 // If no question->Target specified, clear TargetPort
11622 if (!question->Target.type)
11623 question->TargetPort = zeroIPPort;
11624
11625 if (!ValidateDomainName(&question->qname))
11626 {
11627 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11628 return(mStatus_Invalid);
11629 }
11630
11631 // If this question is referencing a specific interface, verify it exists
11632 if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID) && question->InterfaceID != mDNSInterface_Unicast)
11633 {
11634 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11635 if (!intf)
11636 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11637 (uint32_t)question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
11638 }
11639
11640 return(mStatus_NoError);
11641 }
11642
11643 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11644 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
11645 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11646 {
11647 // First reset all DNS Configuration
11648 question->qDNSServer = mDNSNULL;
11649 question->validDNSServers = zeroOpaque128;
11650 question->triedAllServersOnce = 0;
11651 question->noServerResponse = 0;
11652 question->StopTime = (question->TimeoutQuestion) ? question->StopTime : 0;
11653 #if AWD_METRICS
11654 mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
11655 #endif
11656
11657 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11658 if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion)
11659 return;
11660 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11661 if (!mDNSOpaque16IsZero(question->TargetQID))
11662 {
11663 mDNSu32 timeout = SetValidDNSServers(m, question);
11664 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11665 // So if a question is restarted when a network change occurs, the StopTime is not reset.
11666 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11667 // it gets a full timeout value even if the original question times out earlier.
11668 if (question->TimeoutQuestion && !question->StopTime)
11669 {
11670 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11671 LogInfo("InitDNSConfig: Setting StopTime on the uDNS question %p %##s (%s)", question, question->qname.c, DNSTypeName(question->qtype));
11672 }
11673
11674 question->qDNSServer = GetServerForQuestion(m, question);
11675 LogInfo("InitDNSConfig: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
11676 question, question->qname.c, DNSTypeName(question->qtype), timeout,
11677 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11678 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11679 }
11680 else if (question->TimeoutQuestion && !question->StopTime)
11681 {
11682 // If the question is to be timed out and its a multicast, local-only or P2P case,
11683 // then set it's stop time.
11684 mDNSu32 timeout = LocalOnlyOrP2PInterface(question->InterfaceID) ?
11685 DEFAULT_LO_OR_P2P_TIMEOUT : GetTimeoutForMcastQuestion(m, question);
11686 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11687 LogInfo("InitDNSConfig: Setting StopTime on question %p %##s (%s)", question, question->qname.c, DNSTypeName(question->qtype));
11688 }
11689 // Set StopTime here since it is a part of DNS Configuration
11690 if (question->StopTime)
11691 SetNextQueryStopTime(m, question);
11692 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11693 // will never be transmitted on the wire.
11694 if (!(LocalOnlyOrP2PInterface(question->InterfaceID)))
11695 SetNextQueryTime(m,question);
11696 }
11697
11698 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11699 // state fields of the DNS Question. These are independent of the Client layer.
11700 mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question)
11701 {
11702 int i;
11703 mDNSBool isBlocked = mDNSfalse;
11704
11705 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11706 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11707 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11708 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11709 // that to go out immediately.
11710 question->next = mDNSNULL;
11711 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11712 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11713 // the question list to check if ThisQInterval is negative which means the question has been
11714 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11715 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11716 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11717 // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11718 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
11719 question->qnamehash = DomainNameHashValue(&question->qname);
11720 question->DelayAnswering = mDNSOpaque16IsZero(question->TargetQID) ? CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash) : 0;
11721 question->LastQTime = m->timenow;
11722 question->ExpectUnicastResp = 0;
11723 question->LastAnswerPktNum = m->PktNum;
11724 question->RecentAnswerPkts = 0;
11725 question->CurrentAnswers = 0;
11726
11727 #if APPLE_OSX_mDNSResponder
11728
11729 // Initial browse threshold used by Finder.
11730 #define mDNSFinderBrowseThreshold 20
11731
11732 // Set the threshold at which we move to a passive browse state,
11733 // not actively sending queries.
11734 if (question->flags & kDNSServiceFlagsThresholdOne)
11735 question->BrowseThreshold = 1;
11736 else if (question->flags & kDNSServiceFlagsThresholdFinder)
11737 question->BrowseThreshold = mDNSFinderBrowseThreshold;
11738 else
11739 question->BrowseThreshold = 0;
11740
11741 #else // APPLE_OSX_mDNSResponder
11742 question->BrowseThreshold = 0;
11743 #endif // APPLE_OSX_mDNSResponder
11744 question->CachedAnswerNeedsUpdate = mDNSfalse;
11745
11746 question->LargeAnswers = 0;
11747 question->UniqueAnswers = 0;
11748 question->LOAddressAnswers = 0;
11749 question->FlappingInterface1 = mDNSNULL;
11750 question->FlappingInterface2 = mDNSNULL;
11751
11752 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11753 // since we would already have the question->ServiceID in that case.
11754 if (!(question->flags & kDNSServiceFlagsServiceIndex))
11755 {
11756 #if APPLE_OSX_mDNSResponder
11757 mDNSPlatformGetDNSRoutePolicy(question, &isBlocked);
11758 #else
11759 question->ServiceID = -1;
11760 #endif
11761 }
11762 else
11763 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
11764 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
11765
11766 InitDNSConfig(m, question);
11767
11768 question->AuthInfo = GetAuthInfoForQuestion(m, question);
11769 question->SuppressQuery = 0;
11770 if (question->SuppressUnusable)
11771 question->SuppressQuery = ShouldSuppressQuery(m, question);
11772
11773 // If ServiceID is 0 or the policy disallows making DNS requests,
11774 // set DisallowPID
11775 question->DisallowPID = (question->ServiceID == 0 || isBlocked);
11776 if (question->DisallowPID)
11777 LogInfo("InitCommonState: Query suppressed for %##s (%s), PID %d/ServiceID %d not allowed", question->qname.c,
11778 DNSTypeName(question->qtype), question->pid, question->ServiceID);
11779
11780 question->NextInDQList = mDNSNULL;
11781 question->SendQNow = mDNSNULL;
11782 question->SendOnAll = mDNSfalse;
11783 question->RequestUnicast = kDefaultRequestUnicastCount;
11784
11785 #if APPLE_OSX_mDNSResponder
11786 // Set the QU bit in the first query for the following options.
11787 if ((question->flags & kDNSServiceFlagsUnicastResponse) || (question->flags & kDNSServiceFlagsThresholdFinder))
11788 {
11789 question->RequestUnicast = SET_QU_IN_FIRST_QUERY;
11790 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11791 DNSTypeName(question->qtype));
11792 }
11793 #endif // APPLE_OSX_mDNSResponder
11794
11795 question->LastQTxTime = m->timenow;
11796 question->CNAMEReferrals = 0;
11797
11798 question->WakeOnResolveCount = 0;
11799 if (question->WakeOnResolve)
11800 {
11801 question->WakeOnResolveCount = InitialWakeOnResolveCount;
11802 }
11803
11804 for (i=0; i<DupSuppressInfoSize; i++)
11805 question->DupSuppress[i].InterfaceID = mDNSNULL;
11806
11807 question->Restart = 0;
11808
11809 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11810 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11811 NextQSendTime(question) - m->timenow,
11812 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11813 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11814
11815 if (question->DelayAnswering)
11816 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11817 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11818 }
11819
11820 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11821 mDNSlocal void InitWABState(DNSQuestion *const question)
11822 {
11823 // We'll create our question->LocalSocket on demand, if needed.
11824 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11825 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11826 // NAT mapping for receiving inbound add/remove events.
11827 question->LocalSocket = mDNSNULL;
11828 question->unansweredQueries = 0;
11829 question->nta = mDNSNULL;
11830 question->servAddr = zeroAddr;
11831 question->servPort = zeroIPPort;
11832 question->tcp = mDNSNULL;
11833 question->NoAnswer = NoAnswer_Normal;
11834 }
11835
11836 mDNSlocal void InitLLQNATState(mDNS *const m)
11837 {
11838 // If we don't have our NAT mapping active, start it now
11839 if (!m->LLQNAT.clientCallback)
11840 {
11841 m->LLQNAT.Protocol = NATOp_MapUDP;
11842 m->LLQNAT.IntPort = m->UnicastPort4;
11843 m->LLQNAT.RequestedPort = m->UnicastPort4;
11844 m->LLQNAT.clientCallback = LLQNATCallback;
11845 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal just started
11846 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11847 }
11848 }
11849
11850 mDNSlocal void InitLLQState(DNSQuestion *const question)
11851 {
11852 question->state = LLQ_InitialRequest;
11853 question->ReqLease = 0;
11854 question->expire = 0;
11855 question->ntries = 0;
11856 question->id = zeroOpaque64;
11857 }
11858
11859 #ifdef DNS_PUSH_ENABLED
11860 mDNSlocal void InitDNSPNState(DNSQuestion *const question)
11861 {
11862 question->dnsPushState = DNSPUSH_INIT;
11863 }
11864 #endif // DNS_PUSH_ENABLED
11865
11866 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11867 // DNSSEC & DNS Proxy fields of the DNS Question.
11868 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11869 {
11870 (void) m;
11871
11872 // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11873 // or the request is going over cellular interface.
11874 //
11875 // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11876 // at ValidationRequired setting also.
11877 if (question->qDNSServer)
11878 {
11879 if (question->qDNSServer->cellIntf)
11880 {
11881 debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question->qname.c, DNSTypeName(question->qtype));
11882 question->ValidationRequired = mDNSfalse;
11883 }
11884 if (DNSSECOptionalQuestion(question) && !(question->qDNSServer->req_DO))
11885 {
11886 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
11887 question->qname.c, DNSTypeName(question->qtype));
11888 question->ValidationRequired = DNSSEC_VALIDATION_NONE;
11889 }
11890 }
11891 question->ValidationState = (question->ValidationRequired ? DNSSECValRequired : DNSSECValNotRequired);
11892 question->ValidationStatus = 0;
11893 question->responseFlags = zeroID;
11894 }
11895
11896 // Once the question is completely initialized including the duplicate logic, this function
11897 // is called to finalize the unicast question which requires flushing the cache if needed,
11898 // activating the query etc.
11899 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question)
11900 {
11901 // Ensure DNS related info of duplicate question is same as the orig question
11902 if (question->DuplicateOf)
11903 {
11904 question->validDNSServers = question->DuplicateOf->validDNSServers;
11905 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11906 // then we log a line as it could indicate an issue
11907 if (question->DuplicateOf->qDNSServer == mDNSNULL)
11908 {
11909 if (question->qDNSServer)
11910 LogInfo("FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(%#a:%d) but original question(%p) has no DNS Server! %##s (%s)",
11911 question, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11912 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort),
11913 question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype));
11914 }
11915 question->qDNSServer = question->DuplicateOf->qDNSServer;
11916 LogInfo("FinalizeUnicastQuestion: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
11917 question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype),
11918 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11919 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11920 }
11921
11922 ActivateUnicastQuery(m, question, mDNSfalse);
11923
11924 if (!question->DuplicateOf && DNSSECQuestion(question))
11925 {
11926 // For DNSSEC questions, we need to have the RRSIGs also for verification.
11927 CheckForDNSSECRecords(m, question);
11928 }
11929 if (question->LongLived)
11930 {
11931 // Unlike other initializations, InitLLQNATState should be done after
11932 // we determine that it is a unicast question. LongLived is set for
11933 // both multicast and unicast browse questions but we should initialize
11934 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11935 // start the NAT traversal that is not needed.
11936 InitLLQNATState(m);
11937 #if APPLE_OSX_mDNSResponder
11938 UpdateAutoTunnelDomainStatuses(m);
11939 #endif
11940 }
11941 }
11942
11943 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
11944 {
11945 DNSQuestion **q;
11946 mStatus vStatus;
11947
11948 // First check for cache space (can't do queries if there is no cache space allocated)
11949 if (m->rrcache_size == 0)
11950 return(mStatus_NoCache);
11951
11952 vStatus = ValidateParameters(m, question);
11953 if (vStatus)
11954 return(vStatus);
11955
11956 #ifdef USE_LIBIDN
11957 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
11958 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
11959 if (IsHighASCIILabel(LastLabel(&question->qname)))
11960 {
11961 domainname newname;
11962 if (PerformNextPunycodeConversion(question, &newname))
11963 AssignDomainName(&question->qname, &newname);
11964 }
11965 #endif // USE_LIBIDN
11966
11967 question->TargetQID =
11968 #ifndef UNICAST_DISABLED
11969 (question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
11970 #endif // UNICAST_DISABLED
11971 zeroID;
11972 debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11973
11974 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
11975 q = &m->Questions;
11976 if (LocalOnlyOrP2PInterface(question->InterfaceID))
11977 q = &m->LocalOnlyQuestions;
11978 while (*q && *q != question)
11979 q=&(*q)->next;
11980
11981 if (*q)
11982 {
11983 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
11984 question->qname.c, DNSTypeName(question->qtype), question);
11985 return(mStatus_AlreadyRegistered);
11986 }
11987 *q = question;
11988
11989 // Intialize the question. The only ordering constraint we have today is that
11990 // InitDNSSECProxyState should be called after the DNS server is selected (in
11991 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
11992 // validation.
11993
11994 InitCommonState(m, question);
11995 InitWABState(question);
11996 InitLLQState(question);
11997 #ifdef DNS_PUSH_ENABLED
11998 InitDNSPNState(question);
11999 #endif // DNS_PUSH_ENABLED
12000 InitDNSSECProxyState(m, question);
12001
12002 // FindDuplicateQuestion should be called last after all the intialization
12003 // as the duplicate logic could be potentially based on any field in the
12004 // question.
12005 question->DuplicateOf = FindDuplicateQuestion(m, question);
12006 if (question->DuplicateOf)
12007 question->AuthInfo = question->DuplicateOf->AuthInfo;
12008
12009 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12010 {
12011 if (!m->NewLocalOnlyQuestions)
12012 m->NewLocalOnlyQuestions = question;
12013 }
12014 else
12015 {
12016 if (!m->NewQuestions)
12017 m->NewQuestions = question;
12018
12019 // If the question's id is non-zero, then it's Wide Area
12020 // MUST NOT do this Wide Area setup until near the end of
12021 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12022 // NS, etc.) and if we haven't finished setting up our own question and setting
12023 // m->NewQuestions if necessary then we could end up recursively re-entering
12024 // this routine with the question list data structures in an inconsistent state.
12025 if (!mDNSOpaque16IsZero(question->TargetQID))
12026 {
12027 FinalizeUnicastQuestion(m, question);
12028 }
12029 else
12030 {
12031 #if BONJOUR_ON_DEMAND
12032 m->NumAllInterfaceQuestions++;
12033 LogInfo("mDNS_StartQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
12034 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
12035 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12036 {
12037 m->NextBonjourDisableTime = 0;
12038 if (m->BonjourEnabled == 0)
12039 {
12040 // Enable Bonjour immediately by scheduling network changed processing where
12041 // we will join the multicast group on each active interface.
12042 m->BonjourEnabled = 1;
12043 m->NetworkChanged = m->timenow;
12044 }
12045 }
12046 #endif // BONJOUR_ON_DEMAND
12047 if (question->WakeOnResolve)
12048 {
12049 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
12050 mDNS_PurgeBeforeResolve(m, question);
12051 }
12052 }
12053 }
12054
12055 return(mStatus_NoError);
12056 }
12057
12058 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12059 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
12060 {
12061 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
12062 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12063 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12064 // call it again
12065 if (nta->question.ThisQInterval != -1)
12066 {
12067 mDNS_StopQuery_internal(m, &nta->question);
12068 if (nta->question.ThisQInterval != -1)
12069 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
12070 }
12071 mDNSPlatformMemFree(nta);
12072 }
12073
12074 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
12075 {
12076 CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12077 CacheRecord *rr;
12078 DNSQuestion **qp = &m->Questions;
12079
12080 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12081
12082 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12083 qp = &m->LocalOnlyQuestions;
12084 while (*qp && *qp != question) qp=&(*qp)->next;
12085 if (*qp) *qp = (*qp)->next;
12086 else
12087 {
12088 #if !ForceAlerts
12089 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
12090 #endif
12091 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
12092 return(mStatus_BadReferenceErr);
12093 }
12094
12095 #if BONJOUR_ON_DEMAND
12096 if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID))
12097 {
12098 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12099 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
12100 m->NumAllInterfaceQuestions--;
12101 LogInfo("mDNS_StopQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
12102 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
12103 }
12104 #endif // BONJOUR_ON_DEMAND
12105
12106 #if AWD_METRICS
12107 if (Question_uDNS(question) && !question->metrics.answered && (question->metrics.querySendCount > 0))
12108 {
12109 const domainname * queryName;
12110 mDNSBool isForCell;
12111 mDNSu32 durationMs;
12112
12113 queryName = question->metrics.originalQName ? question->metrics.originalQName : &question->qname;
12114 isForCell = (question->qDNSServer && question->qDNSServer->cellIntf);
12115 durationMs = ((m->timenow - question->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
12116 MetricsUpdateDNSQueryStats(queryName, question->qtype, mDNSNULL, question->metrics.querySendCount, durationMs, isForCell);
12117 }
12118 #endif
12119 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12120 UpdateQuestionDuplicates(m, question);
12121 // But don't trash ThisQInterval until afterwards.
12122 question->ThisQInterval = -1;
12123
12124 // If there are any cache records referencing this as their active question, then see if there is any
12125 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12126 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
12127 {
12128 if (rr->CRActiveQuestion == question)
12129 {
12130 DNSQuestion *q;
12131 DNSQuestion *replacement = mDNSNULL;
12132 // If we find an active question that is answered by this cached record, use it as the cache record's
12133 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12134 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12135 // via CacheRecordRmv() when the cache record expires.
12136 for (q = m->Questions; q && (q != m->NewQuestions); q = q->next)
12137 {
12138 if (!q->DuplicateOf && !QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
12139 {
12140 if (q->ThisQInterval > 0)
12141 {
12142 replacement = q;
12143 break;
12144 }
12145 else if (!replacement)
12146 {
12147 replacement = q;
12148 }
12149 }
12150 }
12151 if (replacement)
12152 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12153 "CurrentAnswers %d, SuppressQuery %d", replacement, CRDisplayString(m,rr), question->CurrentAnswers, replacement->CurrentAnswers, replacement->SuppressQuery);
12154 rr->CRActiveQuestion = replacement; // Question used to be active; new value may or may not be null
12155 if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count
12156 }
12157 }
12158
12159 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12160 // bump its pointer forward one question.
12161 if (m->CurrentQuestion == question)
12162 {
12163 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12164 question->qname.c, DNSTypeName(question->qtype));
12165 m->CurrentQuestion = question->next;
12166 }
12167
12168 if (m->NewQuestions == question)
12169 {
12170 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12171 question->qname.c, DNSTypeName(question->qtype));
12172 m->NewQuestions = question->next;
12173 }
12174
12175 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
12176
12177 if (m->RestartQuestion == question)
12178 {
12179 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12180 question->qname.c, DNSTypeName(question->qtype));
12181 m->RestartQuestion = question->next;
12182 }
12183
12184 if (m->ValidationQuestion == question)
12185 {
12186 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
12187 question->qname.c, DNSTypeName(question->qtype));
12188 m->ValidationQuestion = question->next;
12189 }
12190
12191 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12192 question->next = mDNSNULL;
12193
12194 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12195
12196 // And finally, cancel any associated GetZoneData operation that's still running.
12197 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12198 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12199 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12200 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12201 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
12202 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
12203 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
12204 {
12205 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12206 DNSQuestion *q;
12207 for (q = m->Questions; q; q=q->next)
12208 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
12209 if (!q)
12210 {
12211 if (!m->LLQNAT.clientCallback) // Should never happen, but just in case...
12212 {
12213 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12214 }
12215 else
12216 {
12217 LogInfo("Stopping LLQNAT");
12218 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
12219 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
12220 }
12221 }
12222
12223 // If necessary, tell server it can delete this LLQ state
12224 if (question->state == LLQ_Established)
12225 {
12226 question->ReqLease = 0;
12227 sendLLQRefresh(m, question);
12228 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12229 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12230 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12231 // we let that run out its natural course and complete asynchronously.
12232 if (question->tcp)
12233 {
12234 question->tcp->question = mDNSNULL;
12235 question->tcp = mDNSNULL;
12236 }
12237 }
12238 #ifdef DNS_PUSH_ENABLED
12239 else if (question->dnsPushState == DNSPUSH_ESTABLISHED)
12240 {
12241 if (question->tcp)
12242 {
12243 UnSubscribeToDNSPushNotificationServer(m, q);
12244 question->tcp->question = mDNSNULL;
12245 question->tcp = mDNSNULL;
12246 }
12247 }
12248 #endif // DNS_PUSH_ENABLED
12249 #if APPLE_OSX_mDNSResponder
12250 UpdateAutoTunnelDomainStatuses(m);
12251 #endif
12252 }
12253 // wait until we send the refresh above which needs the nta
12254 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
12255
12256 if (question->ValidationRequired && question->DNSSECAuthInfo)
12257 {
12258 LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question->qname.c);
12259 question->DAIFreeCallback(m, question->DNSSECAuthInfo);
12260 question->DNSSECAuthInfo = mDNSNULL;
12261 }
12262 if (question->AnonInfo)
12263 {
12264 FreeAnonInfo(question->AnonInfo);
12265 question->AnonInfo = mDNSNULL;
12266 }
12267 #if AWD_METRICS
12268 if (question->metrics.originalQName)
12269 {
12270 mDNSPlatformMemFree(question->metrics.originalQName);
12271 question->metrics.originalQName = mDNSNULL;
12272 }
12273 #endif
12274
12275 #if USE_DNS64
12276 DNS64ResetState(question);
12277 #endif
12278
12279 return(mStatus_NoError);
12280 }
12281
12282 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
12283 {
12284 mStatus status;
12285 mDNS_Lock(m);
12286 status = mDNS_StartQuery_internal(m, question);
12287 mDNS_Unlock(m);
12288 return(status);
12289 }
12290
12291 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
12292 {
12293 mStatus status;
12294 mDNS_Lock(m);
12295 status = mDNS_StopQuery_internal(m, question);
12296 mDNS_Unlock(m);
12297 return(status);
12298 }
12299
12300 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12301 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12302 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12303 // specifically to catch and report if the client callback does try to make API calls
12304 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
12305 {
12306 mStatus status;
12307 DNSQuestion *qq;
12308 mDNS_Lock(m);
12309
12310 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12311 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
12312
12313 status = mDNS_StopQuery_internal(m, question);
12314 if (status == mStatus_NoError && !qq)
12315 {
12316 const CacheRecord *rr;
12317 CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12318 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12319 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
12320 if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
12321 {
12322 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12323 if (question->QuestionCallback)
12324 question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
12325 }
12326 }
12327 mDNS_Unlock(m);
12328 return(status);
12329 }
12330
12331 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
12332 {
12333 mStatus status;
12334 mDNS_Lock(m);
12335 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12336 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
12337 mDNS_Unlock(m);
12338 return(status);
12339 }
12340
12341 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
12342 {
12343 mStatus status = mStatus_BadReferenceErr;
12344 CacheRecord *cr;
12345 mDNS_Lock(m);
12346 cr = FindIdenticalRecordInCache(m, rr);
12347 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
12348 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12349 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
12350 mDNS_Unlock(m);
12351 return(status);
12352 }
12353
12354 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
12355 const domainname *const srv, const domainname *const domain,
12356 const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12357 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12358 mDNSQuestionCallback *Callback, void *Context)
12359 {
12360 question->InterfaceID = InterfaceID;
12361 question->flags = flags;
12362 question->Target = zeroAddr;
12363 question->qtype = kDNSType_PTR;
12364 question->qclass = kDNSClass_IN;
12365 question->LongLived = mDNStrue;
12366 question->ExpectUnique = mDNSfalse;
12367 question->ForceMCast = ForceMCast;
12368 question->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
12369 question->SuppressUnusable = mDNSfalse;
12370 question->SearchListIndex = 0;
12371 question->AppendSearchDomains = 0;
12372 question->RetryWithSearchDomains = mDNSfalse;
12373 question->TimeoutQuestion = 0;
12374 question->WakeOnResolve = 0;
12375 question->UseBackgroundTrafficClass = useBackgroundTrafficClass;
12376 question->ValidationRequired = 0;
12377 question->ValidatingResponse = 0;
12378 question->ProxyQuestion = 0;
12379 question->qnameOrig = mDNSNULL;
12380 question->AnonInfo = mDNSNULL;
12381 question->QuestionCallback = Callback;
12382 question->QuestionContext = Context;
12383
12384 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
12385 return(mStatus_BadParamErr);
12386
12387 if (anondata)
12388 {
12389 question->AnonInfo = AllocateAnonInfo(&question->qname, anondata, mDNSPlatformStrLen(anondata), mDNSNULL);
12390 if (!question->AnonInfo)
12391 return(mStatus_BadParamErr);
12392 }
12393
12394 return(mDNS_StartQuery_internal(m, question));
12395 }
12396
12397 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
12398 const domainname *const srv, const domainname *const domain,
12399 const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12400 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12401 mDNSQuestionCallback *Callback, void *Context)
12402 {
12403 mStatus status;
12404 mDNS_Lock(m);
12405 status = mDNS_StartBrowse_internal(m, question, srv, domain, anondata, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12406 mDNS_Unlock(m);
12407 return(status);
12408 }
12409
12410
12411 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12412 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12413 {
12414 question->InterfaceID = InterfaceID;
12415 question->flags = 0;
12416 question->Target = zeroAddr;
12417 question->qtype = kDNSType_PTR;
12418 question->qclass = kDNSClass_IN;
12419 question->LongLived = mDNSfalse;
12420 question->ExpectUnique = mDNSfalse;
12421 question->ForceMCast = mDNSfalse;
12422 question->ReturnIntermed = mDNSfalse;
12423 question->SuppressUnusable = mDNSfalse;
12424 question->SearchListIndex = 0;
12425 question->AppendSearchDomains = 0;
12426 question->RetryWithSearchDomains = mDNSfalse;
12427 question->TimeoutQuestion = 0;
12428 question->WakeOnResolve = 0;
12429 question->UseBackgroundTrafficClass = mDNSfalse;
12430 question->ValidationRequired = 0;
12431 question->ValidatingResponse = 0;
12432 question->ProxyQuestion = 0;
12433 question->qnameOrig = mDNSNULL;
12434 question->AnonInfo = mDNSNULL;
12435 question->pid = mDNSPlatformGetPID();
12436 question->euid = 0;
12437 question->QuestionCallback = Callback;
12438 question->QuestionContext = Context;
12439 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12440 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12441 if (!dom) dom = &localdomain;
12442 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12443 return(mDNS_StartQuery(m, question));
12444 }
12445
12446 // ***************************************************************************
12447 #if COMPILER_LIKES_PRAGMA_MARK
12448 #pragma mark -
12449 #pragma mark - Responder Functions
12450 #endif
12451
12452 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12453 {
12454 mStatus status;
12455 mDNS_Lock(m);
12456 status = mDNS_Register_internal(m, rr);
12457 mDNS_Unlock(m);
12458 return(status);
12459 }
12460
12461 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12462 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12463 {
12464 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12465 {
12466 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12467 return(mStatus_Invalid);
12468 }
12469
12470 mDNS_Lock(m);
12471
12472 // If TTL is unspecified, leave TTL unchanged
12473 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12474
12475 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12476 if (rr->NewRData)
12477 {
12478 RData *n = rr->NewRData;
12479 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
12480 if (rr->UpdateCallback)
12481 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
12482 }
12483
12484 rr->NewRData = newrdata;
12485 rr->newrdlength = newrdlength;
12486 rr->UpdateCallback = Callback;
12487
12488 #ifndef UNICAST_DISABLED
12489 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12490 {
12491 mStatus status = uDNS_UpdateRecord(m, rr);
12492 // The caller frees the memory on error, don't retain stale pointers
12493 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12494 mDNS_Unlock(m);
12495 return(status);
12496 }
12497 #endif
12498
12499 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12500 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12501 CompleteRDataUpdate(m, rr);
12502 else
12503 {
12504 rr->AnnounceCount = InitialAnnounceCount;
12505 InitializeLastAPTime(m, rr);
12506 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12507 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12508 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12509 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12510 if (rr->UpdateCredits <= 5)
12511 {
12512 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12513 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12514 rr->ThisAPInterval *= 4;
12515 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12516 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12517 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12518 }
12519 rr->resrec.rroriginalttl = newttl;
12520 }
12521
12522 mDNS_Unlock(m);
12523 return(mStatus_NoError);
12524 }
12525
12526 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12527 // the record list and/or question list.
12528 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12529 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12530 {
12531 mStatus status;
12532 mDNS_Lock(m);
12533 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12534 mDNS_Unlock(m);
12535 return(status);
12536 }
12537
12538 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12539 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12540
12541 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
12542 {
12543 NetworkInterfaceInfo *intf;
12544 for (intf = m->HostInterfaces; intf; intf = intf->next)
12545 if (intf->Advertise) break;
12546 return(intf);
12547 }
12548
12549 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12550 // (It's a set of records, not a set of interfaces.)
12551 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12552 {
12553 char buffer[MAX_REVERSE_MAPPING_NAME];
12554 NetworkInterfaceInfo *primary;
12555 mDNSu8 recordType;
12556
12557 if (m->AutoTargetServices == 0)
12558 {
12559 LogInfo("AdvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
12560 return;
12561 }
12562
12563 primary = FindFirstAdvertisedInterface(m);
12564 if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
12565 // We should never have primary be NULL, because even if there is
12566 // no other interface yet, we should always find ourself in the list.
12567
12568 // If interface is marked as a direct link, we can assume the address record is unique
12569 // and does not need to go through the probe phase of the probe/announce packet sequence.
12570 recordType = (set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique);
12571
12572 if (set->DirectLink)
12573 LogInfo("AdvertiseInterface: Marking address record as kDNSRecordTypeKnownUnique for %s", set->ifname);
12574
12575 // Send dynamic update for non-linklocal IPv4 Addresses
12576 mDNS_SetupResourceRecord(&set->RR_A, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, recordType, AuthRecordAny, mDNS_HostNameCallback, set);
12577 mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12578 mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12579
12580 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12581 set->RR_A.AllowRemoteQuery = mDNStrue;
12582 set->RR_PTR.AllowRemoteQuery = mDNStrue;
12583 set->RR_HINFO.AllowRemoteQuery = mDNStrue;
12584 #endif
12585 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12586 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12587 AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
12588 if (set->ip.type == mDNSAddrType_IPv4)
12589 {
12590 set->RR_A.resrec.rrtype = kDNSType_A;
12591 set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
12592 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12593 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12594 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12595 }
12596 else if (set->ip.type == mDNSAddrType_IPv6)
12597 {
12598 int i;
12599 set->RR_A.resrec.rrtype = kDNSType_AAAA;
12600 set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
12601 for (i = 0; i < 16; i++)
12602 {
12603 static const char hexValues[] = "0123456789ABCDEF";
12604 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12605 buffer[i * 4 + 1] = '.';
12606 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12607 buffer[i * 4 + 3] = '.';
12608 }
12609 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12610 }
12611
12612 MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
12613 set->RR_PTR.AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12614 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
12615
12616 set->RR_A.RRSet = &primary->RR_A; // May refer to self
12617
12618 mDNS_Register_internal(m, &set->RR_A);
12619 mDNS_Register_internal(m, &set->RR_PTR);
12620
12621 #if APPLE_OSX_mDNSResponder
12622 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12623 D2D_start_advertising_interface(set);
12624 #endif // APPLE_OSX_mDNSResponder
12625
12626 if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
12627 {
12628 mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
12629 AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
12630 set->RR_HINFO.DependentOn = &set->RR_A;
12631 mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
12632 p += 1 + (int)p[0];
12633 mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
12634 mDNS_Register_internal(m, &set->RR_HINFO);
12635 }
12636 else
12637 {
12638 debugf("Not creating HINFO record: platform support layer provided no information");
12639 set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
12640 }
12641 }
12642
12643 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12644 {
12645 if (m->AutoTargetServices == 0)
12646 {
12647 LogInfo("DeadvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
12648 return;
12649 }
12650
12651 #if APPLE_OSX_mDNSResponder
12652 D2D_stop_advertising_interface(set);
12653 #endif // APPLE_OSX_mDNSResponder
12654
12655 // Unregister these records.
12656 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12657 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12658 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12659 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12660 if (set->RR_A .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
12661 if (set->RR_PTR .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
12662 if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
12663 }
12664
12665 mDNSlocal void AdvertiseAllInterfaceRecords(mDNS *const m)
12666 {
12667 NetworkInterfaceInfo *intf;
12668 for (intf = m->HostInterfaces; intf; intf = intf->next)
12669 {
12670 if (intf->Advertise)
12671 {
12672 LogInfo("AdvertiseInterface: Advertising for ifname %s", intf->ifname);
12673 AdvertiseInterface(m, intf);
12674 }
12675 }
12676 }
12677
12678 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m)
12679 {
12680 NetworkInterfaceInfo *intf;
12681 for (intf = m->HostInterfaces; intf; intf = intf->next)
12682 {
12683 if (intf->Advertise)
12684 {
12685 LogInfo("DeadvertiseInterface: Deadvertising for ifname %s", intf->ifname);
12686 DeadvertiseInterface(m, intf);
12687 }
12688 }
12689 }
12690
12691 // Change target host name for record.
12692 mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr)
12693 {
12694 #if APPLE_OSX_mDNSResponder
12695 // If this record was also registered with any D2D plugins, stop advertising
12696 // the version with the old host name.
12697 D2D_stop_advertising_record(rr);
12698 #endif
12699
12700 SetTargetToHostName(m, rr);
12701
12702 #if APPLE_OSX_mDNSResponder
12703 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12704 D2D_start_advertising_record(rr);
12705 #endif
12706 }
12707
12708 mDNSexport void mDNS_SetFQDN(mDNS *const m)
12709 {
12710 domainname newmname;
12711 AuthRecord *rr;
12712 newmname.c[0] = 0;
12713
12714 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12715 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12716
12717 mDNS_Lock(m);
12718
12719 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
12720 else
12721 {
12722 AssignDomainName(&m->MulticastHostname, &newmname);
12723 DeadvertiseAllInterfaceRecords(m);
12724 AdvertiseAllInterfaceRecords(m);
12725 }
12726
12727 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12728 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12729 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12730
12731 mDNS_Unlock(m);
12732 }
12733
12734 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12735 {
12736 (void)rr; // Unused parameter
12737
12738 #if MDNS_DEBUGMSGS
12739 {
12740 char *msg = "Unknown result";
12741 if (result == mStatus_NoError) msg = "Name registered";
12742 else if (result == mStatus_NameConflict) msg = "Name conflict";
12743 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
12744 }
12745 #endif
12746
12747 if (result == mStatus_NoError)
12748 {
12749 // Notify the client that the host name is successfully registered
12750 if (m->MainCallback)
12751 m->MainCallback(m, mStatus_NoError);
12752 }
12753 else if (result == mStatus_NameConflict)
12754 {
12755 domainlabel oldlabel = m->hostlabel;
12756
12757 // 1. First give the client callback a chance to pick a new name
12758 if (m->MainCallback)
12759 m->MainCallback(m, mStatus_NameConflict);
12760
12761 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12762 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12763 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12764 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
12765 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
12766
12767 // 3. Generate the FQDNs from the hostlabel,
12768 // and make sure all SRV records, etc., are updated to reference our new hostname
12769 mDNS_SetFQDN(m);
12770 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
12771 }
12772 else if (result == mStatus_MemFree)
12773 {
12774 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12775 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12776 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12777 }
12778 else
12779 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c);
12780 }
12781
12782 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12783 {
12784 NetworkInterfaceInfo *intf;
12785 active->IPv4Available = mDNSfalse;
12786 active->IPv6Available = mDNSfalse;
12787 for (intf = m->HostInterfaces; intf; intf = intf->next)
12788 if (intf->InterfaceID == active->InterfaceID)
12789 {
12790 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12791 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12792 }
12793 }
12794
12795 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12796 {
12797 AuthRecord *rr;
12798 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12799 for (rr = m->ResourceRecords; rr; rr=rr->next)
12800 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12801 {
12802 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12803 // Zero out the updateid so that if we have a pending response from the server, it won't
12804 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12805 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12806 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12807 }
12808 }
12809
12810 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12811 {
12812 int i;
12813 // We initialize ThisQInterval to -1 indicating that the question has not been started
12814 // yet. If the question (browse) is started later during interface registration, it will
12815 // be stopped during interface deregistration. We can't sanity check to see if the
12816 // question has been stopped or not before initializing it to -1 because we need to
12817 // initialize it to -1 the very first time.
12818
12819 set->NetWakeBrowse.ThisQInterval = -1;
12820 for (i=0; i<3; i++)
12821 {
12822 set->NetWakeResolve[i].ThisQInterval = -1;
12823 set->SPSAddr[i].type = mDNSAddrType_None;
12824 }
12825 set->NextSPSAttempt = -1;
12826 set->NextSPSAttemptTime = m->timenow;
12827 }
12828
12829 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12830 {
12831 NetworkInterfaceInfo *p = m->HostInterfaces;
12832 while (p && p != set) p=p->next;
12833 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12834
12835 if (set->InterfaceActive)
12836 {
12837 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12838 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, mDNSNULL, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
12839 }
12840 }
12841
12842 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12843 {
12844 NetworkInterfaceInfo *p = m->HostInterfaces;
12845 while (p && p != set) p=p->next;
12846 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12847
12848 // Note: We start the browse only if the interface is NetWake capable and we use this to
12849 // stop the resolves also. Hence, the resolves should not be started without the browse
12850 // being started i.e, resolves should not happen unless NetWake capable which is
12851 // guaranteed by BeginSleepProcessing.
12852 if (set->NetWakeBrowse.ThisQInterval >= 0)
12853 {
12854 int i;
12855 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
12856
12857 // Stop our browse and resolve operations
12858 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
12859 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
12860
12861 // Make special call to the browse callback to let it know it can to remove all records for this interface
12862 if (m->SPSBrowseCallback)
12863 {
12864 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12865 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
12866 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12867 }
12868
12869 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12870 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12871 InitializeNetWakeState(m, set);
12872 }
12873 }
12874
12875 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
12876 {
12877 AuthRecord *rr;
12878 mDNSBool FirstOfType = mDNStrue;
12879 NetworkInterfaceInfo **p = &m->HostInterfaces;
12880
12881 if (!set->InterfaceID)
12882 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
12883
12884 if (!mDNSAddressIsValidNonZero(&set->mask))
12885 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
12886
12887 mDNS_Lock(m);
12888
12889 // Assume this interface will be active now, unless we find a duplicate already in the list
12890 set->InterfaceActive = mDNStrue;
12891 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
12892 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
12893
12894 InitializeNetWakeState(m, set);
12895
12896 // Scan list to see if this InterfaceID is already represented
12897 while (*p)
12898 {
12899 if (*p == set)
12900 {
12901 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
12902 mDNS_Unlock(m);
12903 return(mStatus_AlreadyRegistered);
12904 }
12905
12906 if ((*p)->InterfaceID == set->InterfaceID)
12907 {
12908 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
12909 set->InterfaceActive = mDNSfalse;
12910 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
12911 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
12912 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
12913 }
12914
12915 p=&(*p)->next;
12916 }
12917
12918 set->next = mDNSNULL;
12919 *p = set;
12920
12921 if (set->Advertise)
12922 AdvertiseInterface(m, set);
12923
12924 LogInfo("mDNS_RegisterInterface: InterfaceID %d %s (%#a) %s",
12925 (uint32_t)set->InterfaceID, set->ifname, &set->ip,
12926 set->InterfaceActive ?
12927 "not represented in list; marking active and retriggering queries" :
12928 "already represented in list; marking inactive for now");
12929
12930 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
12931
12932 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
12933 // giving the false impression that there's an active representative of this interface when there really isn't.
12934 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
12935 // even if we believe that we previously had an active representative of this interface.
12936 if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
12937 {
12938 DNSQuestion *q;
12939 // Normally, after an interface comes up, we pause half a second before beginning probing.
12940 // This is to guard against cases where there's rapid interface changes, where we could be confused by
12941 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
12942 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
12943 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
12944 // and think it's a conflicting answer to our probe.
12945 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
12946 mDNSs32 probedelay;
12947 mDNSu8 numannounce;
12948 switch (activationSpeed)
12949 {
12950 case FastActivation:
12951 probedelay = (mDNSs32)0;
12952 numannounce = InitialAnnounceCount;
12953 LogMsg("mDNS_RegisterInterface: Using fast activation for DirectLink interface %s (%#a)", set->ifname, &set->ip);
12954 break;
12955
12956 case SlowActivation:
12957 probedelay = mDNSPlatformOneSecond * 5;
12958 numannounce = (mDNSu8)1;
12959 LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a), doing slow activation", set->ifname, &set->ip);
12960 m->mDNSStats.InterfaceUpFlap++;
12961 break;
12962
12963 case NormalActivation:
12964 default:
12965 probedelay = mDNSPlatformOneSecond / 2;
12966 numannounce = InitialAnnounceCount;
12967 break;
12968 }
12969
12970 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
12971
12972 // No probe or sending suppression on DirectLink type interfaces.
12973 if (activationSpeed == FastActivation)
12974 {
12975 m->SuppressSending = 0;
12976 m->SuppressProbes = 0;
12977 }
12978 else
12979 {
12980 // Use a small amount of randomness:
12981 // In the case of a network administrator turning on an Ethernet hub so that all the
12982 // connected machines establish link at exactly the same time, we don't want them all
12983 // to go and hit the network with identical queries at exactly the same moment.
12984 // We set a random delay of up to InitialQuestionInterval (1/3 second).
12985 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
12986 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
12987 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
12988 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
12989 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
12990 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
12991
12992 if (m->SuppressProbes == 0 ||
12993 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
12994 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
12995 }
12996
12997 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
12998 // it here also handles the wake up case as the network link comes UP after waking causing
12999 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13000 // that the network link comes UP after 60 seconds and we never set the OWNER option
13001 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
13002 LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
13003
13004 m->mDNSStats.InterfaceUp++;
13005 for (q = m->Questions; q; q=q->next) // Scan our list of questions
13006 {
13007 if (mDNSOpaque16IsZero(q->TargetQID))
13008 {
13009 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
13010 { // then reactivate this question
13011 // If flapping, delay between first and second queries is nine seconds instead of one second
13012 mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
13013 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
13014 mDNSs32 qdelay = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0;
13015 if (dodelay) LogInfo("No cache records expired for %##s (%s); delaying questions by %d seconds", q->qname.c, DNSTypeName(q->qtype), qdelay);
13016
13017 if (!q->ThisQInterval || q->ThisQInterval > initial)
13018 {
13019 q->ThisQInterval = initial;
13020 q->RequestUnicast = kDefaultRequestUnicastCount;
13021 }
13022 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
13023 q->RecentAnswerPkts = 0;
13024 // Change the salt
13025 ReInitAnonInfo(&q->AnonInfo, &q->qname);
13026 SetNextQueryTime(m,q);
13027 }
13028 }
13029 }
13030
13031 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13032 // we now need them to re-probe if necessary, and then re-announce.
13033 for (rr = m->ResourceRecords; rr; rr=rr->next)
13034 {
13035 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
13036 {
13037 // Change the salt
13038 ReInitAnonInfo(&rr->resrec.AnonInfo, rr->resrec.name);
13039 mDNSCoreRestartRegistration(m, rr, numannounce);
13040 }
13041 }
13042 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
13043 DNSSECProbe(m);
13044 #endif
13045 }
13046
13047 RestartRecordGetZoneData(m);
13048
13049 mDNS_UpdateAllowSleep(m);
13050
13051 mDNS_Unlock(m);
13052 return(mStatus_NoError);
13053 }
13054
13055 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13056 // the record list and/or question list.
13057 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13058 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13059 {
13060 NetworkInterfaceInfo **p = &m->HostInterfaces;
13061 mDNSBool revalidate = mDNSfalse;
13062 NetworkInterfaceInfo *primary;
13063 NetworkInterfaceInfo *intf;
13064 AuthRecord *A;
13065
13066 mDNS_Lock(m);
13067
13068 // Find this record in our list
13069 while (*p && *p != set) p=&(*p)->next;
13070 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
13071
13072 mDNS_DeactivateNetWake_internal(m, set);
13073
13074 // Unlink this record from our list
13075 *p = (*p)->next;
13076 set->next = mDNSNULL;
13077
13078 if (!set->InterfaceActive)
13079 {
13080 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13081 for (intf = m->HostInterfaces; intf; intf = intf->next)
13082 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
13083 UpdateInterfaceProtocols(m, intf);
13084 }
13085 else
13086 {
13087 intf = FirstInterfaceForID(m, set->InterfaceID);
13088 if (intf)
13089 {
13090 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %d %s (%#a) exists;"
13091 " making it active", (uint32_t)set->InterfaceID, set->ifname, &set->ip);
13092 if (intf->InterfaceActive)
13093 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
13094 intf->InterfaceActive = mDNStrue;
13095 UpdateInterfaceProtocols(m, intf);
13096
13097 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
13098
13099 // See if another representative *of the same type* exists. If not, we mave have gone from
13100 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13101 for (intf = m->HostInterfaces; intf; intf = intf->next)
13102 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
13103 break;
13104 if (!intf) revalidate = mDNStrue;
13105 }
13106 else
13107 {
13108 mDNSu32 slot;
13109 CacheGroup *cg;
13110 CacheRecord *rr;
13111 DNSQuestion *q;
13112
13113 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %d %s (%#a) deregistered;"
13114 " marking questions etc. dormant", (uint32_t)set->InterfaceID, set->ifname, &set->ip);
13115
13116 m->mDNSStats.InterfaceDown++;
13117
13118 if (set->McastTxRx && (activationSpeed == SlowActivation))
13119 {
13120 LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
13121 m->mDNSStats.InterfaceDownFlap++;
13122 }
13123
13124 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13125 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13126 for (q = m->Questions; q; q=q->next)
13127 {
13128 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
13129 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
13130 {
13131 q->FlappingInterface2 = q->FlappingInterface1;
13132 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
13133 }
13134 }
13135
13136 // 2. Flush any cache records received on this interface
13137 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
13138 FORALL_CACHERECORDS(slot, cg, rr)
13139 {
13140 if (rr->resrec.InterfaceID == set->InterfaceID)
13141 {
13142 // If this interface is deemed flapping,
13143 // postpone deleting the cache records in case the interface comes back again
13144 if (set->McastTxRx && (activationSpeed == SlowActivation))
13145 {
13146 // For a flapping interface we want these records to go away after
13147 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13148 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13149 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13150 // if the interface does come back, any relevant questions will be reactivated anyway
13151 rr->UnansweredQueries = MaxUnansweredQueries;
13152 }
13153 else
13154 {
13155 mDNS_PurgeCacheResourceRecord(m, rr);
13156 }
13157 }
13158 }
13159 }
13160 }
13161
13162 // If we still have address records referring to this one, update them.
13163 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13164 // so the call to FindFirstAdvertisedInterface() won’t accidentally find it.
13165 primary = FindFirstAdvertisedInterface(m);
13166 A = primary ? &primary->RR_A : mDNSNULL;
13167 for (intf = m->HostInterfaces; intf; intf = intf->next)
13168 if (intf->RR_A.RRSet == &set->RR_A)
13169 intf->RR_A.RRSet = A;
13170
13171 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13172 if (set->Advertise) DeadvertiseInterface(m, set);
13173
13174 // If we have any cache records received on this interface that went away, then re-verify them.
13175 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13176 // giving the false impression that there's an active representative of this interface when there really isn't.
13177 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13178 if (revalidate && !m->ShutdownTime)
13179 {
13180 mDNSu32 slot;
13181 CacheGroup *cg;
13182 CacheRecord *rr;
13183 FORALL_CACHERECORDS(slot, cg, rr)
13184 if (rr->resrec.InterfaceID == set->InterfaceID)
13185 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13186 }
13187
13188 mDNS_UpdateAllowSleep(m);
13189
13190 mDNS_Unlock(m);
13191 }
13192
13193 mDNSlocal void SetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13194 {
13195 int i, len;
13196
13197 if (!sr->AnonData)
13198 return;
13199
13200 len = mDNSPlatformStrLen(sr->AnonData);
13201 if (sr->RR_PTR.resrec.AnonInfo)
13202 {
13203 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for PTR record %##s, should have been freed already", sr->RR_PTR.resrec.name->c);
13204 FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13205 }
13206 sr->RR_PTR.resrec.AnonInfo = AllocateAnonInfo(sr->RR_PTR.resrec.name, sr->AnonData, len, mDNSNULL);
13207 for (i=0; i<NumSubTypes; i++)
13208 {
13209 if (sr->SubTypes[i].resrec.AnonInfo)
13210 {
13211 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for subtype record %##s, should have been freed already", sr->SubTypes[i].resrec.name->c);
13212 FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13213 }
13214 sr->SubTypes[i].resrec.AnonInfo = AllocateAnonInfo(sr->SubTypes[i].resrec.name, sr->AnonData, len, mDNSNULL);
13215 }
13216 }
13217
13218 mDNSlocal void ResetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13219 {
13220 int i;
13221
13222 if (!sr->AnonData)
13223 return;
13224 if (sr->RR_PTR.resrec.AnonInfo)
13225 {
13226 FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13227 sr->RR_PTR.resrec.AnonInfo = mDNSNULL;
13228 }
13229 for (i=0; i<NumSubTypes; i++)
13230 {
13231 if (sr->SubTypes[i].resrec.AnonInfo)
13232 {
13233 FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13234 sr->SubTypes[i].resrec.AnonInfo = mDNSNULL;
13235 }
13236 }
13237 }
13238
13239 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13240 {
13241 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13242 (void)m; // Unused parameter
13243
13244 #if MDNS_DEBUGMSGS
13245 {
13246 char *msg = "Unknown result";
13247 if (result == mStatus_NoError) msg = "Name Registered";
13248 else if (result == mStatus_NameConflict) msg = "Name Conflict";
13249 else if (result == mStatus_MemFree) msg = "Memory Free";
13250 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13251 }
13252 #endif
13253
13254 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13255 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13256
13257 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13258 if (result == mStatus_NameConflict)
13259 {
13260 sr->Conflict = mDNStrue; // Record that this service set had a conflict
13261 mDNS_DeregisterService(m, sr); // Unlink the records from our list
13262 return;
13263 }
13264
13265 if (result == mStatus_MemFree)
13266 {
13267 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13268 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13269 // every record is finished cleaning up.
13270 mDNSu32 i;
13271 ExtraResourceRecord *e = sr->Extras;
13272
13273 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13274 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13275 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13276 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13277 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13278
13279 while (e)
13280 {
13281 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13282 e = e->next;
13283 }
13284 ResetAnonInfoSRS(sr, sr->NumSubTypes);
13285
13286 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13287 // then we can now report the NameConflict to the client
13288 if (sr->Conflict) result = mStatus_NameConflict;
13289
13290 }
13291
13292 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13293 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13294 // function is allowed to do anything, including deregistering this service and freeing its memory.
13295 if (sr->ServiceCallback)
13296 sr->ServiceCallback(m, sr, result);
13297 }
13298
13299 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13300 {
13301 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13302 if (sr->ServiceCallback)
13303 sr->ServiceCallback(m, sr, result);
13304 }
13305
13306
13307 // Derive AuthRecType from the kDNSServiceFlags* values.
13308 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13309 {
13310 AuthRecType artype;
13311
13312 if (InterfaceID == mDNSInterface_LocalOnly)
13313 artype = AuthRecordLocalOnly;
13314 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13315 artype = AuthRecordP2P;
13316 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
13317 && (flags & kDNSServiceFlagsIncludeAWDL))
13318 artype = AuthRecordAnyIncludeAWDLandP2P;
13319 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
13320 artype = AuthRecordAnyIncludeP2P;
13321 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
13322 artype = AuthRecordAnyIncludeAWDL;
13323 else
13324 artype = AuthRecordAny;
13325
13326 return artype;
13327 }
13328
13329 // Used to derive the original D2D specific flags specified by the client in the registration
13330 // when we don't have access to the original flag (kDNSServiceFlags*) values.
13331 mDNSexport mDNSu32 deriveD2DFlagsFromAuthRecType(AuthRecType authRecType)
13332 {
13333 mDNSu32 flags = 0;
13334 if ((authRecType == AuthRecordAnyIncludeP2P) || (authRecType == AuthRecordAnyIncludeAWDLandP2P))
13335 flags |= kDNSServiceFlagsIncludeP2P;
13336 else if ((authRecType == AuthRecordAnyIncludeAWDL) || (authRecType == AuthRecordAnyIncludeAWDLandP2P))
13337 flags |= kDNSServiceFlagsIncludeAWDL;
13338 return flags;
13339 }
13340
13341 // Note:
13342 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13343 // Type is service type (e.g. "_ipp._tcp.")
13344 // Domain is fully qualified domain name (i.e. ending with a null label)
13345 // We always register a TXT, even if it is empty (so that clients are not
13346 // left waiting forever looking for a nonexistent record.)
13347 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13348 // then the default host name (m->MulticastHostname) is automatically used
13349 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13350 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13351 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13352 const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13353 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13354 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13355 {
13356 mStatus err;
13357 mDNSu32 i;
13358 mDNSu32 hostTTL;
13359 AuthRecType artype;
13360 mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13361
13362 sr->ServiceCallback = Callback;
13363 sr->ServiceContext = Context;
13364 sr->Conflict = mDNSfalse;
13365
13366 sr->Extras = mDNSNULL;
13367 sr->NumSubTypes = NumSubTypes;
13368 sr->SubTypes = SubTypes;
13369 sr->flags = flags;
13370
13371 artype = setAuthRecType(InterfaceID, flags);
13372
13373 // Initialize the AuthRecord objects to sane values
13374 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13375 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13376 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13377
13378 if (flags & kDNSServiceFlagsWakeOnlyService)
13379 {
13380 sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13381 }
13382
13383 if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
13384 hostTTL = kHostNameSmallTTL;
13385 else
13386 hostTTL = kHostNameTTL;
13387
13388 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
13389 mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr);
13390
13391 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13392 if (mDNSIPPortIsZero(port))
13393 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13394
13395 // If the caller is registering an oversized TXT record,
13396 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13397 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13398 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13399
13400 // Set up the record names
13401 // For now we only create an advisory record for the main type, not for subtypes
13402 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13403 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13404 return(mStatus_BadParamErr);
13405 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13406 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13407 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13408
13409 // 1. Set up the ADV record rdata to advertise our service type
13410 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13411
13412 // 2. Set up the PTR record rdata to point to our service name
13413 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13414 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13415 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13416 sr->RR_PTR.Additional1 = &sr->RR_SRV;
13417 sr->RR_PTR.Additional2 = &sr->RR_TXT;
13418
13419 // 2a. Set up any subtype PTRs to point to our service name
13420 // If the client is using subtypes, it is the client's responsibility to have
13421 // already set the first label of the record name to the subtype being registered
13422 for (i=0; i<NumSubTypes; i++)
13423 {
13424 domainname st;
13425 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13426 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13427 AppendDomainName(&st, type);
13428 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13429 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13430 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13431 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13432 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13433 }
13434
13435 SetAnonInfoSRS(sr, NumSubTypes);
13436
13437 // 3. Set up the SRV record rdata.
13438 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13439 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
13440 sr->RR_SRV.resrec.rdata->u.srv.port = port;
13441
13442 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13443 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13444 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13445
13446 // 4. Set up the TXT record rdata,
13447 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13448 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13449 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13450 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13451 {
13452 sr->RR_TXT.resrec.rdlength = txtlen;
13453 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13454 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13455 }
13456 sr->RR_TXT.DependentOn = &sr->RR_SRV;
13457
13458 mDNS_Lock(m);
13459 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13460 // that if the SRV cannot find a target, rest of the records that belong to this service
13461 // will not be activated.
13462 err = mDNS_Register_internal(m, &sr->RR_SRV);
13463 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13464 // any list and hence no need to deregister. We could probably do similar checks for other
13465 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13466 if (err)
13467 {
13468 mDNS_Unlock(m);
13469 return err;
13470 }
13471 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13472 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13473 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13474 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13475 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13476 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13477 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13478 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13479 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13480
13481 mDNS_Unlock(m);
13482
13483 if (err) mDNS_DeregisterService(m, sr);
13484 return(err);
13485 }
13486
13487 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13488 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags)
13489 {
13490 ExtraResourceRecord **e;
13491 mStatus status;
13492 AuthRecType artype;
13493 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13494 ResourceRecord *rr;
13495
13496 artype = setAuthRecType(InterfaceID, flags);
13497
13498 extra->next = mDNSNULL;
13499 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13500 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13501 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13502
13503 mDNS_Lock(m);
13504 rr = mDNSNULL;
13505 if (extra->r.resrec.rrtype == kDNSType_TXT)
13506 {
13507 if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec;
13508 }
13509 else if (extra->r.resrec.rrtype == kDNSType_SRV)
13510 {
13511 if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec;
13512 }
13513
13514 if (!rr)
13515 {
13516 ExtraResourceRecord *srExtra;
13517
13518 for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next)
13519 {
13520 if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask))
13521 {
13522 rr = &srExtra->r.resrec;
13523 break;
13524 }
13525 }
13526 }
13527
13528 if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl))
13529 {
13530 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13531 extra->r.resrec.rroriginalttl, rr->rroriginalttl, RRDisplayString(m, &extra->r.resrec));
13532 extra->r.resrec.rroriginalttl = rr->rroriginalttl;
13533 }
13534
13535 e = &sr->Extras;
13536 while (*e) e = &(*e)->next;
13537
13538 extra->r.DependentOn = &sr->RR_SRV;
13539
13540 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13541 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13542
13543 status = mDNS_Register_internal(m, &extra->r);
13544 if (status == mStatus_NoError) *e = extra;
13545
13546 mDNS_Unlock(m);
13547 return(status);
13548 }
13549
13550 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13551 mDNSRecordCallback MemFreeCallback, void *Context)
13552 {
13553 ExtraResourceRecord **e;
13554 mStatus status;
13555
13556 mDNS_Lock(m);
13557 e = &sr->Extras;
13558 while (*e && *e != extra) e = &(*e)->next;
13559 if (!*e)
13560 {
13561 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13562 status = mStatus_BadReferenceErr;
13563 }
13564 else
13565 {
13566 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13567 extra->r.RecordCallback = MemFreeCallback;
13568 extra->r.RecordContext = Context;
13569 *e = (*e)->next;
13570 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13571 }
13572 mDNS_Unlock(m);
13573 return(status);
13574 }
13575
13576 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13577 {
13578 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13579 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13580 domainlabel name1, name2;
13581 domainname type, domain;
13582 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13583 ExtraResourceRecord *extras = sr->Extras;
13584 mStatus err;
13585
13586 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13587 if (!newname)
13588 {
13589 name2 = name1;
13590 IncrementLabelSuffix(&name2, mDNStrue);
13591 newname = &name2;
13592 }
13593
13594 if (SameDomainName(&domain, &localdomain))
13595 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13596 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13597
13598 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
13599 host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13600 sr->SubTypes, sr->NumSubTypes,
13601 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13602
13603 // mDNS_RegisterService() just reset sr->Extras to NULL.
13604 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13605 // through the old list of extra records, and re-add them to our freshly created service registration
13606 while (!err && extras)
13607 {
13608 ExtraResourceRecord *e = extras;
13609 extras = extras->next;
13610 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13611 }
13612
13613 return(err);
13614 }
13615
13616 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13617 // which may change the record list and/or question list.
13618 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13619 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13620 {
13621 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13622 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13623
13624 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13625 {
13626 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13627 return(mStatus_BadReferenceErr);
13628 }
13629 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13630 {
13631 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13632 // Avoid race condition:
13633 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13634 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13635 // If the client happens to deregister the service in the middle of that process, then
13636 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13637 // instead of incorrectly promoting it to mStatus_NameConflict.
13638 // This race condition is exposed particularly when the conformance test generates
13639 // a whole batch of simultaneous conflicts across a range of services all advertised
13640 // using the same system default name, and if we don't take this precaution then
13641 // we end up incrementing m->nicelabel multiple times instead of just once.
13642 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13643 sr->Conflict = mDNSfalse;
13644 return(mStatus_NoError);
13645 }
13646 else
13647 {
13648 mDNSu32 i;
13649 mStatus status;
13650 ExtraResourceRecord *e;
13651 mDNS_Lock(m);
13652 e = sr->Extras;
13653
13654 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13655 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13656 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13657 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13658
13659 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13660
13661 // We deregister all of the extra records, but we leave the sr->Extras list intact
13662 // in case the client wants to do a RenameAndReregister and reinstate the registration
13663 while (e)
13664 {
13665 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13666 e = e->next;
13667 }
13668
13669 for (i=0; i<sr->NumSubTypes; i++)
13670 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13671
13672 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13673 mDNS_Unlock(m);
13674 return(status);
13675 }
13676 }
13677
13678 // Create a registration that asserts that no such service exists with this name.
13679 // This can be useful where there is a given function is available through several protocols.
13680 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13681 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13682 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13683 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13684 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13685 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13686 const domainname *const host,
13687 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13688 {
13689 AuthRecType artype;
13690
13691 artype = setAuthRecType(InterfaceID, flags);
13692
13693 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13694 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13695 rr->resrec.rdata->u.srv.priority = 0;
13696 rr->resrec.rdata->u.srv.weight = 0;
13697 rr->resrec.rdata->u.srv.port = zeroIPPort;
13698 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13699 else rr->AutoTarget = Target_AutoHost;
13700 return(mDNS_Register(m, rr));
13701 }
13702
13703 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13704 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13705 {
13706 AuthRecType artype;
13707
13708 if (InterfaceID == mDNSInterface_LocalOnly)
13709 artype = AuthRecordLocalOnly;
13710 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13711 artype = AuthRecordP2P;
13712 else
13713 artype = AuthRecordAny;
13714 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13715 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13716 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13717 return(mDNS_Register(m, rr));
13718 }
13719
13720 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13721 {
13722 AuthRecord *r;
13723 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13724 return mDNSfalse;
13725 }
13726
13727 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13728 {
13729 DNSQuestion *q;
13730 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13731 return mDNSfalse;
13732 }
13733
13734 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13735 {
13736 mDNSOpaque16 id;
13737 int i;
13738
13739 for (i=0; i<10; i++)
13740 {
13741 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13742 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13743 }
13744
13745 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13746
13747 return id;
13748 }
13749
13750 // ***************************************************************************
13751 #if COMPILER_LIKES_PRAGMA_MARK
13752 #pragma mark -
13753 #pragma mark - Sleep Proxy Server
13754 #endif
13755
13756 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13757 {
13758 // If we see an ARP from a machine we think is sleeping, then either
13759 // (i) the machine has woken, or
13760 // (ii) it's just a stray old packet from before the machine slept
13761 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13762 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13763 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13764 // 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*
13765 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13766 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13767
13768 rr->resrec.RecordType = kDNSRecordTypeUnique;
13769 rr->ProbeCount = DefaultProbeCountForTypeUnique;
13770 rr->ProbeRestartCount++;
13771
13772 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13773 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13774 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13775 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13776 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13777 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13778 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13779 InitializeLastAPTime(m, rr);
13780 else
13781 {
13782 rr->AnnounceCount = InitialAnnounceCount;
13783 rr->ThisAPInterval = mDNSPlatformOneSecond;
13784 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13785 SetNextAnnounceProbeTime(m, rr);
13786 }
13787 }
13788
13789 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13790 {
13791 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13792 AuthRecord *rr;
13793 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13794 if (!intf) return;
13795
13796 mDNS_Lock(m);
13797
13798 // Pass 1:
13799 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13800 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13801 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13802 // The times we might need to react to an ARP Announcement are:
13803 // (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
13804 // (ii) if it's a conflicting Announcement from another host
13805 // -- and we check for these in Pass 2 below.
13806 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13807 {
13808 for (rr = m->ResourceRecords; rr; rr=rr->next)
13809 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13810 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13811 {
13812 static const char msg1[] = "ARP Req from owner -- re-probing";
13813 static const char msg2[] = "Ignoring ARP Request from ";
13814 static const char msg3[] = "Creating Local ARP Cache entry ";
13815 static const char msg4[] = "Answering ARP Request from ";
13816 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13817 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
13818 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
13819 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13820 intf->ifname, msg, arp->sha.b, arp->spa.b, arp->tpa.b,
13821 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13822 if (msg == msg1)
13823 {
13824 if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13825 RestartARPProbing(m, rr);
13826 else
13827 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13828 }
13829 else if (msg == msg3)
13830 {
13831 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13832 }
13833 else if (msg == msg4)
13834 {
13835 SendARP(m, 2, rr, (mDNSv4Addr *)arp->tpa.b, &arp->sha, (mDNSv4Addr *)arp->spa.b, &arp->sha);
13836 }
13837 }
13838 }
13839
13840 // Pass 2:
13841 // 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.
13842 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13843 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13844 // 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.
13845 // If we see an apparently conflicting ARP, we check the sender hardware address:
13846 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13847 // 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.
13848 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
13849 debugf("ARP from self for %.4a", arp->tpa.b);
13850 else
13851 {
13852 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
13853 for (rr = m->ResourceRecords; rr; rr=rr->next)
13854 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13855 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13856 {
13857 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13858 {
13859 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13860 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13861 }
13862 else
13863 {
13864 RestartARPProbing(m, rr);
13865 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
13866 {
13867 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
13868 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
13869 arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr));
13870 }
13871 else
13872 {
13873 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13874 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13875 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
13876 }
13877 }
13878 }
13879 }
13880
13881 mDNS_Unlock(m);
13882 }
13883
13884 /*
13885 // Option 1 is Source Link Layer Address Option
13886 // Option 2 is Target Link Layer Address Option
13887 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
13888 {
13889 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
13890 while (options < end)
13891 {
13892 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
13893 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
13894 options += options[1] * 8;
13895 }
13896 return mDNSNULL;
13897 }
13898 */
13899
13900 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
13901 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
13902 {
13903 AuthRecord *rr;
13904 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13905 if (!intf) return;
13906
13907 mDNS_Lock(m);
13908
13909 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
13910 if (ndp->type == NDP_Sol)
13911 {
13912 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
13913 (void)end;
13914 for (rr = m->ResourceRecords; rr; rr=rr->next)
13915 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13916 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
13917 {
13918 static const char msg1[] = "NDP Req from owner -- re-probing";
13919 static const char msg2[] = "Ignoring NDP Request from ";
13920 static const char msg3[] = "Creating Local NDP Cache entry ";
13921 static const char msg4[] = "Answering NDP Request from ";
13922 static const char msg5[] = "Answering NDP Probe from ";
13923 const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
13924 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
13925 sha && mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
13926 spa && mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
13927 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
13928 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13929 if (msg == msg1)
13930 {
13931 if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13932 RestartARPProbing(m, rr);
13933 else
13934 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13935 }
13936 else if (msg == msg3)
13937 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13938 else if (msg == msg4)
13939 SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
13940 else if (msg == msg5)
13941 SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
13942 }
13943 }
13944
13945 // 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.
13946 if (mDNSSameEthAddress(sha, &intf->MAC))
13947 debugf("NDP from self for %.16a", &ndp->target);
13948 else
13949 {
13950 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
13951 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
13952 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
13953 // Hence it is the NDP target address we care about, not the actual packet source address.
13954 if (ndp->type == NDP_Adv) spa = &ndp->target;
13955 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
13956 for (rr = m->ResourceRecords; rr; rr=rr->next)
13957 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13958 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13959 {
13960 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13961 {
13962 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13963 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13964 }
13965 else
13966 {
13967 RestartARPProbing(m, rr);
13968 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
13969 {
13970 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
13971 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
13972 }
13973 else
13974 {
13975 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13976 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13977 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
13978 }
13979 }
13980 }
13981 }
13982
13983 mDNS_Unlock(m);
13984 }
13985
13986 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
13987 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
13988 {
13989 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
13990 mDNSBool wake = mDNSfalse;
13991 mDNSBool kaWake = mDNSfalse;
13992
13993 switch (protocol)
13994 {
13995 #define XX wake ? "Received" : "Ignoring", end-p
13996 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
13997 break;
13998
13999 case 0x06: {
14000 AuthRecord *kr;
14001 mDNSu32 seq, ack;
14002 #define TH_FIN 0x01
14003 #define TH_SYN 0x02
14004 #define TH_RST 0x04
14005 #define TH_ACK 0x10
14006
14007 kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
14008 if (kr)
14009 {
14010 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
14011 // Plan to wake if
14012 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14013 // (b) packet that contains new data and acks a sequence number higher than the one
14014 // we have been sending in the keepalive
14015
14016 wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
14017 if (!wake)
14018 {
14019 mDNSu8 *ptr;
14020 mDNSu32 pseq, pack;
14021 mDNSBool data = mDNSfalse;
14022 mDNSu8 tcphlen;
14023
14024 // Convert to host order
14025 ptr = (mDNSu8 *)&seq;
14026 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14027
14028 ptr = (mDNSu8 *)&ack;
14029 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14030
14031 pseq = t->tcp.seq;
14032 ptr = (mDNSu8 *)&pseq;
14033 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14034
14035 pack = t->tcp.ack;
14036 ptr = (mDNSu8 *)&pack;
14037 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14038
14039 // If the other side is acking one more than our sequence number (keepalive is one
14040 // less than the last valid sequence sent) and it's sequence is more than what we
14041 // acked before
14042 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14043 tcphlen = ((t->tcp.offset >> 4) * 4);
14044 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
14045 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
14046
14047 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14048 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
14049 ((int)(ack - pseq) == 1))
14050 {
14051 // Send an ACK;
14052 mDNS_SendKeepaliveACK(m, kr);
14053 }
14054 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14055 end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
14056 }
14057 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
14058 kaWake = wake;
14059 }
14060 else
14061 {
14062 // Plan to wake if
14063 // (a) RST is not set, AND
14064 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14065 wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
14066
14067 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14068 // except for ssh connections, where we'll wake for plain data packets too
14069 if (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
14070
14071 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
14072 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
14073 (t->tcp.flags & 2) ? " SYN" : "",
14074 (t->tcp.flags & 1) ? " FIN" : "",
14075 (t->tcp.flags & 4) ? " RST" : "");
14076 }
14077 break;
14078 }
14079
14080 case 0x11: {
14081 #define ARD_AsNumber 3283
14082 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
14083 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
14084 if (udplen >= sizeof(UDPHeader))
14085 {
14086 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
14087 wake = mDNStrue;
14088
14089 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14090 if (mDNSSameIPPort(port, IPSECPort))
14091 {
14092 // Specifically ignore NAT keepalive packets
14093 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
14094 else
14095 {
14096 // Skip over the Non-ESP Marker if present
14097 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
14098 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
14099 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
14100 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
14101 if ((ike->Version & 0x10) == 0x10)
14102 {
14103 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14104 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14105 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
14106 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
14107 }
14108 }
14109 }
14110
14111 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14112 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14113 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14114 // UDP header (8 bytes)
14115 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14116 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
14117
14118 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
14119 }
14120 }
14121 break;
14122
14123 case 0x3A: if (&t->bytes[len] <= end)
14124 {
14125 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
14126 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
14127 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
14128 }
14129 break;
14130
14131 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
14132 break;
14133 }
14134
14135 if (wake)
14136 {
14137 AuthRecord *rr, *r2;
14138
14139 mDNS_Lock(m);
14140 for (rr = m->ResourceRecords; rr; rr=rr->next)
14141 if (rr->resrec.InterfaceID == InterfaceID &&
14142 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14143 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
14144 {
14145 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
14146 for (r2 = m->ResourceRecords; r2; r2=r2->next)
14147 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
14148 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
14149 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
14150 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
14151 break;
14152 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14153 if (!r2 && kaWake) r2 = rr; // So that we wake for keepalive packets, even without a matching SRV record
14154 if (r2)
14155 {
14156 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14157 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
14158 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14159 }
14160 else
14161 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14162 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
14163 }
14164 mDNS_Unlock(m);
14165 }
14166 }
14167
14168 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14169 {
14170 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14171 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14172 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14173 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14174 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14175
14176 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14177 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14178 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14179 // since it points to a an address 14 bytes before pkt.
14180 const EthernetHeader *const eth = (const EthernetHeader *)p;
14181 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
14182 mDNSAddr src, dst;
14183 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14184
14185 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14186 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
14187 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
14188 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14189 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
14190 {
14191 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
14192 const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
14193 if (transEnd > end) transEnd = end;
14194 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
14195 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
14196 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
14197 if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
14198 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
14199 }
14200 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14201 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
14202 {
14203 const mDNSu8 *const trans = p + 54;
14204 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
14205 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14206 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14207 if (end >= trans + RequiredCapLen(pkt->v6.pro))
14208 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14209 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14210 }
14211 }
14212
14213 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14214 {
14215 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14216 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14217 }
14218
14219 #ifndef SPC_DISABLED
14220 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14221 {
14222 if (result == mStatus_NameConflict)
14223 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14224 else if (result == mStatus_MemFree)
14225 {
14226 if (m->SleepState)
14227 m->SPSState = 3;
14228 else
14229 {
14230 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14231 if (m->SPSState)
14232 {
14233 domainlabel name;
14234 ConstructSleepProxyServerName(m, &name);
14235 mDNS_RegisterService(m, srs,
14236 &name, &SleepProxyServiceType, &localdomain,
14237 mDNSNULL, m->SPSSocket->port, // Host, port
14238 (mDNSu8 *)"", 1, // TXT data, length
14239 mDNSNULL, 0, // Subtypes (none)
14240 mDNSInterface_Any, // Interface ID
14241 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14242 }
14243 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14244 }
14245 }
14246 }
14247 #endif
14248
14249 // Called with lock held
14250 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14251 {
14252 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14253 mDNS_DropLockBeforeCallback();
14254
14255 // If turning off SPS, close our socket
14256 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14257 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14258
14259 // If turning off, or changing type, deregister old name
14260 #ifndef SPC_DISABLED
14261 if (m->SPSState == 1 && sps != m->SPSType)
14262 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14263 #endif // SPC_DISABLED
14264
14265 // Record our new SPS parameters
14266 m->SPSType = sps;
14267 m->SPSPortability = port;
14268 m->SPSMarginalPower = marginalpower;
14269 m->SPSTotalPower = totpower;
14270 m->SPSFeatureFlags = features;
14271 // If turning on, open socket and advertise service
14272 if (sps)
14273 {
14274 if (!m->SPSSocket)
14275 {
14276 m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort);
14277 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14278 }
14279 #ifndef SPC_DISABLED
14280 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14281 #endif // SPC_DISABLED
14282 }
14283 else if (m->SPSState)
14284 {
14285 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14286 m->NextScheduledSPS = m->timenow;
14287 }
14288 fail:
14289 mDNS_ReclaimLockAfterCallback();
14290 }
14291
14292 // ***************************************************************************
14293 #if COMPILER_LIKES_PRAGMA_MARK
14294 #pragma mark -
14295 #pragma mark - Startup and Shutdown
14296 #endif
14297
14298 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14299 {
14300 if (storage && numrecords)
14301 {
14302 mDNSu32 i;
14303 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14304 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14305 storage[numrecords-1].next = m->rrcache_free;
14306 m->rrcache_free = storage;
14307 m->rrcache_size += numrecords;
14308 }
14309 }
14310
14311 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14312 {
14313 mDNS_Lock(m);
14314 mDNS_GrowCache_internal(m, storage, numrecords);
14315 mDNS_Unlock(m);
14316 }
14317
14318 mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p,
14319 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14320 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14321 {
14322 mDNSu32 slot;
14323 mDNSs32 timenow;
14324 mStatus result;
14325
14326 if (!rrcachestorage) rrcachesize = 0;
14327
14328 m->p = p;
14329 m->NetworkChanged = 0;
14330 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14331 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
14332 m->DivertMulticastAdvertisements = mDNSfalse;
14333 m->mDNSPlatformStatus = mStatus_Waiting;
14334 m->UnicastPort4 = zeroIPPort;
14335 m->UnicastPort6 = zeroIPPort;
14336 m->PrimaryMAC = zeroEthAddr;
14337 m->MainCallback = Callback;
14338 m->MainContext = Context;
14339 m->rec.r.resrec.RecordType = 0;
14340 m->rec.r.resrec.AnonInfo = mDNSNULL;
14341
14342 // For debugging: To catch and report locking failures
14343 m->mDNS_busy = 0;
14344 m->mDNS_reentrancy = 0;
14345 m->ShutdownTime = 0;
14346 m->lock_rrcache = 0;
14347 m->lock_Questions = 0;
14348 m->lock_Records = 0;
14349
14350 // Task Scheduling variables
14351 result = mDNSPlatformTimeInit();
14352 if (result != mStatus_NoError) return(result);
14353 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14354 timenow = mDNS_TimeNow_NoLock(m);
14355
14356 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14357 m->timenow_last = timenow;
14358 m->NextScheduledEvent = timenow;
14359 m->SuppressSending = timenow;
14360 m->NextCacheCheck = timenow + FutureTime;
14361 m->NextScheduledQuery = timenow + FutureTime;
14362 m->NextScheduledProbe = timenow + FutureTime;
14363 m->NextScheduledResponse = timenow + FutureTime;
14364 m->NextScheduledNATOp = timenow + FutureTime;
14365 m->NextScheduledSPS = timenow + FutureTime;
14366 m->NextScheduledKA = timenow + FutureTime;
14367 m->NextScheduledStopTime = timenow + FutureTime;
14368 m->NextBLEServiceTime = 0; // zero indicates inactive
14369
14370 #if BONJOUR_ON_DEMAND
14371 m->NextBonjourDisableTime = 0; // Timer active when non zero.
14372 m->BonjourEnabled = 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14373 #endif // BONJOUR_ON_DEMAND
14374
14375 m->DelayConflictProcessing = MAX_CONFLICT_PROCESSING_DELAYS;
14376 m->RandomQueryDelay = 0;
14377 m->RandomReconfirmDelay = 0;
14378 m->PktNum = 0;
14379 m->MPktNum = 0;
14380 m->LocalRemoveEvents = mDNSfalse;
14381 m->SleepState = SleepState_Awake;
14382 m->SleepSeqNum = 0;
14383 m->SystemWakeOnLANEnabled = mDNSfalse;
14384 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14385 m->DelaySleep = 0;
14386 m->SleepLimit = 0;
14387
14388 #if APPLE_OSX_mDNSResponder
14389 m->UnicastPacketsSent = 0;
14390 m->MulticastPacketsSent = 0;
14391 m->RemoteSubnet = 0;
14392 #endif // APPLE_OSX_mDNSResponder
14393
14394 // These fields only required for mDNS Searcher...
14395 m->Questions = mDNSNULL;
14396 m->NewQuestions = mDNSNULL;
14397 m->CurrentQuestion = mDNSNULL;
14398 m->LocalOnlyQuestions = mDNSNULL;
14399 m->NewLocalOnlyQuestions = mDNSNULL;
14400 m->RestartQuestion = mDNSNULL;
14401 m->ValidationQuestion = mDNSNULL;
14402 m->rrcache_size = 0;
14403 m->rrcache_totalused = 0;
14404 m->rrcache_active = 0;
14405 m->rrcache_report = 10;
14406 m->rrcache_free = mDNSNULL;
14407
14408 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14409 {
14410 m->rrcache_hash[slot] = mDNSNULL;
14411 m->rrcache_nextcheck[slot] = timenow + FutureTime;;
14412 }
14413
14414 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14415 m->rrauth.rrauth_free = mDNSNULL;
14416
14417 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14418 m->rrauth.rrauth_hash[slot] = mDNSNULL;
14419
14420 // Fields below only required for mDNS Responder...
14421 m->hostlabel.c[0] = 0;
14422 m->nicelabel.c[0] = 0;
14423 m->MulticastHostname.c[0] = 0;
14424 m->HIHardware.c[0] = 0;
14425 m->HISoftware.c[0] = 0;
14426 m->ResourceRecords = mDNSNULL;
14427 m->DuplicateRecords = mDNSNULL;
14428 m->NewLocalRecords = mDNSNULL;
14429 m->NewLocalOnlyRecords = mDNSfalse;
14430 m->CurrentRecord = mDNSNULL;
14431 m->HostInterfaces = mDNSNULL;
14432 m->ProbeFailTime = 0;
14433 m->NumFailedProbes = 0;
14434 m->SuppressProbes = 0;
14435
14436 #ifndef UNICAST_DISABLED
14437 m->NextuDNSEvent = timenow + FutureTime;
14438 m->NextSRVUpdate = timenow + FutureTime;
14439
14440 m->DNSServers = mDNSNULL;
14441
14442 m->Router = zeroAddr;
14443 m->AdvertisedV4 = zeroAddr;
14444 m->AdvertisedV6 = zeroAddr;
14445
14446 m->AuthInfoList = mDNSNULL;
14447
14448 m->ReverseMap.ThisQInterval = -1;
14449 m->StaticHostname.c[0] = 0;
14450 m->FQDN.c[0] = 0;
14451 m->Hostnames = mDNSNULL;
14452 m->AutoTunnelNAT.clientContext = mDNSNULL;
14453
14454 m->WABBrowseQueriesCount = 0;
14455 m->WABLBrowseQueriesCount = 0;
14456 m->WABRegQueriesCount = 0;
14457 m->AutoTargetServices = 0;
14458
14459 #if BONJOUR_ON_DEMAND
14460 m->NumAllInterfaceRecords = 0;
14461 m->NumAllInterfaceQuestions = 0;
14462 #endif
14463 // NAT traversal fields
14464 m->LLQNAT.clientCallback = mDNSNULL;
14465 m->LLQNAT.clientContext = mDNSNULL;
14466 m->NATTraversals = mDNSNULL;
14467 m->CurrentNATTraversal = mDNSNULL;
14468 m->retryIntervalGetAddr = 0; // delta between time sent and retry
14469 m->retryGetAddr = timenow + FutureTime; // absolute time when we retry
14470 m->ExtAddress = zerov4Addr;
14471 m->PCPNonce[0] = mDNSRandom(-1);
14472 m->PCPNonce[1] = mDNSRandom(-1);
14473 m->PCPNonce[2] = mDNSRandom(-1);
14474
14475 m->NATMcastRecvskt = mDNSNULL;
14476 m->LastNATupseconds = 0;
14477 m->LastNATReplyLocalTime = timenow;
14478 m->LastNATMapResultCode = NATErr_None;
14479
14480 m->UPnPInterfaceID = 0;
14481 m->SSDPSocket = mDNSNULL;
14482 m->SSDPWANPPPConnection = mDNSfalse;
14483 m->UPnPRouterPort = zeroIPPort;
14484 m->UPnPSOAPPort = zeroIPPort;
14485 m->UPnPRouterURL = mDNSNULL;
14486 m->UPnPWANPPPConnection = mDNSfalse;
14487 m->UPnPSOAPURL = mDNSNULL;
14488 m->UPnPRouterAddressString = mDNSNULL;
14489 m->UPnPSOAPAddressString = mDNSNULL;
14490 m->SPSType = 0;
14491 m->SPSPortability = 0;
14492 m->SPSMarginalPower = 0;
14493 m->SPSTotalPower = 0;
14494 m->SPSFeatureFlags = 0;
14495 m->SPSState = 0;
14496 m->SPSProxyListChanged = mDNSNULL;
14497 m->SPSSocket = mDNSNULL;
14498 m->SPSBrowseCallback = mDNSNULL;
14499 m->ProxyRecords = 0;
14500
14501 m->DNSPushServers = mDNSNULL;
14502 m->DNSPushZones = mDNSNULL;
14503 #endif
14504
14505 #if APPLE_OSX_mDNSResponder
14506 m->TunnelClients = mDNSNULL;
14507
14508 #if !NO_WCF
14509 CHECK_WCF_FUNCTION(WCFConnectionNew)
14510 {
14511 m->WCF = WCFConnectionNew();
14512 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14513 }
14514 #endif
14515
14516 #endif
14517
14518 return(result);
14519 }
14520
14521 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14522 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14523 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14524 {
14525 mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context);
14526 if (result != mStatus_NoError)
14527 return(result);
14528
14529 result = mDNSPlatformInit(m);
14530
14531 #ifndef UNICAST_DISABLED
14532 // It's better to do this *after* the platform layer has set up the
14533 // interface list and security credentials
14534 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
14535 #endif
14536
14537 return(result);
14538 }
14539
14540 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14541 {
14542 if (m->SPSState == 1)
14543 {
14544 domainlabel name, newname;
14545 #ifndef SPC_DISABLED
14546 domainname type, domain;
14547 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14548 #endif // SPC_DISABLED
14549 ConstructSleepProxyServerName(m, &newname);
14550 if (!SameDomainLabelCS(name.c, newname.c))
14551 {
14552 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14553 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14554 // it will reregister the service under the new name
14555 m->SPSState = 2;
14556 #ifndef SPC_DISABLED
14557 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14558 #endif // SPC_DISABLED
14559 }
14560 }
14561
14562 if (m->MainCallback)
14563 m->MainCallback(m, mStatus_ConfigChanged);
14564 }
14565
14566 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14567 {
14568 (void)m; // unused
14569 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14570 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14571 }
14572
14573 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
14574 {
14575 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14576 cr->resrec.rrtype == kDNSType_A ||
14577 cr->resrec.rrtype == kDNSType_AAAA ||
14578 cr->resrec.rrtype == kDNSType_SRV ||
14579 cr->resrec.rrtype == kDNSType_CNAME;
14580
14581 (void) lameduck;
14582 (void) ptr;
14583 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
14584 purge ? "purging" : "reconfirming",
14585 lameduck ? "lame duck" : "new",
14586 ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
14587
14588 if (purge)
14589 {
14590 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14591 mDNS_PurgeCacheResourceRecord(m, cr);
14592 }
14593 else
14594 {
14595 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14596 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14597 }
14598 }
14599
14600 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
14601 {
14602 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14603 CacheRecord *rp;
14604 mDNSu8 validatingResponse = 0;
14605
14606 // For DNSSEC questions, purge the corresponding RRSIGs also.
14607 if (DNSSECQuestion(q))
14608 {
14609 validatingResponse = q->ValidatingResponse;
14610 q->ValidatingResponse = mDNStrue;
14611 }
14612 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14613 {
14614 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14615 {
14616 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
14617 mDNS_PurgeCacheResourceRecord(m, rp);
14618 }
14619 }
14620 if (DNSSECQuestion(q))
14621 {
14622 q->ValidatingResponse = validatingResponse;
14623 }
14624 }
14625
14626 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14627 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14628 // Just re-issuing the question for RRSIGs does not work in practice as the response
14629 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14630 //
14631 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14632 // have the cached NSECs, purge them. For positive responses, if we don't have the
14633 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14634 // them.
14635 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q)
14636 {
14637 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14638 CacheRecord *rp;
14639
14640 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14641 {
14642 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14643 {
14644 if (rp->resrec.RecordType != kDNSRecordTypePacketNegative || !rp->nsec)
14645 {
14646 if (!rp->CRDNSSECQuestion)
14647 {
14648 LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m, rp));
14649 mDNS_PurgeCacheResourceRecord(m, rp);
14650 }
14651 }
14652 }
14653 }
14654 }
14655
14656 // Check for a positive unicast response to the question but with qtype
14657 mDNSexport mDNSBool mDNS_CheckForCacheRecord(mDNS *const m, DNSQuestion *q, mDNSu16 qtype)
14658 {
14659 DNSQuestion question;
14660 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14661 CacheRecord *rp;
14662
14663 // Create an identical question but with qtype
14664 mDNS_SetupQuestion(&question, q->InterfaceID, &q->qname, qtype, mDNSNULL, mDNSNULL);
14665 question.qDNSServer = q->qDNSServer;
14666
14667 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14668 {
14669 if (!rp->resrec.InterfaceID && rp->resrec.RecordType != kDNSRecordTypePacketNegative &&
14670 SameNameRecordAnswersQuestion(&rp->resrec, &question))
14671 {
14672 LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m, rp));
14673 return mDNStrue;
14674 }
14675 }
14676 return mDNSfalse;
14677 }
14678
14679 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14680 {
14681 DNSQuestion *qptr;
14682
14683 (void) m;
14684
14685 if (q->DuplicateOf)
14686 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14687
14688 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14689 // of events for all of them are consistent. Duplicates for a question are always inserted
14690 // after in the list.
14691 q->qDNSServer = new;
14692 for (qptr = q->next ; qptr; qptr = qptr->next)
14693 {
14694 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14695 }
14696 }
14697
14698 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14699 {
14700 McastResolver *mr;
14701 DNSServer *ptr;
14702
14703 if (delete)
14704 {
14705 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14706 {
14707 ptr->penaltyTime = 0;
14708 NumUnicastDNSServers--;
14709 ptr->flags |= DNSServer_FlagDelete;
14710 #if APPLE_OSX_mDNSResponder
14711 if (ptr->flags & DNSServer_FlagUnreachable)
14712 NumUnreachableDNSServers--;
14713 #endif
14714 }
14715 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14716 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14717 // API
14718 for (mr = m->McastResolvers; mr; mr = mr->next)
14719 mr->flags |= McastResolver_FlagDelete;
14720 }
14721 else
14722 {
14723 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14724 {
14725 ptr->penaltyTime = 0;
14726 NumUnicastDNSServers++;
14727 ptr->flags &= ~DNSServer_FlagDelete;
14728 #if APPLE_OSX_mDNSResponder
14729 if (ptr->flags & DNSServer_FlagUnreachable)
14730 NumUnreachableDNSServers++;
14731 #endif
14732 }
14733 for (mr = m->McastResolvers; mr; mr = mr->next)
14734 mr->flags &= ~McastResolver_FlagDelete;
14735 }
14736 }
14737
14738 mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn)
14739 {
14740 // Did our FQDN change?
14741 if (!SameDomainName(fqdn, &m->FQDN))
14742 {
14743 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14744
14745 AssignDomainName(&m->FQDN, fqdn);
14746
14747 if (m->FQDN.c[0])
14748 {
14749 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14750 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14751 }
14752 }
14753 }
14754
14755 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14756 {
14757 mDNSu32 slot;
14758 CacheGroup *cg;
14759 CacheRecord *cr;
14760 mDNSBool Restart = mDNSfalse;
14761 mDNSAddr v4, v6, r;
14762 domainname fqdn;
14763 DNSServer *ptr, **p = &m->DNSServers;
14764 const DNSServer *oldServers = m->DNSServers;
14765 DNSQuestion *q;
14766 McastResolver *mr, **mres = &m->McastResolvers;
14767
14768 debugf("uDNS_SetupDNSConfig: entry");
14769
14770 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14771 uDNS_SetupWABQueries(m);
14772
14773 mDNS_Lock(m);
14774
14775 // We need to first mark all the entries to be deleted. If the configuration changed, then
14776 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14777 //
14778 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14779 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14780 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14781 // for the dns configuration change notification.
14782 SetConfigState(m, mDNStrue);
14783 if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14784 {
14785 SetDynDNSHostNameIfChanged(m, &fqdn);
14786 SetConfigState(m, mDNSfalse);
14787 mDNS_Unlock(m);
14788 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14789 return mStatus_NoError;
14790 }
14791
14792 // For now, we just delete the mcast resolvers. We don't deal with cache or
14793 // questions here. Neither question nor cache point to mcast resolvers. Questions
14794 // do inherit the timeout values from mcast resolvers. But we don't bother
14795 // affecting them as they never change.
14796 while (*mres)
14797 {
14798 if (((*mres)->flags & McastResolver_FlagDelete) != 0)
14799 {
14800 mr = *mres;
14801 *mres = (*mres)->next;
14802 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14803 mDNSPlatformMemFree(mr);
14804 }
14805 else
14806 {
14807 (*mres)->flags &= ~McastResolver_FlagNew;
14808 mres = &(*mres)->next;
14809 }
14810 }
14811
14812 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14813 //
14814 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14815 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14816 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14817 // DNSServers and flush the cache.
14818 //
14819 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14820 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14821 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14822 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14823 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14824 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14825 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14826 // the same resGroupID.
14827 //
14828 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14829 // of the old followed by ADD of the new records.
14830 //
14831 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14832 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14833 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14834 //
14835 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14836 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14837 // non-scoped question and vice versa.
14838 //
14839 #if USE_DNS64
14840 DNS64RestartQuestions(m);
14841 #endif
14842 for (q = m->Questions; q; q=q->next)
14843 {
14844 if (!mDNSOpaque16IsZero(q->TargetQID))
14845 {
14846 DNSServer *s, *t;
14847 DNSQuestion *qptr;
14848 if (q->DuplicateOf) continue;
14849 SetValidDNSServers(m, q);
14850 q->triedAllServersOnce = 0;
14851 s = GetServerForQuestion(m, q);
14852 t = q->qDNSServer;
14853 if (t != s)
14854 {
14855 mDNSBool old, new;
14856 // If DNS Server for this question has changed, reactivate it
14857 LogInfo("uDNS_SetupDNSConfig: Updating DNS Server from %#a:%d (%##s) to %#a:%d (%##s) for question %##s (%s) (scope:%p)",
14858 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
14859 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
14860 q->qname.c, DNSTypeName(q->qtype), q->InterfaceID);
14861
14862 old = q->SuppressQuery;
14863 new = ShouldSuppressUnicastQuery(m, q, s);
14864 if (old != new)
14865 {
14866 // Changing the DNS server affected the SuppressQuery status. We need to
14867 // deliver RMVs for the previous ADDs (if any) before switching to the new
14868 // DNSServer. To keep it simple, we walk all the questions and mark them
14869 // to be restarted and then handle all of them at once.
14870 q->Restart = 1;
14871 q->SuppressQuery = new;
14872 for (qptr = q->next ; qptr; qptr = qptr->next)
14873 {
14874 if (qptr->DuplicateOf == q)
14875 qptr->Restart = 1;
14876 }
14877 Restart = mDNStrue;
14878 }
14879 else
14880 {
14881 DNSServerChangeForQuestion(m, q, s);
14882 q->unansweredQueries = 0;
14883
14884 // If we had sent a query out to DNSServer "t" and we are changing to "s", we
14885 // need to ignore the responses coming back from "t" as the DNS configuration
14886 // has changed e.g., when a new interface is coming up and that becomes the primary
14887 // interface, we switch to the DNS servers configured for the primary interface. In
14888 // this case, we should not accept responses associated with the previous interface as
14889 // the "name" could resolve differently on this new primary interface. Hence, discard
14890 // in-flight responses.
14891 q->TargetQID = mDNS_NewMessageID(m);
14892
14893 if (!QuerySuppressed(q))
14894 {
14895 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
14896 ActivateUnicastQuery(m, q, mDNStrue);
14897 // ActivateUnicastQuery is called for duplicate questions also as it does something
14898 // special for AutoTunnel questions
14899 for (qptr = q->next ; qptr; qptr = qptr->next)
14900 {
14901 if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
14902 }
14903 }
14904 }
14905 }
14906 else
14907 {
14908 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
14909 q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
14910 for (qptr = q->next ; qptr; qptr = qptr->next)
14911 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
14912 }
14913 }
14914 }
14915 if (Restart)
14916 RestartUnicastQuestions(m);
14917
14918 FORALL_CACHERECORDS(slot, cg, cr)
14919 {
14920 if (cr->resrec.InterfaceID)
14921 continue;
14922
14923 // We already walked the questions and restarted/reactivated them if the dns server
14924 // change affected the question. That should take care of updating the cache. But
14925 // what if there is no active question at this point when the DNS server change
14926 // happened ? There could be old cache entries lying around and if we don't flush
14927 // them, a new question after the DNS server change could pick up these stale
14928 // entries and get a wrong answer.
14929 //
14930 // For cache entries that have active questions we might have skipped rescheduling
14931 // the questions if they were suppressed (see above). To keep it simple, we walk
14932 // all the cache entries to make sure that there are no stale entries. We use the
14933 // active question's InterfaceID/ServiceID for looking up the right DNS server.
14934 // Note that the unscoped value for ServiceID is -1.
14935 //
14936 // Note: If GetServerForName returns NULL, it could either mean that there are no
14937 // DNS servers or no matching DNS servers for this question. In either case,
14938 // the cache should get purged below when we process deleted DNS servers.
14939
14940 ptr = GetServerForName(m, cr->resrec.name,
14941 (cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL),
14942 (cr->CRActiveQuestion ? cr->CRActiveQuestion->ServiceID : -1));
14943
14944 // Purge or Reconfirm if this cache entry would use the new DNS server
14945 if (ptr && (ptr != cr->resrec.rDNSServer))
14946 {
14947 // As the DNSServers for this cache record is not the same anymore, we don't
14948 // want any new questions to pick this old value. If there is no active question,
14949 // we can't possibly re-confirm, so purge in that case. If it is a DNSSEC question,
14950 // purge the cache as the DNSSEC capabilities of the DNS server may have changed.
14951
14952 if (cr->CRActiveQuestion == mDNSNULL || DNSSECQuestion(cr->CRActiveQuestion))
14953 {
14954 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s, New DNS server %#a , Old DNS server %#a", CRDisplayString(m, cr),
14955 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
14956 mDNS_PurgeCacheResourceRecord(m, cr);
14957 }
14958 else
14959 {
14960 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", CRDisplayString(m, cr),
14961 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
14962 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
14963 }
14964 }
14965
14966 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
14967 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
14968 if (!cr->resrec.rDNSServer && cr->CRActiveQuestion && cr->CRActiveQuestion->qDNSServer)
14969 {
14970 cr->resrec.rDNSServer = cr->CRActiveQuestion->qDNSServer;
14971 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr->resrec.rDNSServer->addr, CRDisplayString(m, cr));
14972 }
14973 }
14974
14975 while (*p)
14976 {
14977 if (((*p)->flags & DNSServer_FlagDelete) != 0)
14978 {
14979 // Scan our cache, looking for uDNS records that we would have queried this server for.
14980 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
14981 // different DNS servers can give different answers to the same question.
14982 ptr = *p;
14983 FORALL_CACHERECORDS(slot, cg, cr)
14984 {
14985 if (cr->resrec.InterfaceID) continue;
14986 if (cr->resrec.rDNSServer == ptr)
14987 {
14988 // If we don't have an active question for this cache record, neither Purge can
14989 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
14990 // pointer on the record NULL so that we don't point to freed memory (We might dereference
14991 // DNSServer pointers from resource record for logging purposes).
14992 //
14993 // If there is an active question, point to its DNSServer as long as it does not point to the
14994 // freed one. We already went through the questions above and made them point at either the
14995 // new server or NULL if there is no server.
14996
14997 if (cr->CRActiveQuestion)
14998 {
14999 DNSQuestion *qptr = cr->CRActiveQuestion;
15000
15001 if (qptr->qDNSServer == ptr)
15002 {
15003 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15004 " to be freed", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID, &ptr->addr);
15005 qptr->validDNSServers = zeroOpaque128;
15006 qptr->qDNSServer = mDNSNULL;
15007 cr->resrec.rDNSServer = mDNSNULL;
15008 }
15009 else
15010 {
15011 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15012 " resetting to question's DNSServer Address %#a", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype),
15013 qptr->InterfaceID, &ptr->addr, (qptr->qDNSServer) ? &qptr->qDNSServer->addr : mDNSNULL);
15014 cr->resrec.rDNSServer = qptr->qDNSServer;
15015 }
15016 }
15017 else
15018 {
15019 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
15020 cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
15021 cr->resrec.rDNSServer = mDNSNULL;
15022 }
15023
15024 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
15025 }
15026 }
15027 *p = (*p)->next;
15028 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s) %d", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, NumUnicastDNSServers);
15029 mDNSPlatformMemFree(ptr);
15030 }
15031 else
15032 {
15033 (*p)->flags &= ~DNSServer_FlagNew;
15034 p = &(*p)->next;
15035 }
15036 }
15037
15038 // 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).
15039 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15040 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15041 // 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.
15042 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
15043 {
15044 int count = 0;
15045 FORALL_CACHERECORDS(slot, cg, cr)
15046 {
15047 if (!cr->resrec.InterfaceID)
15048 {
15049 mDNS_PurgeCacheResourceRecord(m, cr);
15050 count++;
15051 }
15052 }
15053 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15054 m->DNSServers ? "DNS server became" : "No DNS servers", count);
15055
15056 // Force anything that needs to get zone data to get that information again
15057 RestartRecordGetZoneData(m);
15058 }
15059
15060 SetDynDNSHostNameIfChanged(m, &fqdn);
15061
15062 mDNS_Unlock(m);
15063
15064 // handle router and primary interface changes
15065 v4 = v6 = r = zeroAddr;
15066 v4.type = r.type = mDNSAddrType_IPv4;
15067
15068 if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
15069 {
15070 mDNS_SetPrimaryInterfaceInfo(m,
15071 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
15072 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
15073 !mDNSIPv4AddressIsZero(r.ip.v4) ? &r : mDNSNULL);
15074 }
15075 else
15076 {
15077 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
15078 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
15079 }
15080
15081 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
15082 return mStatus_NoError;
15083 }
15084
15085 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
15086 {
15087 m->mDNSPlatformStatus = result;
15088 if (m->MainCallback)
15089 {
15090 mDNS_Lock(m);
15091 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15092 m->MainCallback(m, mStatus_NoError);
15093 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15094 mDNS_Unlock(m);
15095 }
15096 }
15097
15098 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
15099 {
15100 m->CurrentRecord = start;
15101 while (m->CurrentRecord)
15102 {
15103 AuthRecord *rr = m->CurrentRecord;
15104 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15105 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
15106 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15107 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
15108 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
15109 else if (rr->AnnounceCount > 1)
15110 {
15111 rr->AnnounceCount = 1;
15112 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
15113 }
15114 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15115 // new records could have been added to the end of the list as a result of that call.
15116 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
15117 m->CurrentRecord = rr->next;
15118 }
15119 }
15120
15121 mDNSexport void mDNS_StartExit(mDNS *const m)
15122 {
15123 AuthRecord *rr;
15124
15125 mDNS_Lock(m);
15126
15127 LogInfo("mDNS_StartExit");
15128 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
15129
15130 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
15131
15132 #if APPLE_OSX_mDNSResponder
15133 #if !NO_WCF
15134 CHECK_WCF_FUNCTION(WCFConnectionDealloc)
15135 {
15136 if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
15137 }
15138 #endif
15139 #endif
15140
15141 #ifndef UNICAST_DISABLED
15142 {
15143 SearchListElem *s;
15144 SuspendLLQs(m);
15145 // Don't need to do SleepRecordRegistrations() here
15146 // because we deregister all records and services later in this routine
15147 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
15148
15149 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15150 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15151 // and we may crash because the list still contains dangling pointers.
15152 for (s = SearchList; s; s = s->next)
15153 while (s->AuthRecs)
15154 {
15155 ARListElem *dereg = s->AuthRecs;
15156 s->AuthRecs = s->AuthRecs->next;
15157 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
15158 }
15159 }
15160 #endif
15161
15162 DeadvertiseAllInterfaceRecords(m);
15163
15164 // Shut down all our active NAT Traversals
15165 while (m->NATTraversals)
15166 {
15167 NATTraversalInfo *t = m->NATTraversals;
15168 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15169
15170 // After stopping the NAT Traversal, we zero out the fields.
15171 // This has particularly important implications for our AutoTunnel records --
15172 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15173 // handlers to just turn around and attempt to re-register those same records.
15174 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15175 // to not do this.
15176 t->ExternalAddress = zerov4Addr;
15177 t->NewAddress = zerov4Addr;
15178 t->ExternalPort = zeroIPPort;
15179 t->RequestedPort = zeroIPPort;
15180 t->Lifetime = 0;
15181 t->Result = mStatus_NoError;
15182 }
15183
15184 // Make sure there are nothing but deregistering records remaining in the list
15185 if (m->CurrentRecord)
15186 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
15187
15188 // We're in the process of shutting down, so queries, etc. are no longer available.
15189 // Consequently, determining certain information, e.g. the uDNS update server's IP
15190 // address, will not be possible. The records on the main list are more likely to
15191 // already contain such information, so we deregister the duplicate records first.
15192 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
15193 DeregLoop(m, m->DuplicateRecords);
15194 LogInfo("mDNS_StartExit: Deregistering resource records");
15195 DeregLoop(m, m->ResourceRecords);
15196
15197 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15198 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15199 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
15200 {
15201 m->NextScheduledResponse = m->timenow;
15202 m->SuppressSending = 0;
15203 }
15204
15205 if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
15206 else LogInfo("mDNS_StartExit: No deregistering records remain");
15207
15208 for (rr = m->DuplicateRecords; rr; rr = rr->next)
15209 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
15210
15211 // If any deregistering records remain, send their deregistration announcements before we exit
15212 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
15213
15214 mDNS_Unlock(m);
15215
15216 LogInfo("mDNS_StartExit: done");
15217 }
15218
15219 mDNSexport void mDNS_FinalExit(mDNS *const m)
15220 {
15221 mDNSu32 rrcache_active = 0;
15222 mDNSu32 rrcache_totalused = m->rrcache_totalused;
15223 mDNSu32 slot;
15224 AuthRecord *rr;
15225
15226 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
15227 mDNSPlatformClose(m);
15228
15229 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
15230 {
15231 while (m->rrcache_hash[slot])
15232 {
15233 CacheGroup *cg = m->rrcache_hash[slot];
15234 while (cg->members)
15235 {
15236 CacheRecord *cr = cg->members;
15237 cg->members = cg->members->next;
15238 if (cr->CRActiveQuestion) rrcache_active++;
15239 ReleaseCacheRecord(m, cr);
15240 }
15241 cg->rrcache_tail = &cg->members;
15242 ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
15243 }
15244 }
15245 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
15246 if (rrcache_active != m->rrcache_active)
15247 LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active);
15248
15249 for (rr = m->ResourceRecords; rr; rr = rr->next)
15250 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15251
15252 LogInfo("mDNS_FinalExit: done");
15253 }
15254
15255 #ifdef UNIT_TEST
15256 #include "../unittests/mdns_ut.c"
15257 #endif