]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-522.92.1.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2013 Apple Computer, 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 untility 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
49 #if APPLE_OSX_mDNSResponder
50
51 #include <WebFilterDNS/WebFilterDNS.h>
52
53 #if !NO_WCF
54 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
55 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
56
57 // Do we really need to define a macro for "if"?
58 #define CHECK_WCF_FUNCTION(X) if (X)
59 #endif // ! NO_WCF
60
61 #else
62
63 #define NO_WCF 1
64 #endif // APPLE_OSX_mDNSResponder
65
66 // Forward declarations
67 mDNSlocal void BeginSleepProcessing(mDNS *const m);
68 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
69 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password);
70 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
71 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
72 mDNSlocal void mDNS_PurgeForQuestion(mDNS *const m, DNSQuestion *q);
73 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q);
74 mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
75 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth,
76 mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
77
78 mDNSlocal void AdvertiseAllInterfaceRecords(mDNS *const m);
79 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m);
80 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords);
81 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
82 const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records);
83
84
85 // ***************************************************************************
86 #if COMPILER_LIKES_PRAGMA_MARK
87 #pragma mark - Program Constants
88 #endif
89
90 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
91 #define MDNS_TRACER 1
92
93 #define NO_HINFO 1
94
95 // Any records bigger than this are considered 'large' records
96 #define SmallRecordLimit 1024
97
98 #define kMaxUpdateCredits 10
99 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
100
101 // define special NR_AnswerTo values
102 #define NR_AnswerMulticast (mDNSu8*)~0
103 #define NR_AnswerUnicast (mDNSu8*)~1
104
105 // Defined to set the kDNSQClass_UnicastResponse bit in the first four query packets.
106 // else, it's just set it the first query.
107 #define mDNS_REQUEST_UNICAST_RESPONSE 0
108
109 // The code (see SendQueries() and BuildQuestion()) needs to have the
110 // RequestUnicast value set to a value one greater than the number of times you want the query
111 // sent with the "request unicast response" (QU) bit set.
112 #define SET_QU_IN_FIRST_QUERY 2
113 #define SET_QU_IN_FIRST_FOUR_QUERIES 5
114
115
116 mDNSexport const char *const mDNS_DomainTypeNames[] =
117 {
118 "b._dns-sd._udp.", // Browse
119 "db._dns-sd._udp.", // Default Browse
120 "lb._dns-sd._udp.", // Automatic Browse
121 "r._dns-sd._udp.", // Registration
122 "dr._dns-sd._udp." // Default Registration
123 };
124
125 #ifdef UNICAST_DISABLED
126 #define uDNS_IsActiveQuery(q, u) mDNSfalse
127 #endif
128
129 // ***************************************************************************
130 #if COMPILER_LIKES_PRAGMA_MARK
131 #pragma mark -
132 #pragma mark - General Utility Functions
133 #endif
134
135 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
136 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
137 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
138 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
139 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
140 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
141 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
142 (rr)->resrec.rrtype == kDNSType_CNAME || \
143 (rr)->resrec.rrtype == kDNSType_PTR))
144
145 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
146 {
147 mDNS_CheckLock(m);
148
149 #if ForceAlerts
150 if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
151 #endif
152
153 if (m->NextScheduledStopTime - q->StopTime > 0)
154 m->NextScheduledStopTime = q->StopTime;
155 }
156
157 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
158 {
159 mDNS_CheckLock(m);
160
161 #if ForceAlerts
162 if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
163 #endif
164
165 if (ActiveQuestion(q))
166 {
167 // Depending on whether this is a multicast or unicast question we want to set either:
168 // m->NextScheduledQuery = NextQSendTime(q) or
169 // m->NextuDNSEvent = NextQSendTime(q)
170 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
171 if (*timer - NextQSendTime(q) > 0)
172 *timer = NextQSendTime(q);
173 }
174 }
175
176 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
177 {
178 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
179 unsigned int i;
180 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
181 #endif
182 e->next = r->rrauth_free;
183 r->rrauth_free = e;
184 r->rrauth_totalused--;
185 }
186
187 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
188 {
189 AuthEntity *e = (AuthEntity *)(*cp);
190 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp)->name->c);
191 if ((*cp)->rrauth_tail != &(*cp)->members)
192 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
193 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
194 (*cp)->name = mDNSNULL;
195 *cp = (*cp)->next; // Cut record from list
196 ReleaseAuthEntity(r, e);
197 }
198
199 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
200 {
201 AuthEntity *e = mDNSNULL;
202
203 if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
204 r->rrauth_lock = 1;
205
206 if (!r->rrauth_free)
207 {
208 // We allocate just one AuthEntity at a time because we need to be able
209 // free them all individually which normally happens when we parse /etc/hosts into
210 // AuthHash where we add the "new" entries and discard (free) the already added
211 // entries. If we allocate as chunks, we can't free them individually.
212 AuthEntity *storage = mDNSPlatformMemAllocate(sizeof(AuthEntity));
213 storage->next = mDNSNULL;
214 r->rrauth_free = storage;
215 }
216
217 // If we still have no free records, recycle all the records we can.
218 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
219 if (!r->rrauth_free)
220 {
221 mDNSu32 oldtotalused = r->rrauth_totalused;
222 mDNSu32 slot;
223 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
224 {
225 AuthGroup **cp = &r->rrauth_hash[slot];
226 while (*cp)
227 {
228 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
229 else ReleaseAuthGroup(r, cp);
230 }
231 }
232 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
233 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
234 }
235
236 if (r->rrauth_free) // If there are records in the free list, take one
237 {
238 e = r->rrauth_free;
239 r->rrauth_free = e->next;
240 if (++r->rrauth_totalused >= r->rrauth_report)
241 {
242 LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
243 if (r->rrauth_report < 100) r->rrauth_report += 10;
244 else if (r->rrauth_report < 1000) r->rrauth_report += 100;
245 else r->rrauth_report += 1000;
246 }
247 mDNSPlatformMemZero(e, sizeof(*e));
248 }
249
250 r->rrauth_lock = 0;
251
252 return(e);
253 }
254
255 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
256 {
257 AuthGroup *ag;
258 for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
259 if (ag->namehash == namehash && SameDomainName(ag->name, name))
260 break;
261 return(ag);
262 }
263
264 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
265 {
266 return(AuthGroupForName(r, slot, rr->namehash, rr->name));
267 }
268
269 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
270 {
271 mDNSu16 namelen = DomainNameLength(rr->name);
272 AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
273 if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
274 ag->next = r->rrauth_hash[slot];
275 ag->namehash = rr->namehash;
276 ag->members = mDNSNULL;
277 ag->rrauth_tail = &ag->members;
278 ag->NewLocalOnlyRecords = mDNSNULL;
279 if (namelen > sizeof(ag->namestorage))
280 ag->name = mDNSPlatformMemAllocate(namelen);
281 else
282 ag->name = (domainname*)ag->namestorage;
283 if (!ag->name)
284 {
285 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
286 ReleaseAuthEntity(r, (AuthEntity*)ag);
287 return(mDNSNULL);
288 }
289 AssignDomainName(ag->name, rr->name);
290
291 if (AuthGroupForRecord(r, slot, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
292 r->rrauth_hash[slot] = ag;
293 if (AuthGroupForRecord(r, slot, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
294
295 return(ag);
296 }
297
298 // Returns the AuthGroup in which the AuthRecord was inserted
299 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
300 {
301 AuthGroup *ag;
302 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
303 ag = AuthGroupForRecord(r, slot, &rr->resrec);
304 if (!ag) ag = GetAuthGroup(r, slot, &rr->resrec); // If we don't have a AuthGroup for this name, make one now
305 if (ag)
306 {
307 LogInfo("InsertAuthRecord: inserting auth record %s from table", ARDisplayString(m, rr));
308 *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list
309 ag->rrauth_tail = &(rr->next); // Advance tail pointer
310 }
311 return ag;
312 }
313
314 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
315 {
316 AuthGroup *a;
317 AuthGroup **ag = &a;
318 AuthRecord **rp;
319 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
320
321 a = AuthGroupForRecord(r, slot, &rr->resrec);
322 if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
323 rp = &(*ag)->members;
324 while (*rp)
325 {
326 if (*rp != rr)
327 rp=&(*rp)->next;
328 else
329 {
330 // We don't break here, so that we can set the tail below without tracking "prev" pointers
331
332 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
333 *rp = (*rp)->next; // Cut record from list
334 }
335 }
336 // TBD: If there are no more members, release authgroup ?
337 (*ag)->rrauth_tail = rp;
338 return a;
339 }
340
341 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
342 {
343 CacheGroup *cg;
344 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
345 if (cg->namehash == namehash && SameDomainName(cg->name, name))
346 break;
347 return(cg);
348 }
349
350 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
351 {
352 return(CacheGroupForName(m, slot, rr->namehash, rr->name));
353 }
354
355 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr, mDNSBool *myself)
356 {
357 NetworkInterfaceInfo *intf;
358
359 if (addr->type == mDNSAddrType_IPv4)
360 {
361 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
362 if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
363 for (intf = m->HostInterfaces; intf; intf = intf->next)
364 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
365 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
366 {
367 if (myself)
368 {
369 if (mDNSSameIPv4Address(intf->ip.ip.v4, addr->ip.v4))
370 *myself = mDNStrue;
371 else
372 *myself = mDNSfalse;
373 if (*myself)
374 debugf("mDNS_AddressIsLocalSubnet: IPv4 %#a returning true", addr);
375 else
376 debugf("mDNS_AddressIsLocalSubnet: IPv4 %#a returning false", addr);
377 }
378 return(mDNStrue);
379 }
380 }
381
382 if (addr->type == mDNSAddrType_IPv6)
383 {
384 for (intf = m->HostInterfaces; intf; intf = intf->next)
385 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
386 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
387 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
388 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
389 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
390 {
391 if (myself)
392 {
393 if (mDNSSameIPv6Address(intf->ip.ip.v6, addr->ip.v6))
394 *myself = mDNStrue;
395 else
396 *myself = mDNSfalse;
397 if (*myself)
398 debugf("mDNS_AddressIsLocalSubnet: IPv6 %#a returning true", addr);
399 else
400 debugf("mDNS_AddressIsLocalSubnet: IPv6 %#a returning false", addr);
401 }
402 return(mDNStrue);
403 }
404 }
405
406 return(mDNSfalse);
407 }
408
409 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
410 {
411 NetworkInterfaceInfo *intf = m->HostInterfaces;
412 while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
413 return(intf);
414 }
415
416 mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
417 {
418 NetworkInterfaceInfo *intf;
419
420 if (!InterfaceID)
421 return mDNSNULL;
422
423 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
424 // we still want to find the first IPv4 Link-Local interface
425 for (intf = m->HostInterfaces; intf; intf = intf->next)
426 {
427 if (intf->InterfaceID == InterfaceID &&
428 intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4))
429 {
430 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4);
431 return intf;
432 }
433 }
434 return (mDNSNULL);
435 }
436
437 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
438 {
439 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
440 return(intf ? intf->ifname : mDNSNULL);
441 }
442
443 // Caller should hold the lock
444 mDNSlocal void GenerateNegativeResponse(mDNS *const m, QC_result qc)
445 {
446 DNSQuestion *q;
447 if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
448 q = m->CurrentQuestion;
449 LogInfo("GenerateNegativeResponse: Generating negative response for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
450
451 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, mDNSNULL);
452 // We need to force the response through in the following cases
453 //
454 // a) SuppressUnusable questions that are suppressed
455 // b) Append search domains and retry the question
456 //
457 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
458 // through we use "QC_forceresponse".
459 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc);
460 if (m->CurrentQuestion == q) { q->ThisQInterval = 0; } // Deactivate this question
461 // Don't touch the question after this
462 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
463 }
464
465 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
466 {
467 const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
468 if (q->CNAMEReferrals >= 10 || selfref)
469 LogMsg("AnswerQuestionByFollowingCNAME: %p %##s (%s) NOT following CNAME referral %d%s for %s",
470 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
471 else
472 {
473 const mDNSu32 c = q->CNAMEReferrals + 1; // Stash a copy of the new q->CNAMEReferrals value
474 UDPSocket *sock = q->LocalSocket;
475 mDNSOpaque16 id = q->TargetQID;
476
477 // if there is a message waiting at the socket, we want to process that instead
478 // of throwing it away. If we have a CNAME response that answers
479 // both A and AAAA question and while answering it we don't want to throw
480 // away the response where the actual addresses are present.
481 if (mDNSPlatformPeekUDP(m, q->LocalSocket))
482 {
483 LogInfo("AnswerQuestionByFollowingCNAME: Preserving UDP socket for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
484 q->LocalSocket = mDNSNULL;
485 }
486 else
487 {
488 sock = mDNSNULL;
489 }
490
491 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
492 // themselves. Without that check we can get into a case where we have two duplicate questions,
493 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
494 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
495 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
496 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
497 // for either of them. This is not a problem for CNAME loops of two or more records because in
498 // those cases the newly re-appended question A has a different target name and therefore cannot be
499 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
500
501 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
502 // and track CNAMEs coming and going, we should really create a subordinate query here,
503 // which we would subsequently cancel and retract if the CNAME referral record were removed.
504 // In reality this is such a corner case we'll ignore it until someone actually needs it.
505
506 LogInfo("AnswerQuestionByFollowingCNAME: %p %##s (%s) following CNAME referral %d for %s",
507 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, RRDisplayString(m, rr));
508
509 mDNS_StopQuery_internal(m, q); // Stop old query
510 AssignDomainName(&q->qname, &rr->rdata->u.name); // Update qname
511 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
512 // If a unicast query results in a CNAME that points to a .local, we need to re-try
513 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
514 // to try this as unicast query even though it is a .local name
515 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
516 {
517 LogInfo("AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p %##s (%s) Record %s",
518 q, q->qname.c, DNSTypeName(q->qtype), RRDisplayString(m, rr));
519 q->InterfaceID = mDNSInterface_Unicast;
520 }
521 mDNS_StartQuery_internal(m, q); // start new query
522 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
523 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
524 q->CNAMEReferrals = c;
525 if (sock)
526 {
527 // We have a message waiting and that should answer this question.
528 if (q->LocalSocket)
529 mDNSPlatformUDPClose(q->LocalSocket);
530 q->LocalSocket = sock;
531 q->TargetQID = id;
532 }
533 }
534 }
535
536 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
537 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
538 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
539 {
540 DNSQuestion *q = m->CurrentQuestion;
541 mDNSBool followcname;
542
543 if (!q)
544 {
545 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
546 return;
547 }
548
549 followcname = FollowCNAME(q, &rr->resrec, AddRecord);
550
551 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
552 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
553 {
554 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
555 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
556 return;
557 }
558
559 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
560 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
561 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
562 if (q->QuestionCallback && !q->NoAnswer)
563 {
564 q->CurrentAnswers += AddRecord ? 1 : -1;
565 if (UniqueLocalOnlyRecord(rr))
566 {
567 if (!followcname || q->ReturnIntermed)
568 {
569 // Don't send this packet on the wire as we answered from /etc/hosts
570 q->ThisQInterval = 0;
571 q->LOAddressAnswers += AddRecord ? 1 : -1;
572 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
573 }
574 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
575 // The callback above could have caused the question to stop. Detect that
576 // using m->CurrentQuestion
577 if (followcname && m->CurrentQuestion == q)
578 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
579 return;
580 }
581 else
582 {
583 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
584 }
585 }
586 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
587 }
588
589 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
590 {
591 if (m->CurrentQuestion)
592 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
593 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
594 m->CurrentQuestion = m->Questions;
595 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
596 {
597 mDNSBool answered;
598 DNSQuestion *q = m->CurrentQuestion;
599 if (RRAny(rr))
600 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
601 else
602 answered = LocalOnlyRecordAnswersQuestion(rr, q);
603 if (answered)
604 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
605 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
606 m->CurrentQuestion = q->next;
607 }
608 m->CurrentQuestion = mDNSNULL;
609 }
610
611 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
612 // delivers the appropriate add/remove events to listening questions:
613 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
614 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
615 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
616 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
617 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
618 //
619 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
620 // and by mDNS_Deregister_internal()
621
622 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
623 {
624 if (m->CurrentQuestion)
625 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
626 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
627
628 m->CurrentQuestion = m->LocalOnlyQuestions;
629 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
630 {
631 mDNSBool answered;
632 DNSQuestion *q = m->CurrentQuestion;
633 // We are called with both LocalOnly/P2P record or a regular AuthRecord
634 if (RRAny(rr))
635 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
636 else
637 answered = LocalOnlyRecordAnswersQuestion(rr, q);
638 if (answered)
639 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
640 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
641 m->CurrentQuestion = q->next;
642 }
643
644 m->CurrentQuestion = mDNSNULL;
645
646 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
647 if (rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P)
648 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, rr, AddRecord);
649
650 }
651
652 // ***************************************************************************
653 #if COMPILER_LIKES_PRAGMA_MARK
654 #pragma mark -
655 #pragma mark - Resource Record Utility Functions
656 #endif
657
658 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
659
660 #define ResourceRecordIsValidAnswer(RR) ( ((RR)->resrec.RecordType & kDNSRecordTypeActiveMask) && \
661 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
662 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
663 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
664
665 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
666 (ResourceRecordIsValidAnswer(RR) && \
667 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
668
669 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
670 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
671
672 // See RFC 6762: "8.3 Announcing"
673 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
674 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
675 #define InitialAnnounceCount ((mDNSu8)4)
676
677 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
678 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
679 // and then if the machine fails to wake, 3 goodbye packets).
680 #define GoodbyeCount ((mDNSu8)3)
681 #define WakeupCount ((mDNSu8)18)
682 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
683
684 // Number of wakeups we send if WakeOnResolve is set in the question
685 #define InitialWakeOnResolveCount ((mDNSu8)3)
686
687 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
688 // This means that because the announce interval is doubled after sending the first packet, the first
689 // observed on-the-wire inter-packet interval between announcements is actually one second.
690 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
691 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
692 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
693 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
694
695 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
696 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
697 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
698
699 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
700 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
701 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
702 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
703
704 // Adjustment factor to avoid race condition (used for unicast cache entries) :
705 // 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.
706 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
707 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
708 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
709 // We adjust the 100 second TTL to 127. This means that when we do our 80% query at 102 seconds,
710 // the cached copy at our local caching server will already have expired, so the server will be forced
711 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
712
713 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
714 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
715
716 #define MaxUnansweredQueries 4
717
718 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
719 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
720 // TTL and rdata may differ.
721 // This is used for cache flush management:
722 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
723 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
724
725 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
726
727 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
728
729 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
730 {
731 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
732 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
733 if (r1->resrec.InterfaceID &&
734 r2->resrec.InterfaceID &&
735 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
736 return (mDNSBool)(
737 r1->resrec.rrclass == r2->resrec.rrclass &&
738 r1->resrec.namehash == r2->resrec.namehash &&
739 SameDomainName(r1->resrec.name, r2->resrec.name));
740 }
741
742 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
743 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
744 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
745 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
746 // so a response of any type should match, even if it is not actually the type the client plans to use.
747
748 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
749 // and require the rrtypes to match for the rdata to be considered potentially conflicting
750 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
751 {
752 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
753 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
754 if (pktrr->resrec.InterfaceID &&
755 authrr->resrec.InterfaceID &&
756 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
757 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
758 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
759 return (mDNSBool)(
760 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
761 pktrr->resrec.namehash == authrr->resrec.namehash &&
762 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
763 }
764
765 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
766 // This is the information that the requester believes to be correct.
767 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
768 // This is the information that we believe to be correct.
769 // We've already determined that we plan to give this answer on this interface
770 // (either the record is non-specific, or it is specific to this interface)
771 // so now we just need to check the name, type, class, rdata and TTL.
772 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
773 {
774 // If RR signature is different, or data is different, then don't suppress our answer
775 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
776
777 // If the requester's indicated TTL is less than half the real TTL,
778 // we need to give our answer before the requester's copy expires.
779 // If the requester's indicated TTL is at least half the real TTL,
780 // then we can suppress our answer this time.
781 // If the requester's indicated TTL is greater than the TTL we believe,
782 // then that's okay, and we don't need to do anything about it.
783 // (If two responders on the network are offering the same information,
784 // that's okay, and if they are offering the information with different TTLs,
785 // the one offering the lower TTL should defer to the one offering the higher TTL.)
786 return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
787 }
788
789 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
790 {
791 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
792 {
793 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
794 {
795 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
796 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
797 }
798 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
799 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
800 // Some defensive code:
801 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
802 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
803 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
804 if (m->NextScheduledProbe - m->timenow < 0)
805 m->NextScheduledProbe = m->timenow;
806 }
807 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
808 {
809 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
810 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
811 }
812 }
813
814 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
815 {
816 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
817 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
818
819 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
820 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
821 // records that are going to probe, then we delay its first announcement so that it will
822 // go out synchronized with the first announcement for the other records that *are* probing.
823 // This is a minor performance tweak that helps keep groups of related records synchronized together.
824 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
825 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
826 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
827 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
828 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
829
830 if (rr->ProbeCount)
831 {
832 // If we have no probe suppression time set, or it is in the past, set it now
833 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
834 {
835 // To allow us to aggregate probes when a group of services are registered together,
836 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
837 // 1/4 second wait; probe
838 // 1/4 second wait; probe
839 // 1/4 second wait; probe
840 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
841 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
842
843 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
844 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
845 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
846 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
847 m->SuppressProbes = m->timenow;
848
849 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
850 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
851 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
852 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
853 m->SuppressProbes = m->timenow;
854
855 // except... don't expect to be able to send before the m->SuppressSending timer fires
856 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
857 m->SuppressProbes = NonZeroTime(m->SuppressSending);
858
859 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
860 {
861 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
862 m->SuppressProbes - m->timenow,
863 m->NextScheduledProbe - m->timenow,
864 m->NextScheduledQuery - m->timenow,
865 m->SuppressSending,
866 m->SuppressSending - m->timenow);
867 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
868 }
869 }
870 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
871 }
872 else if (m->SuppressProbes && m->SuppressProbes - m->timenow >= 0)
873 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
874 else
875 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
876
877 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
878 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
879 // After three probes one second apart with no answer, we conclude the client is now sleeping
880 // and we can begin broadcasting our announcements to take over ownership of that IP address.
881 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
882 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
883 if (rr->AddressProxy.type)
884 rr->LastAPTime = m->timenow;
885
886 // Set LastMCTime to now, to inhibit multicast responses
887 // (no need to send additional multicast responses when we're announcing anyway)
888 rr->LastMCTime = m->timenow;
889 rr->LastMCInterface = mDNSInterfaceMark;
890
891 SetNextAnnounceProbeTime(m, rr);
892 }
893
894 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
895 {
896 const domainname *target;
897 if (rr->AutoTarget)
898 {
899 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
900 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
901 // with the port number in our advertised SRV record automatically tracking the external mapped port.
902 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
903 if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
904 }
905
906 target = GetServiceTarget(m, rr);
907 if (!target || target->c[0] == 0)
908 {
909 // defer registration until we've got a target
910 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
911 rr->state = regState_NoTarget;
912 return mDNSNULL;
913 }
914 else
915 {
916 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
917 return target;
918 }
919 }
920
921 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
922 // Eventually we should unify this with GetServiceTarget() in uDNS.c
923 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
924 {
925 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
926 const domainname *newname = &m->MulticastHostname;
927
928 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
929
930 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
931 {
932 const domainname *const n = SetUnicastTargetToHostName(m, rr);
933 if (n) newname = n;
934 else { target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
935 }
936
937 if (target && SameDomainName(target, newname))
938 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
939
940 if (target && !SameDomainName(target, newname))
941 {
942 AssignDomainName(target, newname);
943 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
944
945 // If we're in the middle of probing this record, we need to start again,
946 // because changing its rdata may change the outcome of the tie-breaker.
947 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
948 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
949
950 // If we've announced this record, we really should send a goodbye packet for the old rdata before
951 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
952 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
953 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
954 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
955 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
956
957 rr->AnnounceCount = InitialAnnounceCount;
958 rr->RequireGoodbye = mDNSfalse;
959 rr->ProbeRestartCount = 0;
960 InitializeLastAPTime(m, rr);
961 }
962 }
963
964 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
965 {
966 if (rr->RecordCallback)
967 {
968 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
969 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
970 rr->Acknowledged = mDNStrue;
971 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
972 rr->RecordCallback(m, rr, mStatus_NoError);
973 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
974 }
975 }
976
977 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
978 {
979 // Make sure that we don't activate the SRV record and associated service records, if it is in
980 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
981 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
982 // the target becomes available, the records will be reregistered.
983 if (rr->resrec.rrtype != kDNSType_SRV)
984 {
985 AuthRecord *srvRR = mDNSNULL;
986 if (rr->resrec.rrtype == kDNSType_PTR)
987 srvRR = rr->Additional1;
988 else if (rr->resrec.rrtype == kDNSType_TXT)
989 srvRR = rr->DependentOn;
990 if (srvRR)
991 {
992 if (srvRR->resrec.rrtype != kDNSType_SRV)
993 {
994 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
995 }
996 else
997 {
998 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
999 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1000 rr->state = srvRR->state;
1001 }
1002 }
1003 }
1004
1005 if (rr->state == regState_NoTarget)
1006 {
1007 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1008 return;
1009 }
1010 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1011 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1012 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1013 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1014 // 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.
1015 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1016 {
1017 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1018 rr->state = regState_DeregPending;
1019 }
1020 else
1021 {
1022 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1023 rr->state = regState_Pending;
1024 }
1025 rr->ProbeCount = 0;
1026 rr->ProbeRestartCount = 0;
1027 rr->AnnounceCount = 0;
1028 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1029 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1030 rr->expire = 0; // Forget about all the leases, start fresh
1031 rr->uselease = mDNStrue;
1032 rr->updateid = zeroID;
1033 rr->SRVChanged = mDNSfalse;
1034 rr->updateError = mStatus_NoError;
1035 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1036 // The records might already be registered with the server and hence could have NAT state.
1037 if (rr->NATinfo.clientContext)
1038 {
1039 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1040 rr->NATinfo.clientContext = mDNSNULL;
1041 }
1042 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1043 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1044 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1045 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1046 }
1047
1048 // Two records qualify to be local duplicates if:
1049 // (a) the RecordTypes are the same, or
1050 // (b) one is Unique and the other Verified
1051 // (c) either is in the process of deregistering
1052 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1053 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1054 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1055
1056 #define RecordIsLocalDuplicate(A,B) \
1057 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1058
1059 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1060 {
1061 AuthGroup *a;
1062 AuthGroup **ag = &a;
1063 AuthRecord **rp;
1064 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1065
1066 a = AuthGroupForRecord(r, slot, &rr->resrec);
1067 if (!a) return mDNSNULL;
1068 rp = &(*ag)->members;
1069 while (*rp)
1070 {
1071 if (!RecordIsLocalDuplicate(*rp, rr))
1072 rp=&(*rp)->next;
1073 else
1074 {
1075 if ((*rp)->resrec.RecordType == kDNSRecordTypeDeregistering)
1076 {
1077 (*rp)->AnnounceCount = 0;
1078 rp=&(*rp)->next;
1079 }
1080 else return *rp;
1081 }
1082 }
1083 return (mDNSNULL);
1084 }
1085
1086 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1087 {
1088 AuthGroup *a;
1089 AuthGroup **ag = &a;
1090 AuthRecord **rp;
1091 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1092
1093 a = AuthGroupForRecord(r, slot, &rr->resrec);
1094 if (!a) return mDNSfalse;
1095 rp = &(*ag)->members;
1096 while (*rp)
1097 {
1098 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1099 const AuthRecord *s2 = (*rp)->RRSet ? (*rp)->RRSet : *rp;
1100 if (s1 != s2 && SameResourceRecordSignature((*rp), rr) && !IdenticalSameNameRecord(&(*rp)->resrec, &rr->resrec))
1101 return mDNStrue;
1102 else
1103 rp=&(*rp)->next;
1104 }
1105 return (mDNSfalse);
1106 }
1107
1108 // checks to see if "rr" is already present
1109 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1110 {
1111 AuthGroup *a;
1112 AuthGroup **ag = &a;
1113 AuthRecord **rp;
1114 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1115
1116 a = AuthGroupForRecord(r, slot, &rr->resrec);
1117 if (!a) return mDNSNULL;
1118 rp = &(*ag)->members;
1119 while (*rp)
1120 {
1121 if (*rp != rr)
1122 rp=&(*rp)->next;
1123 else
1124 {
1125 return *rp;
1126 }
1127 }
1128 return (mDNSNULL);
1129 }
1130
1131
1132 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1133 {
1134 if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1135 {
1136 m->AutoTargetServices--;
1137 LogInfo("DecrementAutoTargetServices: AutoService Record %s, AutoTargetServices %d", ARDisplayString(m, rr), m->AutoTargetServices);
1138 if (!m->AutoTargetServices)
1139 DeadvertiseAllInterfaceRecords(m);
1140 }
1141 }
1142
1143 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1144 {
1145 if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1146 {
1147 int count = m->AutoTargetServices;
1148
1149 // Bump up before calling AdvertiseAllInterfaceRecords. AdvertiseInterface
1150 // returns without doing anything if the count is zero.
1151 m->AutoTargetServices++;
1152 LogInfo("IncrementAutoTargetServices: AutoService Record %s, AutoTargetServices %d", ARDisplayString(m, rr), m->AutoTargetServices);
1153 if (!count)
1154 AdvertiseAllInterfaceRecords(m);
1155 }
1156 }
1157
1158 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1159 {
1160 mDNSAddr laddr;
1161 mDNSEthAddr eth;
1162 mDNSIPPort lport, rport;
1163 mDNSu32 timeout, seq, ack;
1164 mDNSu16 win;
1165
1166 if (mDNS_KeepaliveRecord(&rr->resrec))
1167 {
1168 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, &eth, &seq, &ack, &lport, &rport, &win);
1169 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1170 {
1171 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1172 return;
1173 }
1174 }
1175 }
1176
1177 // Exported so uDNS.c can call this
1178 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1179 {
1180 domainname *target = GetRRDomainNameTarget(&rr->resrec);
1181 AuthRecord *r;
1182 AuthRecord **p = &m->ResourceRecords;
1183 AuthRecord **d = &m->DuplicateRecords;
1184
1185 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1186 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1187
1188 if (!rr->resrec.RecordType)
1189 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1190
1191 if (m->ShutdownTime)
1192 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1193
1194 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1195 {
1196 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1197 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1198 {
1199 rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1200 rr->ARType = AuthRecordLocalOnly;
1201 }
1202 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1203 {
1204 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1205 if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1206 }
1207 if (rr->resrec.InterfaceID != previousID)
1208 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1209 }
1210
1211 if (RRLocalOnly(rr))
1212 {
1213 if (CheckAuthSameRecord(&m->rrauth, rr))
1214 {
1215 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1216 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1217 return(mStatus_AlreadyRegistered);
1218 }
1219 }
1220 else
1221 {
1222 while (*p && *p != rr) p=&(*p)->next;
1223 if (*p)
1224 {
1225 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1226 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1227 return(mStatus_AlreadyRegistered);
1228 }
1229 }
1230
1231 while (*d && *d != rr) d=&(*d)->next;
1232 if (*d)
1233 {
1234 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1235 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1236 return(mStatus_AlreadyRegistered);
1237 }
1238
1239 if (rr->DependentOn)
1240 {
1241 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1242 rr->resrec.RecordType = kDNSRecordTypeVerified;
1243 else
1244 {
1245 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1246 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1247 return(mStatus_Invalid);
1248 }
1249 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1250 {
1251 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1252 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1253 return(mStatus_Invalid);
1254 }
1255 }
1256
1257 // If this resource record is referencing a specific interface, make sure it exists.
1258 // Skip checks for LocalOnly and P2P as they are not valid InterfaceIDs. Also, for scoped
1259 // entries in /etc/hosts skip that check as that interface may not be valid at this time.
1260 if (rr->resrec.InterfaceID && rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
1261 {
1262 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1263 if (!intf)
1264 {
1265 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr->resrec.InterfaceID);
1266 return(mStatus_BadReferenceErr);
1267 }
1268 }
1269
1270 rr->next = mDNSNULL;
1271
1272 // Field Group 1: The actual information pertaining to this resource record
1273 // Set up by client prior to call
1274
1275 // Field Group 2: Persistent metadata for Authoritative Records
1276 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1277 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1278 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1279 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1280 // rr->Callback = already set in mDNS_SetupResourceRecord
1281 // rr->Context = already set in mDNS_SetupResourceRecord
1282 // rr->RecordType = already set in mDNS_SetupResourceRecord
1283 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1284 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1285 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1286 if (rr->AutoTarget && target) target->c[0] = 0;
1287
1288 // Field Group 3: Transient state for Authoritative Records
1289 rr->Acknowledged = mDNSfalse;
1290 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1291 rr->ProbeRestartCount = 0;
1292 rr->AnnounceCount = InitialAnnounceCount;
1293 rr->RequireGoodbye = mDNSfalse;
1294 rr->AnsweredLocalQ = mDNSfalse;
1295 rr->IncludeInProbe = mDNSfalse;
1296 rr->ImmedUnicast = mDNSfalse;
1297 rr->SendNSECNow = mDNSNULL;
1298 rr->ImmedAnswer = mDNSNULL;
1299 rr->ImmedAdditional = mDNSNULL;
1300 rr->SendRNow = mDNSNULL;
1301 rr->v4Requester = zerov4Addr;
1302 rr->v6Requester = zerov6Addr;
1303 rr->NextResponse = mDNSNULL;
1304 rr->NR_AnswerTo = mDNSNULL;
1305 rr->NR_AdditionalTo = mDNSNULL;
1306 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1307 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1308 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1309 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1310 rr->NewRData = mDNSNULL;
1311 rr->newrdlength = 0;
1312 rr->UpdateCallback = mDNSNULL;
1313 rr->UpdateCredits = kMaxUpdateCredits;
1314 rr->NextUpdateCredit = 0;
1315 rr->UpdateBlocked = 0;
1316
1317 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1318 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1319
1320 // Field Group 4: Transient uDNS state for Authoritative Records
1321 rr->state = regState_Zero;
1322 rr->uselease = 0;
1323 rr->expire = 0;
1324 rr->Private = 0;
1325 rr->updateid = zeroID;
1326 rr->updateIntID = zeroOpaque64;
1327 rr->zone = rr->resrec.name;
1328 rr->nta = mDNSNULL;
1329 rr->tcp = mDNSNULL;
1330 rr->OrigRData = 0;
1331 rr->OrigRDLen = 0;
1332 rr->InFlightRData = 0;
1333 rr->InFlightRDLen = 0;
1334 rr->QueuedRData = 0;
1335 rr->QueuedRDLen = 0;
1336 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1337 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1338 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1339 // times with different values if the external NAT port changes during the lifetime of the service registration.
1340 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1341
1342 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1343 // rr->resrec.name->c = MUST be set by client
1344 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1345 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1346 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1347 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1348
1349 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1350 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1351 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1352 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1353
1354 if (rr->AutoTarget)
1355 {
1356 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1357 #ifndef UNICAST_DISABLED
1358 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1359 // 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.
1360 if (rr->state == regState_NoTarget)
1361 {
1362 // Initialize the target so that we don't crash while logging etc.
1363 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1364 if (tar) tar->c[0] = 0;
1365 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1366 }
1367 #endif
1368 }
1369 else
1370 {
1371 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
1372 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1373 }
1374
1375 if (!ValidateDomainName(rr->resrec.name))
1376 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1377
1378 // Don't do this until *after* we've set rr->resrec.rdlength
1379 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1380 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1381
1382 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
1383 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1384
1385 if (RRLocalOnly(rr))
1386 {
1387 // If this is supposed to be unique, make sure we don't have any name conflicts.
1388 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1389 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1390 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1391 // Hence, just bail out.
1392 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1393 {
1394 if (CheckAuthRecordConflict(&m->rrauth, rr))
1395 {
1396 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1397 return mStatus_NameConflict;
1398 }
1399 }
1400 }
1401
1402 // For uDNS records, we don't support duplicate checks at this time.
1403 #ifndef UNICAST_DISABLED
1404 if (AuthRecord_uDNS(rr))
1405 {
1406 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1407 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1408 // 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.
1409 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1410 while (*p) p=&(*p)->next;
1411 *p = rr;
1412 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1413 rr->ProbeCount = 0;
1414 rr->ProbeRestartCount = 0;
1415 rr->AnnounceCount = 0;
1416 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1417 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
1418 }
1419 #endif
1420
1421 // Now that we've finished building our new record, make sure it's not identical to one we already have
1422 if (RRLocalOnly(rr))
1423 {
1424 rr->ProbeCount = 0;
1425 rr->ProbeRestartCount = 0;
1426 rr->AnnounceCount = 0;
1427 r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1428 }
1429 else
1430 {
1431 for (r = m->ResourceRecords; r; r=r->next)
1432 if (RecordIsLocalDuplicate(r, rr))
1433 {
1434 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1435 else break;
1436 }
1437 }
1438
1439 if (r)
1440 {
1441 debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m,rr));
1442 *d = rr;
1443 // If the previous copy of this record is already verified unique,
1444 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1445 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1446 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1447 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1448 rr->ProbeCount = 0;
1449 }
1450 else
1451 {
1452 debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1453 if (RRLocalOnly(rr))
1454 {
1455 AuthGroup *ag;
1456 ag = InsertAuthRecord(m, &m->rrauth, rr);
1457 if (ag && !ag->NewLocalOnlyRecords) {
1458 m->NewLocalOnlyRecords = mDNStrue;
1459 ag->NewLocalOnlyRecords = rr;
1460 }
1461 // No probing for LocalOnly records, Acknowledge them right away
1462 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1463 AcknowledgeRecord(m, rr);
1464 return(mStatus_NoError);
1465 }
1466 else
1467 {
1468 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1469 *p = rr;
1470 }
1471 }
1472
1473 // If this is a keepalive record, fetch the MAC address of the remote host.
1474 // This is used by the in-NIC proxy to send the keepalive packets.
1475 if (mDNS_KeepaliveRecord(&rr->resrec))
1476 {
1477 // Set the record type to known unique to prevent probing keep alive records.
1478 // Also make sure we do not announce the keepalive records.
1479 rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1480 rr->AnnounceCount = 0;
1481 mDNSAddr raddr;
1482 getKeepaliveRaddr(m, rr, &raddr);
1483 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1484 // asynchronous task to update the resource record
1485 mDNSPlatformGetRemoteMacAddr(m, &raddr);
1486 }
1487
1488 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
1489 {
1490 // We have inserted the record in the list. See if we have to advertise the A/AAAA,HINFO,PTR records.
1491 IncrementAutoTargetServices(m, rr);
1492 // For records that are not going to probe, acknowledge them right away
1493 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1494 AcknowledgeRecord(m, rr);
1495
1496 // Adding a record may affect whether or not we should sleep
1497 mDNS_UpdateAllowSleep(m);
1498 }
1499
1500 return(mStatus_NoError);
1501 }
1502
1503 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1504 {
1505 m->ProbeFailTime = m->timenow;
1506 m->NumFailedProbes++;
1507 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1508 // If a bunch of hosts have all been configured with the same name, then they'll all
1509 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1510 // up to name-10. After that they'll start adding random increments in the range 1-100,
1511 // so they're more likely to branch out in the available namespace and settle on a set of
1512 // unique names quickly. If after five more tries the host is still conflicting, then we
1513 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1514 if (m->NumFailedProbes >= 15)
1515 {
1516 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1517 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1518 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1519 }
1520 }
1521
1522 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1523 {
1524 RData *OldRData = rr->resrec.rdata;
1525 mDNSu16 OldRDLen = rr->resrec.rdlength;
1526 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
1527 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
1528 if (rr->UpdateCallback)
1529 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
1530 }
1531
1532 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1533 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1534 // Exported so uDNS.c can call this
1535 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1536 {
1537 AuthRecord *r2;
1538 mDNSu8 RecordType = rr->resrec.RecordType;
1539 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
1540 mDNSBool dupList = mDNSfalse;
1541
1542 if (RRLocalOnly(rr))
1543 {
1544 AuthGroup *a;
1545 AuthGroup **ag = &a;
1546 AuthRecord **rp;
1547 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1548
1549 a = AuthGroupForRecord(&m->rrauth, slot, &rr->resrec);
1550 if (!a) return mDNSfalse;
1551 rp = &(*ag)->members;
1552 while (*rp && *rp != rr) rp=&(*rp)->next;
1553 p = rp;
1554 }
1555 else
1556 {
1557 while (*p && *p != rr) p=&(*p)->next;
1558 }
1559
1560 if (*p)
1561 {
1562 // We found our record on the main list. See if there are any duplicates that need special handling.
1563 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
1564 {
1565 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1566 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1567 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1568 }
1569 else
1570 {
1571 // Before we delete the record (and potentially send a goodbye packet)
1572 // first see if we have a record on the duplicate list ready to take over from it.
1573 AuthRecord **d = &m->DuplicateRecords;
1574 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1575 if (*d)
1576 {
1577 AuthRecord *dup = *d;
1578 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1579 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1580 *d = dup->next; // Cut replacement record from DuplicateRecords list
1581 if (RRLocalOnly(rr))
1582 {
1583 dup->next = mDNSNULL;
1584 if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1585 }
1586 else
1587 {
1588 dup->next = rr->next; // And then...
1589 rr->next = dup; // ... splice it in right after the record we're about to delete
1590 }
1591 dup->resrec.RecordType = rr->resrec.RecordType;
1592 dup->ProbeCount = rr->ProbeCount;
1593 dup->ProbeRestartCount = rr->ProbeRestartCount;
1594 dup->AnnounceCount = rr->AnnounceCount;
1595 dup->RequireGoodbye = rr->RequireGoodbye;
1596 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
1597 dup->ImmedAnswer = rr->ImmedAnswer;
1598 dup->ImmedUnicast = rr->ImmedUnicast;
1599 dup->ImmedAdditional = rr->ImmedAdditional;
1600 dup->v4Requester = rr->v4Requester;
1601 dup->v6Requester = rr->v6Requester;
1602 dup->ThisAPInterval = rr->ThisAPInterval;
1603 dup->LastAPTime = rr->LastAPTime;
1604 dup->LastMCTime = rr->LastMCTime;
1605 dup->LastMCInterface = rr->LastMCInterface;
1606 dup->Private = rr->Private;
1607 dup->state = rr->state;
1608 rr->RequireGoodbye = mDNSfalse;
1609 rr->AnsweredLocalQ = mDNSfalse;
1610 }
1611 }
1612 }
1613 else
1614 {
1615 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1616 p = &m->DuplicateRecords;
1617 while (*p && *p != rr) p=&(*p)->next;
1618 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1619 if (*p)
1620 {
1621 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1622 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1623 // also that have been marked above in this function. In that case, we come here and if we don't
1624 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1625 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1626 // details.
1627 rr->WakeUp.HMAC = zeroEthAddr;
1628 rr->RequireGoodbye = mDNSfalse;
1629 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1630 dupList = mDNStrue;
1631 }
1632 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1633 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1634 }
1635
1636 if (!*p)
1637 {
1638 // No need to log an error message if we already know this is a potentially repeated deregistration
1639 if (drt != mDNS_Dereg_repeat)
1640 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1641 return(mStatus_BadReferenceErr);
1642 }
1643
1644 // If this is a shared record and we've announced it at least once,
1645 // we need to retract that announcement before we delete the record
1646
1647 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1648 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1649 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1650 // mechanism to cope with the client callback modifying the question list while that's happening.
1651 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1652 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1653 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1654 // records, thereby invoking yet more callbacks, without limit.
1655 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1656 // actual goodbye packets.
1657
1658 #ifndef UNICAST_DISABLED
1659 if (AuthRecord_uDNS(rr))
1660 {
1661 if (rr->RequireGoodbye)
1662 {
1663 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1664 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1665 m->LocalRemoveEvents = mDNStrue;
1666 uDNS_DeregisterRecord(m, rr);
1667 // At this point unconditionally we bail out
1668 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1669 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1670 // process and will complete asynchronously. Either way we don't need to do anything more here.
1671 return(mStatus_NoError);
1672 }
1673 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1674 // from the server. In that case, if the records have been part of a group update, clear the
1675 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1676 rr->updateid = zeroID;
1677
1678 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1679 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1680 // This happens today when we turn on/off interface where we get multiple network transitions
1681 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1682 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1683 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1684 // NAT state here takes care of the case where we did not send goodbyes at all.
1685 if (rr->NATinfo.clientContext)
1686 {
1687 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1688 rr->NATinfo.clientContext = mDNSNULL;
1689 }
1690 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1691 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1692 }
1693 #endif // UNICAST_DISABLED
1694
1695 if (RecordType == kDNSRecordTypeUnregistered)
1696 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1697 else if (RecordType == kDNSRecordTypeDeregistering)
1698 {
1699 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1700 return(mStatus_BadReferenceErr);
1701 }
1702
1703 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1704 // We may want to consider changing this code so that we generate local-only question "rmv"
1705 // events (and maybe goodbye packets too) for unique records as well as for shared records
1706 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1707 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1708 // clause will execute here and the record will be cut from the list.
1709 if (rr->WakeUp.HMAC.l[0] ||
1710 (RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1711 {
1712 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1713 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1714 rr->resrec.rroriginalttl = 0;
1715 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1716 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
1717 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1718 m->LocalRemoveEvents = mDNStrue;
1719 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1720 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1721 }
1722 else
1723 {
1724 if (!dupList && RRLocalOnly(rr))
1725 {
1726 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1727 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1728 }
1729 else
1730 {
1731 *p = rr->next; // Cut this record from the list
1732 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1733 DecrementAutoTargetServices(m, rr);
1734 }
1735 // If someone is about to look at this, bump the pointer forward
1736 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
1737 rr->next = mDNSNULL;
1738
1739 // Should we generate local remove events here?
1740 // i.e. something like:
1741 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1742
1743 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1744 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1745
1746 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1747 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1748 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1749
1750 // If we have an update queued up which never executed, give the client a chance to free that memory
1751 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
1752
1753
1754 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1755 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1756 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1757 // so any attempt to touch rr after this is likely to lead to a crash.
1758 if (drt != mDNS_Dereg_conflict)
1759 {
1760 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1761 LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m, rr));
1762 if (rr->RecordCallback)
1763 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
1764 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1765 }
1766 else
1767 {
1768 RecordProbeFailure(m, rr);
1769 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1770 if (rr->RecordCallback)
1771 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
1772 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1773 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1774 // Note that with all the client callbacks going on, by the time we get here all the
1775 // records we marked may have been explicitly deregistered by the client anyway.
1776 r2 = m->DuplicateRecords;
1777 while (r2)
1778 {
1779 if (r2->ProbeCount != 0xFF)
1780 {
1781 r2 = r2->next;
1782 }
1783 else
1784 {
1785 mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
1786 // As this is a duplicate record, it will be unlinked from the list
1787 // immediately
1788 r2 = m->DuplicateRecords;
1789 }
1790 }
1791 }
1792 }
1793 mDNS_UpdateAllowSleep(m);
1794 return(mStatus_NoError);
1795 }
1796
1797 // ***************************************************************************
1798 #if COMPILER_LIKES_PRAGMA_MARK
1799 #pragma mark -
1800 #pragma mark - Packet Sending Functions
1801 #endif
1802
1803 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1804 {
1805 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1806 {
1807 **nrpp = rr;
1808 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1809 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1810 // The referenced record will definitely be acceptable (by recursive application of this rule)
1811 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1812 rr->NR_AdditionalTo = add;
1813 *nrpp = &rr->NextResponse;
1814 }
1815 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1816 }
1817
1818 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1819 {
1820 AuthRecord *rr, *rr2;
1821 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
1822 {
1823 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1824 // later in the "for" loop, and we will follow further "additional" links then.)
1825 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1826 AddRecordToResponseList(nrpp, rr->Additional1, rr);
1827
1828 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
1829 AddRecordToResponseList(nrpp, rr->Additional2, rr);
1830
1831 // For SRV records, automatically add the Address record(s) for the target host
1832 if (rr->resrec.rrtype == kDNSType_SRV)
1833 {
1834 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1835 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1836 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1837 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
1838 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
1839 AddRecordToResponseList(nrpp, rr2, rr);
1840 }
1841 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
1842 {
1843 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1844 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1845 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1846 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
1847 SameDomainName(rr->resrec.name, rr2->resrec.name))
1848 AddRecordToResponseList(nrpp, rr2, rr);
1849 }
1850 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
1851 {
1852 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
1853 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1854 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
1855 }
1856 }
1857 }
1858
1859 mDNSlocal int AnonInfoSpace(AnonymousInfo *info)
1860 {
1861 ResourceRecord *rr = info->nsec3RR;
1862
1863 // 2 bytes for compressed name + type (2) class (2) TTL (4) rdlength (2) rdata (n)
1864 return (2 + 10 + rr->rdlength);
1865 }
1866
1867 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
1868 {
1869 AuthRecord *rr;
1870 AuthRecord *ResponseRecords = mDNSNULL;
1871 AuthRecord **nrp = &ResponseRecords;
1872 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
1873 int AnoninfoSpace = 0;
1874
1875 // Make a list of all our records that need to be unicast to this destination
1876 for (rr = m->ResourceRecords; rr; rr=rr->next)
1877 {
1878 // If we find we can no longer unicast this answer, clear ImmedUnicast
1879 if (rr->ImmedAnswer == mDNSInterfaceMark ||
1880 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
1881 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
1882 rr->ImmedUnicast = mDNSfalse;
1883
1884 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
1885 {
1886 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
1887 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
1888 {
1889 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
1890 rr->ImmedUnicast = mDNSfalse;
1891 rr->v4Requester = zerov4Addr;
1892 rr->v6Requester = zerov6Addr;
1893
1894 // Only sent records registered for P2P over P2P interfaces
1895 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf))
1896 {
1897 LogInfo("SendDelayedUnicastResponse: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, InterfaceID));
1898 continue;
1899 }
1900
1901 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
1902 {
1903 rr->NR_AnswerTo = NR_AnswerMulticast;
1904 *nrp = rr;
1905 nrp = &rr->NextResponse;
1906 }
1907 }
1908 }
1909 }
1910
1911 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
1912
1913 while (ResponseRecords)
1914 {
1915 mDNSu8 *responseptr = m->omsg.data;
1916 mDNSu8 *newptr;
1917 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1918
1919 // Put answers in the packet
1920 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
1921 {
1922 rr = ResponseRecords;
1923 if (rr->resrec.AnonInfo)
1924 {
1925 AnoninfoSpace += AnonInfoSpace(rr->resrec.AnonInfo);
1926 rr->resrec.AnonInfo->SendNow = mDNSInterfaceMark;
1927 }
1928 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1929 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1930
1931 // Retract the limit by AnoninfoSpace which we need to put the AnoInfo option.
1932 newptr = PutResourceRecordTTLWithLimit(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec, rr->resrec.rroriginalttl,
1933 m->omsg.data + (AllowedRRSpace(&m->omsg) - AnoninfoSpace));
1934
1935 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1936 if (!newptr && m->omsg.h.numAnswers)
1937 {
1938 break; // If packet full, send it now
1939 }
1940 if (newptr) responseptr = newptr;
1941 ResponseRecords = rr->NextResponse;
1942 rr->NextResponse = mDNSNULL;
1943 rr->NR_AnswerTo = mDNSNULL;
1944 rr->NR_AdditionalTo = mDNSNULL;
1945 rr->RequireGoodbye = mDNStrue;
1946 }
1947
1948 // We have reserved the space for AnonInfo option. PutResourceRecord uses the
1949 // standard limit (AllowedRRSpace) and we should have space now.
1950 for (rr = m->ResourceRecords; rr; rr=rr->next)
1951 {
1952 if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == mDNSInterfaceMark)
1953 {
1954 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
1955
1956 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAuthorities, nsec3RR);
1957 if (newptr)
1958 {
1959 responseptr = newptr;
1960 debugf("SendDelayedUnicastResponse: Added NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
1961 }
1962 else
1963 {
1964 // We allocated space and we should not fail. Don't break, we need to clear the SendNow flag.
1965 LogMsg("SendDelayedUnicastResponse: ERROR!! Cannot Add NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
1966 }
1967 rr->resrec.AnonInfo->SendNow = mDNSNULL;
1968 }
1969 }
1970
1971 // Add additionals, if there's space
1972 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
1973 {
1974 rr = ResponseRecords;
1975 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1976 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1977 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
1978 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1979
1980 if (newptr) responseptr = newptr;
1981 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
1982 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
1983 ResponseRecords = rr->NextResponse;
1984 rr->NextResponse = mDNSNULL;
1985 rr->NR_AnswerTo = mDNSNULL;
1986 rr->NR_AdditionalTo = mDNSNULL;
1987 }
1988
1989 if (m->omsg.h.numAnswers)
1990 mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
1991 }
1992 }
1993
1994 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1995 // and the client's mStatus_MemFree callback will have been invoked
1996 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
1997 {
1998 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
1999 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2000 // it should go ahead and immediately dispose of this registration
2001 rr->resrec.RecordType = kDNSRecordTypeShared;
2002 rr->RequireGoodbye = mDNSfalse;
2003 rr->WakeUp.HMAC = zeroEthAddr;
2004 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
2005 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
2006 }
2007
2008 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2009 // any deregistering records that remain in the m->ResourceRecords list.
2010 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2011 // which may change the record list and/or question list.
2012 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2013 mDNSlocal void DiscardDeregistrations(mDNS *const m)
2014 {
2015 if (m->CurrentRecord)
2016 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2017 m->CurrentRecord = m->ResourceRecords;
2018
2019 while (m->CurrentRecord)
2020 {
2021 AuthRecord *rr = m->CurrentRecord;
2022 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2023 CompleteDeregistration(m, rr); // Don't touch rr after this
2024 else
2025 m->CurrentRecord = rr->next;
2026 }
2027 }
2028
2029 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2030 {
2031 int i, val = 0;
2032 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2033 for (i=1; i<=src[0]; i++)
2034 {
2035 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2036 val = val * 10 + src[i] - '0';
2037 }
2038 if (val > 255) return(mStatus_Invalid);
2039 *dst = (mDNSu8)val;
2040 return(mStatus_NoError);
2041 }
2042
2043 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2044 {
2045 int skip = CountLabels(name) - 6;
2046 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2047 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2048 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2049 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2050 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2051 a->type = mDNSAddrType_IPv4;
2052 return(mStatus_NoError);
2053 }
2054
2055 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2056 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2057 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2058
2059 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2060 {
2061 int i, h, l;
2062 const domainname *n;
2063
2064 int skip = CountLabels(name) - 34;
2065 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2066
2067 n = SkipLeadingLabels(name, skip);
2068 for (i=0; i<16; i++)
2069 {
2070 if (n->c[0] != 1) return mStatus_Invalid;
2071 l = HexVal(n->c[1]);
2072 n = (const domainname *)(n->c + 2);
2073
2074 if (n->c[0] != 1) return mStatus_Invalid;
2075 h = HexVal(n->c[1]);
2076 n = (const domainname *)(n->c + 2);
2077
2078 if (l<0 || h<0) return mStatus_Invalid;
2079 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2080 }
2081
2082 a->type = mDNSAddrType_IPv6;
2083 return(mStatus_NoError);
2084 }
2085
2086 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2087 {
2088 int skip = CountLabels(name) - 2;
2089 if (skip >= 0)
2090 {
2091 const domainname *suffix = SkipLeadingLabels(name, skip);
2092 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2093 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
2094 }
2095 return(mDNSAddrType_None);
2096 }
2097
2098 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2099 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2100 {
2101 int i;
2102 mDNSu8 *ptr = m->omsg.data;
2103 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2104 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2105
2106 // 0x00 Destination address
2107 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2108
2109 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2110 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2111
2112 // 0x0C ARP Ethertype (0x0806)
2113 *ptr++ = 0x08; *ptr++ = 0x06;
2114
2115 // 0x0E ARP header
2116 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
2117 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
2118 *ptr++ = 6; // Hardware address length
2119 *ptr++ = 4; // Protocol address length
2120 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
2121
2122 // 0x16 Sender hardware address (our MAC address)
2123 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2124
2125 // 0x1C Sender protocol address
2126 for (i=0; i<4; i++) *ptr++ = spa->b[i];
2127
2128 // 0x20 Target hardware address
2129 for (i=0; i<6; i++) *ptr++ = tha->b[i];
2130
2131 // 0x26 Target protocol address
2132 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2133
2134 // 0x2A Total ARP Packet length 42 bytes
2135 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2136 }
2137
2138 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2139 {
2140 const mDNSu16 *ptr = data;
2141 while (length > 0) { length -= 2; sum += *ptr++; }
2142 sum = (sum & 0xFFFF) + (sum >> 16);
2143 sum = (sum & 0xFFFF) + (sum >> 16);
2144 return(sum != 0xFFFF ? sum : 0);
2145 }
2146
2147 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2148 {
2149 IPv6PseudoHeader ph;
2150 ph.src = *src;
2151 ph.dst = *dst;
2152 ph.len.b[0] = length >> 24;
2153 ph.len.b[1] = length >> 16;
2154 ph.len.b[2] = length >> 8;
2155 ph.len.b[3] = length;
2156 ph.pro.b[0] = 0;
2157 ph.pro.b[1] = 0;
2158 ph.pro.b[2] = 0;
2159 ph.pro.b[3] = protocol;
2160 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2161 }
2162
2163 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2164 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2165 {
2166 int i;
2167 mDNSOpaque16 checksum;
2168 mDNSu8 *ptr = m->omsg.data;
2169 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2170 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2171 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2172 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] } };
2173 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2174 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2175 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2176
2177 // 0x00 Destination address
2178 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2179 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2180 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2181 // link with a pointless link-layer multicast.
2182 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2183 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2184 // *ptr++ = 0x33;
2185 // *ptr++ = 0x33;
2186 // *ptr++ = 0xFF;
2187 // *ptr++ = tpa->b[0xD];
2188 // *ptr++ = tpa->b[0xE];
2189 // *ptr++ = tpa->b[0xF];
2190
2191 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2192 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2193
2194 // 0x0C IPv6 Ethertype (0x86DD)
2195 *ptr++ = 0x86; *ptr++ = 0xDD;
2196
2197 // 0x0E IPv6 header
2198 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
2199 *ptr++ = 0x00; *ptr++ = 0x20; // Length
2200 *ptr++ = 0x3A; // Protocol == ICMPv6
2201 *ptr++ = 0xFF; // Hop Limit
2202
2203 // 0x16 Sender IPv6 address
2204 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2205
2206 // 0x26 Destination IPv6 address
2207 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2208
2209 // 0x36 NDP header
2210 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2211 *ptr++ = 0x00; // Code
2212 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
2213 *ptr++ = flags;
2214 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2215
2216 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
2217 {
2218 // 0x3E NDP target.
2219 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2220 // 0x4E Source Link-layer Address
2221 // <http://www.ietf.org/rfc/rfc2461.txt>
2222 // MUST NOT be included when the source IP address is the unspecified address.
2223 // Otherwise, on link layers that have addresses this option MUST be included
2224 // in multicast solicitations and SHOULD be included in unicast solicitations.
2225 if (!mDNSIPv6AddressIsZero(*spa))
2226 {
2227 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2228 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2229 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2230 }
2231 }
2232 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2233 {
2234 // 0x3E NDP target.
2235 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2236 // 0x4E Target Link-layer Address
2237 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2238 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2239 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2240 }
2241
2242 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2243 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
2244 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2245 m->omsg.data[0x38] = checksum.b[0];
2246 m->omsg.data[0x39] = checksum.b[1];
2247
2248 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2249 }
2250
2251 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2252 {
2253 mDNSu32 DNS_VERS = _DNS_SD_H;
2254 Trace->u.tracer.platf = m->mDNS_plat;
2255 Trace->u.tracer.mDNSv = DNS_VERS;
2256
2257 Trace->opt = kDNSOpt_Trace;
2258 Trace->optlen = DNSOpt_TraceData_Space - 4;
2259 }
2260
2261 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2262 {
2263 owner->u.owner.vers = 0;
2264 owner->u.owner.seq = m->SleepSeqNum;
2265 owner->u.owner.HMAC = m->PrimaryMAC;
2266 owner->u.owner.IMAC = intf->MAC;
2267 owner->u.owner.password = zeroEthAddr;
2268
2269 // Don't try to compute the optlen until *after* we've set up the data fields
2270 // 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
2271 owner->opt = kDNSOpt_Owner;
2272 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2273 }
2274
2275 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2276 {
2277 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2278 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2279 }
2280
2281 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2282 {
2283 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2284 // and hence there is no need to check for Transfering state. But if we have sleep
2285 // proxies and partially sending goodbyes for some records, we will be in Transfering
2286 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2287 // we are not awake handles both cases.
2288 if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2289 {
2290 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2291 return mDNStrue;
2292 }
2293
2294 if (m->SleepState != SleepState_Sleeping)
2295 return mDNSfalse;
2296
2297 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2298 // whether you can send goodbyes or not.
2299 if (!intf->SendGoodbyes)
2300 {
2301 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2302 return mDNSfalse;
2303 }
2304 else
2305 {
2306 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2307 return mDNStrue;
2308 }
2309 }
2310
2311 // Note about acceleration of announcements to facilitate automatic coalescing of
2312 // multiple independent threads of announcements into a single synchronized thread:
2313 // The announcements in the packet may be at different stages of maturity;
2314 // One-second interval, two-second interval, four-second interval, and so on.
2315 // After we've put in all the announcements that are due, we then consider
2316 // whether there are other nearly-due announcements that are worth accelerating.
2317 // To be eligible for acceleration, a record MUST NOT be older (further along
2318 // its timeline) than the most mature record we've already put in the packet.
2319 // In other words, younger records can have their timelines accelerated to catch up
2320 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2321 // Older records cannot have their timelines accelerated; this would just widen
2322 // the gap between them and their younger bretheren and get them even more out of sync.
2323
2324 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2325 // the record list and/or question list.
2326 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2327 mDNSlocal void SendResponses(mDNS *const m)
2328 {
2329 int pktcount = 0;
2330 AuthRecord *rr, *r2;
2331 mDNSs32 maxExistingAnnounceInterval = 0;
2332 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2333
2334 m->NextScheduledResponse = m->timenow + 0x78000000;
2335
2336 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2337
2338 for (rr = m->ResourceRecords; rr; rr=rr->next)
2339 if (rr->ImmedUnicast)
2340 {
2341 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2342 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2343 v4.ip.v4 = rr->v4Requester;
2344 v6.ip.v6 = rr->v6Requester;
2345 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2346 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2347 if (rr->ImmedUnicast)
2348 {
2349 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2350 rr->ImmedUnicast = mDNSfalse;
2351 }
2352 }
2353
2354 // ***
2355 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2356 // ***
2357
2358 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2359 for (rr = m->ResourceRecords; rr; rr=rr->next)
2360 {
2361 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2362 if (TimeToAnnounceThisRecord(rr, m->timenow))
2363 {
2364 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2365 {
2366 if (!rr->WakeUp.HMAC.l[0])
2367 {
2368 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
2369 }
2370 else
2371 {
2372 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2373 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
2374 for (r2 = rr; r2; r2=r2->next)
2375 if (r2->AnnounceCount && r2->resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) &&
2376 !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2377 {
2378 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2379 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2380 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2381 {
2382 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2383 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2384 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2385 }
2386 r2->LastAPTime = m->timenow;
2387 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2388 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2389 }
2390 }
2391 }
2392 else if (ResourceRecordIsValidAnswer(rr))
2393 {
2394 if (rr->AddressProxy.type)
2395 {
2396 if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2397 {
2398 rr->AnnounceCount--;
2399 rr->ThisAPInterval *= 2;
2400 rr->LastAPTime = m->timenow;
2401 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2402 {
2403 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2404 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2405 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2406 }
2407 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2408 {
2409 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2410 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2411 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2412 }
2413 }
2414 }
2415 else
2416 {
2417 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2418 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2419 maxExistingAnnounceInterval = rr->ThisAPInterval;
2420 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2421 }
2422 }
2423 }
2424 }
2425
2426 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2427 // Eligible records that are more than half-way to their announcement time are accelerated
2428 for (rr = m->ResourceRecords; rr; rr=rr->next)
2429 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2430 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2431 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2432 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
2433 ResourceRecordIsValidAnswer(rr)))
2434 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2435
2436 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2437 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2438 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2439 // then all that means is that it won't get sent -- which would not be the end of the world.
2440 for (rr = m->ResourceRecords; rr; rr=rr->next)
2441 {
2442 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2443 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
2444 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
2445 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
2446 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
2447 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
2448 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2449 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2450 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
2451 // We also make sure we send the DeviceInfo TXT record too, if necessary
2452 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2453 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2454 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2455 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2456 {
2457 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2458 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2459 }
2460 }
2461
2462 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2463 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2464 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2465 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2466 // -- 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
2467 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2468 for (rr = m->ResourceRecords; rr; rr=rr->next)
2469 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2470 {
2471 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
2472 {
2473 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2474 if (ResourceRecordIsValidAnswer(r2))
2475 if (r2->ImmedAnswer != mDNSInterfaceMark &&
2476 r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(r2, rr))
2477 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2478 }
2479 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
2480 {
2481 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2482 if (ResourceRecordIsValidAnswer(r2))
2483 if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(r2, rr))
2484 r2->ImmedAdditional = rr->ImmedAdditional;
2485 }
2486 }
2487
2488 // Now set SendRNow state appropriately
2489 for (rr = m->ResourceRecords; rr; rr=rr->next)
2490 {
2491 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
2492 {
2493 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2494 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
2495 rr->LastMCTime = m->timenow;
2496 rr->LastMCInterface = rr->ImmedAnswer;
2497 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2498 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2499 {
2500 rr->AnnounceCount--;
2501 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2502 rr->ThisAPInterval *= 2;
2503 rr->LastAPTime = m->timenow;
2504 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2505 }
2506 }
2507 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
2508 {
2509 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
2510 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
2511 rr->LastMCTime = m->timenow;
2512 rr->LastMCInterface = rr->ImmedAnswer;
2513 }
2514 SetNextAnnounceProbeTime(m, rr);
2515 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2516 }
2517
2518 // ***
2519 // *** 2. Loop through interface list, sending records as appropriate
2520 // ***
2521
2522 while (intf)
2523 {
2524 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2525 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2526 int numDereg = 0;
2527 int numAnnounce = 0;
2528 int numAnswer = 0;
2529 int AnoninfoSpace = 0;
2530 mDNSu8 *responseptr = m->omsg.data;
2531 mDNSu8 *newptr;
2532 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2533
2534 // First Pass. Look for:
2535 // 1. Deregistering records that need to send their goodbye packet
2536 // 2. Updated records that need to retract their old data
2537 // 3. Answers and announcements we need to send
2538 for (rr = m->ResourceRecords; rr; rr=rr->next)
2539 {
2540
2541 // Skip this interface if the record InterfaceID is *Any and the record is not
2542 // appropriate for the interface type.
2543 if ((rr->SendRNow == intf->InterfaceID) &&
2544 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf)))
2545 {
2546 LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
2547 rr->SendRNow = GetNextActiveInterfaceID(intf);
2548 }
2549 else if (rr->SendRNow == intf->InterfaceID)
2550 {
2551 RData *OldRData = rr->resrec.rdata;
2552 mDNSu16 oldrdlength = rr->resrec.rdlength;
2553 mDNSu8 active = (mDNSu8)
2554 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2555 newptr = mDNSNULL;
2556 if (rr->NewRData && active)
2557 {
2558 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2559 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2560 {
2561 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2562 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2563 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
2564 }
2565 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2566 }
2567
2568 if (rr->resrec.AnonInfo)
2569 {
2570 int tmp = AnonInfoSpace(rr->resrec.AnonInfo);
2571
2572 AnoninfoSpace += tmp;
2573 // Adjust OwnerRecordSpace/TraceRecordSpace which is used by PutRR_OS_TTL below so that
2574 // we have space to put in the NSEC3 record in the authority section.
2575 OwnerRecordSpace += tmp;
2576 TraceRecordSpace += tmp;
2577 }
2578
2579 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2580 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2581 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2582 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2583 if (newptr)
2584 {
2585 responseptr = newptr;
2586 rr->RequireGoodbye = active;
2587 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2588 else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2589 }
2590
2591 if (rr->NewRData && active)
2592 SetNewRData(&rr->resrec, OldRData, oldrdlength);
2593
2594 // The first time through (pktcount==0), if this record is verified unique
2595 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2596 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2597 rr->SendNSECNow = mDNSInterfaceMark;
2598
2599 if (newptr) // If succeeded in sending, advance to next interface
2600 {
2601 if (rr->resrec.AnonInfo)
2602 {
2603 debugf("SendResponses: Marking %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2604 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2605 rr->resrec.AnonInfo->SendNow = intf->InterfaceID;
2606 }
2607
2608 // If sending on all interfaces, go to next interface; else we're finished now
2609 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2610 rr->SendRNow = GetNextActiveInterfaceID(intf);
2611 else
2612 rr->SendRNow = mDNSNULL;
2613 }
2614 }
2615 }
2616
2617 // Get the reserved space back
2618 OwnerRecordSpace -= AnoninfoSpace;
2619 TraceRecordSpace -= AnoninfoSpace;
2620 newptr = responseptr;
2621 for (rr = m->ResourceRecords; rr; rr=rr->next)
2622 {
2623 if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == intf->InterfaceID)
2624 {
2625 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
2626
2627 newptr = PutRR_OS_TTL(newptr, &m->omsg.h.numAuthorities, nsec3RR, nsec3RR->rroriginalttl);
2628 if (newptr)
2629 {
2630 responseptr = newptr;
2631 debugf("SendResponses: Added NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2632 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2633 }
2634 else
2635 {
2636 LogMsg("SendResponses: Cannot add NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2637 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2638 }
2639 rr->resrec.AnonInfo->SendNow = mDNSNULL;
2640 }
2641 }
2642 // Second Pass. Add additional records, if there's space.
2643 newptr = responseptr;
2644 for (rr = m->ResourceRecords; rr; rr=rr->next)
2645 if (rr->ImmedAdditional == intf->InterfaceID)
2646 if (ResourceRecordIsValidAnswer(rr))
2647 {
2648 // If we have at least one answer already in the packet, then plan to add additionals too
2649 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2650
2651 // If we're not planning to send any additionals, but this record is a unique one, then
2652 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2653 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2654 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2655 {
2656 const AuthRecord *a;
2657 for (a = m->ResourceRecords; a; a=a->next)
2658 if (a->LastMCTime == m->timenow &&
2659 a->LastMCInterface == intf->InterfaceID &&
2660 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2661 }
2662 if (!SendAdditional) // If we don't want to send this after all,
2663 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
2664 else if (newptr) // Else, try to add it if we can
2665 {
2666 // The first time through (pktcount==0), if this record is verified unique
2667 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2668 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2669 rr->SendNSECNow = mDNSInterfaceMark;
2670
2671 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2672 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2673 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2674 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2675 if (newptr)
2676 {
2677 responseptr = newptr;
2678 rr->ImmedAdditional = mDNSNULL;
2679 rr->RequireGoodbye = mDNStrue;
2680 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2681 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2682 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2683 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2684 rr->LastMCTime = m->timenow;
2685 rr->LastMCInterface = intf->InterfaceID;
2686 }
2687 }
2688 }
2689
2690 // Third Pass. Add NSEC records, if there's space.
2691 // When we're generating an NSEC record in response to a specify query for that type
2692 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2693 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2694 for (rr = m->ResourceRecords; rr; rr=rr->next)
2695 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2696 {
2697 AuthRecord nsec;
2698 mDNSu8 *ptr;
2699 int len;
2700 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2701 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2702 AssignDomainName(&nsec.namestorage, rr->resrec.name);
2703 ptr = nsec.rdatastorage.u.data;
2704 len = DomainNameLength(rr->resrec.name);
2705 // We have a nxt name followed by window number, window length and a window bitmap
2706 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
2707 if (nsec.resrec.rdlength <= StandardAuthRDSize)
2708 {
2709 mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
2710 AssignDomainName((domainname *)ptr, rr->resrec.name);
2711 ptr += len;
2712 *ptr++ = 0; // window number
2713 *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
2714 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2715 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2716 {
2717 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2718 else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2719 }
2720 newptr = responseptr;
2721 if (!r2) // If we successfully built our NSEC record, add it to the packet now
2722 {
2723 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2724 if (newptr) responseptr = newptr;
2725 }
2726 }
2727 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength);
2728
2729 // If we successfully put the NSEC record, clear the SendNSECNow flag
2730 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2731 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2732 {
2733 rr->SendNSECNow = mDNSNULL;
2734 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2735 for (r2 = rr->next; r2; r2=r2->next)
2736 if (SameResourceRecordNameClassInterface(r2, rr))
2737 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2738 r2->SendNSECNow = mDNSNULL;
2739 }
2740 }
2741
2742 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2743 {
2744 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
2745 if (OwnerRecordSpace || TraceRecordSpace)
2746 {
2747 AuthRecord opt;
2748 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2749 opt.resrec.rrclass = NormalMaxDNSMessageData;
2750 opt.resrec.rdlength = sizeof(rdataOPT);
2751 opt.resrec.rdestimate = sizeof(rdataOPT);
2752 if (OwnerRecordSpace && TraceRecordSpace)
2753 {
2754 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
2755 opt.resrec.rdestimate += sizeof(rdataOPT);
2756 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2757 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
2758 }
2759 else if (OwnerRecordSpace)
2760 {
2761 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2762 }
2763 else if (TraceRecordSpace)
2764 {
2765 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
2766 }
2767 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2768 if (newptr)
2769 {
2770 responseptr = newptr;
2771 LogInfo("SendResponses put %s %s: %s %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", intf->ifname, ARDisplayString(m, &opt));
2772 }
2773 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2774 {
2775 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2776 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2777 }
2778 else
2779 {
2780 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2781 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2782 }
2783 }
2784
2785 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2786 numDereg, numDereg == 1 ? "" : "s",
2787 numAnnounce, numAnnounce == 1 ? "" : "s",
2788 numAnswer, numAnswer == 1 ? "" : "s",
2789 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2790
2791 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2792 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2793 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2794 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
2795 // There might be more things to send on this interface, so go around one more time and try again.
2796 }
2797 else // Nothing more to send on this interface; go to next
2798 {
2799 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
2800 #if MDNS_DEBUGMSGS && 0
2801 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2802 debugf(msg, intf, next);
2803 #endif
2804 intf = next;
2805 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2806 }
2807 }
2808
2809 // ***
2810 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2811 // ***
2812
2813 if (m->CurrentRecord)
2814 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2815 m->CurrentRecord = m->ResourceRecords;
2816 while (m->CurrentRecord)
2817 {
2818 rr = m->CurrentRecord;
2819 m->CurrentRecord = rr->next;
2820
2821 if (rr->SendRNow)
2822 {
2823 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
2824 LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr->SendRNow, rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
2825 rr->SendRNow = mDNSNULL;
2826 }
2827
2828 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2829 {
2830 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
2831
2832 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
2833 {
2834 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
2835 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
2836 }
2837 else
2838 {
2839 rr->ImmedAnswer = mDNSNULL;
2840 rr->ImmedUnicast = mDNSfalse;
2841 rr->v4Requester = zerov4Addr;
2842 rr->v6Requester = zerov6Addr;
2843 }
2844 }
2845 }
2846 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
2847 }
2848
2849 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2850 // so we want to be lazy about how frequently we do it.
2851 // 1. If a cache record is currently referenced by *no* active questions,
2852 // then we don't mind expiring it up to a minute late (who will know?)
2853 // 2. Else, if a cache record is due for some of its final expiration queries,
2854 // we'll allow them to be late by up to 2% of the TTL
2855 // 3. Else, if a cache record has completed all its final expiration queries without success,
2856 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2857 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2858 // so allow at most 1/10 second lateness
2859 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2860 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2861 #define CacheCheckGracePeriod(RR) ( \
2862 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
2863 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
2864 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
2865 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
2866
2867 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2868
2869 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
2870 {
2871 if (m->rrcache_nextcheck[slot] - event > 0)
2872 m->rrcache_nextcheck[slot] = event;
2873 if (m->NextCacheCheck - event > 0)
2874 m->NextCacheCheck = event;
2875 }
2876
2877 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2878 // rr->TimeRcvd
2879 // rr->resrec.rroriginalttl
2880 // rr->UnansweredQueries
2881 // rr->CRActiveQuestion
2882 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
2883 {
2884 rr->NextRequiredQuery = RRExpireTime(rr);
2885
2886 // If we have an active question, then see if we want to schedule a refresher query for this record.
2887 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2888 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
2889 {
2890 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
2891 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
2892 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2893 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
2894 }
2895 ScheduleNextCacheCheckTime(m, HashSlot(rr->resrec.name), NextCacheCheckEvent(rr));
2896 }
2897
2898 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
2899 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
2900 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
2901 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 5)
2902
2903 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
2904 {
2905 if (interval < kMinimumReconfirmTime)
2906 interval = kMinimumReconfirmTime;
2907 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
2908 interval = 0x10000000;
2909
2910 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2911 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
2912 {
2913 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2914 // For all the reconfirmations in a given batch, we want to use the same random value
2915 // so that the reconfirmation questions can be grouped into a single query packet
2916 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(0x3FFFFFFF);
2917 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
2918 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
2919 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
2920 SetNextCacheCheckTimeForRecord(m, rr);
2921 }
2922 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2923 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
2924 return(mStatus_NoError);
2925 }
2926
2927 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2928 // It also appends to the list of known answer records that need to be included,
2929 // and updates the forcast for the size of the known answer section.
2930 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
2931 CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
2932 {
2933 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353;
2934 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2935 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
2936 mDNSu8 anoninfo_space = q->AnonInfo ? AnonInfoSpace(q->AnonInfo) : 0;
2937 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast - anoninfo_space, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
2938 if (!newptr)
2939 {
2940 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2941 return(mDNSfalse);
2942 }
2943 else
2944 {
2945 mDNSu32 forecast = *answerforecast + anoninfo_space;
2946 const mDNSu32 slot = HashSlot(&q->qname);
2947 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2948 CacheRecord *rr;
2949 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
2950
2951 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
2952 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2953 !(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
2954 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not already in the known answer list
2955 rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
2956 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
2957 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
2958 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
2959 {
2960 // We don't want to include unique records in the Known Answer section. The Known Answer section
2961 // is intended to suppress floods of shared-record replies from many other devices on the network.
2962 // That concept really does not apply to unique records, and indeed if we do send a query for
2963 // which we have a unique record already in our cache, then including that unique record as a
2964 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2965
2966 *ka = rr; // Link this record into our known answer chain
2967 ka = &rr->NextInKAList;
2968 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2969 forecast += 12 + rr->resrec.rdestimate;
2970 // If we're trying to put more than one question in this packet, and it doesn't fit
2971 // then undo that last question and try again next time
2972 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
2973 {
2974 query->h.numQuestions--;
2975 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
2976 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
2977 ka = *kalistptrptr; // Go back to where we started and retract these answer records
2978 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
2979 return(mDNSfalse); // Return false, so we'll try again in the next packet
2980 }
2981 }
2982
2983 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2984 *queryptr = newptr; // Update the packet pointer
2985 *answerforecast = forecast; // Update the forecast
2986 *kalistptrptr = ka; // Update the known answer list pointer
2987 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
2988
2989 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // For every resource record in our cache,
2990 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2991 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not in the known answer list
2992 SameNameRecordAnswersQuestion(&rr->resrec, q)) // which answers our question
2993 {
2994 rr->UnansweredQueries++; // indicate that we're expecting a response
2995 rr->LastUnansweredTime = m->timenow;
2996 SetNextCacheCheckTimeForRecord(m, rr);
2997 }
2998
2999 return(mDNStrue);
3000 }
3001 }
3002
3003 // When we have a query looking for a specified name, but there appear to be no answers with
3004 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3005 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3006 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3007 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3008 // A typical reconfirmation scenario might go like this:
3009 // Depth 0: Name "myhost.local" has no address records
3010 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3011 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3012 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3013 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3014 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3015 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
3016 {
3017 mDNSu32 slot;
3018 CacheGroup *cg;
3019 CacheRecord *cr;
3020 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
3021 FORALL_CACHERECORDS(slot, cg, cr)
3022 {
3023 domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
3024 if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
3025 {
3026 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
3027 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3028 if (depth < 5)
3029 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
3030 }
3031 }
3032 }
3033
3034 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3035 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3036 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3037 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3038 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3039 {
3040 CacheGroup *const cg = CacheGroupForName(m, HashSlot(name), namehash, name);
3041 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3042 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3043 return(cr);
3044 }
3045
3046
3047 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3048 {
3049 #ifndef SPC_DISABLED
3050 CacheGroup *const cg = CacheGroupForName(m, HashSlot(&q->qname), q->qnamehash, &q->qname);
3051 const CacheRecord *cr, *bestcr = mDNSNULL;
3052 mDNSu32 bestmetric = 1000000;
3053 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3054 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
3055 if (cr != c0 && cr != c1) // that's not one we've seen before,
3056 if (SameNameRecordAnswersQuestion(&cr->resrec, q)) // and answers our browse query,
3057 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
3058 {
3059 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3060 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3061 }
3062 return(bestcr);
3063 #else // SPC_DISABLED
3064 (void) m;
3065 (void) q;
3066 (void) c0;
3067 (void) c1;
3068 (void) c1;
3069 return mDNSNULL;
3070 #endif // SPC_DISABLED
3071 }
3072
3073 mDNSlocal void CheckAndSwapSPS(const CacheRecord *sps1, const CacheRecord *sps2)
3074 {
3075 const CacheRecord *swap_sps;
3076 mDNSu32 metric1, metric2;
3077
3078 if (!sps1 || !sps2) return;
3079 metric1 = SPSMetric(sps1->resrec.rdata->u.name.c);
3080 metric2 = SPSMetric(sps2->resrec.rdata->u.name.c);
3081 if (!SPSFeatures(sps1->resrec.rdata->u.name.c) && SPSFeatures(sps2->resrec.rdata->u.name.c) && (metric2 >= metric1))
3082 {
3083 swap_sps = sps1;
3084 sps1 = sps2;
3085 sps2 = swap_sps;
3086 }
3087 }
3088
3089 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3090 {
3091 CheckAndSwapSPS(sps[0], sps[1]);
3092 CheckAndSwapSPS(sps[0], sps[2]);
3093 CheckAndSwapSPS(sps[1], sps[2]);
3094 }
3095
3096
3097 // Finds the three best Sleep Proxies we currently have in our cache
3098 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3099 {
3100 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3101 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
3102 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
3103
3104 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3105 // only if they have equally good metric and support features.
3106 ReorderSPSByFeature(sps);
3107 }
3108
3109 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3110 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3111 {
3112 int i;
3113 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3114 }
3115
3116 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3117 {
3118 int i;
3119 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3120 }
3121
3122 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3123 {
3124 int i;
3125 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3126 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3127 for (i=0; i<DupSuppressInfoSize; i++)
3128 if (ds[i].InterfaceID == intf->InterfaceID)
3129 {
3130 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3131 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3132 if (v4 && v6) return(mDNStrue);
3133 }
3134 return(mDNSfalse);
3135 }
3136
3137 mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3138 {
3139 int i, j;
3140
3141 // See if we have this one in our list somewhere already
3142 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3143
3144 // If not, find a slot we can re-use
3145 if (i >= DupSuppressInfoSize)
3146 {
3147 i = 0;
3148 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3149 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3150 i = j;
3151 }
3152
3153 // Record the info about this query we saw
3154 ds[i].Time = Time;
3155 ds[i].InterfaceID = InterfaceID;
3156 ds[i].Type = Type;
3157
3158 return(i);
3159 }
3160
3161 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3162 {
3163 int len, i, cnt;
3164 mDNSInterfaceID InterfaceID = q->InterfaceID;
3165 domainname *d = &q->qname;
3166
3167 // We can't send magic packets without knowing which interface to send it on.
3168 if (InterfaceID == mDNSInterface_Any || InterfaceID == mDNSInterface_LocalOnly || InterfaceID == mDNSInterface_P2P)
3169 {
3170 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3171 return;
3172 }
3173
3174 // Split MAC@IPAddress and pass them separately
3175 len = d->c[0];
3176 i = 1;
3177 cnt = 0;
3178 for (i = 1; i < len; i++)
3179 {
3180 if (d->c[i] == '@')
3181 {
3182 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3183 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3184 if (cnt != 5)
3185 {
3186 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3187 return;
3188 }
3189 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3190 {
3191 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3192 return;
3193 }
3194 if ((len - i) > (int)(sizeof(IPAddr) - 1))
3195 {
3196 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3197 return;
3198 }
3199 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3200 EthAddr[i - 1] = 0;
3201 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3202 IPAddr[len - i] = 0;
3203 m->mDNSStats.WakeOnResolves++;
3204 mDNSPlatformSendWakeupPacket(m, InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3205 return;
3206 }
3207 else if (d->c[i] == ':')
3208 cnt++;
3209 }
3210 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3211 }
3212
3213
3214 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3215 {
3216 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3217 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3218 return(mDNStrue);
3219
3220 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3221 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3222 {
3223 // We forecast: qname (n) type (2) class (2)
3224 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3225 const mDNSu32 slot = HashSlot(&q->qname);
3226 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3227 const CacheRecord *rr;
3228 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
3229 if (rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3230 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
3231 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
3232 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3233 {
3234 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3235 forecast += 12 + rr->resrec.rdestimate;
3236 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3237 }
3238 return(mDNStrue);
3239 }
3240
3241 return(mDNSfalse);
3242 }
3243
3244 // How Standard Queries are generated:
3245 // 1. The Question Section contains the question
3246 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3247
3248 // How Probe Queries are generated:
3249 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3250 // if some other host is already using *any* records with this name, we want to know about it.
3251 // 2. The Authority Section contains the proposed values we intend to use for one or more
3252 // of our records with that name (analogous to the Update section of DNS Update packets)
3253 // because if some other host is probing at the same time, we each want to know what the other is
3254 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3255
3256 mDNSlocal void SendQueries(mDNS *const m)
3257 {
3258 mDNSu32 slot;
3259 CacheGroup *cg;
3260 CacheRecord *cr;
3261 AuthRecord *ar;
3262 int pktcount = 0;
3263 DNSQuestion *q;
3264 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3265 mDNSs32 maxExistingQuestionInterval = 0;
3266 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3267 CacheRecord *KnownAnswerList = mDNSNULL;
3268
3269 // 1. If time for a query, work out what we need to do
3270
3271 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3272 // to their NextRequiredQuery to be worth batching them together with this one
3273 FORALL_CACHERECORDS(slot, cg, cr)
3274 {
3275 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3276 {
3277 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3278 {
3279 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3280 q = cr->CRActiveQuestion;
3281 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3282 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3283 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3284 if (q->Target.type)
3285 {
3286 q->SendQNow = mDNSInterfaceMark; // If targeted query, mark it
3287 }
3288 else if (!mDNSOpaque16IsZero(q->TargetQID))
3289 {
3290 q->LastQTime = m->timenow - q->ThisQInterval;
3291 cr->UnansweredQueries++;
3292 m->mDNSStats.CacheRefreshQueries++;
3293 }
3294 else if (q->SendQNow == mDNSNULL)
3295 {
3296 q->SendQNow = cr->resrec.InterfaceID;
3297 }
3298 else if (q->SendQNow != cr->resrec.InterfaceID)
3299 {
3300 q->SendQNow = mDNSInterfaceMark;
3301 }
3302
3303 // Indicate that this question was marked for sending
3304 // to update an existing cached answer record.
3305 // The browse throttling logic below uses this to determine
3306 // if the query should be sent.
3307 if (mDNSOpaque16IsZero(q->TargetQID))
3308 q->CachedAnswerNeedsUpdate = mDNStrue;
3309 }
3310 }
3311 }
3312
3313 // Scan our list of questions to see which:
3314 // *WideArea* queries need to be sent
3315 // *unicast* queries need to be sent
3316 // *multicast* queries we're definitely going to send
3317 if (m->CurrentQuestion)
3318 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3319 m->CurrentQuestion = m->Questions;
3320 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3321 {
3322 q = m->CurrentQuestion;
3323 if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
3324 {
3325 mDNSu8 *qptr = m->omsg.data;
3326 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
3327
3328 // 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
3329 if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
3330 if (q->LocalSocket)
3331 {
3332 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
3333 qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
3334 mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL, q->UseBackgroundTrafficClass);
3335 q->ThisQInterval *= QuestionIntervalStep;
3336 }
3337 if (q->ThisQInterval > MaxQuestionInterval)
3338 q->ThisQInterval = MaxQuestionInterval;
3339 q->LastQTime = m->timenow;
3340 q->LastQTxTime = m->timenow;
3341 q->RecentAnswerPkts = 0;
3342 q->SendQNow = mDNSNULL;
3343 q->ExpectUnicastResp = NonZeroTime(m->timenow);
3344 }
3345 else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
3346 {
3347 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3348 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3349 if (maxExistingQuestionInterval < q->ThisQInterval)
3350 maxExistingQuestionInterval = q->ThisQInterval;
3351 }
3352 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3353 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3354 // m->CurrentQuestion point to the right question
3355 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3356 }
3357 while (m->CurrentQuestion)
3358 {
3359 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3360 m->CurrentQuestion = m->CurrentQuestion->next;
3361 }
3362 m->CurrentQuestion = mDNSNULL;
3363
3364 // Scan our list of questions
3365 // (a) to see if there are any more that are worth accelerating, and
3366 // (b) to update the state variables for *all* the questions we're going to send
3367 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3368 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3369 // 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.
3370 m->NextScheduledQuery = m->timenow + 0x78000000;
3371 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3372 {
3373 if (mDNSOpaque16IsZero(q->TargetQID)
3374 && (q->SendQNow || (!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3375 {
3376 // If at least halfway to next query time, advance to next interval
3377 // If less than halfway to next query time, then
3378 // treat this as logically a repeat of the last transmission, without advancing the interval
3379 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3380 {
3381 // If we have reached the answer threshold for this question,
3382 // don't send it again until MaxQuestionInterval unless:
3383 // one of its cached answers needs to be refreshed,
3384 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3385 if (q->BrowseThreshold
3386 && (q->CurrentAnswers >= q->BrowseThreshold)
3387 && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3388 && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3389 {
3390 q->SendQNow = mDNSNULL;
3391 q->ThisQInterval = MaxQuestionInterval;
3392 q->LastQTime = m->timenow;
3393 q->RequestUnicast = 0;
3394 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3395 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3396 }
3397 else
3398 {
3399 // Mark this question for sending on all interfaces
3400 q->SendQNow = mDNSInterfaceMark;
3401 q->ThisQInterval *= QuestionIntervalStep;
3402 }
3403
3404 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3405 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3406
3407 if (q->ThisQInterval >= QuestionIntervalThreshold)
3408 {
3409 q->ThisQInterval = MaxQuestionInterval;
3410 }
3411 else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3412 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3413 {
3414 // Generally don't need to log this.
3415 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3416 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3417 // and when there simply happen to be no instances of the service the client is looking
3418 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3419 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3420 q->qname.c, DNSTypeName(q->qtype));
3421 // Sending third query, and no answers yet; time to begin doubting the source
3422 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3423 }
3424 }
3425
3426 // Mark for sending. (If no active interfaces, then don't even try.)
3427 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3428 if (q->SendOnAll)
3429 {
3430 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3431 q->LastQTime = m->timenow;
3432 }
3433
3434 // If we recorded a duplicate suppression for this question less than half an interval ago,
3435 // then we consider it recent enough that we don't need to do an identical query ourselves.
3436 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3437
3438 q->LastQTxTime = m->timenow;
3439 q->RecentAnswerPkts = 0;
3440 if (q->RequestUnicast) q->RequestUnicast--;
3441 }
3442 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3443 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3444 SetNextQueryTime(m,q);
3445 }
3446
3447 // 2. Scan our authoritative RR list to see what probes we might need to send
3448
3449 m->NextScheduledProbe = m->timenow + 0x78000000;
3450
3451 if (m->CurrentRecord)
3452 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3453 m->CurrentRecord = m->ResourceRecords;
3454 while (m->CurrentRecord)
3455 {
3456 ar = m->CurrentRecord;
3457 m->CurrentRecord = ar->next;
3458 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
3459 {
3460 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3461 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3462 {
3463 SetNextAnnounceProbeTime(m, ar);
3464 }
3465 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3466 else if (ar->ProbeCount)
3467 {
3468 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3469 {
3470 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3471 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3472 }
3473 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3474 {
3475 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3476 // IPv6 source = zero
3477 // No target hardware address
3478 // IPv6 target address is address we're probing
3479 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3480 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3481 }
3482 // Mark for sending. (If no active interfaces, then don't even try.)
3483 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3484 ar->LastAPTime = m->timenow;
3485 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3486 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3487 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3488 ar->ProbeCount = DefaultProbeCountForTypeUnique;
3489 ar->ProbeCount--;
3490 SetNextAnnounceProbeTime(m, ar);
3491 if (ar->ProbeCount == 0)
3492 {
3493 // If this is the last probe for this record, then see if we have any matching records
3494 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3495 AuthRecord *r2;
3496 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3497 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3498 r2->ProbeCount = 0;
3499 // ... then acknowledge this record to the client.
3500 // We do this optimistically, just as we're about to send the third probe.
3501 // This helps clients that both advertise and browse, and want to filter themselves
3502 // from the browse results list, because it helps ensure that the registration
3503 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3504 // A potential downside is that we could deliver a registration confirmation and then find out
3505 // moments later that there's a name conflict, but applications have to be prepared to handle
3506 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3507 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3508 }
3509 }
3510 // else, if it has now finished probing, move it to state Verified,
3511 // and update m->NextScheduledResponse so it will be announced
3512 else
3513 {
3514 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
3515 ar->resrec.RecordType = kDNSRecordTypeVerified;
3516 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3517 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3518 SetNextAnnounceProbeTime(m, ar);
3519 }
3520 }
3521 }
3522 m->CurrentRecord = m->DuplicateRecords;
3523 while (m->CurrentRecord)
3524 {
3525 ar = m->CurrentRecord;
3526 m->CurrentRecord = ar->next;
3527 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3528 AcknowledgeRecord(m, ar);
3529 }
3530
3531 // 3. Now we know which queries and probes we're sending,
3532 // go through our interface list sending the appropriate queries on each interface
3533 while (intf)
3534 {
3535 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3536 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3537 mDNSu8 *queryptr = m->omsg.data;
3538 mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class
3539
3540 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3541 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3542 if (!KnownAnswerList)
3543 {
3544 // Start a new known-answer list
3545 CacheRecord **kalistptr = &KnownAnswerList;
3546 mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3547
3548 // Put query questions in this packet
3549 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3550 {
3551 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3552 {
3553 mDNSBool Suppress = mDNSfalse;
3554 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3555 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
3556 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3557
3558 // If interface is P2P type, verify that query should be sent over it.
3559 if (!mDNSPlatformValidQuestionForInterface(q, intf))
3560 {
3561 LogInfo("SendQueries: Not sending (%s) %##s on %s", DNSTypeName(q->qtype), q->qname.c, InterfaceNameForID(m, intf->InterfaceID));
3562 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3563 }
3564 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3565 else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3566 BuildQuestion(m, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3567 {
3568 // We successfully added the question to the packet. Make sure that
3569 // we also send the NSEC3 record if required. BuildQuestion accounted for
3570 // the space.
3571 //
3572 // Note: We don't suppress anonymous questions and hence Suppress should always
3573 // be zero.
3574
3575 if (Suppress)
3576 m->mDNSStats.DupQuerySuppressions++;
3577
3578 if (!Suppress && q->AnonInfo)
3579 {
3580 debugf("SendQueries: marking for question %##s, Suppress %d", q->qname.c, Suppress);
3581 q->AnonInfo->SendNow = intf->InterfaceID;
3582 }
3583 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3584 if (q->WakeOnResolveCount)
3585 {
3586 mDNSSendWakeOnResolve(m, q);
3587 q->WakeOnResolveCount--;
3588 }
3589
3590 // use brackground traffic class if any included question requires it
3591 if (q->UseBackgroundTrafficClass)
3592 {
3593 useBackgroundTrafficClass = mDNStrue;
3594 }
3595 }
3596 }
3597 }
3598
3599 // Put probe questions in this packet
3600 for (ar = m->ResourceRecords; ar; ar=ar->next)
3601 if (ar->SendRNow == intf->InterfaceID)
3602 {
3603 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353;
3604 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3605 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3606 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3607 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3608 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, (mDNSu16)(ar->resrec.rrclass | ucbit));
3609 if (newptr)
3610 {
3611 queryptr = newptr;
3612 answerforecast = forecast;
3613 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3614 ar->IncludeInProbe = mDNStrue;
3615 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d",
3616 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount);
3617 }
3618 }
3619 }
3620
3621 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3622 while (KnownAnswerList)
3623 {
3624 CacheRecord *ka = KnownAnswerList;
3625 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3626 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3627 m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3628 if (newptr)
3629 {
3630 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3631 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3632 queryptr = newptr;
3633 KnownAnswerList = ka->NextInKAList;
3634 ka->NextInKAList = mDNSNULL;
3635 }
3636 else
3637 {
3638 // If we ran out of space and we have more than one question in the packet, that's an error --
3639 // we shouldn't have put more than one question if there was a risk of us running out of space.
3640 if (m->omsg.h.numQuestions > 1)
3641 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3642 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3643 break;
3644 }
3645 }
3646
3647 for (ar = m->ResourceRecords; ar; ar=ar->next)
3648 {
3649 if (ar->IncludeInProbe)
3650 {
3651 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3652 ar->IncludeInProbe = mDNSfalse;
3653 if (newptr) queryptr = newptr;
3654 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3655 }
3656 }
3657
3658 for (q = m->Questions; q; q = q->next)
3659 {
3660 if (q->AnonInfo && q->AnonInfo->SendNow == intf->InterfaceID)
3661 {
3662 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, q->AnonInfo->nsec3RR);
3663 if (newptr)
3664 {
3665 debugf("SendQueries: Added NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3666 queryptr = newptr;
3667 }
3668 else
3669 {
3670 LogMsg("SendQueries: ERROR!! Cannot add NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3671 }
3672 q->AnonInfo->SendNow = mDNSNULL;
3673 }
3674 }
3675
3676 if (queryptr > m->omsg.data)
3677 {
3678 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3679 if (OwnerRecordSpace || TraceRecordSpace)
3680 {
3681 AuthRecord opt;
3682 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3683 opt.resrec.rrclass = NormalMaxDNSMessageData;
3684 opt.resrec.rdlength = sizeof(rdataOPT);
3685 opt.resrec.rdestimate = sizeof(rdataOPT);
3686 if (OwnerRecordSpace && TraceRecordSpace)
3687 {
3688 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
3689 opt.resrec.rdestimate += sizeof(rdataOPT);
3690 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3691 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3692 }
3693 else if (OwnerRecordSpace)
3694 {
3695 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3696 }
3697 else if (TraceRecordSpace)
3698 {
3699 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3700 }
3701 LogInfo("SendQueries putting %s %s: %s %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", intf->ifname, ARDisplayString(m, &opt));
3702 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3703 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3704 if (!queryptr)
3705 {
3706 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3707 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3708 }
3709 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3710 {
3711 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3712 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
3713 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
3714 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3715 }
3716 }
3717
3718 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3719 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3720 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
3721 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
3722 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
3723 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3724 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3725 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3726 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3727 if (++pktcount >= 1000)
3728 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3729 // There might be more records left in the known answer list, or more questions to send
3730 // on this interface, so go around one more time and try again.
3731 }
3732 else // Nothing more to send on this interface; go to next
3733 {
3734 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3735 #if MDNS_DEBUGMSGS && 0
3736 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
3737 debugf(msg, intf, next);
3738 #endif
3739 intf = next;
3740 }
3741 }
3742
3743 // 4. Final housekeeping
3744
3745 // 4a. Debugging check: Make sure we announced all our records
3746 for (ar = m->ResourceRecords; ar; ar=ar->next)
3747 if (ar->SendRNow)
3748 {
3749 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
3750 LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar->SendRNow, ar->resrec.InterfaceID, ARDisplayString(m, ar));
3751 ar->SendRNow = mDNSNULL;
3752 }
3753
3754 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3755 // that their interface which went away might come back again, the logic will want to send queries
3756 // for those records, but we can't because their interface isn't here any more, so to keep the
3757 // state machine ticking over we just pretend we did so.
3758 // If the interface does not come back in time, the cache record will expire naturally
3759 FORALL_CACHERECORDS(slot, cg, cr)
3760 {
3761 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3762 {
3763 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3764 {
3765 cr->UnansweredQueries++;
3766 cr->CRActiveQuestion->SendQNow = mDNSNULL;
3767 SetNextCacheCheckTimeForRecord(m, cr);
3768 }
3769 }
3770 }
3771
3772 // 4c. Debugging check: Make sure we sent all our planned questions
3773 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3774 // we legitimately couldn't send because the interface is no longer available
3775 for (q = m->Questions; q; q=q->next)
3776 {
3777 if (q->SendQNow)
3778 {
3779 DNSQuestion *x;
3780 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
3781 LogMsg("SendQueries: No active interface %p to send %s question: %p %##s (%s)", q->SendQNow, x ? "new" : "old", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
3782 q->SendQNow = mDNSNULL;
3783 }
3784 q->CachedAnswerNeedsUpdate = mDNSfalse;
3785 }
3786 }
3787
3788 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password)
3789 {
3790 int i, j;
3791 mDNSu8 *ptr = m->omsg.data;
3792 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
3793 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
3794
3795 // 0x00 Destination address
3796 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3797
3798 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
3799 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
3800
3801 // 0x0C Ethertype (0x0842)
3802 *ptr++ = 0x08;
3803 *ptr++ = 0x42;
3804
3805 // 0x0E Wakeup sync sequence
3806 for (i=0; i<6; i++) *ptr++ = 0xFF;
3807
3808 // 0x14 Wakeup data
3809 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3810
3811 // 0x74 Password
3812 for (i=0; i<6; i++) *ptr++ = password->b[i];
3813
3814 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3815
3816 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
3817 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
3818 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
3819 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
3820 // So, we send one of each, unicast first, then broadcast second.
3821 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
3822 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3823 }
3824
3825 // ***************************************************************************
3826 #if COMPILER_LIKES_PRAGMA_MARK
3827 #pragma mark -
3828 #pragma mark - RR List Management & Task Management
3829 #endif
3830
3831 // Whenever a question is answered, reset its state so that we don't query
3832 // the network repeatedly. This happens first time when we answer the question and
3833 // and later when we refresh the cache.
3834 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
3835 {
3836 q->LastQTime = m->timenow;
3837 q->LastQTxTime = m->timenow;
3838 q->RecentAnswerPkts = 0;
3839 q->ThisQInterval = MaxQuestionInterval;
3840 q->RequestUnicast = 0;
3841 // Reset unansweredQueries so that we don't penalize this server later when we
3842 // start sending queries when the cache expires.
3843 q->unansweredQueries = 0;
3844 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3845 }
3846
3847 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
3848 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
3849 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
3850 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
3851 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
3852 {
3853 DNSQuestion *const q = m->CurrentQuestion;
3854 mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
3855
3856 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
3857 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
3858
3859 // When the response for the question was validated, the entire rrset was validated. If we deliver
3860 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
3861 // in the future, we will do the revalidation again.
3862 //
3863 // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
3864 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
3865 // negative response which can happen e.g., when disconnecting from network that leads to a negative response
3866 // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
3867 // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
3868 // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
3869 // a real negative response, we would reset the state here and validate the results at the end of this function.
3870 // or the real response again if we purge the cache.
3871 if (q->ValidationRequired && ((AddRecord == QC_rmv) ||
3872 (rr->resrec.RecordType == kDNSRecordTypePacketNegative && (AddRecord == QC_add))))
3873 {
3874 q->ValidationStatus = 0;
3875 q->ValidationState = DNSSECValRequired;
3876 }
3877
3878 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
3879 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
3880 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
3881 // we check to see if that query already has a unique local answer.
3882 if (q->LOAddressAnswers)
3883 {
3884 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
3885 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
3886 q->LOAddressAnswers);
3887 return;
3888 }
3889
3890 if (QuerySuppressed(q))
3891 {
3892 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
3893 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
3894 // that are timing out, which we know are answered with negative cache record when timing out.
3895 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
3896 return;
3897 }
3898
3899 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
3900 // may be called twice, once when the record is received, and again when it's time to notify local clients.
3901 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
3902
3903 rr->LastUsed = m->timenow;
3904 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
3905 {
3906 if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
3907 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
3908 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
3909 rr->CRActiveQuestion = q; // We know q is non-null
3910 SetNextCacheCheckTimeForRecord(m, rr);
3911 }
3912
3913 // If this is:
3914 // (a) a no-cache add, where we've already done at least one 'QM' query, or
3915 // (b) a normal add, where we have at least one unique-type answer,
3916 // then there's no need to keep polling the network.
3917 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
3918 // We do this for mDNS questions and uDNS one-shot questions, but not for
3919 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
3920 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
3921 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
3922 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
3923 {
3924 ResetQuestionState(m, q);
3925 }
3926
3927 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
3928
3929 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
3930 // for the purpose of retrying search domains/timeout OR the question is suppressed
3931 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
3932 if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
3933
3934 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
3935 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
3936 {
3937 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
3938 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
3939 {
3940 CacheRecord neg;
3941 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
3942 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
3943 }
3944 else
3945 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
3946 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3947 }
3948 // If this is an "Add" operation and this question needs validation, validate the response.
3949 // In the case of negative responses, extra care should be taken. Negative cache records are
3950 // used for many purposes. For example,
3951 //
3952 // 1) Suppressing questions (SuppressUnusable)
3953 // 2) Timeout questions
3954 // 3) The name does not exist
3955 // 4) No DNS servers are available and we need a quick response for the application
3956 //
3957 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
3958 // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
3959 // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
3960 // signature for (4) and hence the explicit check for q->qDNSServer.
3961 //
3962 if (m->CurrentQuestion == q && (AddRecord == QC_add) && !q->ValidatingResponse && q->ValidationRequired &&
3963 q->ValidationState == DNSSECValRequired && q->qDNSServer)
3964 {
3965 q->ValidationState = DNSSECValInProgress;
3966 // Treat it as callback call as that's what dnssec code expects
3967 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
3968 VerifySignature(m, mDNSNULL, q);
3969 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3970 return;
3971 }
3972
3973 // Note: Proceed with caution here because client callback function is allowed to do anything,
3974 // including starting/stopping queries, registering/deregistering records, etc.
3975 //
3976 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
3977 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
3978 // first before following it
3979 if (!ValidatingQuestion(q) && followcname && m->CurrentQuestion == q)
3980 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
3981 }
3982
3983 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
3984 {
3985 rr->DelayDelivery = 0;
3986 if (m->CurrentQuestion)
3987 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
3988 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3989 m->CurrentQuestion = m->Questions;
3990 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3991 {
3992 DNSQuestion *q = m->CurrentQuestion;
3993 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3994 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3995 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3996 m->CurrentQuestion = q->next;
3997 }
3998 m->CurrentQuestion = mDNSNULL;
3999 }
4000
4001 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSu32 slot, mDNSBool *purge)
4002 {
4003 const mDNSs32 threshhold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
4004 const mDNSs32 start = m->timenow - 0x10000000;
4005 mDNSs32 delay = start;
4006 CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
4007 const CacheRecord *rr;
4008
4009 if (purge)
4010 *purge = mDNSfalse;
4011 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4012 {
4013 // If there are records that will expire soon, there are cases that need delayed
4014 // delivery of events:
4015 //
4016 // 1) A new cache entry is about to be added as a replacement. The caller needs to
4017 // deliver a RMV (for the current old entry) followed by ADD (for the new entry).
4018 // It needs to schedule the timer for the next cache expiry (ScheduleNextCacheCheckTime),
4019 // so that the cache entry can be purged (purging causes the RMV followed by ADD)
4020 //
4021 // 2) A new question is about to be answered and the caller needs to know whether it's
4022 // scheduling should be delayed so that the question is not answered with this record.
4023 // Instead of delivering an ADD (old entry) followed by RMV (old entry) and another ADD
4024 // (new entry), a single ADD can be delivered by delaying the scheduling of the question
4025 // immediately.
4026 //
4027 // When the unicast cache record is created, it's TTL has been extended beyond its value
4028 // given in the resource record (See RRAdjustTTL). If it is in the "extended" time, the
4029 // cache is already expired and we set "purge" to indicate that. When "purge" is set, the
4030 // return value of the function should be ignored by the callers.
4031 //
4032 // Note: For case (1), "purge" argument is NULL and hence the following checks are skipped.
4033 // It is okay to skip in that case because the cache records have been set to expire almost
4034 // immediately and the extended time does not apply.
4035 //
4036 // Also, if there is already an active question we don't try to optimize as purging the cache
4037 // would end up delivering RMV for the active question and hence we avoid that.
4038
4039 if (purge && !rr->resrec.InterfaceID && !rr->CRActiveQuestion && rr->resrec.rroriginalttl)
4040 {
4041 mDNSu32 uTTL = RRUnadjustedTTL(rr->resrec.rroriginalttl);
4042 if (m->timenow - (rr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
4043 {
4044 LogInfo("CheckForSoonToExpireRecords: %s: rroriginalttl %u, unadjustedTTL %u, currentTTL %u",
4045 CRDisplayString(m, rr), rr->resrec.rroriginalttl, uTTL, (m->timenow - rr->TimeRcvd)/mDNSPlatformOneSecond);
4046 *purge = mDNStrue;
4047 continue;
4048 }
4049 }
4050 if (threshhold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
4051 {
4052 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
4053 delay = RRExpireTime(rr);
4054 }
4055 }
4056 if (delay - start > 0)
4057 return(NonZeroTime(delay));
4058 else
4059 return(0);
4060 }
4061
4062 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4063 // If new questions are created as a result of invoking client callbacks, they will be added to
4064 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4065 // rr is a new CacheRecord just received into our cache
4066 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4067 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4068 // which may change the record list and/or question list.
4069 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4070 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
4071 {
4072 DNSQuestion *q;
4073
4074 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4075 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4076 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4077 {
4078 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4079 {
4080 // If this question is one that's actively sending queries, and it's received ten answers within one
4081 // second of sending the last query packet, then that indicates some radical network topology change,
4082 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4083 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4084 // because we will anyway send another query within a few seconds. The first reset query is sent out
4085 // randomized over the next four seconds to reduce possible synchronization between machines.
4086 if (q->LastAnswerPktNum != m->PktNum)
4087 {
4088 q->LastAnswerPktNum = m->PktNum;
4089 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4090 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4091 {
4092 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4093 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4094 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4095 q->ThisQInterval = InitialQuestionInterval;
4096 SetNextQueryTime(m,q);
4097 }
4098 }
4099 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
4100 DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
4101 &rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
4102 rr->resrec.rDNSServer->port : zeroIPPort), q);
4103 q->CurrentAnswers++;
4104
4105 q->unansweredQueries = 0;
4106 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4107 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4108 if (q->CurrentAnswers > 4000)
4109 {
4110 static int msgcount = 0;
4111 if (msgcount++ < 10)
4112 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4113 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4114 rr->resrec.rroriginalttl = 0;
4115 rr->UnansweredQueries = MaxUnansweredQueries;
4116 }
4117 }
4118 }
4119
4120 if (!rr->DelayDelivery)
4121 {
4122 if (m->CurrentQuestion)
4123 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4124 m->CurrentQuestion = m->Questions;
4125 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4126 {
4127 q = m->CurrentQuestion;
4128 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4129 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4130 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4131 m->CurrentQuestion = q->next;
4132 }
4133 m->CurrentQuestion = mDNSNULL;
4134 }
4135
4136 SetNextCacheCheckTimeForRecord(m, rr);
4137 }
4138
4139 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4140 // If new questions are created as a result of invoking client callbacks, they will be added to
4141 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4142 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4143 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4144 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4145 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4146 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4147 // which may change the record list and/or question list.
4148 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4149 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
4150 {
4151 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4152 if (m->CurrentQuestion)
4153 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4154 m->CurrentQuestion = m->Questions;
4155 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4156 // since we're not caching the record and we'll get no opportunity to do this later
4157 while (m->CurrentQuestion)
4158 {
4159 DNSQuestion *q = m->CurrentQuestion;
4160 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4161 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
4162 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4163 m->CurrentQuestion = q->next;
4164 }
4165 m->CurrentQuestion = mDNSNULL;
4166 }
4167
4168 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4169 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4170 // If new questions are created as a result of invoking client callbacks, they will be added to
4171 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4172 // rr is an existing cache CacheRecord that just expired and is being deleted
4173 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4174 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4175 // which may change the record list and/or question list.
4176 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4177 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
4178 {
4179 if (m->CurrentQuestion)
4180 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4181 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4182 m->CurrentQuestion = m->Questions;
4183
4184 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4185 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4186 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4187 {
4188 DNSQuestion *q = m->CurrentQuestion;
4189 // When a question enters suppressed state, we generate RMV events and generate a negative
4190 // response. A cache may be present that answers this question e.g., cache entry generated
4191 // before the question became suppressed. We need to skip the suppressed questions here as
4192 // the RMV event has already been generated.
4193 if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
4194 {
4195 verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
4196 q->FlappingInterface1 = mDNSNULL;
4197 q->FlappingInterface2 = mDNSNULL;
4198
4199 if (q->CurrentAnswers == 0)
4200 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4201 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4202 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
4203 else
4204 {
4205 q->CurrentAnswers--;
4206 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4207 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4208 }
4209
4210 // If we have dropped below the answer threshold for this mDNS question,
4211 // restart the queries at InitialQuestionInterval.
4212 if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4213 {
4214 q->ThisQInterval = InitialQuestionInterval;
4215 q->LastQTime = m->timenow - q->ThisQInterval;
4216 SetNextQueryTime(m,q);
4217 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4218 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4219 }
4220 if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4221 {
4222 if (q->CurrentAnswers == 0)
4223 {
4224 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4225 q->qname.c, DNSTypeName(q->qtype));
4226 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
4227 }
4228 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
4229 }
4230 }
4231 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4232 m->CurrentQuestion = q->next;
4233 }
4234 m->CurrentQuestion = mDNSNULL;
4235 }
4236
4237 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4238 {
4239 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
4240 unsigned int i;
4241 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4242 #endif
4243 e->next = m->rrcache_free;
4244 m->rrcache_free = e;
4245 m->rrcache_totalused--;
4246 }
4247
4248 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4249 {
4250 CacheEntity *e = (CacheEntity *)(*cp);
4251 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4252 if ((*cp)->rrcache_tail != &(*cp)->members)
4253 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4254 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4255 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4256 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4257 (*cp)->name = mDNSNULL;
4258 *cp = (*cp)->next; // Cut record from list
4259 ReleaseCacheEntity(m, e);
4260 }
4261
4262 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4263 {
4264 while (*rp)
4265 {
4266 CacheRecord *rr = *rp;
4267 *rp = (*rp)->next; // Cut record from list
4268 if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4269 {
4270 mDNSPlatformMemFree(rr->resrec.rdata);
4271 rr->resrec.rdata = mDNSNULL;
4272 }
4273 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4274 // of the CacheGroup.
4275 if (rr->resrec.name)
4276 {
4277 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4278 mDNSPlatformMemFree((void *)rr->resrec.name);
4279 rr->resrec.name = mDNSNULL;
4280 }
4281 // Don't count the NSEC3 records used by anonymous browse/reg
4282 if (!rr->resrec.InterfaceID)
4283 {
4284 m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4285 if (DNSSECRecordType(rr->resrec.rrtype))
4286 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
4287 }
4288 ReleaseCacheEntity(m, (CacheEntity *)rr);
4289 }
4290 }
4291
4292 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4293 {
4294 CacheGroup *cg;
4295 const mDNSu32 slot = HashSlot(r->resrec.name);
4296
4297 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4298 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4299 r->resrec.rdata = mDNSNULL;
4300
4301 cg = CacheGroupForRecord(m, slot, &r->resrec);
4302
4303 if (!cg)
4304 {
4305 // It is okay to have this printed for NSEC/NSEC3s
4306 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4307 }
4308 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4309 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4310 // (which is handled below) and in that case it should be freed here.
4311 if (r->resrec.name && cg && r->resrec.name != cg->name)
4312 {
4313 debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4314 mDNSPlatformMemFree((void *)r->resrec.name);
4315 }
4316 r->resrec.name = mDNSNULL;
4317
4318 if (r->resrec.AnonInfo)
4319 {
4320 debugf("ReleaseCacheRecord: freeing AnonInfo for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4321 FreeAnonInfo((void *)r->resrec.AnonInfo);
4322 }
4323 r->resrec.AnonInfo = mDNSNULL;
4324
4325 if (!r->resrec.InterfaceID)
4326 {
4327 m->rrcache_totalused_unicast -= r->resrec.rdlength;
4328 if (DNSSECRecordType(r->resrec.rrtype))
4329 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, r->resrec.rdlength);
4330 }
4331
4332 ReleaseAdditionalCacheRecords(m, &r->nsec);
4333 ReleaseAdditionalCacheRecords(m, &r->soa);
4334
4335 ReleaseCacheEntity(m, (CacheEntity *)r);
4336 }
4337
4338 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4339 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4340 // callbacks for old records are delivered before callbacks for newer records.
4341 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4342 {
4343 CacheRecord **rp = &cg->members;
4344
4345 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4346 m->lock_rrcache = 1;
4347
4348 while (*rp)
4349 {
4350 CacheRecord *const rr = *rp;
4351 mDNSs32 event = RRExpireTime(rr);
4352 if (m->timenow - event >= 0) // If expired, delete it
4353 {
4354 *rp = rr->next; // Cut it from the list
4355
4356 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
4357 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4358 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
4359 {
4360 DNSQuestion *q = rr->CRActiveQuestion;
4361 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4362 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4363 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4364 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4365 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4366 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4367 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4368 if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
4369 {
4370 q->ThisQInterval = InitialQuestionInterval;
4371 q->LastQTime = m->timenow - q->ThisQInterval;
4372 SetNextQueryTime(m, q);
4373 }
4374 CacheRecordRmv(m, rr);
4375 m->rrcache_active--;
4376 }
4377 ReleaseCacheRecord(m, rr);
4378 }
4379 else // else, not expired; see if we need to query
4380 {
4381 // If waiting to delay delivery, do nothing until then
4382 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4383 event = rr->DelayDelivery;
4384 else
4385 {
4386 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4387 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4388 {
4389 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
4390 event = NextCacheCheckEvent(rr); // then just record when we want the next query
4391 else // else trigger our question to go out now
4392 {
4393 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4394 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4395 m->NextScheduledQuery = m->timenow;
4396 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4397 // which will correctly update m->NextCacheCheck for us.
4398 event = m->timenow + 0x3FFFFFFF;
4399 }
4400 }
4401 }
4402 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4403 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4404 if (m->rrcache_nextcheck[slot] - event > 0)
4405 m->rrcache_nextcheck[slot] = event;
4406 rp = &rr->next;
4407 }
4408 }
4409 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4410 cg->rrcache_tail = rp;
4411 m->lock_rrcache = 0;
4412 }
4413
4414 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4415 //
4416 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4417 // returns true if there is an answer.
4418 //
4419 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4420 // returns true to indicate the same.
4421 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4422 {
4423 mDNSu32 slot;
4424 AuthRecord *lr;
4425 AuthGroup *ag;
4426
4427 if (m->CurrentRecord)
4428 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4429
4430 slot = AuthHashSlot(&q->qname);
4431 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4432 if (ag)
4433 {
4434 m->CurrentRecord = ag->members;
4435 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4436 {
4437 AuthRecord *rr = m->CurrentRecord;
4438 m->CurrentRecord = rr->next;
4439 //
4440 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4441 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4442 //
4443 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4444 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4445 // we handle both mDNSInterface_Any and scoped questions.
4446
4447 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && q->InterfaceID == mDNSInterface_Any))
4448 if (LocalOnlyRecordAnswersQuestion(rr, q))
4449 {
4450 if (checkOnly)
4451 {
4452 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4453 ARDisplayString(m, rr));
4454 m->CurrentRecord = mDNSNULL;
4455 return mDNStrue;
4456 }
4457 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4458 if (m->CurrentQuestion != q)
4459 break; // If callback deleted q, then we're finished here
4460 }
4461 }
4462 }
4463 m->CurrentRecord = mDNSNULL;
4464
4465 if (m->CurrentQuestion != q)
4466 {
4467 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4468 return mDNStrue;
4469 }
4470
4471 if (q->LOAddressAnswers)
4472 {
4473 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4474 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4475 return mDNStrue;
4476 }
4477
4478 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4479 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4480 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4481 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4482 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4483 if (ag)
4484 {
4485 lr = ag->NewLocalOnlyRecords;
4486 while (lr)
4487 {
4488 if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4489 {
4490 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4491 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4492 return mDNStrue;
4493 }
4494 lr = lr->next;
4495 }
4496 }
4497 return mDNSfalse;
4498 }
4499
4500 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4501 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4502 // DNS requests. We need to temporarily suspend the suppress status so that we can
4503 // deliver a negative response (AnswerCurrentQuestionWithResourceRecord does not answer
4504 // suppressed questions) and reset it back. In the future, if there are other
4505 // reasons for suppressing the query, this function should be updated.
4506 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4507 {
4508 mDNSBool SuppressQuery = q->SuppressQuery;
4509 mDNSBool DisallowPID = q->DisallowPID;
4510
4511 // make sure that QuerySuppressed() returns false
4512 q->SuppressQuery = mDNSfalse;
4513 q->DisallowPID = mDNSfalse;
4514
4515 GenerateNegativeResponse(m, QC_suppressed);
4516
4517 q->SuppressQuery = SuppressQuery;
4518 q->DisallowPID = DisallowPID;
4519 }
4520
4521 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4522 {
4523 mDNSBool ShouldQueryImmediately = mDNStrue;
4524 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
4525 mDNSu32 slot = HashSlot(&q->qname);
4526 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
4527 mDNSBool AnsweredFromCache = mDNSfalse;
4528
4529 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4530
4531 if (cg) CheckCacheExpiration(m, slot, cg);
4532 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4533 m->NewQuestions = q->next;
4534 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4535 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4536 //
4537 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4538 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4539 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4540 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4541 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4542 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4543 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4544 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4545 //
4546 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4547 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4548 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4549 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4550
4551 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4552 // This should be safe, because calling the client's question callback may cause the
4553 // question list to be modified, but should not ever cause the rrcache list to be modified.
4554 // If the client's question callback deletes the question, then m->CurrentQuestion will
4555 // be advanced, and we'll exit out of the loop
4556 m->lock_rrcache = 1;
4557 if (m->CurrentQuestion)
4558 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4559 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4560 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4561
4562 if (q->NoAnswer == NoAnswer_Fail)
4563 {
4564 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4565 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
4566 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
4567 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
4568 // Don't touch the question if it has been stopped already
4569 if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
4570 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
4571 }
4572
4573 if (m->CurrentQuestion != q)
4574 {
4575 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4576 goto exit;
4577 }
4578
4579 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4580 // or P2P record, then we are done.
4581 if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
4582 goto exit;
4583
4584 // If we are not supposed to answer this question, generate a negative response.
4585 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
4586 //
4587 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
4588 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
4589 // the question out.
4590 if (QuerySuppressed(q))
4591 {
4592 AnswerSuppressedQuestion(m, q);
4593 }
4594 else if (!q->ValidatingResponse)
4595 {
4596 CacheRecord *rr;
4597 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4598 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
4599 {
4600 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4601 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
4602 if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
4603 {
4604 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
4605 rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
4606 continue; // Go to next one in loop
4607 }
4608
4609 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4610 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4611 if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
4612 ShouldQueryImmediately = mDNSfalse;
4613 q->CurrentAnswers++;
4614 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4615 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4616 AnsweredFromCache = mDNStrue;
4617 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4618 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4619 }
4620 else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
4621 ShouldQueryImmediately = mDNSfalse;
4622 }
4623 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
4624 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
4625 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
4626
4627 // Neither a local record nor a cache entry could answer this question. If this question need to be retried
4628 // with search domains, generate a negative response which will now retry after appending search domains.
4629 // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
4630 // we will retry with search domains.
4631 if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
4632 {
4633 LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4634 GenerateNegativeResponse(m, QC_forceresponse);
4635 }
4636
4637 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
4638
4639 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
4640 // Hence we don't execute the following block of code for those cases.
4641 if (ShouldQueryImmediately && ActiveQuestion(q))
4642 {
4643 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4644 q->ThisQInterval = InitialQuestionInterval;
4645 q->LastQTime = m->timenow - q->ThisQInterval;
4646 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
4647 {
4648 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
4649 if (!m->RandomQueryDelay)
4650 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
4651 q->LastQTime += m->RandomQueryDelay;
4652 }
4653 }
4654
4655 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
4656 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
4657 // answers for this question until *after* its scheduled transmission time, in which case
4658 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
4659 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
4660 SetNextQueryTime(m,q);
4661
4662 exit:
4663 m->CurrentQuestion = mDNSNULL;
4664 m->lock_rrcache = 0;
4665 }
4666
4667 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
4668 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
4669 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
4670 {
4671 mDNSu32 slot;
4672 AuthGroup *ag;
4673 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
4674 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
4675
4676 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4677
4678 if (m->CurrentQuestion)
4679 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4680 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4681 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4682
4683 if (m->CurrentRecord)
4684 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4685
4686 // 1. First walk the LocalOnly records answering the LocalOnly question
4687 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
4688 // walk the ResourceRecords list delivering the answers
4689 slot = AuthHashSlot(&q->qname);
4690 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4691 if (ag)
4692 {
4693 m->CurrentRecord = ag->members;
4694 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4695 {
4696 AuthRecord *rr = m->CurrentRecord;
4697 m->CurrentRecord = rr->next;
4698 if (LocalOnlyRecordAnswersQuestion(rr, q))
4699 {
4700 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4701 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4702 }
4703 }
4704 }
4705
4706 if (m->CurrentQuestion == q)
4707 {
4708 m->CurrentRecord = m->ResourceRecords;
4709
4710 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
4711 {
4712 AuthRecord *rr = m->CurrentRecord;
4713 m->CurrentRecord = rr->next;
4714 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4715 {
4716 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4717 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4718 }
4719 }
4720 }
4721
4722 m->CurrentQuestion = mDNSNULL;
4723 m->CurrentRecord = mDNSNULL;
4724 }
4725
4726 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
4727 {
4728 CacheEntity *e = mDNSNULL;
4729
4730 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
4731 m->lock_rrcache = 1;
4732
4733 // If we have no free records, ask the client layer to give us some more memory
4734 if (!m->rrcache_free && m->MainCallback)
4735 {
4736 if (m->rrcache_totalused != m->rrcache_size)
4737 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4738 m->rrcache_totalused, m->rrcache_size);
4739
4740 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4741 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4742 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
4743 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
4744 // and recycle them, instead of allocating more memory.
4745 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
4746 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4747 m->rrcache_size, m->rrcache_active);
4748 else
4749 {
4750 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
4751 m->MainCallback(m, mStatus_GrowCache);
4752 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4753 }
4754 }
4755
4756 // If we still have no free records, recycle all the records we can.
4757 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4758 if (!m->rrcache_free)
4759 {
4760 mDNSu32 oldtotalused = m->rrcache_totalused;
4761 mDNSu32 slot;
4762 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4763 {
4764 CacheGroup **cp = &m->rrcache_hash[slot];
4765 while (*cp)
4766 {
4767 CacheRecord **rp = &(*cp)->members;
4768 while (*rp)
4769 {
4770 // Records that answer still-active questions are not candidates for recycling
4771 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
4772 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
4773 rp=&(*rp)->next;
4774 else
4775 {
4776 CacheRecord *rr = *rp;
4777 *rp = (*rp)->next; // Cut record from list
4778 ReleaseCacheRecord(m, rr);
4779 }
4780 }
4781 if ((*cp)->rrcache_tail != rp)
4782 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
4783 (*cp)->rrcache_tail = rp;
4784 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
4785 else ReleaseCacheGroup(m, cp);
4786 }
4787 }
4788 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
4789 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
4790 }
4791
4792 if (m->rrcache_free) // If there are records in the free list, take one
4793 {
4794 e = m->rrcache_free;
4795 m->rrcache_free = e->next;
4796 if (++m->rrcache_totalused >= m->rrcache_report)
4797 {
4798 LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
4799 if (m->rrcache_report < 100) m->rrcache_report += 10;
4800 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
4801 else m->rrcache_report += 1000;
4802 }
4803 mDNSPlatformMemZero(e, sizeof(*e));
4804 }
4805
4806 m->lock_rrcache = 0;
4807
4808 return(e);
4809 }
4810
4811 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
4812 {
4813 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
4814 if (r)
4815 {
4816 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
4817 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
4818 {
4819 r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
4820 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
4821 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
4822 }
4823 }
4824 return(r);
4825 }
4826
4827 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
4828 {
4829 mDNSu16 namelen = DomainNameLength(rr->name);
4830 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
4831 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
4832 cg->next = m->rrcache_hash[slot];
4833 cg->namehash = rr->namehash;
4834 cg->members = mDNSNULL;
4835 cg->rrcache_tail = &cg->members;
4836 if (namelen > sizeof(cg->namestorage))
4837 cg->name = mDNSPlatformMemAllocate(namelen);
4838 else
4839 cg->name = (domainname*)cg->namestorage;
4840 if (!cg->name)
4841 {
4842 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
4843 ReleaseCacheEntity(m, (CacheEntity*)cg);
4844 return(mDNSNULL);
4845 }
4846 AssignDomainName(cg->name, rr->name);
4847
4848 if (CacheGroupForRecord(m, slot, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
4849 m->rrcache_hash[slot] = cg;
4850 if (CacheGroupForRecord(m, slot, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
4851
4852 return(cg);
4853 }
4854
4855 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
4856 {
4857 mDNS_CheckLock(m);
4858
4859 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4860 // a positive answer using an expired record (e.g. from an interface that has gone away).
4861 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4862 // summary deletion without giving the proper callback to any questions that are monitoring it.
4863 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4864 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
4865 rr->UnansweredQueries = MaxUnansweredQueries;
4866 rr->resrec.rroriginalttl = 0;
4867 SetNextCacheCheckTimeForRecord(m, rr);
4868 }
4869
4870 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
4871 {
4872 mDNSs32 time;
4873 mDNSPlatformLock(m);
4874 if (m->mDNS_busy)
4875 {
4876 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
4877 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
4878 }
4879
4880 if (m->timenow) time = m->timenow;
4881 else time = mDNS_TimeNow_NoLock(m);
4882 mDNSPlatformUnlock(m);
4883 return(time);
4884 }
4885
4886 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
4887 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
4888 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
4889 #define SetSPSProxyListChanged(X) do { \
4890 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
4891 m->SPSProxyListChanged = (X); } while(0)
4892
4893 // Called from mDNS_Execute() to expire stale proxy records
4894 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
4895 {
4896 m->CurrentRecord = list;
4897 while (m->CurrentRecord)
4898 {
4899 AuthRecord *rr = m->CurrentRecord;
4900 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
4901 {
4902 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
4903 // so we need to cease proxying for *all* records we may have, expired or not.
4904 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
4905 {
4906 if (m->NextScheduledSPS - rr->TimeExpire > 0)
4907 m->NextScheduledSPS = rr->TimeExpire;
4908 }
4909 else // else proxy record expired, so remove it
4910 {
4911 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
4912 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
4913 SetSPSProxyListChanged(rr->resrec.InterfaceID);
4914 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4915 // Don't touch rr after this -- memory may have been free'd
4916 }
4917 }
4918 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4919 // new records could have been added to the end of the list as a result of that call.
4920 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
4921 m->CurrentRecord = rr->next;
4922 }
4923 }
4924
4925 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
4926 {
4927 while (m->CurrentRecord)
4928 {
4929 AuthRecord *rr = m->CurrentRecord;
4930 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
4931 {
4932 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
4933 rr->resrec.RecordType = kDNSRecordTypeShared;
4934 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
4935 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
4936 {
4937 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
4938 rr->AnsweredLocalQ = mDNSfalse;
4939 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
4940 // For LocalOnly records, we don't do that and hence we need to do that here.
4941 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
4942 }
4943 }
4944 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
4945 m->CurrentRecord = rr->next;
4946 }
4947 }
4948
4949 mDNSlocal void TimeoutQuestions(mDNS *const m)
4950 {
4951 m->NextScheduledStopTime = m->timenow + 0x3FFFFFFF;
4952 if (m->CurrentQuestion)
4953 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
4954 DNSTypeName(m->CurrentQuestion->qtype));
4955 m->CurrentQuestion = m->Questions;
4956 while (m->CurrentQuestion)
4957 {
4958 DNSQuestion *const q = m->CurrentQuestion;
4959 if (q->StopTime)
4960 {
4961 if (!q->TimeoutQuestion)
4962 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4963
4964 if (m->timenow - q->StopTime >= 0)
4965 {
4966 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
4967 GenerateNegativeResponse(m, QC_forceresponse);
4968 if (m->CurrentQuestion == q) q->StopTime = 0;
4969 }
4970 else
4971 {
4972 if (m->NextScheduledStopTime - q->StopTime > 0)
4973 m->NextScheduledStopTime = q->StopTime;
4974 }
4975 }
4976 // If m->CurrentQuestion wasn't modified out from under us, advance it now
4977 // We can't do this at the start of the loop because GenerateNegativeResponse
4978 // depends on having m->CurrentQuestion point to the right question
4979 if (m->CurrentQuestion == q)
4980 m->CurrentQuestion = q->next;
4981 }
4982 m->CurrentQuestion = mDNSNULL;
4983 }
4984
4985 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
4986 {
4987 AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
4988 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
4989 while (rrPtr)
4990 {
4991 rrNext = rrPtr->next;
4992 mDNSPlatformMemFree(rrPtr);
4993 rrPtr = rrNext;
4994 }
4995 m->SPSRRSet = mDNSNULL;
4996 }
4997
4998 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
4999 {
5000 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
5001
5002 #if APPLE_OSX_mDNSResponder
5003 mDNSLogStatistics(m);
5004 #endif // APPLE_OSX_mDNSResponder
5005
5006 if (m->timenow - m->NextScheduledEvent >= 0)
5007 {
5008 int i;
5009 AuthRecord *head, *tail;
5010 mDNSu32 slot;
5011 AuthGroup *ag;
5012
5013 verbosedebugf("mDNS_Execute");
5014
5015 if (m->CurrentQuestion)
5016 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5017 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5018
5019 if (m->CurrentRecord)
5020 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5021
5022 // 1. If we're past the probe suppression time, we can clear it
5023 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5024
5025 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5026 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5027
5028 // 3. Purge our cache of stale old records
5029 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5030 {
5031 mDNSu32 numchecked = 0;
5032 m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
5033 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5034 {
5035 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5036 {
5037 CacheGroup **cp = &m->rrcache_hash[slot];
5038 m->rrcache_nextcheck[slot] = m->timenow + 0x3FFFFFFF;
5039 while (*cp)
5040 {
5041 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5042 numchecked++;
5043 CheckCacheExpiration(m, slot, *cp);
5044 if ((*cp)->members) cp=&(*cp)->next;
5045 else ReleaseCacheGroup(m, cp);
5046 }
5047 }
5048 // Even if we didn't need to actually check this slot yet, still need to
5049 // factor its nextcheck time into our overall NextCacheCheck value
5050 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5051 m->NextCacheCheck = m->rrcache_nextcheck[slot];
5052 }
5053 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5054 }
5055
5056 if (m->timenow - m->NextScheduledSPS >= 0)
5057 {
5058 m->NextScheduledSPS = m->timenow + 0x3FFFFFFF;
5059 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
5060 CheckProxyRecords(m, m->ResourceRecords);
5061 }
5062
5063 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
5064
5065 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5066 // as records could have expired during that check
5067 if (m->timenow - m->NextScheduledKA >= 0)
5068 {
5069 m->NextScheduledKA = m->timenow + 0x3FFFFFFF;
5070 mDNS_SendKeepalives(m);
5071 }
5072
5073 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5074 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5075 {
5076 m->AnnounceOwner = 0;
5077 }
5078
5079 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5080 {
5081 m->DelaySleep = 0;
5082 if (m->SleepState == SleepState_Transferring)
5083 {
5084 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5085 BeginSleepProcessing(m);
5086 }
5087 }
5088
5089 // 4. See if we can answer any of our new local questions from the cache
5090 for (i=0; m->NewQuestions && i<1000; i++)
5091 {
5092 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5093 AnswerNewQuestion(m);
5094 }
5095 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5096
5097 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5098 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5099 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5100 {
5101 m->LocalRemoveEvents = mDNSfalse;
5102 m->CurrentRecord = m->ResourceRecords;
5103 CheckRmvEventsForLocalRecords(m);
5104 // Walk the LocalOnly records and deliver the RMV events
5105 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5106 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5107 {
5108 m->CurrentRecord = ag->members;
5109 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5110 }
5111 }
5112
5113 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5114
5115 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5116 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5117
5118 head = tail = mDNSNULL;
5119 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5120 {
5121 AuthRecord *rr = m->NewLocalRecords;
5122 m->NewLocalRecords = m->NewLocalRecords->next;
5123 if (LocalRecordReady(rr))
5124 {
5125 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5126 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
5127 }
5128 else if (!rr->next)
5129 {
5130 // If we have just one record that is not ready, we don't have to unlink and
5131 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5132 // terminate and set the NewLocalRecords to rr.
5133 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5134 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5135 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5136
5137 head = rr;
5138 }
5139 else
5140 {
5141 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
5142 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5143 // if this is the first record we are skipping, move to the end of the list.
5144 // if we have already skipped records before, append it at the end.
5145 while (*p && *p != rr) p=&(*p)->next;
5146 if (*p) *p = rr->next; // Cut this record from the list
5147 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5148 if (!head)
5149 {
5150 while (*p) p=&(*p)->next;
5151 *p = rr;
5152 head = tail = rr;
5153 }
5154 else
5155 {
5156 tail->next = rr;
5157 tail = rr;
5158 }
5159 rr->next = mDNSNULL;
5160 }
5161 }
5162 m->NewLocalRecords = head;
5163 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5164
5165 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5166
5167 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5168 // to our local questions
5169 if (m->NewLocalOnlyRecords)
5170 {
5171 m->NewLocalOnlyRecords = mDNSfalse;
5172 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5173 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5174 {
5175 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5176 {
5177 AuthRecord *rr = ag->NewLocalOnlyRecords;
5178 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5179 // LocalOnly records should always be ready as they never probe
5180 if (LocalRecordReady(rr))
5181 {
5182 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5183 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
5184 }
5185 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5186 }
5187 // We limit about 100 per AuthGroup that can be serviced at a time
5188 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5189 }
5190 }
5191
5192 // 5. See what packets we need to send
5193 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5194 DiscardDeregistrations(m);
5195 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5196 {
5197 // If the platform code is ready, and we're not suppressing packet generation right now
5198 // then send our responses, probes, and questions.
5199 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5200 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5201 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5202 // Finally, we send responses, including the previously mentioned records that just completed probing.
5203 m->SuppressSending = 0;
5204
5205 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5206 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5207 if (m->timenow - m->NextScheduledQuery >= 0)
5208 {
5209 DNSQuestion *q;
5210 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5211 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5212 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5213 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5214 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5215 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5216 }
5217 if (m->timenow - m->NextScheduledProbe >= 0)
5218 {
5219 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5220 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5221 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5222 }
5223
5224 // 7. Send Response packets, including probing records just advanced to announcing state
5225 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5226 if (m->timenow - m->NextScheduledResponse >= 0)
5227 {
5228 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5229 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5230 }
5231 }
5232
5233 // Clear RandomDelay values, ready to pick a new different value next time
5234 m->RandomQueryDelay = 0;
5235 m->RandomReconfirmDelay = 0;
5236
5237 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5238 #ifndef UNICAST_DISABLED
5239 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5240 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5241 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5242 #endif
5243 }
5244
5245 // Note about multi-threaded systems:
5246 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5247 // performing mDNS API operations that change our next scheduled event time.
5248 //
5249 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5250 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5251 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5252 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5253 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5254 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5255 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5256 // without blocking. This avoids the race condition between the signal from the other thread arriving
5257 // just *before* or just *after* the main thread enters the blocking primitive.
5258 //
5259 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5260 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5261 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5262 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5263 // by the time it gets to the timer callback function).
5264
5265 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5266 return(m->NextScheduledEvent);
5267 }
5268
5269 #ifndef UNICAST_DISABLED
5270 mDNSlocal void SuspendLLQs(mDNS *m)
5271 {
5272 DNSQuestion *q;
5273 for (q = m->Questions; q; q = q->next)
5274 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5275 { q->ReqLease = 0; sendLLQRefresh(m, q); }
5276 }
5277 #endif // UNICAST_DISABLED
5278
5279 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5280 {
5281 AuthRecord *rr;
5282 mDNSu32 slot;
5283 AuthGroup *ag;
5284
5285 slot = AuthHashSlot(&q->qname);
5286 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
5287 if (ag)
5288 {
5289 for (rr = ag->members; rr; rr=rr->next)
5290 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5291 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5292 {
5293 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5294 return mDNStrue;
5295 }
5296 }
5297 return mDNSfalse;
5298 }
5299
5300 // ActivateUnicastQuery() is called from three places:
5301 // 1. When a new question is created
5302 // 2. On wake from sleep
5303 // 3. When the DNS configuration changes
5304 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5305 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5306 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5307 {
5308 // For now this AutoTunnel stuff is specific to Mac OS X.
5309 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
5310 #if APPLE_OSX_mDNSResponder
5311 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
5312 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
5313 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
5314 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
5315 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
5316 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
5317
5318 if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
5319 !SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
5320 {
5321 question->NoAnswer = NoAnswer_Suspended;
5322 AddNewClientTunnel(m, question);
5323 return;
5324 }
5325 #endif // APPLE_OSX_mDNSResponder
5326
5327 if (!question->DuplicateOf)
5328 {
5329 debugf("ActivateUnicastQuery: %##s %s%s%s",
5330 question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
5331 question->CNAMEReferrals = 0;
5332 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5333 if (question->LongLived)
5334 {
5335 question->state = LLQ_InitialRequest;
5336 question->id = zeroOpaque64;
5337 question->servPort = zeroIPPort;
5338 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5339 }
5340 // If the question has local answers, then we don't want answers from outside
5341 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5342 {
5343 question->ThisQInterval = InitialQuestionInterval;
5344 question->LastQTime = m->timenow - question->ThisQInterval;
5345 SetNextQueryTime(m, question);
5346 }
5347 }
5348 }
5349
5350 // Caller should hold the lock
5351 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5352 CallbackBeforeStartQuery BeforeStartCallback, void *context)
5353 {
5354 DNSQuestion *q;
5355 DNSQuestion *restart = mDNSNULL;
5356
5357 mDNS_CheckLock(m);
5358
5359 // 1. Flush the cache records
5360 if (flushCacheRecords) flushCacheRecords(m);
5361
5362 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5363 // we are going to stop the question. Hence we need to deliver the RMV event before we
5364 // stop the question.
5365 //
5366 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5367 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5368 // *any* other question which could be the next one that we may process here. RestartQuestion
5369 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5370 // if the "next" question is stopped while the CurrentQuestion is stopped
5371
5372 if (m->RestartQuestion)
5373 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5374 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5375
5376 m->RestartQuestion = m->Questions;
5377 while (m->RestartQuestion)
5378 {
5379 q = m->RestartQuestion;
5380 m->RestartQuestion = q->next;
5381 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5382 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5383 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5384 // question followed by the original query that refers to this GetZoneData question, we will end up
5385 // freeing the GetZoneData question and then start the "freed" question at the end.
5386
5387 if (IsGetZoneDataQuestion(q))
5388 {
5389 DNSQuestion *refq = q->next;
5390 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5391 // debug stuff, we just try to find the referencing question and don't do much with it
5392 while (refq)
5393 {
5394 if (q == &refq->nta->question)
5395 {
5396 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5397 }
5398 refq = refq->next;
5399 }
5400 continue;
5401 }
5402
5403 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5404 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5405
5406 // If the search domains did not change, then we restart all the queries. Otherwise, only
5407 // for queries for which we "might" have appended search domains ("might" because we may
5408 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5409 if (!SearchDomainsChanged || q->AppendSearchDomains)
5410 {
5411 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5412 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5413 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5414 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5415 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5416 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5417 // for the original query using these cache entries as ADDs were never delivered using these cache
5418 // entries and hence this order is needed.
5419
5420 // If the query is suppressed, the RMV events won't be delivered
5421 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5422
5423 // SuppressQuery status does not affect questions that are answered using local records
5424 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5425
5426 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
5427 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
5428 mDNS_StopQuery_internal(m, q);
5429 // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
5430 // and then search domains should be appended. At the beginning, qnameOrig was NULL.
5431 if (q->qnameOrig)
5432 {
5433 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
5434 AssignDomainName(&q->qname, q->qnameOrig);
5435 mDNSPlatformMemFree(q->qnameOrig);
5436 q->qnameOrig = mDNSNULL;
5437 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
5438 }
5439 q->SearchListIndex = 0;
5440 q->next = restart;
5441 restart = q;
5442 }
5443 }
5444
5445 // 3. Callback before we start the query
5446 if (BeforeStartCallback) BeforeStartCallback(m, context);
5447
5448 // 4. Restart all the stopped queries
5449 while (restart)
5450 {
5451 q = restart;
5452 restart = restart->next;
5453 q->next = mDNSNULL;
5454 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5455 mDNS_StartQuery_internal(m, q);
5456 }
5457 }
5458
5459 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5460 {
5461 DNSQuestion *q;
5462
5463 #ifndef UNICAST_DISABLED
5464 // Retrigger all our uDNS questions
5465 if (m->CurrentQuestion)
5466 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5467 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5468 m->CurrentQuestion = m->Questions;
5469 while (m->CurrentQuestion)
5470 {
5471 q = m->CurrentQuestion;
5472 m->CurrentQuestion = m->CurrentQuestion->next;
5473 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
5474 }
5475 #endif
5476
5477 // Retrigger all our mDNS questions
5478 for (q = m->Questions; q; q=q->next) // Scan our list of questions
5479 mDNSCoreRestartQuestion(m, q);
5480 }
5481
5482 // restart question if it's multicast and currently active
5483 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5484 {
5485 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5486 {
5487 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
5488 #if mDNS_REQUEST_UNICAST_RESPONSE
5489 q->RequestUnicast = SET_QU_IN_FIRST_FOUR_QUERIES;
5490 #else // mDNS_REQUEST_UNICAST_RESPONSE
5491 q->RequestUnicast = SET_QU_IN_FIRST_QUERY;
5492 #endif // mDNS_REQUEST_UNICAST_RESPONSE
5493 q->LastQTime = m->timenow - q->ThisQInterval;
5494 q->RecentAnswerPkts = 0;
5495 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5496 m->NextScheduledQuery = m->timenow;
5497 }
5498 }
5499
5500 // restart the probe/announce cycle for multicast record
5501 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
5502 {
5503 if (!AuthRecord_uDNS(rr))
5504 {
5505 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5506 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5507
5508 // announceCount < 0 indicates default announce count should be used
5509 if (announceCount < 0)
5510 announceCount = InitialAnnounceCount;
5511 if (rr->AnnounceCount < announceCount)
5512 rr->AnnounceCount = announceCount;
5513
5514 if (mDNS_KeepaliveRecord(&rr->resrec))
5515 rr->AnnounceCount = 0; // Do not announce keepalive records
5516 else
5517 rr->AnnounceCount = InitialAnnounceCount;
5518 rr->SendNSECNow = mDNSNULL;
5519 InitializeLastAPTime(m, rr);
5520 }
5521 }
5522
5523 // ***************************************************************************
5524 #if COMPILER_LIKES_PRAGMA_MARK
5525 #pragma mark -
5526 #pragma mark - Power Management (Sleep/Wake)
5527 #endif
5528
5529 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
5530 {
5531 #ifndef IDLESLEEPCONTROL_DISABLED
5532 mDNSBool allowSleep = mDNStrue;
5533 char reason[128];
5534
5535 reason[0] = 0;
5536
5537 if (m->SystemSleepOnlyIfWakeOnLAN)
5538 {
5539 // Don't sleep if we are a proxy for any services
5540 if (m->ProxyRecords)
5541 {
5542 allowSleep = mDNSfalse;
5543 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
5544 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
5545 }
5546
5547 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
5548 {
5549 // Scan the list of active interfaces
5550 NetworkInterfaceInfo *intf;
5551 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5552 {
5553 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
5554 {
5555 // Disallow sleep if this interface doesn't support NetWake
5556 if (!intf->NetWake)
5557 {
5558 allowSleep = mDNSfalse;
5559 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
5560 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
5561 break;
5562 }
5563
5564 // Disallow sleep if there is no sleep proxy server
5565 if (FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL) == mDNSNULL)
5566 {
5567 allowSleep = mDNSfalse;
5568 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
5569 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
5570 break;
5571 }
5572 }
5573 }
5574 }
5575 }
5576
5577 // Call the platform code to enable/disable sleep
5578 mDNSPlatformSetAllowSleep(m, allowSleep, reason);
5579 #else
5580 (void) m;
5581 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
5582
5583 }
5584
5585 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
5586 {
5587 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
5588 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
5589 // to send.
5590 if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
5591 m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
5592 {
5593 return mDNSfalse;
5594 }
5595
5596 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
5597 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
5598 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
5599 // updateid and we should have returned from above.
5600 //
5601 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
5602 // platform function to extract the value from "intf" everytime.
5603
5604 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
5605 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
5606 return mDNStrue;
5607
5608 return mDNSfalse;
5609 }
5610
5611 mDNSexport void UpdateRMACCallback(mDNS *const m, void *context)
5612 {
5613 IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
5614 m->CurrentRecord = m->ResourceRecords;
5615
5616 if (!addrmap)
5617 {
5618 LogMsg("UpdateRMACCallback: Address mapping is NULL");
5619 return;
5620 }
5621
5622 while (m->CurrentRecord)
5623 {
5624 AuthRecord *rr = m->CurrentRecord;
5625 // If this is a keepalive record and the remote IP address matches, update the RData
5626 if (mDNS_KeepaliveRecord(&rr->resrec))
5627 {
5628 mDNSAddr raddr;
5629 getKeepaliveRaddr(m, rr, &raddr);
5630 if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
5631 {
5632 UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
5633 }
5634 }
5635 m->CurrentRecord = rr->next;
5636 }
5637
5638 if (addrmap)
5639 {
5640 mDNSPlatformMemFree(addrmap);
5641 }
5642 }
5643
5644 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
5645 {
5646 mDNSu16 newrdlength;
5647 mDNSAddr laddr, raddr;
5648 mDNSEthAddr eth;
5649 mDNSIPPort lport, rport;
5650 mDNSu32 timeout, seq, ack;
5651 mDNSu16 win;
5652 UTF8str255 txt;
5653 int rdsize;
5654 RData *newrd;
5655 mDNSTCPInfo mti;
5656 mStatus ret;
5657
5658 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
5659 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
5660 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
5661 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) ||
5662 mDNSIPPortIsZero(rport))
5663 {
5664 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
5665 return mStatus_UnknownErr;
5666 }
5667
5668 if (updateMac)
5669 {
5670 if (laddr.type == mDNSAddrType_IPv4)
5671 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);
5672 else
5673 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);
5674
5675 }
5676 else
5677 {
5678 // If this keepalive packet would be sent on a different interface than the current one that we are processing
5679 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
5680 // this DNS NULL record, it does not send any keepalives as it does not have all the information
5681 mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
5682 ret = mDNSPlatformRetrieveTCPInfo(m, &laddr, &lport, &raddr, &rport, &mti);
5683 if (ret != mStatus_NoError)
5684 {
5685 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
5686 return ret;
5687 }
5688 if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
5689 {
5690 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti.IntfId, intf->InterfaceID);
5691 return mStatus_BadParamErr;
5692 }
5693
5694 if (laddr.type == mDNSAddrType_IPv4)
5695 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);
5696 else
5697 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);
5698 }
5699
5700 // Did we insert a null byte at the end ?
5701 if (newrdlength == (sizeof(txt.c) - 1))
5702 {
5703 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
5704 return mStatus_NoMemoryErr;
5705 }
5706
5707 // Include the length for the null byte at the end
5708 txt.c[0] = newrdlength + 1;
5709 // Account for the first length byte and the null byte at the end
5710 newrdlength += 2;
5711
5712 rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
5713 newrd = mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
5714 if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
5715
5716 newrd->MaxRDLength = (mDNSu16) rdsize;
5717 mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
5718
5719 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
5720 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
5721 // If the resource record has data that we allocated in a previous pass (to update MAC address),
5722 // free that memory here before copying in the new data.
5723 if ( rr->resrec.rdata != &rr->rdatastorage)
5724 {
5725 mDNSPlatformMemFree(rr->resrec.rdata);
5726 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
5727 }
5728 SetNewRData(&rr->resrec, newrd, newrdlength); // Update our rdata
5729
5730 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
5731 return mStatus_NoError;
5732 }
5733
5734 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
5735 {
5736 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
5737 const int sps = intf->NextSPSAttempt / 3;
5738 AuthRecord *rr;
5739 mDNSOpaque16 msgid;
5740 mDNSu32 scopeid;
5741
5742 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
5743 if (!intf->SPSAddr[sps].type)
5744 {
5745 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
5746 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
5747 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
5748 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
5749 goto exit;
5750 }
5751
5752 // Mark our mDNS records (not unicast records) for transfer to SPS
5753 if (mDNSOpaque16IsZero(id))
5754 {
5755 // We may have to register this record over multiple interfaces and we don't want to
5756 // overwrite the id. We send the registration over interface X with id "IDX" and before
5757 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
5758 // for "IDX". Hence, we want to use the same ID across all interfaces.
5759 //
5760 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
5761 // option check below will set the same ID across the records from the same owner. Records
5762 // with different owner option gets different ID.
5763 msgid = mDNS_NewMessageID(m);
5764 for (rr = m->ResourceRecords; rr; rr=rr->next)
5765 {
5766 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
5767 {
5768 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
5769 {
5770 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
5771 {
5772 rr->SendRNow = mDNSInterfaceMark; // mark it now
5773 // When we are registering on the first interface, rr->updateid is zero in which case
5774 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
5775 // At the end, all the updates sent across all the interfaces with the same ID.
5776 if (mDNSOpaque16IsZero(rr->updateid))
5777 rr->updateid = msgid;
5778 else
5779 msgid = rr->updateid;
5780 }
5781 }
5782 }
5783 }
5784 }
5785 else
5786 msgid = id;
5787
5788 while (1)
5789 {
5790 mDNSu8 *p = m->omsg.data;
5791 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
5792 // For now we follow that same logic for SPS registrations too.
5793 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
5794 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
5795 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
5796
5797 for (rr = m->ResourceRecords; rr; rr=rr->next)
5798 if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
5799 {
5800 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
5801 {
5802 mDNSu8 *newptr;
5803 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
5804
5805 // If we can't update the keepalive record, don't send it
5806 if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
5807 {
5808 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
5809 {
5810 bit_clr_opaque64(rr->updateIntID, scopeid);
5811 }
5812 rr->SendRNow = mDNSNULL;
5813 continue;
5814 }
5815
5816 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
5817 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
5818 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
5819 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
5820 if (!newptr)
5821 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
5822 else
5823 {
5824 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));
5825 rr->SendRNow = mDNSNULL;
5826 rr->ThisAPInterval = mDNSPlatformOneSecond;
5827 rr->LastAPTime = m->timenow;
5828 // should be initialized above
5829 if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
5830 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
5831 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
5832 p = newptr;
5833 }
5834 }
5835 }
5836
5837 if (!m->omsg.h.mDNS_numUpdates) break;
5838 else
5839 {
5840 AuthRecord opt;
5841 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
5842 opt.resrec.rrclass = NormalMaxDNSMessageData;
5843 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
5844 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
5845 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
5846 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
5847 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
5848 if (!owner->HMAC.l[0]) // If no owner data,
5849 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information
5850 else // otherwise, use the owner data we were given
5851 {
5852 opt.resrec.rdata->u.opt[1].u.owner = *owner;
5853 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner;
5854 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
5855 }
5856 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
5857 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
5858 if (!p)
5859 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
5860 else
5861 {
5862 mStatus err;
5863
5864 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
5865 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
5866 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
5867 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL, mDNSfalse);
5868 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
5869 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
5870 {
5871 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
5872 intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
5873 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
5874 return;
5875 }
5876 }
5877 }
5878 }
5879
5880 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
5881
5882 exit:
5883 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
5884 }
5885
5886 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
5887 {
5888 AuthRecord *ar;
5889 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
5890 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
5891 return mDNStrue;
5892 }
5893
5894 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
5895 {
5896 AuthRecord *newRR = mDNSPlatformMemAllocate(sizeof(AuthRecord));
5897
5898 if (newRR == mDNSNULL)
5899 {
5900 LogSPS("%s : could not allocate memory for new resource record", __func__);
5901 return;
5902 }
5903
5904 mDNSPlatformMemZero(newRR, sizeof(AuthRecord));
5905 mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
5906 rr->resrec.rroriginalttl, rr->resrec.RecordType,
5907 rr->ARType, mDNSNULL, mDNSNULL);
5908
5909 AssignDomainName(&newRR->namestorage, &rr->namestorage);
5910 newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
5911 newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
5912 newRR->resrec.rrclass = rr->resrec.rrclass;
5913
5914 if (rr->resrec.rrtype == kDNSType_A)
5915 {
5916 newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4;
5917 }
5918 else if (rr->resrec.rrtype == kDNSType_AAAA)
5919 {
5920 newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
5921 }
5922 SetNewRData(&newRR->resrec, mDNSNULL, 0);
5923
5924 // Insert the new node at the head of the list.
5925 newRR->next = m->SPSRRSet;
5926 m->SPSRRSet = newRR;
5927 LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
5928 }
5929
5930 // Some records are interface specific and some are not. The ones that are supposed to be registered
5931 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
5932 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
5933 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
5934 // registration on all the interfaces
5935 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
5936 {
5937 AuthRecord *ar;
5938 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
5939
5940 *WakeOnlyService = mDNSfalse;
5941
5942 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
5943 // make sure that the old sleep proxy records are removed.
5944 mDNSCoreFreeProxyRR(m);
5945
5946 // For records that are registered only on a specific interface, mark only that bit as it will
5947 // never be registered on any other interface. For others, it should be sent on all interfaces.
5948 for (ar = m->ResourceRecords; ar; ar=ar->next)
5949 {
5950 ar->updateIntID = zeroOpaque64;
5951 ar->updateid = zeroID;
5952 if (AuthRecord_uDNS(ar))
5953 {
5954 continue;
5955 }
5956 if (ar->AuthFlags & AuthFlagsWakeOnly)
5957 {
5958 if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
5959 {
5960 ar->ImmedAnswer = mDNSInterfaceMark;
5961 *WakeOnlyService = mDNStrue;
5962 continue;
5963 }
5964 }
5965 if (!ar->resrec.InterfaceID)
5966 {
5967 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
5968 ar->updateIntID = updateIntID;
5969 }
5970 else
5971 {
5972 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
5973 // exactly this.
5974 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
5975 if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
5976 {
5977 bit_set_opaque64(ar->updateIntID, scopeid);
5978 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
5979 ar->updateIntID.l[0], ARDisplayString(m, ar));
5980 }
5981 else
5982 {
5983 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
5984 }
5985 }
5986 // Store the A and AAAA records that we registered with the sleep proxy.
5987 // We will use this to prevent spurious name conflicts that may occur when we wake up
5988 if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
5989 {
5990 mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
5991 }
5992 }
5993 }
5994
5995 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
5996 {
5997 AuthRecord *ar;
5998 OwnerOptData owner = zeroOwner;
5999
6000 SendSPSRegistrationForOwner(m, intf, id, &owner);
6001
6002 for (ar = m->ResourceRecords; ar; ar=ar->next)
6003 {
6004 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6005 {
6006 owner = ar->WakeUp;
6007 SendSPSRegistrationForOwner(m, intf, id, &owner);
6008 }
6009 }
6010 }
6011
6012 // RetrySPSRegistrations is called from SendResponses, with the lock held
6013 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6014 {
6015 AuthRecord *rr;
6016 NetworkInterfaceInfo *intf;
6017
6018 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6019 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6020 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6021 intf->NextSPSAttemptTime++;
6022
6023 // Retry any record registrations that are due
6024 for (rr = m->ResourceRecords; rr; rr=rr->next)
6025 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6026 {
6027 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6028 {
6029 // If we still have registrations pending on this interface, send it now
6030 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6031 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6032 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6033 {
6034 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6035 SendSPSRegistration(m, intf, rr->updateid);
6036 }
6037 }
6038 }
6039
6040 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6041 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6042 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6043 intf->NextSPSAttempt++;
6044 }
6045
6046 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6047 {
6048 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6049 int sps = (int)(question - intf->NetWakeResolve);
6050 (void)m; // Unused
6051 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6052
6053 if (!AddRecord) return; // Don't care about REMOVE events
6054 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
6055
6056 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6057
6058 if (answer->rrtype == kDNSType_SRV)
6059 {
6060 // 1. Got the SRV record; now look up the target host's IP address
6061 mDNS_StopQuery(m, question);
6062 intf->SPSPort[sps] = answer->rdata->u.srv.port;
6063 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6064 question->qtype = kDNSType_A;
6065 mDNS_StartQuery(m, question);
6066 }
6067 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6068 {
6069 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6070 mDNS_StopQuery(m, question);
6071 question->ThisQInterval = -1;
6072 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6073 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6074 mDNS_Lock(m);
6075 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6076 mDNS_Unlock(m);
6077 }
6078 else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6079 {
6080 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6081 mDNS_StopQuery(m, question);
6082 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6083 question->qtype = kDNSType_AAAA;
6084 mDNS_StartQuery(m, question);
6085 }
6086 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6087 {
6088 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6089 mDNS_StopQuery(m, question);
6090 question->ThisQInterval = -1;
6091 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6092 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6093 mDNS_Lock(m);
6094 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6095 mDNS_Unlock(m);
6096 }
6097 }
6098
6099 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6100 {
6101 AuthRecord *rr;
6102 for (rr = m->ResourceRecords; rr; rr=rr->next)
6103 if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6104 return mDNStrue;
6105 return mDNSfalse;
6106 }
6107
6108 #ifdef APPLE_OSX_mDNSResponder
6109 // This function is used only in the case of local NIC proxy. For external
6110 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6111 // walk the resource records.
6112 mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6113 {
6114 AuthRecord *rr;
6115
6116 *WakeOnlyService = mDNSfalse;
6117
6118 // Mark all the records we need to deregister and send them
6119 for (rr = m->ResourceRecords; rr; rr=rr->next)
6120 {
6121 if ((rr->AuthFlags & AuthFlagsWakeOnly) &&
6122 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6123 {
6124 rr->ImmedAnswer = mDNSInterfaceMark;
6125 *WakeOnlyService = mDNStrue;
6126 }
6127 }
6128 }
6129 #endif // APPLE_OSx_mDNSResponder
6130
6131 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6132 {
6133 AuthRecord *rr;
6134 m->SleepState = SleepState_Sleeping;
6135
6136 // If AllInterfaces is not set, the caller has already marked it appropriately
6137 // on which interfaces this should be sent.
6138 if (AllInterfaces)
6139 {
6140 NetworkInterfaceInfo *intf;
6141 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6142 {
6143 intf->SendGoodbyes = 1;
6144 }
6145 }
6146 if (unicast)
6147 {
6148 #ifndef UNICAST_DISABLED
6149 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
6150 #endif /* UNICAST_DISABLED */
6151 }
6152
6153 // Mark all the records we need to deregister and send them
6154 for (rr = m->ResourceRecords; rr; rr=rr->next)
6155 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6156 rr->ImmedAnswer = mDNSInterfaceMark;
6157 SendResponses(m);
6158 }
6159
6160 /*
6161 * This function attempts to detect if multiple interfaces are on the same subnet.
6162 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6163 * IPv6 link local addresses that are configured by default on all interfaces make
6164 * it hard to make this determination
6165 *
6166 * The 'real' fix for this would be to send out multicast packets over one interface
6167 * and conclude that multiple interfaces are on the same subnet only if these packets
6168 * are seen on other interfaces on the same system
6169 */
6170 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6171 {
6172 NetworkInterfaceInfo *intf;
6173 NetworkInterfaceInfo *newIntf;
6174 mDNSu32 i;
6175
6176 for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6177 {
6178 if ((newIntf->InterfaceID != intfid) ||
6179 (newIntf->ip.type != mDNSAddrType_IPv4))
6180 {
6181 continue;
6182 }
6183 for ( i = 0; i < count; i++)
6184 {
6185 for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6186 {
6187 if ((intf->InterfaceID != regID[i]) ||
6188 (intf->ip.type != mDNSAddrType_IPv4))
6189 {
6190 continue;
6191 }
6192 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6193 {
6194 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6195 return (mDNStrue);
6196 }
6197 }
6198 }
6199 }
6200 return (mDNSfalse);
6201 }
6202
6203 mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6204 {
6205 // Loop through the keepalive records and callback with an error
6206 m->CurrentRecord = m->ResourceRecords;
6207 while (m->CurrentRecord)
6208 {
6209 AuthRecord *const rr = m->CurrentRecord;
6210 if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6211 {
6212 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6213 if (rr->RecordCallback)
6214 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6215 }
6216 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6217 m->CurrentRecord = rr->next;
6218 }
6219 }
6220
6221 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6222 mDNSlocal void BeginSleepProcessing(mDNS *const m)
6223 {
6224 mDNSBool SendGoodbyes = mDNStrue;
6225 mDNSBool WakeOnlyService = mDNSfalse;
6226 mDNSBool invokeKACallback = mDNStrue;
6227 const CacheRecord *sps[3] = { mDNSNULL };
6228 mDNSOpaque64 updateIntID = zeroOpaque64;
6229 mDNSInterfaceID registeredIntfIDS[128];
6230 mDNSu32 registeredCount = 0;
6231 int skippedRegistrations = 0;
6232
6233 m->NextScheduledSPRetry = m->timenow;
6234
6235 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6236 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6237 else // If we have at least one advertised service
6238 {
6239 NetworkInterfaceInfo *intf;
6240 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6241 {
6242 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6243 intf->SendGoodbyes = 0;
6244
6245 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6246 // servers.
6247 if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6248 {
6249 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6250 continue;
6251 }
6252
6253 // If we are not capable of WOMP, then don't register with sleep proxy.
6254 //
6255 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6256 // We might find sleep proxy servers in the cache and start a resolve on them.
6257 // But then if the interface goes away, we won't stop these questions because
6258 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6259 // to stop both the browse and resolve questions.
6260 if (!intf->NetWake)
6261 {
6262 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6263 intf->SendGoodbyes = 1;
6264 skippedRegistrations++;
6265 continue;
6266 }
6267
6268 // Check if we have already registered with a sleep proxy for this subnet
6269 if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6270 {
6271 LogSPS("%s : Skipping sleep proxy registration on %s", __func__, intf->ifname);
6272 continue;
6273 }
6274
6275 #if APPLE_OSX_mDNSResponder
6276 else if (SupportsInNICProxy(intf))
6277 {
6278 if (ActivateLocalProxy(m, intf) == mStatus_NoError)
6279 {
6280 SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6281 SendGoodbyes = mDNSfalse;
6282 invokeKACallback = mDNSfalse;
6283 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6284 // This will leave m->SleepState set to SleepState_Transferring,
6285 // which is okay because with no outstanding resolves, or updates in flight,
6286 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6287
6288 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6289 registeredCount++;
6290 }
6291 }
6292 #endif // APPLE_OSX_mDNSResponder
6293 else
6294 {
6295 #if APPLE_OSX_mDNSResponder
6296 // If on battery, do not attempt to offload to external sleep proxies
6297 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6298 {
6299 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6300 return;
6301 }
6302 #endif // APPLE_OSX_mDNSResponder
6303 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6304 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6305 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6306 else
6307 {
6308 int i;
6309 mDNSu32 scopeid;
6310 SendGoodbyes = mDNSfalse;
6311 intf->NextSPSAttempt = 0;
6312 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6313
6314 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6315 // Now we know for sure that we have to wait for registration to complete on this interface.
6316 if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6317 bit_set_opaque64(updateIntID, scopeid);
6318
6319 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6320 for (i=0; i<3; i++)
6321 {
6322 #if ForceAlerts
6323 if (intf->SPSAddr[i].type)
6324 { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); *(long*)0 = 0; }
6325 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6326 { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); *(long*)0 = 0; }
6327 #endif
6328 intf->SPSAddr[i].type = mDNSAddrType_None;
6329 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6330 intf->NetWakeResolve[i].ThisQInterval = -1;
6331 if (sps[i])
6332 {
6333 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6334 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6335 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6336 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6337
6338 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6339 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6340 registeredCount++;
6341 }
6342 }
6343 }
6344 }
6345 }
6346 }
6347
6348 // If we have at least one interface on which we are registering with an external sleep proxy,
6349 // initialize all the records appropriately.
6350 if (!mDNSOpaque64IsZero(&updateIntID))
6351 SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6352
6353 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6354 // the records to a sleep proxy.
6355 if (invokeKACallback)
6356 {
6357 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6358 DoKeepaliveCallbacks(m);
6359 }
6360
6361 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6362 // interfaces and also deregister unicast registrations.
6363 //
6364 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6365 // for both multicast and unicast.
6366 //
6367 // - If we skipped registrations on some interfaces, then we have already marked
6368 // them appropriately above. We don't need to send goodbyes for unicast as
6369 // we have registered with at least one sleep proxy.
6370 //
6371 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6372 //
6373 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6374 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6375 // at WakeOnlyServices first.
6376 if (SendGoodbyes)
6377 {
6378 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6379 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6380 }
6381 else if (skippedRegistrations)
6382 {
6383 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6384 SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6385 }
6386 else if (WakeOnlyService)
6387 {
6388 // If we saw WakeOnly service above, send the goodbyes now.
6389 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyServices");
6390 SendResponses(m);
6391 }
6392 }
6393
6394 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6395 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6396 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6397 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6398 {
6399 AuthRecord *rr;
6400
6401 LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6402
6403 if (sleep && !m->SleepState) // Going to sleep
6404 {
6405 mDNS_Lock(m);
6406 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6407 if (m->SPSSocket)
6408 {
6409 mDNSu8 oldstate = m->SPSState;
6410 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6411 m->SPSState = 2;
6412 #ifndef SPC_DISABLED
6413 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6414 #else
6415 (void)oldstate;
6416 #endif
6417 mDNS_ReclaimLockAfterCallback();
6418 }
6419
6420 m->SleepState = SleepState_Transferring;
6421 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6422 {
6423 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6424 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6425 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6426 }
6427 else
6428 {
6429 m->DelaySleep = 0;
6430 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6431 m->mDNSStats.Sleeps++;
6432 BeginSleepProcessing(m);
6433 }
6434
6435 #ifndef UNICAST_DISABLED
6436 SuspendLLQs(m);
6437 #endif
6438 #if APPLE_OSX_mDNSResponder
6439 RemoveAutoTunnel6Record(m);
6440 #endif
6441 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
6442 m->SleepState == SleepState_Transferring ? "Transferring" :
6443 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
6444 mDNS_Unlock(m);
6445 }
6446 else if (!sleep) // Waking up
6447 {
6448 mDNSu32 slot;
6449 CacheGroup *cg;
6450 CacheRecord *cr;
6451 NetworkInterfaceInfo *intf;
6452 mDNSs32 currtime, diff;
6453
6454 mDNS_Lock(m);
6455 // Reset SleepLimit back to 0 now that we're awake again.
6456 m->SleepLimit = 0;
6457
6458 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6459 if (m->SleepState != SleepState_Awake)
6460 {
6461 m->SleepState = SleepState_Awake;
6462 m->SleepSeqNum++;
6463 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6464 // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
6465 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6466 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6467 m->DelaySleep = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 16);
6468 }
6469
6470 if (m->SPSState == 3)
6471 {
6472 m->SPSState = 0;
6473 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
6474 }
6475 m->mDNSStats.Wakes++;
6476
6477 // ... and the same for NextSPSAttempt
6478 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
6479
6480 // Restart unicast and multicast queries
6481 mDNSCoreRestartQueries(m);
6482
6483 // and reactivtate service registrations
6484 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
6485 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
6486
6487 // 2. Re-validate our cache records
6488 currtime = mDNSPlatformUTC();
6489
6490 #if APPLE_OSX_mDNSResponder
6491 // start time of this statistics gathering interval
6492 m->StatStartTime = currtime;
6493 #endif // APPLE_OSX_mDNSResponder
6494
6495 diff = currtime - m->TimeSlept;
6496 FORALL_CACHERECORDS(slot, cg, cr)
6497 {
6498 // Temporary fix: For unicast cache records, look at how much time we slept.
6499 // Adjust the RecvTime by the amount of time we slept so that we age the
6500 // cache record appropriately. If it is expired already, purge. If there
6501 // is a network change that happens after the wakeup, we might purge the
6502 // cache anyways and this helps only in the case where there are no network
6503 // changes across sleep/wakeup transition.
6504 //
6505 // Note: If there is a network/DNS server change that already happened and
6506 // these cache entries are already refreshed and we are getting a delayed
6507 // wake up notification, we might adjust the TimeRcvd based on the time slept
6508 // now which can cause the cache to purge pre-maturely. As this is not a very
6509 // common case, this should happen rarely.
6510 if (!cr->resrec.InterfaceID)
6511 {
6512 if (diff > 0)
6513 {
6514 mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
6515 const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
6516
6517 // -if we have slept longer than the remaining TTL, purge and start fresh.
6518 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6519 // a sufficiently big value which could cause the value to go into the future
6520 // because of the signed comparison of time. For this to happen, we should have been
6521 // sleeping really long (~24 days). For now, we want to be conservative and flush even
6522 // if we have slept for more than two days.
6523
6524 if (diff >= remain || diff > (2 * 24 * 3600))
6525 {
6526 LogInfo("mDNSCoreMachineSleep: %s: Purging cache entry SleptTime %d, Remaining TTL %d",
6527 CRDisplayString(m, cr), diff, remain);
6528 mDNS_PurgeCacheResourceRecord(m, cr);
6529 continue;
6530 }
6531 cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
6532 if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
6533 {
6534 LogInfo("mDNSCoreMachineSleep: %s: Purging after adjusting the remaining TTL %d by %d seconds",
6535 CRDisplayString(m, cr), remain, diff);
6536 mDNS_PurgeCacheResourceRecord(m, cr);
6537 }
6538 else
6539 {
6540 LogInfo("mDNSCoreMachineSleep: %s: Adjusted the remain ttl %u by %d seconds", CRDisplayString(m, cr), remain, diff);
6541 }
6542 }
6543 }
6544 else
6545 {
6546 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
6547 }
6548 }
6549
6550 // 3. Retrigger probing and announcing for all our authoritative records
6551 for (rr = m->ResourceRecords; rr; rr=rr->next)
6552 {
6553 if (AuthRecord_uDNS(rr))
6554 {
6555 ActivateUnicastRegistration(m, rr);
6556 }
6557 else
6558 {
6559 mDNSCoreRestartRegistration(m, rr, -1);
6560 }
6561 }
6562
6563 // 4. Refresh NAT mappings
6564 // We don't want to have to assume that all hardware can necessarily keep accurate
6565 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
6566 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
6567 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
6568 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
6569 // than five seconds from now.
6570 LogInfo("mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
6571 RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
6572 mDNS_Unlock(m);
6573 }
6574 }
6575
6576 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
6577 {
6578 DNSQuestion *q;
6579 AuthRecord *rr;
6580 NetworkInterfaceInfo *intf;
6581
6582 mDNS_Lock(m);
6583
6584 if (m->DelaySleep) goto notready;
6585
6586 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
6587 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
6588
6589 m->NextScheduledSPRetry = now + 0x40000000UL;
6590
6591 // See if we might need to retransmit any lost Sleep Proxy Registrations
6592 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6593 if (intf->NextSPSAttempt >= 0)
6594 {
6595 if (now - intf->NextSPSAttemptTime >= 0)
6596 {
6597 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
6598 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
6599 SendSPSRegistration(m, intf, zeroID);
6600 // Don't need to "goto notready" here, because if we do still have record registrations
6601 // that have not been acknowledged yet, we'll catch that in the record list scan below.
6602 }
6603 else
6604 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6605 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6606 }
6607
6608 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
6609 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6610 {
6611 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
6612 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
6613 {
6614 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
6615 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
6616 goto spsnotready;
6617 }
6618 }
6619
6620 // Scan list of registered records
6621 for (rr = m->ResourceRecords; rr; rr = rr->next)
6622 if (!AuthRecord_uDNS(rr))
6623 if (!mDNSOpaque64IsZero(&rr->updateIntID))
6624 { 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; }
6625
6626 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
6627 for (q = m->Questions; q; q = q->next)
6628 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
6629 {
6630 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
6631 goto notready;
6632 }
6633
6634 // Scan list of registered records
6635 for (rr = m->ResourceRecords; rr; rr = rr->next)
6636 if (AuthRecord_uDNS(rr))
6637 {
6638 if (rr->state == regState_Refresh && rr->tcp)
6639 { 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; }
6640 #if APPLE_OSX_mDNSResponder
6641 if (!RecordReadyForSleep(m, rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
6642 #endif
6643 }
6644
6645 mDNS_Unlock(m);
6646 return mDNStrue;
6647
6648 spsnotready:
6649
6650 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
6651 // and allow up to ten seconds more to complete wide-area deregistration instead
6652 if (now - m->SleepLimit >= 0)
6653 {
6654 LogMsg("Failed to register with SPS, now sending goodbyes");
6655
6656 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6657 if (intf->NetWakeBrowse.ThisQInterval >= 0)
6658 {
6659 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
6660 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
6661 mDNS_DeactivateNetWake_internal(m, intf);
6662 }
6663
6664 for (rr = m->ResourceRecords; rr; rr = rr->next)
6665 if (!AuthRecord_uDNS(rr))
6666 if (!mDNSOpaque64IsZero(&rr->updateIntID))
6667 {
6668 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));
6669 rr->updateIntID = zeroOpaque64;
6670 }
6671
6672 // We'd really like to allow up to ten seconds more here,
6673 // but if we don't respond to the sleep notification within 30 seconds
6674 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
6675 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
6676 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
6677 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
6678 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
6679
6680 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6681 }
6682
6683 notready:
6684 mDNS_Unlock(m);
6685 return mDNSfalse;
6686 }
6687
6688 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
6689 {
6690 AuthRecord *ar;
6691
6692 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
6693 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
6694 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
6695 // and if that happens we don't want to just give up and go back to sleep and never try again.
6696 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
6697
6698 NATTraversalInfo *nat;
6699 for (nat = m->NATTraversals; nat; nat=nat->next)
6700 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
6701 {
6702 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
6703 if (e - t > 0) e = t;
6704 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
6705 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
6706 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
6707 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
6708 nat->retryInterval / mDNSPlatformOneSecond,
6709 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
6710 (t - now) / mDNSPlatformOneSecond);
6711 }
6712
6713 // This loop checks both the time we need to renew wide-area registrations,
6714 // and the time we need to renew Sleep Proxy registrations
6715 for (ar = m->ResourceRecords; ar; ar = ar->next)
6716 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
6717 {
6718 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
6719 if (e - t > 0) e = t;
6720 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
6721 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
6722 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
6723 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
6724 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
6725 }
6726
6727 return(e - now);
6728 }
6729
6730 // ***************************************************************************
6731 #if COMPILER_LIKES_PRAGMA_MARK
6732 #pragma mark -
6733 #pragma mark - Packet Reception Functions
6734 #endif
6735
6736 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
6737
6738 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
6739 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
6740 {
6741 mDNSu8 *responseptr = response->data;
6742 const mDNSu8 *const limit = response->data + sizeof(response->data);
6743 const mDNSu8 *ptr = query->data;
6744 AuthRecord *rr;
6745 mDNSu32 maxttl = 0x70000000;
6746 int i;
6747
6748 // Initialize the response fields so we can answer the questions
6749 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
6750
6751 // ***
6752 // *** 1. Write out the list of questions we are actually going to answer with this packet
6753 // ***
6754 if (LegacyQuery)
6755 {
6756 maxttl = kStaticCacheTTL;
6757 for (i=0; i<query->h.numQuestions; i++) // For each question...
6758 {
6759 DNSQuestion q;
6760 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
6761 if (!ptr) return(mDNSNULL);
6762
6763 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
6764 {
6765 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
6766 { // then put the question in the question section
6767 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
6768 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
6769 break; // break out of the ResponseRecords loop, and go on to the next question
6770 }
6771 }
6772 }
6773
6774 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
6775 }
6776
6777 // ***
6778 // *** 2. Write Answers
6779 // ***
6780 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6781 if (rr->NR_AnswerTo)
6782 {
6783 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
6784 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
6785 if (p) responseptr = p;
6786 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
6787 }
6788
6789 // ***
6790 // *** 3. Write Additionals
6791 // ***
6792 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6793 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
6794 {
6795 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
6796 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
6797 if (p) responseptr = p;
6798 else debugf("GenerateUnicastResponse: No more space for additionals");
6799 }
6800
6801 return(responseptr);
6802 }
6803
6804 // AuthRecord *our is our Resource Record
6805 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
6806 // Returns 0 if there is no conflict
6807 // Returns +1 if there was a conflict and we won
6808 // Returns -1 if there was a conflict and we lost and have to rename
6809 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
6810 {
6811 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
6812 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
6813 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
6814 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
6815
6816 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
6817 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
6818 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
6819 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
6820
6821 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
6822 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
6823 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
6824 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
6825
6826 LogMsg("CompareRData ERROR: Invalid state");
6827 return(-1);
6828 }
6829
6830 // See if we have an authoritative record that's identical to this packet record,
6831 // whose canonical DependentOn record is the specified master record.
6832 // The DependentOn pointer is typically used for the TXT record of service registrations
6833 // It indicates that there is no inherent conflict detection for the TXT record
6834 // -- it depends on the SRV record to resolve name conflicts
6835 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
6836 // pointer chain (if any) to make sure we reach the canonical DependentOn record
6837 // If the record has no DependentOn, then just return that record's pointer
6838 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6839 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
6840 {
6841 const AuthRecord *r1;
6842 for (r1 = m->ResourceRecords; r1; r1=r1->next)
6843 {
6844 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
6845 {
6846 const AuthRecord *r2 = r1;
6847 while (r2->DependentOn) r2 = r2->DependentOn;
6848 if (r2 == master) return(mDNStrue);
6849 }
6850 }
6851 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
6852 {
6853 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
6854 {
6855 const AuthRecord *r2 = r1;
6856 while (r2->DependentOn) r2 = r2->DependentOn;
6857 if (r2 == master) return(mDNStrue);
6858 }
6859 }
6860 return(mDNSfalse);
6861 }
6862
6863 // Find the canonical RRSet pointer for this RR received in a packet.
6864 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
6865 // pointers (if any) to make sure we return the canonical member of this name/type/class
6866 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6867 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
6868 {
6869 const AuthRecord *rr;
6870 for (rr = m->ResourceRecords; rr; rr=rr->next)
6871 {
6872 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
6873 {
6874 while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
6875 return(rr);
6876 }
6877 }
6878 return(mDNSNULL);
6879 }
6880
6881 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
6882 // as one of our records (our) but different rdata.
6883 // 1. If our record is not a type that's supposed to be unique, we don't care.
6884 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
6885 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
6886 // points to our record, ignore this conflict (e.g. the packet record matches one of our
6887 // TXT records, and that record is marked as dependent on 'our', its SRV record).
6888 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
6889 // are members of the same RRSet, then this is not a conflict.
6890 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
6891 {
6892 // If not supposed to be unique, not a conflict
6893 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
6894
6895 // If a dependent record, not a conflict
6896 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
6897 else
6898 {
6899 // If the pktrr matches a member of ourset, not a conflict
6900 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
6901 const AuthRecord *pktset = FindRRSet(m, pktrr);
6902 if (pktset == ourset) return(mDNSfalse);
6903
6904 // For records we're proxying, where we don't know the full
6905 // relationship between the records, having any matching record
6906 // in our AuthRecords list is sufficient evidence of non-conflict
6907 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
6908 }
6909
6910 // Okay, this is a conflict
6911 return(mDNStrue);
6912 }
6913
6914 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
6915 // the record list and/or question list.
6916 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6917 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
6918 DNSQuestion *q, AuthRecord *our)
6919 {
6920 int i;
6921 const mDNSu8 *ptr = LocateAuthorities(query, end);
6922 mDNSBool FoundUpdate = mDNSfalse;
6923
6924 for (i = 0; i < query->h.numAuthorities; i++)
6925 {
6926 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
6927 if (!ptr) break;
6928 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
6929 {
6930 FoundUpdate = mDNStrue;
6931 if (PacketRRConflict(m, our, &m->rec.r))
6932 {
6933 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
6934 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
6935 if (!result) result = CompareRData(our, &m->rec.r);
6936 if (result)
6937 {
6938 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
6939 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
6940 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
6941 }
6942 // 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.
6943 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
6944 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
6945 if (result < 0)
6946 {
6947 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
6948 our->ProbeCount = DefaultProbeCountForTypeUnique;
6949 our->AnnounceCount = InitialAnnounceCount;
6950 InitializeLastAPTime(m, our);
6951 goto exit;
6952 }
6953 }
6954 #if 0
6955 else
6956 {
6957 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
6958 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
6959 }
6960 #endif
6961 }
6962 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6963 }
6964 if (!FoundUpdate)
6965 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
6966 exit:
6967 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6968 }
6969
6970 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
6971 {
6972 mDNSu32 slot = HashSlot(pktrr->name);
6973 CacheGroup *cg = CacheGroupForRecord(m, slot, pktrr);
6974 CacheRecord *rr;
6975 mDNSBool match;
6976 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6977 {
6978 if (!pktrr->InterfaceID)
6979 {
6980 mDNSu16 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
6981 mDNSu16 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
6982 match = (id1 == id2);
6983 }
6984 else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
6985
6986 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
6987 }
6988 return(rr);
6989 }
6990 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
6991 {
6992 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
6993 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
6994 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
6995 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
6996 }
6997
6998 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
6999 {
7000 if (m->CurrentRecord)
7001 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7002 m->CurrentRecord = thelist;
7003
7004 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7005 // clean up the keepalive record.
7006 while (m->CurrentRecord)
7007 {
7008 AuthRecord *const rr = m->CurrentRecord;
7009 if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7010 {
7011 if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7012 {
7013 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7014 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7015 DeregisterProxyRecord(m, rr);
7016 }
7017 }
7018 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7019 // new records could have been added to the end of the list as a result of that call.
7020 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7021 m->CurrentRecord = rr->next;
7022 }
7023 }
7024
7025 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7026 // to check our lists and discard any stale duplicates of this record we already have
7027 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7028 {
7029 if (m->CurrentRecord)
7030 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7031 m->CurrentRecord = thelist;
7032 while (m->CurrentRecord)
7033 {
7034 AuthRecord *const rr = m->CurrentRecord;
7035 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7036 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7037 {
7038 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7039 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7040 DeregisterProxyRecord(m, rr);
7041 }
7042 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7043 // new records could have been added to the end of the list as a result of that call.
7044 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7045 m->CurrentRecord = rr->next;
7046 }
7047 }
7048
7049 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7050 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7051 {
7052 if (m->CurrentRecord)
7053 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7054 m->CurrentRecord = thelist;
7055 while (m->CurrentRecord)
7056 {
7057 AuthRecord *const rr = m->CurrentRecord;
7058 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7059 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7060 {
7061 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7062 {
7063 // We don't do this here because we know that the host is waking up at this point, so we don't send
7064 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7065 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7066 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7067 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7068 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7069 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7070 #endif
7071 }
7072 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7073 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7074 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7075 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7076 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7077 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7078 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7079 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7080 }
7081 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7082 // new records could have been added to the end of the list as a result of that call.
7083 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7084 m->CurrentRecord = rr->next;
7085 }
7086 }
7087
7088 // ProcessQuery examines a received query to see if we have any answers to give
7089 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7090 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7091 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7092 {
7093 mDNSBool FromLocalSubnet = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, mDNSNULL);
7094 AuthRecord *ResponseRecords = mDNSNULL;
7095 AuthRecord **nrp = &ResponseRecords;
7096
7097 #if POOF_ENABLED
7098 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
7099 CacheRecord **eap = &ExpectedAnswers;
7100 #endif // POOF_ENABLED
7101
7102 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
7103 DNSQuestion **dqp = &DupQuestions;
7104 mDNSs32 delayresponse = 0;
7105 mDNSBool SendLegacyResponse = mDNSfalse;
7106 const mDNSu8 *ptr;
7107 mDNSu8 *responseptr = mDNSNULL;
7108 AuthRecord *rr;
7109 int i;
7110 CacheRecord *McastNSEC3Records = mDNSNULL;
7111
7112 // ***
7113 // *** 1. Look in Additional Section for an OPT record
7114 // ***
7115 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7116 if (ptr)
7117 {
7118 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7119 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7120 {
7121 const rdataOPT *opt;
7122 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7123 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7124 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7125 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7126 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7127 {
7128 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7129 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7130 }
7131 }
7132 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7133 }
7134
7135 //
7136 // Look in Authority Section for NSEC3 record
7137 //
7138
7139 mDNSParseNSEC3Records(m, query, end, InterfaceID, &McastNSEC3Records);
7140
7141 // ***
7142 // *** 2. Parse Question Section and mark potential answers
7143 // ***
7144 ptr = query->data;
7145 for (i=0; i<query->h.numQuestions; i++) // For each question...
7146 {
7147 mDNSBool QuestionNeedsMulticastResponse;
7148 int NumAnswersForThisQuestion = 0;
7149 AuthRecord *NSECAnswer = mDNSNULL;
7150 DNSQuestion pktq, *q;
7151 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7152 if (!ptr) goto exit;
7153
7154 pktq.AnonInfo = mDNSNULL;
7155 if (McastNSEC3Records)
7156 InitializeAnonInfoForQuestion(m, &McastNSEC3Records, &pktq);
7157 // The only queries that *need* a multicast response are:
7158 // * Queries sent via multicast
7159 // * from port 5353
7160 // * that don't have the kDNSQClass_UnicastResponse bit set
7161 // These queries need multicast responses because other clients will:
7162 // * suppress their own identical questions when they see these questions, and
7163 // * expire their cache records if they don't see the expected responses
7164 // For other queries, we may still choose to send the occasional multicast response anyway,
7165 // to keep our neighbours caches warm, and for ongoing conflict detection.
7166 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7167
7168 if (pktq.qclass & kDNSQClass_UnicastResponse)
7169 m->mDNSStats.UnicastBitInQueries++;
7170 else
7171 m->mDNSStats.NormalQueries++;
7172
7173 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7174 pktq.qclass &= ~kDNSQClass_UnicastResponse;
7175
7176 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7177 // can result in user callbacks which may change the record list and/or question list.
7178 // Also note: we just mark potential answer records here, without trying to build the
7179 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7180 // from that list while we're in the middle of trying to build it.
7181 if (m->CurrentRecord)
7182 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7183 m->CurrentRecord = m->ResourceRecords;
7184 while (m->CurrentRecord)
7185 {
7186 rr = m->CurrentRecord;
7187 m->CurrentRecord = rr->next;
7188 if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7189 {
7190 m->mDNSStats.MatchingAnswersForQueries++;
7191 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7192 {
7193 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7194 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7195 else if (ResourceRecordIsValidAnswer(rr))
7196 {
7197 NumAnswersForThisQuestion++;
7198 // As we have verified this question to be part of the same subset,
7199 // set the anonymous data which is needed below when walk the cache
7200 // records to see what answers we should be expecting. The cache records
7201 // may cache only the nsec3RR and not the anonymous data itself.
7202 if (pktq.AnonInfo && rr->resrec.AnonInfo)
7203 SetAnonData(&pktq, &rr->resrec, mDNStrue);
7204
7205 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7206 // unicast answer back to the source, because timeliness in answering probes is important.
7207
7208 // Notes:
7209 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7210 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7211 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7212 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7213 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7214 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7215 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7216 {
7217 // We only mark this question for sending if it is at least one second since the last time we multicast it
7218 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7219 // This is to guard against the case where someone blasts us with queries as fast as they can.
7220 if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
7221 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7222 rr->NR_AnswerTo = NR_AnswerMulticast;
7223 }
7224 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7225 }
7226 }
7227 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7228 {
7229 // If we don't have any answers for this question, but we do own another record with the same name,
7230 // then we'll want to mark it to generate an NSEC record on this interface
7231 if (!NSECAnswer) NSECAnswer = rr;
7232 }
7233 }
7234 }
7235
7236 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7237 {
7238 NumAnswersForThisQuestion++;
7239 NSECAnswer->SendNSECNow = InterfaceID;
7240 m->NextScheduledResponse = m->timenow;
7241 }
7242
7243 // If we couldn't answer this question, someone else might be able to,
7244 // so use random delay on response to reduce collisions
7245 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7246
7247 if (query->h.flags.b[0] & kDNSFlag0_TC)
7248 m->mDNSStats.KnownAnswerMultiplePkts++;
7249 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7250 if (QuestionNeedsMulticastResponse)
7251 #else
7252 // We only do the following accelerated cache expiration and duplicate question suppression processing
7253 // for non-truncated multicast queries with multicast responses.
7254 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7255 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7256 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7257 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7258 #endif
7259 {
7260 #if POOF_ENABLED
7261 const mDNSu32 slot = HashSlot(&pktq.qname);
7262 CacheGroup *cg = CacheGroupForName(m, slot, pktq.qnamehash, &pktq.qname);
7263 CacheRecord *cr;
7264
7265 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7266 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7267 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7268 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7269 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7270 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7271 if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7272 if (!cr->NextInKAList && eap != &cr->NextInKAList)
7273 {
7274 *eap = cr;
7275 eap = &cr->NextInKAList;
7276 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7277 if (cr->MPUnansweredQ == 0 || m->timenow - cr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
7278 {
7279 // Although MPUnansweredQ is only really used for multi-packet query processing,
7280 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
7281 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
7282 cr->MPUnansweredQ++;
7283 cr->MPLastUnansweredQT = m->timenow;
7284 cr->MPExpectingKA = mDNStrue;
7285 }
7286 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7287 }
7288 #endif // POOF_ENABLED
7289
7290 // Check if this question is the same as any of mine.
7291 // We only do this for non-truncated queries. Right now it would be too complicated to try
7292 // to keep track of duplicate suppression state between multiple packets, especially when we
7293 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7294 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7295 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7296 #endif
7297 // For anonymous question, the duplicate suppressesion should happen if the
7298 // question belongs in the same group. As the group is expected to be
7299 // small, we don't do the optimization for now.
7300 if (!pktq.AnonInfo)
7301 {
7302 for (q = m->Questions; q; q=q->next)
7303 if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7304 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7305 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7306 if (q->qtype == pktq.qtype &&
7307 q->qclass == pktq.qclass &&
7308 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7309 { *dqp = q; dqp = &q->NextInDQList; }
7310 }
7311 }
7312 if (pktq.AnonInfo)
7313 {
7314 FreeAnonInfo(pktq.AnonInfo);
7315 }
7316 }
7317
7318 // ***
7319 // *** 3. Now we can safely build the list of marked answers
7320 // ***
7321 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
7322 if (rr->NR_AnswerTo) // If we marked the record...
7323 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
7324
7325 // ***
7326 // *** 4. Add additional records
7327 // ***
7328 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7329
7330 // ***
7331 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7332 // ***
7333 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
7334 {
7335 // Get the record...
7336 CacheRecord *ourcacherr;
7337 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7338 if (!ptr) goto exit;
7339 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7340 {
7341 // See if this Known-Answer suppresses any of our currently planned answers
7342 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7343 {
7344 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7345 {
7346 m->mDNSStats.KnownAnswerSuppressions++;
7347 rr->NR_AnswerTo = mDNSNULL;
7348 rr->NR_AdditionalTo = mDNSNULL;
7349 }
7350 }
7351
7352 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7353 for (rr=m->ResourceRecords; rr; rr=rr->next)
7354 {
7355 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7356 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7357 {
7358 if (srcaddr->type == mDNSAddrType_IPv4)
7359 {
7360 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7361 }
7362 else if (srcaddr->type == mDNSAddrType_IPv6)
7363 {
7364 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7365 }
7366 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7367 {
7368 m->mDNSStats.KnownAnswerSuppressions++;
7369 rr->ImmedAnswer = mDNSNULL;
7370 rr->ImmedUnicast = mDNSfalse;
7371 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7372 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7373 #endif
7374 }
7375 }
7376 }
7377
7378 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7379
7380 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7381 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
7382 // even if the TC bit is not set (the TC bit will *not* be set in the *last* packet of a multi-packet KA list).
7383 if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
7384 {
7385 ourcacherr->MPUnansweredKA++;
7386 ourcacherr->MPExpectingKA = mDNSfalse;
7387 }
7388 #endif
7389
7390 #if POOF_ENABLED
7391 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7392 // any records that are suppressed by the Known Answer list in this packet.
7393 eap = &ExpectedAnswers;
7394 while (*eap)
7395 {
7396 CacheRecord *cr = *eap;
7397 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7398 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7399 else eap = &cr->NextInKAList;
7400 }
7401 #endif // POOF_ENABLED
7402
7403 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7404 if (!ourcacherr)
7405 {
7406 dqp = &DupQuestions;
7407 while (*dqp)
7408 {
7409 DNSQuestion *q = *dqp;
7410 if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
7411 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7412 else dqp = &q->NextInDQList;
7413 }
7414 }
7415 }
7416 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7417 }
7418
7419 // ***
7420 // *** 6. Cancel any additionals that were added because of now-deleted records
7421 // ***
7422 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7423 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7424 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7425
7426 // ***
7427 // *** 7. Mark the send flags on the records we plan to send
7428 // ***
7429 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7430 {
7431 if (rr->NR_AnswerTo)
7432 {
7433 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
7434 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
7435
7436 #if !TARGET_OS_EMBEDDED
7437 // always honor kDNSQClass_UnicastResponse in embedded environment to increase reliability
7438 // in high multicast packet loss environments.
7439
7440 // If it's been one TTL/4 since we multicast this, then send a multicast response
7441 // for conflict detection, etc.
7442 if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0)
7443 {
7444 SendMulticastResponse = mDNStrue;
7445 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7446 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7447 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7448 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7449 {
7450 m->mDNSStats.UnicastDemotedToMulticast++;
7451 rr->NR_AnswerTo = NR_AnswerMulticast;
7452 }
7453 }
7454 #endif // !TARGET_OS_EMBEDDED
7455
7456 // If the client insists on a multicast response, then we'd better send one
7457 if (rr->NR_AnswerTo == NR_AnswerMulticast)
7458 {
7459 m->mDNSStats.MulticastResponses++;
7460 SendMulticastResponse = mDNStrue;
7461 }
7462 else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7463 {
7464 m->mDNSStats.UnicastResponses++;
7465 SendUnicastResponse = mDNStrue;
7466 }
7467 else if (rr->NR_AnswerTo)
7468 {
7469 SendLegacyResponse = mDNStrue;
7470 }
7471
7472
7473 if (SendMulticastResponse || SendUnicastResponse)
7474 {
7475 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7476 rr->ImmedAnswerMarkTime = m->timenow;
7477 #endif
7478 m->NextScheduledResponse = m->timenow;
7479 // If we're already planning to send this on another interface, just send it on all interfaces
7480 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7481 rr->ImmedAnswer = mDNSInterfaceMark;
7482 else
7483 {
7484 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
7485 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7486 if (srcaddr->type == mDNSAddrType_IPv4)
7487 {
7488 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7489 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
7490 }
7491 else if (srcaddr->type == mDNSAddrType_IPv6)
7492 {
7493 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
7494 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
7495 }
7496 }
7497 }
7498 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7499 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7500 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7501 // else, for a simple unique record reply, we can reply immediately; no need for delay
7502 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
7503 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7504 }
7505 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
7506 {
7507 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7508 // If two clients on different interfaces do queries that invoke the same optional additional answer,
7509 // then the earlier client is out of luck
7510 rr->ImmedAdditional = InterfaceID;
7511 // No need to set m->NextScheduledResponse here
7512 // We'll send these additional records when we send them, or not, as the case may be
7513 }
7514 }
7515
7516 // ***
7517 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7518 // ***
7519 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
7520 {
7521 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7522 mDNSs32 oldss = m->SuppressSending;
7523 if (oldss && delayresponse)
7524 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
7525 #endif
7526 // Pick a random delay:
7527 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7528 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7529 // This is an integer value, with resolution determined by the platform clock rate.
7530 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7531 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7532 // The +49 before dividing is to ensure we round up, not down, to ensure that even
7533 // on platforms where the native clock rate is less than fifty ticks per second,
7534 // we still guarantee that the final calculated delay is at least one platform tick.
7535 // We want to make sure we don't ever allow the delay to be zero ticks,
7536 // because if that happens we'll fail the Bonjour Conformance Test.
7537 // Our final computed delay is 20-120ms for normal delayed replies,
7538 // or 400-500ms in the case of multi-packet known-answer lists.
7539 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
7540 if (m->SuppressSending == 0) m->SuppressSending = 1;
7541 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7542 if (oldss && delayresponse)
7543 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
7544 #endif
7545 }
7546
7547 // ***
7548 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7549 // ***
7550 if (SendLegacyResponse)
7551 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
7552
7553 exit:
7554 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7555
7556 // ***
7557 // *** 10. Finally, clear our link chains ready for use next time
7558 // ***
7559 while (ResponseRecords)
7560 {
7561 rr = ResponseRecords;
7562 ResponseRecords = rr->NextResponse;
7563 rr->NextResponse = mDNSNULL;
7564 rr->NR_AnswerTo = mDNSNULL;
7565 rr->NR_AdditionalTo = mDNSNULL;
7566 }
7567
7568 #if POOF_ENABLED
7569 while (ExpectedAnswers)
7570 {
7571 CacheRecord *cr = ExpectedAnswers;
7572 ExpectedAnswers = cr->NextInKAList;
7573 cr->NextInKAList = mDNSNULL;
7574
7575 // For non-truncated queries, we can definitively say that we should expect
7576 // to be seeing a response for any records still left in the ExpectedAnswers list
7577 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7578 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond)
7579 {
7580 cr->UnansweredQueries++;
7581 cr->LastUnansweredTime = m->timenow;
7582 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7583 if (cr->UnansweredQueries > 1)
7584 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
7585 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
7586 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7587 SetNextCacheCheckTimeForRecord(m, cr);
7588 }
7589
7590 // If we've seen multiple unanswered queries for this record,
7591 // then mark it to expire in five seconds if we don't get a response by then.
7592 if (cr->UnansweredQueries >= MaxUnansweredQueries)
7593 {
7594 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7595 // Only show debugging message if this record was not about to expire anyway
7596 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
7597 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
7598 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
7599 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7600 m->mDNSStats.PoofCacheDeletions++;
7601 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
7602 }
7603 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7604 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
7605 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
7606 // possible packet loss of up to 20% of the additional KA packets.)
7607 else if (cr->MPUnansweredQ * 4 > cr->MPUnansweredKA * 5 + 8)
7608 {
7609 // We want to do this conservatively.
7610 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
7611 // then we don't want them to all hit the network simultaneously with their final expiration queries.
7612 // By setting the record to expire in four minutes, we achieve two things:
7613 // (a) the 90-95% final expiration queries will be less bunched together
7614 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
7615 mDNSu32 remain = (mDNSu32)(RRExpireTime(cr) - m->timenow) / 4;
7616 if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
7617 remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
7618
7619 // Only show debugging message if this record was not about to expire anyway
7620 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
7621 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
7622 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
7623
7624 if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
7625 cr->UnansweredQueries++; // Treat this as equivalent to one definite unanswered query
7626 cr->MPUnansweredQ = 0; // Clear MPQ/MPKA statistics
7627 cr->MPUnansweredKA = 0;
7628 cr->MPExpectingKA = mDNSfalse;
7629
7630 if (remain < kDefaultReconfirmTimeForNoAnswer)
7631 remain = kDefaultReconfirmTimeForNoAnswer;
7632 mDNS_Reconfirm_internal(m, cr, remain);
7633 }
7634 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7635 }
7636 #endif // POOF_ENABLED
7637
7638 while (DupQuestions)
7639 {
7640 DNSQuestion *q = DupQuestions;
7641 DupQuestions = q->NextInDQList;
7642 q->NextInDQList = mDNSNULL;
7643 i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
7644 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
7645 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
7646 }
7647
7648 if (McastNSEC3Records)
7649 {
7650 debugf("ProcessQuery: McastNSEC3Records not used");
7651 FreeNSECRecords(m, McastNSEC3Records);
7652 }
7653
7654 return(responseptr);
7655 }
7656
7657 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
7658 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
7659 const mDNSInterfaceID InterfaceID)
7660 {
7661 mDNSu8 *responseend = mDNSNULL;
7662 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
7663 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, mDNSNULL);
7664
7665 if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
7666 {
7667 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7668 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
7669 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7670 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
7671 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
7672 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
7673 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
7674 return;
7675 }
7676
7677 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7678 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
7679 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7680 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
7681 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
7682 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
7683 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
7684
7685 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
7686 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
7687
7688 if (responseend) // If responseend is non-null, that means we built a unicast response packet
7689 {
7690 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
7691 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
7692 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
7693 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
7694 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
7695 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
7696 }
7697 }
7698
7699 #if 0
7700 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
7701 {
7702 DNSServer *s;
7703 (void)m; // Unused
7704 (void)srcaddr; // Unused
7705 for (s = m->DNSServers; s; s = s->next)
7706 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
7707 return(mDNSfalse);
7708 }
7709 #endif
7710
7711 struct UDPSocket_struct
7712 {
7713 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
7714 };
7715
7716 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
7717 {
7718 DNSQuestion *q;
7719 for (q = m->Questions; q; q=q->next)
7720 {
7721 if (!tcp && !q->LocalSocket) continue;
7722 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
7723 mDNSSameOpaque16(q->TargetQID, id) &&
7724 q->qtype == question->qtype &&
7725 q->qclass == question->qclass &&
7726 q->qnamehash == question->qnamehash &&
7727 SameDomainName(&q->qname, &question->qname))
7728 return(q);
7729 }
7730 return(mDNSNULL);
7731 }
7732
7733 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
7734 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
7735 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
7736 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
7737 {
7738 DNSQuestion *q;
7739 (void)id;
7740 (void)srcaddr;
7741
7742 for (q = m->Questions; q; q=q->next)
7743 {
7744 if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
7745 {
7746 if (!mDNSOpaque16IsZero(q->TargetQID))
7747 {
7748 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
7749
7750 if (mDNSSameOpaque16(q->TargetQID, id))
7751 {
7752 mDNSIPPort srcp;
7753 if (!tcp)
7754 {
7755 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
7756 }
7757 else
7758 {
7759 srcp = q->tcpSrcPort;
7760 }
7761 if (mDNSSameIPPort(srcp, port)) return(q);
7762
7763 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
7764 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
7765 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
7766 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
7767 q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
7768 return(mDNSNULL);
7769 }
7770 }
7771 else
7772 {
7773 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
7774 return(q);
7775 }
7776 }
7777 }
7778 return(mDNSNULL);
7779 }
7780
7781 // Return a pointer to the primary service name, skipping subtype name if present.
7782 mDNSlocal const domainname *getPrimaryServiceName(const domainname *domainName)
7783 {
7784 const domainname *primaryName = domainName;
7785 const domainname *subName = SkipLeadingLabels(domainName, 1);
7786
7787 if (SameDomainLabel(subName->c, (const mDNSu8 *)mDNSSubTypeLabel))
7788 {
7789 // skip "<sub type name>._sub" portion of name
7790 primaryName = SkipLeadingLabels(domainName, 2);
7791 debugf("getPrimaryServiceName: returning %##s for _sub type", primaryName);
7792 }
7793
7794 return primaryName;
7795 }
7796
7797 // This function is not called if the packet is from us, which implies that we accept all multicast packets coming from us.
7798 mDNSlocal mDNSBool ExpectingMulticastResponseForRecord(mDNS *const m, CacheRecord *rr, const mDNSAddr *srcaddr, mDNSBool recordAccepted,
7799 CacheRecord **McastNSEC3Records)
7800 {
7801 DNSQuestion *q;
7802
7803 // Accept A and AAAA if we accepted something before in the same packet as most likely related to the
7804 // service records that we may have accepted.
7805 if (recordAccepted && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA))
7806 {
7807 LogInfo("ExpectingMulticastResponseForRecord:A:AAAA: accepting %s, from %#a due to same packet %d", CRDisplayString(m, rr), srcaddr, m->PktNum);
7808 return mDNStrue;
7809 }
7810 for (q = m->Questions; q; q=q->next)
7811 {
7812 if (!q->DuplicateOf && mDNSOpaque16IsZero(q->TargetQID))
7813 {
7814 mDNSBool ret;
7815 // 1. If a resource record answers question, cache it. This also will cache NSECs if it asserts
7816 // non-existence of q->qtype. If we have any matching NSEC3 Records for the question, send
7817 // it along with the resource record. Do it only for questions that are expecting to
7818 // discover only its peers (q->AnonInfo not NULL)
7819 if (q->AnonInfo && McastNSEC3Records && !rr->resrec.AnonInfo)
7820 {
7821 InitializeAnonInfoForCR(m, McastNSEC3Records, rr);
7822 }
7823 ret = ResourceRecordAnswersQuestion(&rr->resrec, q);
7824 if (ret)
7825 {
7826 // The record and the question belong to the same subset. Set the
7827 // anonymous data in the cache record.
7828 if (q->AnonInfo && rr->resrec.AnonInfo)
7829 {
7830 SetAnonData(q, &rr->resrec, mDNSfalse);
7831 }
7832 LogInfo("ExpectingMulticastResponseForRecord: Name and Type match, accepting %s, from %#a", CRDisplayString(m, rr), srcaddr);
7833 if (rr->resrec.rrtype == kDNSType_NSEC)
7834 LogInfo("ExpectingMulticastResponseForRecord: record %s, question %##s (%s)", CRDisplayString(m, rr), q->qname.c, DNSTypeName(q->qtype));
7835 return mDNStrue;
7836 }
7837 if (rr->resrec.rrtype == kDNSType_SRV || rr->resrec.rrtype == kDNSType_TXT)
7838 {
7839 // Point to the service type in the record name
7840 const domainname *name = SkipLeadingLabels(rr->resrec.name, 1);
7841
7842 // If question is for a sub type, just compare against the primary service type
7843 const domainname *primaryName = getPrimaryServiceName(&q->qname);
7844
7845 // 2. If the SRV or TXT record matches the service name, then cache it. If the TXT or SRV record is
7846 // before the PTR record in the packet, PTR record may not be in the cache yet and hence the logic
7847 // in (3) below will fail to cache it.
7848 if (q->qtype == kDNSType_PTR && name && SameDomainName(primaryName, name))
7849 {
7850 LogInfo("ExpectingMulticastResponseForRecord: Accepting %s due to PTR match, question %##s from %#a, pktnum %d",
7851 CRDisplayString(m, rr), q->qname.c, srcaddr, m->PktNum);
7852 return mDNStrue;
7853 }
7854
7855 if (name)
7856 {
7857 const mDNSu32 slot = HashSlot(name);
7858 const mDNSu32 namehash = DomainNameHashValue(name);
7859 CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
7860 CacheRecord *cr;
7861
7862 // 3. Same as in (2), but look in the cache in case we don't have the PTR question.
7863
7864 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7865 {
7866 if (cr->resrec.rrtype == kDNSType_PTR)
7867 {
7868 primaryName = getPrimaryServiceName(cr->resrec.name);
7869
7870 if (SameDomainName(primaryName, name))
7871 {
7872 LogInfo("ExpectingMulticastResponseForRecord: accepting %s, from %#a, pktnum %d",
7873 CRDisplayString(m, rr), srcaddr, m->PktNum);
7874 return mDNStrue;
7875 }
7876 }
7877 }
7878 }
7879 }
7880 }
7881 }
7882 debugf("ExpectingMulticastResponseForRecord: discarding %s, from %#a, pktnum %d", CRDisplayString(m, rr), srcaddr, m->PktNum);
7883 return(mDNSfalse);
7884 }
7885
7886 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
7887 // Currently this applies only to rdata types containing more than one domainname,
7888 // or types where the domainname is not the last item in the structure.
7889 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
7890 {
7891 switch (rr->rrtype)
7892 {
7893 case kDNSType_SOA: return sizeof(rdataSOA);
7894 case kDNSType_RP: return sizeof(rdataRP);
7895 case kDNSType_PX: return sizeof(rdataPX);
7896 default: return rr->rdlength;
7897 }
7898 }
7899
7900 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
7901 {
7902 CacheRecord *rr = mDNSNULL;
7903 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
7904
7905 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
7906
7907 //if (RDLength > InlineCacheRDSize)
7908 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
7909
7910 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
7911 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
7912 if (!rr) NoCacheAnswer(m, &m->rec.r);
7913 else
7914 {
7915 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
7916 *rr = m->rec.r; // Block copy the CacheRecord object
7917 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
7918 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
7919
7920 // We need to add the anonymous info before we call CacheRecordAdd so that
7921 // if it finds a matching question with this record, it bumps up the counters like
7922 // CurrentAnswers etc. Otherwise, when a cache entry gets removed, CacheRecordRmv
7923 // will complain.
7924 if (m->rec.r.resrec.AnonInfo)
7925 {
7926 rr->resrec.AnonInfo = m->rec.r.resrec.AnonInfo;
7927 m->rec.r.resrec.AnonInfo = mDNSNULL;
7928 }
7929 rr->DelayDelivery = delay;
7930
7931 // If this is an oversized record with external storage allocated, copy rdata to external storage
7932 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
7933 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
7934 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
7935 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
7936 if (RDLength > InlineCacheRDSize)
7937 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
7938
7939 rr->next = mDNSNULL; // Clear 'next' pointer
7940 rr->nsec = mDNSNULL;
7941 rr->soa = mDNSNULL;
7942
7943 if (sourceAddress)
7944 rr->sourceAddress = *sourceAddress;
7945
7946 if (!rr->resrec.InterfaceID)
7947 {
7948 m->rrcache_totalused_unicast += rr->resrec.rdlength;
7949 if (DNSSECRecordType(rr->resrec.rrtype))
7950 BumpDNSSECStats(m, kStatsActionIncrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
7951 }
7952
7953 if (Add)
7954 {
7955 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
7956 cg->rrcache_tail = &(rr->next); // Advance tail pointer
7957 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
7958 }
7959 else
7960 {
7961 // Can't use the "cg->name" if we are not adding to the cache as the
7962 // CacheGroup may be released anytime if it is empty
7963 domainname *name = mDNSPlatformMemAllocate(DomainNameLength(cg->name));
7964 if (name)
7965 {
7966 AssignDomainName(name, cg->name);
7967 rr->resrec.name = name;
7968 }
7969 else
7970 {
7971 ReleaseCacheRecord(m, rr);
7972 NoCacheAnswer(m, &m->rec.r);
7973 rr = mDNSNULL;
7974 }
7975 }
7976 }
7977 return(rr);
7978 }
7979
7980 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
7981 {
7982 rr->TimeRcvd = m->timenow;
7983 rr->resrec.rroriginalttl = ttl;
7984 rr->UnansweredQueries = 0;
7985 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7986 rr->MPUnansweredQ = 0;
7987 rr->MPUnansweredKA = 0;
7988 rr->MPExpectingKA = mDNSfalse;
7989 #endif
7990 SetNextCacheCheckTimeForRecord(m, rr);
7991 }
7992
7993 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
7994 {
7995 CacheRecord *rr;
7996 const mDNSu32 slot = HashSlot(&q->qname);
7997 CacheGroup *cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
7998 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7999 if (rr->CRActiveQuestion == q)
8000 {
8001 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8002 RefreshCacheRecord(m, rr, lease);
8003 }
8004 }
8005
8006 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
8007 {
8008 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8009 else if (LLQType == uDNS_LLQ_Events)
8010 {
8011 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8012 if (ttl == 0xFFFFFFFF) ttl = 0;
8013 else ttl = kLLQ_DefLease;
8014 }
8015 else // else not LLQ (standard uDNS response)
8016 {
8017 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8018 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8019 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8020
8021 ttl = RRAdjustTTL(ttl);
8022
8023 // For mDNS, TTL zero means "delete this record"
8024 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8025 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8026 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8027 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8028 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8029 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8030 // (with the current code) result in the server having even less than three seconds to respond
8031 // before we deleted the record and reported a "remove" event to any active questions.
8032 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8033 // then things really break (e.g. we end up making a negative cache entry).
8034 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8035 if (ttl < 15) ttl = 15;
8036 }
8037
8038 return ttl;
8039 }
8040
8041 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8042 // in m->rec.
8043 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist, DNSQuestion *q, mDNSBool *nseclist)
8044 {
8045 CacheRecord *const newcr = &m->rec.r;
8046 ResourceRecord *rr = &newcr->resrec;
8047 const CacheRecord *cr;
8048
8049 *nseclist = mDNSfalse;
8050 for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8051 {
8052 domainname *target = GetRRDomainNameTarget(&cr->resrec);
8053 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8054 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8055 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8056 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8057 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8058
8059 if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8060 {
8061 LogInfo("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8062 return (mDNStrue);
8063 }
8064 }
8065
8066 // Either the question requires validation or we are validating a response with DNSSEC in which case
8067 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8068 // we receive NSECs for our query which does not match the qname and we need to cache in that case
8069 // too. nseclist is set if they have to be cached as part of the negative cache record.
8070 if (q && DNSSECQuestion(q))
8071 {
8072 mDNSBool same = SameDomainName(&q->qname, rr->name);
8073 if (same && (q->qtype == rr->rrtype || rr->rrtype == kDNSType_CNAME))
8074 {
8075 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q->qtype),
8076 CRDisplayString(m, newcr));
8077 return mDNStrue;
8078 }
8079 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
8080 // "nseclist" is set
8081 if (rr->rrtype == kDNSType_RRSIG)
8082 {
8083 RDataBody2 *const rdb = (RDataBody2 *)newcr->smallrdatastorage.data;
8084 rdataRRSig *rrsig = &rdb->rrsig;
8085 mDNSu16 typeCovered = swap16(rrsig->typeCovered);
8086
8087 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8088 // would match the qtype and they are cached normally as they are not used to prove the
8089 // non-existence of any name. In that case, it is like any other normal dnssec validation
8090 // and hence nseclist should not be set.
8091
8092 if (same && ((typeCovered == q->qtype) || (typeCovered == kDNSType_CNAME)))
8093 {
8094 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m, newcr),
8095 DNSTypeName(q->qtype));
8096 return mDNStrue;
8097 }
8098 else if (typeCovered == kDNSType_NSEC || typeCovered == kDNSType_NSEC3)
8099 {
8100 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m, newcr), DNSTypeName(typeCovered));
8101 *nseclist = mDNStrue;
8102 return mDNStrue;
8103 }
8104 else if (typeCovered == kDNSType_SOA)
8105 {
8106 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m, newcr));
8107 *nseclist = mDNStrue;
8108 return mDNStrue;
8109 }
8110 else return mDNSfalse;
8111 }
8112 if (rr->rrtype == kDNSType_NSEC)
8113 {
8114 if (!UNICAST_NSEC(rr))
8115 {
8116 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m, newcr));
8117 return mDNSfalse;
8118 }
8119 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m, newcr));
8120 *nseclist = mDNStrue;
8121 return mDNStrue;
8122 }
8123 if (rr->rrtype == kDNSType_SOA)
8124 {
8125 LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m, newcr));
8126 *nseclist = mDNStrue;
8127 return mDNStrue;
8128 }
8129 else if (rr->rrtype == kDNSType_NSEC3)
8130 {
8131 LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m, newcr));
8132 *nseclist = mDNStrue;
8133 return mDNStrue;
8134 }
8135 }
8136 return mDNSfalse;
8137 }
8138
8139 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords)
8140 {
8141 CacheRecord *rp, *next;
8142
8143 for (rp = NSECRecords; rp; rp = next)
8144 {
8145 next = rp->next;
8146 ReleaseCacheRecord(m, rp);
8147 }
8148 }
8149
8150 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8151 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8152 mDNSlocal void mDNSCoreReceiveNoDNSSECAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8153 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID)
8154 {
8155 int i;
8156 const mDNSu8 *ptr = response->data;
8157
8158 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8159 {
8160 DNSQuestion pktq;
8161 DNSQuestion *qptr = mDNSNULL;
8162 ptr = getQuestion(response, ptr, end, InterfaceID, &pktq);
8163 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &pktq, !dstaddr)) &&
8164 qptr->ValidatingResponse)
8165 {
8166 DNSQuestion *next, *q;
8167
8168 if (qptr->DuplicateOf)
8169 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr->qname.c, DNSTypeName(qptr->qtype));
8170
8171 // Be careful to call the callback for duplicate questions first and then the original
8172 // question. If we called the callback on the original question, it could stop and
8173 // a duplicate question would become the original question.
8174 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
8175 for (q = qptr->next ; q && q != m->NewQuestions; q = next)
8176 {
8177 next = q->next;
8178 if (q->DuplicateOf == qptr)
8179 {
8180 if (q->ValidatingResponse)
8181 LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q->qname.c, DNSTypeName(q->qtype));
8182 else
8183 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q->qname.c, DNSTypeName(q->qtype));
8184 if (q->QuestionCallback)
8185 q->QuestionCallback(m, q, mDNSNULL, QC_nodnssec);
8186 }
8187 }
8188 if (qptr->QuestionCallback)
8189 qptr->QuestionCallback(m, qptr, mDNSNULL, QC_nodnssec);
8190 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8191 }
8192 }
8193 }
8194
8195 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8196 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, uDNS_LLQType LLQType, mDNSu8 rcode, CacheRecord *NSECRecords)
8197 {
8198 int i;
8199 const mDNSu8 *ptr = response->data;
8200 CacheRecord *SOARecord = mDNSNULL;
8201
8202 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8203 {
8204 DNSQuestion q;
8205 DNSQuestion *qptr = mDNSNULL;
8206 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8207 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
8208 {
8209 CacheRecord *rr, *neg = mDNSNULL;
8210 mDNSu32 slot = HashSlot(&q.qname);
8211 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
8212 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8213 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
8214 {
8215 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8216 if (RRExpireTime(rr) - m->timenow > 0) break;
8217 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8218 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
8219 }
8220 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8221 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8222 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8223 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8224 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8225 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8226 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8227 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8228 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8229 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8230 //
8231 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8232 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8233 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8234 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8235 // do the appropriate thing. This negative response is also needed for appending new search domains.
8236 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8237 {
8238 if (!rr)
8239 {
8240 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8241 m->CurrentQuestion = qptr;
8242 // We are not creating a cache record in this case, we need to pass back
8243 // the error we got so that the proxy code can return the right one to
8244 // the application
8245 if (qptr->ProxyQuestion)
8246 qptr->responseFlags = response->h.flags;
8247 GenerateNegativeResponse(m, QC_forceresponse);
8248 m->CurrentQuestion = mDNSNULL;
8249 }
8250 else
8251 {
8252 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8253 }
8254 }
8255 else
8256 {
8257 if (!rr)
8258 {
8259 // We start off assuming a negative caching TTL of 60 seconds
8260 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8261 mDNSu32 negttl = 60;
8262 int repeat = 0;
8263 const domainname *name = &q.qname;
8264 mDNSu32 hash = q.qnamehash;
8265
8266 // Special case for our special Microsoft Active Directory "local SOA" check.
8267 // Some cheap home gateways don't include an SOA record in the authority section when
8268 // they send negative responses, so we don't know how long to cache the negative result.
8269 // Because we don't want to keep hitting the root name servers with our query to find
8270 // if we're on a network using Microsoft Active Directory using "local" as a private
8271 // internal top-level domain, we make sure to cache the negative result for at least one day.
8272 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8273
8274 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8275 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8276 {
8277 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8278 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8279 {
8280 const mDNSu32 s = HashSlot(m->rec.r.resrec.name);
8281 CacheGroup *cgSOA = CacheGroupForRecord(m, s, &m->rec.r.resrec);
8282 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8283 mDNSu32 ttl_s = soa->min;
8284 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8285 // for the SOA record for ".", where the record is reported as non-cacheable
8286 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8287 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8288 ttl_s = m->rec.r.resrec.rroriginalttl;
8289 if (negttl < ttl_s) negttl = ttl_s;
8290
8291 // Create the SOA record as we may have to return this to the questions
8292 // that we are acting as a proxy for currently or in the future.
8293 SOARecord = CreateNewCacheEntry(m, s, cgSOA, 1, mDNSfalse, mDNSNULL);
8294
8295 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8296 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8297 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8298 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8299 //
8300 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8301 // along with the negative cache record. For simplicity, we don't create the additional records.
8302 if (!qptr->ProxyQuestion && q.qtype == kDNSType_SOA)
8303 {
8304 int qcount = CountLabels(&q.qname);
8305 int scount = CountLabels(m->rec.r.resrec.name);
8306 if (qcount - 1 > scount)
8307 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8308 repeat = qcount - 1 - scount;
8309 }
8310 }
8311 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8312 }
8313
8314 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8315 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8316 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8317 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8318 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8319 // so that we back off our polling rate and don't keep hitting the server continually.
8320 if (neg)
8321 {
8322 if (negttl < neg->resrec.rroriginalttl * 2)
8323 negttl = neg->resrec.rroriginalttl * 2;
8324 if (negttl > 3600)
8325 negttl = 3600;
8326 }
8327
8328 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
8329
8330 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8331 if (neg)
8332 {
8333 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8334 RefreshCacheRecord(m, neg, negttl);
8335 // When we created the cache for the first time and answered the question, the question's
8336 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8337 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8338 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8339 // we should reset its question interval here to MaxQuestionInterval.
8340 ResetQuestionState(m, qptr);
8341 if (DNSSECQuestion(qptr))
8342 neg->CRDNSSECQuestion = 1;
8343 // Update the NSEC records again.
8344 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8345 if (NSECRecords)
8346 {
8347 if (!AddNSECSForCacheRecord(m, NSECRecords, neg, rcode))
8348 {
8349 // We might just have an SOA record for zones that are not signed and hence don't log
8350 // this as an error
8351 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s during refresh", CRDisplayString(m, neg));
8352 FreeNSECRecords(m, NSECRecords);
8353 neg->CRDNSSECQuestion = 0;
8354 }
8355 NSECRecords = mDNSNULL;
8356 }
8357 if (SOARecord)
8358 {
8359 if (neg->soa)
8360 ReleaseCacheRecord(m, neg->soa);
8361 neg->soa = SOARecord;
8362 SOARecord = mDNSNULL;
8363 }
8364 }
8365 else while (1)
8366 {
8367 CacheRecord *negcr;
8368 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8369 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8370 m->rec.r.responseFlags = response->h.flags;
8371 // We create SOA records above which might create new cache groups. Earlier
8372 // in the function we looked up the cache group for the name and it could have
8373 // been NULL. If we pass NULL cg to new cache entries that we create below,
8374 // it will create additional cache groups for the same name. To avoid that,
8375 // look up the cache group again to re-initialize cg again.
8376 cg = CacheGroupForName(m, slot, hash, name);
8377 if (NSECRecords && DNSSECQuestion(qptr))
8378 {
8379 // Create the cache entry with delay and then add the NSEC records
8380 // to it and add it immediately.
8381 negcr = CreateNewCacheEntry(m, slot, cg, 1, mDNStrue, mDNSNULL);
8382 if (negcr)
8383 {
8384 negcr->CRDNSSECQuestion = 0;
8385 if (!AddNSECSForCacheRecord(m, NSECRecords, negcr, rcode))
8386 {
8387 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s",
8388 CRDisplayString(m, negcr));
8389 FreeNSECRecords(m, NSECRecords);
8390 }
8391 else
8392 {
8393 negcr->CRDNSSECQuestion = 1;
8394 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for %s", CRDisplayString(m, negcr));
8395 }
8396 NSECRecords = mDNSNULL;
8397 negcr->DelayDelivery = 0;
8398 CacheRecordDeferredAdd(m, negcr);
8399 }
8400 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8401 break;
8402 }
8403 else
8404 {
8405 // Need to add with a delay so that we can tag the SOA record
8406 negcr = CreateNewCacheEntry(m, slot, cg, 1, mDNStrue, mDNSNULL);
8407 if (negcr)
8408 {
8409 negcr->CRDNSSECQuestion = 0;
8410 if (DNSSECQuestion(qptr))
8411 negcr->CRDNSSECQuestion = 1;
8412 negcr->DelayDelivery = 0;
8413
8414 if (SOARecord)
8415 {
8416 if (negcr->soa)
8417 ReleaseCacheRecord(m, negcr->soa);
8418 negcr->soa = SOARecord;
8419 SOARecord = mDNSNULL;
8420 }
8421 CacheRecordDeferredAdd(m, negcr);
8422 }
8423 }
8424 m->rec.r.responseFlags = zeroID;
8425 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8426 if (!repeat) break;
8427 repeat--;
8428 name = (const domainname *)(name->c + 1 + name->c[0]);
8429 hash = DomainNameHashValue(name);
8430 slot = HashSlot(name);
8431 cg = CacheGroupForName(m, slot, hash, name);
8432 }
8433 }
8434 }
8435 }
8436 }
8437 if (NSECRecords) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used"); FreeNSECRecords(m, NSECRecords); }
8438 if (SOARecord) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: SOARecord not used"); ReleaseCacheRecord(m, SOARecord); }
8439 }
8440
8441 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8442 {
8443 AuthRecord *rrPtr = mDNSNULL;
8444 LogSPS("Stored Proxy records :");
8445 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8446 {
8447 LogSPS("%s", ARDisplayString(m, rrPtr));
8448 }
8449 }
8450
8451 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8452 {
8453 AuthRecord *rrPtr = mDNSNULL;
8454
8455 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8456 {
8457 if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8458 {
8459 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8460 return mDNStrue;
8461 }
8462 }
8463 mDNSCorePrintStoredProxyRecords(m);
8464 return mDNSfalse;
8465 }
8466
8467 mDNSlocal CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8468 const mDNSu32 slot, CacheGroup *cg, DNSQuestion *unicastQuestion, CacheRecord ***cfp, CacheRecord **NSECCachePtr,
8469 mDNSInterfaceID InterfaceID)
8470 {
8471 CacheRecord *rr;
8472 CacheRecord **cflocal = *cfp;
8473
8474 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8475 {
8476 mDNSBool match;
8477 // Resource record received via unicast, the resGroupID should match ?
8478 if (!InterfaceID)
8479 {
8480 mDNSu16 id1 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
8481 mDNSu16 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8482 match = (id1 == id2);
8483 }
8484 else
8485 match = (rr->resrec.InterfaceID == InterfaceID);
8486 // If we found this exact resource record, refresh its TTL
8487 if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
8488 {
8489 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8490 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8491 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8492
8493 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8494 {
8495 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8496 if (rr->NextInCFList == mDNSNULL && *cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
8497 {
8498 *cflocal = rr;
8499 cflocal = &rr->NextInCFList;
8500 *cflocal = (CacheRecord*)1;
8501 *cfp = &rr->NextInCFList;
8502 }
8503
8504 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8505 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8506 {
8507 DNSQuestion *q;
8508 for (q = m->Questions; q; q=q->next)
8509 {
8510 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
8511 q->UniqueAnswers++;
8512 }
8513 rr->resrec.RecordType = m->rec.r.resrec.RecordType;
8514 }
8515 }
8516
8517 if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
8518 {
8519 // If the rdata of the packet record differs in name capitalization from the record in our cache
8520 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8521 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8522 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8523 rr->resrec.rroriginalttl = 0;
8524 rr->TimeRcvd = m->timenow;
8525 rr->UnansweredQueries = MaxUnansweredQueries;
8526 SetNextCacheCheckTimeForRecord(m, rr);
8527 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: %s", CRDisplayString(m, rr));
8528 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: %s", CRDisplayString(m, &m->rec.r));
8529 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8530 NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8531 // DO NOT break out here -- we want to continue as if we never found it
8532 }
8533 else if (!IdenticalAnonInfo(m->rec.r.resrec.AnonInfo, rr->resrec.AnonInfo))
8534 {
8535 // If the NSEC3 record changed, a few possibilities
8536 //
8537 // 1) the peer reinitialized e.g., after network change and still part of the
8538 // same set.
8539 // 2) the peer went to a different set but we did not see the goodbyes. If we just
8540 // update the nsec3 record, it would be incorrect. Flush the cache so that we
8541 // can deliver a RMV followed by ADD.
8542 // 3) if the peer is ourselves and we see the goodbye when moving to a different set
8543 // and so we flush the cache and create a new cache record with the new set information.
8544 // Now we move back to the original set. In this case, we can't just update the
8545 // NSEC3 record alone. We need to flush so that we can deliver an RMV followed by ADD
8546 // when we create the new cache entry.
8547 //
8548 // Note: For case (1), we could avoid flushing the cache but we can't tell the difference
8549 // from the other cases.
8550 rr->resrec.rroriginalttl = 0;
8551 rr->TimeRcvd = m->timenow;
8552 rr->UnansweredQueries = MaxUnansweredQueries;
8553 SetNextCacheCheckTimeForRecord(m, rr);
8554 LogInfo("mDNSCoreReceiveCacheCheck: AnonInfo changed for %s", CRDisplayString(m, rr));
8555 // DO NOT break out here -- we want to continue as if we never found it. When we return
8556 // from this function, we will create a new cache entry with the new NSEC3 record
8557 }
8558 else if (m->rec.r.resrec.rroriginalttl > 0)
8559 {
8560 DNSQuestion *q;
8561
8562 m->mDNSStats.CacheRefreshed++;
8563
8564 if (rr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, rr));
8565 RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
8566 rr->responseFlags = response->h.flags;
8567
8568 // If we may have NSEC records returned with the answer (which we don't know yet as it
8569 // has not been processed), we need to cache them along with the first cache
8570 // record in the list that answers the question so that it can be used for validation
8571 // later. The "type" check below is to make sure that we cache on the cache record
8572 // that would answer the question. It is possible that we might cache additional things
8573 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8574 // the record that answers the question.
8575 if (response->h.numAnswers && unicastQuestion && unicastQuestion->qtype == rr->resrec.rrtype
8576 && !(*NSECCachePtr))
8577 {
8578 LogInfo("mDNSCoreReceiveCacheCheck: rescuing RR %s", CRDisplayString(m, rr));
8579 *NSECCachePtr = rr;
8580 }
8581 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8582 // polling the network once we get a valid response back. For the first time when a new
8583 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8584 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8585 // configuration changed, without flushing the cache, we reset the question interval here.
8586 // Currently, we do this for for both multicast and unicast questions as long as the record
8587 // type is unique. For unicast, resource record is always unique and for multicast it is
8588 // true for records like A etc. but not for PTR.
8589 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8590 {
8591 for (q = m->Questions; q; q=q->next)
8592 {
8593 if (!q->DuplicateOf && !q->LongLived &&
8594 ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
8595 {
8596 ResetQuestionState(m, q);
8597 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8598 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8599 }
8600 }
8601 }
8602 break;
8603 }
8604 else
8605 {
8606
8607 // If the packet TTL is zero, that means we're deleting this record.
8608 // To give other hosts on the network a chance to protest, we push the deletion
8609 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8610 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8611 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8612 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8613 // If the record is already going to expire in less than one second anyway, we leave it alone --
8614 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8615 debugf("DE for %s", CRDisplayString(m, rr));
8616 if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
8617 {
8618 rr->resrec.rroriginalttl = 1;
8619 rr->TimeRcvd = m->timenow;
8620 rr->UnansweredQueries = MaxUnansweredQueries;
8621 SetNextCacheCheckTimeForRecord(m, rr);
8622 }
8623 break;
8624 }
8625 }
8626 }
8627 return rr;
8628 }
8629
8630 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8631 const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records)
8632 {
8633 const mDNSu8 *ptr = response->data;
8634 CacheRecord *rr;
8635 int i;
8636
8637 if (!response->h.numAuthorities)
8638 return;
8639 ptr = LocateAuthorities(response, end);
8640 if (!ptr)
8641 {
8642 LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8643 return;
8644 }
8645 for (i = 0; i < response->h.numAuthorities && ptr && ptr < end; i++)
8646 {
8647 mDNSu32 slot;
8648 CacheGroup *cg;
8649
8650 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8651 if (!ptr || m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative || m->rec.r.resrec.rrtype != kDNSType_NSEC3)
8652 {
8653 debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr, CRDisplayString(m, &m->rec.r));
8654 m->rec.r.resrec.RecordType = 0;
8655 continue;
8656 }
8657 slot = HashSlot(m->rec.r.resrec.name);
8658 cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
8659 // Create the cache entry but don't add it to the cache it. We need
8660 // to cache this along with the main cache record.
8661 rr = CreateNewCacheEntry(m, slot, cg, 0, mDNSfalse, mDNSNULL);
8662 if (rr)
8663 {
8664 debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m, rr));
8665 *NSEC3Records = rr;
8666 NSEC3Records = &rr->next;
8667 }
8668 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8669 }
8670 }
8671
8672 mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
8673 {
8674 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8675 if (m->rec.r.resrec.AnonInfo)
8676 {
8677 FreeAnonInfo(m->rec.r.resrec.AnonInfo);
8678 m->rec.r.resrec.AnonInfo = mDNSNULL;
8679 }
8680 }
8681
8682 #define DEVICE_INFO_RECORD_LABELS 4
8683
8684 // Determine if the record is an instance of _device-info._tcp.local.
8685 mDNSlocal mDNSBool IsDeviceInfoRecord(const domainname *d)
8686 {
8687 const domainname *afterInstance;
8688
8689 if (CountLabels(d) != DEVICE_INFO_RECORD_LABELS)
8690 return mDNSfalse;
8691
8692 // skip the instance name
8693 afterInstance = SkipLeadingLabels(d, 1);
8694 if (SameDomainName(afterInstance, &LocalDeviceInfoName))
8695 return mDNStrue;
8696
8697 return mDNSfalse;
8698 }
8699
8700 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8701 // the record list and/or question list.
8702 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8703 // InterfaceID non-NULL tells us the interface this multicast response was received on
8704 // InterfaceID NULL tells us this was a unicast response
8705 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8706 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
8707 const DNSMessage *const response, const mDNSu8 *end,
8708 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8709 const mDNSInterfaceID InterfaceID)
8710 {
8711 int i;
8712 mDNSBool myself;
8713 mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
8714 mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, &myself);
8715 DNSQuestion *llqMatch = mDNSNULL;
8716 DNSQuestion *unicastQuestion = mDNSNULL;
8717 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
8718
8719 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8720 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8721 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8722 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
8723 CacheRecord **cfp = &CacheFlushRecords;
8724 CacheRecord *NSECRecords = mDNSNULL;
8725 CacheRecord *NSECCachePtr = mDNSNULL;
8726 CacheRecord **nsecp = &NSECRecords;
8727 CacheRecord *McastNSEC3Records = mDNSNULL;
8728 mDNSBool nseclist;
8729 mDNSu8 rcode = '\0';
8730 mDNSBool rrsigsCreated = mDNSfalse;
8731 mDNSBool DNSSECQuestion = mDNSfalse;
8732 mDNSBool recordAccepted = mDNSfalse;
8733 NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
8734
8735 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8736 // to guard against spoof responses, then the only credible protection against that is cryptographic
8737 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
8738 int firstauthority = response->h.numAnswers;
8739 int firstadditional = firstauthority + response->h.numAuthorities;
8740 int totalrecords = firstadditional + response->h.numAdditionals;
8741 const mDNSu8 *ptr = response->data;
8742 DNSServer *uDNSServer = mDNSNULL;
8743
8744 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8745 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8746 srcaddr, dstaddr, InterfaceID,
8747 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
8748 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
8749 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
8750 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
8751
8752 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8753 // When a DNS client receives a reply with TC
8754 // set, it should ignore that response, and query again, using a
8755 // mechanism, such as a TCP connection, that will permit larger replies.
8756 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8757 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8758 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8759 // <rdar://problem/6690034> Can't bind to Active Directory
8760 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8761 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8762 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
8763 // and not even do the TCP query.
8764 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
8765 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC)) return;
8766
8767 if (LLQType == uDNS_LLQ_Ignore) return;
8768
8769 // 1. We ignore questions (if any) in mDNS response packets
8770 // 2. If this is an LLQ response, we handle it much the same
8771 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
8772 // answer as being the authoritative complete RRSet, and respond by deleting all other
8773 // matching cache records that don't appear in this packet.
8774 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
8775 if (ResponseMCast || LLQType == uDNS_LLQ_Events || (response->h.flags.b[0] & kDNSFlag0_TC))
8776 ptr = LocateAnswers(response, end);
8777 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
8778 // in this response packet are immediately deemed to be invalid.
8779 else
8780 {
8781 mDNSBool failure, returnEarly;
8782 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
8783 failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
8784 returnEarly = mDNSfalse;
8785 // We could possibly combine this with the similar loop at the end of this function --
8786 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
8787 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
8788 // which it was received (or refreshed), and then at the end if we find any cache records which
8789 // answer questions in this packet's question section, but which aren't tagged with this packet's
8790 // packet number, then we deduce they are old and delete them
8791 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8792 {
8793 DNSQuestion q, *qptr = mDNSNULL;
8794 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8795 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
8796 {
8797 if (!failure)
8798 {
8799 CacheRecord *rr;
8800 // Remember the unicast question that we found, which we use to make caching
8801 // decisions later on in this function
8802 const mDNSu32 slot = HashSlot(&q.qname);
8803 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
8804 if (!mDNSOpaque16IsZero(response->h.id))
8805 {
8806 unicastQuestion = qptr;
8807 if (qptr->qDNSServer && DNSSECQuestion(qptr))
8808 {
8809 LogInfo("mDNSCoreReceiveResponse: Setting aware for %##s (%s) on %#a", qptr->qname.c,
8810 DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr);
8811 qptr->qDNSServer->DNSSECAware = mDNStrue;
8812 qptr->qDNSServer->req_DO = mDNStrue;
8813 }
8814 if (qptr->ValidatingResponse)
8815 DNSSECQuestion = mDNStrue;
8816 }
8817 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8818 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
8819 {
8820 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
8821 rr->resrec.InterfaceID, CRDisplayString(m, rr));
8822 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
8823 rr->TimeRcvd = m->timenow - TicksTTL(rr) - 1;
8824 rr->UnansweredQueries = MaxUnansweredQueries;
8825 rr->CRDNSSECQuestion = 0;
8826 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
8827 {
8828 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for record %s, question %##s (%s)", CRDisplayString(m, rr),
8829 unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
8830 rr->CRDNSSECQuestion = 1;
8831 }
8832 }
8833 }
8834 else
8835 {
8836 if (qptr)
8837 {
8838 // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
8839 // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
8840 // req_DO to false here, the next retransmission for this question will turn off validation
8841 // and hence retransmit without the EDNS0/DOK option.
8842 if (DNSSECOptionalQuestion(qptr) && qptr->qDNSServer && !qptr->qDNSServer->DNSSECAware)
8843 {
8844 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query %##s (%s), clear DO flag",
8845 qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
8846 qptr->qDNSServer->req_DO = mDNSfalse;
8847 }
8848 // For Unicast DNS Queries, penalize the DNSServer
8849 else
8850 {
8851 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)",
8852 qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
8853 PenalizeDNSServer(m, qptr, response->h.flags);
8854 }
8855 }
8856 returnEarly = mDNStrue;
8857 }
8858 }
8859 }
8860 if (returnEarly)
8861 {
8862 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
8863 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
8864 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
8865 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
8866 // not goto exit because we won't have any CacheFlushRecords and we do not want to
8867 // generate negative cache entries (we want to query the next server)
8868 return;
8869 }
8870 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
8871 {
8872 BumpDNSSECStats(m, kStatsActionSet, kStatsTypeMsgSize, (end - response->data));
8873 }
8874 }
8875
8876 // Parse the NSEC3 records from the Authority section before we process
8877 // the Answer section so that we can cache them along with the proper
8878 // cache records we create.
8879 if (mDNSOpaque16IsZero(response->h.id))
8880 mDNSParseNSEC3Records(m, response, end, InterfaceID, &McastNSEC3Records);
8881
8882 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
8883 {
8884 // All responses sent via LL multicast are acceptable for caching
8885 // All responses received over our outbound TCP connections are acceptable for caching
8886 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType;
8887 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
8888 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
8889
8890 const mDNSu8 RecordType =
8891 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
8892 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
8893 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
8894 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
8895
8896 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
8897 {
8898 mDNSCoreResetRecord(m);
8899 continue;
8900 }
8901
8902 // We have already parsed the NSEC3 records and cached them approrpriately for
8903 // multicast responses.
8904 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype == kDNSType_NSEC3)
8905 {
8906 mDNSCoreResetRecord(m);
8907 continue;
8908 }
8909 // Don't want to cache OPT or TSIG pseudo-RRs
8910 if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
8911 {
8912 mDNSCoreResetRecord(m);
8913 continue;
8914 }
8915 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
8916 {
8917 const rdataOPT *opt;
8918 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
8919 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
8920 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
8921 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
8922 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
8923 {
8924 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
8925 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
8926 }
8927 mDNSCoreResetRecord(m);
8928 continue;
8929 }
8930 // if a CNAME record points to itself, then don't add it to the cache
8931 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
8932 {
8933 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
8934 mDNSCoreResetRecord(m);
8935 continue;
8936 }
8937
8938 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
8939 // In the case of active LLQs, we'll get remove events when the records actually do go away
8940 // In the case of polling LLQs, we assume the record remains valid until the next poll
8941 if (!mDNSOpaque16IsZero(response->h.id))
8942 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
8943
8944 // If response was not sent via LL multicast,
8945 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
8946 if (!ResponseMCast)
8947 {
8948 if (LLQType)
8949 {
8950 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
8951 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
8952 // queries to get ADD/RMV events. To lookup the question, we can't use
8953 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
8954 // has already matched the question using the 64 bit Id in the packet and we use that here.
8955
8956 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
8957
8958 // If this is a DNSSEC question that is also LongLived, don't accept records from the
8959 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
8960 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
8961 // for both negative responses and wildcard expanded positive responses as both of come
8962 // back with NSEC/NSEC3s.
8963 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
8964 AcceptableResponse = mDNSfalse;
8965 }
8966 else if (!AcceptableResponse || !dstaddr)
8967 {
8968 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
8969 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
8970 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
8971 // we create.
8972
8973 if (!mDNSOpaque16IsZero(response->h.id))
8974 {
8975 DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
8976
8977 // Initialize the DNS server on the resource record which will now filter what questions we answer with
8978 // this record.
8979 //
8980 // We could potentially lookup the DNS server based on the source address, but that may not work always
8981 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
8982 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
8983 // on the "id" and "source port", then this response answers the question and assume the response
8984 // came from the same DNS server that we sent the query to.
8985
8986 if (q != mDNSNULL)
8987 {
8988 AcceptableResponse = mDNStrue;
8989 if (!InterfaceID)
8990 {
8991 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
8992 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
8993 }
8994 else
8995 LogInfo("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
8996 }
8997 else
8998 {
8999 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9000 // the question. The code below does that. So, make this record unacceptable for now
9001 if (!InterfaceID)
9002 {
9003 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9004 AcceptableResponse = mDNSfalse;
9005 }
9006 }
9007 }
9008 else if (ExpectingMulticastResponseForRecord(m, &m->rec.r, srcaddr, recordAccepted, &McastNSEC3Records))
9009 {
9010 recordAccepted = mDNStrue;
9011 AcceptableResponse = mDNStrue;
9012 LogInfo("mDNSCoreReceiveResponse: Accepting record in response to QU question %s, InterfaceID %p", CRDisplayString(m, &m->rec.r),
9013 InterfaceID);
9014 }
9015 else if (IsDeviceInfoRecord(m->rec.r.resrec.name))
9016 {
9017 recordAccepted = mDNStrue;
9018 AcceptableResponse = mDNStrue;
9019 LogInfo("mDNSCoreReceiveResponse: Accepting _device-info record %s, InterfaceID %p",
9020 CRDisplayString(m, &m->rec.r), InterfaceID);
9021 }
9022 }
9023 }
9024 else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9025 {
9026 CacheRecord *const rr = &m->rec.r;
9027 RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9028
9029 // If we are supposed to ignore link-local addresses on this interface, drop
9030 // all "A" records that have link-local address in them.
9031 if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9032 {
9033 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9034 mDNSCoreResetRecord(m);
9035 continue;
9036 }
9037 }
9038
9039 // 1. Check that this packet resource record does not conflict with any of ours
9040 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9041 {
9042 if (m->CurrentRecord)
9043 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9044 m->CurrentRecord = m->ResourceRecords;
9045 while (m->CurrentRecord)
9046 {
9047 AuthRecord *rr = m->CurrentRecord;
9048 m->CurrentRecord = rr->next;
9049 // We accept all multicast responses, and unicast responses resulting from queries we issued
9050 // For other unicast responses, this code accepts them only for responses with an
9051 // (apparently) local source address that pertain to a record of our own that's in probing state
9052 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9053
9054 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
9055 {
9056 // ... check to see if type and rdata are identical
9057 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9058 {
9059 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9060 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9061 {
9062 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9063 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9064 }
9065 else
9066 {
9067 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
9068 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9069 }
9070 }
9071 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9072 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9073 {
9074 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
9075 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9076
9077 // If this record is marked DependentOn another record for conflict detection purposes,
9078 // then *that* record has to be bumped back to probing state to resolve the conflict
9079 if (rr->DependentOn)
9080 {
9081 while (rr->DependentOn) rr = rr->DependentOn;
9082 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9083 }
9084
9085 // If we've just whacked this record's ProbeCount, don't need to do it again
9086 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9087 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9088 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9089 LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9090 else
9091 {
9092 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9093 // If we'd previously verified this record, put it back to probing state and try again
9094 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9095 {
9096 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9097 rr->resrec.RecordType = kDNSRecordTypeUnique;
9098 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9099 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9100 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9101 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9102 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
9103 rr->AnnounceCount = InitialAnnounceCount;
9104 InitializeLastAPTime(m, rr);
9105 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
9106 }
9107 // If we're probing for this record, we just failed
9108 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9109 {
9110 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9111 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9112 {
9113 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
9114
9115 m->mDNSStats.NameConflicts++;
9116 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9117 }
9118 }
9119 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9120 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9121 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9122 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9123 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9124 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9125 {
9126 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9127 m->mDNSStats.KnownUniqueNameConflicts++;
9128 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9129 }
9130 else
9131 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9132 }
9133 }
9134 // Else, matching signature, different type or rdata, but not a considered a conflict.
9135 // If the packet record has the cache-flush bit set, then we check to see if we
9136 // have any record(s) of the same type that we should re-assert to rescue them
9137 // (see note about "multi-homing and bridged networks" at the end of this function).
9138 else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
9139 if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
9140 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9141 }
9142 }
9143 }
9144
9145 nseclist = mDNSfalse;
9146 if (!AcceptableResponse)
9147 {
9148 AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords, unicastQuestion, &nseclist);
9149 if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9150 }
9151
9152 // 2. See if we want to add this packet resource record to our cache
9153 // We only try to cache answers if we have a cache to put them in
9154 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9155 if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
9156 if (m->rrcache_size && AcceptableResponse)
9157 {
9158 const mDNSu32 slot = HashSlot(m->rec.r.resrec.name);
9159 CacheGroup *cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
9160 CacheRecord *rr = mDNSNULL;
9161
9162 if (McastNSEC3Records)
9163 InitializeAnonInfoForCR(m, &McastNSEC3Records, &m->rec.r);
9164
9165 // 2a. Check if this packet resource record is already in our cache.
9166 //
9167 // If this record should go in the nseclist, don't look in the cache for updating it.
9168 // They are supposed to be cached under the "nsec" field of the cache record for
9169 // validation. Just create the cache record.
9170 if (!nseclist)
9171 {
9172 rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, unicastQuestion, &cfp, &NSECCachePtr, InterfaceID);
9173 }
9174
9175 // If mDNSOppCaching is set (which affects only multicast), enable opportunistic caching in which case we cache
9176 // everything that was received over multicast. Otherwise, we are selective about the caching.
9177 //
9178 // Cache everything that is from ourselves (that's how we answer any questions looking for them). Otherwise call
9179 // ExpectingMulticastResponseForRecord which decides whether to cache this record or not.
9180 //
9181 if (!m->mDNSOppCaching && !rr && !myself && mDNSOpaque16IsZero(response->h.id))
9182 {
9183 if (!ExpectingMulticastResponseForRecord(m, &m->rec.r, srcaddr, recordAccepted, &McastNSEC3Records))
9184 {
9185 //LogMsg("mDNSCoreReceiveResponse: discarding %s", CRDisplayString(m, &m->rec.r));
9186 mDNSCoreResetRecord(m);
9187 continue;
9188 }
9189 else
9190 {
9191 recordAccepted = mDNStrue;
9192 }
9193 }
9194
9195
9196 // If packet resource record not in our cache, add it now
9197 // (unless it is just a deletion of a record we never had, in which case we don't care)
9198 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9199 {
9200 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9201 mDNSs32 delay;
9202
9203 if (AddToCFList)
9204 delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9205 else
9206 delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash, slot, mDNSNULL);
9207
9208 // If unique, assume we may have to delay delivery of this 'add' event.
9209 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9210 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9211 // to schedule an mDNS_Execute task at the appropriate time.
9212 rr = CreateNewCacheEntry(m, slot, cg, delay, !nseclist, srcaddr);
9213 if (rr)
9214 {
9215 rr->responseFlags = response->h.flags;
9216 // If we are not creating signatures, then we need to inform DNSSEC so that
9217 // it does not wait forever. Don't do this if we got NSEC records
9218 // as it indicates that this name does not exist.
9219 if (rr->resrec.rrtype == kDNSType_RRSIG && !nseclist)
9220 {
9221 rrsigsCreated = mDNStrue;
9222 }
9223 // Remember whether we created a cache record in response to a DNSSEC question.
9224 // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9225 rr->CRDNSSECQuestion = 0;
9226 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9227 {
9228 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record %s, question %##s (%s)", CRDisplayString(m, rr),
9229 unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
9230 rr->CRDNSSECQuestion = 1;
9231 }
9232 // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9233 // which we should be creating below. It is also needed in the wildcard
9234 // expanded answer case and in that case it is cached along with the answer.
9235 if (nseclist)
9236 {
9237 rr->TimeRcvd = m->timenow;
9238 *nsecp = rr;
9239 nsecp = &rr->next;
9240 }
9241 else if (AddToCFList)
9242 {
9243 *cfp = rr;
9244 cfp = &rr->NextInCFList;
9245 *cfp = (CacheRecord*)1;
9246 }
9247 else if (rr->DelayDelivery)
9248 {
9249 ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9250 }
9251 }
9252 }
9253 else
9254 {
9255 if (rr && rr->resrec.AnonInfo && m->rec.r.resrec.AnonInfo)
9256 {
9257 CopyAnonInfoForCR(m, rr, &m->rec.r);
9258 }
9259 }
9260 }
9261 mDNSCoreResetRecord(m);
9262 }
9263
9264 exit:
9265 mDNSCoreResetRecord(m);
9266
9267 // If we've just received one or more records with their cache flush bits set,
9268 // then scan that cache slot to see if there are any old stale records we need to flush
9269 while (CacheFlushRecords != (CacheRecord*)1)
9270 {
9271 CacheRecord *r1 = CacheFlushRecords, *r2;
9272 const mDNSu32 slot = HashSlot(r1->resrec.name);
9273 const CacheGroup *cg = CacheGroupForRecord(m, slot, &r1->resrec);
9274 CacheFlushRecords = CacheFlushRecords->NextInCFList;
9275 r1->NextInCFList = mDNSNULL;
9276
9277 // Look for records in the cache with the same signature as this new one with the cache flush
9278 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9279 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9280 // We make these TTL adjustments *only* for records that still have *more* than one second
9281 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9282 // (and now has half a second remaining) could inadvertently get its life extended, by either
9283 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9284 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9285 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9286 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9287 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9288 // To avoid this, we need to ensure that the cache flushing operation will only act to
9289 // *decrease* a record's remaining lifetime, never *increase* it.
9290 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9291 {
9292 mDNSu16 id1;
9293 mDNSu16 id2;
9294 if (!r1->resrec.InterfaceID)
9295 {
9296 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9297 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9298 }
9299 else
9300 {
9301 id1 = id2 = 0;
9302 }
9303 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9304 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9305 // the new RRSIG that we received. Process only if the typeCovered matches.
9306 if ((r1->resrec.rrtype == r2->resrec.rrtype) && (r1->resrec.rrtype == kDNSType_RRSIG))
9307 {
9308 rdataRRSig *rrsig1 = (rdataRRSig *)(((RDataBody2 *)(r1->resrec.rdata->u.data))->data);
9309 rdataRRSig *rrsig2 = (rdataRRSig *)(((RDataBody2 *)(r2->resrec.rdata->u.data))->data);
9310 if (swap16(rrsig1->typeCovered) != swap16(rrsig2->typeCovered))
9311 {
9312 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9313 DNSTypeName(swap16(rrsig1->typeCovered)), DNSTypeName(swap16(rrsig2->typeCovered)));
9314 continue;
9315 }
9316 }
9317
9318 // For Unicast (null InterfaceID) the resolver IDs should also match
9319 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9320 (r1->resrec.InterfaceID || (id1 == id2)) &&
9321 r1->resrec.rrtype == r2->resrec.rrtype &&
9322 r1->resrec.rrclass == r2->resrec.rrclass)
9323 {
9324 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9325 // else, if record is old, mark it to be flushed
9326 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9327 {
9328 // If we find mismatched TTLs in an RRSet, correct them.
9329 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9330 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9331 // which we treat as a goodbye followed by an addition) and in that case it would be
9332 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9333 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9334 // because certain early Bonjour devices are known to have this specific mismatch, and
9335 // there's no point filling syslog with messages about something we already know about.
9336 // We also don't log this for uDNS responses, since a caching name server is obliged
9337 // to give us an aged TTL to correct for how long it has held the record,
9338 // so our received TTLs are expected to vary in that case
9339 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9340 {
9341 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9342 mDNSOpaque16IsZero(response->h.id))
9343 LogInfo("Correcting TTL from %4d to %4d for %s",
9344 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9345 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9346 }
9347 r2->TimeRcvd = m->timenow;
9348 }
9349 else // else, if record is old, mark it to be flushed
9350 {
9351 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9352 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9353 // We set stale records to expire in one second.
9354 // This gives the owner a chance to rescue it if necessary.
9355 // This is important in the case of multi-homing and bridged networks:
9356 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9357 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9358 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9359 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9360 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9361 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9362
9363 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9364 // final expiration queries for this record.
9365
9366 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9367 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9368 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9369 // <rdar://problem/5636422> Updating TXT records is too slow
9370 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9371 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9372 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9373 {
9374 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9375 r2->resrec.rroriginalttl = 0;
9376 }
9377 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9378 {
9379 // We only set a record to expire in one second if it currently has *more* than a second to live
9380 // If it's already due to expire in a second or less, we just leave it alone
9381 r2->resrec.rroriginalttl = 1;
9382 r2->UnansweredQueries = MaxUnansweredQueries;
9383 r2->TimeRcvd = m->timenow - 1;
9384 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9385 // that we marked for deletion via an explicit DE record
9386 }
9387 }
9388 SetNextCacheCheckTimeForRecord(m, r2);
9389 }
9390 }
9391
9392 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
9393 {
9394 // If we had a unicast question for this response with at least one positive answer and we
9395 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9396 // signatures along with the cache record which will be used for validation later. If
9397 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9398 // use that instead.
9399 if (response->h.numAnswers && unicastQuestion && NSECRecords)
9400 {
9401 if (!NSECCachePtr)
9402 {
9403 LogInfo("mDNSCoreReceiveResponse: Updating NSECCachePtr to %s", CRDisplayString(m, r1));
9404 NSECCachePtr = r1;
9405 }
9406 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9407 // might start the verification process which needs these NSEC records
9408 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9409 {
9410 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9411 FreeNSECRecords(m, NSECRecords);
9412 }
9413 NSECRecords = mDNSNULL;
9414 NSECCachePtr = mDNSNULL;
9415 }
9416 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash, slot, mDNSNULL);
9417 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9418 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9419 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9420 }
9421 }
9422
9423 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9424 // update them now for future validations.
9425 if (NSECRecords && NSECCachePtr)
9426 {
9427 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m, NSECCachePtr));
9428 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9429 {
9430 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9431 FreeNSECRecords(m, NSECRecords);
9432 }
9433 NSECRecords = mDNSNULL;
9434 NSECCachePtr = mDNSNULL;
9435 }
9436
9437 // If there is at least one answer and we did not create RRSIGs and there was a
9438 // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9439 // were created. We don't need to give a hint:
9440 //
9441 // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9442 // generate a negative response
9443 //
9444 // - if we have NSECRecords, it means we might have a potential proof for
9445 // non-existence of name that we are looking for
9446 //
9447 if (response->h.numAnswers && !rrsigsCreated && DNSSECQuestion && !NSECRecords)
9448 mDNSCoreReceiveNoDNSSECAnswers(m, response, end, dstaddr, dstport, InterfaceID);
9449
9450 // See if we need to generate negative cache entries for unanswered unicast questions
9451 mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, LLQType, rcode, NSECRecords);
9452
9453 if (McastNSEC3Records)
9454 {
9455 debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9456 FreeNSECRecords(m, McastNSEC3Records);
9457 }
9458 }
9459
9460 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9461 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9462 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9463 // that warrants waking the sleeping host.
9464 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9465
9466 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9467 {
9468 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9469 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9470 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9471 // simple, we use the same mechanism for both lists.
9472 if (!e->l[0])
9473 {
9474 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9475 return;
9476 }
9477 m->CurrentRecord = thelist;
9478 while (m->CurrentRecord)
9479 {
9480 AuthRecord *const rr = m->CurrentRecord;
9481 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9482 {
9483 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9484 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9485 }
9486 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9487 m->CurrentRecord = rr->next;
9488 }
9489 }
9490
9491 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9492 {
9493 if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9494 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9495 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9496 }
9497
9498 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9499 {
9500 if (result && result != mStatus_MemFree)
9501 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9502
9503 if (result == mStatus_NameConflict)
9504 {
9505 mDNS_Lock(m);
9506 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9507 if (ar->WakeUp.HMAC.l[0])
9508 {
9509 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password); // Send one wakeup magic packet
9510 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken
9511 }
9512 mDNS_Unlock(m);
9513 }
9514
9515 if (result == mStatus_NameConflict || result == mStatus_MemFree)
9516 {
9517 m->ProxyRecords--;
9518 mDNSPlatformMemFree(ar);
9519 mDNS_UpdateAllowSleep(m);
9520 }
9521 }
9522
9523 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9524 {
9525 int i;
9526 mDNSs8 hval = 0;
9527 int colons = 0;
9528 mDNSu8 val = 0;
9529
9530 for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9531 {
9532 hval = HexVal(*ptr);
9533 if (hval != -1)
9534 {
9535 val <<= 4;
9536 val |= hval;
9537 }
9538 else if (*ptr == ':')
9539 {
9540 eth->b[colons] = val;
9541 colons++;
9542 val = 0;
9543 }
9544 }
9545 if (colons != 5)
9546 {
9547 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9548 return mDNSNULL;
9549 }
9550 eth->b[colons] = val;
9551 return ptr;
9552 }
9553
9554 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9555 {
9556 int hval;
9557 int value;
9558 int numBytes;
9559 int digitsProcessed;
9560 int zeroFillStart;
9561 int numColons;
9562 mDNSu8 v6addr[16];
9563
9564 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9565 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9566 //
9567 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9568 // the result in "v6"
9569
9570 numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9571 while (ptr < limit && *ptr != ' ')
9572 {
9573 hval = HexVal(*ptr);
9574 if (hval != -1)
9575 {
9576 value <<= 4;
9577 value |= hval;
9578 digitsProcessed = 1;
9579 }
9580 else if (*ptr == ':')
9581 {
9582 if (!digitsProcessed)
9583 {
9584 // If we have already seen a "::", we should not see one more. Handle the special
9585 // case of "::"
9586 if (numColons)
9587 {
9588 // if we never filled any bytes and the next character is space (we have reached the end)
9589 // we are done
9590 if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
9591 {
9592 mDNSPlatformMemZero(v6->b, 16);
9593 return ptr + 1;
9594 }
9595 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
9596 return mDNSNULL;
9597 }
9598
9599 // We processed "::". We need to fill zeroes later. For now, mark the
9600 // point where we will start filling zeroes from.
9601 zeroFillStart = numBytes;
9602 numColons++;
9603 }
9604 else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
9605 {
9606 // We have a trailing ":" i.e., no more characters after ":"
9607 LogMsg("GetValueForIPv6Addr: Trailing colon");
9608 return mDNSNULL;
9609 }
9610 else
9611 {
9612 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9613 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9614 // filled here is 12 and 13.
9615 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
9616
9617 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9618 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9619 digitsProcessed = value = 0;
9620
9621 // Make sure that we did not fill the 13th and 14th byte above
9622 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
9623 }
9624 }
9625 ptr++;
9626 }
9627
9628 // We should be processing the last set of bytes following the last ":" here
9629 if (!digitsProcessed)
9630 {
9631 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
9632 return mDNSNULL;
9633 }
9634
9635 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
9636 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9637 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9638
9639 if (zeroFillStart)
9640 {
9641 int i, j, n;
9642 for (i = 0; i < zeroFillStart; i++)
9643 v6->b[i] = v6addr[i];
9644 for (j = i, n = 0; n < 16 - numBytes; j++, n++)
9645 v6->b[j] = 0;
9646 for (; j < 16; i++, j++)
9647 v6->b[j] = v6addr[i];
9648 }
9649 else if (numBytes == 16)
9650 mDNSPlatformMemCopy(v6->b, v6addr, 16);
9651 else
9652 {
9653 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
9654 return mDNSNULL;
9655 }
9656 return ptr;
9657 }
9658
9659 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
9660 {
9661 mDNSu32 val;
9662 int dots = 0;
9663 val = 0;
9664
9665 for ( ; ptr < limit && *ptr != ' '; ptr++)
9666 {
9667 if (*ptr >= '0' && *ptr <= '9')
9668 val = val * 10 + *ptr - '0';
9669 else if (*ptr == '.')
9670 {
9671 v4->b[dots++] = val;
9672 val = 0;
9673 }
9674 else
9675 {
9676 // We have a zero at the end and if we reached that, then we are done.
9677 if (*ptr == 0 && ptr == limit - 1 && dots == 3)
9678 {
9679 v4->b[dots] = val;
9680 return ptr + 1;
9681 }
9682 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
9683 }
9684 }
9685 if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
9686 v4->b[dots] = val;
9687 return ptr;
9688 }
9689
9690 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
9691 {
9692 mDNSu32 val;
9693
9694 val = 0;
9695 for ( ; ptr < limit && *ptr != ' '; ptr++)
9696 {
9697 if (*ptr < '0' || *ptr > '9')
9698 {
9699 // We have a zero at the end and if we reached that, then we are done.
9700 if (*ptr == 0 && ptr == limit - 1)
9701 {
9702 *value = val;
9703 return ptr + 1;
9704 }
9705 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
9706 }
9707 val = val * 10 + *ptr - '0';
9708 }
9709 *value = val;
9710 return ptr;
9711 }
9712
9713 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
9714 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
9715 {
9716 if (ar->resrec.rrtype != kDNSType_NULL)
9717 return;
9718
9719 if (mDNS_KeepaliveRecord(&ar->resrec))
9720 {
9721 int len = ar->resrec.rdlength;
9722 mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
9723 mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
9724 mDNSu32 value = 0;
9725
9726 while (ptr < limit)
9727 {
9728 mDNSu8 param = *ptr;
9729 ptr += 2; // Skip the letter and the "="
9730 if (param == 'h')
9731 {
9732 laddr->type = mDNSAddrType_IPv4;
9733 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
9734 }
9735 else if (param == 'd')
9736 {
9737 raddr->type = mDNSAddrType_IPv4;
9738 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
9739 }
9740 if (param == 'H')
9741 {
9742 laddr->type = mDNSAddrType_IPv6;
9743 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
9744 }
9745 else if (param == 'D')
9746 {
9747 raddr->type = mDNSAddrType_IPv6;
9748 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
9749 }
9750 else if (param == 'm')
9751 {
9752 ptr = GetValueForMACAddr(ptr, limit, eth);
9753 }
9754 else
9755 {
9756 ptr = GetValueForKeepalive(ptr, limit, &value);
9757 }
9758 if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
9759
9760 // Extract everything in network order so that it is easy for sending a keepalive and also
9761 // for matching incoming TCP packets
9762 switch (param)
9763 {
9764 case 't':
9765 *timeout = value;
9766 //if (*timeout < 120) *timeout = 120;
9767 break;
9768 case 'h':
9769 case 'H':
9770 case 'd':
9771 case 'D':
9772 case 'm':
9773 case 'i':
9774 case 'c':
9775 break;
9776 case 'l':
9777 lport->NotAnInteger = swap16((mDNSu16)value);
9778 break;
9779 case 'r':
9780 rport->NotAnInteger = swap16((mDNSu16)value);
9781 break;
9782 case 's':
9783 *seq = swap32(value);
9784 break;
9785 case 'a':
9786 *ack = swap32(value);
9787 break;
9788 case 'w':
9789 *win = swap16((mDNSu16)value);
9790 break;
9791 default:
9792 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
9793 ptr = limit;
9794 break;
9795 }
9796 ptr++; // skip the space
9797 }
9798 }
9799 }
9800
9801 // 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
9802 // the clients need not retrieve this information from the auth record again.
9803 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
9804 const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
9805 {
9806 AuthRecord *ar;
9807 mDNSAddr laddr, raddr;
9808 mDNSEthAddr eth;
9809 mDNSIPPort lport, rport;
9810 mDNSu32 timeout, seq, ack;
9811 mDNSu16 win;
9812
9813 for (ar = m->ResourceRecords; ar; ar=ar->next)
9814 {
9815 timeout = seq = ack = 0;
9816 win = 0;
9817 laddr = raddr = zeroAddr;
9818 lport = rport = zeroIPPort;
9819
9820 if (!ar->WakeUp.HMAC.l[0]) continue;
9821
9822 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9823
9824 // Did we parse correctly ?
9825 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
9826 {
9827 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
9828 continue;
9829 }
9830
9831 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
9832 &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
9833
9834 // Does it match the incoming TCP packet ?
9835 if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
9836 {
9837 // returning in network order
9838 *rseq = seq;
9839 *rack = ack;
9840 return ar;
9841 }
9842 }
9843 return mDNSNULL;
9844 }
9845
9846 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
9847 {
9848 AuthRecord *ar;
9849
9850 for (ar = m->ResourceRecords; ar; ar=ar->next)
9851 {
9852 mDNSu32 timeout, seq, ack;
9853 mDNSu16 win;
9854 mDNSAddr laddr, raddr;
9855 mDNSEthAddr eth;
9856 mDNSIPPort lport, rport;
9857
9858 timeout = seq = ack = 0;
9859 win = 0;
9860
9861 laddr = raddr = zeroAddr;
9862 lport = rport = zeroIPPort;
9863
9864 if (!ar->WakeUp.HMAC.l[0]) continue;
9865
9866 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9867
9868 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
9869 {
9870 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
9871 continue;
9872 }
9873 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
9874
9875 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
9876 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
9877 if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
9878 {
9879 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
9880 ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
9881 }
9882 if (m->NextScheduledKA - ar->KATimeExpire > 0)
9883 m->NextScheduledKA = ar->KATimeExpire;
9884 }
9885 }
9886
9887 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
9888 {
9889 if (ar != mDNSNULL)
9890 {
9891 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
9892 return;
9893 }
9894 mDNSu32 timeout, seq, ack;
9895 mDNSu16 win;
9896 mDNSAddr laddr, raddr;
9897 mDNSEthAddr eth;
9898 mDNSIPPort lport, rport;
9899
9900 timeout = seq = ack = 0;
9901 win = 0;
9902
9903 laddr = raddr = zeroAddr;
9904 lport = rport = zeroIPPort;
9905
9906 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9907
9908 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
9909 {
9910 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
9911 return;
9912 }
9913 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
9914 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
9915 }
9916
9917 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
9918 const DNSMessage *const msg, const mDNSu8 *end,
9919 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
9920 const mDNSInterfaceID InterfaceID)
9921 {
9922 int i;
9923 AuthRecord opt;
9924 mDNSu8 *p = m->omsg.data;
9925 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
9926 mDNSu32 updatelease = 0;
9927 const mDNSu8 *ptr;
9928
9929 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
9930 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
9931 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
9932 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
9933 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
9934 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
9935 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
9936
9937 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
9938
9939 if (mDNS_PacketLoggingEnabled)
9940 DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
9941
9942 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
9943 if (ptr)
9944 {
9945 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
9946 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
9947 {
9948 const rdataOPT *o;
9949 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
9950 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
9951 {
9952 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
9953 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
9954 }
9955 }
9956 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
9957 }
9958
9959 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
9960
9961 if (!updatelease || !owner.HMAC.l[0])
9962 {
9963 static int msgs = 0;
9964 if (msgs < 100)
9965 {
9966 msgs++;
9967 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
9968 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
9969 }
9970 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
9971 }
9972 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
9973 {
9974 static int msgs = 0;
9975 if (msgs < 100)
9976 {
9977 msgs++;
9978 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
9979 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
9980 }
9981 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
9982 }
9983 else
9984 {
9985 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
9986
9987 if (updatelease > 24 * 60 * 60)
9988 updatelease = 24 * 60 * 60;
9989
9990 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
9991 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
9992
9993 ptr = LocateAuthorities(msg, end);
9994
9995 // Clear any stale TCP keepalive records that may exist
9996 ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
9997 ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
9998
9999 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10000 {
10001 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10002 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10003 {
10004 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10005 AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10006 if (!ar)
10007 {
10008 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10009 break;
10010 }
10011 else
10012 {
10013 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10014 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10015 // All stale keepalive records have been flushed prior to this loop.
10016 if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10017 {
10018 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10019 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10020 }
10021 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10022 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10023 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10024 ar->resrec.rdata->MaxRDLength = RDLengthMem;
10025 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10026 ar->ForceMCast = mDNStrue;
10027 ar->WakeUp = owner;
10028 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10029 {
10030 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10031 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10032 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10033 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10034 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10035 }
10036 ar->TimeRcvd = m->timenow;
10037 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10038 if (m->NextScheduledSPS - ar->TimeExpire > 0)
10039 m->NextScheduledSPS = ar->TimeExpire;
10040 ar->KATimeExpire = 0;
10041 mDNS_Register_internal(m, ar);
10042
10043 m->ProxyRecords++;
10044 mDNS_UpdateAllowSleep(m);
10045 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10046 }
10047 }
10048 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10049 }
10050
10051 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10052 {
10053 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10054 ClearProxyRecords(m, &owner, m->DuplicateRecords);
10055 ClearProxyRecords(m, &owner, m->ResourceRecords);
10056 }
10057 else
10058 {
10059 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10060 opt.resrec.rrclass = NormalMaxDNSMessageData;
10061 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
10062 opt.resrec.rdestimate = sizeof(rdataOPT);
10063 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
10064 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10065 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10066 }
10067 }
10068
10069 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
10070 mDNS_SendKeepalives(m);
10071 }
10072
10073 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10074 {
10075 if (InterfaceID)
10076 {
10077 mDNSu32 updatelease = 60 * 60; // If SPS fails to indicate lease time, assume one hour
10078 const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
10079 if (ptr)
10080 {
10081 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10082 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10083 {
10084 const rdataOPT *o;
10085 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10086 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10087 if (o->opt == kDNSOpt_Lease)
10088 {
10089 updatelease = o->u.updatelease;
10090 LogSPS("Sleep Proxy granted lease time %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10091 }
10092 }
10093 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10094 }
10095
10096 if (m->CurrentRecord)
10097 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10098 m->CurrentRecord = m->ResourceRecords;
10099 while (m->CurrentRecord)
10100 {
10101 AuthRecord *const rr = m->CurrentRecord;
10102 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10103 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10104 {
10105 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10106 // Clear the updateid when we are done sending on all interfaces.
10107 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10108 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10109 bit_clr_opaque64(rr->updateIntID, scopeid);
10110 if (mDNSOpaque64IsZero(&rr->updateIntID))
10111 rr->updateid = zeroID;
10112 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10113 LogSPS("Sleep Proxy %s record %5d 0x%x 0x%x (%d) %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", updatelease, rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr));
10114 if (rr->WakeUp.HMAC.l[0])
10115 {
10116 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10117 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10118 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10119 }
10120 }
10121 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10122 // new records could have been added to the end of the list as a result of that call.
10123 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10124 m->CurrentRecord = rr->next;
10125 }
10126
10127 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10128 char *ifname = InterfaceNameForID(m, InterfaceID);
10129 mDNSAddr spsaddr;
10130 mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10131 mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10132 }
10133 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10134 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10135 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10136 }
10137
10138 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
10139 const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
10140 {
10141 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10142 {
10143 LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10144 #if ForceAlerts
10145 *(long*)0 = 0;
10146 #endif
10147 }
10148
10149 // Create empty resource record
10150 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
10151 cr->resrec.InterfaceID = InterfaceID;
10152 cr->resrec.rDNSServer = dnsserver;
10153 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10154 cr->resrec.rrtype = rrtype;
10155 cr->resrec.rrclass = rrclass;
10156 cr->resrec.rroriginalttl = ttl_seconds;
10157 cr->resrec.rdlength = 0;
10158 cr->resrec.rdestimate = 0;
10159 cr->resrec.namehash = namehash;
10160 cr->resrec.rdatahash = 0;
10161 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10162 cr->resrec.rdata->MaxRDLength = 0;
10163
10164 cr->NextInKAList = mDNSNULL;
10165 cr->TimeRcvd = m->timenow;
10166 cr->DelayDelivery = 0;
10167 cr->NextRequiredQuery = m->timenow;
10168 cr->LastUsed = m->timenow;
10169 cr->CRActiveQuestion = mDNSNULL;
10170 cr->UnansweredQueries = 0;
10171 cr->LastUnansweredTime = 0;
10172 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
10173 cr->MPUnansweredQ = 0;
10174 cr->MPLastUnansweredQT = 0;
10175 cr->MPUnansweredKA = 0;
10176 cr->MPExpectingKA = mDNSfalse;
10177 #endif
10178 cr->NextInCFList = mDNSNULL;
10179 cr->nsec = mDNSNULL;
10180 cr->soa = mDNSNULL;
10181 cr->CRDNSSECQuestion = 0;
10182 // Initialize to the basic one and the caller can set it to more
10183 // specific based on the response if any
10184 cr->responseFlags = ResponseFlags;
10185 }
10186
10187 mDNSexport void mDNSCoreReceive(mDNS *const m, void *const pkt, const mDNSu8 *const end,
10188 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10189 const mDNSInterfaceID InterfaceID)
10190 {
10191 mDNSInterfaceID ifid = InterfaceID;
10192 DNSMessage *msg = (DNSMessage *)pkt;
10193 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
10194 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10195 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
10196 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10197 mDNSu8 QR_OP;
10198 mDNSu8 *ptr = mDNSNULL;
10199 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10200 if (TLS) dstaddr = mDNSNULL;
10201
10202 #ifndef UNICAST_DISABLED
10203 if (mDNSSameAddress(srcaddr, &m->Router))
10204 {
10205 #ifdef _LEGACY_NAT_TRAVERSAL_
10206 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10207 {
10208 mDNS_Lock(m);
10209 LNT_ConfigureRouterInfo(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
10210 mDNS_Unlock(m);
10211 return;
10212 }
10213 #endif
10214 if (mDNSSameIPPort(srcport, NATPMPPort))
10215 {
10216 mDNS_Lock(m);
10217 uDNS_ReceiveNATPacket(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
10218 mDNS_Unlock(m);
10219 return;
10220 }
10221 }
10222 #ifdef _LEGACY_NAT_TRAVERSAL_
10223 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10224 #endif
10225
10226 #endif
10227 if ((unsigned)(end - (mDNSu8 *)pkt) < sizeof(DNSMessageHeader))
10228 {
10229 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt);
10230 return;
10231 }
10232 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10233 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10234 ptr = (mDNSu8 *)&msg->h.numQuestions;
10235 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10236 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10237 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10238 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10239
10240 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10241
10242 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10243 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10244 if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10245
10246 mDNS_Lock(m);
10247 m->PktNum++;
10248 if (mDNSOpaque16IsZero(msg->h.id))
10249 {
10250 m->MPktNum++;
10251 #if APPLE_OSX_mDNSResponder
10252 // Track the number of multicast packets received from a source outside our subnet.
10253 // Check the destination address to avoid accounting for spurious packets that
10254 // comes in with message id zero.
10255 if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, mDNSNULL) &&
10256 mDNSAddressIsAllDNSLinkGroup(dstaddr))
10257 {
10258 m->RemoteSubnet++;
10259 }
10260 #endif // #if APPLE_OSX_mDNSResponder
10261 }
10262
10263 #ifndef UNICAST_DISABLED
10264 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10265 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10266 {
10267 ifid = mDNSInterface_Any;
10268 if (mDNS_PacketLoggingEnabled)
10269 DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
10270 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10271 // Note: mDNSCore also needs to get access to received unicast responses
10272 }
10273 #endif
10274 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10275 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10276 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10277 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr, InterfaceID);
10278 else
10279 {
10280 LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10281 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt, InterfaceID);
10282 if (mDNS_LoggingEnabled)
10283 {
10284 int i = 0;
10285 while (i<end - (mDNSu8 *)pkt)
10286 {
10287 char buffer[128];
10288 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10289 do if (i<end - (mDNSu8 *)pkt) p += mDNS_snprintf(p, sizeof(buffer), " %02X", ((mDNSu8 *)pkt)[i]);while (++i & 15);
10290 LogInfo("%s", buffer);
10291 }
10292 }
10293 }
10294 // Packet reception often causes a change to the task list:
10295 // 1. Inbound queries can cause us to need to send responses
10296 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10297 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10298 // 4. Response packets that answer questions may cause our client to issue new questions
10299 mDNS_Unlock(m);
10300 }
10301
10302 // ***************************************************************************
10303 #if COMPILER_LIKES_PRAGMA_MARK
10304 #pragma mark -
10305 #pragma mark - Searcher Functions
10306 #endif
10307
10308 // Targets are considered the same if both queries are untargeted, or
10309 // if both are targeted to the same address+port
10310 // (If Target address is zero, TargetPort is undefined)
10311 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
10312 (mDNSSameAddress(& (A)->Target, & (B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
10313
10314 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10315 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10316 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10317 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10318 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10319 //
10320 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10321 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10322 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10323 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10324 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10325 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10326 // breaks this design principle.
10327 //
10328
10329 // If IsLLQ(Q) is true, it means the question is both:
10330 // (a) long-lived and
10331 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10332 // for multicast questions, we don't want to treat LongLived as anything special
10333 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10334
10335 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10336 {
10337 DNSQuestion *q;
10338 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10339 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10340 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10341 // further in the list.
10342 for (q = m->Questions; q && q != question; q=q->next) // Scan our list for another question
10343 if (q->InterfaceID == question->InterfaceID && // with the same InterfaceID,
10344 SameQTarget(q, question) && // and same unicast/multicast target settings
10345 q->qtype == question->qtype && // type,
10346 q->qclass == question->qclass && // class,
10347 IsLLQ(q) == IsLLQ(question) && // and long-lived status matches
10348 (!q->AuthInfo || question->AuthInfo) && // to avoid deadlock, don't make public query dup of a private one
10349 (q->AnonInfo == question->AnonInfo) && // Anonymous query not a dup of normal query
10350 (q->SuppressQuery == question->SuppressQuery) && // Questions that are suppressed/not suppressed
10351 (q->ValidationRequired == question->ValidationRequired) && // Questions that require DNSSEC validation
10352 (q->ValidatingResponse == question->ValidatingResponse) && // Questions that are validating responses using DNSSEC
10353 (q->DisallowPID == question->DisallowPID) && // Disallowing a PID should not affect a PID that is allowed
10354 (q->BrowseThreshold == question->BrowseThreshold) && // browse thresholds must match
10355 q->qnamehash == question->qnamehash &&
10356 SameDomainName(&q->qname, &question->qname)) // and name
10357 return(q);
10358 return(mDNSNULL);
10359 }
10360
10361 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10362 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10363 {
10364 DNSQuestion *q;
10365 DNSQuestion *first = mDNSNULL;
10366
10367 // This is referring to some other question as duplicate. No other question can refer to this
10368 // question as a duplicate.
10369 if (question->DuplicateOf)
10370 {
10371 LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
10372 question, question->qname.c, DNSTypeName(question->qtype),
10373 question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
10374 return;
10375 }
10376
10377 for (q = m->Questions; q; q=q->next) // Scan our list of questions
10378 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
10379 {
10380 q->DuplicateOf = first;
10381 if (!first)
10382 {
10383 first = q;
10384 // If q used to be a duplicate, but now is not,
10385 // then inherit the state from the question that's going away
10386 q->LastQTime = question->LastQTime;
10387 q->ThisQInterval = question->ThisQInterval;
10388 q->ExpectUnicastResp = question->ExpectUnicastResp;
10389 q->LastAnswerPktNum = question->LastAnswerPktNum;
10390 q->RecentAnswerPkts = question->RecentAnswerPkts;
10391 q->RequestUnicast = question->RequestUnicast;
10392 q->LastQTxTime = question->LastQTxTime;
10393 q->CNAMEReferrals = question->CNAMEReferrals;
10394 q->nta = question->nta;
10395 q->servAddr = question->servAddr;
10396 q->servPort = question->servPort;
10397 q->qDNSServer = question->qDNSServer;
10398 q->validDNSServers = question->validDNSServers;
10399 q->unansweredQueries = question->unansweredQueries;
10400 q->noServerResponse = question->noServerResponse;
10401 q->triedAllServersOnce = question->triedAllServersOnce;
10402
10403 q->TargetQID = question->TargetQID;
10404 if (q->LocalSocket)
10405 {
10406 mDNSPlatformUDPClose(q->LocalSocket);
10407 }
10408
10409 q->LocalSocket = question->LocalSocket;
10410
10411 q->state = question->state;
10412 // q->tcp = question->tcp;
10413 q->ReqLease = question->ReqLease;
10414 q->expire = question->expire;
10415 q->ntries = question->ntries;
10416 q->id = question->id;
10417
10418 question->LocalSocket = mDNSNULL;
10419 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
10420 // question->tcp = mDNSNULL;
10421
10422 if (q->LocalSocket)
10423 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10424
10425 if (q->nta)
10426 {
10427 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10428 q->nta->ZoneDataContext = q;
10429 }
10430
10431 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10432 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10433
10434 if (question->state == LLQ_Established)
10435 {
10436 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10437 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10438 }
10439
10440 SetNextQueryTime(m,q);
10441 }
10442 }
10443 }
10444
10445 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10446 {
10447 McastResolver **p = &m->McastResolvers;
10448 McastResolver *tmp = mDNSNULL;
10449
10450 if (!d) d = (const domainname *)"";
10451
10452 LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
10453
10454 mDNS_CheckLock(m);
10455
10456 while (*p) // Check if we already have this {interface, domain} tuple registered
10457 {
10458 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10459 {
10460 if (!((*p)->flags & DNSServer_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10461 (*p)->flags &= ~DNSServer_FlagDelete;
10462 tmp = *p;
10463 *p = tmp->next;
10464 tmp->next = mDNSNULL;
10465 }
10466 else
10467 p=&(*p)->next;
10468 }
10469
10470 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10471 else
10472 {
10473 // allocate, add to list
10474 *p = mDNSPlatformMemAllocate(sizeof(**p));
10475 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10476 else
10477 {
10478 (*p)->interface = interface;
10479 (*p)->flags = DNSServer_FlagNew;
10480 (*p)->timeout = timeout;
10481 AssignDomainName(&(*p)->domain, d);
10482 (*p)->next = mDNSNULL;
10483 }
10484 }
10485 return(*p);
10486 }
10487
10488 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10489 {
10490 mDNSs32 ptime = 0;
10491 if (server->penaltyTime != 0)
10492 {
10493 ptime = server->penaltyTime - m->timenow;
10494 if (ptime < 0)
10495 {
10496 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10497 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10498 // here
10499 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10500 ptime, server->penaltyTime, m->timenow);
10501 server->penaltyTime = 0;
10502 ptime = 0;
10503 }
10504 }
10505 return ptime;
10506 }
10507
10508 //Checks to see whether the newname is a better match for the name, given the best one we have
10509 //seen so far (given in bestcount).
10510 //Returns -1 if the newname is not a better match
10511 //Returns 0 if the newname is the same as the old match
10512 //Returns 1 if the newname is a better match
10513 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
10514 int bestcount)
10515 {
10516 // If the name contains fewer labels than the new server's domain or the new name
10517 // contains fewer labels than the current best, then it can't possibly be a better match
10518 if (namecount < newcount || newcount < bestcount) return -1;
10519
10520 // If there is no match, return -1 and the caller will skip this newname for
10521 // selection
10522 //
10523 // If we find a match and the number of labels is the same as bestcount, then
10524 // we return 0 so that the caller can do additional logic to pick one of
10525 // the best based on some other factors e.g., penaltyTime
10526 //
10527 // If we find a match and the number of labels is more than bestcount, then we
10528 // return 1 so that the caller can pick this over the old one.
10529 //
10530 // Note: newcount can either be equal or greater than bestcount beause of the
10531 // check above.
10532
10533 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
10534 return bestcount == newcount ? 0 : 1;
10535 else
10536 return -1;
10537 }
10538
10539 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10540 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10541 // names. In that case, we give a default timeout of 5 seconds
10542 #define DEFAULT_MCAST_TIMEOUT 5
10543 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
10544 {
10545 McastResolver *curmatch = mDNSNULL;
10546 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10547 McastResolver *curr;
10548 int bettermatch, currcount;
10549 for (curr = m->McastResolvers; curr; curr = curr->next)
10550 {
10551 currcount = CountLabels(&curr->domain);
10552 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10553 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10554 // the timeout value from the first one
10555 if (bettermatch == 1)
10556 {
10557 curmatch = curr;
10558 bestmatchlen = currcount;
10559 }
10560 }
10561 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
10562 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10563 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10564 }
10565
10566 // Returns true if it is a Domain Enumeration Query
10567 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
10568 {
10569 const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
10570 (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
10571 const domainname *d = qname;
10572 const mDNSu8 *label;
10573 int i = 0;
10574
10575 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10576 if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
10577
10578 label = (const mDNSu8 *)d;
10579 while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
10580 {
10581 if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
10582 i++;
10583 }
10584 if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
10585 {
10586 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
10587 return mDNSfalse;
10588 }
10589 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
10590
10591 // CountLabels already verified the number of labels
10592 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label
10593 label = (const mDNSu8 *)d;
10594 if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
10595 {
10596 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
10597 return(mDNSfalse);
10598 }
10599 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
10600
10601 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label
10602 label = (const mDNSu8 *)d;
10603 if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
10604 {
10605 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
10606 return(mDNSfalse);
10607 }
10608 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
10609
10610 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
10611
10612 return mDNStrue;
10613 }
10614
10615 // Note: InterfaceID is the InterfaceID of the question
10616 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
10617 {
10618 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
10619 // with "scoped" set to kScopeNone)
10620 //
10621 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
10622 // with "scoped" set to kScopeInterfaceId) and their InterfaceIDs should match.
10623 //
10624 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
10625 // with "scoped" set to kScopeServiceID) and their ServiceIDs should match.
10626 //
10627 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
10628 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
10629 //
10630 // If the first condition fails, following are the possible cases (the notes below are using
10631 // InterfaceID for discussion and the same holds good for ServiceID):
10632 //
10633 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
10634 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
10635 //
10636 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
10637 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
10638 // would fail in this case.
10639 //
10640 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
10641 // should match (Refer to (2) above).
10642 //
10643 // Note: mDNSInterface_Unicast is used only by .local unicast questions and are treated as unscoped.
10644 // If a question is scoped both to InterfaceID and ServiceID, the question will be scoped to InterfaceID.
10645
10646 if (((d->scoped == kScopeNone) && ((!InterfaceID && ServiceID == -1) || InterfaceID == mDNSInterface_Unicast)) ||
10647 ((d->scoped == kScopeInterfaceID) && d->interface == InterfaceID) ||
10648 ((d->scoped == kScopeServiceID) && d->serviceID == ServiceID))
10649 {
10650 return mDNStrue;
10651 }
10652 return mDNSfalse;
10653 }
10654
10655 // Sets all the Valid DNS servers for a question
10656 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
10657 {
10658 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10659 DNSServer *curr;
10660 int bettermatch, currcount;
10661 int index = 0;
10662 mDNSu32 timeout = 0;
10663 mDNSBool DEQuery;
10664
10665 question->validDNSServers = zeroOpaque64;
10666 DEQuery = DomainEnumQuery(&question->qname);
10667 for (curr = m->DNSServers; curr; curr = curr->next)
10668 {
10669 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
10670 // skip servers that will soon be deleted
10671 if (curr->flags & DNSServer_FlagDelete)
10672 {
10673 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
10674 continue;
10675 }
10676
10677 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
10678 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
10679 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
10680 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
10681 // match the scoped entries by mistake.
10682 //
10683 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
10684
10685 if (curr->scoped && curr->interface == mDNSInterface_Any)
10686 {
10687 debugf("SetValidDNSServers: Scoped DNS server %#a (Domain %##s) with Interface Any", &curr->addr, curr->domain.c);
10688 continue;
10689 }
10690
10691 currcount = CountLabels(&curr->domain);
10692 if ((!DEQuery || !curr->cellIntf) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
10693 {
10694 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10695
10696 // If we found a better match (bettermatch == 1) then clear all the bits
10697 // corresponding to the old DNSServers that we have may set before and start fresh.
10698 // If we find an equal match, then include that DNSServer also by setting the corresponding
10699 // bit
10700 if ((bettermatch == 1) || (bettermatch == 0))
10701 {
10702 bestmatchlen = currcount;
10703 if (bettermatch)
10704 {
10705 debugf("SetValidDNSServers: Resetting all the bits");
10706 question->validDNSServers = zeroOpaque64;
10707 timeout = 0;
10708 }
10709 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
10710 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
10711 curr->interface);
10712 timeout += curr->timeout;
10713 if (DEQuery)
10714 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->cellIntf);
10715 bit_set_opaque64(question->validDNSServers, index);
10716 }
10717 }
10718 index++;
10719 }
10720 question->noServerResponse = 0;
10721
10722 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
10723 question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
10724 // If there are no matching resolvers, then use the default timeout value.
10725 // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
10726 return ((question->ProxyQuestion || question->ValidatingResponse) ? DEFAULT_UDNSSEC_TIMEOUT : timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
10727 }
10728
10729 // Get the Best server that matches a name. If you find penalized servers, look for the one
10730 // that will come out of the penalty box soon
10731 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque64 validBits,
10732 int *selected, mDNSBool nameMatch)
10733 {
10734 DNSServer *curmatch = mDNSNULL;
10735 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
10736 DNSServer *curr;
10737 mDNSs32 bestPenaltyTime, currPenaltyTime;
10738 int bettermatch, currcount;
10739 int index = 0;
10740 int currindex = -1;
10741
10742 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
10743 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
10744 for (curr = m->DNSServers; curr; curr = curr->next)
10745 {
10746 // skip servers that will soon be deleted
10747 if (curr->flags & DNSServer_FlagDelete)
10748 {
10749 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
10750 continue;
10751 }
10752
10753 // Check if this is a valid DNSServer
10754 if (!bit_get_opaque64(validBits, index))
10755 {
10756 debugf("GetBestServer: continuing for index %d", index);
10757 index++;
10758 continue;
10759 }
10760
10761 currcount = CountLabels(&curr->domain);
10762 currPenaltyTime = PenaltyTimeForServer(m, curr);
10763
10764 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
10765 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
10766
10767 // If there are multiple best servers for a given question, we will pick the first one
10768 // if none of them are penalized. If some of them are penalized in that list, we pick
10769 // the least penalized one. BetterMatchForName walks through all best matches and
10770 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
10771 // in the list when there are no penalized servers and least one among them
10772 // when there are some penalized servers.
10773
10774 if (DNSServerMatch(curr, InterfaceID, ServiceID))
10775 {
10776
10777 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
10778 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
10779 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
10780 // part and still do some redundant steps e.g., InterfaceID match
10781
10782 if (nameMatch)
10783 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
10784 else
10785 bettermatch = 0;
10786
10787 // If we found a better match (bettermatch == 1) then we don't need to
10788 // compare penalty times. But if we found an equal match, then we compare
10789 // the penalty times to pick a better match
10790
10791 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
10792 {
10793 currindex = index;
10794 curmatch = curr;
10795 bestmatchlen = currcount;
10796 bestPenaltyTime = currPenaltyTime;
10797 }
10798 }
10799 index++;
10800 }
10801 if (selected) *selected = currindex;
10802 return curmatch;
10803 }
10804
10805 // Look up a DNS Server, matching by name and InterfaceID
10806 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
10807 {
10808 DNSServer *curmatch = mDNSNULL;
10809 char *ifname = mDNSNULL; // for logging purposes only
10810 mDNSOpaque64 allValid;
10811
10812 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
10813 InterfaceID = mDNSNULL;
10814
10815 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
10816
10817 // By passing in all ones, we make sure that every DNS server is considered
10818 allValid.l[0] = allValid.l[1] = 0xFFFFFFFF;
10819
10820 curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
10821
10822 if (curmatch != mDNSNULL)
10823 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
10824 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
10825 InterfaceID, name);
10826 else
10827 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
10828
10829 return(curmatch);
10830 }
10831
10832 // Look up a DNS Server for a question within its valid DNSServer bits
10833 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
10834 {
10835 DNSServer *curmatch = mDNSNULL;
10836 char *ifname = mDNSNULL; // for logging purposes only
10837 mDNSInterfaceID InterfaceID = question->InterfaceID;
10838 const domainname *name = &question->qname;
10839 int currindex;
10840
10841 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
10842 InterfaceID = mDNSNULL;
10843
10844 if (InterfaceID)
10845 ifname = InterfaceNameForID(m, InterfaceID);
10846
10847 if (!mDNSOpaque64IsZero(&question->validDNSServers))
10848 {
10849 curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
10850 if (currindex != -1)
10851 bit_clr_opaque64(question->validDNSServers, currindex);
10852 }
10853
10854 if (curmatch != mDNSNULL)
10855 {
10856 LogInfo("GetServerForQuestion: %p DNS server (%p) %#a:%d (Penalty Time Left %d) (Scope %s:%p:%d) found for name %##s (%s)",
10857 question, curmatch, &curmatch->addr, mDNSVal16(curmatch->port),
10858 (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
10859 InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
10860 }
10861 else
10862 {
10863 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p:%d) found for name %##s (%s)",
10864 question, ifname ? ifname : "None", InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
10865 }
10866
10867 return(curmatch);
10868 }
10869
10870
10871 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
10872 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
10873
10874 // Called in normal client context (lock not held)
10875 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
10876 {
10877 DNSQuestion *q;
10878 mDNS_Lock(m);
10879 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
10880 n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
10881 for (q = m->Questions; q; q=q->next)
10882 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
10883 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
10884 #if APPLE_OSX_mDNSResponder
10885 UpdateAutoTunnelDomainStatuses(m);
10886 #endif
10887 mDNS_Unlock(m);
10888 }
10889
10890 mDNSlocal mDNSBool IsPrivateDomain(mDNS *const m, DNSQuestion *q)
10891 {
10892 DomainAuthInfo *AuthInfo;
10893 // Skip Private domains as we have special addresses to get the hosts in the Private domain
10894 AuthInfo = GetAuthInfoForName_internal(m, &q->qname);
10895 if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
10896 {
10897 debugf("IsPrivateDomain: %##s true", q->qname.c);
10898 return mDNStrue;
10899 }
10900 else
10901 {
10902 debugf("IsPrivateDomain: %##s false", q->qname.c);
10903 return mDNSfalse;
10904 }
10905 }
10906
10907 // This function takes the DNSServer as a separate argument because sometimes the
10908 // caller has not yet assigned the DNSServer, but wants to evaluate the SuppressQuery
10909 // status before switching to it.
10910 mDNSlocal mDNSBool ShouldSuppressUnicastQuery(mDNS *const m, DNSQuestion *q, DNSServer *d)
10911 {
10912 // Some callers don't check for the qtype
10913 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
10914 {
10915 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
10916 return mDNSfalse;
10917 }
10918
10919 // Private domains are exempted irrespective of what the DNSServer says
10920 if (IsPrivateDomain(m, q))
10921 {
10922 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, Private Domain", q->qname.c, DNSTypeName(q->qtype));
10923 return mDNSfalse;
10924 }
10925
10926 if (!d)
10927 {
10928 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, as the DNS server is NULL", q->qname.c, DNSTypeName(q->qtype));
10929 return mDNStrue;
10930 }
10931
10932 // Check if the DNS Configuration allows A/AAAA queries to be sent
10933 if ((q->qtype == kDNSType_A) && (d->req_A))
10934 {
10935 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows A queries", q->qname.c,
10936 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
10937 return mDNSfalse;
10938 }
10939 if ((q->qtype == kDNSType_AAAA) && (d->req_AAAA))
10940 {
10941 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows AAAA queries", q->qname.c,
10942 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
10943 return mDNSfalse;
10944 }
10945
10946 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, since DNS Configuration does not allow (req_A is %s and req_AAAA is %s)",
10947 q->qname.c, DNSTypeName(q->qtype), d->req_A ? "true" : "false", d->req_AAAA ? "true" : "false");
10948
10949 return mDNStrue;
10950 }
10951
10952 mDNSlocal mDNSBool ShouldSuppressDotLocalQuery(mDNS *const m, DNSQuestion *q)
10953 {
10954 NetworkInterfaceInfo *intf;
10955 AuthRecord *rr;
10956 mDNSBool ret;
10957
10958 // Check to see if there is at least one interface other than loopback and don't suppress
10959 // .local questions if you find one. If we have at least one interface, it means that
10960 // we can send unicast queries for the .local name and we don't want to suppress
10961 // multicast in that case as upper layers don't know how to handle if we return a
10962 // negative response for multicast followed by a positive response for unicast.
10963 //
10964 // Note: we used to check for multicast capable interfaces instead of just any interface
10965 // present. That did not work in the case where we have a valid interface for unicast
10966 // but not multicast capable e.g., cellular, as we ended up delivering a negative response
10967 // first and the upper layer did not wait for the positive response that came later.
10968 for (intf = m->HostInterfaces; intf; intf = intf->next)
10969 {
10970 if (intf->InterfaceActive && !intf->Loopback)
10971 {
10972 LogInfo("ShouldSuppressDotLocalQuery: Found interface %s, not suppressing", intf->ifname);
10973 return mDNSfalse;
10974 }
10975 }
10976
10977 // 1. If we find a LocalOnly or P2P record answering this question, then don't suppress it.
10978 // Set m->CurrentQuestion as it is required by AnswerQuestionWithLORecord.
10979 m->CurrentQuestion = q;
10980 ret = AnswerQuestionWithLORecord(m, q, mDNStrue);
10981 m->CurrentQuestion = mDNSNULL;
10982
10983 if (ret)
10984 {
10985 LogInfo("ShouldSuppressDotLocalQuery: Found LocalOnly record for %##s (%s), not suppressing", q->qname.c,
10986 DNSTypeName(q->qtype));
10987 return mDNSfalse;
10988 }
10989
10990 // 2. If we find a local AuthRecord answering this question, then don't suppress it.
10991 for (rr = m->ResourceRecords; rr; rr = rr->next)
10992 {
10993 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
10994 {
10995 LogInfo("ShouldSuppressDotLocalQuery: Found resource record %s for %##s (%s) not suppressing", ARDisplayString(m, rr),
10996 q->qname.c, DNSTypeName(q->qtype));
10997 return mDNSfalse;
10998 }
10999 }
11000 return mDNStrue;
11001 }
11002
11003 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, DNSQuestion *q)
11004 {
11005 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
11006 {
11007 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
11008 return mDNSfalse;
11009 }
11010
11011 // We still want the ability to be able to listen to the local services and hence
11012 // don't fail .local query if we have local records that can potentially answer
11013 // the question.
11014 if (q->InterfaceID != mDNSInterface_Unicast && IsLocalDomain(&q->qname))
11015 {
11016 if (!ShouldSuppressDotLocalQuery(m, q))
11017 {
11018 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11019 return mDNSfalse;
11020 }
11021 else
11022 {
11023 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11024 return mDNStrue;
11025 }
11026 }
11027
11028 return (ShouldSuppressUnicastQuery(m, q, q->qDNSServer));
11029 }
11030
11031 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11032 {
11033 CacheRecord *rr;
11034 mDNSu32 slot;
11035 CacheGroup *cg;
11036
11037 slot = HashSlot(&q->qname);
11038 cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
11039 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
11040 {
11041 // Don't deliver RMV events for negative records
11042 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
11043 {
11044 LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
11045 CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
11046 continue;
11047 }
11048
11049 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
11050 {
11051 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11052 q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
11053
11054 q->CurrentAnswers--;
11055 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11056 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11057
11058 if (rr->CRActiveQuestion == q)
11059 {
11060 DNSQuestion *qptr;
11061 // If this was the active question for this cache entry, it was the one that was
11062 // responsible for keeping the cache entry fresh when the cache entry was reaching
11063 // its expiry. We need to handover the responsibility to someone else. Otherwise,
11064 // when the cache entry is about to expire, we won't find an active question
11065 // (pointed by CRActiveQuestion) to refresh the cache.
11066 for (qptr = m->Questions; qptr; qptr=qptr->next)
11067 if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
11068 break;
11069
11070 if (qptr)
11071 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
11072 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
11073 qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
11074
11075 rr->CRActiveQuestion = qptr; // Question used to be active; new value may or may not be null
11076 if (!qptr) m->rrcache_active--; // If no longer active, decrement rrcache_active count
11077 }
11078 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
11079 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
11080 }
11081 }
11082 }
11083
11084 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11085 {
11086 DNSQuestion *q;
11087 for (q = m->NewQuestions; q; q = q->next)
11088 if (q == question) return mDNStrue;
11089 return mDNSfalse;
11090 }
11091
11092 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11093 {
11094 AuthRecord *rr;
11095 mDNSu32 slot;
11096 AuthGroup *ag;
11097
11098 if (m->CurrentQuestion)
11099 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11100 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11101
11102 if (IsQuestionNew(m, q))
11103 {
11104 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11105 return mDNStrue;
11106 }
11107 m->CurrentQuestion = q;
11108 slot = AuthHashSlot(&q->qname);
11109 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
11110 if (ag)
11111 {
11112 for (rr = ag->members; rr; rr=rr->next)
11113 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11114 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11115 {
11116 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11117 ARDisplayString(m, rr));
11118 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11119 {
11120 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11121 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11122 q->CurrentAnswers, q->LOAddressAnswers);
11123 continue;
11124 }
11125 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again
11126 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11127 }
11128 }
11129 m->CurrentQuestion = mDNSNULL;
11130 return mDNStrue;
11131 }
11132
11133 // Returns false if the question got deleted while delivering the RMV events
11134 // The caller should handle the case
11135 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11136 {
11137 if (m->CurrentQuestion)
11138 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11139 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11140
11141 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11142 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11143 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11144 {
11145 m->CurrentQuestion = q;
11146 CacheRecordRmvEventsForCurrentQuestion(m, q);
11147 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11148 m->CurrentQuestion = mDNSNULL;
11149 }
11150 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11151 return mDNStrue;
11152 }
11153
11154 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11155 {
11156 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11157 // LOddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11158 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11159 if (q->SuppressQuery)
11160 {
11161 q->SuppressQuery = mDNSfalse;
11162 if (!CacheRecordRmvEventsForQuestion(m, q))
11163 {
11164 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from cache");
11165 return;
11166 }
11167 q->SuppressQuery = mDNStrue;
11168 }
11169
11170 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11171 // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
11172 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11173 // the restart will not be a duplicate ADD
11174 if (!LocalRecordRmvEventsForQuestion(m, q))
11175 {
11176 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords");
11177 return;
11178 }
11179
11180 // There are two cases here.
11181 //
11182 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11183 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11184 // because when we get the response, if we had entries in the cache already, it will not answer
11185 // this question if the cache entry did not change. Hence, we need to restart
11186 // the query so that it can be answered from the cache.
11187 //
11188 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11189 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11190 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
11191 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11192 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
11193 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11194 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11195 // This affects both efficiency and also the current design where there is only one active question
11196 // pointed to from a cache entry.
11197 //
11198 // We restart queries in a two step process by first calling stop and build a temporary list which we
11199 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11200 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11201 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11202 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11203 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11204 //
11205 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11206
11207 LogInfo("SuppressStatusChanged: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11208 mDNS_StopQuery_internal(m, q);
11209 q->next = *restart;
11210 *restart = q;
11211 }
11212
11213 // The caller should hold the lock
11214 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11215 {
11216 DNSQuestion *q;
11217 DNSQuestion *restart = mDNSNULL;
11218
11219 // We look through all questions including new questions. During network change events,
11220 // we potentially restart questions here in this function that ends up as new questions,
11221 // which may be suppressed at this instance. Before it is handled we get another network
11222 // event that changes the status e.g., address becomes available. If we did not process
11223 // new questions, we would never change its SuppressQuery status.
11224 //
11225 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11226 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11227 // *any* other question which could be the next one that we may process here. RestartQuestion
11228 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11229 // if the "next" question is stopped while the CurrentQuestion is stopped
11230 if (m->RestartQuestion)
11231 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11232 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11233 m->RestartQuestion = m->Questions;
11234 while (m->RestartQuestion)
11235 {
11236 q = m->RestartQuestion;
11237 m->RestartQuestion = q->next;
11238 if (q->SuppressUnusable)
11239 {
11240 mDNSBool old = q->SuppressQuery;
11241 q->SuppressQuery = ShouldSuppressQuery(m, q);
11242 if (q->SuppressQuery != old)
11243 {
11244 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11245 // followed by a negative cache response. Temporarily turn off suppression so that
11246 // AnswerCurrentQuestionWithResourceRecord can answer the question
11247 SuppressStatusChanged(m, q, &restart);
11248 }
11249 }
11250 }
11251 while (restart)
11252 {
11253 q = restart;
11254 restart = restart->next;
11255 q->next = mDNSNULL;
11256 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11257 mDNS_StartQuery_internal(m, q);
11258 }
11259 }
11260
11261 mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11262 {
11263 DNSQuestion *q;
11264 DNSQuestion *restart = mDNSNULL;
11265
11266 if (m->RestartQuestion)
11267 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11268 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11269 m->RestartQuestion = m->Questions;
11270 while (m->RestartQuestion)
11271 {
11272 q = m->RestartQuestion;
11273 m->RestartQuestion = q->next;
11274 if (q->Restart)
11275 {
11276 if (mDNSOpaque16IsZero(q->TargetQID))
11277 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11278
11279 q->Restart = 0;
11280 SuppressStatusChanged(m, q, &restart);
11281 }
11282 }
11283 while (restart)
11284 {
11285 q = restart;
11286 restart = restart->next;
11287 q->next = mDNSNULL;
11288 LogInfo("RestartUnicastQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11289 mDNS_StartQuery_internal(m, q);
11290 }
11291 }
11292
11293
11294 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11295 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11296 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11297 {
11298
11299 if (question->Target.type && !ValidQuestionTarget(question))
11300 {
11301 LogMsg("ValidateParameters: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
11302 question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
11303 question->Target.type = mDNSAddrType_None;
11304 }
11305
11306 // If no question->Target specified, clear TargetPort
11307 if (!question->Target.type)
11308 question->TargetPort = zeroIPPort;
11309
11310 if (!ValidateDomainName(&question->qname))
11311 {
11312 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11313 return(mStatus_Invalid);
11314 }
11315
11316 // If this question is referencing a specific interface, verify it exists
11317 if (question->InterfaceID && question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_Unicast && question->InterfaceID != mDNSInterface_P2P)
11318 {
11319 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11320 if (!intf)
11321 LogMsg("ValidateParameters: Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
11322 question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
11323 }
11324
11325 return(mStatus_NoError);
11326 }
11327
11328 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11329 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeForQuestion()
11330 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11331 {
11332 // First reset all DNS Configuration
11333 question->qDNSServer = mDNSNULL;
11334 question->validDNSServers = zeroOpaque64;
11335 question->triedAllServersOnce = 0;
11336 question->noServerResponse = 0;
11337 question->StopTime = 0;
11338
11339 // Need not initialize the DNS Configuration for Local Only OR P2P Questions
11340 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
11341 return;
11342 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11343 if (!mDNSOpaque16IsZero(question->TargetQID))
11344 {
11345 mDNSu32 timeout = SetValidDNSServers(m, question);
11346 // We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
11347 // a networking change/search domain change that calls this function again we keep
11348 // reinitializing the timeout value which means it may never timeout. If this becomes
11349 // a common case in the future, we can easily fix this by adding extra state that
11350 // indicates that we have already set the StopTime.
11351 //
11352 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11353 // it gets a full timeout value even if the original question times out earlier.
11354 if (question->TimeoutQuestion)
11355 {
11356 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11357 LogInfo("InitDNSConfig: Setting StopTime on question %p %##s (%s)", question, question->qname.c, DNSTypeName(question->qtype));
11358 }
11359
11360 question->qDNSServer = GetServerForQuestion(m, question);
11361 LogInfo("InitDNSConfig: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
11362 question, question->qname.c, DNSTypeName(question->qtype), timeout,
11363 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11364 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11365 }
11366 else
11367 {
11368 if (question->TimeoutQuestion)
11369 question->StopTime = NonZeroTime(m->timenow + GetTimeoutForMcastQuestion(m, question) * mDNSPlatformOneSecond);
11370 }
11371 // Set StopTime here since it is a part of DNS Configuration
11372 if (question->StopTime)
11373 SetNextQueryStopTime(m, question);
11374 // SetNextQueryTime() need not be initialized for LocalOnly OR P2P Questions since those questions
11375 // will never be transmitted on the wire. Hence we call SetNextQueryTime() here.
11376 SetNextQueryTime(m,question);
11377 }
11378
11379 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11380 // state fields of the DNS Question. These are independent of the Client layer.
11381 mDNSlocal mDNSBool InitCommonState(mDNS *const m, DNSQuestion *const question)
11382 {
11383 mDNSBool purge;
11384 int i;
11385
11386 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11387 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11388 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11389 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11390 // that to go out immediately.
11391 question->next = mDNSNULL;
11392 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11393 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11394 // the question list to check if ThisQInterval is negative which means the question has been
11395 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11396 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11397 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11398 // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11399 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
11400 question->qnamehash = DomainNameHashValue(&question->qname);
11401 question->DelayAnswering = CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash, HashSlot(&question->qname), &purge);
11402 question->LastQTime = m->timenow;
11403 question->ExpectUnicastResp = 0;
11404 question->LastAnswerPktNum = m->PktNum;
11405 question->RecentAnswerPkts = 0;
11406 question->CurrentAnswers = 0;
11407
11408 #if APPLE_OSX_mDNSResponder
11409
11410 // Initial browse threshold used by Finder.
11411 #define mDNSFinderBrowseThreshold 20
11412
11413 // Set the threshold at which we move to a passive browse state,
11414 // not actively sending queries.
11415 if (question->flags & kDNSServiceFlagsThresholdOne)
11416 question->BrowseThreshold = 1;
11417 else if (question->flags & kDNSServiceFlagsThresholdFinder)
11418 question->BrowseThreshold = mDNSFinderBrowseThreshold;
11419 else
11420 question->BrowseThreshold = 0;
11421
11422 #else // APPLE_OSX_mDNSResponder
11423 question->BrowseThreshold = 0;
11424 #endif // APPLE_OSX_mDNSResponder
11425 question->CachedAnswerNeedsUpdate = mDNSfalse;
11426
11427 question->LargeAnswers = 0;
11428 question->UniqueAnswers = 0;
11429 question->LOAddressAnswers = 0;
11430 question->FlappingInterface1 = mDNSNULL;
11431 question->FlappingInterface2 = mDNSNULL;
11432
11433 question->ServiceID = mDNSPlatformGetServiceID(m, question);
11434
11435 InitDNSConfig(m, question);
11436
11437 question->AuthInfo = GetAuthInfoForQuestion(m, question);
11438 question->SuppressQuery = 0;
11439 if (question->SuppressUnusable)
11440 question->SuppressQuery = ShouldSuppressQuery(m, question);
11441
11442 // If ServiceID is 0 or the policy disallows making DNS requests,
11443 // set DisallowPID
11444 question->DisallowPID = (question->ServiceID == 0 || (mDNSPlatformAllowPID(m, question) == 0));
11445 if (question->DisallowPID)
11446 {
11447 LogInfo("InitCommonState: Query suppressed for %##s (%s), PID %d/ServiceID %d not allowed", question->qname.c,
11448 DNSTypeName(question->qtype), question->pid, question->ServiceID);
11449 }
11450
11451 question->NextInDQList = mDNSNULL;
11452 question->SendQNow = mDNSNULL;
11453 question->SendOnAll = mDNSfalse;
11454
11455 #if mDNS_REQUEST_UNICAST_RESPONSE
11456 question->RequestUnicast = SET_QU_IN_FIRST_FOUR_QUERIES;
11457 #else // mDNS_REQUEST_UNICAST_RESPONSE
11458 question->RequestUnicast = SET_QU_IN_FIRST_QUERY;
11459 #endif // mDNS_REQUEST_UNICAST_RESPONSE
11460
11461 #if APPLE_OSX_mDNSResponder
11462 // Request unicast response for first 4 queries to increase
11463 // reliability in an environment with high multicast packet loss.
11464 // Must set to one more than the number of unicast queries you want, since SendQueries()
11465 // decrements it before calling BuildQuestion() which acts on it.
11466 if (question->flags & kDNSServiceFlagsUnicastResponse)
11467 {
11468 question->RequestUnicast = SET_QU_IN_FIRST_FOUR_QUERIES;
11469 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11470 DNSTypeName(question->qtype));
11471 }
11472 else if (question->flags & kDNSServiceFlagsThresholdFinder)
11473 {
11474 // always send one request with QU bit set when kDNSServiceFlagsThresholdFinder is set
11475 #if mDNS_REQUEST_UNICAST_RESPONSE
11476 question->RequestUnicast = SET_QU_IN_FIRST_FOUR_QUERIES;
11477 #else // mDNS_REQUEST_UNICAST_RESPONSE
11478 question->RequestUnicast = SET_QU_IN_FIRST_QUERY;
11479 #endif // mDNS_REQUEST_UNICAST_RESPONSE
11480
11481 LogInfo("InitCommonState: kDNSServiceFlagsThresholdFinder set, setting RequestUnicast = %d for %##s (%s)",
11482 question->RequestUnicast, question->qname.c, DNSTypeName(question->qtype));
11483 }
11484 #endif // APPLE_OSX_mDNSResponder
11485
11486 question->LastQTxTime = m->timenow;
11487 question->CNAMEReferrals = 0;
11488
11489 question->WakeOnResolveCount = 0;
11490 if (question->WakeOnResolve)
11491 {
11492 question->WakeOnResolveCount = InitialWakeOnResolveCount;
11493 purge = mDNStrue;
11494 }
11495
11496 for (i=0; i<DupSuppressInfoSize; i++)
11497 question->DupSuppress[i].InterfaceID = mDNSNULL;
11498
11499 question->Restart = 0;
11500
11501 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11502 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11503 NextQSendTime(question) - m->timenow,
11504 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11505 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11506
11507 if (question->DelayAnswering)
11508 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11509 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11510
11511 return(purge);
11512 }
11513
11514 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11515 mDNSlocal void InitWABState(DNSQuestion *const question)
11516 {
11517 // We'll create our question->LocalSocket on demand, if needed.
11518 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11519 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11520 // NAT mapping for receiving inbound add/remove events.
11521 question->LocalSocket = mDNSNULL;
11522 question->unansweredQueries = 0;
11523 question->nta = mDNSNULL;
11524 question->servAddr = zeroAddr;
11525 question->servPort = zeroIPPort;
11526 question->tcp = mDNSNULL;
11527 question->NoAnswer = NoAnswer_Normal;
11528 }
11529
11530 mDNSlocal void InitLLQNATState(mDNS *const m)
11531 {
11532 // If we don't have our NAT mapping active, start it now
11533 if (!m->LLQNAT.clientCallback)
11534 {
11535 m->LLQNAT.Protocol = NATOp_MapUDP;
11536 m->LLQNAT.IntPort = m->UnicastPort4;
11537 m->LLQNAT.RequestedPort = m->UnicastPort4;
11538 m->LLQNAT.clientCallback = LLQNATCallback;
11539 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal just started
11540 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11541 }
11542 }
11543
11544 mDNSlocal void InitLLQState(DNSQuestion *const question)
11545 {
11546 question->state = LLQ_InitialRequest;
11547 question->ReqLease = 0;
11548 question->expire = 0;
11549 question->ntries = 0;
11550 question->id = zeroOpaque64;
11551 }
11552
11553 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11554 // DNSSEC & DNS Proxy fields of the DNS Question.
11555 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11556 {
11557 (void) m;
11558
11559 // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11560 // or the request is going over cellular interface.
11561 //
11562 // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11563 // at ValidationRequired setting also.
11564 if (question->qDNSServer)
11565 {
11566 if (question->qDNSServer->cellIntf)
11567 {
11568 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question->qname.c, DNSTypeName(question->qtype));
11569 question->ValidationRequired = mDNSfalse;
11570 }
11571 if (DNSSECOptionalQuestion(question) && !(question->qDNSServer->req_DO))
11572 {
11573 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
11574 question->qname.c, DNSTypeName(question->qtype));
11575 question->ValidationRequired = DNSSEC_VALIDATION_NONE;
11576 }
11577 }
11578 question->ValidationState = (question->ValidationRequired ? DNSSECValRequired : DNSSECValNotRequired);
11579 question->ValidationStatus = 0;
11580 question->responseFlags = zeroID;
11581 }
11582
11583 // Once the question is completely initialized including the duplicate logic, this function
11584 // is called to finalize the unicast question which requires flushing the cache if needed,
11585 // activating the query etc.
11586 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question, mDNSBool purge)
11587 {
11588 // Ensure DNS related info of duplicate question is same as the orig question
11589 if (question->DuplicateOf)
11590 {
11591 question->validDNSServers = question->DuplicateOf->validDNSServers;
11592 question->qDNSServer = question->DuplicateOf->qDNSServer;
11593 LogInfo("FinalizeUnicastQuestion: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
11594 question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype),
11595 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11596 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11597 }
11598
11599 ActivateUnicastQuery(m, question, mDNSfalse);
11600
11601 // If purge was set above, flush the cache. Need to do this after we set the
11602 // DNS server on the question
11603 if (purge)
11604 {
11605 question->DelayAnswering = 0;
11606 mDNS_PurgeForQuestion(m, question);
11607 }
11608 else if (!question->DuplicateOf && DNSSECQuestion(question))
11609 {
11610 // For DNSSEC questions, we need to have the RRSIGs also for verification.
11611 CheckForDNSSECRecords(m, question);
11612 }
11613 if (question->LongLived)
11614 {
11615 // Unlike other initializations, InitLLQNATState should be done after
11616 // we determine that it is a unicast question. LongLived is set for
11617 // both multicast and unicast browse questions but we should initialize
11618 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11619 // start the NAT traversal that is not needed.
11620 InitLLQNATState(m);
11621 #if APPLE_OSX_mDNSResponder
11622 UpdateAutoTunnelDomainStatuses(m);
11623 #endif
11624 }
11625 }
11626
11627 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
11628 {
11629 DNSQuestion **q;
11630 mStatus vStatus;
11631 mDNSBool purge;
11632
11633 // First check for cache space (can't do queries if there is no cache space allocated)
11634 if (m->rrcache_size == 0)
11635 return(mStatus_NoCache);
11636
11637 vStatus = ValidateParameters(m, question);
11638 if (vStatus)
11639 return(vStatus);
11640
11641 question->TargetQID =
11642 #ifndef UNICAST_DISABLED
11643 (question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
11644 #endif // UNICAST_DISABLED
11645 zeroID;
11646 debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11647
11648 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
11649 q = &m->Questions;
11650 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
11651 q = &m->LocalOnlyQuestions;
11652 while (*q && *q != question)
11653 q=&(*q)->next;
11654
11655 if (*q)
11656 {
11657 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
11658 question->qname.c, DNSTypeName(question->qtype), question);
11659 return(mStatus_AlreadyRegistered);
11660 }
11661 *q = question;
11662
11663
11664 // Intialize the question. The only ordering constraint we have today is that
11665 // InitDNSSECProxyState should be called after the DNS server is selected (in
11666 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
11667 // validation.
11668
11669 purge = InitCommonState(m, question);
11670 InitWABState(question);
11671 InitLLQState(question);
11672 InitDNSSECProxyState(m, question);
11673
11674 // FindDuplicateQuestion should be called last after all the intialization
11675 // as the duplicate logic could be potentially based on any field in the
11676 // question.
11677 question->DuplicateOf = FindDuplicateQuestion(m, question);
11678 if (question->DuplicateOf)
11679 question->AuthInfo = question->DuplicateOf->AuthInfo;
11680
11681 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
11682 {
11683 if (!m->NewLocalOnlyQuestions)
11684 m->NewLocalOnlyQuestions = question;
11685 }
11686 else
11687 {
11688 if (!m->NewQuestions)
11689 m->NewQuestions = question;
11690
11691 // If the question's id is non-zero, then it's Wide Area
11692 // MUST NOT do this Wide Area setup until near the end of
11693 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
11694 // NS, etc.) and if we haven't finished setting up our own question and setting
11695 // m->NewQuestions if necessary then we could end up recursively re-entering
11696 // this routine with the question list data structures in an inconsistent state.
11697 if (!mDNSOpaque16IsZero(question->TargetQID))
11698 {
11699 FinalizeUnicastQuestion(m, question, purge);
11700 }
11701 else
11702 {
11703 if (purge)
11704 {
11705 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
11706 mDNS_PurgeForQuestion(m, question);
11707 }
11708 }
11709 }
11710
11711 return(mStatus_NoError);
11712 }
11713
11714 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
11715 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
11716 {
11717 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
11718 // This function may be called anytime to free the zone information.The question may or may not have stopped.
11719 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
11720 // call it again
11721 if (nta->question.ThisQInterval != -1)
11722 {
11723 mDNS_StopQuery_internal(m, &nta->question);
11724 if (nta->question.ThisQInterval != -1)
11725 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
11726 }
11727 mDNSPlatformMemFree(nta);
11728 }
11729
11730 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
11731 {
11732 const mDNSu32 slot = HashSlot(&question->qname);
11733 CacheGroup *cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
11734 CacheRecord *rr;
11735 DNSQuestion **qp = &m->Questions;
11736
11737 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11738
11739 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) qp = &m->LocalOnlyQuestions;
11740 while (*qp && *qp != question) qp=&(*qp)->next;
11741 if (*qp) *qp = (*qp)->next;
11742 else
11743 {
11744 #if !ForceAlerts
11745 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
11746 #endif
11747 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
11748 question->qname.c, DNSTypeName(question->qtype));
11749 #if ForceAlerts
11750 *(long*)0 = 0;
11751 #endif
11752 return(mStatus_BadReferenceErr);
11753 }
11754
11755 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
11756 UpdateQuestionDuplicates(m, question);
11757 // But don't trash ThisQInterval until afterwards.
11758 question->ThisQInterval = -1;
11759
11760 // If there are any cache records referencing this as their active question, then see if there is any
11761 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
11762 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
11763 {
11764 if (rr->CRActiveQuestion == question)
11765 {
11766 DNSQuestion *q;
11767 // Checking for ActiveQuestion filters questions that are suppressed also
11768 // as suppressed questions are not active
11769 for (q = m->Questions; q; q=q->next) // Scan our list of questions
11770 if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
11771 break;
11772 if (q)
11773 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
11774 "CurrentAnswers %d, SuppressQuery %d", q, CRDisplayString(m,rr), question->CurrentAnswers, q->CurrentAnswers, q->SuppressQuery);
11775 rr->CRActiveQuestion = q; // Question used to be active; new value may or may not be null
11776 if (!q) m->rrcache_active--; // If no longer active, decrement rrcache_active count
11777 }
11778 }
11779
11780 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
11781 // bump its pointer forward one question.
11782 if (m->CurrentQuestion == question)
11783 {
11784 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
11785 question->qname.c, DNSTypeName(question->qtype));
11786 m->CurrentQuestion = question->next;
11787 }
11788
11789 if (m->NewQuestions == question)
11790 {
11791 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
11792 question->qname.c, DNSTypeName(question->qtype));
11793 m->NewQuestions = question->next;
11794 }
11795
11796 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
11797
11798 if (m->RestartQuestion == question)
11799 {
11800 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
11801 question->qname.c, DNSTypeName(question->qtype));
11802 m->RestartQuestion = question->next;
11803 }
11804
11805 if (m->ValidationQuestion == question)
11806 {
11807 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
11808 question->qname.c, DNSTypeName(question->qtype));
11809 m->ValidationQuestion = question->next;
11810 }
11811
11812 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
11813 question->next = mDNSNULL;
11814
11815 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
11816
11817 // And finally, cancel any associated GetZoneData operation that's still running.
11818 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
11819 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
11820 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
11821 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
11822 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
11823 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
11824 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
11825 {
11826 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
11827 DNSQuestion *q;
11828 for (q = m->Questions; q; q=q->next)
11829 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
11830 if (!q)
11831 {
11832 if (!m->LLQNAT.clientCallback) // Should never happen, but just in case...
11833 {
11834 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
11835 }
11836 else
11837 {
11838 LogInfo("Stopping LLQNAT");
11839 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
11840 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
11841 }
11842 }
11843
11844 // If necessary, tell server it can delete this LLQ state
11845 if (question->state == LLQ_Established)
11846 {
11847 question->ReqLease = 0;
11848 sendLLQRefresh(m, question);
11849 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
11850 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
11851 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
11852 // we let that run out its natural course and complete asynchronously.
11853 if (question->tcp)
11854 {
11855 question->tcp->question = mDNSNULL;
11856 question->tcp = mDNSNULL;
11857 }
11858 }
11859 #if APPLE_OSX_mDNSResponder
11860 UpdateAutoTunnelDomainStatuses(m);
11861 #endif
11862 }
11863 // wait until we send the refresh above which needs the nta
11864 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
11865
11866 if (question->ValidationRequired && question->DNSSECAuthInfo)
11867 {
11868 LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question->qname.c);
11869 question->DAIFreeCallback(m, question->DNSSECAuthInfo);
11870 question->DNSSECAuthInfo = mDNSNULL;
11871 }
11872 if (question->AnonInfo)
11873 {
11874 FreeAnonInfo(question->AnonInfo);
11875 question->AnonInfo = mDNSNULL;
11876 }
11877
11878 return(mStatus_NoError);
11879 }
11880
11881 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
11882 {
11883 mStatus status;
11884 mDNS_Lock(m);
11885 status = mDNS_StartQuery_internal(m, question);
11886 mDNS_Unlock(m);
11887 return(status);
11888 }
11889
11890 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
11891 {
11892 mStatus status;
11893 mDNS_Lock(m);
11894 status = mDNS_StopQuery_internal(m, question);
11895 mDNS_Unlock(m);
11896 return(status);
11897 }
11898
11899 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
11900 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
11901 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
11902 // specifically to catch and report if the client callback does try to make API calls
11903 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
11904 {
11905 mStatus status;
11906 DNSQuestion *qq;
11907 mDNS_Lock(m);
11908
11909 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
11910 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
11911
11912 status = mDNS_StopQuery_internal(m, question);
11913 if (status == mStatus_NoError && !qq)
11914 {
11915 const CacheRecord *rr;
11916 const mDNSu32 slot = HashSlot(&question->qname);
11917 CacheGroup *const cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
11918 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11919 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
11920 if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
11921 {
11922 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
11923 if (question->QuestionCallback)
11924 question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
11925 }
11926 }
11927 mDNS_Unlock(m);
11928 return(status);
11929 }
11930
11931 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
11932 {
11933 mStatus status;
11934 mDNS_Lock(m);
11935 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
11936 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
11937 mDNS_Unlock(m);
11938 return(status);
11939 }
11940
11941 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
11942 {
11943 mStatus status = mStatus_BadReferenceErr;
11944 CacheRecord *cr;
11945 mDNS_Lock(m);
11946 cr = FindIdenticalRecordInCache(m, rr);
11947 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
11948 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
11949 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
11950 mDNS_Unlock(m);
11951 return(status);
11952 }
11953
11954 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
11955 const domainname *const srv, const domainname *const domain,
11956 const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
11957 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
11958 mDNSQuestionCallback *Callback, void *Context)
11959 {
11960 question->InterfaceID = InterfaceID;
11961 question->flags = flags;
11962 question->Target = zeroAddr;
11963 question->qtype = kDNSType_PTR;
11964 question->qclass = kDNSClass_IN;
11965 question->LongLived = mDNStrue;
11966 question->ExpectUnique = mDNSfalse;
11967 question->ForceMCast = ForceMCast;
11968 question->ReturnIntermed = mDNSfalse;
11969 question->SuppressUnusable = mDNSfalse;
11970 question->SearchListIndex = 0;
11971 question->AppendSearchDomains = 0;
11972 question->RetryWithSearchDomains = mDNSfalse;
11973 question->TimeoutQuestion = 0;
11974 question->WakeOnResolve = 0;
11975 question->UseBackgroundTrafficClass = useBackgroundTrafficClass;
11976 question->ValidationRequired = 0;
11977 question->ValidatingResponse = 0;
11978 question->ProxyQuestion = 0;
11979 question->qnameOrig = mDNSNULL;
11980 question->AnonInfo = mDNSNULL;
11981 question->QuestionCallback = Callback;
11982 question->QuestionContext = Context;
11983
11984 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
11985 return(mStatus_BadParamErr);
11986
11987 if (anondata)
11988 {
11989 question->AnonInfo = AllocateAnonInfo(&question->qname, anondata, mDNSPlatformStrLen(anondata), mDNSNULL);
11990 if (!question->AnonInfo)
11991 return(mStatus_BadParamErr);
11992 }
11993
11994 return(mDNS_StartQuery_internal(m, question));
11995 }
11996
11997 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
11998 const domainname *const srv, const domainname *const domain,
11999 const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12000 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12001 mDNSQuestionCallback *Callback, void *Context)
12002 {
12003 mStatus status;
12004 mDNS_Lock(m);
12005 status = mDNS_StartBrowse_internal(m, question, srv, domain, anondata, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12006 mDNS_Unlock(m);
12007 return(status);
12008 }
12009
12010 mDNSlocal mDNSBool MachineHasActiveIPv6(mDNS *const m)
12011 {
12012 NetworkInterfaceInfo *intf;
12013 for (intf = m->HostInterfaces; intf; intf = intf->next)
12014 if (intf->ip.type == mDNSAddrType_IPv6) return(mDNStrue);
12015 return(mDNSfalse);
12016 }
12017
12018 mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
12019 {
12020 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
12021 mDNSBool PortChanged = !mDNSSameIPPort(query->info->port, answer->rdata->u.srv.port);
12022 if (!AddRecord) return;
12023 if (answer->rrtype != kDNSType_SRV) return;
12024
12025 query->info->port = answer->rdata->u.srv.port;
12026
12027 // If this is our first answer, then set the GotSRV flag and start the address query
12028 if (!query->GotSRV)
12029 {
12030 query->GotSRV = mDNStrue;
12031 query->qAv4.InterfaceID = answer->InterfaceID;
12032 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
12033 query->qAv6.InterfaceID = answer->InterfaceID;
12034 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
12035 mDNS_StartQuery(m, &query->qAv4);
12036 // Only do the AAAA query if this machine actually has IPv6 active
12037 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
12038 }
12039 // If this is not our first answer, only re-issue the address query if the target host name has changed
12040 else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
12041 !SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
12042 {
12043 mDNS_StopQuery(m, &query->qAv4);
12044 if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery(m, &query->qAv6);
12045 if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
12046 {
12047 // If we get here, it means:
12048 // 1. This is not our first SRV answer
12049 // 2. The interface ID is different, but the target host and port are the same
12050 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
12051 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
12052 query->qAv4.InterfaceID = query->qSRV.InterfaceID; // Will be mDNSInterface_Any, or a specific interface
12053 query->qAv6.InterfaceID = query->qSRV.InterfaceID;
12054 }
12055 else
12056 {
12057 query->qAv4.InterfaceID = answer->InterfaceID;
12058 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
12059 query->qAv6.InterfaceID = answer->InterfaceID;
12060 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
12061 }
12062 debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query->qAv4.qname.c, DNSTypeName(query->qAv4.qtype));
12063 mDNS_StartQuery(m, &query->qAv4);
12064 // Only do the AAAA query if this machine actually has IPv6 active
12065 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
12066 }
12067 else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
12068 {
12069 if (++query->Answers >= 100)
12070 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
12071 query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
12072 mDNSVal16(answer->rdata->u.srv.port));
12073 query->ServiceInfoQueryCallback(m, query);
12074 }
12075 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
12076 // callback function is allowed to do anything, including deleting this query and freeing its memory.
12077 }
12078
12079 mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
12080 {
12081 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
12082 if (!AddRecord) return;
12083 if (answer->rrtype != kDNSType_TXT) return;
12084 if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
12085
12086 query->GotTXT = mDNStrue;
12087 query->info->TXTlen = answer->rdlength;
12088 query->info->TXTinfo[0] = 0; // In case answer->rdlength is zero
12089 mDNSPlatformMemCopy(query->info->TXTinfo, answer->rdata->u.txt.c, answer->rdlength);
12090
12091 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
12092
12093 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
12094 // callback function is allowed to do anything, including deleting this query and freeing its memory.
12095 if (query->ServiceInfoQueryCallback && query->GotADD)
12096 {
12097 if (++query->Answers >= 100)
12098 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
12099 query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
12100 query->ServiceInfoQueryCallback(m, query);
12101 }
12102 }
12103
12104 mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
12105 {
12106 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
12107 //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
12108 if (!AddRecord) return;
12109
12110 if (answer->rrtype == kDNSType_A)
12111 {
12112 query->info->ip.type = mDNSAddrType_IPv4;
12113 query->info->ip.ip.v4 = answer->rdata->u.ipv4;
12114 }
12115 else if (answer->rrtype == kDNSType_AAAA)
12116 {
12117 query->info->ip.type = mDNSAddrType_IPv6;
12118 query->info->ip.ip.v6 = answer->rdata->u.ipv6;
12119 }
12120 else
12121 {
12122 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name->c, answer->rrtype, DNSTypeName(answer->rrtype));
12123 return;
12124 }
12125
12126 query->GotADD = mDNStrue;
12127 query->info->InterfaceID = answer->InterfaceID;
12128
12129 verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
12130
12131 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
12132 // callback function is allowed to do anything, including deleting this query and freeing its memory.
12133 if (query->ServiceInfoQueryCallback && query->GotTXT)
12134 {
12135 if (++query->Answers >= 100)
12136 debugf(answer->rrtype == kDNSType_A ?
12137 "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
12138 "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
12139 query->Answers, query->qSRV.qname.c, &answer->rdata->u.data);
12140 query->ServiceInfoQueryCallback(m, query);
12141 }
12142 }
12143
12144 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
12145 // If the query is not interface-specific, then InterfaceID may be zero
12146 // Each time the Callback is invoked, the remainder of the fields will have been filled in
12147 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
12148 mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
12149 ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
12150 {
12151 mStatus status;
12152 mDNS_Lock(m);
12153
12154 query->qSRV.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
12155 query->qSRV.InterfaceID = info->InterfaceID;
12156 query->qSRV.flags = 0;
12157 query->qSRV.Target = zeroAddr;
12158 AssignDomainName(&query->qSRV.qname, &info->name);
12159 query->qSRV.qtype = kDNSType_SRV;
12160 query->qSRV.qclass = kDNSClass_IN;
12161 query->qSRV.LongLived = mDNSfalse;
12162 query->qSRV.ExpectUnique = mDNStrue;
12163 query->qSRV.ForceMCast = mDNSfalse;
12164 query->qSRV.ReturnIntermed = mDNSfalse;
12165 query->qSRV.SuppressUnusable = mDNSfalse;
12166 query->qSRV.SearchListIndex = 0;
12167 query->qSRV.AppendSearchDomains = 0;
12168 query->qSRV.RetryWithSearchDomains = mDNSfalse;
12169 query->qSRV.TimeoutQuestion = 0;
12170 query->qSRV.WakeOnResolve = 0;
12171 query->qSRV.UseBackgroundTrafficClass = mDNSfalse;
12172 query->qSRV.ValidationRequired = 0;
12173 query->qSRV.ValidatingResponse = 0;
12174 query->qSRV.ProxyQuestion = 0;
12175 query->qSRV.qnameOrig = mDNSNULL;
12176 query->qSRV.AnonInfo = mDNSNULL;
12177 query->qSRV.QuestionCallback = FoundServiceInfoSRV;
12178 query->qSRV.QuestionContext = query;
12179
12180 query->qTXT.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
12181 query->qTXT.InterfaceID = info->InterfaceID;
12182 query->qTXT.flags = 0;
12183 query->qTXT.Target = zeroAddr;
12184 AssignDomainName(&query->qTXT.qname, &info->name);
12185 query->qTXT.qtype = kDNSType_TXT;
12186 query->qTXT.qclass = kDNSClass_IN;
12187 query->qTXT.LongLived = mDNSfalse;
12188 query->qTXT.ExpectUnique = mDNStrue;
12189 query->qTXT.ForceMCast = mDNSfalse;
12190 query->qTXT.ReturnIntermed = mDNSfalse;
12191 query->qTXT.SuppressUnusable = mDNSfalse;
12192 query->qTXT.SearchListIndex = 0;
12193 query->qTXT.AppendSearchDomains = 0;
12194 query->qTXT.RetryWithSearchDomains = mDNSfalse;
12195 query->qTXT.TimeoutQuestion = 0;
12196 query->qTXT.WakeOnResolve = 0;
12197 query->qTXT.UseBackgroundTrafficClass = mDNSfalse;
12198 query->qTXT.ValidationRequired = 0;
12199 query->qTXT.ValidatingResponse = 0;
12200 query->qTXT.ProxyQuestion = 0;
12201 query->qTXT.qnameOrig = mDNSNULL;
12202 query->qTXT.AnonInfo = mDNSNULL;
12203 query->qTXT.QuestionCallback = FoundServiceInfoTXT;
12204 query->qTXT.QuestionContext = query;
12205
12206 query->qAv4.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
12207 query->qAv4.InterfaceID = info->InterfaceID;
12208 query->qAv4.flags = 0;
12209 query->qAv4.Target = zeroAddr;
12210 query->qAv4.qname.c[0] = 0;
12211 query->qAv4.qtype = kDNSType_A;
12212 query->qAv4.qclass = kDNSClass_IN;
12213 query->qAv4.LongLived = mDNSfalse;
12214 query->qAv4.ExpectUnique = mDNStrue;
12215 query->qAv4.ForceMCast = mDNSfalse;
12216 query->qAv4.ReturnIntermed = mDNSfalse;
12217 query->qAv4.SuppressUnusable = mDNSfalse;
12218 query->qAv4.SearchListIndex = 0;
12219 query->qAv4.AppendSearchDomains = 0;
12220 query->qAv4.RetryWithSearchDomains = mDNSfalse;
12221 query->qAv4.TimeoutQuestion = 0;
12222 query->qAv4.WakeOnResolve = 0;
12223 query->qAv4.UseBackgroundTrafficClass = mDNSfalse;
12224 query->qAv4.ValidationRequired = 0;
12225 query->qAv4.ValidatingResponse = 0;
12226 query->qAv4.ProxyQuestion = 0;
12227 query->qAv4.qnameOrig = mDNSNULL;
12228 query->qAv4.AnonInfo = mDNSNULL;
12229 query->qAv4.QuestionCallback = FoundServiceInfo;
12230 query->qAv4.QuestionContext = query;
12231
12232 query->qAv6.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
12233 query->qAv6.InterfaceID = info->InterfaceID;
12234 query->qAv6.flags = 0;
12235 query->qAv6.Target = zeroAddr;
12236 query->qAv6.qname.c[0] = 0;
12237 query->qAv6.qtype = kDNSType_AAAA;
12238 query->qAv6.qclass = kDNSClass_IN;
12239 query->qAv6.LongLived = mDNSfalse;
12240 query->qAv6.ExpectUnique = mDNStrue;
12241 query->qAv6.ForceMCast = mDNSfalse;
12242 query->qAv6.ReturnIntermed = mDNSfalse;
12243 query->qAv6.SuppressUnusable = mDNSfalse;
12244 query->qAv6.SearchListIndex = 0;
12245 query->qAv6.AppendSearchDomains = 0;
12246 query->qAv6.RetryWithSearchDomains = mDNSfalse;
12247 query->qAv6.TimeoutQuestion = 0;
12248 query->qAv6.UseBackgroundTrafficClass = mDNSfalse;
12249 query->qAv6.ValidationRequired = 0;
12250 query->qAv6.ValidatingResponse = 0;
12251 query->qAv6.ProxyQuestion = 0;
12252 query->qAv6.qnameOrig = mDNSNULL;
12253 query->qAv6.AnonInfo = mDNSNULL;
12254 query->qAv6.QuestionCallback = FoundServiceInfo;
12255 query->qAv6.QuestionContext = query;
12256
12257 query->GotSRV = mDNSfalse;
12258 query->GotTXT = mDNSfalse;
12259 query->GotADD = mDNSfalse;
12260 query->Answers = 0;
12261
12262 query->info = info;
12263 query->ServiceInfoQueryCallback = Callback;
12264 query->ServiceInfoQueryContext = Context;
12265
12266 // info->name = Must already be set up by client
12267 // info->interface = Must already be set up by client
12268 info->ip = zeroAddr;
12269 info->port = zeroIPPort;
12270 info->TXTlen = 0;
12271
12272 // We use mDNS_StartQuery_internal here because we're already holding the lock
12273 status = mDNS_StartQuery_internal(m, &query->qSRV);
12274 if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
12275 if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
12276
12277 mDNS_Unlock(m);
12278 return(status);
12279 }
12280
12281 mDNSexport void mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *q)
12282 {
12283 mDNS_Lock(m);
12284 // We use mDNS_StopQuery_internal here because we're already holding the lock
12285 if (q->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qSRV);
12286 if (q->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qTXT);
12287 if (q->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv4);
12288 if (q->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv6);
12289 mDNS_Unlock(m);
12290 }
12291
12292 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12293 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12294 {
12295 question->InterfaceID = InterfaceID;
12296 question->flags = 0;
12297 question->Target = zeroAddr;
12298 question->qtype = kDNSType_PTR;
12299 question->qclass = kDNSClass_IN;
12300 question->LongLived = mDNSfalse;
12301 question->ExpectUnique = mDNSfalse;
12302 question->ForceMCast = mDNSfalse;
12303 question->ReturnIntermed = mDNSfalse;
12304 question->SuppressUnusable = mDNSfalse;
12305 question->SearchListIndex = 0;
12306 question->AppendSearchDomains = 0;
12307 question->RetryWithSearchDomains = mDNSfalse;
12308 question->TimeoutQuestion = 0;
12309 question->WakeOnResolve = 0;
12310 question->UseBackgroundTrafficClass = mDNSfalse;
12311 question->ValidationRequired = 0;
12312 question->ValidatingResponse = 0;
12313 question->ProxyQuestion = 0;
12314 question->qnameOrig = mDNSNULL;
12315 question->AnonInfo = mDNSNULL;
12316 question->pid = mDNSPlatformGetPID();
12317 question->QuestionCallback = Callback;
12318 question->QuestionContext = Context;
12319 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12320 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12321 if (!dom) dom = &localdomain;
12322 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12323 return(mDNS_StartQuery(m, question));
12324 }
12325
12326 // ***************************************************************************
12327 #if COMPILER_LIKES_PRAGMA_MARK
12328 #pragma mark -
12329 #pragma mark - Responder Functions
12330 #endif
12331
12332 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12333 {
12334 mStatus status;
12335 mDNS_Lock(m);
12336 status = mDNS_Register_internal(m, rr);
12337 mDNS_Unlock(m);
12338 return(status);
12339 }
12340
12341 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12342 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12343 {
12344 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12345 {
12346 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12347 return(mStatus_Invalid);
12348 }
12349
12350 mDNS_Lock(m);
12351
12352 // If TTL is unspecified, leave TTL unchanged
12353 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12354
12355 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12356 if (rr->NewRData)
12357 {
12358 RData *n = rr->NewRData;
12359 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
12360 if (rr->UpdateCallback)
12361 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
12362 }
12363
12364 rr->NewRData = newrdata;
12365 rr->newrdlength = newrdlength;
12366 rr->UpdateCallback = Callback;
12367
12368 #ifndef UNICAST_DISABLED
12369 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12370 {
12371 mStatus status = uDNS_UpdateRecord(m, rr);
12372 // The caller frees the memory on error, don't retain stale pointers
12373 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12374 mDNS_Unlock(m);
12375 return(status);
12376 }
12377 #endif
12378
12379 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12380 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12381 CompleteRDataUpdate(m, rr);
12382 else
12383 {
12384 rr->AnnounceCount = InitialAnnounceCount;
12385 InitializeLastAPTime(m, rr);
12386 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12387 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12388 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12389 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12390 if (rr->UpdateCredits <= 5)
12391 {
12392 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12393 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12394 rr->ThisAPInterval *= 4;
12395 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12396 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12397 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12398 }
12399 rr->resrec.rroriginalttl = newttl;
12400 }
12401
12402 mDNS_Unlock(m);
12403 return(mStatus_NoError);
12404 }
12405
12406 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12407 // the record list and/or question list.
12408 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12409 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12410 {
12411 mStatus status;
12412 mDNS_Lock(m);
12413 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12414 mDNS_Unlock(m);
12415 return(status);
12416 }
12417
12418 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12419 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12420
12421 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
12422 {
12423 NetworkInterfaceInfo *intf;
12424 for (intf = m->HostInterfaces; intf; intf = intf->next)
12425 if (intf->Advertise) break;
12426 return(intf);
12427 }
12428
12429 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12430 {
12431 char buffer[MAX_REVERSE_MAPPING_NAME];
12432 NetworkInterfaceInfo *primary;
12433
12434 if (!set->McastTxRx)
12435 {
12436 LogInfo("AdvertiseInterface: Returning, not multicast capable %s", set->ifname);
12437 return;
12438 }
12439 #if TARGET_OS_EMBEDDED
12440 if (!m->AutoTargetServices)
12441 {
12442 LogInfo("AdvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
12443 return;
12444 }
12445 #endif
12446
12447 primary = FindFirstAdvertisedInterface(m);
12448 if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
12449
12450 // Send dynamic update for non-linklocal IPv4 Addresses
12451 mDNS_SetupResourceRecord(&set->RR_A, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNS_HostNameCallback, set);
12452 mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12453 mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12454
12455 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12456 set->RR_A.AllowRemoteQuery = mDNStrue;
12457 set->RR_PTR.AllowRemoteQuery = mDNStrue;
12458 set->RR_HINFO.AllowRemoteQuery = mDNStrue;
12459 #endif
12460 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12461 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12462 AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
12463 if (set->ip.type == mDNSAddrType_IPv4)
12464 {
12465 set->RR_A.resrec.rrtype = kDNSType_A;
12466 set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
12467 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12468 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12469 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12470 }
12471 else if (set->ip.type == mDNSAddrType_IPv6)
12472 {
12473 int i;
12474 set->RR_A.resrec.rrtype = kDNSType_AAAA;
12475 set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
12476 for (i = 0; i < 16; i++)
12477 {
12478 static const char hexValues[] = "0123456789ABCDEF";
12479 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12480 buffer[i * 4 + 1] = '.';
12481 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12482 buffer[i * 4 + 3] = '.';
12483 }
12484 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12485 }
12486
12487 MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
12488 set->RR_PTR.AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12489 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
12490
12491 set->RR_A.RRSet = &primary->RR_A; // May refer to self
12492
12493 #if APPLE_OSX_mDNSResponder
12494 D2D_start_advertising_interface(set);
12495 #endif // APPLE_OSX_mDNSResponder
12496
12497 mDNS_Register_internal(m, &set->RR_A);
12498 mDNS_Register_internal(m, &set->RR_PTR);
12499
12500 if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
12501 {
12502 mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
12503 AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
12504 set->RR_HINFO.DependentOn = &set->RR_A;
12505 mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
12506 p += 1 + (int)p[0];
12507 mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
12508 mDNS_Register_internal(m, &set->RR_HINFO);
12509 }
12510 else
12511 {
12512 debugf("Not creating HINFO record: platform support layer provided no information");
12513 set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
12514 }
12515 }
12516
12517 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12518 {
12519 NetworkInterfaceInfo *intf;
12520
12521 // If we still have address records referring to this one, update them
12522 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
12523 AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
12524 for (intf = m->HostInterfaces; intf; intf = intf->next)
12525 if (intf->RR_A.RRSet == &set->RR_A)
12526 intf->RR_A.RRSet = A;
12527
12528 // Unregister these records.
12529 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12530 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12531 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12532 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12533 if (set->RR_A.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
12534 if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
12535 if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
12536
12537 #if APPLE_OSX_mDNSResponder
12538 D2D_stop_advertising_interface(set);
12539 #endif // APPLE_OSX_mDNSResponder
12540
12541 }
12542
12543 mDNSlocal void AdvertiseAllInterfaceRecords(mDNS *const m)
12544 {
12545 NetworkInterfaceInfo *intf;
12546 for (intf = m->HostInterfaces; intf; intf = intf->next)
12547 {
12548 if (intf->Advertise)
12549 {
12550 LogInfo("AdvertiseInterface: Advertising for ifname %s", intf->ifname);
12551 AdvertiseInterface(m, intf);
12552 }
12553 }
12554 }
12555
12556 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m)
12557 {
12558 #if TARGET_OS_EMBEDDED
12559 NetworkInterfaceInfo *intf;
12560 for (intf = m->HostInterfaces; intf; intf = intf->next)
12561 {
12562 if (intf->Advertise)
12563 {
12564 LogInfo("DeadvertiseInterface: Deadvertising for ifname %s", intf->ifname);
12565 DeadvertiseInterface(m, intf);
12566 }
12567 }
12568 #else
12569 (void) m; //unused
12570 #endif
12571 }
12572
12573 mDNSexport void mDNS_SetFQDN(mDNS *const m)
12574 {
12575 domainname newmname;
12576 NetworkInterfaceInfo *intf;
12577 AuthRecord *rr;
12578 newmname.c[0] = 0;
12579
12580 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12581 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12582
12583 mDNS_Lock(m);
12584
12585 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
12586 else
12587 {
12588 AssignDomainName(&m->MulticastHostname, &newmname);
12589
12590 // 1. Stop advertising our address records on all interfaces
12591 for (intf = m->HostInterfaces; intf; intf = intf->next)
12592 if (intf->Advertise) DeadvertiseInterface(m, intf);
12593
12594 // 2. Start advertising our address records using the new name
12595 for (intf = m->HostInterfaces; intf; intf = intf->next)
12596 if (intf->Advertise) AdvertiseInterface(m, intf);
12597 }
12598
12599 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12600 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
12601 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
12602
12603 mDNS_Unlock(m);
12604 }
12605
12606 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12607 {
12608 (void)rr; // Unused parameter
12609
12610 #if MDNS_DEBUGMSGS
12611 {
12612 char *msg = "Unknown result";
12613 if (result == mStatus_NoError) msg = "Name registered";
12614 else if (result == mStatus_NameConflict) msg = "Name conflict";
12615 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
12616 }
12617 #endif
12618
12619 if (result == mStatus_NoError)
12620 {
12621 // Notify the client that the host name is successfully registered
12622 if (m->MainCallback)
12623 m->MainCallback(m, mStatus_NoError);
12624 }
12625 else if (result == mStatus_NameConflict)
12626 {
12627 domainlabel oldlabel = m->hostlabel;
12628
12629 // 1. First give the client callback a chance to pick a new name
12630 if (m->MainCallback)
12631 m->MainCallback(m, mStatus_NameConflict);
12632
12633 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12634 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12635 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12636 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
12637 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
12638
12639 // 3. Generate the FQDNs from the hostlabel,
12640 // and make sure all SRV records, etc., are updated to reference our new hostname
12641 mDNS_SetFQDN(m);
12642 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
12643 }
12644 else if (result == mStatus_MemFree)
12645 {
12646 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12647 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12648 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12649 }
12650 else
12651 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c);
12652 }
12653
12654 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12655 {
12656 NetworkInterfaceInfo *intf;
12657 active->IPv4Available = mDNSfalse;
12658 active->IPv6Available = mDNSfalse;
12659 for (intf = m->HostInterfaces; intf; intf = intf->next)
12660 if (intf->InterfaceID == active->InterfaceID)
12661 {
12662 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12663 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12664 }
12665 }
12666
12667 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12668 {
12669 AuthRecord *rr;
12670 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12671 for (rr = m->ResourceRecords; rr; rr=rr->next)
12672 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12673 {
12674 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12675 // Zero out the updateid so that if we have a pending response from the server, it won't
12676 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12677 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12678 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12679 }
12680 }
12681
12682 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12683 {
12684 int i;
12685 // We initialize ThisQInterval to -1 indicating that the question has not been started
12686 // yet. If the question (browse) is started later during interface registration, it will
12687 // be stopped during interface deregistration. We can't sanity check to see if the
12688 // question has been stopped or not before initializing it to -1 because we need to
12689 // initialize it to -1 the very first time.
12690
12691 set->NetWakeBrowse.ThisQInterval = -1;
12692 for (i=0; i<3; i++)
12693 {
12694 set->NetWakeResolve[i].ThisQInterval = -1;
12695 set->SPSAddr[i].type = mDNSAddrType_None;
12696 }
12697 set->NextSPSAttempt = -1;
12698 set->NextSPSAttemptTime = m->timenow;
12699 }
12700
12701 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12702 {
12703 NetworkInterfaceInfo *p = m->HostInterfaces;
12704 while (p && p != set) p=p->next;
12705 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12706
12707 if (set->InterfaceActive)
12708 {
12709 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12710 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, mDNSNULL, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
12711 }
12712 }
12713
12714 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12715 {
12716 NetworkInterfaceInfo *p = m->HostInterfaces;
12717 while (p && p != set) p=p->next;
12718 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12719
12720 // Note: We start the browse only if the interface is NetWake capable and we use this to
12721 // stop the resolves also. Hence, the resolves should not be started without the browse
12722 // being started i.e, resolves should not happen unless NetWake capable which is
12723 // guaranteed by BeginSleepProcessing.
12724 if (set->NetWakeBrowse.ThisQInterval >= 0)
12725 {
12726 int i;
12727 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
12728
12729 // Stop our browse and resolve operations
12730 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
12731 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
12732
12733 // Make special call to the browse callback to let it know it can to remove all records for this interface
12734 if (m->SPSBrowseCallback)
12735 {
12736 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12737 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
12738 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12739 }
12740
12741 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12742 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12743 InitializeNetWakeState(m, set);
12744 }
12745 }
12746
12747 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
12748 {
12749 AuthRecord *rr;
12750 mDNSBool FirstOfType = mDNStrue;
12751 NetworkInterfaceInfo **p = &m->HostInterfaces;
12752
12753 if (!set->InterfaceID)
12754 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
12755
12756 if (!mDNSAddressIsValidNonZero(&set->mask))
12757 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
12758
12759 mDNS_Lock(m);
12760
12761 // Assume this interface will be active now, unless we find a duplicate already in the list
12762 set->InterfaceActive = mDNStrue;
12763 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
12764 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
12765
12766 InitializeNetWakeState(m, set);
12767
12768 // Scan list to see if this InterfaceID is already represented
12769 while (*p)
12770 {
12771 if (*p == set)
12772 {
12773 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
12774 mDNS_Unlock(m);
12775 return(mStatus_AlreadyRegistered);
12776 }
12777
12778 if ((*p)->InterfaceID == set->InterfaceID)
12779 {
12780 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
12781 set->InterfaceActive = mDNSfalse;
12782 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
12783 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
12784 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
12785 }
12786
12787 p=&(*p)->next;
12788 }
12789
12790 set->next = mDNSNULL;
12791 *p = set;
12792
12793 if (set->Advertise)
12794 AdvertiseInterface(m, set);
12795
12796 LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set->InterfaceID, set->ifname, &set->ip,
12797 set->InterfaceActive ?
12798 "not represented in list; marking active and retriggering queries" :
12799 "already represented in list; marking inactive for now");
12800
12801 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
12802
12803 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
12804 // giving the false impression that there's an active representative of this interface when there really isn't.
12805 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
12806 // even if we believe that we previously had an active representative of this interface.
12807 if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
12808 {
12809 DNSQuestion *q;
12810 // Normally, after an interface comes up, we pause half a second before beginning probing.
12811 // This is to guard against cases where there's rapid interface changes, where we could be confused by
12812 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
12813 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
12814 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
12815 // and think it's a conflicting answer to our probe.
12816 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
12817 const mDNSs32 probedelay = flapping ? mDNSPlatformOneSecond * 5 : mDNSPlatformOneSecond / 2;
12818 const mDNSu8 numannounce = flapping ? (mDNSu8)1 : InitialAnnounceCount;
12819
12820 // Use a small amount of randomness:
12821 // In the case of a network administrator turning on an Ethernet hub so that all the
12822 // connected machines establish link at exactly the same time, we don't want them all
12823 // to go and hit the network with identical queries at exactly the same moment.
12824 // We set a random delay of up to InitialQuestionInterval (1/3 second).
12825 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
12826 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
12827 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
12828 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
12829 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
12830 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
12831
12832 if (flapping)
12833 {
12834 LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
12835 m->mDNSStats.InterfaceUpFlap++;
12836 }
12837
12838 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
12839 if (m->SuppressProbes == 0 ||
12840 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
12841 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
12842
12843 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
12844 // it here also handles the wake up case as the network link comes UP after waking causing
12845 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
12846 // that the network link comes UP after 60 seconds and we never set the OWNER option
12847 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
12848 LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
12849
12850 m->mDNSStats.InterfaceUp++;
12851 for (q = m->Questions; q; q=q->next) // Scan our list of questions
12852 {
12853 if (mDNSOpaque16IsZero(q->TargetQID))
12854 {
12855 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
12856 { // then reactivate this question
12857 // If flapping, delay between first and second queries is nine seconds instead of one second
12858 mDNSBool dodelay = flapping && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
12859 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
12860 mDNSs32 qdelay = dodelay ? mDNSPlatformOneSecond * 5 : 0;
12861 if (dodelay) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q->qname.c, DNSTypeName(q->qtype));
12862
12863 if (!q->ThisQInterval || q->ThisQInterval > initial)
12864 {
12865 q->ThisQInterval = initial;
12866
12867 #if mDNS_REQUEST_UNICAST_RESPONSE
12868 q->RequestUnicast = SET_QU_IN_FIRST_FOUR_QUERIES;
12869 #else // mDNS_REQUEST_UNICAST_RESPONSE
12870 q->RequestUnicast = SET_QU_IN_FIRST_QUERY;
12871 #endif // mDNS_REQUEST_UNICAST_RESPONSE
12872
12873 }
12874 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
12875 q->RecentAnswerPkts = 0;
12876 // Change the salt
12877 ReInitAnonInfo(&q->AnonInfo, &q->qname);
12878 SetNextQueryTime(m,q);
12879 }
12880 }
12881 }
12882
12883 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
12884 // we now need them to re-probe if necessary, and then re-announce.
12885 for (rr = m->ResourceRecords; rr; rr=rr->next)
12886 {
12887 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
12888 {
12889 // Change the salt
12890 ReInitAnonInfo(&rr->resrec.AnonInfo, rr->resrec.name);
12891 mDNSCoreRestartRegistration(m, rr, numannounce);
12892 }
12893 }
12894 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
12895 DNSSECProbe(m);
12896 #endif
12897 }
12898
12899 RestartRecordGetZoneData(m);
12900
12901 mDNS_UpdateAllowSleep(m);
12902
12903 mDNS_Unlock(m);
12904 return(mStatus_NoError);
12905 }
12906
12907 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
12908 // the record list and/or question list.
12909 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12910 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
12911 {
12912 NetworkInterfaceInfo **p = &m->HostInterfaces;
12913 mDNSBool revalidate = mDNSfalse;
12914
12915 mDNS_Lock(m);
12916
12917 // Find this record in our list
12918 while (*p && *p != set) p=&(*p)->next;
12919 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
12920
12921 mDNS_DeactivateNetWake_internal(m, set);
12922
12923 // Unlink this record from our list
12924 *p = (*p)->next;
12925 set->next = mDNSNULL;
12926
12927 if (!set->InterfaceActive)
12928 {
12929 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
12930 NetworkInterfaceInfo *intf;
12931 for (intf = m->HostInterfaces; intf; intf = intf->next)
12932 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
12933 UpdateInterfaceProtocols(m, intf);
12934 }
12935 else
12936 {
12937 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, set->InterfaceID);
12938 if (intf)
12939 {
12940 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
12941 " making it active", set->InterfaceID, set->ifname, &set->ip);
12942 if (intf->InterfaceActive)
12943 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
12944 intf->InterfaceActive = mDNStrue;
12945 UpdateInterfaceProtocols(m, intf);
12946
12947 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
12948
12949 // See if another representative *of the same type* exists. If not, we mave have gone from
12950 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
12951 for (intf = m->HostInterfaces; intf; intf = intf->next)
12952 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
12953 break;
12954 if (!intf) revalidate = mDNStrue;
12955 }
12956 else
12957 {
12958 mDNSu32 slot;
12959 CacheGroup *cg;
12960 CacheRecord *rr;
12961 DNSQuestion *q;
12962
12963 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
12964 " marking questions etc. dormant", set->InterfaceID, set->ifname, &set->ip);
12965
12966 m->mDNSStats.InterfaceDown++;
12967
12968 if (set->McastTxRx && flapping)
12969 {
12970 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
12971 m->mDNSStats.InterfaceDownFlap++;
12972 }
12973
12974 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
12975 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
12976 for (q = m->Questions; q; q=q->next)
12977 {
12978 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
12979 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
12980 {
12981 q->FlappingInterface2 = q->FlappingInterface1;
12982 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
12983 }
12984 }
12985
12986 // 2. Flush any cache records received on this interface
12987 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
12988 FORALL_CACHERECORDS(slot, cg, rr)
12989 {
12990 if (rr->resrec.InterfaceID == set->InterfaceID)
12991 {
12992 // If this interface is deemed flapping,
12993 // postpone deleting the cache records in case the interface comes back again
12994 if (set->McastTxRx && flapping)
12995 {
12996 // For a flapping interface we want these record to go away after 30 seconds
12997 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
12998 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
12999 // if the interface does come back, any relevant questions will be reactivated anyway
13000 rr->UnansweredQueries = MaxUnansweredQueries;
13001 }
13002 else
13003 {
13004 mDNS_PurgeCacheResourceRecord(m, rr);
13005 }
13006 }
13007 }
13008 }
13009 }
13010
13011 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13012 if (set->Advertise) DeadvertiseInterface(m, set);
13013
13014 // If we have any cache records received on this interface that went away, then re-verify them.
13015 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13016 // giving the false impression that there's an active representative of this interface when there really isn't.
13017 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13018 if (revalidate && !m->ShutdownTime)
13019 {
13020 mDNSu32 slot;
13021 CacheGroup *cg;
13022 CacheRecord *rr;
13023 FORALL_CACHERECORDS(slot, cg, rr)
13024 if (rr->resrec.InterfaceID == set->InterfaceID)
13025 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13026 }
13027
13028 mDNS_UpdateAllowSleep(m);
13029
13030 mDNS_Unlock(m);
13031 }
13032
13033 mDNSlocal void SetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13034 {
13035 int i, len;
13036
13037 if (!sr->AnonData)
13038 return;
13039
13040 len = mDNSPlatformStrLen(sr->AnonData);
13041 if (sr->RR_PTR.resrec.AnonInfo)
13042 {
13043 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for PTR record %##s, should have been freed already", sr->RR_PTR.resrec.name->c);
13044 FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13045 }
13046 sr->RR_PTR.resrec.AnonInfo = AllocateAnonInfo(sr->RR_PTR.resrec.name, sr->AnonData, len, mDNSNULL);
13047 for (i=0; i<NumSubTypes; i++)
13048 {
13049 if (sr->SubTypes[i].resrec.AnonInfo)
13050 {
13051 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for subtype record %##s, should have been freed already", sr->SubTypes[i].resrec.name->c);
13052 FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13053 }
13054 sr->SubTypes[i].resrec.AnonInfo = AllocateAnonInfo(sr->SubTypes[i].resrec.name, sr->AnonData, len, mDNSNULL);
13055 }
13056 }
13057
13058 mDNSlocal void ResetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13059 {
13060 int i;
13061
13062 if (!sr->AnonData)
13063 return;
13064 if (sr->RR_PTR.resrec.AnonInfo)
13065 {
13066 FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13067 sr->RR_PTR.resrec.AnonInfo = mDNSNULL;
13068 }
13069 for (i=0; i<NumSubTypes; i++)
13070 {
13071 if (sr->SubTypes[i].resrec.AnonInfo)
13072 {
13073 FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13074 sr->SubTypes[i].resrec.AnonInfo = mDNSNULL;
13075 }
13076 }
13077 }
13078
13079 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13080 {
13081 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13082 (void)m; // Unused parameter
13083
13084 #if MDNS_DEBUGMSGS
13085 {
13086 char *msg = "Unknown result";
13087 if (result == mStatus_NoError) msg = "Name Registered";
13088 else if (result == mStatus_NameConflict) msg = "Name Conflict";
13089 else if (result == mStatus_MemFree) msg = "Memory Free";
13090 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13091 }
13092 #endif
13093
13094 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13095 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13096
13097 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13098 if (result == mStatus_NameConflict)
13099 {
13100 sr->Conflict = mDNStrue; // Record that this service set had a conflict
13101 mDNS_DeregisterService(m, sr); // Unlink the records from our list
13102 return;
13103 }
13104
13105 if (result == mStatus_MemFree)
13106 {
13107 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13108 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13109 // every record is finished cleaning up.
13110 mDNSu32 i;
13111 ExtraResourceRecord *e = sr->Extras;
13112
13113 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13114 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13115 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13116 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13117 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13118
13119 while (e)
13120 {
13121 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13122 e = e->next;
13123 }
13124 ResetAnonInfoSRS(sr, sr->NumSubTypes);
13125
13126 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13127 // then we can now report the NameConflict to the client
13128 if (sr->Conflict) result = mStatus_NameConflict;
13129
13130 }
13131
13132 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13133 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13134 // function is allowed to do anything, including deregistering this service and freeing its memory.
13135 if (sr->ServiceCallback)
13136 sr->ServiceCallback(m, sr, result);
13137 }
13138
13139 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13140 {
13141 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13142 if (sr->ServiceCallback)
13143 sr->ServiceCallback(m, sr, result);
13144 }
13145
13146
13147 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13148 {
13149 AuthRecType artype;
13150
13151 if (InterfaceID == mDNSInterface_LocalOnly)
13152 artype = AuthRecordLocalOnly;
13153 else if (InterfaceID == mDNSInterface_P2P)
13154 artype = AuthRecordP2P;
13155 else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeP2P)
13156 && (flags & coreFlagIncludeAWDL))
13157 artype = AuthRecordAnyIncludeAWDLandP2P;
13158 else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeP2P))
13159 artype = AuthRecordAnyIncludeP2P;
13160 else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeAWDL))
13161 artype = AuthRecordAnyIncludeAWDL;
13162 else
13163 artype = AuthRecordAny;
13164
13165 return artype;
13166 }
13167
13168 // Note:
13169 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13170 // Type is service type (e.g. "_ipp._tcp.")
13171 // Domain is fully qualified domain name (i.e. ending with a null label)
13172 // We always register a TXT, even if it is empty (so that clients are not
13173 // left waiting forever looking for a nonexistent record.)
13174 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13175 // then the default host name (m->MulticastHostname) is automatically used
13176 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13177 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13178 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13179 const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13180 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13181 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13182 {
13183 mStatus err;
13184 mDNSu32 i;
13185 mDNSu32 hostTTL;
13186 AuthRecType artype;
13187 mDNSu8 recordType = (flags & coreFlagKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13188
13189 sr->ServiceCallback = Callback;
13190 sr->ServiceContext = Context;
13191 sr->Conflict = mDNSfalse;
13192
13193 sr->Extras = mDNSNULL;
13194 sr->NumSubTypes = NumSubTypes;
13195 sr->SubTypes = SubTypes;
13196 sr->flags = flags;
13197
13198 artype = setAuthRecType(InterfaceID, flags);
13199
13200 // Initialize the AuthRecord objects to sane values
13201 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13202 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13203 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13204
13205 if (flags & coreFlagWakeOnly)
13206 {
13207 sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13208 }
13209
13210 if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
13211 hostTTL = kHostNameSmallTTL;
13212 else
13213 hostTTL = kHostNameTTL;
13214
13215 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
13216 mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13217
13218 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13219 if (mDNSIPPortIsZero(port))
13220 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13221
13222 // If the client is registering an oversized TXT record,
13223 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
13224 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13225 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13226
13227 // Set up the record names
13228 // For now we only create an advisory record for the main type, not for subtypes
13229 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13230 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13231 return(mStatus_BadParamErr);
13232 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13233 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13234 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13235
13236 // 1. Set up the ADV record rdata to advertise our service type
13237 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13238
13239 // 2. Set up the PTR record rdata to point to our service name
13240 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13241 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13242 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13243 sr->RR_PTR.Additional1 = &sr->RR_SRV;
13244 sr->RR_PTR.Additional2 = &sr->RR_TXT;
13245
13246 // 2a. Set up any subtype PTRs to point to our service name
13247 // If the client is using subtypes, it is the client's responsibility to have
13248 // already set the first label of the record name to the subtype being registered
13249 for (i=0; i<NumSubTypes; i++)
13250 {
13251 domainname st;
13252 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13253 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13254 AppendDomainName(&st, type);
13255 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13256 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13257 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13258 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13259 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13260 }
13261
13262 SetAnonInfoSRS(sr, NumSubTypes);
13263
13264 // 3. Set up the SRV record rdata.
13265 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13266 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
13267 sr->RR_SRV.resrec.rdata->u.srv.port = port;
13268
13269 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13270 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13271 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13272
13273 // 4. Set up the TXT record rdata,
13274 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13275 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13276 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13277 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13278 {
13279 sr->RR_TXT.resrec.rdlength = txtlen;
13280 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13281 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13282 }
13283 sr->RR_TXT.DependentOn = &sr->RR_SRV;
13284
13285 mDNS_Lock(m);
13286 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13287 // that if the SRV cannot find a target, rest of the records that belong to this service
13288 // will not be activated.
13289 err = mDNS_Register_internal(m, &sr->RR_SRV);
13290 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13291 // any list and hence no need to deregister. We could probably do similar checks for other
13292 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13293 if (err)
13294 {
13295 mDNS_Unlock(m);
13296 return err;
13297 }
13298 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13299 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13300 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13301 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13302 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13303 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13304 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13305 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13306 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13307
13308 mDNS_Unlock(m);
13309
13310 if (err) mDNS_DeregisterService(m, sr);
13311 return(err);
13312 }
13313
13314 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13315 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags)
13316 {
13317 ExtraResourceRecord **e;
13318 mStatus status;
13319 AuthRecType artype;
13320 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13321
13322 artype = setAuthRecType(InterfaceID, flags);
13323
13324 extra->next = mDNSNULL;
13325 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13326 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13327 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13328
13329 mDNS_Lock(m);
13330 e = &sr->Extras;
13331 while (*e) e = &(*e)->next;
13332
13333 if (ttl == 0) ttl = kStandardTTL;
13334
13335 extra->r.DependentOn = &sr->RR_SRV;
13336
13337 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13338 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13339
13340 status = mDNS_Register_internal(m, &extra->r);
13341 if (status == mStatus_NoError) *e = extra;
13342
13343 mDNS_Unlock(m);
13344 return(status);
13345 }
13346
13347 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13348 mDNSRecordCallback MemFreeCallback, void *Context)
13349 {
13350 ExtraResourceRecord **e;
13351 mStatus status;
13352
13353 mDNS_Lock(m);
13354 e = &sr->Extras;
13355 while (*e && *e != extra) e = &(*e)->next;
13356 if (!*e)
13357 {
13358 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13359 status = mStatus_BadReferenceErr;
13360 }
13361 else
13362 {
13363 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13364 extra->r.RecordCallback = MemFreeCallback;
13365 extra->r.RecordContext = Context;
13366 *e = (*e)->next;
13367 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13368 }
13369 mDNS_Unlock(m);
13370 return(status);
13371 }
13372
13373 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13374 {
13375 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13376 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13377 domainlabel name1, name2;
13378 domainname type, domain;
13379 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13380 ExtraResourceRecord *extras = sr->Extras;
13381 mStatus err;
13382
13383 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13384 if (!newname)
13385 {
13386 name2 = name1;
13387 IncrementLabelSuffix(&name2, mDNStrue);
13388 newname = &name2;
13389 }
13390
13391 if (SameDomainName(&domain, &localdomain))
13392 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13393 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13394
13395 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
13396 host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13397 sr->SubTypes, sr->NumSubTypes,
13398 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13399
13400 // mDNS_RegisterService() just reset sr->Extras to NULL.
13401 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13402 // through the old list of extra records, and re-add them to our freshly created service registration
13403 while (!err && extras)
13404 {
13405 ExtraResourceRecord *e = extras;
13406 extras = extras->next;
13407 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13408 }
13409
13410 return(err);
13411 }
13412
13413 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13414 // which may change the record list and/or question list.
13415 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13416 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13417 {
13418 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13419 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13420
13421 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13422 {
13423 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13424 return(mStatus_BadReferenceErr);
13425 }
13426 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13427 {
13428 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13429 // Avoid race condition:
13430 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13431 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13432 // If the client happens to deregister the service in the middle of that process, then
13433 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13434 // instead of incorrectly promoting it to mStatus_NameConflict.
13435 // This race condition is exposed particularly when the conformance test generates
13436 // a whole batch of simultaneous conflicts across a range of services all advertised
13437 // using the same system default name, and if we don't take this precaution then
13438 // we end up incrementing m->nicelabel multiple times instead of just once.
13439 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13440 sr->Conflict = mDNSfalse;
13441 return(mStatus_NoError);
13442 }
13443 else
13444 {
13445 mDNSu32 i;
13446 mStatus status;
13447 ExtraResourceRecord *e;
13448 mDNS_Lock(m);
13449 e = sr->Extras;
13450
13451 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13452 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13453 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13454 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13455
13456 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13457
13458 // We deregister all of the extra records, but we leave the sr->Extras list intact
13459 // in case the client wants to do a RenameAndReregister and reinstate the registration
13460 while (e)
13461 {
13462 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13463 e = e->next;
13464 }
13465
13466 for (i=0; i<sr->NumSubTypes; i++)
13467 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13468
13469 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13470 mDNS_Unlock(m);
13471 return(status);
13472 }
13473 }
13474
13475 // Create a registration that asserts that no such service exists with this name.
13476 // This can be useful where there is a given function is available through several protocols.
13477 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13478 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13479 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13480 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13481 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13482 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13483 const domainname *const host,
13484 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13485 {
13486 AuthRecType artype;
13487
13488 artype = setAuthRecType(InterfaceID, flags);
13489
13490 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13491 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13492 rr->resrec.rdata->u.srv.priority = 0;
13493 rr->resrec.rdata->u.srv.weight = 0;
13494 rr->resrec.rdata->u.srv.port = zeroIPPort;
13495 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13496 else rr->AutoTarget = Target_AutoHost;
13497 return(mDNS_Register(m, rr));
13498 }
13499
13500 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13501 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13502 {
13503 AuthRecType artype;
13504
13505 if (InterfaceID == mDNSInterface_LocalOnly)
13506 artype = AuthRecordLocalOnly;
13507 else if (InterfaceID == mDNSInterface_P2P)
13508 artype = AuthRecordP2P;
13509 else
13510 artype = AuthRecordAny;
13511 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13512 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13513 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13514 return(mDNS_Register(m, rr));
13515 }
13516
13517 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13518 {
13519 AuthRecord *r;
13520 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13521 return mDNSfalse;
13522 }
13523
13524 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13525 {
13526 DNSQuestion *q;
13527 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13528 return mDNSfalse;
13529 }
13530
13531 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13532 {
13533 mDNSOpaque16 id;
13534 int i;
13535
13536 for (i=0; i<10; i++)
13537 {
13538 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13539 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13540 }
13541
13542 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13543
13544 return id;
13545 }
13546
13547 // ***************************************************************************
13548 #if COMPILER_LIKES_PRAGMA_MARK
13549 #pragma mark -
13550 #pragma mark - Sleep Proxy Server
13551 #endif
13552
13553 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13554 {
13555 // If we see an ARP from a machine we think is sleeping, then either
13556 // (i) the machine has woken, or
13557 // (ii) it's just a stray old packet from before the machine slept
13558 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13559 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13560 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13561 // 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*
13562 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13563 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13564
13565 rr->resrec.RecordType = kDNSRecordTypeUnique;
13566 rr->ProbeCount = DefaultProbeCountForTypeUnique;
13567 rr->ProbeRestartCount++;
13568
13569 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13570 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13571 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13572 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13573 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13574 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13575 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13576 InitializeLastAPTime(m, rr);
13577 else
13578 {
13579 rr->AnnounceCount = InitialAnnounceCount;
13580 rr->ThisAPInterval = mDNSPlatformOneSecond;
13581 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13582 SetNextAnnounceProbeTime(m, rr);
13583 }
13584 }
13585
13586 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13587 {
13588 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13589 AuthRecord *rr;
13590 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13591 if (!intf) return;
13592
13593 mDNS_Lock(m);
13594
13595 // Pass 1:
13596 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13597 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13598 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13599 // The times we might need to react to an ARP Announcement are:
13600 // (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
13601 // (ii) if it's a conflicting Announcement from another host
13602 // -- and we check for these in Pass 2 below.
13603 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13604 {
13605 for (rr = m->ResourceRecords; rr; rr=rr->next)
13606 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13607 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13608 {
13609 static const char msg1[] = "ARP Req from owner -- re-probing";
13610 static const char msg2[] = "Ignoring ARP Request from ";
13611 static const char msg3[] = "Creating Local ARP Cache entry ";
13612 static const char msg4[] = "Answering ARP Request from ";
13613 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13614 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
13615 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
13616 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13617 intf->ifname, msg, &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13618 if (msg == msg1)
13619 {
13620 if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13621 RestartARPProbing(m, rr);
13622 else
13623 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13624 }
13625 else if (msg == msg3)
13626 {
13627 mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13628 }
13629 else if (msg == msg4)
13630 {
13631 SendARP(m, 2, rr, &arp->tpa, &arp->sha, &arp->spa, &arp->sha);
13632 }
13633 }
13634 }
13635
13636 // Pass 2:
13637 // 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.
13638 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13639 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13640 // 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.
13641 // If we see an apparently conflicting ARP, we check the sender hardware address:
13642 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13643 // 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.
13644 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
13645 debugf("ARP from self for %.4a", &arp->tpa);
13646 else
13647 {
13648 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
13649 for (rr = m->ResourceRecords; rr; rr=rr->next)
13650 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13651 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13652 {
13653 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13654 {
13655 LogSPS("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13656 &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13657 }
13658 else
13659 {
13660 RestartARPProbing(m, rr);
13661 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
13662 {
13663 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
13664 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
13665 &arp->sha, &arp->spa, &arp->tpa, ARDisplayString(m, rr));
13666 }
13667 else
13668 {
13669 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13670 &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13671 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
13672 }
13673 }
13674 }
13675 }
13676
13677 mDNS_Unlock(m);
13678 }
13679
13680 /*
13681 // Option 1 is Source Link Layer Address Option
13682 // Option 2 is Target Link Layer Address Option
13683 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
13684 {
13685 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
13686 while (options < end)
13687 {
13688 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
13689 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
13690 options += options[1] * 8;
13691 }
13692 return mDNSNULL;
13693 }
13694 */
13695
13696 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
13697 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
13698 {
13699 AuthRecord *rr;
13700 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13701 if (!intf) return;
13702
13703 mDNS_Lock(m);
13704
13705 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
13706 if (ndp->type == NDP_Sol)
13707 {
13708 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
13709 (void)end;
13710 for (rr = m->ResourceRecords; rr; rr=rr->next)
13711 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13712 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
13713 {
13714 static const char msg1[] = "NDP Req from owner -- re-probing";
13715 static const char msg2[] = "Ignoring NDP Request from ";
13716 static const char msg3[] = "Creating Local NDP Cache entry ";
13717 static const char msg4[] = "Answering NDP Request from ";
13718 static const char msg5[] = "Answering NDP Probe from ";
13719 const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
13720 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
13721 sha && mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
13722 spa && mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
13723 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
13724 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13725 if (msg == msg1)
13726 {
13727 if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13728 RestartARPProbing(m, rr);
13729 else
13730 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13731 }
13732 else if (msg == msg3)
13733 mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13734 else if (msg == msg4)
13735 SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
13736 else if (msg == msg5)
13737 SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
13738 }
13739 }
13740
13741 // 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.
13742 if (mDNSSameEthAddress(sha, &intf->MAC))
13743 debugf("NDP from self for %.16a", &ndp->target);
13744 else
13745 {
13746 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
13747 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
13748 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
13749 // Hence it is the NDP target address we care about, not the actual packet source address.
13750 if (ndp->type == NDP_Adv) spa = &ndp->target;
13751 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
13752 for (rr = m->ResourceRecords; rr; rr=rr->next)
13753 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13754 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13755 {
13756 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13757 {
13758 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13759 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13760 }
13761 else
13762 {
13763 RestartARPProbing(m, rr);
13764 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
13765 {
13766 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
13767 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
13768 }
13769 else
13770 {
13771 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13772 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13773 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
13774 }
13775 }
13776 }
13777 }
13778
13779 mDNS_Unlock(m);
13780 }
13781
13782 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
13783 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
13784 {
13785 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
13786 mDNSBool wake = mDNSfalse;
13787 mDNSBool kaWake = mDNSfalse;
13788
13789 switch (protocol)
13790 {
13791 #define XX wake ? "Received" : "Ignoring", end-p
13792 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
13793 break;
13794
13795 case 0x06: {
13796 AuthRecord *kr;
13797 mDNSu32 seq, ack;
13798 #define TH_FIN 0x01
13799 #define TH_SYN 0x02
13800 #define TH_RST 0x04
13801 #define TH_ACK 0x10
13802
13803 kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
13804 if (kr)
13805 {
13806 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
13807 // Plan to wake if
13808 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
13809 // (b) packet that contains new data and acks a sequence number higher than the one
13810 // we have been sending in the keepalive
13811
13812 wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
13813 if (!wake)
13814 {
13815 mDNSu8 *ptr;
13816 mDNSu32 pseq, pack;
13817 mDNSBool data = mDNSfalse;
13818 mDNSu8 tcphlen;
13819
13820 // Convert to host order
13821 ptr = (mDNSu8 *)&seq;
13822 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13823
13824 ptr = (mDNSu8 *)&ack;
13825 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13826
13827 pseq = t->tcp.seq;
13828 ptr = (mDNSu8 *)&pseq;
13829 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13830
13831 pack = t->tcp.ack;
13832 ptr = (mDNSu8 *)&pack;
13833 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13834
13835 // If the other side is acking one more than our sequence number (keepalive is one
13836 // less than the last valid sequence sent) and it's sequence is more than what we
13837 // acked before
13838 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
13839 tcphlen = ((t->tcp.offset >> 4) * 4);
13840 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
13841 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
13842
13843 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
13844 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
13845 ((int)(ack - pseq) == 1))
13846 {
13847 // Send an ACK;
13848 mDNS_SendKeepaliveACK(m, kr);
13849 }
13850 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
13851 end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
13852 }
13853 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
13854 kaWake = wake;
13855 }
13856 else
13857 {
13858 // Plan to wake if
13859 // (a) RST is not set, AND
13860 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
13861 wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
13862
13863 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
13864 // except for ssh connections, where we'll wake for plain data packets too
13865 if (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
13866
13867 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
13868 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
13869 (t->tcp.flags & 2) ? " SYN" : "",
13870 (t->tcp.flags & 1) ? " FIN" : "",
13871 (t->tcp.flags & 4) ? " RST" : "");
13872 }
13873 break;
13874 }
13875
13876 case 0x11: {
13877 #define ARD_AsNumber 3283
13878 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
13879 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
13880 if (udplen >= sizeof(UDPHeader))
13881 {
13882 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
13883 wake = mDNStrue;
13884
13885 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
13886 if (mDNSSameIPPort(port, IPSECPort))
13887 {
13888 // Specifically ignore NAT keepalive packets
13889 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
13890 else
13891 {
13892 // Skip over the Non-ESP Marker if present
13893 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
13894 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
13895 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
13896 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
13897 if ((ike->Version & 0x10) == 0x10)
13898 {
13899 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
13900 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
13901 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
13902 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
13903 }
13904 }
13905 }
13906
13907 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
13908 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
13909 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
13910 // UDP header (8 bytes)
13911 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
13912 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
13913
13914 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
13915 }
13916 }
13917 break;
13918
13919 case 0x3A: if (&t->bytes[len] <= end)
13920 {
13921 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
13922 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
13923 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
13924 }
13925 break;
13926
13927 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
13928 break;
13929 }
13930
13931 if (wake)
13932 {
13933 AuthRecord *rr, *r2;
13934
13935 mDNS_Lock(m);
13936 for (rr = m->ResourceRecords; rr; rr=rr->next)
13937 if (rr->resrec.InterfaceID == InterfaceID &&
13938 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13939 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
13940 {
13941 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
13942 for (r2 = m->ResourceRecords; r2; r2=r2->next)
13943 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
13944 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
13945 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
13946 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
13947 break;
13948 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
13949 if (!r2 && kaWake) r2 = rr; // So that we wake for keepalive packets, even without a matching SRV record
13950 if (r2)
13951 {
13952 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
13953 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
13954 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
13955 }
13956 else
13957 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
13958 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
13959 }
13960 mDNS_Unlock(m);
13961 }
13962 }
13963
13964 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
13965 {
13966 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
13967 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
13968 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
13969 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
13970 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
13971
13972 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
13973 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
13974 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
13975 // since it points to a an address 14 bytes before pkt.
13976 const EthernetHeader *const eth = (const EthernetHeader *)p;
13977 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
13978 mDNSAddr src, dst;
13979 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
13980
13981 // Is ARP? Length must be at least 14 + 28 = 42 bytes
13982 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
13983 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
13984 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
13985 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
13986 {
13987 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
13988 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
13989 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
13990 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
13991 if (end >= trans + RequiredCapLen(pkt->v4.protocol))
13992 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, end, InterfaceID, 0);
13993 }
13994 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
13995 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
13996 {
13997 const mDNSu8 *const trans = p + 54;
13998 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
13999 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14000 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14001 if (end >= trans + RequiredCapLen(pkt->v6.pro))
14002 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14003 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14004 }
14005 }
14006
14007 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14008 {
14009 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14010 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14011 }
14012
14013 #ifndef SPC_DISABLED
14014 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14015 {
14016 if (result == mStatus_NameConflict)
14017 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14018 else if (result == mStatus_MemFree)
14019 {
14020 if (m->SleepState)
14021 m->SPSState = 3;
14022 else
14023 {
14024 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14025 if (m->SPSState)
14026 {
14027 domainlabel name;
14028 ConstructSleepProxyServerName(m, &name);
14029 mDNS_RegisterService(m, srs,
14030 &name, &SleepProxyServiceType, &localdomain,
14031 mDNSNULL, m->SPSSocket->port, // Host, port
14032 (mDNSu8 *)"", 1, // TXT data, length
14033 mDNSNULL, 0, // Subtypes (none)
14034 mDNSInterface_Any, // Interface ID
14035 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14036 }
14037 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14038 }
14039 }
14040 }
14041 #endif
14042
14043 // Called with lock held
14044 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14045 {
14046 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14047 mDNS_DropLockBeforeCallback();
14048
14049 // If turning off SPS, close our socket
14050 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14051 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14052
14053 // If turning off, or changing type, deregister old name
14054 #ifndef SPC_DISABLED
14055 if (m->SPSState == 1 && sps != m->SPSType)
14056 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14057 #endif // SPC_DISABLED
14058
14059 // Record our new SPS parameters
14060 m->SPSType = sps;
14061 m->SPSPortability = port;
14062 m->SPSMarginalPower = marginalpower;
14063 m->SPSTotalPower = totpower;
14064 m->SPSFeatureFlags = features;
14065 // If turning on, open socket and advertise service
14066 if (sps)
14067 {
14068 if (!m->SPSSocket)
14069 {
14070 m->SPSSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
14071 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14072 }
14073 #ifndef SPC_DISABLED
14074 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14075 #endif // SPC_DISABLED
14076 }
14077 else if (m->SPSState)
14078 {
14079 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14080 m->NextScheduledSPS = m->timenow;
14081 }
14082 fail:
14083 mDNS_ReclaimLockAfterCallback();
14084 }
14085
14086 // ***************************************************************************
14087 #if COMPILER_LIKES_PRAGMA_MARK
14088 #pragma mark -
14089 #pragma mark - Startup and Shutdown
14090 #endif
14091
14092 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14093 {
14094 if (storage && numrecords)
14095 {
14096 mDNSu32 i;
14097 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14098 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14099 storage[numrecords-1].next = m->rrcache_free;
14100 m->rrcache_free = storage;
14101 m->rrcache_size += numrecords;
14102 }
14103 }
14104
14105 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14106 {
14107 mDNS_Lock(m);
14108 mDNS_GrowCache_internal(m, storage, numrecords);
14109 mDNS_Unlock(m);
14110 }
14111
14112 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14113 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14114 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14115 {
14116 mDNSu32 slot;
14117 mDNSs32 timenow;
14118 mStatus result;
14119
14120 if (!rrcachestorage) rrcachesize = 0;
14121
14122 m->p = p;
14123 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14124 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
14125 m->DivertMulticastAdvertisements = mDNSfalse;
14126 m->mDNSPlatformStatus = mStatus_Waiting;
14127 m->UnicastPort4 = zeroIPPort;
14128 m->UnicastPort6 = zeroIPPort;
14129 m->PrimaryMAC = zeroEthAddr;
14130 m->MainCallback = Callback;
14131 m->MainContext = Context;
14132 m->rec.r.resrec.RecordType = 0;
14133 m->rec.r.resrec.AnonInfo = mDNSNULL;
14134
14135 // For debugging: To catch and report locking failures
14136 m->mDNS_busy = 0;
14137 m->mDNS_reentrancy = 0;
14138 m->ShutdownTime = 0;
14139 m->lock_rrcache = 0;
14140 m->lock_Questions = 0;
14141 m->lock_Records = 0;
14142
14143 // Task Scheduling variables
14144 result = mDNSPlatformTimeInit();
14145 if (result != mStatus_NoError) return(result);
14146 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14147 timenow = mDNS_TimeNow_NoLock(m);
14148
14149 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14150 m->timenow_last = timenow;
14151 m->NextScheduledEvent = timenow;
14152 m->SuppressSending = timenow;
14153 m->NextCacheCheck = timenow + 0x78000000;
14154 m->NextScheduledQuery = timenow + 0x78000000;
14155 m->NextScheduledProbe = timenow + 0x78000000;
14156 m->NextScheduledResponse = timenow + 0x78000000;
14157 m->NextScheduledNATOp = timenow + 0x78000000;
14158 m->NextScheduledSPS = timenow + 0x78000000;
14159 m->NextScheduledKA = timenow + 0x78000000;
14160 m->NextScheduledStopTime = timenow + 0x78000000;
14161 m->RandomQueryDelay = 0;
14162 m->RandomReconfirmDelay = 0;
14163 m->PktNum = 0;
14164 m->MPktNum = 0;
14165 m->LocalRemoveEvents = mDNSfalse;
14166 m->SleepState = SleepState_Awake;
14167 m->SleepSeqNum = 0;
14168 m->SystemWakeOnLANEnabled = mDNSfalse;
14169 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14170 m->DelaySleep = 0;
14171 m->SleepLimit = 0;
14172
14173 #if APPLE_OSX_mDNSResponder
14174 m->StatStartTime = mDNSPlatformUTC();
14175 m->NextStatLogTime = m->StatStartTime + kDefaultNextStatsticsLogTime;
14176 m->ActiveStatTime = 0;
14177 m->UnicastPacketsSent = 0;
14178 m->MulticastPacketsSent = 0;
14179 m->RemoteSubnet = 0;
14180 #endif // APPLE_OSX_mDNSResponder
14181
14182 // These fields only required for mDNS Searcher...
14183 m->Questions = mDNSNULL;
14184 m->NewQuestions = mDNSNULL;
14185 m->CurrentQuestion = mDNSNULL;
14186 m->LocalOnlyQuestions = mDNSNULL;
14187 m->NewLocalOnlyQuestions = mDNSNULL;
14188 m->RestartQuestion = mDNSNULL;
14189 m->ValidationQuestion = mDNSNULL;
14190 m->rrcache_size = 0;
14191 m->rrcache_totalused = 0;
14192 m->rrcache_active = 0;
14193 m->rrcache_report = 10;
14194 m->rrcache_free = mDNSNULL;
14195
14196 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14197 {
14198 m->rrcache_hash[slot] = mDNSNULL;
14199 m->rrcache_nextcheck[slot] = timenow + 0x78000000;;
14200 }
14201
14202 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14203 m->rrauth.rrauth_free = mDNSNULL;
14204
14205 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14206 m->rrauth.rrauth_hash[slot] = mDNSNULL;
14207
14208 // Fields below only required for mDNS Responder...
14209 m->hostlabel.c[0] = 0;
14210 m->nicelabel.c[0] = 0;
14211 m->MulticastHostname.c[0] = 0;
14212 m->HIHardware.c[0] = 0;
14213 m->HISoftware.c[0] = 0;
14214 m->ResourceRecords = mDNSNULL;
14215 m->DuplicateRecords = mDNSNULL;
14216 m->NewLocalRecords = mDNSNULL;
14217 m->NewLocalOnlyRecords = mDNSfalse;
14218 m->CurrentRecord = mDNSNULL;
14219 m->HostInterfaces = mDNSNULL;
14220 m->ProbeFailTime = 0;
14221 m->NumFailedProbes = 0;
14222 m->SuppressProbes = 0;
14223
14224 #ifndef UNICAST_DISABLED
14225 m->NextuDNSEvent = timenow + 0x78000000;
14226 m->NextSRVUpdate = timenow + 0x78000000;
14227
14228 m->DNSServers = mDNSNULL;
14229
14230 m->Router = zeroAddr;
14231 m->AdvertisedV4 = zeroAddr;
14232 m->AdvertisedV6 = zeroAddr;
14233
14234 m->AuthInfoList = mDNSNULL;
14235
14236 m->ReverseMap.ThisQInterval = -1;
14237 m->StaticHostname.c[0] = 0;
14238 m->FQDN.c[0] = 0;
14239 m->Hostnames = mDNSNULL;
14240 m->AutoTunnelNAT.clientContext = mDNSNULL;
14241
14242 m->WABBrowseQueriesCount = 0;
14243 m->WABLBrowseQueriesCount = 0;
14244 m->WABRegQueriesCount = 0;
14245 #if !TARGET_OS_EMBEDDED
14246 m->mDNSOppCaching = mDNStrue;
14247 #else
14248 m->mDNSOppCaching = mDNSfalse;
14249 #endif
14250 m->AutoTargetServices = 0;
14251
14252 // NAT traversal fields
14253 m->LLQNAT.clientCallback = mDNSNULL;
14254 m->LLQNAT.clientContext = mDNSNULL;
14255 m->NATTraversals = mDNSNULL;
14256 m->CurrentNATTraversal = mDNSNULL;
14257 m->retryIntervalGetAddr = 0; // delta between time sent and retry
14258 m->retryGetAddr = timenow + 0x78000000; // absolute time when we retry
14259 m->ExtAddress = zerov4Addr;
14260 m->PCPNonce[0] = mDNSRandom(-1);
14261 m->PCPNonce[1] = mDNSRandom(-1);
14262 m->PCPNonce[2] = mDNSRandom(-1);
14263
14264 m->NATMcastRecvskt = mDNSNULL;
14265 m->LastNATupseconds = 0;
14266 m->LastNATReplyLocalTime = timenow;
14267 m->LastNATMapResultCode = NATErr_None;
14268
14269 m->UPnPInterfaceID = 0;
14270 m->SSDPSocket = mDNSNULL;
14271 m->SSDPWANPPPConnection = mDNSfalse;
14272 m->UPnPRouterPort = zeroIPPort;
14273 m->UPnPSOAPPort = zeroIPPort;
14274 m->UPnPRouterURL = mDNSNULL;
14275 m->UPnPWANPPPConnection = mDNSfalse;
14276 m->UPnPSOAPURL = mDNSNULL;
14277 m->UPnPRouterAddressString = mDNSNULL;
14278 m->UPnPSOAPAddressString = mDNSNULL;
14279 m->SPSType = 0;
14280 m->SPSPortability = 0;
14281 m->SPSMarginalPower = 0;
14282 m->SPSTotalPower = 0;
14283 m->SPSFeatureFlags = 0;
14284 m->SPSState = 0;
14285 m->SPSProxyListChanged = mDNSNULL;
14286 m->SPSSocket = mDNSNULL;
14287 m->SPSBrowseCallback = mDNSNULL;
14288 m->ProxyRecords = 0;
14289
14290 #endif
14291
14292 #if APPLE_OSX_mDNSResponder
14293 m->TunnelClients = mDNSNULL;
14294
14295 #if !NO_WCF
14296 CHECK_WCF_FUNCTION(WCFConnectionNew)
14297 {
14298 m->WCF = WCFConnectionNew();
14299 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14300 }
14301 #endif
14302
14303 #endif
14304
14305 result = mDNSPlatformInit(m);
14306
14307 #ifndef UNICAST_DISABLED
14308 // It's better to do this *after* the platform layer has set up the
14309 // interface list and security credentials
14310 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
14311 #endif
14312
14313 return(result);
14314 }
14315
14316 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14317 {
14318 if (m->SPSState == 1)
14319 {
14320 domainlabel name, newname;
14321 #ifndef SPC_DISABLED
14322 domainname type, domain;
14323 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14324 #endif // SPC_DISABLED
14325 ConstructSleepProxyServerName(m, &newname);
14326 if (!SameDomainLabelCS(name.c, newname.c))
14327 {
14328 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14329 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14330 // it will reregister the service under the new name
14331 m->SPSState = 2;
14332 #ifndef SPC_DISABLED
14333 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14334 #endif // SPC_DISABLED
14335 }
14336 }
14337
14338 if (m->MainCallback)
14339 m->MainCallback(m, mStatus_ConfigChanged);
14340 }
14341
14342 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14343 {
14344 (void)m; // unused
14345 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14346 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14347 }
14348
14349 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
14350 {
14351 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14352 cr->resrec.rrtype == kDNSType_A ||
14353 cr->resrec.rrtype == kDNSType_AAAA ||
14354 cr->resrec.rrtype == kDNSType_SRV;
14355
14356 (void) lameduck;
14357 (void) ptr;
14358 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
14359 purge ? "purging" : "reconfirming",
14360 lameduck ? "lame duck" : "new",
14361 ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
14362
14363 if (purge)
14364 {
14365 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14366 mDNS_PurgeCacheResourceRecord(m, cr);
14367 }
14368 else
14369 {
14370 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14371 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14372 }
14373 }
14374
14375 mDNSlocal void mDNS_PurgeForQuestion(mDNS *const m, DNSQuestion *q)
14376 {
14377 const mDNSu32 slot = HashSlot(&q->qname);
14378 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
14379 CacheRecord *rp;
14380 mDNSu8 validatingResponse = 0;
14381
14382 // For DNSSEC questions, purge the corresponding RRSIGs also.
14383 if (DNSSECQuestion(q))
14384 {
14385 validatingResponse = q->ValidatingResponse;
14386 q->ValidatingResponse = mDNStrue;
14387 }
14388 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14389 {
14390 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14391 {
14392 LogInfo("mDNS_PurgeForQuestion: Flushing %s", CRDisplayString(m, rp));
14393 mDNS_PurgeCacheResourceRecord(m, rp);
14394 }
14395 }
14396 if (DNSSECQuestion(q))
14397 {
14398 q->ValidatingResponse = validatingResponse;
14399 }
14400 }
14401
14402 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14403 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14404 // Just re-issuing the question for RRSIGs does not work in practice as the response
14405 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14406 //
14407 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14408 // have the cached NSECs, purge them. For positive responses, if we don't have the
14409 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14410 // them.
14411 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q)
14412 {
14413 const mDNSu32 slot = HashSlot(&q->qname);
14414 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
14415 CacheRecord *rp;
14416
14417 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14418 {
14419 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14420 {
14421 if (rp->resrec.RecordType != kDNSRecordTypePacketNegative || !rp->nsec)
14422 {
14423 if (!rp->CRDNSSECQuestion)
14424 {
14425 LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m, rp));
14426 mDNS_PurgeCacheResourceRecord(m, rp);
14427 }
14428 }
14429 }
14430 }
14431 }
14432
14433 // Check for a positive unicast response to the question but with qtype
14434 mDNSexport mDNSBool mDNS_CheckForCacheRecord(mDNS *const m, DNSQuestion *q, mDNSu16 qtype)
14435 {
14436 DNSQuestion question;
14437 const mDNSu32 slot = HashSlot(&q->qname);
14438 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
14439 CacheRecord *rp;
14440
14441 // Create an identical question but with qtype
14442 mDNS_SetupQuestion(&question, q->InterfaceID, &q->qname, qtype, mDNSNULL, mDNSNULL);
14443 question.qDNSServer = q->qDNSServer;
14444
14445 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14446 {
14447 if (!rp->resrec.InterfaceID && rp->resrec.RecordType != kDNSRecordTypePacketNegative &&
14448 SameNameRecordAnswersQuestion(&rp->resrec, &question))
14449 {
14450 LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m, rp));
14451 return mDNStrue;
14452 }
14453 }
14454 return mDNSfalse;
14455 }
14456
14457 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14458 {
14459 DNSQuestion *qptr;
14460
14461 (void) m;
14462
14463 if (q->DuplicateOf)
14464 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14465
14466 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14467 // of events for all of them are consistent. Duplicates for a question are always inserted
14468 // after in the list.
14469 q->qDNSServer = new;
14470 for (qptr = q->next ; qptr; qptr = qptr->next)
14471 {
14472 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14473 }
14474 }
14475
14476 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14477 {
14478 McastResolver *mr;
14479 DNSServer *ptr;
14480
14481 if (delete)
14482 {
14483 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14484 {
14485 ptr->penaltyTime = 0;
14486 NumUnicastDNSServers--;
14487 ptr->flags |= DNSServer_FlagDelete;
14488 }
14489 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14490 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14491 // API
14492 for (mr = m->McastResolvers; mr; mr = mr->next)
14493 mr->flags |= McastResolver_FlagDelete;
14494 }
14495 else
14496 {
14497 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14498 {
14499 ptr->penaltyTime = 0;
14500 NumUnicastDNSServers++;
14501 ptr->flags &= ~DNSServer_FlagDelete;
14502 }
14503 for (mr = m->McastResolvers; mr; mr = mr->next)
14504 mr->flags &= ~McastResolver_FlagDelete;
14505 }
14506 }
14507
14508 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14509 {
14510 mDNSu32 slot;
14511 CacheGroup *cg;
14512 CacheRecord *cr;
14513 mDNSBool Restart = mDNSfalse;
14514 mDNSAddr v4, v6, r;
14515 domainname fqdn;
14516 DNSServer *ptr, **p = &m->DNSServers;
14517 const DNSServer *oldServers = m->DNSServers;
14518 DNSQuestion *q;
14519 McastResolver *mr, **mres = &m->McastResolvers;
14520
14521 debugf("uDNS_SetupDNSConfig: entry");
14522
14523 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14524 uDNS_SetupWABQueries(m);
14525
14526 mDNS_Lock(m);
14527
14528 // We need to first mark all the entries to be deleted. If the configuration changed, then
14529 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14530 //
14531 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14532 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14533 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14534 // for the dns configuration change notification.
14535 SetConfigState(m, mDNStrue);
14536 if (!mDNSPlatformSetDNSConfig(m, mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14537 {
14538 SetConfigState(m, mDNSfalse);
14539 mDNS_Unlock(m);
14540 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14541 return mStatus_NoError;
14542 }
14543
14544 // For now, we just delete the mcast resolvers. We don't deal with cache or
14545 // questions here. Neither question nor cache point to mcast resolvers. Questions
14546 // do inherit the timeout values from mcast resolvers. But we don't bother
14547 // affecting them as they never change.
14548 while (*mres)
14549 {
14550 if (((*mres)->flags & DNSServer_FlagDelete) != 0)
14551 {
14552 mr = *mres;
14553 *mres = (*mres)->next;
14554 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14555 mDNSPlatformMemFree(mr);
14556 }
14557 else
14558 {
14559 (*mres)->flags &= ~McastResolver_FlagNew;
14560 mres = &(*mres)->next;
14561 }
14562 }
14563
14564 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14565 //
14566 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14567 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14568 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14569 // DNSServers and flush the cache.
14570 //
14571 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14572 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14573 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14574 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14575 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14576 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14577 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14578 // the same resGroupID.
14579 //
14580 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14581 // of the old followed by ADD of the new records.
14582 //
14583 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14584 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14585 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14586 //
14587 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14588 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14589 // non-scoped question and vice versa.
14590 //
14591 for (q = m->Questions; q; q=q->next)
14592 {
14593 if (!mDNSOpaque16IsZero(q->TargetQID))
14594 {
14595 DNSServer *s, *t;
14596 DNSQuestion *qptr;
14597 if (q->DuplicateOf) continue;
14598 SetValidDNSServers(m, q);
14599 q->triedAllServersOnce = 0;
14600 s = GetServerForQuestion(m, q);
14601 t = q->qDNSServer;
14602 if (t != s)
14603 {
14604 mDNSBool old, new;
14605 // If DNS Server for this question has changed, reactivate it
14606 LogInfo("uDNS_SetupDNSConfig: Updating DNS Server from %#a:%d (%##s) to %#a:%d (%##s) for question %##s (%s) (scope:%p)",
14607 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
14608 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
14609 q->qname.c, DNSTypeName(q->qtype), q->InterfaceID);
14610
14611 old = q->SuppressQuery;
14612 new = ShouldSuppressUnicastQuery(m, q, s);
14613 if (old != new)
14614 {
14615 // Changing the DNS server affected the SuppressQuery status. We need to
14616 // deliver RMVs for the previous ADDs (if any) before switching to the new
14617 // DNSServer. To keep it simple, we walk all the questions and mark them
14618 // to be restarted and then handle all of them at once.
14619 q->Restart = 1;
14620 q->SuppressQuery = new;
14621 for (qptr = q->next ; qptr; qptr = qptr->next)
14622 {
14623 if (qptr->DuplicateOf == q)
14624 qptr->Restart = 1;
14625 }
14626 Restart = mDNStrue;
14627 }
14628 else
14629 {
14630 DNSServerChangeForQuestion(m, q, s);
14631 q->unansweredQueries = 0;
14632
14633 // If we had sent a query out to DNSServer "t" and we are changing to "s", we
14634 // need to ignore the responses coming back from "t" as the DNS configuration
14635 // has changed e.g., when a new interface is coming up and that becomes the primary
14636 // interface, we switch to the DNS servers configured for the primary interface. In
14637 // this case, we should not accept responses associated with the previous interface as
14638 // the "name" could resolve differently on this new primary interface. Hence, discard
14639 // in-flight responses.
14640 q->TargetQID = mDNS_NewMessageID(m);
14641
14642 if (!QuerySuppressed(q))
14643 {
14644 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
14645 ActivateUnicastQuery(m, q, mDNStrue);
14646 // ActivateUnicastQuery is called for duplicate questions also as it does something
14647 // special for AutoTunnel questions
14648 for (qptr = q->next ; qptr; qptr = qptr->next)
14649 {
14650 if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
14651 }
14652 }
14653 }
14654 }
14655 else
14656 {
14657 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
14658 q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
14659 for (qptr = q->next ; qptr; qptr = qptr->next)
14660 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
14661 }
14662 }
14663 }
14664 if (Restart)
14665 RestartUnicastQuestions(m);
14666
14667 FORALL_CACHERECORDS(slot, cg, cr)
14668 {
14669 if (cr->resrec.InterfaceID)
14670 continue;
14671
14672 // We already walked the questions and restarted/reactivated them if the dns server
14673 // change affected the question. That should take care of updating the cache. But
14674 // what if there is no active question at this point when the DNS server change
14675 // happened ? There could be old cache entries lying around and if we don't flush
14676 // them, a new question after the DNS server change could pick up these stale
14677 // entries and get a wrong answer.
14678 //
14679 // For cache entries that have active questions we might have skipped rescheduling
14680 // the questions if they were suppressed (see above). To keep it simple, we walk
14681 // all the cache entries to make sure that there are no stale entries. We use the
14682 // active question's InterfaceID/ServiceID for looking up the right DNS server.
14683 // Note that the unscoped value for ServiceID is -1.
14684 //
14685 // Note: If GetServerForName returns NULL, it could either mean that there are no
14686 // DNS servers or no matching DNS servers for this question. In either case,
14687 // the cache should get purged below when we process deleted DNS servers.
14688
14689 ptr = GetServerForName(m, cr->resrec.name,
14690 (cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL),
14691 (cr->CRActiveQuestion ? cr->CRActiveQuestion->ServiceID : -1));
14692
14693 // Purge or Reconfirm if this cache entry would use the new DNS server
14694 if (ptr && (ptr != cr->resrec.rDNSServer))
14695 {
14696 // As the DNSServers for this cache record is not the same anymore, we don't
14697 // want any new questions to pick this old value. If there is no active question,
14698 // we can't possibly re-confirm, so purge in that case. If it is a DNSSEC question,
14699 // purge the cache as the DNSSEC capabilities of the DNS server may have changed.
14700
14701 if (cr->CRActiveQuestion == mDNSNULL || DNSSECQuestion(cr->CRActiveQuestion))
14702 {
14703 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s, New DNS server %#a , Old DNS server %#a", CRDisplayString(m, cr),
14704 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
14705 mDNS_PurgeCacheResourceRecord(m, cr);
14706 }
14707 else
14708 {
14709 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", CRDisplayString(m, cr),
14710 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
14711 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
14712 }
14713 }
14714 }
14715
14716 while (*p)
14717 {
14718 if (((*p)->flags & DNSServer_FlagDelete) != 0)
14719 {
14720 // Scan our cache, looking for uDNS records that we would have queried this server for.
14721 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
14722 // different DNS servers can give different answers to the same question.
14723 ptr = *p;
14724 FORALL_CACHERECORDS(slot, cg, cr)
14725 {
14726 if (cr->resrec.InterfaceID) continue;
14727 if (cr->resrec.rDNSServer == ptr)
14728 {
14729 // If we don't have an active question for this cache record, neither Purge can
14730 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
14731 // pointer on the record NULL so that we don't point to freed memory (We might dereference
14732 // DNSServer pointers from resource record for logging purposes).
14733 //
14734 // If there is an active question, point to its DNSServer as long as it does not point to the
14735 // freed one. We already went through the questions above and made them point at either the
14736 // new server or NULL if there is no server.
14737
14738 if (cr->CRActiveQuestion)
14739 {
14740 DNSQuestion *qptr = cr->CRActiveQuestion;
14741
14742 if (qptr->qDNSServer == ptr)
14743 {
14744 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) poining to DNSServer Address %#a"
14745 " to be freed", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID, &ptr->addr);
14746 qptr->validDNSServers = zeroOpaque64;
14747 qptr->qDNSServer = mDNSNULL;
14748 cr->resrec.rDNSServer = mDNSNULL;
14749 }
14750 else
14751 {
14752 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
14753 " resetting to question's DNSServer Address %#a", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype),
14754 qptr->InterfaceID, &ptr->addr, (qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL));
14755 cr->resrec.rDNSServer = qptr->qDNSServer;
14756 }
14757 }
14758 else
14759 {
14760 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
14761 cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
14762 cr->resrec.rDNSServer = mDNSNULL;
14763 }
14764
14765 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
14766 }
14767 }
14768 *p = (*p)->next;
14769 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s) %d", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, NumUnicastDNSServers);
14770 mDNSPlatformMemFree(ptr);
14771 }
14772 else
14773 {
14774 (*p)->flags &= ~DNSServer_FlagNew;
14775 p = &(*p)->next;
14776 }
14777 }
14778
14779 // 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).
14780 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
14781 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
14782 // 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.
14783 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
14784 {
14785 int count = 0;
14786 FORALL_CACHERECORDS(slot, cg, cr)
14787 {
14788 if (!cr->resrec.InterfaceID)
14789 {
14790 mDNS_PurgeCacheResourceRecord(m, cr);
14791 count++;
14792 }
14793 }
14794 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
14795 m->DNSServers ? "DNS server became" : "No DNS servers", count);
14796
14797 // Force anything that needs to get zone data to get that information again
14798 RestartRecordGetZoneData(m);
14799 }
14800
14801 // Did our FQDN change?
14802 if (!SameDomainName(&fqdn, &m->FQDN))
14803 {
14804 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14805
14806 AssignDomainName(&m->FQDN, &fqdn);
14807
14808 if (m->FQDN.c[0])
14809 {
14810 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14811 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14812 }
14813 }
14814
14815 mDNS_Unlock(m);
14816
14817 // handle router and primary interface changes
14818 v4 = v6 = r = zeroAddr;
14819 v4.type = r.type = mDNSAddrType_IPv4;
14820
14821 if (mDNSPlatformGetPrimaryInterface(m, &v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
14822 {
14823 mDNS_SetPrimaryInterfaceInfo(m,
14824 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
14825 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
14826 !mDNSIPv4AddressIsZero(r.ip.v4) ? &r : mDNSNULL);
14827 }
14828 else
14829 {
14830 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
14831 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
14832 }
14833
14834 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
14835 return mStatus_NoError;
14836 }
14837
14838 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
14839 {
14840 m->mDNSPlatformStatus = result;
14841 if (m->MainCallback)
14842 {
14843 mDNS_Lock(m);
14844 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
14845 m->MainCallback(m, mStatus_NoError);
14846 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
14847 mDNS_Unlock(m);
14848 }
14849 }
14850
14851 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
14852 {
14853 m->CurrentRecord = start;
14854 while (m->CurrentRecord)
14855 {
14856 AuthRecord *rr = m->CurrentRecord;
14857 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
14858 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
14859 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
14860 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
14861 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
14862 else if (rr->AnnounceCount > 1)
14863 {
14864 rr->AnnounceCount = 1;
14865 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
14866 }
14867 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
14868 // new records could have been added to the end of the list as a result of that call.
14869 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
14870 m->CurrentRecord = rr->next;
14871 }
14872 }
14873
14874 mDNSexport void mDNS_StartExit(mDNS *const m)
14875 {
14876 NetworkInterfaceInfo *intf;
14877 AuthRecord *rr;
14878
14879 mDNS_Lock(m);
14880
14881 LogInfo("mDNS_StartExit");
14882 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
14883
14884 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
14885
14886 #if APPLE_OSX_mDNSResponder
14887 #if !NO_WCF
14888 CHECK_WCF_FUNCTION(WCFConnectionDealloc)
14889 {
14890 if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
14891 }
14892 #endif
14893 #endif
14894
14895 #ifndef UNICAST_DISABLED
14896 {
14897 SearchListElem *s;
14898 SuspendLLQs(m);
14899 // Don't need to do SleepRecordRegistrations() here
14900 // because we deregister all records and services later in this routine
14901 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
14902
14903 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
14904 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
14905 // and we may crash because the list still contains dangling pointers.
14906 for (s = SearchList; s; s = s->next)
14907 while (s->AuthRecs)
14908 {
14909 ARListElem *dereg = s->AuthRecs;
14910 s->AuthRecs = s->AuthRecs->next;
14911 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
14912 }
14913 }
14914 #endif
14915
14916 for (intf = m->HostInterfaces; intf; intf = intf->next)
14917 if (intf->Advertise)
14918 DeadvertiseInterface(m, intf);
14919
14920 // Shut down all our active NAT Traversals
14921 while (m->NATTraversals)
14922 {
14923 NATTraversalInfo *t = m->NATTraversals;
14924 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
14925
14926 // After stopping the NAT Traversal, we zero out the fields.
14927 // This has particularly important implications for our AutoTunnel records --
14928 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
14929 // handlers to just turn around and attempt to re-register those same records.
14930 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
14931 // to not do this.
14932 t->ExternalAddress = zerov4Addr;
14933 t->NewAddress = zerov4Addr;
14934 t->ExternalPort = zeroIPPort;
14935 t->RequestedPort = zeroIPPort;
14936 t->Lifetime = 0;
14937 t->Result = mStatus_NoError;
14938 }
14939
14940 // Make sure there are nothing but deregistering records remaining in the list
14941 if (m->CurrentRecord)
14942 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
14943
14944 // We're in the process of shutting down, so queries, etc. are no longer available.
14945 // Consequently, determining certain information, e.g. the uDNS update server's IP
14946 // address, will not be possible. The records on the main list are more likely to
14947 // already contain such information, so we deregister the duplicate records first.
14948 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
14949 DeregLoop(m, m->DuplicateRecords);
14950 LogInfo("mDNS_StartExit: Deregistering resource records");
14951 DeregLoop(m, m->ResourceRecords);
14952
14953 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
14954 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
14955 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
14956 {
14957 m->NextScheduledResponse = m->timenow;
14958 m->SuppressSending = 0;
14959 }
14960
14961 if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
14962 else LogInfo("mDNS_StartExit: No deregistering records remain");
14963
14964 for (rr = m->DuplicateRecords; rr; rr = rr->next)
14965 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
14966
14967 // If any deregistering records remain, send their deregistration announcements before we exit
14968 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
14969
14970 mDNS_Unlock(m);
14971
14972 LogInfo("mDNS_StartExit: done");
14973 }
14974
14975 mDNSexport void mDNS_FinalExit(mDNS *const m)
14976 {
14977 mDNSu32 rrcache_active = 0;
14978 mDNSu32 rrcache_totalused = 0;
14979 mDNSu32 slot;
14980 AuthRecord *rr;
14981
14982 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
14983 mDNSPlatformClose(m);
14984
14985 rrcache_totalused = m->rrcache_totalused;
14986 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14987 {
14988 while (m->rrcache_hash[slot])
14989 {
14990 CacheGroup *cg = m->rrcache_hash[slot];
14991 while (cg->members)
14992 {
14993 CacheRecord *cr = cg->members;
14994 cg->members = cg->members->next;
14995 if (cr->CRActiveQuestion) rrcache_active++;
14996 ReleaseCacheRecord(m, cr);
14997 }
14998 cg->rrcache_tail = &cg->members;
14999 ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
15000 }
15001 }
15002 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
15003 if (rrcache_active != m->rrcache_active)
15004 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
15005
15006 for (rr = m->ResourceRecords; rr; rr = rr->next)
15007 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15008
15009 LogInfo("mDNS_FinalExit: done");
15010 }