]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-379.38.1.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2012 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
31 // Disable certain benign warnings with Microsoft compilers
32 #if (defined(_MSC_VER))
33 // Disable "conditional expression is constant" warning for debug macros.
34 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
35 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
36 #pragma warning(disable:4127)
37
38 // Disable "assignment within conditional expression".
39 // Other compilers understand the convention that if you place the assignment expression within an extra pair
40 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
41 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
42 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
43 #pragma warning(disable:4706)
44 #endif
45
46 #if APPLE_OSX_mDNSResponder
47
48 #include <WebFilterDNS/WebFilterDNS.h>
49
50 #if !NO_WCF
51 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
52 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
53
54 // Do we really need to define a macro for "if"?
55 #define CHECK_WCF_FUNCTION(X) if (X)
56 #endif // ! NO_WCF
57
58 #else
59
60 #define NO_WCF 1
61 #endif // APPLE_OSX_mDNSResponder
62
63 // Forward declarations
64 mDNSlocal void BeginSleepProcessing(mDNS *const m);
65 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
66 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password);
67 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
68 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
69 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
70 mDNSlocal void mDNS_CheckForCachedNSECS(mDNS *const m, DNSQuestion *q);
71 mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
72 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSu32 *seq,
73 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
74
75 #define mDNS_KeepaliveRecord(rr) ((rr)->rrtype == kDNSType_NULL && SameDomainLabel(SecondLabel((rr)->name)->c, (mDNSu8 *)"\x0A_keepalive"))
76
77 // ***************************************************************************
78 #if COMPILER_LIKES_PRAGMA_MARK
79 #pragma mark - Program Constants
80 #endif
81
82 #define NO_HINFO 1
83
84
85 // Any records bigger than this are considered 'large' records
86 #define SmallRecordLimit 1024
87
88 #define kMaxUpdateCredits 10
89 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
90
91 mDNSexport const char *const mDNS_DomainTypeNames[] =
92 {
93 "b._dns-sd._udp.", // Browse
94 "db._dns-sd._udp.", // Default Browse
95 "lb._dns-sd._udp.", // Automatic Browse
96 "r._dns-sd._udp.", // Registration
97 "dr._dns-sd._udp." // Default Registration
98 };
99
100 #ifdef UNICAST_DISABLED
101 #define uDNS_IsActiveQuery(q, u) mDNSfalse
102 #endif
103
104 // ***************************************************************************
105 #if COMPILER_LIKES_PRAGMA_MARK
106 #pragma mark -
107 #pragma mark - General Utility Functions
108 #endif
109
110 // If there is a authoritative LocalOnly record that answers questions of type A, AAAA and CNAME
111 // this returns true. Main use is to handle /etc/hosts records.
112 #define LORecordAnswersAddressType(rr) ((rr)->ARType == AuthRecordLocalOnly && \
113 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
114 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
115 (rr)->resrec.rrtype == kDNSType_CNAME))
116
117 #define FollowCNAME(q, rr, AddRecord) (AddRecord && (q)->qtype != kDNSType_CNAME && \
118 (rr)->RecordType != kDNSRecordTypePacketNegative && \
119 (rr)->rrtype == kDNSType_CNAME)
120
121 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
122 {
123 if (m->mDNS_busy != m->mDNS_reentrancy+1)
124 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
125
126 #if ForceAlerts
127 if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
128 #endif
129
130 if (m->NextScheduledStopTime - q->StopTime > 0)
131 m->NextScheduledStopTime = q->StopTime;
132 }
133
134 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
135 {
136 if (m->mDNS_busy != m->mDNS_reentrancy+1)
137 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
138
139 #if ForceAlerts
140 if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
141 #endif
142
143 if (ActiveQuestion(q))
144 {
145 // Depending on whether this is a multicast or unicast question we want to set either:
146 // m->NextScheduledQuery = NextQSendTime(q) or
147 // m->NextuDNSEvent = NextQSendTime(q)
148 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
149 if (*timer - NextQSendTime(q) > 0)
150 *timer = NextQSendTime(q);
151 }
152 }
153
154 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
155 {
156 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
157 unsigned int i;
158 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
159 #endif
160 e->next = r->rrauth_free;
161 r->rrauth_free = e;
162 r->rrauth_totalused--;
163 }
164
165 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
166 {
167 AuthEntity *e = (AuthEntity *)(*cp);
168 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp)->name->c);
169 if ((*cp)->rrauth_tail != &(*cp)->members)
170 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
171 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
172 (*cp)->name = mDNSNULL;
173 *cp = (*cp)->next; // Cut record from list
174 ReleaseAuthEntity(r, e);
175 }
176
177 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
178 {
179 AuthEntity *e = mDNSNULL;
180
181 if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
182 r->rrauth_lock = 1;
183
184 if (!r->rrauth_free)
185 {
186 // We allocate just one AuthEntity at a time because we need to be able
187 // free them all individually which normally happens when we parse /etc/hosts into
188 // AuthHash where we add the "new" entries and discard (free) the already added
189 // entries. If we allocate as chunks, we can't free them individually.
190 AuthEntity *storage = mDNSPlatformMemAllocate(sizeof(AuthEntity));
191 storage->next = mDNSNULL;
192 r->rrauth_free = storage;
193 }
194
195 // If we still have no free records, recycle all the records we can.
196 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
197 if (!r->rrauth_free)
198 {
199 mDNSu32 oldtotalused = r->rrauth_totalused;
200 mDNSu32 slot;
201 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
202 {
203 AuthGroup **cp = &r->rrauth_hash[slot];
204 while (*cp)
205 {
206 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
207 else ReleaseAuthGroup(r, cp);
208 }
209 }
210 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
211 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
212 }
213
214 if (r->rrauth_free) // If there are records in the free list, take one
215 {
216 e = r->rrauth_free;
217 r->rrauth_free = e->next;
218 if (++r->rrauth_totalused >= r->rrauth_report)
219 {
220 LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
221 if (r->rrauth_report < 100) r->rrauth_report += 10;
222 else if (r->rrauth_report < 1000) r->rrauth_report += 100;
223 else r->rrauth_report += 1000;
224 }
225 mDNSPlatformMemZero(e, sizeof(*e));
226 }
227
228 r->rrauth_lock = 0;
229
230 return(e);
231 }
232
233 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
234 {
235 AuthGroup *ag;
236 for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
237 if (ag->namehash == namehash && SameDomainName(ag->name, name))
238 break;
239 return(ag);
240 }
241
242 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
243 {
244 return(AuthGroupForName(r, slot, rr->namehash, rr->name));
245 }
246
247 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
248 {
249 mDNSu16 namelen = DomainNameLength(rr->name);
250 AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
251 if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
252 ag->next = r->rrauth_hash[slot];
253 ag->namehash = rr->namehash;
254 ag->members = mDNSNULL;
255 ag->rrauth_tail = &ag->members;
256 ag->NewLocalOnlyRecords = mDNSNULL;
257 if (namelen > sizeof(ag->namestorage))
258 ag->name = mDNSPlatformMemAllocate(namelen);
259 else
260 ag->name = (domainname*)ag->namestorage;
261 if (!ag->name)
262 {
263 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
264 ReleaseAuthEntity(r, (AuthEntity*)ag);
265 return(mDNSNULL);
266 }
267 AssignDomainName(ag->name, rr->name);
268
269 if (AuthGroupForRecord(r, slot, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
270 r->rrauth_hash[slot] = ag;
271 if (AuthGroupForRecord(r, slot, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
272
273 return(ag);
274 }
275
276 // Returns the AuthGroup in which the AuthRecord was inserted
277 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
278 {
279 AuthGroup *ag;
280 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
281 ag = AuthGroupForRecord(r, slot, &rr->resrec);
282 if (!ag) ag = GetAuthGroup(r, slot, &rr->resrec); // If we don't have a AuthGroup for this name, make one now
283 if (ag)
284 {
285 LogInfo("InsertAuthRecord: inserting auth record %s from table", ARDisplayString(m, rr));
286 *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list
287 ag->rrauth_tail = &(rr->next); // Advance tail pointer
288 }
289 return ag;
290 }
291
292 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
293 {
294 AuthGroup *a;
295 AuthGroup **ag = &a;
296 AuthRecord **rp;
297 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
298
299 a = AuthGroupForRecord(r, slot, &rr->resrec);
300 if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
301 rp = &(*ag)->members;
302 while (*rp)
303 {
304 if (*rp != rr)
305 rp=&(*rp)->next;
306 else
307 {
308 // We don't break here, so that we can set the tail below without tracking "prev" pointers
309
310 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
311 *rp = (*rp)->next; // Cut record from list
312 }
313 }
314 // TBD: If there are no more members, release authgroup ?
315 (*ag)->rrauth_tail = rp;
316 return a;
317 }
318
319 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
320 {
321 CacheGroup *cg;
322 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
323 if (cg->namehash == namehash && SameDomainName(cg->name, name))
324 break;
325 return(cg);
326 }
327
328 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
329 {
330 return(CacheGroupForName(m, slot, rr->namehash, rr->name));
331 }
332
333 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
334 {
335 NetworkInterfaceInfo *intf;
336
337 if (addr->type == mDNSAddrType_IPv4)
338 {
339 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
340 if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
341 for (intf = m->HostInterfaces; intf; intf = intf->next)
342 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
343 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
344 return(mDNStrue);
345 }
346
347 if (addr->type == mDNSAddrType_IPv6)
348 {
349 if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
350 for (intf = m->HostInterfaces; intf; intf = intf->next)
351 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
352 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
353 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
354 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
355 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
356 return(mDNStrue);
357 }
358
359 return(mDNSfalse);
360 }
361
362 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
363 {
364 NetworkInterfaceInfo *intf = m->HostInterfaces;
365 while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
366 return(intf);
367 }
368
369 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
370 {
371 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
372 return(intf ? intf->ifname : mDNSNULL);
373 }
374
375 // Caller should hold the lock
376 mDNSlocal void GenerateNegativeResponse(mDNS *const m)
377 {
378 DNSQuestion *q;
379 if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
380 q = m->CurrentQuestion;
381 LogInfo("GenerateNegativeResponse: Generating negative response for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
382
383 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, mDNSNULL);
384 // We need to force the response through in the following cases
385 //
386 // a) SuppressUnusable questions that are suppressed
387 // b) Append search domains and retry the question
388 //
389 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
390 // through we use "QC_forceresponse".
391 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_forceresponse);
392 if (m->CurrentQuestion == q) { q->ThisQInterval = 0; } // Deactivate this question
393 // Don't touch the question after this
394 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
395 }
396
397 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
398 {
399 const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
400 if (q->CNAMEReferrals >= 10 || selfref)
401 LogMsg("AnswerQuestionByFollowingCNAME: %p %##s (%s) NOT following CNAME referral %d%s for %s",
402 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
403 else
404 {
405 const mDNSu32 c = q->CNAMEReferrals + 1; // Stash a copy of the new q->CNAMEReferrals value
406
407 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
408 // themselves. Without that check we can get into a case where we have two duplicate questions,
409 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
410 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
411 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
412 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
413 // for either of them. This is not a problem for CNAME loops of two or more records because in
414 // those cases the newly re-appended question A has a different target name and therefore cannot be
415 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
416
417 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
418 // and track CNAMEs coming and going, we should really create a subordinate query here,
419 // which we would subsequently cancel and retract if the CNAME referral record were removed.
420 // In reality this is such a corner case we'll ignore it until someone actually needs it.
421
422 LogInfo("AnswerQuestionByFollowingCNAME: %p %##s (%s) following CNAME referral %d for %s",
423 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, RRDisplayString(m, rr));
424
425 mDNS_StopQuery_internal(m, q); // Stop old query
426 AssignDomainName(&q->qname, &rr->rdata->u.name); // Update qname
427 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
428 // If a unicast query results in a CNAME that points to a .local, we need to re-try
429 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
430 // to try this as unicast query even though it is a .local name
431 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
432 {
433 LogInfo("AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p %##s (%s) Record %s",
434 q, q->qname.c, DNSTypeName(q->qtype), RRDisplayString(m, rr));
435 q->InterfaceID = mDNSInterface_Unicast;
436 }
437 mDNS_StartQuery_internal(m, q); // start new query
438 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
439 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
440 q->CNAMEReferrals = c;
441 }
442 }
443
444 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
445 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
446 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
447 {
448 DNSQuestion *q = m->CurrentQuestion;
449 mDNSBool followcname;
450
451 if (!q)
452 {
453 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
454 return;
455 }
456
457 followcname = FollowCNAME(q, &rr->resrec, AddRecord);
458
459 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
460 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
461 {
462 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
463 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
464 return;
465 }
466
467 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
468 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
469 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
470 if (q->QuestionCallback && !q->NoAnswer)
471 {
472 q->CurrentAnswers += AddRecord ? 1 : -1;
473 if (LORecordAnswersAddressType(rr))
474 {
475 if (!followcname || q->ReturnIntermed)
476 {
477 // Don't send this packet on the wire as we answered from /etc/hosts
478 q->ThisQInterval = 0;
479 q->LOAddressAnswers += AddRecord ? 1 : -1;
480 // We can't possibly validate the entries in /etc/hosts. Hence, we
481 // report it as insecure.
482 if (q->ValidationRequired)
483 {
484 q->ValidationStatus = DNSSEC_Insecure;
485 q->ValidationState = DNSSECValDone;
486 }
487 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
488 }
489 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
490 // The callback above could have caused the question to stop. Detect that
491 // using m->CurrentQuestion
492 if (followcname && m->CurrentQuestion == q)
493 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
494 return;
495 }
496 else
497 {
498 if (q->ValidationRequired)
499 {
500 q->ValidationStatus = DNSSEC_Insecure;
501 q->ValidationState = DNSSECValDone;
502 }
503 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
504 }
505 }
506 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
507 }
508
509 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
510 {
511 if (m->CurrentQuestion)
512 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
513 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
514 m->CurrentQuestion = m->Questions;
515 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
516 {
517 mDNSBool answered;
518 DNSQuestion *q = m->CurrentQuestion;
519 if (RRAny(rr))
520 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
521 else
522 answered = LocalOnlyRecordAnswersQuestion(rr, q);
523 if (answered)
524 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
525 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
526 m->CurrentQuestion = q->next;
527 }
528 m->CurrentQuestion = mDNSNULL;
529 }
530
531 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
532 // delivers the appropriate add/remove events to listening questions:
533 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
534 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
535 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
536 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
537 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
538 //
539 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
540 // and by mDNS_Deregister_internal()
541
542 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
543 {
544 if (m->CurrentQuestion)
545 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
546 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
547
548 m->CurrentQuestion = m->LocalOnlyQuestions;
549 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
550 {
551 mDNSBool answered;
552 DNSQuestion *q = m->CurrentQuestion;
553 // We are called with both LocalOnly/P2P record or a regular AuthRecord
554 if (RRAny(rr))
555 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
556 else
557 answered = LocalOnlyRecordAnswersQuestion(rr, q);
558 if (answered)
559 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
560 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
561 m->CurrentQuestion = q->next;
562 }
563
564 m->CurrentQuestion = mDNSNULL;
565
566 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
567 if (rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P)
568 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, rr, AddRecord);
569
570 }
571
572 // ***************************************************************************
573 #if COMPILER_LIKES_PRAGMA_MARK
574 #pragma mark -
575 #pragma mark - Resource Record Utility Functions
576 #endif
577
578 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
579
580 #define ResourceRecordIsValidAnswer(RR) ( ((RR)->resrec.RecordType & kDNSRecordTypeActiveMask) && \
581 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
582 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
583 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
584
585 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
586 (ResourceRecordIsValidAnswer(RR) && \
587 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
588
589 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
590 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
591
592 #define InitialAnnounceCount ((mDNSu8)8)
593
594 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
595 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
596 // and then if the machine fails to wake, 3 goodbye packets).
597 #define GoodbyeCount ((mDNSu8)3)
598 #define WakeupCount ((mDNSu8)18)
599
600 // Number of wakeups we send if WakeOnResolve is set in the question
601 #define InitialWakeOnResolveCount ((mDNSu8)3)
602
603 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
604 // This means that because the announce interval is doubled after sending the first packet, the first
605 // observed on-the-wire inter-packet interval between announcements is actually one second.
606 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
607 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
608 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
609 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
610
611 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
612 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
613 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
614
615 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
616 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
617 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
618 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
619
620 #define MaxUnansweredQueries 4
621
622 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
623 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
624 // TTL and rdata may differ.
625 // This is used for cache flush management:
626 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
627 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
628
629 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
630
631 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
632
633 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
634 {
635 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
636 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
637 if (r1->resrec.InterfaceID &&
638 r2->resrec.InterfaceID &&
639 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
640 return (mDNSBool)(
641 r1->resrec.rrclass == r2->resrec.rrclass &&
642 r1->resrec.namehash == r2->resrec.namehash &&
643 SameDomainName(r1->resrec.name, r2->resrec.name));
644 }
645
646 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
647 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
648 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
649 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
650 // so a response of any type should match, even if it is not actually the type the client plans to use.
651
652 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
653 // and require the rrtypes to match for the rdata to be considered potentially conflicting
654 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
655 {
656 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
657 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
658 if (pktrr->resrec.InterfaceID &&
659 authrr->resrec.InterfaceID &&
660 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
661 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
662 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
663 return (mDNSBool)(
664 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
665 pktrr->resrec.namehash == authrr->resrec.namehash &&
666 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
667 }
668
669 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
670 // This is the information that the requester believes to be correct.
671 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
672 // This is the information that we believe to be correct.
673 // We've already determined that we plan to give this answer on this interface
674 // (either the record is non-specific, or it is specific to this interface)
675 // so now we just need to check the name, type, class, rdata and TTL.
676 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
677 {
678 // If RR signature is different, or data is different, then don't suppress our answer
679 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
680
681 // If the requester's indicated TTL is less than half the real TTL,
682 // we need to give our answer before the requester's copy expires.
683 // If the requester's indicated TTL is at least half the real TTL,
684 // then we can suppress our answer this time.
685 // If the requester's indicated TTL is greater than the TTL we believe,
686 // then that's okay, and we don't need to do anything about it.
687 // (If two responders on the network are offering the same information,
688 // that's okay, and if they are offering the information with different TTLs,
689 // the one offering the lower TTL should defer to the one offering the higher TTL.)
690 return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
691 }
692
693 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
694 {
695 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
696 {
697 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
698 {
699 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
700 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
701 }
702 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
703 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
704 // Some defensive code:
705 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
706 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
707 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
708 if (m->NextScheduledProbe - m->timenow < 0)
709 m->NextScheduledProbe = m->timenow;
710 }
711 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
712 {
713 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
714 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
715 }
716 }
717
718 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
719 {
720 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
721 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
722
723 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
724 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
725 // records that are going to probe, then we delay its first announcement so that it will
726 // go out synchronized with the first announcement for the other records that *are* probing.
727 // This is a minor performance tweak that helps keep groups of related records synchronized together.
728 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
729 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
730 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
731 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
732 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
733
734 if (rr->ProbeCount)
735 {
736 // If we have no probe suppression time set, or it is in the past, set it now
737 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
738 {
739 // To allow us to aggregate probes when a group of services are registered together,
740 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
741 // 1/4 second wait; probe
742 // 1/4 second wait; probe
743 // 1/4 second wait; probe
744 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
745 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
746
747 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
748 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
749 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
750 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
751 m->SuppressProbes = m->timenow;
752
753 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
754 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
755 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
756 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
757 m->SuppressProbes = m->timenow;
758
759 // except... don't expect to be able to send before the m->SuppressSending timer fires
760 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
761 m->SuppressProbes = NonZeroTime(m->SuppressSending);
762
763 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
764 {
765 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
766 m->SuppressProbes - m->timenow,
767 m->NextScheduledProbe - m->timenow,
768 m->NextScheduledQuery - m->timenow,
769 m->SuppressSending,
770 m->SuppressSending - m->timenow);
771 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
772 }
773 }
774 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
775 }
776 else if (m->SuppressProbes && m->SuppressProbes - m->timenow >= 0)
777 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
778 else
779 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
780
781 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
782 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
783 // After three probes one second apart with no answer, we conclude the client is now sleeping
784 // and we can begin broadcasting our announcements to take over ownership of that IP address.
785 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
786 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
787 if (rr->AddressProxy.type) rr->LastAPTime = m->timenow;
788
789 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
790 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
791 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
792 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
793 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
794 if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
795 if (rr->WakeUp.HMAC.l[0] && rr->resrec.rrtype == kDNSType_AAAA)
796 rr->LastAPTime = m->timenow - rr->ThisAPInterval + mDNSPlatformOneSecond * 10;
797
798 // Set LastMCTime to now, to inhibit multicast responses
799 // (no need to send additional multicast responses when we're announcing anyway)
800 rr->LastMCTime = m->timenow;
801 rr->LastMCInterface = mDNSInterfaceMark;
802
803 SetNextAnnounceProbeTime(m, rr);
804 }
805
806 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
807 {
808 const domainname *target;
809 if (rr->AutoTarget)
810 {
811 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
812 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
813 // with the port number in our advertised SRV record automatically tracking the external mapped port.
814 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
815 if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
816 }
817
818 target = GetServiceTarget(m, rr);
819 if (!target || target->c[0] == 0)
820 {
821 // defer registration until we've got a target
822 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
823 rr->state = regState_NoTarget;
824 return mDNSNULL;
825 }
826 else
827 {
828 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
829 return target;
830 }
831 }
832
833 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
834 // Eventually we should unify this with GetServiceTarget() in uDNS.c
835 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
836 {
837 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
838 const domainname *newname = &m->MulticastHostname;
839
840 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
841
842 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
843 {
844 const domainname *const n = SetUnicastTargetToHostName(m, rr);
845 if (n) newname = n;
846 else { target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
847 }
848
849 if (target && SameDomainName(target, newname))
850 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
851
852 if (target && !SameDomainName(target, newname))
853 {
854 AssignDomainName(target, newname);
855 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
856
857 // If we're in the middle of probing this record, we need to start again,
858 // because changing its rdata may change the outcome of the tie-breaker.
859 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
860 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
861
862 // If we've announced this record, we really should send a goodbye packet for the old rdata before
863 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
864 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
865 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
866 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
867 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
868
869 rr->AnnounceCount = InitialAnnounceCount;
870 rr->RequireGoodbye = mDNSfalse;
871 InitializeLastAPTime(m, rr);
872 }
873 }
874
875 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
876 {
877 if (rr->RecordCallback)
878 {
879 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
880 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
881 rr->Acknowledged = mDNStrue;
882 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
883 rr->RecordCallback(m, rr, mStatus_NoError);
884 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
885 }
886 }
887
888 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
889 {
890 // Make sure that we don't activate the SRV record and associated service records, if it is in
891 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
892 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
893 // the target becomes available, the records will be reregistered.
894 if (rr->resrec.rrtype != kDNSType_SRV)
895 {
896 AuthRecord *srvRR = mDNSNULL;
897 if (rr->resrec.rrtype == kDNSType_PTR)
898 srvRR = rr->Additional1;
899 else if (rr->resrec.rrtype == kDNSType_TXT)
900 srvRR = rr->DependentOn;
901 if (srvRR)
902 {
903 if (srvRR->resrec.rrtype != kDNSType_SRV)
904 {
905 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
906 }
907 else
908 {
909 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
910 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
911 rr->state = srvRR->state;
912 }
913 }
914 }
915
916 if (rr->state == regState_NoTarget)
917 {
918 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
919 return;
920 }
921 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
922 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
923 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
924 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
925 // 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.
926 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
927 {
928 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
929 rr->state = regState_DeregPending;
930 }
931 else
932 {
933 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
934 rr->state = regState_Pending;
935 }
936 rr->ProbeCount = 0;
937 rr->AnnounceCount = 0;
938 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
939 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
940 rr->expire = 0; // Forget about all the leases, start fresh
941 rr->uselease = mDNStrue;
942 rr->updateid = zeroID;
943 rr->SRVChanged = mDNSfalse;
944 rr->updateError = mStatus_NoError;
945 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
946 // The records might already be registered with the server and hence could have NAT state.
947 if (rr->NATinfo.clientContext)
948 {
949 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
950 rr->NATinfo.clientContext = mDNSNULL;
951 }
952 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
953 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
954 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
955 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
956 }
957
958 // Two records qualify to be local duplicates if:
959 // (a) the RecordTypes are the same, or
960 // (b) one is Unique and the other Verified
961 // (c) either is in the process of deregistering
962 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
963 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
964 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
965
966 #define RecordIsLocalDuplicate(A,B) \
967 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
968
969 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
970 {
971 AuthGroup *a;
972 AuthGroup **ag = &a;
973 AuthRecord **rp;
974 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
975
976 a = AuthGroupForRecord(r, slot, &rr->resrec);
977 if (!a) return mDNSNULL;
978 rp = &(*ag)->members;
979 while (*rp)
980 {
981 if (!RecordIsLocalDuplicate(*rp, rr))
982 rp=&(*rp)->next;
983 else
984 {
985 if ((*rp)->resrec.RecordType == kDNSRecordTypeDeregistering)
986 {
987 (*rp)->AnnounceCount = 0;
988 rp=&(*rp)->next;
989 }
990 else return *rp;
991 }
992 }
993 return (mDNSNULL);
994 }
995
996 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
997 {
998 AuthGroup *a;
999 AuthGroup **ag = &a;
1000 AuthRecord **rp;
1001 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1002
1003 a = AuthGroupForRecord(r, slot, &rr->resrec);
1004 if (!a) return mDNSfalse;
1005 rp = &(*ag)->members;
1006 while (*rp)
1007 {
1008 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1009 const AuthRecord *s2 = (*rp)->RRSet ? (*rp)->RRSet : *rp;
1010 if (s1 != s2 && SameResourceRecordSignature((*rp), rr) && !IdenticalSameNameRecord(&(*rp)->resrec, &rr->resrec))
1011 return mDNStrue;
1012 else
1013 rp=&(*rp)->next;
1014 }
1015 return (mDNSfalse);
1016 }
1017
1018 // checks to see if "rr" is already present
1019 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1020 {
1021 AuthGroup *a;
1022 AuthGroup **ag = &a;
1023 AuthRecord **rp;
1024 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1025
1026 a = AuthGroupForRecord(r, slot, &rr->resrec);
1027 if (!a) return mDNSNULL;
1028 rp = &(*ag)->members;
1029 while (*rp)
1030 {
1031 if (*rp != rr)
1032 rp=&(*rp)->next;
1033 else
1034 {
1035 return *rp;
1036 }
1037 }
1038 return (mDNSNULL);
1039 }
1040
1041 // Exported so uDNS.c can call this
1042 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1043 {
1044 domainname *target = GetRRDomainNameTarget(&rr->resrec);
1045 AuthRecord *r;
1046 AuthRecord **p = &m->ResourceRecords;
1047 AuthRecord **d = &m->DuplicateRecords;
1048
1049 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1050 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1051
1052 if (!rr->resrec.RecordType)
1053 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1054
1055 if (m->ShutdownTime)
1056 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1057
1058 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1059 {
1060 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1061 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1062 {
1063 rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1064 rr->ARType = AuthRecordLocalOnly;
1065 }
1066 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1067 {
1068 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1069 if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1070 }
1071 if (rr->resrec.InterfaceID != previousID)
1072 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1073 }
1074
1075 if (RRLocalOnly(rr))
1076 {
1077 if (CheckAuthSameRecord(&m->rrauth, rr))
1078 {
1079 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1080 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1081 return(mStatus_AlreadyRegistered);
1082 }
1083 }
1084 else
1085 {
1086 while (*p && *p != rr) p=&(*p)->next;
1087 if (*p)
1088 {
1089 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1090 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1091 return(mStatus_AlreadyRegistered);
1092 }
1093 }
1094
1095 while (*d && *d != rr) d=&(*d)->next;
1096 if (*d)
1097 {
1098 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1099 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1100 return(mStatus_AlreadyRegistered);
1101 }
1102
1103 if (rr->DependentOn)
1104 {
1105 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1106 rr->resrec.RecordType = kDNSRecordTypeVerified;
1107 else
1108 {
1109 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1110 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1111 return(mStatus_Invalid);
1112 }
1113 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1114 {
1115 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1116 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1117 return(mStatus_Invalid);
1118 }
1119 }
1120
1121 // If this resource record is referencing a specific interface, make sure it exists.
1122 // Skip checks for LocalOnly and P2P as they are not valid InterfaceIDs. Also, for scoped
1123 // entries in /etc/hosts skip that check as that interface may not be valid at this time.
1124 if (rr->resrec.InterfaceID && rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
1125 {
1126 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1127 if (!intf)
1128 {
1129 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr->resrec.InterfaceID);
1130 return(mStatus_BadReferenceErr);
1131 }
1132 }
1133
1134 rr->next = mDNSNULL;
1135
1136 // Field Group 1: The actual information pertaining to this resource record
1137 // Set up by client prior to call
1138
1139 // Field Group 2: Persistent metadata for Authoritative Records
1140 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1141 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1142 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1143 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1144 // rr->Callback = already set in mDNS_SetupResourceRecord
1145 // rr->Context = already set in mDNS_SetupResourceRecord
1146 // rr->RecordType = already set in mDNS_SetupResourceRecord
1147 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1148 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1149 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1150 if (rr->AutoTarget && target) target->c[0] = 0;
1151
1152 // Field Group 3: Transient state for Authoritative Records
1153 rr->Acknowledged = mDNSfalse;
1154 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1155 rr->AnnounceCount = InitialAnnounceCount;
1156 rr->RequireGoodbye = mDNSfalse;
1157 rr->AnsweredLocalQ = mDNSfalse;
1158 rr->IncludeInProbe = mDNSfalse;
1159 rr->ImmedUnicast = mDNSfalse;
1160 rr->SendNSECNow = mDNSNULL;
1161 rr->ImmedAnswer = mDNSNULL;
1162 rr->ImmedAdditional = mDNSNULL;
1163 rr->SendRNow = mDNSNULL;
1164 rr->v4Requester = zerov4Addr;
1165 rr->v6Requester = zerov6Addr;
1166 rr->NextResponse = mDNSNULL;
1167 rr->NR_AnswerTo = mDNSNULL;
1168 rr->NR_AdditionalTo = mDNSNULL;
1169 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1170 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1171 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1172 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1173 rr->NewRData = mDNSNULL;
1174 rr->newrdlength = 0;
1175 rr->UpdateCallback = mDNSNULL;
1176 rr->UpdateCredits = kMaxUpdateCredits;
1177 rr->NextUpdateCredit = 0;
1178 rr->UpdateBlocked = 0;
1179
1180 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1181 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1182
1183 // Field Group 4: Transient uDNS state for Authoritative Records
1184 rr->state = regState_Zero;
1185 rr->uselease = 0;
1186 rr->expire = 0;
1187 rr->Private = 0;
1188 rr->updateid = zeroID;
1189 rr->updateIntID = zeroOpaque64;
1190 rr->zone = rr->resrec.name;
1191 rr->nta = mDNSNULL;
1192 rr->tcp = mDNSNULL;
1193 rr->OrigRData = 0;
1194 rr->OrigRDLen = 0;
1195 rr->InFlightRData = 0;
1196 rr->InFlightRDLen = 0;
1197 rr->QueuedRData = 0;
1198 rr->QueuedRDLen = 0;
1199 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1200 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1201 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1202 // times with different values if the external NAT port changes during the lifetime of the service registration.
1203 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1204
1205 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1206 // rr->resrec.name->c = MUST be set by client
1207 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1208 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1209 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1210 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1211
1212 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1213 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1214 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1215 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1216
1217 if (rr->AutoTarget)
1218 {
1219 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1220 #ifndef UNICAST_DISABLED
1221 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1222 // 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.
1223 if (rr->state == regState_NoTarget)
1224 {
1225 // Initialize the target so that we don't crash while logging etc.
1226 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1227 if (tar) tar->c[0] = 0;
1228 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1229 }
1230 #endif
1231 }
1232 else
1233 {
1234 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
1235 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1236 }
1237
1238 if (!ValidateDomainName(rr->resrec.name))
1239 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1240
1241 // Don't do this until *after* we've set rr->resrec.rdlength
1242 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1243 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1244
1245 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
1246 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1247
1248 if (RRLocalOnly(rr))
1249 {
1250 // If this is supposed to be unique, make sure we don't have any name conflicts.
1251 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1252 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1253 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1254 // Hence, just bail out.
1255 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1256 {
1257 if (CheckAuthRecordConflict(&m->rrauth, rr))
1258 {
1259 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1260 return mStatus_NameConflict;
1261 }
1262 }
1263 }
1264
1265 // For uDNS records, we don't support duplicate checks at this time.
1266 #ifndef UNICAST_DISABLED
1267 if (AuthRecord_uDNS(rr))
1268 {
1269 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1270 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1271 // 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.
1272 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1273 while (*p) p=&(*p)->next;
1274 *p = rr;
1275 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1276 rr->ProbeCount = 0;
1277 rr->AnnounceCount = 0;
1278 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1279 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
1280 }
1281 #endif
1282
1283 // Now that we've finished building our new record, make sure it's not identical to one we already have
1284 if (RRLocalOnly(rr))
1285 {
1286 rr->ProbeCount = 0;
1287 rr->AnnounceCount = 0;
1288 r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1289 }
1290 else
1291 {
1292 for (r = m->ResourceRecords; r; r=r->next)
1293 if (RecordIsLocalDuplicate(r, rr))
1294 {
1295 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1296 else break;
1297 }
1298 }
1299
1300 if (r)
1301 {
1302 debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m,rr));
1303 *d = rr;
1304 // If the previous copy of this record is already verified unique,
1305 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1306 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1307 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1308 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1309 rr->ProbeCount = 0;
1310 }
1311 else
1312 {
1313 debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1314 if (RRLocalOnly(rr))
1315 {
1316 AuthGroup *ag;
1317 ag = InsertAuthRecord(m, &m->rrauth, rr);
1318 if (ag && !ag->NewLocalOnlyRecords) {
1319 m->NewLocalOnlyRecords = mDNStrue;
1320 ag->NewLocalOnlyRecords = rr;
1321 }
1322 // No probing for LocalOnly records, Acknowledge them right away
1323 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1324 AcknowledgeRecord(m, rr);
1325 return(mStatus_NoError);
1326 }
1327 else
1328 {
1329 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1330 *p = rr;
1331 }
1332 }
1333
1334 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
1335 {
1336 // For records that are not going to probe, acknowledge them right away
1337 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1338 AcknowledgeRecord(m, rr);
1339
1340 // Adding a record may affect whether or not we should sleep
1341 mDNS_UpdateAllowSleep(m);
1342 }
1343
1344 return(mStatus_NoError);
1345 }
1346
1347 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1348 {
1349 m->ProbeFailTime = m->timenow;
1350 m->NumFailedProbes++;
1351 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1352 // If a bunch of hosts have all been configured with the same name, then they'll all
1353 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1354 // up to name-10. After that they'll start adding random increments in the range 1-100,
1355 // so they're more likely to branch out in the available namespace and settle on a set of
1356 // unique names quickly. If after five more tries the host is still conflicting, then we
1357 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1358 if (m->NumFailedProbes >= 15)
1359 {
1360 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1361 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1362 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1363 }
1364 }
1365
1366 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1367 {
1368 RData *OldRData = rr->resrec.rdata;
1369 mDNSu16 OldRDLen = rr->resrec.rdlength;
1370 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
1371 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
1372 if (rr->UpdateCallback)
1373 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
1374 }
1375
1376 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1377 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1378 // Exported so uDNS.c can call this
1379 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1380 {
1381 AuthRecord *r2;
1382 mDNSu8 RecordType = rr->resrec.RecordType;
1383 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
1384 mDNSBool dupList = mDNSfalse;
1385
1386 if (RRLocalOnly(rr))
1387 {
1388 AuthGroup *a;
1389 AuthGroup **ag = &a;
1390 AuthRecord **rp;
1391 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1392
1393 a = AuthGroupForRecord(&m->rrauth, slot, &rr->resrec);
1394 if (!a) return mDNSfalse;
1395 rp = &(*ag)->members;
1396 while (*rp && *rp != rr) rp=&(*rp)->next;
1397 p = rp;
1398 }
1399 else
1400 {
1401 while (*p && *p != rr) p=&(*p)->next;
1402 }
1403
1404 if (*p)
1405 {
1406 // We found our record on the main list. See if there are any duplicates that need special handling.
1407 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
1408 {
1409 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1410 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1411 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1412 }
1413 else
1414 {
1415 // Before we delete the record (and potentially send a goodbye packet)
1416 // first see if we have a record on the duplicate list ready to take over from it.
1417 AuthRecord **d = &m->DuplicateRecords;
1418 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1419 if (*d)
1420 {
1421 AuthRecord *dup = *d;
1422 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1423 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1424 *d = dup->next; // Cut replacement record from DuplicateRecords list
1425 if (RRLocalOnly(rr))
1426 {
1427 dup->next = mDNSNULL;
1428 if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1429 }
1430 else
1431 {
1432 dup->next = rr->next; // And then...
1433 rr->next = dup; // ... splice it in right after the record we're about to delete
1434 }
1435 dup->resrec.RecordType = rr->resrec.RecordType;
1436 dup->ProbeCount = rr->ProbeCount;
1437 dup->AnnounceCount = rr->AnnounceCount;
1438 dup->RequireGoodbye = rr->RequireGoodbye;
1439 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
1440 dup->ImmedAnswer = rr->ImmedAnswer;
1441 dup->ImmedUnicast = rr->ImmedUnicast;
1442 dup->ImmedAdditional = rr->ImmedAdditional;
1443 dup->v4Requester = rr->v4Requester;
1444 dup->v6Requester = rr->v6Requester;
1445 dup->ThisAPInterval = rr->ThisAPInterval;
1446 dup->LastAPTime = rr->LastAPTime;
1447 dup->LastMCTime = rr->LastMCTime;
1448 dup->LastMCInterface = rr->LastMCInterface;
1449 dup->Private = rr->Private;
1450 dup->state = rr->state;
1451 rr->RequireGoodbye = mDNSfalse;
1452 rr->AnsweredLocalQ = mDNSfalse;
1453 }
1454 }
1455 }
1456 else
1457 {
1458 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1459 p = &m->DuplicateRecords;
1460 while (*p && *p != rr) p=&(*p)->next;
1461 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1462 if (*p)
1463 {
1464 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1465 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1466 // also that have been marked above in this function. In that case, we come here and if we don't
1467 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1468 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1469 // details.
1470 rr->WakeUp.HMAC = zeroEthAddr;
1471 rr->RequireGoodbye = mDNSfalse;
1472 dupList = mDNStrue;
1473 }
1474 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1475 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1476 }
1477
1478 if (!*p)
1479 {
1480 // No need to log an error message if we already know this is a potentially repeated deregistration
1481 if (drt != mDNS_Dereg_repeat)
1482 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1483 return(mStatus_BadReferenceErr);
1484 }
1485
1486 // If this is a shared record and we've announced it at least once,
1487 // we need to retract that announcement before we delete the record
1488
1489 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1490 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1491 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1492 // mechanism to cope with the client callback modifying the question list while that's happening.
1493 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1494 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1495 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1496 // records, thereby invoking yet more callbacks, without limit.
1497 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1498 // actual goodbye packets.
1499
1500 #ifndef UNICAST_DISABLED
1501 if (AuthRecord_uDNS(rr))
1502 {
1503 if (rr->RequireGoodbye)
1504 {
1505 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1506 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1507 m->LocalRemoveEvents = mDNStrue;
1508 uDNS_DeregisterRecord(m, rr);
1509 // At this point unconditionally we bail out
1510 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1511 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1512 // process and will complete asynchronously. Either way we don't need to do anything more here.
1513 return(mStatus_NoError);
1514 }
1515 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1516 // from the server. In that case, if the records have been part of a group update, clear the
1517 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1518 rr->updateid = zeroID;
1519
1520 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1521 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1522 // This happens today when we turn on/off interface where we get multiple network transitions
1523 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1524 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1525 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1526 // NAT state here takes care of the case where we did not send goodbyes at all.
1527 if (rr->NATinfo.clientContext)
1528 {
1529 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1530 rr->NATinfo.clientContext = mDNSNULL;
1531 }
1532 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1533 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1534 }
1535 #endif // UNICAST_DISABLED
1536
1537 if (RecordType == kDNSRecordTypeUnregistered)
1538 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1539 else if (RecordType == kDNSRecordTypeDeregistering)
1540 {
1541 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1542 return(mStatus_BadReferenceErr);
1543 }
1544
1545 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1546 // We may want to consider changing this code so that we generate local-only question "rmv"
1547 // events (and maybe goodbye packets too) for unique records as well as for shared records
1548 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1549 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1550 // clause will execute here and the record will be cut from the list.
1551 if (rr->WakeUp.HMAC.l[0] ||
1552 (RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1553 {
1554 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1555 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1556 rr->resrec.rroriginalttl = 0;
1557 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1558 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
1559 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1560 m->LocalRemoveEvents = mDNStrue;
1561 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1562 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1563 }
1564 else
1565 {
1566 if (!dupList && RRLocalOnly(rr))
1567 {
1568 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1569 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1570 }
1571 else
1572 {
1573 *p = rr->next; // Cut this record from the list
1574 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1575 }
1576 // If someone is about to look at this, bump the pointer forward
1577 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
1578 rr->next = mDNSNULL;
1579
1580 // Should we generate local remove events here?
1581 // i.e. something like:
1582 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1583
1584 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1585 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1586
1587 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1588 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1589 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1590
1591 // If we have an update queued up which never executed, give the client a chance to free that memory
1592 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
1593
1594
1595 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1596 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1597 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1598 // so any attempt to touch rr after this is likely to lead to a crash.
1599 if (drt != mDNS_Dereg_conflict)
1600 {
1601 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1602 LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m, rr));
1603 if (rr->RecordCallback)
1604 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
1605 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1606 }
1607 else
1608 {
1609 RecordProbeFailure(m, rr);
1610 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1611 if (rr->RecordCallback)
1612 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
1613 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1614 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1615 // Note that with all the client callbacks going on, by the time we get here all the
1616 // records we marked may have been explicitly deregistered by the client anyway.
1617 r2 = m->DuplicateRecords;
1618 while (r2)
1619 {
1620 if (r2->ProbeCount != 0xFF)
1621 {
1622 r2 = r2->next;
1623 }
1624 else
1625 {
1626 mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
1627 // As this is a duplicate record, it will be unlinked from the list
1628 // immediately
1629 r2 = m->DuplicateRecords;
1630 }
1631 }
1632 }
1633 }
1634 mDNS_UpdateAllowSleep(m);
1635 return(mStatus_NoError);
1636 }
1637
1638 // ***************************************************************************
1639 #if COMPILER_LIKES_PRAGMA_MARK
1640 #pragma mark -
1641 #pragma mark - Packet Sending Functions
1642 #endif
1643
1644 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1645 {
1646 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1647 {
1648 **nrpp = rr;
1649 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1650 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1651 // The referenced record will definitely be acceptable (by recursive application of this rule)
1652 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1653 rr->NR_AdditionalTo = add;
1654 *nrpp = &rr->NextResponse;
1655 }
1656 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1657 }
1658
1659 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1660 {
1661 AuthRecord *rr, *rr2;
1662 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
1663 {
1664 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1665 // later in the "for" loop, and we will follow further "additional" links then.)
1666 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1667 AddRecordToResponseList(nrpp, rr->Additional1, rr);
1668
1669 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
1670 AddRecordToResponseList(nrpp, rr->Additional2, rr);
1671
1672 // For SRV records, automatically add the Address record(s) for the target host
1673 if (rr->resrec.rrtype == kDNSType_SRV)
1674 {
1675 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1676 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1677 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1678 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
1679 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
1680 AddRecordToResponseList(nrpp, rr2, rr);
1681 }
1682 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
1683 {
1684 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1685 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1686 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1687 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
1688 SameDomainName(rr->resrec.name, rr2->resrec.name))
1689 AddRecordToResponseList(nrpp, rr2, rr);
1690 }
1691 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
1692 {
1693 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
1694 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1695 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
1696 }
1697 }
1698 }
1699
1700 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
1701 {
1702 AuthRecord *rr;
1703 AuthRecord *ResponseRecords = mDNSNULL;
1704 AuthRecord **nrp = &ResponseRecords;
1705 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
1706
1707 // Make a list of all our records that need to be unicast to this destination
1708 for (rr = m->ResourceRecords; rr; rr=rr->next)
1709 {
1710 // If we find we can no longer unicast this answer, clear ImmedUnicast
1711 if (rr->ImmedAnswer == mDNSInterfaceMark ||
1712 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
1713 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
1714 rr->ImmedUnicast = mDNSfalse;
1715
1716 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
1717 {
1718 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
1719 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
1720 {
1721 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
1722 rr->ImmedUnicast = mDNSfalse;
1723 rr->v4Requester = zerov4Addr;
1724 rr->v6Requester = zerov6Addr;
1725
1726 // Only sent records registered for P2P over P2P interfaces
1727 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf))
1728 {
1729 LogInfo("SendDelayedUnicastResponse: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, InterfaceID));
1730 continue;
1731 }
1732
1733 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
1734 { rr->NR_AnswerTo = (mDNSu8*)~0; *nrp = rr; nrp = &rr->NextResponse; }
1735 }
1736 }
1737 }
1738
1739 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
1740
1741 while (ResponseRecords)
1742 {
1743 mDNSu8 *responseptr = m->omsg.data;
1744 mDNSu8 *newptr;
1745 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1746
1747 // Put answers in the packet
1748 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
1749 {
1750 rr = ResponseRecords;
1751 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1752 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1753 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
1754 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1755 if (!newptr && m->omsg.h.numAnswers) break; // If packet full, send it now
1756 if (newptr) responseptr = newptr;
1757 ResponseRecords = rr->NextResponse;
1758 rr->NextResponse = mDNSNULL;
1759 rr->NR_AnswerTo = mDNSNULL;
1760 rr->NR_AdditionalTo = mDNSNULL;
1761 rr->RequireGoodbye = mDNStrue;
1762 }
1763
1764 // Add additionals, if there's space
1765 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
1766 {
1767 rr = ResponseRecords;
1768 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1769 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1770 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
1771 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1772
1773 if (newptr) responseptr = newptr;
1774 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
1775 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
1776 ResponseRecords = rr->NextResponse;
1777 rr->NextResponse = mDNSNULL;
1778 rr->NR_AnswerTo = mDNSNULL;
1779 rr->NR_AdditionalTo = mDNSNULL;
1780 }
1781
1782 if (m->omsg.h.numAnswers)
1783 mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
1784 }
1785 }
1786
1787 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1788 // and the client's mStatus_MemFree callback will have been invoked
1789 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
1790 {
1791 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
1792 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
1793 // it should go ahead and immediately dispose of this registration
1794 rr->resrec.RecordType = kDNSRecordTypeShared;
1795 rr->RequireGoodbye = mDNSfalse;
1796 rr->WakeUp.HMAC = zeroEthAddr;
1797 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1798 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
1799 }
1800
1801 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
1802 // any deregistering records that remain in the m->ResourceRecords list.
1803 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
1804 // which may change the record list and/or question list.
1805 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1806 mDNSlocal void DiscardDeregistrations(mDNS *const m)
1807 {
1808 if (m->CurrentRecord)
1809 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
1810 m->CurrentRecord = m->ResourceRecords;
1811
1812 while (m->CurrentRecord)
1813 {
1814 AuthRecord *rr = m->CurrentRecord;
1815 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1816 CompleteDeregistration(m, rr); // Don't touch rr after this
1817 else
1818 m->CurrentRecord = rr->next;
1819 }
1820 }
1821
1822 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
1823 {
1824 int i, val = 0;
1825 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
1826 for (i=1; i<=src[0]; i++)
1827 {
1828 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
1829 val = val * 10 + src[i] - '0';
1830 }
1831 if (val > 255) return(mStatus_Invalid);
1832 *dst = (mDNSu8)val;
1833 return(mStatus_NoError);
1834 }
1835
1836 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
1837 {
1838 int skip = CountLabels(name) - 6;
1839 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
1840 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
1841 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
1842 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
1843 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
1844 a->type = mDNSAddrType_IPv4;
1845 return(mStatus_NoError);
1846 }
1847
1848 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
1849 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
1850 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
1851
1852 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
1853 {
1854 int i, h, l;
1855 const domainname *n;
1856
1857 int skip = CountLabels(name) - 34;
1858 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
1859
1860 n = SkipLeadingLabels(name, skip);
1861 for (i=0; i<16; i++)
1862 {
1863 if (n->c[0] != 1) return mStatus_Invalid;
1864 l = HexVal(n->c[1]);
1865 n = (const domainname *)(n->c + 2);
1866
1867 if (n->c[0] != 1) return mStatus_Invalid;
1868 h = HexVal(n->c[1]);
1869 n = (const domainname *)(n->c + 2);
1870
1871 if (l<0 || h<0) return mStatus_Invalid;
1872 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
1873 }
1874
1875 a->type = mDNSAddrType_IPv6;
1876 return(mStatus_NoError);
1877 }
1878
1879 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
1880 {
1881 int skip = CountLabels(name) - 2;
1882 if (skip >= 0)
1883 {
1884 const domainname *suffix = SkipLeadingLabels(name, skip);
1885 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
1886 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
1887 }
1888 return(mDNSAddrType_None);
1889 }
1890
1891 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
1892 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
1893 {
1894 int i;
1895 mDNSu8 *ptr = m->omsg.data;
1896 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1897 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1898
1899 // 0x00 Destination address
1900 for (i=0; i<6; i++) *ptr++ = dst->b[i];
1901
1902 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1903 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
1904
1905 // 0x0C ARP Ethertype (0x0806)
1906 *ptr++ = 0x08; *ptr++ = 0x06;
1907
1908 // 0x0E ARP header
1909 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
1910 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
1911 *ptr++ = 6; // Hardware address length
1912 *ptr++ = 4; // Protocol address length
1913 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
1914
1915 // 0x16 Sender hardware address (our MAC address)
1916 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
1917
1918 // 0x1C Sender protocol address
1919 for (i=0; i<4; i++) *ptr++ = spa->b[i];
1920
1921 // 0x20 Target hardware address
1922 for (i=0; i<6; i++) *ptr++ = tha->b[i];
1923
1924 // 0x26 Target protocol address
1925 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
1926
1927 // 0x2A Total ARP Packet length 42 bytes
1928 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
1929 }
1930
1931 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
1932 {
1933 const mDNSu16 *ptr = data;
1934 while (length > 0) { length -= 2; sum += *ptr++; }
1935 sum = (sum & 0xFFFF) + (sum >> 16);
1936 sum = (sum & 0xFFFF) + (sum >> 16);
1937 return(sum != 0xFFFF ? sum : 0);
1938 }
1939
1940 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
1941 {
1942 IPv6PseudoHeader ph;
1943 ph.src = *src;
1944 ph.dst = *dst;
1945 ph.len.b[0] = length >> 24;
1946 ph.len.b[1] = length >> 16;
1947 ph.len.b[2] = length >> 8;
1948 ph.len.b[3] = length;
1949 ph.pro.b[0] = 0;
1950 ph.pro.b[1] = 0;
1951 ph.pro.b[2] = 0;
1952 ph.pro.b[3] = protocol;
1953 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
1954 }
1955
1956 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
1957 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
1958 {
1959 int i;
1960 mDNSOpaque16 checksum;
1961 mDNSu8 *ptr = m->omsg.data;
1962 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
1963 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
1964 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
1965 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] } };
1966 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
1967 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1968 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1969
1970 // 0x00 Destination address
1971 for (i=0; i<6; i++) *ptr++ = dst->b[i];
1972 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
1973 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
1974 // link with a pointless link-layer multicast.
1975 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
1976 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
1977 // *ptr++ = 0x33;
1978 // *ptr++ = 0x33;
1979 // *ptr++ = 0xFF;
1980 // *ptr++ = tpa->b[0xD];
1981 // *ptr++ = tpa->b[0xE];
1982 // *ptr++ = tpa->b[0xF];
1983
1984 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1985 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1986
1987 // 0x0C IPv6 Ethertype (0x86DD)
1988 *ptr++ = 0x86; *ptr++ = 0xDD;
1989
1990 // 0x0E IPv6 header
1991 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
1992 *ptr++ = 0x00; *ptr++ = 0x20; // Length
1993 *ptr++ = 0x3A; // Protocol == ICMPv6
1994 *ptr++ = 0xFF; // Hop Limit
1995
1996 // 0x16 Sender IPv6 address
1997 for (i=0; i<16; i++) *ptr++ = spa->b[i];
1998
1999 // 0x26 Destination IPv6 address
2000 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2001
2002 // 0x36 NDP header
2003 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2004 *ptr++ = 0x00; // Code
2005 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
2006 *ptr++ = flags;
2007 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2008
2009 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
2010 {
2011 // 0x3E NDP target.
2012 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2013 // 0x4E Source Link-layer Address
2014 // <http://www.ietf.org/rfc/rfc2461.txt>
2015 // MUST NOT be included when the source IP address is the unspecified address.
2016 // Otherwise, on link layers that have addresses this option MUST be included
2017 // in multicast solicitations and SHOULD be included in unicast solicitations.
2018 if (!mDNSIPv6AddressIsZero(*spa))
2019 {
2020 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2021 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2022 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2023 }
2024 }
2025 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2026 {
2027 // 0x3E NDP target.
2028 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2029 // 0x4E Target Link-layer Address
2030 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2031 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2032 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2033 }
2034
2035 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2036 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
2037 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2038 m->omsg.data[0x38] = checksum.b[0];
2039 m->omsg.data[0x39] = checksum.b[1];
2040
2041 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2042 }
2043
2044 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2045 {
2046 owner->u.owner.vers = 0;
2047 owner->u.owner.seq = m->SleepSeqNum;
2048 owner->u.owner.HMAC = m->PrimaryMAC;
2049 owner->u.owner.IMAC = intf->MAC;
2050 owner->u.owner.password = zeroEthAddr;
2051
2052 // Don't try to compute the optlen until *after* we've set up the data fields
2053 // 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
2054 owner->opt = kDNSOpt_Owner;
2055 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2056 }
2057
2058 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2059 {
2060 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2061 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2062 }
2063
2064 // Note about acceleration of announcements to facilitate automatic coalescing of
2065 // multiple independent threads of announcements into a single synchronized thread:
2066 // The announcements in the packet may be at different stages of maturity;
2067 // One-second interval, two-second interval, four-second interval, and so on.
2068 // After we've put in all the announcements that are due, we then consider
2069 // whether there are other nearly-due announcements that are worth accelerating.
2070 // To be eligible for acceleration, a record MUST NOT be older (further along
2071 // its timeline) than the most mature record we've already put in the packet.
2072 // In other words, younger records can have their timelines accelerated to catch up
2073 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2074 // Older records cannot have their timelines accelerated; this would just widen
2075 // the gap between them and their younger bretheren and get them even more out of sync.
2076
2077 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2078 // the record list and/or question list.
2079 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2080 mDNSlocal void SendResponses(mDNS *const m)
2081 {
2082 int pktcount = 0;
2083 AuthRecord *rr, *r2;
2084 mDNSs32 maxExistingAnnounceInterval = 0;
2085 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2086
2087 m->NextScheduledResponse = m->timenow + 0x78000000;
2088
2089 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2090
2091 for (rr = m->ResourceRecords; rr; rr=rr->next)
2092 if (rr->ImmedUnicast)
2093 {
2094 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2095 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2096 v4.ip.v4 = rr->v4Requester;
2097 v6.ip.v6 = rr->v6Requester;
2098 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2099 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2100 if (rr->ImmedUnicast)
2101 {
2102 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2103 rr->ImmedUnicast = mDNSfalse;
2104 }
2105 }
2106
2107 // ***
2108 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2109 // ***
2110
2111 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2112 for (rr = m->ResourceRecords; rr; rr=rr->next)
2113 {
2114 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2115 if (TimeToAnnounceThisRecord(rr, m->timenow))
2116 {
2117 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2118 {
2119 if (!rr->WakeUp.HMAC.l[0])
2120 {
2121 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
2122 }
2123 else
2124 {
2125 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2126 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
2127 for (r2 = rr; r2; r2=r2->next)
2128 if (r2->AnnounceCount && r2->resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC))
2129 {
2130 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2131 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2132 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2133 {
2134 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2135 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2136 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2137 }
2138 r2->LastAPTime = m->timenow;
2139 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2140 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2141 }
2142 }
2143 }
2144 else if (ResourceRecordIsValidAnswer(rr))
2145 {
2146 if (rr->AddressProxy.type)
2147 {
2148 rr->AnnounceCount--;
2149 rr->ThisAPInterval *= 2;
2150 rr->LastAPTime = m->timenow;
2151 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2152 {
2153 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2154 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2155 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2156 }
2157 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2158 {
2159 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2160 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2161 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2162 }
2163 }
2164 else
2165 {
2166 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2167 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2168 maxExistingAnnounceInterval = rr->ThisAPInterval;
2169 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2170 }
2171 }
2172 }
2173 }
2174
2175 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2176 // Eligible records that are more than half-way to their announcement time are accelerated
2177 for (rr = m->ResourceRecords; rr; rr=rr->next)
2178 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2179 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2180 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2181 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
2182 ResourceRecordIsValidAnswer(rr)))
2183 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2184
2185 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2186 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2187 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2188 // then all that means is that it won't get sent -- which would not be the end of the world.
2189 for (rr = m->ResourceRecords; rr; rr=rr->next)
2190 {
2191 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2192 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
2193 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
2194 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
2195 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
2196 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
2197 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2198 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2199 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
2200 // We also make sure we send the DeviceInfo TXT record too, if necessary
2201 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2202 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2203 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2204 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2205 {
2206 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2207 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2208 }
2209 }
2210
2211 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2212 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2213 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2214 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2215 // -- 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
2216 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2217 for (rr = m->ResourceRecords; rr; rr=rr->next)
2218 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2219 {
2220 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
2221 {
2222 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2223 if (ResourceRecordIsValidAnswer(r2))
2224 if (r2->ImmedAnswer != mDNSInterfaceMark &&
2225 r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(r2, rr))
2226 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2227 }
2228 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
2229 {
2230 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2231 if (ResourceRecordIsValidAnswer(r2))
2232 if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(r2, rr))
2233 r2->ImmedAdditional = rr->ImmedAdditional;
2234 }
2235 }
2236
2237 // Now set SendRNow state appropriately
2238 for (rr = m->ResourceRecords; rr; rr=rr->next)
2239 {
2240 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
2241 {
2242 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2243 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
2244 rr->LastMCTime = m->timenow;
2245 rr->LastMCInterface = rr->ImmedAnswer;
2246 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2247 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2248 {
2249 rr->AnnounceCount--;
2250 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2251 rr->ThisAPInterval *= 2;
2252 rr->LastAPTime = m->timenow;
2253 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2254 }
2255 }
2256 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
2257 {
2258 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
2259 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
2260 rr->LastMCTime = m->timenow;
2261 rr->LastMCInterface = rr->ImmedAnswer;
2262 }
2263 SetNextAnnounceProbeTime(m, rr);
2264 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2265 }
2266
2267 // ***
2268 // *** 2. Loop through interface list, sending records as appropriate
2269 // ***
2270
2271 while (intf)
2272 {
2273 const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2274 int numDereg = 0;
2275 int numAnnounce = 0;
2276 int numAnswer = 0;
2277 mDNSu8 *responseptr = m->omsg.data;
2278 mDNSu8 *newptr;
2279 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2280
2281 // First Pass. Look for:
2282 // 1. Deregistering records that need to send their goodbye packet
2283 // 2. Updated records that need to retract their old data
2284 // 3. Answers and announcements we need to send
2285 for (rr = m->ResourceRecords; rr; rr=rr->next)
2286 {
2287
2288 // Skip this interface if the record InterfaceID is *Any and the record is not
2289 // appropriate for the interface type.
2290 if ((rr->SendRNow == intf->InterfaceID) &&
2291 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf)))
2292 {
2293 LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
2294 rr->SendRNow = GetNextActiveInterfaceID(intf);
2295 }
2296 else if (rr->SendRNow == intf->InterfaceID)
2297 {
2298 RData *OldRData = rr->resrec.rdata;
2299 mDNSu16 oldrdlength = rr->resrec.rdlength;
2300 mDNSu8 active = (mDNSu8)
2301 (rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
2302 (m->SleepState != SleepState_Sleeping || intf->SPSAddr[0].type || intf->SPSAddr[1].type || intf->SPSAddr[2].type));
2303 newptr = mDNSNULL;
2304 if (rr->NewRData && active)
2305 {
2306 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2307 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2308 {
2309 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2310 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2311 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
2312 }
2313 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2314 }
2315
2316 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2317 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2318 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2319 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2320 if (newptr)
2321 {
2322 responseptr = newptr;
2323 rr->RequireGoodbye = active;
2324 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2325 else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2326 }
2327
2328 if (rr->NewRData && active)
2329 SetNewRData(&rr->resrec, OldRData, oldrdlength);
2330
2331 // The first time through (pktcount==0), if this record is verified unique
2332 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2333 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2334 rr->SendNSECNow = mDNSInterfaceMark;
2335
2336 if (newptr) // If succeeded in sending, advance to next interface
2337 {
2338 // If sending on all interfaces, go to next interface; else we're finished now
2339 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2340 rr->SendRNow = GetNextActiveInterfaceID(intf);
2341 else
2342 rr->SendRNow = mDNSNULL;
2343 }
2344 }
2345 }
2346
2347 // Second Pass. Add additional records, if there's space.
2348 newptr = responseptr;
2349 for (rr = m->ResourceRecords; rr; rr=rr->next)
2350 if (rr->ImmedAdditional == intf->InterfaceID)
2351 if (ResourceRecordIsValidAnswer(rr))
2352 {
2353 // If we have at least one answer already in the packet, then plan to add additionals too
2354 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2355
2356 // If we're not planning to send any additionals, but this record is a unique one, then
2357 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2358 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2359 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2360 {
2361 const AuthRecord *a;
2362 for (a = m->ResourceRecords; a; a=a->next)
2363 if (a->LastMCTime == m->timenow &&
2364 a->LastMCInterface == intf->InterfaceID &&
2365 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2366 }
2367 if (!SendAdditional) // If we don't want to send this after all,
2368 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
2369 else if (newptr) // Else, try to add it if we can
2370 {
2371 // The first time through (pktcount==0), if this record is verified unique
2372 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2373 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2374 rr->SendNSECNow = mDNSInterfaceMark;
2375
2376 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2377 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2378 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2379 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2380 if (newptr)
2381 {
2382 responseptr = newptr;
2383 rr->ImmedAdditional = mDNSNULL;
2384 rr->RequireGoodbye = mDNStrue;
2385 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2386 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2387 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2388 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2389 rr->LastMCTime = m->timenow;
2390 rr->LastMCInterface = intf->InterfaceID;
2391 }
2392 }
2393 }
2394
2395 // Third Pass. Add NSEC records, if there's space.
2396 // When we're generating an NSEC record in response to a specify query for that type
2397 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2398 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2399 for (rr = m->ResourceRecords; rr; rr=rr->next)
2400 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2401 {
2402 AuthRecord nsec;
2403 mDNSu8 *ptr;
2404 int len;
2405 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2406 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2407 AssignDomainName(&nsec.namestorage, rr->resrec.name);
2408 ptr = nsec.rdatastorage.u.data;
2409 len = DomainNameLength(rr->resrec.name);
2410 // We have a nxt name followed by window number, window length and a window bitmap
2411 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
2412 if (nsec.resrec.rdlength <= StandardAuthRDSize)
2413 {
2414 mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
2415 AssignDomainName((domainname *)ptr, rr->resrec.name);
2416 ptr += len;
2417 *ptr++ = 0; // window number
2418 *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
2419 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2420 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2421 {
2422 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2423 else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2424 }
2425 newptr = responseptr;
2426 if (!r2) // If we successfully built our NSEC record, add it to the packet now
2427 {
2428 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2429 if (newptr) responseptr = newptr;
2430 }
2431 }
2432 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength);
2433
2434 // If we successfully put the NSEC record, clear the SendNSECNow flag
2435 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2436 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2437 {
2438 rr->SendNSECNow = mDNSNULL;
2439 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2440 for (r2 = rr->next; r2; r2=r2->next)
2441 if (SameResourceRecordNameClassInterface(r2, rr))
2442 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2443 r2->SendNSECNow = mDNSNULL;
2444 }
2445 }
2446
2447 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2448 {
2449 // If we have data to send, add OWNER option if necessary, then send packet
2450
2451 if (OwnerRecordSpace)
2452 {
2453 AuthRecord opt;
2454 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2455 opt.resrec.rrclass = NormalMaxDNSMessageData;
2456 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
2457 opt.resrec.rdestimate = sizeof(rdataOPT);
2458 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2459 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2460 if (newptr) { responseptr = newptr; LogSPS("SendResponses put %s", ARDisplayString(m, &opt)); }
2461 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2462 LogSPS("SendResponses: No space in packet for Owner OPT record (%d/%d/%d/%d) %s",
2463 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2464 else
2465 LogMsg("SendResponses: How did we fail to have space for Owner OPT record (%d/%d/%d/%d) %s",
2466 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2467 }
2468
2469 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2470 numDereg, numDereg == 1 ? "" : "s",
2471 numAnnounce, numAnnounce == 1 ? "" : "s",
2472 numAnswer, numAnswer == 1 ? "" : "s",
2473 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2474
2475 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2476 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2477 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2478 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
2479 // There might be more things to send on this interface, so go around one more time and try again.
2480 }
2481 else // Nothing more to send on this interface; go to next
2482 {
2483 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
2484 #if MDNS_DEBUGMSGS && 0
2485 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2486 debugf(msg, intf, next);
2487 #endif
2488 intf = next;
2489 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2490 }
2491 }
2492
2493 // ***
2494 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2495 // ***
2496
2497 if (m->CurrentRecord)
2498 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2499 m->CurrentRecord = m->ResourceRecords;
2500 while (m->CurrentRecord)
2501 {
2502 rr = m->CurrentRecord;
2503 m->CurrentRecord = rr->next;
2504
2505 if (rr->SendRNow)
2506 {
2507 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
2508 LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr->SendRNow, rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
2509 rr->SendRNow = mDNSNULL;
2510 }
2511
2512 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2513 {
2514 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
2515
2516 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
2517 {
2518 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
2519 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
2520 }
2521 else
2522 {
2523 rr->ImmedAnswer = mDNSNULL;
2524 rr->ImmedUnicast = mDNSfalse;
2525 rr->v4Requester = zerov4Addr;
2526 rr->v6Requester = zerov6Addr;
2527 }
2528 }
2529 }
2530 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
2531 }
2532
2533 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2534 // so we want to be lazy about how frequently we do it.
2535 // 1. If a cache record is currently referenced by *no* active questions,
2536 // then we don't mind expiring it up to a minute late (who will know?)
2537 // 2. Else, if a cache record is due for some of its final expiration queries,
2538 // we'll allow them to be late by up to 2% of the TTL
2539 // 3. Else, if a cache record has completed all its final expiration queries without success,
2540 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2541 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2542 // so allow at most 1/10 second lateness
2543 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2544 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2545 #define CacheCheckGracePeriod(RR) ( \
2546 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
2547 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
2548 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
2549 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
2550
2551 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2552
2553 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
2554 {
2555 if (m->rrcache_nextcheck[slot] - event > 0)
2556 m->rrcache_nextcheck[slot] = event;
2557 if (m->NextCacheCheck - event > 0)
2558 m->NextCacheCheck = event;
2559 }
2560
2561 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2562 // rr->TimeRcvd
2563 // rr->resrec.rroriginalttl
2564 // rr->UnansweredQueries
2565 // rr->CRActiveQuestion
2566 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
2567 {
2568 rr->NextRequiredQuery = RRExpireTime(rr);
2569
2570 // If we have an active question, then see if we want to schedule a refresher query for this record.
2571 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2572 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
2573 {
2574 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
2575 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
2576 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2577 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
2578 }
2579
2580 ScheduleNextCacheCheckTime(m, HashSlot(rr->resrec.name), NextCacheCheckEvent(rr));
2581 }
2582
2583 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
2584 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
2585 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
2586 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 30)
2587
2588 mDNSlocal mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
2589 {
2590 if (interval < kMinimumReconfirmTime)
2591 interval = kMinimumReconfirmTime;
2592 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
2593 interval = 0x10000000;
2594
2595 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2596 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
2597 {
2598 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2599 // For all the reconfirmations in a given batch, we want to use the same random value
2600 // so that the reconfirmation questions can be grouped into a single query packet
2601 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(0x3FFFFFFF);
2602 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
2603 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
2604 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
2605 SetNextCacheCheckTimeForRecord(m, rr);
2606 }
2607 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2608 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
2609 return(mStatus_NoError);
2610 }
2611
2612 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
2613
2614 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2615 // It also appends to the list of known answer records that need to be included,
2616 // and updates the forcast for the size of the known answer section.
2617 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
2618 CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
2619 {
2620 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353;
2621 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2622 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
2623 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
2624 if (!newptr)
2625 {
2626 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2627 return(mDNSfalse);
2628 }
2629 else
2630 {
2631 mDNSu32 forecast = *answerforecast;
2632 const mDNSu32 slot = HashSlot(&q->qname);
2633 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2634 CacheRecord *rr;
2635 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
2636
2637 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
2638 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2639 !(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
2640 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not already in the known answer list
2641 rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
2642 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
2643 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
2644 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
2645 {
2646 // We don't want to include unique records in the Known Answer section. The Known Answer section
2647 // is intended to suppress floods of shared-record replies from many other devices on the network.
2648 // That concept really does not apply to unique records, and indeed if we do send a query for
2649 // which we have a unique record already in our cache, then including that unique record as a
2650 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2651
2652 *ka = rr; // Link this record into our known answer chain
2653 ka = &rr->NextInKAList;
2654 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2655 forecast += 12 + rr->resrec.rdestimate;
2656 // If we're trying to put more than one question in this packet, and it doesn't fit
2657 // then undo that last question and try again next time
2658 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
2659 {
2660 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
2661 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data);
2662 query->h.numQuestions--;
2663 ka = *kalistptrptr; // Go back to where we started and retract these answer records
2664 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
2665 return(mDNSfalse); // Return false, so we'll try again in the next packet
2666 }
2667 }
2668
2669 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2670 *queryptr = newptr; // Update the packet pointer
2671 *answerforecast = forecast; // Update the forecast
2672 *kalistptrptr = ka; // Update the known answer list pointer
2673 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
2674
2675 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // For every resource record in our cache,
2676 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2677 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not in the known answer list
2678 SameNameRecordAnswersQuestion(&rr->resrec, q)) // which answers our question
2679 {
2680 rr->UnansweredQueries++; // indicate that we're expecting a response
2681 rr->LastUnansweredTime = m->timenow;
2682 SetNextCacheCheckTimeForRecord(m, rr);
2683 }
2684
2685 return(mDNStrue);
2686 }
2687 }
2688
2689 // When we have a query looking for a specified name, but there appear to be no answers with
2690 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
2691 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
2692 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
2693 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
2694 // A typical reconfirmation scenario might go like this:
2695 // Depth 0: Name "myhost.local" has no address records
2696 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
2697 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
2698 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
2699 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
2700 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
2701 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
2702 {
2703 mDNSu32 slot;
2704 CacheGroup *cg;
2705 CacheRecord *cr;
2706 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
2707 FORALL_CACHERECORDS(slot, cg, cr)
2708 {
2709 domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
2710 if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
2711 {
2712 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
2713 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
2714 if (depth < 5)
2715 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
2716 }
2717 }
2718 }
2719
2720 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
2721 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
2722 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
2723 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
2724 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
2725 {
2726 CacheGroup *const cg = CacheGroupForName(m, HashSlot(name), namehash, name);
2727 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
2728 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
2729 return(cr);
2730 }
2731
2732 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
2733 {
2734 CacheGroup *const cg = CacheGroupForName(m, HashSlot(&q->qname), q->qnamehash, &q->qname);
2735 const CacheRecord *cr, *bestcr = mDNSNULL;
2736 mDNSu32 bestmetric = 1000000;
2737 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
2738 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
2739 if (cr != c0 && cr != c1) // that's not one we've seen before,
2740 if (SameNameRecordAnswersQuestion(&cr->resrec, q)) // and answers our browse query,
2741 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
2742 {
2743 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
2744 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
2745 }
2746 return(bestcr);
2747 }
2748
2749 mDNSlocal void CheckAndSwapSPS(const CacheRecord *sps1, const CacheRecord *sps2)
2750 {
2751 const CacheRecord *swap_sps;
2752 mDNSu32 metric1, metric2;
2753
2754 if (!sps1 || !sps2) return;
2755 metric1 = SPSMetric(sps1->resrec.rdata->u.name.c);
2756 metric2 = SPSMetric(sps2->resrec.rdata->u.name.c);
2757 if (!SPSFeatures(sps1->resrec.rdata->u.name.c) && SPSFeatures(sps2->resrec.rdata->u.name.c) && (metric2 >= metric1))
2758 {
2759 swap_sps = sps1;
2760 sps1 = sps2;
2761 sps2 = swap_sps;
2762 }
2763 }
2764
2765 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
2766 {
2767 CheckAndSwapSPS(sps[0], sps[1]);
2768 CheckAndSwapSPS(sps[0], sps[2]);
2769 CheckAndSwapSPS(sps[1], sps[2]);
2770 }
2771
2772
2773 // Finds the three best Sleep Proxies we currently have in our cache
2774 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
2775 {
2776 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
2777 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
2778 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
2779
2780 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
2781 // only if they have equally good metric and support features.
2782 ReorderSPSByFeature(sps);
2783 }
2784
2785 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
2786 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
2787 {
2788 int i;
2789 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2790 }
2791
2792 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
2793 {
2794 int i;
2795 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2796 }
2797
2798 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
2799 {
2800 int i;
2801 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
2802 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
2803 for (i=0; i<DupSuppressInfoSize; i++)
2804 if (ds[i].InterfaceID == intf->InterfaceID)
2805 {
2806 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
2807 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
2808 if (v4 && v6) return(mDNStrue);
2809 }
2810 return(mDNSfalse);
2811 }
2812
2813 mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
2814 {
2815 int i, j;
2816
2817 // See if we have this one in our list somewhere already
2818 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
2819
2820 // If not, find a slot we can re-use
2821 if (i >= DupSuppressInfoSize)
2822 {
2823 i = 0;
2824 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
2825 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
2826 i = j;
2827 }
2828
2829 // Record the info about this query we saw
2830 ds[i].Time = Time;
2831 ds[i].InterfaceID = InterfaceID;
2832 ds[i].Type = Type;
2833
2834 return(i);
2835 }
2836
2837 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
2838 {
2839 int len, i, cnt;
2840 mDNSInterfaceID InterfaceID = q->InterfaceID;
2841 domainname *d = &q->qname;
2842
2843 // We can't send magic packets without knowing which interface to send it on.
2844 if (InterfaceID == mDNSInterface_Any || InterfaceID == mDNSInterface_LocalOnly || InterfaceID == mDNSInterface_P2P)
2845 {
2846 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
2847 return;
2848 }
2849
2850 // Split MAC@IPAddress and pass them separately
2851 len = d->c[0];
2852 i = 1;
2853 cnt = 0;
2854 for (i = 1; i < len; i++)
2855 {
2856 if (d->c[i] == '@')
2857 {
2858 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
2859 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
2860 if (cnt != 5)
2861 {
2862 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
2863 return;
2864 }
2865 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
2866 {
2867 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
2868 return;
2869 }
2870 if ((len - i) > (int)(sizeof(IPAddr) - 1))
2871 {
2872 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
2873 return;
2874 }
2875 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
2876 EthAddr[i - 1] = 0;
2877 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
2878 IPAddr[len - i] = 0;
2879 mDNSPlatformSendWakeupPacket(m, InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
2880 return;
2881 }
2882 else if (d->c[i] == ':')
2883 cnt++;
2884 }
2885 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
2886 }
2887
2888
2889 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
2890 {
2891 // If more than 90% of the way to the query time, we should unconditionally accelerate it
2892 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
2893 return(mDNStrue);
2894
2895 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
2896 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
2897 {
2898 // We forecast: qname (n) type (2) class (2)
2899 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
2900 const mDNSu32 slot = HashSlot(&q->qname);
2901 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2902 const CacheRecord *rr;
2903 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
2904 if (rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
2905 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
2906 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
2907 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
2908 {
2909 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2910 forecast += 12 + rr->resrec.rdestimate;
2911 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
2912 }
2913 return(mDNStrue);
2914 }
2915
2916 return(mDNSfalse);
2917 }
2918
2919 // How Standard Queries are generated:
2920 // 1. The Question Section contains the question
2921 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
2922
2923 // How Probe Queries are generated:
2924 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
2925 // if some other host is already using *any* records with this name, we want to know about it.
2926 // 2. The Authority Section contains the proposed values we intend to use for one or more
2927 // of our records with that name (analogous to the Update section of DNS Update packets)
2928 // because if some other host is probing at the same time, we each want to know what the other is
2929 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
2930
2931 mDNSlocal void SendQueries(mDNS *const m)
2932 {
2933 mDNSu32 slot;
2934 CacheGroup *cg;
2935 CacheRecord *cr;
2936 AuthRecord *ar;
2937 int pktcount = 0;
2938 DNSQuestion *q;
2939 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
2940 mDNSs32 maxExistingQuestionInterval = 0;
2941 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2942 CacheRecord *KnownAnswerList = mDNSNULL;
2943
2944 // 1. If time for a query, work out what we need to do
2945
2946 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
2947 // to their NextRequiredQuery to be worth batching them together with this one
2948 FORALL_CACHERECORDS(slot, cg, cr)
2949 {
2950 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
2951 {
2952 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
2953 {
2954 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
2955 q = cr->CRActiveQuestion;
2956 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
2957 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
2958 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
2959 if (q->Target.type)
2960 {
2961 q->SendQNow = mDNSInterfaceMark; // If targeted query, mark it
2962 }
2963 else if (!mDNSOpaque16IsZero(q->TargetQID))
2964 {
2965 q->LastQTime = m->timenow - q->ThisQInterval;
2966 cr->UnansweredQueries++;
2967 }
2968 else if (q->SendQNow == mDNSNULL)
2969 {
2970 q->SendQNow = cr->resrec.InterfaceID;
2971 }
2972 else if (q->SendQNow != cr->resrec.InterfaceID)
2973 {
2974 q->SendQNow = mDNSInterfaceMark;
2975 }
2976 }
2977 }
2978 }
2979
2980 // Scan our list of questions to see which:
2981 // *WideArea* queries need to be sent
2982 // *unicast* queries need to be sent
2983 // *multicast* queries we're definitely going to send
2984 if (m->CurrentQuestion)
2985 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2986 m->CurrentQuestion = m->Questions;
2987 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
2988 {
2989 q = m->CurrentQuestion;
2990 if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
2991 {
2992 mDNSu8 *qptr = m->omsg.data;
2993 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
2994
2995 // 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
2996 if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
2997 if (q->LocalSocket)
2998 {
2999 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
3000 qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
3001 mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL, q->UseBrackgroundTrafficClass);
3002 q->ThisQInterval *= QuestionIntervalStep;
3003 }
3004 if (q->ThisQInterval > MaxQuestionInterval)
3005 q->ThisQInterval = MaxQuestionInterval;
3006 q->LastQTime = m->timenow;
3007 q->LastQTxTime = m->timenow;
3008 q->RecentAnswerPkts = 0;
3009 q->SendQNow = mDNSNULL;
3010 q->ExpectUnicastResp = NonZeroTime(m->timenow);
3011 }
3012 else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
3013 {
3014 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3015 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3016 if (maxExistingQuestionInterval < q->ThisQInterval)
3017 maxExistingQuestionInterval = q->ThisQInterval;
3018 }
3019 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3020 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3021 // m->CurrentQuestion point to the right question
3022 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3023 }
3024 while (m->CurrentQuestion)
3025 {
3026 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3027 m->CurrentQuestion = m->CurrentQuestion->next;
3028 }
3029 m->CurrentQuestion = mDNSNULL;
3030
3031 // Scan our list of questions
3032 // (a) to see if there are any more that are worth accelerating, and
3033 // (b) to update the state variables for *all* the questions we're going to send
3034 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3035 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3036 // 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.
3037 m->NextScheduledQuery = m->timenow + 0x78000000;
3038 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3039 {
3040 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow ||
3041 (!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3042 {
3043 // If at least halfway to next query time, advance to next interval
3044 // If less than halfway to next query time, then
3045 // treat this as logically a repeat of the last transmission, without advancing the interval
3046 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3047 {
3048 //LogInfo("Accelerating %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3049 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3050 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3051 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3052 q->ThisQInterval *= QuestionIntervalStep;
3053 if (q->ThisQInterval > MaxQuestionInterval)
3054 q->ThisQInterval = MaxQuestionInterval;
3055 else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3056 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3057 {
3058 // Generally don't need to log this.
3059 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3060 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3061 // and when there simply happen to be no instances of the service the client is looking
3062 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3063 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3064 q->qname.c, DNSTypeName(q->qtype));
3065 // Sending third query, and no answers yet; time to begin doubting the source
3066 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3067 }
3068 }
3069
3070 // Mark for sending. (If no active interfaces, then don't even try.)
3071 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3072 if (q->SendOnAll)
3073 {
3074 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3075 q->LastQTime = m->timenow;
3076 }
3077
3078 // If we recorded a duplicate suppression for this question less than half an interval ago,
3079 // then we consider it recent enough that we don't need to do an identical query ourselves.
3080 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3081
3082 q->LastQTxTime = m->timenow;
3083 q->RecentAnswerPkts = 0;
3084 if (q->RequestUnicast) q->RequestUnicast--;
3085 }
3086 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3087 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3088 SetNextQueryTime(m,q);
3089 }
3090
3091 // 2. Scan our authoritative RR list to see what probes we might need to send
3092
3093 m->NextScheduledProbe = m->timenow + 0x78000000;
3094
3095 if (m->CurrentRecord)
3096 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3097 m->CurrentRecord = m->ResourceRecords;
3098 while (m->CurrentRecord)
3099 {
3100 ar = m->CurrentRecord;
3101 m->CurrentRecord = ar->next;
3102 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
3103 {
3104 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3105 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3106 {
3107 SetNextAnnounceProbeTime(m, ar);
3108 }
3109 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3110 else if (ar->ProbeCount)
3111 {
3112 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3113 {
3114 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3115 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3116 }
3117 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3118 {
3119 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3120 // IPv6 source = zero
3121 // No target hardware address
3122 // IPv6 target address is address we're probing
3123 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3124 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3125 }
3126 // Mark for sending. (If no active interfaces, then don't even try.)
3127 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3128 ar->LastAPTime = m->timenow;
3129 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3130 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3131 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3132 ar->ProbeCount = DefaultProbeCountForTypeUnique;
3133 ar->ProbeCount--;
3134 SetNextAnnounceProbeTime(m, ar);
3135 if (ar->ProbeCount == 0)
3136 {
3137 // If this is the last probe for this record, then see if we have any matching records
3138 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3139 AuthRecord *r2;
3140 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3141 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3142 r2->ProbeCount = 0;
3143 // ... then acknowledge this record to the client.
3144 // We do this optimistically, just as we're about to send the third probe.
3145 // This helps clients that both advertise and browse, and want to filter themselves
3146 // from the browse results list, because it helps ensure that the registration
3147 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3148 // A potential downside is that we could deliver a registration confirmation and then find out
3149 // moments later that there's a name conflict, but applications have to be prepared to handle
3150 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3151 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3152 }
3153 }
3154 // else, if it has now finished probing, move it to state Verified,
3155 // and update m->NextScheduledResponse so it will be announced
3156 else
3157 {
3158 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
3159 ar->resrec.RecordType = kDNSRecordTypeVerified;
3160 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3161 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3162 SetNextAnnounceProbeTime(m, ar);
3163 }
3164 }
3165 }
3166 m->CurrentRecord = m->DuplicateRecords;
3167 while (m->CurrentRecord)
3168 {
3169 ar = m->CurrentRecord;
3170 m->CurrentRecord = ar->next;
3171 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3172 AcknowledgeRecord(m, ar);
3173 }
3174
3175 // 3. Now we know which queries and probes we're sending,
3176 // go through our interface list sending the appropriate queries on each interface
3177 while (intf)
3178 {
3179 const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3180 mDNSu8 *queryptr = m->omsg.data;
3181 mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class
3182
3183 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3184 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3185 if (!KnownAnswerList)
3186 {
3187 // Start a new known-answer list
3188 CacheRecord **kalistptr = &KnownAnswerList;
3189 mDNSu32 answerforecast = OwnerRecordSpace; // We start by assuming we'll need at least enough space to put the Owner Option
3190
3191 // Put query questions in this packet
3192 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3193 {
3194 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3195 {
3196 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3197 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
3198 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3199
3200 // If interface is P2P type, verify that query should be sent over it.
3201 if (!mDNSPlatformValidQuestionForInterface(q, intf))
3202 {
3203 LogInfo("SendQueries: Not sending (%s) %##s on %s", DNSTypeName(q->qtype), q->qname.c, InterfaceNameForID(m, intf->InterfaceID));
3204 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3205 }
3206 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3207 else if (SuppressOnThisInterface(q->DupSuppress, intf) ||
3208 BuildQuestion(m, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3209 {
3210 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3211 if (q->WakeOnResolveCount)
3212 {
3213 mDNSSendWakeOnResolve(m, q);
3214 q->WakeOnResolveCount--;
3215 }
3216
3217 // use brackground traffic class if any included question requires it
3218 if (q->UseBrackgroundTrafficClass)
3219 {
3220 useBackgroundTrafficClass = mDNStrue;
3221 }
3222 }
3223 }
3224 }
3225
3226 // Put probe questions in this packet
3227 for (ar = m->ResourceRecords; ar; ar=ar->next)
3228 if (ar->SendRNow == intf->InterfaceID)
3229 {
3230 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353;
3231 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3232 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3233 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3234 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3235 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, (mDNSu16)(ar->resrec.rrclass | ucbit));
3236 if (newptr)
3237 {
3238 queryptr = newptr;
3239 answerforecast = forecast;
3240 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3241 ar->IncludeInProbe = mDNStrue;
3242 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d",
3243 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount);
3244 }
3245 }
3246 }
3247
3248 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3249 while (KnownAnswerList)
3250 {
3251 CacheRecord *ka = KnownAnswerList;
3252 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3253 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers,
3254 &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd, m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace);
3255 if (newptr)
3256 {
3257 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3258 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3259 queryptr = newptr;
3260 KnownAnswerList = ka->NextInKAList;
3261 ka->NextInKAList = mDNSNULL;
3262 }
3263 else
3264 {
3265 // If we ran out of space and we have more than one question in the packet, that's an error --
3266 // we shouldn't have put more than one question if there was a risk of us running out of space.
3267 if (m->omsg.h.numQuestions > 1)
3268 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3269 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3270 break;
3271 }
3272 }
3273
3274 for (ar = m->ResourceRecords; ar; ar=ar->next)
3275 if (ar->IncludeInProbe)
3276 {
3277 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3278 ar->IncludeInProbe = mDNSfalse;
3279 if (newptr) queryptr = newptr;
3280 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3281 }
3282
3283 if (queryptr > m->omsg.data)
3284 {
3285 if (OwnerRecordSpace)
3286 {
3287 AuthRecord opt;
3288 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3289 opt.resrec.rrclass = NormalMaxDNSMessageData;
3290 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
3291 opt.resrec.rdestimate = sizeof(rdataOPT);
3292 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3293 LogSPS("SendQueries putting %s", ARDisplayString(m, &opt));
3294 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3295 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3296 if (!queryptr)
3297 LogMsg("SendQueries: How did we fail to have space for the OPT record (%d/%d/%d/%d) %s",
3298 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3299 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3300 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3301 LogMsg("SendQueries: Why did we generate oversized packet with OPT record %p %p %p (%d/%d/%d/%d) %s",
3302 m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr,
3303 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3304 }
3305
3306 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3307 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3308 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
3309 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
3310 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
3311 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3312 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3313 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3314 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3315 if (++pktcount >= 1000)
3316 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3317 // There might be more records left in the known answer list, or more questions to send
3318 // on this interface, so go around one more time and try again.
3319 }
3320 else // Nothing more to send on this interface; go to next
3321 {
3322 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3323 #if MDNS_DEBUGMSGS && 0
3324 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
3325 debugf(msg, intf, next);
3326 #endif
3327 intf = next;
3328 }
3329 }
3330
3331 // 4. Final housekeeping
3332
3333 // 4a. Debugging check: Make sure we announced all our records
3334 for (ar = m->ResourceRecords; ar; ar=ar->next)
3335 if (ar->SendRNow)
3336 {
3337 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
3338 LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar->SendRNow, ar->resrec.InterfaceID, ARDisplayString(m, ar));
3339 ar->SendRNow = mDNSNULL;
3340 }
3341
3342 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3343 // that their interface which went away might come back again, the logic will want to send queries
3344 // for those records, but we can't because their interface isn't here any more, so to keep the
3345 // state machine ticking over we just pretend we did so.
3346 // If the interface does not come back in time, the cache record will expire naturally
3347 FORALL_CACHERECORDS(slot, cg, cr)
3348 {
3349 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3350 {
3351 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3352 {
3353 cr->UnansweredQueries++;
3354 cr->CRActiveQuestion->SendQNow = mDNSNULL;
3355 SetNextCacheCheckTimeForRecord(m, cr);
3356 }
3357 }
3358 }
3359
3360 // 4c. Debugging check: Make sure we sent all our planned questions
3361 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3362 // we legitimately couldn't send because the interface is no longer available
3363 for (q = m->Questions; q; q=q->next)
3364 if (q->SendQNow)
3365 {
3366 DNSQuestion *x;
3367 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
3368 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));
3369 q->SendQNow = mDNSNULL;
3370 }
3371 }
3372
3373 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password)
3374 {
3375 int i, j;
3376 mDNSu8 *ptr = m->omsg.data;
3377 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
3378 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
3379
3380 // 0x00 Destination address
3381 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3382
3383 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
3384 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
3385
3386 // 0x0C Ethertype (0x0842)
3387 *ptr++ = 0x08;
3388 *ptr++ = 0x42;
3389
3390 // 0x0E Wakeup sync sequence
3391 for (i=0; i<6; i++) *ptr++ = 0xFF;
3392
3393 // 0x14 Wakeup data
3394 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3395
3396 // 0x74 Password
3397 for (i=0; i<6; i++) *ptr++ = password->b[i];
3398
3399 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3400
3401 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
3402 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
3403 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
3404 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
3405 // So, we send one of each, unicast first, then broadcast second.
3406 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
3407 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3408 }
3409
3410 // ***************************************************************************
3411 #if COMPILER_LIKES_PRAGMA_MARK
3412 #pragma mark -
3413 #pragma mark - RR List Management & Task Management
3414 #endif
3415
3416 // Whenever a question is answered, reset its state so that we don't query
3417 // the network repeatedly. This happens first time when we answer the question and
3418 // and later when we refresh the cache.
3419 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
3420 {
3421 q->LastQTime = m->timenow;
3422 q->LastQTxTime = m->timenow;
3423 q->RecentAnswerPkts = 0;
3424 q->ThisQInterval = MaxQuestionInterval;
3425 q->RequestUnicast = mDNSfalse;
3426 // Reset unansweredQueries so that we don't penalize this server later when we
3427 // start sending queries when the cache expires.
3428 q->unansweredQueries = 0;
3429 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3430 }
3431
3432 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
3433 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
3434 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
3435 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
3436 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
3437 {
3438 DNSQuestion *const q = m->CurrentQuestion;
3439 mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
3440
3441 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
3442 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
3443
3444 // When the response for the question was validated, the entire rrset was validated. If we deliver
3445 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
3446 // in the future, we will do the revalidation again.
3447 //
3448 // Also, if we deliver an ADD for a negative cache record and it has no NSECS, the ValidationStatus needs
3449 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
3450 // negative response which can happen e.g., when disconnecting from network. As we don't deliver RMVs for
3451 // negative responses that were delivered before, we need to do it on the next ADD of a negative cache
3452 // record. This ADD could be the result of a timeout, no DNS servers etc. If we don't reset the state, we
3453 // will deliver this as a secure response.
3454 if (q->ValidationRequired && ((AddRecord == QC_rmv) ||
3455 (rr->resrec.RecordType == kDNSRecordTypePacketNegative && !rr->nsec)))
3456 {
3457 q->ValidationStatus = 0;
3458 q->ValidationState = DNSSECValRequired;
3459 }
3460
3461 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
3462 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
3463 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
3464 // we check to see if that query already has a unique local answer.
3465 if (q->LOAddressAnswers)
3466 {
3467 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
3468 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
3469 q->LOAddressAnswers);
3470 return;
3471 }
3472
3473 if (QuerySuppressed(q))
3474 {
3475 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
3476 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
3477 // that are timing out, which we know are answered with Negative cache record when timing out.
3478 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
3479 return;
3480 }
3481
3482 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
3483 // may be called twice, once when the record is received, and again when it's time to notify local clients.
3484 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
3485
3486 rr->LastUsed = m->timenow;
3487 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
3488 {
3489 if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
3490 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
3491 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
3492 rr->CRActiveQuestion = q; // We know q is non-null
3493 SetNextCacheCheckTimeForRecord(m, rr);
3494 }
3495
3496 // If this is:
3497 // (a) a no-cache add, where we've already done at least one 'QM' query, or
3498 // (b) a normal add, where we have at least one unique-type answer,
3499 // then there's no need to keep polling the network.
3500 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
3501 // We do this for mDNS questions and uDNS one-shot questions, but not for
3502 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
3503 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
3504 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
3505 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
3506 {
3507 ResetQuestionState(m, q);
3508 }
3509
3510 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
3511
3512 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
3513 // for the purpose of retrying search domains
3514 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
3515 if (!AddRecord || (AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
3516
3517 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
3518 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
3519 {
3520 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
3521 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
3522 {
3523 CacheRecord neg;
3524 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
3525 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
3526 }
3527 else
3528 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
3529 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3530 }
3531 // If this is an "Add" operation and this question needs validation, validate the response.
3532 // In the case of negative responses, extra care should be taken. Negative cache records are
3533 // used for many purposes. For example,
3534 //
3535 // 1) Suppressing questions (SuppressUnusable)
3536 // 2) Timeout questions
3537 // 3) The name does not exist
3538 // 4) No DNS servers are available and we need a quick response for the application
3539 //
3540 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" in that case.
3541 // For (3), it is possible that we don't get nsecs back but we still need to call VerifySignature so
3542 // that we can deliver the appropriate DNSSEC result. There is no point in verifying signature for (4)
3543 // and hence the explicit check for q->qDNSServer.
3544 //
3545 // Note: It is important that we avoid (4) here because once the state is set to DNSSECValInProgress,
3546 // we won't verify the signature when it is really needed. For example, start a query (which is answered
3547 // securely), disconnect from the network. (3) would happen now and if we start the verification, we
3548 // move DNSSECValInProgress but never have a chance to go back to DNSSECValRequired as we don't deliver
3549 // RMVs for negative response that was added before.
3550 //
3551 if (m->CurrentQuestion == q && (AddRecord == QC_add) && !q->ValidatingResponse &&
3552 q->ValidationState == DNSSECValRequired && q->qDNSServer)
3553 {
3554 q->ValidationState = DNSSECValInProgress;
3555 // Treat it as callback call as that's what dnssec code expects
3556 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
3557 VerifySignature(m, mDNSNULL, q);
3558 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3559 return;
3560 }
3561
3562 // Note: Proceed with caution here because client callback function is allowed to do anything,
3563 // including starting/stopping queries, registering/deregistering records, etc.
3564 //
3565 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
3566 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
3567 // first before following it
3568 if (!DNSSECQuestion(q) && followcname && m->CurrentQuestion == q)
3569 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
3570 }
3571
3572 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
3573 {
3574 rr->DelayDelivery = 0;
3575 if (m->CurrentQuestion)
3576 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
3577 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3578 m->CurrentQuestion = m->Questions;
3579 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3580 {
3581 DNSQuestion *q = m->CurrentQuestion;
3582 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3583 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3584 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3585 m->CurrentQuestion = q->next;
3586 }
3587 m->CurrentQuestion = mDNSNULL;
3588 }
3589
3590 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSu32 slot)
3591 {
3592 const mDNSs32 threshhold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
3593 const mDNSs32 start = m->timenow - 0x10000000;
3594 mDNSs32 delay = start;
3595 CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
3596 const CacheRecord *rr;
3597 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3598 if (threshhold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
3599 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
3600 delay = RRExpireTime(rr);
3601 if (delay - start > 0) return(NonZeroTime(delay));
3602 else return(0);
3603 }
3604
3605 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
3606 // If new questions are created as a result of invoking client callbacks, they will be added to
3607 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3608 // rr is a new CacheRecord just received into our cache
3609 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3610 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3611 // which may change the record list and/or question list.
3612 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3613 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
3614 {
3615 DNSQuestion *q;
3616
3617 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
3618 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
3619 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3620 {
3621 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3622 {
3623 // If this question is one that's actively sending queries, and it's received ten answers within one
3624 // second of sending the last query packet, then that indicates some radical network topology change,
3625 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
3626 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3627 // because we will anyway send another query within a few seconds. The first reset query is sent out
3628 // randomized over the next four seconds to reduce possible synchronization between machines.
3629 if (q->LastAnswerPktNum != m->PktNum)
3630 {
3631 q->LastAnswerPktNum = m->PktNum;
3632 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
3633 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
3634 {
3635 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3636 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
3637 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
3638 q->ThisQInterval = InitialQuestionInterval;
3639 SetNextQueryTime(m,q);
3640 }
3641 }
3642 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
3643 DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
3644 &rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
3645 rr->resrec.rDNSServer->port : zeroIPPort), q);
3646 q->CurrentAnswers++;
3647 q->unansweredQueries = 0;
3648 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3649 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3650 if (q->CurrentAnswers > 4000)
3651 {
3652 static int msgcount = 0;
3653 if (msgcount++ < 10)
3654 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3655 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
3656 rr->resrec.rroriginalttl = 0;
3657 rr->UnansweredQueries = MaxUnansweredQueries;
3658 }
3659 }
3660 }
3661
3662 if (!rr->DelayDelivery)
3663 {
3664 if (m->CurrentQuestion)
3665 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3666 m->CurrentQuestion = m->Questions;
3667 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3668 {
3669 q = m->CurrentQuestion;
3670 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3671 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3672 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3673 m->CurrentQuestion = q->next;
3674 }
3675 m->CurrentQuestion = mDNSNULL;
3676 }
3677
3678 SetNextCacheCheckTimeForRecord(m, rr);
3679 }
3680
3681 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3682 // If new questions are created as a result of invoking client callbacks, they will be added to
3683 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3684 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3685 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3686 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3687 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3688 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3689 // which may change the record list and/or question list.
3690 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3691 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
3692 {
3693 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
3694 if (m->CurrentQuestion)
3695 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3696 m->CurrentQuestion = m->Questions;
3697 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
3698 // since we're not caching the record and we'll get no opportunity to do this later
3699 while (m->CurrentQuestion)
3700 {
3701 DNSQuestion *q = m->CurrentQuestion;
3702 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3703 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
3704 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3705 m->CurrentQuestion = q->next;
3706 }
3707 m->CurrentQuestion = mDNSNULL;
3708 }
3709
3710 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3711 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3712 // If new questions are created as a result of invoking client callbacks, they will be added to
3713 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3714 // rr is an existing cache CacheRecord that just expired and is being deleted
3715 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3716 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3717 // which may change the record list and/or question list.
3718 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3719 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
3720 {
3721 if (m->CurrentQuestion)
3722 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3723 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3724 m->CurrentQuestion = m->Questions;
3725
3726 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3727 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3728 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3729 {
3730 DNSQuestion *q = m->CurrentQuestion;
3731 // When a question enters suppressed state, we generate RMV events and generate a negative
3732 // response. A cache may be present that answers this question e.g., cache entry generated
3733 // before the question became suppressed. We need to skip the suppressed questions here as
3734 // the RMV event has already been generated.
3735 if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
3736 {
3737 verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
3738 q->FlappingInterface1 = mDNSNULL;
3739 q->FlappingInterface2 = mDNSNULL;
3740
3741 if (q->CurrentAnswers == 0)
3742 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3743 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3744 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3745 else
3746 {
3747 q->CurrentAnswers--;
3748 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
3749 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
3750 }
3751 if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
3752 {
3753 if (q->CurrentAnswers == 0)
3754 {
3755 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3756 q->qname.c, DNSTypeName(q->qtype));
3757 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3758 }
3759 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
3760 }
3761 }
3762 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3763 m->CurrentQuestion = q->next;
3764 }
3765 m->CurrentQuestion = mDNSNULL;
3766 }
3767
3768 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
3769 {
3770 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3771 unsigned int i;
3772 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
3773 #endif
3774 e->next = m->rrcache_free;
3775 m->rrcache_free = e;
3776 m->rrcache_totalused--;
3777 }
3778
3779 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
3780 {
3781 CacheEntity *e = (CacheEntity *)(*cp);
3782 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3783 if ((*cp)->rrcache_tail != &(*cp)->members)
3784 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3785 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
3786 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3787 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
3788 (*cp)->name = mDNSNULL;
3789 *cp = (*cp)->next; // Cut record from list
3790 ReleaseCacheEntity(m, e);
3791 }
3792
3793 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
3794 {
3795 CacheGroup *cg;
3796 CacheRecord **rp;
3797 const mDNSu32 slot = HashSlot(r->resrec.name);
3798
3799 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3800 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
3801 r->resrec.rdata = mDNSNULL;
3802
3803 cg = CacheGroupForRecord(m, slot, &r->resrec);
3804 if (!cg) LogMsg("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
3805
3806 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
3807 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
3808 // (which is handled below) and in that case it should be freed here.
3809 if (r->resrec.name && cg && r->resrec.name != cg->name)
3810 {
3811 LogInfo("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
3812 mDNSPlatformMemFree((void *)r->resrec.name);
3813 }
3814 r->resrec.name = mDNSNULL;
3815
3816 rp = &(r->nsec);
3817 while (*rp)
3818 {
3819 CacheRecord *rr = *rp;
3820 *rp = (*rp)->next; // Cut record from list
3821 if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
3822 {
3823 mDNSPlatformMemFree(rr->resrec.rdata);
3824 rr->resrec.rdata = mDNSNULL;
3825 }
3826 // NSEC records that are added to the "nsec" list does not share the name
3827 // of the CacheGroup.
3828 if (rr->resrec.name)
3829 {
3830 LogInfo("ReleaseCacheRecord: freeing cached nsec %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
3831 mDNSPlatformMemFree((void *)rr->resrec.name);
3832 rr->resrec.name = mDNSNULL;
3833 }
3834 ReleaseCacheEntity(m, (CacheEntity *)rr);
3835 }
3836 ReleaseCacheEntity(m, (CacheEntity *)r);
3837 }
3838
3839 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3840 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3841 // callbacks for old records are delivered before callbacks for newer records.
3842 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
3843 {
3844 CacheRecord **rp = &cg->members;
3845
3846 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3847 m->lock_rrcache = 1;
3848
3849 while (*rp)
3850 {
3851 CacheRecord *const rr = *rp;
3852 mDNSs32 event = RRExpireTime(rr);
3853 if (m->timenow - event >= 0) // If expired, delete it
3854 {
3855 *rp = rr->next; // Cut it from the list
3856 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3857 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
3858 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
3859 {
3860 DNSQuestion *q = rr->CRActiveQuestion;
3861 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3862 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3863 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3864 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3865 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3866 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3867 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
3868 if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
3869 {
3870 q->ThisQInterval = InitialQuestionInterval;
3871 q->LastQTime = m->timenow - q->ThisQInterval;
3872 SetNextQueryTime(m, q);
3873 }
3874 CacheRecordRmv(m, rr);
3875 m->rrcache_active--;
3876 }
3877 ReleaseCacheRecord(m, rr);
3878 }
3879 else // else, not expired; see if we need to query
3880 {
3881 // If waiting to delay delivery, do nothing until then
3882 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
3883 event = rr->DelayDelivery;
3884 else
3885 {
3886 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
3887 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3888 {
3889 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
3890 event = NextCacheCheckEvent(rr); // then just record when we want the next query
3891 else // else trigger our question to go out now
3892 {
3893 // Set NextScheduledQuery to timenow so that SendQueries() will run.
3894 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
3895 m->NextScheduledQuery = m->timenow;
3896 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3897 // which will correctly update m->NextCacheCheck for us.
3898 event = m->timenow + 0x3FFFFFFF;
3899 }
3900 }
3901 }
3902 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3903 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
3904 if (m->rrcache_nextcheck[slot] - event > 0)
3905 m->rrcache_nextcheck[slot] = event;
3906 rp = &rr->next;
3907 }
3908 }
3909 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
3910 cg->rrcache_tail = rp;
3911 m->lock_rrcache = 0;
3912 }
3913
3914 mDNSlocal void AnswerNewQuestion(mDNS *const m)
3915 {
3916 mDNSBool ShouldQueryImmediately = mDNStrue;
3917 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
3918 mDNSu32 slot = HashSlot(&q->qname);
3919 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3920 AuthRecord *lr;
3921 AuthGroup *ag;
3922 mDNSBool AnsweredFromCache = mDNSfalse;
3923
3924 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3925
3926 if (cg) CheckCacheExpiration(m, slot, cg);
3927 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
3928 m->NewQuestions = q->next;
3929 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3930 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3931 //
3932 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3933 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
3934 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3935 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3936 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3937 // advanced it), that means the question was deleted, so we no longer need to worry about answering
3938 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3939 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
3940 //
3941 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
3942 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3943 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3944 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3945
3946 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3947 // This should be safe, because calling the client's question callback may cause the
3948 // question list to be modified, but should not ever cause the rrcache list to be modified.
3949 // If the client's question callback deletes the question, then m->CurrentQuestion will
3950 // be advanced, and we'll exit out of the loop
3951 m->lock_rrcache = 1;
3952 if (m->CurrentQuestion)
3953 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3954 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3955 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
3956
3957 if (q->NoAnswer == NoAnswer_Fail)
3958 {
3959 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3960 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
3961 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
3962 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
3963 // Don't touch the question if it has been stopped already
3964 if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
3965 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
3966 }
3967 if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit; }
3968
3969 // See if we want to tell it about LocalOnly records
3970 if (m->CurrentRecord)
3971 LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3972 slot = AuthHashSlot(&q->qname);
3973 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
3974 if (ag)
3975 {
3976 m->CurrentRecord = ag->members;
3977 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
3978 {
3979 AuthRecord *rr = m->CurrentRecord;
3980 m->CurrentRecord = rr->next;
3981 //
3982 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
3983 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
3984 //
3985 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
3986 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
3987 // we handle both mDNSInterface_Any and scoped questions.
3988
3989 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && q->InterfaceID == mDNSInterface_Any))
3990 if (LocalOnlyRecordAnswersQuestion(rr, q))
3991 {
3992 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
3993 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3994 }
3995 }
3996 }
3997 m->CurrentRecord = mDNSNULL;
3998
3999 if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit; }
4000
4001 if (q->LOAddressAnswers)
4002 {
4003 LogInfo("AnswerNewQuestion: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4004 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4005 goto exit;
4006 }
4007
4008 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4009 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4010 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4011 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4012 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4013 if (ag)
4014 {
4015 lr = ag->NewLocalOnlyRecords;
4016 while (lr)
4017 {
4018 if (LORecordAnswersAddressType(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4019 {
4020 LogInfo("AnswerNewQuestion: Question %p %##s (%s) will be answered using new local auth records "
4021 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4022 goto exit;
4023 }
4024 lr = lr->next;
4025 }
4026 }
4027
4028
4029 // If we are not supposed to answer this question, generate a negative response.
4030 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
4031 //
4032 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
4033 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
4034 // the question out.
4035 if (QuerySuppressed(q)) { q->SuppressQuery = mDNSfalse; GenerateNegativeResponse(m); q->SuppressQuery = mDNStrue; }
4036 else if (!q->ValidatingResponse)
4037 {
4038 CacheRecord *rr;
4039 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4040 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
4041 {
4042 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4043 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
4044 if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
4045 {
4046 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
4047 rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
4048 continue; // Go to next one in loop
4049 }
4050
4051 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4052 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4053 if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
4054 ShouldQueryImmediately = mDNSfalse;
4055 q->CurrentAnswers++;
4056 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4057 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4058 AnsweredFromCache = mDNStrue;
4059 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4060 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4061 }
4062 else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
4063 ShouldQueryImmediately = mDNSfalse;
4064 }
4065 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
4066 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
4067 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
4068
4069 // Neither a local record nor a cache entry could answer this question. If this question need to be retried
4070 // with search domains, generate a negative response which will now retry after appending search domains.
4071 // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
4072 // we will retry with search domains.
4073 if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
4074 {
4075 LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4076 GenerateNegativeResponse(m);
4077 }
4078
4079 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
4080
4081 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
4082 // Hence we don't execute the following block of code for those cases.
4083 if (ShouldQueryImmediately && ActiveQuestion(q))
4084 {
4085 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4086 q->ThisQInterval = InitialQuestionInterval;
4087 q->LastQTime = m->timenow - q->ThisQInterval;
4088 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
4089 {
4090 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
4091 if (!m->RandomQueryDelay)
4092 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
4093 q->LastQTime += m->RandomQueryDelay;
4094 }
4095 }
4096
4097 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
4098 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
4099 // answers for this question until *after* its scheduled transmission time, in which case
4100 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
4101 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
4102 SetNextQueryTime(m,q);
4103
4104 exit:
4105 m->CurrentQuestion = mDNSNULL;
4106 m->lock_rrcache = 0;
4107 }
4108
4109 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
4110 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
4111 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
4112 {
4113 mDNSu32 slot;
4114 AuthGroup *ag;
4115 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
4116 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
4117
4118 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4119
4120 if (m->CurrentQuestion)
4121 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4122 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4123 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4124
4125 if (m->CurrentRecord)
4126 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4127
4128 // 1. First walk the LocalOnly records answering the LocalOnly question
4129 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
4130 // walk the ResourceRecords list delivering the answers
4131 slot = AuthHashSlot(&q->qname);
4132 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4133 if (ag)
4134 {
4135 m->CurrentRecord = ag->members;
4136 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4137 {
4138 AuthRecord *rr = m->CurrentRecord;
4139 m->CurrentRecord = rr->next;
4140 if (LocalOnlyRecordAnswersQuestion(rr, q))
4141 {
4142 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4143 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4144 }
4145 }
4146 }
4147
4148 if (m->CurrentQuestion == q)
4149 {
4150 m->CurrentRecord = m->ResourceRecords;
4151
4152 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
4153 {
4154 AuthRecord *rr = m->CurrentRecord;
4155 m->CurrentRecord = rr->next;
4156 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4157 {
4158 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4159 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4160 }
4161 }
4162 }
4163
4164 m->CurrentQuestion = mDNSNULL;
4165 m->CurrentRecord = mDNSNULL;
4166 }
4167
4168 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
4169 {
4170 CacheEntity *e = mDNSNULL;
4171
4172 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
4173 m->lock_rrcache = 1;
4174
4175 // If we have no free records, ask the client layer to give us some more memory
4176 if (!m->rrcache_free && m->MainCallback)
4177 {
4178 if (m->rrcache_totalused != m->rrcache_size)
4179 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4180 m->rrcache_totalused, m->rrcache_size);
4181
4182 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4183 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4184 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
4185 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
4186 // and recycle them, instead of allocating more memory.
4187 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
4188 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4189 m->rrcache_size, m->rrcache_active);
4190 else
4191 {
4192 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
4193 m->MainCallback(m, mStatus_GrowCache);
4194 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4195 }
4196 }
4197
4198 // If we still have no free records, recycle all the records we can.
4199 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4200 if (!m->rrcache_free)
4201 {
4202 mDNSu32 oldtotalused = m->rrcache_totalused;
4203 mDNSu32 slot;
4204 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4205 {
4206 CacheGroup **cp = &m->rrcache_hash[slot];
4207 while (*cp)
4208 {
4209 CacheRecord **rp = &(*cp)->members;
4210 while (*rp)
4211 {
4212 // Records that answer still-active questions are not candidates for recycling
4213 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
4214 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
4215 rp=&(*rp)->next;
4216 else
4217 {
4218 CacheRecord *rr = *rp;
4219 *rp = (*rp)->next; // Cut record from list
4220 ReleaseCacheRecord(m, rr);
4221 }
4222 }
4223 if ((*cp)->rrcache_tail != rp)
4224 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
4225 (*cp)->rrcache_tail = rp;
4226 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
4227 else ReleaseCacheGroup(m, cp);
4228 }
4229 }
4230 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
4231 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
4232 }
4233
4234 if (m->rrcache_free) // If there are records in the free list, take one
4235 {
4236 e = m->rrcache_free;
4237 m->rrcache_free = e->next;
4238 if (++m->rrcache_totalused >= m->rrcache_report)
4239 {
4240 LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
4241 if (m->rrcache_report < 100) m->rrcache_report += 10;
4242 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
4243 else m->rrcache_report += 1000;
4244 }
4245 mDNSPlatformMemZero(e, sizeof(*e));
4246 }
4247
4248 m->lock_rrcache = 0;
4249
4250 return(e);
4251 }
4252
4253 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
4254 {
4255 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
4256 if (r)
4257 {
4258 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
4259 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
4260 {
4261 r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
4262 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
4263 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
4264 }
4265 }
4266 return(r);
4267 }
4268
4269 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
4270 {
4271 mDNSu16 namelen = DomainNameLength(rr->name);
4272 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
4273 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
4274 cg->next = m->rrcache_hash[slot];
4275 cg->namehash = rr->namehash;
4276 cg->members = mDNSNULL;
4277 cg->rrcache_tail = &cg->members;
4278 if (namelen > sizeof(cg->namestorage))
4279 cg->name = mDNSPlatformMemAllocate(namelen);
4280 else
4281 cg->name = (domainname*)cg->namestorage;
4282 if (!cg->name)
4283 {
4284 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
4285 ReleaseCacheEntity(m, (CacheEntity*)cg);
4286 return(mDNSNULL);
4287 }
4288 AssignDomainName(cg->name, rr->name);
4289
4290 if (CacheGroupForRecord(m, slot, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
4291 m->rrcache_hash[slot] = cg;
4292 if (CacheGroupForRecord(m, slot, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
4293
4294 return(cg);
4295 }
4296
4297 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
4298 {
4299 if (m->mDNS_busy != m->mDNS_reentrancy+1)
4300 LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
4301 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4302 // a positive answer using an expired record (e.g. from an interface that has gone away).
4303 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4304 // summary deletion without giving the proper callback to any questions that are monitoring it.
4305 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4306 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
4307 rr->UnansweredQueries = MaxUnansweredQueries;
4308 rr->resrec.rroriginalttl = 0;
4309 SetNextCacheCheckTimeForRecord(m, rr);
4310 }
4311
4312 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
4313 {
4314 mDNSs32 time;
4315 mDNSPlatformLock(m);
4316 if (m->mDNS_busy)
4317 {
4318 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
4319 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
4320 }
4321
4322 if (m->timenow) time = m->timenow;
4323 else time = mDNS_TimeNow_NoLock(m);
4324 mDNSPlatformUnlock(m);
4325 return(time);
4326 }
4327
4328 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
4329 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
4330 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
4331 #define SetSPSProxyListChanged(X) do { \
4332 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
4333 m->SPSProxyListChanged = (X); } while(0)
4334
4335 // Called from mDNS_Execute() to expire stale proxy records
4336 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
4337 {
4338 m->CurrentRecord = list;
4339 while (m->CurrentRecord)
4340 {
4341 AuthRecord *rr = m->CurrentRecord;
4342 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
4343 {
4344 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
4345 // so we need to cease proxying for *all* records we may have, expired or not.
4346 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
4347 {
4348 if (m->NextScheduledSPS - rr->TimeExpire > 0)
4349 m->NextScheduledSPS = rr->TimeExpire;
4350 }
4351 else // else proxy record expired, so remove it
4352 {
4353 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
4354 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
4355 SetSPSProxyListChanged(rr->resrec.InterfaceID);
4356 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4357 // Don't touch rr after this -- memory may have been free'd
4358 }
4359 }
4360 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4361 // new records could have been added to the end of the list as a result of that call.
4362 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
4363 m->CurrentRecord = rr->next;
4364 }
4365 }
4366
4367 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
4368 {
4369 while (m->CurrentRecord)
4370 {
4371 AuthRecord *rr = m->CurrentRecord;
4372 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
4373 {
4374 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
4375 rr->resrec.RecordType = kDNSRecordTypeShared;
4376 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
4377 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
4378 {
4379 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
4380 rr->AnsweredLocalQ = mDNSfalse;
4381 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
4382 // For LocalOnly records, we don't do that and hence we need to do that here.
4383 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
4384 }
4385 }
4386 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
4387 m->CurrentRecord = rr->next;
4388 }
4389 }
4390
4391 mDNSlocal void TimeoutQuestions(mDNS *const m)
4392 {
4393 m->NextScheduledStopTime = m->timenow + 0x3FFFFFFF;
4394 if (m->CurrentQuestion)
4395 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
4396 DNSTypeName(m->CurrentQuestion->qtype));
4397 m->CurrentQuestion = m->Questions;
4398 while (m->CurrentQuestion)
4399 {
4400 DNSQuestion *const q = m->CurrentQuestion;
4401 if (q->StopTime)
4402 {
4403 if (m->timenow - q->StopTime >= 0)
4404 {
4405 LogInfo("TimeoutQuestions: question %##s timed out, time %d", q->qname.c, m->timenow - q->StopTime);
4406 GenerateNegativeResponse(m);
4407 if (m->CurrentQuestion == q) q->StopTime = 0;
4408 }
4409 else
4410 {
4411 if (m->NextScheduledStopTime - q->StopTime > 0)
4412 m->NextScheduledStopTime = q->StopTime;
4413 }
4414 }
4415 // If m->CurrentQuestion wasn't modified out from under us, advance it now
4416 // We can't do this at the start of the loop because GenerateNegativeResponse
4417 // depends on having m->CurrentQuestion point to the right question
4418 if (m->CurrentQuestion == q)
4419 m->CurrentQuestion = q->next;
4420 }
4421 m->CurrentQuestion = mDNSNULL;
4422 }
4423
4424 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
4425 {
4426 AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
4427 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
4428 rrPtr = m->SPSRRSet;
4429 while (rrPtr)
4430 {
4431 rrNext = rrPtr->next;
4432 mDNSPlatformMemFree(rrPtr);
4433 rrPtr = rrNext;
4434 }
4435 m->SPSRRSet = mDNSNULL;
4436 }
4437
4438 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
4439 {
4440 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
4441
4442 if (m->timenow - m->NextScheduledEvent >= 0)
4443 {
4444 int i;
4445 AuthRecord *head, *tail;
4446 mDNSu32 slot;
4447 AuthGroup *ag;
4448
4449 verbosedebugf("mDNS_Execute");
4450
4451 if (m->CurrentQuestion)
4452 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
4453 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4454
4455 if (m->CurrentRecord)
4456 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
4457
4458 // 1. If we're past the probe suppression time, we can clear it
4459 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
4460
4461 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4462 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
4463
4464 // 3. Purge our cache of stale old records
4465 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
4466 {
4467 mDNSu32 numchecked = 0;
4468 m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
4469 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4470 {
4471 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
4472 {
4473 CacheGroup **cp = &m->rrcache_hash[slot];
4474 m->rrcache_nextcheck[slot] = m->timenow + 0x3FFFFFFF;
4475 while (*cp)
4476 {
4477 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
4478 numchecked++;
4479 CheckCacheExpiration(m, slot, *cp);
4480 if ((*cp)->members) cp=&(*cp)->next;
4481 else ReleaseCacheGroup(m, cp);
4482 }
4483 }
4484 // Even if we didn't need to actually check this slot yet, still need to
4485 // factor its nextcheck time into our overall NextCacheCheck value
4486 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
4487 m->NextCacheCheck = m->rrcache_nextcheck[slot];
4488 }
4489 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
4490 }
4491
4492 if (m->timenow - m->NextScheduledSPS >= 0)
4493 {
4494 m->NextScheduledSPS = m->timenow + 0x3FFFFFFF;
4495 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
4496 CheckProxyRecords(m, m->ResourceRecords);
4497 }
4498
4499 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
4500
4501 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
4502 // as records could have expired during that check
4503 if (m->timenow - m->NextScheduledKA >= 0)
4504 {
4505 m->NextScheduledKA = m->timenow + 0x3FFFFFFF;
4506 mDNS_SendKeepalives(m);
4507 }
4508
4509 // After two seconds after the owner option is set, call the ioctl to clear the
4510 // ignore neighbor advertisement flag.
4511 #if APPLE_OSX_mDNSResponder
4512 if (m->clearIgnoreNA && m->timenow - m->clearIgnoreNA >= 0)
4513 {
4514 mDNSPlatformToggleInterfaceAdvt(m, mDNSfalse);
4515 m->clearIgnoreNA = 0;
4516 }
4517 #endif
4518 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
4519 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
4520 {
4521 m->AnnounceOwner = 0;
4522 }
4523 if (m->ClearSPSRecords && m->timenow - m->ClearSPSRecords >= 0)
4524 {
4525 // Free the stored records that we had registered with the sleep proxy
4526 mDNSCoreFreeProxyRR(m);
4527 m->ClearSPSRecords = 0;
4528 }
4529
4530 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
4531 {
4532 m->DelaySleep = 0;
4533 if (m->SleepState == SleepState_Transferring)
4534 {
4535 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
4536 BeginSleepProcessing(m);
4537 }
4538 }
4539
4540 // 4. See if we can answer any of our new local questions from the cache
4541 for (i=0; m->NewQuestions && i<1000; i++)
4542 {
4543 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
4544 AnswerNewQuestion(m);
4545 }
4546 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4547
4548 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
4549 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
4550 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
4551 {
4552 m->LocalRemoveEvents = mDNSfalse;
4553 m->CurrentRecord = m->ResourceRecords;
4554 CheckRmvEventsForLocalRecords(m);
4555 // Walk the LocalOnly records and deliver the RMV events
4556 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4557 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4558 {
4559 m->CurrentRecord = ag->members;
4560 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
4561 }
4562 }
4563
4564 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
4565
4566 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
4567 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4568
4569 head = tail = mDNSNULL;
4570 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
4571 {
4572 AuthRecord *rr = m->NewLocalRecords;
4573 m->NewLocalRecords = m->NewLocalRecords->next;
4574 if (LocalRecordReady(rr))
4575 {
4576 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4577 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4578 }
4579 else if (!rr->next)
4580 {
4581 // If we have just one record that is not ready, we don't have to unlink and
4582 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
4583 // terminate and set the NewLocalRecords to rr.
4584 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
4585 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
4586 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
4587
4588 head = rr;
4589 }
4590 else
4591 {
4592 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
4593 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
4594 // if this is the first record we are skipping, move to the end of the list.
4595 // if we have already skipped records before, append it at the end.
4596 while (*p && *p != rr) p=&(*p)->next;
4597 if (*p) *p = rr->next; // Cut this record from the list
4598 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
4599 if (!head)
4600 {
4601 while (*p) p=&(*p)->next;
4602 *p = rr;
4603 head = tail = rr;
4604 }
4605 else
4606 {
4607 tail->next = rr;
4608 tail = rr;
4609 }
4610 rr->next = mDNSNULL;
4611 }
4612 }
4613 m->NewLocalRecords = head;
4614 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
4615
4616 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
4617
4618 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
4619 // to our local questions
4620 if (m->NewLocalOnlyRecords)
4621 {
4622 m->NewLocalOnlyRecords = mDNSfalse;
4623 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4624 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4625 {
4626 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
4627 {
4628 AuthRecord *rr = ag->NewLocalOnlyRecords;
4629 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
4630 // LocalOnly records should always be ready as they never probe
4631 if (LocalRecordReady(rr))
4632 {
4633 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4634 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4635 }
4636 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
4637 }
4638 // We limit about 100 per AuthGroup that can be serviced at a time
4639 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
4640 }
4641 }
4642
4643 // 5. See what packets we need to send
4644 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
4645 DiscardDeregistrations(m);
4646 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
4647 {
4648 // If the platform code is ready, and we're not suppressing packet generation right now
4649 // then send our responses, probes, and questions.
4650 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
4651 // We send queries next, because there might be final-stage probes that complete their probing here, causing
4652 // them to advance to announcing state, and we want those to be included in any announcements we send out.
4653 // Finally, we send responses, including the previously mentioned records that just completed probing.
4654 m->SuppressSending = 0;
4655
4656 // 6. Send Query packets. This may cause some probing records to advance to announcing state
4657 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
4658 if (m->timenow - m->NextScheduledQuery >= 0)
4659 {
4660 DNSQuestion *q;
4661 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
4662 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
4663 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
4664 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4665 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
4666 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4667 }
4668 if (m->timenow - m->NextScheduledProbe >= 0)
4669 {
4670 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
4671 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
4672 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
4673 }
4674
4675 // 7. Send Response packets, including probing records just advanced to announcing state
4676 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
4677 if (m->timenow - m->NextScheduledResponse >= 0)
4678 {
4679 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4680 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
4681 }
4682 }
4683
4684 // Clear RandomDelay values, ready to pick a new different value next time
4685 m->RandomQueryDelay = 0;
4686 m->RandomReconfirmDelay = 0;
4687
4688 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
4689 #ifndef UNICAST_DISABLED
4690 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
4691 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
4692 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
4693 #endif
4694 }
4695
4696 // Note about multi-threaded systems:
4697 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4698 // performing mDNS API operations that change our next scheduled event time.
4699 //
4700 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
4701 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4702 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4703 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4704 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4705 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4706 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4707 // without blocking. This avoids the race condition between the signal from the other thread arriving
4708 // just *before* or just *after* the main thread enters the blocking primitive.
4709 //
4710 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4711 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4712 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4713 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4714 // by the time it gets to the timer callback function).
4715
4716 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4717 return(m->NextScheduledEvent);
4718 }
4719
4720 mDNSlocal void SuspendLLQs(mDNS *m)
4721 {
4722 DNSQuestion *q;
4723 for (q = m->Questions; q; q = q->next)
4724 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
4725 { q->ReqLease = 0; sendLLQRefresh(m, q); }
4726 }
4727
4728 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
4729 {
4730 AuthRecord *rr;
4731 mDNSu32 slot;
4732 AuthGroup *ag;
4733
4734 slot = AuthHashSlot(&q->qname);
4735 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4736 if (ag)
4737 {
4738 for (rr = ag->members; rr; rr=rr->next)
4739 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
4740 if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
4741 {
4742 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
4743 return mDNStrue;
4744 }
4745 }
4746 return mDNSfalse;
4747 }
4748
4749 // ActivateUnicastQuery() is called from three places:
4750 // 1. When a new question is created
4751 // 2. On wake from sleep
4752 // 3. When the DNS configuration changes
4753 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
4754 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
4755 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
4756 {
4757 // For now this AutoTunnel stuff is specific to Mac OS X.
4758 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
4759 #if APPLE_OSX_mDNSResponder
4760 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
4761 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
4762 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
4763 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
4764 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
4765 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
4766
4767 if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
4768 !SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
4769 {
4770 question->NoAnswer = NoAnswer_Suspended;
4771 AddNewClientTunnel(m, question);
4772 return;
4773 }
4774 #endif // APPLE_OSX_mDNSResponder
4775
4776 if (!question->DuplicateOf)
4777 {
4778 debugf("ActivateUnicastQuery: %##s %s%s%s",
4779 question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
4780 question->CNAMEReferrals = 0;
4781 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
4782 if (question->LongLived)
4783 {
4784 question->state = LLQ_InitialRequest;
4785 question->id = zeroOpaque64;
4786 question->servPort = zeroIPPort;
4787 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
4788 }
4789 // If the question has local answers, then we don't want answers from outside
4790 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
4791 {
4792 question->ThisQInterval = InitialQuestionInterval;
4793 question->LastQTime = m->timenow - question->ThisQInterval;
4794 SetNextQueryTime(m, question);
4795 }
4796 }
4797 }
4798
4799 // Caller should hold the lock
4800 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
4801 CallbackBeforeStartQuery BeforeStartCallback, void *context)
4802 {
4803 DNSQuestion *q;
4804 DNSQuestion *restart = mDNSNULL;
4805
4806 if (!m->mDNS_busy) LogMsg("mDNSCoreRestartAddressQueries: ERROR!! Lock not held");
4807
4808 // 1. Flush the cache records
4809 if (flushCacheRecords) flushCacheRecords(m);
4810
4811 // 2. Even though we may have purged the cache records above, before it can generate RMV event
4812 // we are going to stop the question. Hence we need to deliver the RMV event before we
4813 // stop the question.
4814 //
4815 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
4816 // application callback can potentially stop the current question (detected by CurrentQuestion) or
4817 // *any* other question which could be the next one that we may process here. RestartQuestion
4818 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
4819 // if the "next" question is stopped while the CurrentQuestion is stopped
4820
4821 if (m->RestartQuestion)
4822 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
4823 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
4824
4825 m->RestartQuestion = m->Questions;
4826 while (m->RestartQuestion)
4827 {
4828 q = m->RestartQuestion;
4829 m->RestartQuestion = q->next;
4830 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
4831 // question) through their "nta" pointer. Normally when the original query stops, it stops the
4832 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
4833 // question followed by the original query that refers to this GetZoneData question, we will end up
4834 // freeing the GetZoneData question and then start the "freed" question at the end.
4835
4836 if (IsGetZoneDataQuestion(q))
4837 {
4838 DNSQuestion *refq = q->next;
4839 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4840 // debug stuff, we just try to find the referencing question and don't do much with it
4841 while (refq)
4842 {
4843 if (q == &refq->nta->question)
4844 {
4845 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
4846 }
4847 refq = refq->next;
4848 }
4849 continue;
4850 }
4851
4852 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
4853 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
4854
4855 // If the search domains did not change, then we restart all the queries. Otherwise, only
4856 // for queries for which we "might" have appended search domains ("might" because we may
4857 // find results before we apply search domains even though AppendSearchDomains is set to 1)
4858 if (!SearchDomainsChanged || q->AppendSearchDomains)
4859 {
4860 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
4861 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
4862 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
4863 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
4864 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
4865 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
4866 // for the original query using these cache entries as ADDs were never delivered using these cache
4867 // entries and hence this order is needed.
4868
4869 // If the query is suppressed, the RMV events won't be delivered
4870 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
4871
4872 // SuppressQuery status does not affect questions that are answered using local records
4873 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
4874
4875 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
4876 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
4877 mDNS_StopQuery_internal(m, q);
4878 // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
4879 // and then search domains should be appended. At the beginning, qnameOrig was NULL.
4880 if (q->qnameOrig)
4881 {
4882 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
4883 AssignDomainName(&q->qname, q->qnameOrig);
4884 mDNSPlatformMemFree(q->qnameOrig);
4885 q->qnameOrig = mDNSNULL;
4886 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
4887 }
4888 q->SearchListIndex = 0;
4889 q->next = restart;
4890 restart = q;
4891 }
4892 }
4893
4894 // 3. Callback before we start the query
4895 if (BeforeStartCallback) BeforeStartCallback(m, context);
4896
4897 // 4. Restart all the stopped queries
4898 while (restart)
4899 {
4900 q = restart;
4901 restart = restart->next;
4902 q->next = mDNSNULL;
4903 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4904 mDNS_StartQuery_internal(m, q);
4905 }
4906 }
4907
4908 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
4909 {
4910 DNSQuestion *q;
4911
4912 #ifndef UNICAST_DISABLED
4913 // Retrigger all our uDNS questions
4914 if (m->CurrentQuestion)
4915 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
4916 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4917 m->CurrentQuestion = m->Questions;
4918 while (m->CurrentQuestion)
4919 {
4920 q = m->CurrentQuestion;
4921 m->CurrentQuestion = m->CurrentQuestion->next;
4922 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
4923 }
4924 #endif
4925
4926 // Retrigger all our mDNS questions
4927 for (q = m->Questions; q; q=q->next) // Scan our list of questions
4928 mDNSCoreRestartQuestion(m, q);
4929 }
4930
4931 // restart question if it's multicast and currently active
4932 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
4933 {
4934 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
4935 {
4936 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
4937 q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
4938 q->LastQTime = m->timenow - q->ThisQInterval;
4939 q->RecentAnswerPkts = 0;
4940 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
4941 m->NextScheduledQuery = m->timenow;
4942 }
4943 }
4944
4945 // restart the probe/announce cycle for multicast record
4946 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
4947 {
4948 if (!AuthRecord_uDNS(rr))
4949 {
4950 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
4951 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
4952
4953 // announceCount < 0 indicates default announce count should be used
4954 if (announceCount < 0)
4955 announceCount = InitialAnnounceCount;
4956 if (rr->AnnounceCount < announceCount)
4957 rr->AnnounceCount = announceCount;
4958 rr->AnnounceCount = InitialAnnounceCount;
4959 rr->SendNSECNow = mDNSNULL;
4960 InitializeLastAPTime(m, rr);
4961 }
4962 }
4963
4964 // ***************************************************************************
4965 #if COMPILER_LIKES_PRAGMA_MARK
4966 #pragma mark -
4967 #pragma mark - Power Management (Sleep/Wake)
4968 #endif
4969
4970 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
4971 {
4972 #ifndef IDLESLEEPCONTROL_DISABLED
4973 mDNSBool allowSleep = mDNStrue;
4974 char reason[128];
4975
4976 reason[0] = 0;
4977
4978 if (m->SystemSleepOnlyIfWakeOnLAN)
4979 {
4980 // Don't sleep if we are a proxy for any services
4981 if (m->ProxyRecords)
4982 {
4983 allowSleep = mDNSfalse;
4984 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
4985 LogInfo("Sleep disabled because we are proxying %d records", m->ProxyRecords);
4986 }
4987
4988 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
4989 {
4990 // Scan the list of active interfaces
4991 NetworkInterfaceInfo *intf;
4992 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4993 {
4994 if (intf->McastTxRx && !intf->Loopback)
4995 {
4996 // Disallow sleep if this interface doesn't support NetWake
4997 if (!intf->NetWake)
4998 {
4999 allowSleep = mDNSfalse;
5000 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
5001 LogInfo("Sleep disabled because %s does not support NetWake", intf->ifname);
5002 break;
5003 }
5004
5005 // Disallow sleep if there is no sleep proxy server
5006 if (FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL) == mDNSNULL)
5007 {
5008 allowSleep = mDNSfalse;
5009 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
5010 LogInfo("Sleep disabled because %s has no sleep proxy", intf->ifname);
5011 break;
5012 }
5013 }
5014 }
5015 }
5016 }
5017
5018 // Call the platform code to enable/disable sleep
5019 mDNSPlatformSetAllowSleep(m, allowSleep, reason);
5020 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
5021 }
5022
5023 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
5024 {
5025 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
5026 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
5027 // to send.
5028 if (AuthRecord_uDNS(rr) || mDNSOpaque16IsZero(rr->updateid) || m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
5029 return mDNSfalse;
5030
5031 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
5032 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
5033 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
5034 // updateid and we should have returned from above.
5035 //
5036 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
5037 // platform function to extract the value from "intf" everytime.
5038
5039 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
5040 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
5041 return mDNStrue;
5042
5043 return mDNSfalse;
5044 }
5045
5046 mDNSlocal mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf)
5047 {
5048 mDNSu16 newrdlength;
5049 mDNSAddr laddr, raddr;
5050 mDNSIPPort lport, rport;
5051 mDNSu32 timeout, seq, ack;
5052 mDNSu16 win;
5053 UTF8str255 txt;
5054 int rdsize;
5055 RData *newrd;
5056 mDNSTCPInfo mti;
5057 mStatus ret;
5058
5059 if (rr->NewRData)
5060 {
5061 RData *n = rr->NewRData;
5062
5063 LogMsg("UpdateKeepaliveRData: Update was queued on %s", ARDisplayString(m, rr));
5064
5065 rr->NewRData = mDNSNULL;
5066 if (rr->UpdateCallback)
5067 rr->UpdateCallback(m, rr, n, rr->newrdlength);
5068 }
5069
5070 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
5071 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
5072
5073 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &seq, &ack, &lport, &rport, &win);
5074 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) ||
5075 mDNSIPPortIsZero(rport))
5076 {
5077 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
5078 return mStatus_UnknownErr;
5079 }
5080
5081 // If this keepalive packet would be sent on a different interface than the current one that we are processing
5082 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
5083 // this DNS NULL record, it does not send any keepalives as it does not have all the information
5084
5085 ret = mDNSPlatformRetrieveTCPInfo(m, &laddr, &lport, &raddr, &rport, &mti);
5086 if (ret != mStatus_NoError)
5087 {
5088 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
5089 return ret;
5090 }
5091
5092 if (mti.IntfId != intf->InterfaceID)
5093 {
5094 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti %p, Interface %p", mti.IntfId, intf->InterfaceID);
5095 return mStatus_BadParamErr;
5096 }
5097
5098 if (laddr.type == mDNSAddrType_IPv4)
5099 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d h=%#a d=%#a l=%u r=%u s=%u a=%u w=%u", timeout, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), mti.seq, mti.ack, mti.window);
5100 else
5101 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d H=%#a D=%#a l=%u%u r=%u%u s=%u a=%u w=%u", timeout, &laddr, &raddr, lport.b[0], lport.b[1], rport.b[0], rport.b[1], rport.NotAnInteger, mti.seq, mti.ack, mti.window);
5102
5103 // Did we insert a null byte at the end ?
5104 if (newrdlength == (sizeof(txt.c) - 1))
5105 {
5106 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
5107 return mStatus_NoMemoryErr;
5108 }
5109
5110 // Include the length for the null byte at the end
5111 txt.c[0] = newrdlength + 1;
5112 // Account for the first length byte and the null byte at the end
5113 newrdlength += 2;
5114
5115 rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
5116 newrd = mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
5117 if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
5118
5119 newrd->MaxRDLength = (mDNSu16) rdsize;
5120 mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
5121
5122 rr->NewRData = newrd;
5123 rr->newrdlength = newrdlength;
5124 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrd))
5125 {
5126 LogMsg("UpdateKeepaliveRData: ValidateRData failed %s", ARDisplayString(m, rr));
5127 return mStatus_BadParamErr;
5128 }
5129
5130 // We don't send goodbyes for non-shared records and hence updating here should be fine
5131 CompleteRDataUpdate(m, rr);
5132
5133 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
5134 return mStatus_NoError;
5135 }
5136
5137 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
5138 {
5139 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
5140 const int sps = intf->NextSPSAttempt / 3;
5141 AuthRecord *rr;
5142 mDNSOpaque16 msgid;
5143 mDNSu32 scopeid;
5144
5145 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
5146 if (!intf->SPSAddr[sps].type)
5147 {
5148 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
5149 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
5150 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
5151 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
5152 goto exit;
5153 }
5154
5155 // Mark our mDNS records (not unicast records) for transfer to SPS
5156 if (mDNSOpaque16IsZero(id))
5157 {
5158 // We may have to register this record over multiple interfaces and we don't want to
5159 // overwrite the id. We send the registration over interface X with id "IDX" and before
5160 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
5161 // for "IDX". Hence, we want to use the same ID across all interfaces.
5162 //
5163 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
5164 // option check below will set the same ID across the records from the same owner. Records
5165 // with different owner option gets different ID.
5166 msgid = mDNS_NewMessageID(m);
5167 for (rr = m->ResourceRecords; rr; rr=rr->next)
5168 if (rr->resrec.RecordType > kDNSRecordTypeDeregistering)
5169 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
5170 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
5171 {
5172 rr->SendRNow = mDNSInterfaceMark; // mark it now
5173 // When we are registering on the first interface, rr->updateid is zero in which case
5174 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
5175 // At the end, all the updates sent across all the interfaces with the same ID.
5176 if (mDNSOpaque16IsZero(rr->updateid))
5177 rr->updateid = msgid;
5178 else
5179 msgid = rr->updateid;
5180 }
5181 }
5182 else
5183 msgid = id;
5184
5185 while (1)
5186 {
5187 mDNSu8 *p = m->omsg.data;
5188 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
5189 // For now we follow that same logic for SPS registrations too.
5190 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
5191 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
5192 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
5193
5194 for (rr = m->ResourceRecords; rr; rr=rr->next)
5195 if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
5196 {
5197 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
5198 {
5199 mDNSu8 *newptr;
5200 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
5201
5202 // If we can't update the keepalive record, don't send it
5203 if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf) != mStatus_NoError))
5204 {
5205 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
5206 {
5207 bit_clr_opaque64(rr->updateIntID, scopeid);
5208 }
5209 continue;
5210 }
5211
5212 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
5213 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
5214 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
5215 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
5216 if (!newptr)
5217 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
5218 else
5219 {
5220 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));
5221 rr->SendRNow = mDNSNULL;
5222 rr->ThisAPInterval = mDNSPlatformOneSecond;
5223 rr->LastAPTime = m->timenow;
5224 // should be initialized above
5225 if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
5226 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
5227 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
5228 p = newptr;
5229 }
5230 }
5231 }
5232
5233 if (!m->omsg.h.mDNS_numUpdates) break;
5234 else
5235 {
5236 AuthRecord opt;
5237 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
5238 opt.resrec.rrclass = NormalMaxDNSMessageData;
5239 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
5240 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
5241 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
5242 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
5243 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
5244 if (!owner->HMAC.l[0]) // If no owner data,
5245 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information
5246 else // otherwise, use the owner data we were given
5247 {
5248 opt.resrec.rdata->u.opt[1].u.owner = *owner;
5249 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner;
5250 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
5251 }
5252 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
5253 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
5254 if (!p)
5255 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
5256 else
5257 {
5258 mStatus err;
5259
5260 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
5261 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
5262 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
5263 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL, mDNSfalse);
5264 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
5265 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
5266 {
5267 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
5268 intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
5269 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
5270 return;
5271 }
5272 }
5273 }
5274 }
5275
5276 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
5277
5278 exit:
5279 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
5280 }
5281
5282 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
5283 {
5284 AuthRecord *ar;
5285 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
5286 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
5287 return mDNStrue;
5288 }
5289
5290 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
5291 {
5292 AuthRecord *newRR = mDNSPlatformMemAllocate(sizeof(AuthRecord));
5293 if (newRR == mDNSNULL)
5294 {
5295 LogSPS("%s : could not allocate memory for new resource record", __func__);
5296 return;
5297 }
5298
5299 mDNSPlatformMemZero(newRR, sizeof(AuthRecord));
5300 mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
5301 rr->resrec.rroriginalttl, rr->resrec.RecordType,
5302 rr->ARType, mDNSNULL, mDNSNULL);
5303
5304 AssignDomainName(&newRR->namestorage, &rr->namestorage);
5305 newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
5306 newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
5307 newRR->resrec.rrclass = rr->resrec.rrclass;
5308
5309 if (rr->resrec.rrtype == kDNSType_A)
5310 {
5311 newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4;
5312 }
5313 else if (rr->resrec.rrtype == kDNSType_AAAA)
5314 {
5315 newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
5316 }
5317 SetNewRData(&newRR->resrec, mDNSNULL, 0);
5318
5319 // Insert the new node at the head of the list.
5320 newRR->next = m->SPSRRSet;
5321 m->SPSRRSet = newRR;
5322 m->ClearSPSRecords = 0;
5323 LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
5324 }
5325
5326 // Some records are interface specific and some are not. The ones that are supposed to be registered
5327 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
5328 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
5329 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
5330 // registration on all the interfaces
5331 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID)
5332 {
5333 AuthRecord *ar;
5334 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
5335
5336 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
5337 // make sure that the old sleep proxy records are removed.
5338 mDNSCoreFreeProxyRR(m);
5339
5340 // For records that are registered only on a specific interface, mark only that bit as it will
5341 // never be registered on any other interface. For others, it should be sent on all interfaces.
5342 for (ar = m->ResourceRecords; ar; ar=ar->next)
5343 {
5344 if (AuthRecord_uDNS(ar))
5345 {
5346 continue;
5347 }
5348 ar->updateid = zeroID;
5349 if (!ar->resrec.InterfaceID)
5350 {
5351 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
5352 ar->updateIntID = updateIntID;
5353 }
5354 else
5355 {
5356 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
5357 // exactly this.
5358 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
5359 if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
5360 {
5361 ar->updateIntID = zeroOpaque64;
5362 bit_set_opaque64(ar->updateIntID, scopeid);
5363 LogSPS("Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1], ar->updateIntID.l[0], ARDisplayString(m, ar));
5364 }
5365 else
5366 {
5367 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
5368 }
5369 }
5370 // Store the A and AAAA records that we registered with the sleep proxy.
5371 // We will use this to prevent spurious name conflicts that may occur when we wake up
5372 if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
5373 {
5374 mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
5375 }
5376 }
5377 }
5378
5379 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
5380 {
5381 AuthRecord *ar;
5382 OwnerOptData owner = zeroOwner;
5383
5384 SendSPSRegistrationForOwner(m, intf, id, &owner);
5385
5386 for (ar = m->ResourceRecords; ar; ar=ar->next)
5387 {
5388 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
5389 {
5390 owner = ar->WakeUp;
5391 SendSPSRegistrationForOwner(m, intf, id, &owner);
5392 }
5393 }
5394 }
5395
5396 // RetrySPSRegistrations is called from SendResponses, with the lock held
5397 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
5398 {
5399 AuthRecord *rr;
5400 NetworkInterfaceInfo *intf;
5401
5402 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
5403 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5404 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
5405 intf->NextSPSAttemptTime++;
5406
5407 // Retry any record registrations that are due
5408 for (rr = m->ResourceRecords; rr; rr=rr->next)
5409 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
5410 {
5411 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5412 {
5413 // If we still have registrations pending on this interface, send it now
5414 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
5415 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
5416 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
5417 {
5418 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
5419 SendSPSRegistration(m, intf, rr->updateid);
5420 }
5421 }
5422 }
5423
5424 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
5425 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5426 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
5427 intf->NextSPSAttempt++;
5428 }
5429
5430 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
5431 {
5432 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
5433 int sps = (int)(question - intf->NetWakeResolve);
5434 (void)m; // Unused
5435 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
5436
5437 if (!AddRecord) return; // Don't care about REMOVE events
5438 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
5439
5440 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
5441
5442 if (answer->rrtype == kDNSType_SRV)
5443 {
5444 // 1. Got the SRV record; now look up the target host's IP address
5445 mDNS_StopQuery(m, question);
5446 intf->SPSPort[sps] = answer->rdata->u.srv.port;
5447 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
5448 question->qtype = kDNSType_A;
5449 mDNS_StartQuery(m, question);
5450 }
5451 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
5452 {
5453 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
5454 mDNS_StopQuery(m, question);
5455 question->ThisQInterval = -1;
5456 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
5457 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
5458 mDNS_Lock(m);
5459 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
5460 mDNS_Unlock(m);
5461 }
5462 else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
5463 {
5464 // 3. Got negative response -- target host apparently has IPv4 disabled -- so try looking up the target host's IPv6 address(es) instead
5465 mDNS_StopQuery(m, question);
5466 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
5467 question->qtype = kDNSType_AAAA;
5468 mDNS_StartQuery(m, question);
5469 }
5470 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
5471 {
5472 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
5473 mDNS_StopQuery(m, question);
5474 question->ThisQInterval = -1;
5475 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
5476 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
5477 mDNS_Lock(m);
5478 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
5479 mDNS_Unlock(m);
5480 }
5481 }
5482
5483 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
5484 {
5485 AuthRecord *rr;
5486 for (rr = m->ResourceRecords; rr; rr=rr->next)
5487 if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
5488 return mDNStrue;
5489 return mDNSfalse;
5490 }
5491
5492 mDNSlocal void SendSleepGoodbyes(mDNS *const m)
5493 {
5494 AuthRecord *rr;
5495 m->SleepState = SleepState_Sleeping;
5496
5497 #ifndef UNICAST_DISABLED
5498 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
5499 #endif /* UNICAST_DISABLED */
5500
5501 // Mark all the records we need to deregister and send them
5502 for (rr = m->ResourceRecords; rr; rr=rr->next)
5503 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
5504 rr->ImmedAnswer = mDNSInterfaceMark;
5505 SendResponses(m);
5506 }
5507
5508 /*
5509 * This function attempts to detect if multiple interfaces are on the same subnet.
5510 * It makes this determination based only on the IPv4 Addresses and subnet masks.
5511 * IPv6 link local addresses that are configured by default on all interfaces make
5512 * it hard to make this determination
5513 *
5514 * The 'real' fix for this would be to send out multicast packets over one interface
5515 * and conclude that multiple interfaces are on the same subnet only if these packets
5516 * are seen on other interfaces on the same system
5517 */
5518 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
5519 {
5520 NetworkInterfaceInfo *intf;
5521 NetworkInterfaceInfo *newIntf;
5522 mDNSu32 i;
5523
5524 for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
5525 {
5526 if ((newIntf->InterfaceID != intfid) ||
5527 (newIntf->ip.type != mDNSAddrType_IPv4))
5528 {
5529 continue;
5530 }
5531 for ( i = 0; i < count; i++)
5532 {
5533 for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
5534 {
5535 if ((intf->InterfaceID != regID[i]) ||
5536 (intf->ip.type != mDNSAddrType_IPv4))
5537 {
5538 continue;
5539 }
5540 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
5541 {
5542 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
5543 return (mDNStrue);
5544 }
5545 }
5546 }
5547 }
5548 return (mDNSfalse);
5549 }
5550
5551 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
5552 mDNSlocal void BeginSleepProcessing(mDNS *const m)
5553 {
5554 mDNSBool SendGoodbyes = mDNStrue;
5555 const CacheRecord *sps[3] = { mDNSNULL };
5556 mDNSOpaque64 updateIntID = zeroOpaque64;
5557 mDNSInterfaceID registeredIntfIDS[128];
5558 mDNSu32 registeredCount = 0;
5559
5560 m->NextScheduledSPRetry = m->timenow;
5561
5562 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
5563 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
5564 else // If we have at least one advertised service
5565 {
5566 NetworkInterfaceInfo *intf;
5567 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5568 {
5569 if (!intf->NetWake) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
5570
5571 // Check if we have already registered with a sleep proxy for this subnet
5572 if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
5573 {
5574 LogSPS("%s : Skipping sleep proxy registration on %s", __func__, intf->ifname);
5575 continue;
5576 }
5577
5578 #if APPLE_OSX_mDNSResponder
5579 else if (ActivateLocalProxy(m, intf->ifname) == mStatus_NoError)
5580 {
5581 SendGoodbyes = mDNSfalse;
5582 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
5583 // This will leave m->SleepState set to SleepState_Transferring,
5584 // which is okay because with no outstanding resolves, or updates in flight,
5585 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
5586
5587 registeredIntfIDS[registeredCount] = intf->InterfaceID;
5588 registeredCount++;
5589 }
5590 #endif // APPLE_OSX_mDNSResponder
5591 else
5592 {
5593 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
5594 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
5595 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
5596 else
5597 {
5598 int i;
5599 mDNSu32 scopeid;
5600 SendGoodbyes = mDNSfalse;
5601 intf->NextSPSAttempt = 0;
5602 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
5603
5604 #if APPLE_OSX_mDNSResponder
5605 // Before we start the sleep processing, stop IPv6 advertisements
5606 mDNSPlatformToggleInterfaceAdvt(m, mDNStrue);
5607 #endif
5608 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
5609 // Now we know for sure that we have to wait for registration to complete on this interface.
5610 if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
5611 bit_set_opaque64(updateIntID, scopeid);
5612
5613 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
5614 for (i=0; i<3; i++)
5615 {
5616 #if ForceAlerts
5617 if (intf->SPSAddr[i].type)
5618 { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); *(long*)0 = 0; }
5619 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
5620 { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); *(long*)0 = 0; }
5621 #endif
5622 intf->SPSAddr[i].type = mDNSAddrType_None;
5623 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
5624 intf->NetWakeResolve[i].ThisQInterval = -1;
5625 if (sps[i])
5626 {
5627 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
5628 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
5629 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
5630 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
5631
5632 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
5633 registeredIntfIDS[registeredCount] = intf->InterfaceID;
5634 registeredCount++;
5635 }
5636 }
5637 }
5638 }
5639 }
5640 }
5641
5642 // If we have at least one interface on which we are registering with an external sleep proxy,
5643 // initialize all the records appropriately.
5644 if (!mDNSOpaque64IsZero(&updateIntID)) SPSInitRecordsBeforeUpdate(m, updateIntID);
5645
5646 if (SendGoodbyes) // If we didn't find even one Sleep Proxy
5647 {
5648 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
5649 SendSleepGoodbyes(m);
5650 }
5651 }
5652
5653 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
5654 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
5655 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
5656 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
5657 {
5658 AuthRecord *rr;
5659
5660 LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
5661
5662 if (sleep && !m->SleepState) // Going to sleep
5663 {
5664 mDNS_Lock(m);
5665 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
5666 if (m->SPSSocket)
5667 {
5668 mDNSu8 oldstate = m->SPSState;
5669 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
5670 m->SPSState = 2;
5671 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
5672 mDNS_ReclaimLockAfterCallback();
5673 }
5674
5675 m->SleepState = SleepState_Transferring;
5676 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
5677 {
5678 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
5679 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
5680 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
5681 }
5682 else
5683 {
5684 m->DelaySleep = 0;
5685 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
5686 BeginSleepProcessing(m);
5687 }
5688
5689 #ifndef UNICAST_DISABLED
5690 SuspendLLQs(m);
5691 #endif
5692 #if APPLE_OSX_mDNSResponder
5693 RemoveAutoTunnel6Record(m);
5694 #endif
5695 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
5696 m->SleepState == SleepState_Transferring ? "Transferring" :
5697 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
5698 mDNS_Unlock(m);
5699 }
5700 else if (!sleep) // Waking up
5701 {
5702 mDNSu32 slot;
5703 CacheGroup *cg;
5704 CacheRecord *cr;
5705 NetworkInterfaceInfo *intf;
5706
5707 mDNS_Lock(m);
5708 // Reset SleepLimit back to 0 now that we're awake again.
5709 m->SleepLimit = 0;
5710
5711 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
5712 if (m->SleepState != SleepState_Awake)
5713 {
5714 m->SleepState = SleepState_Awake;
5715 m->SleepSeqNum++;
5716 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
5717 // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
5718 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
5719 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
5720 m->DelaySleep = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 16);
5721 }
5722
5723 if (m->SPSState == 3)
5724 {
5725 m->SPSState = 0;
5726 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
5727 }
5728
5729 // ... and the same for NextSPSAttempt
5730 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
5731
5732 // Restart unicast and multicast queries
5733 mDNSCoreRestartQueries(m);
5734
5735 // and reactivtate service registrations
5736 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
5737 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
5738
5739 // 2. Re-validate our cache records
5740 FORALL_CACHERECORDS(slot, cg, cr)
5741 {
5742 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
5743 }
5744
5745 // 3. Retrigger probing and announcing for all our authoritative records
5746 for (rr = m->ResourceRecords; rr; rr=rr->next)
5747 if (AuthRecord_uDNS(rr))
5748 {
5749 ActivateUnicastRegistration(m, rr);
5750 }
5751 else
5752 {
5753 mDNSCoreRestartRegistration(m, rr, -1);
5754 }
5755
5756 // 4. Refresh NAT mappings
5757 // We don't want to have to assume that all hardware can necessarily keep accurate
5758 // track of passage of time while asleep, so on wake we refresh our NAT mappings
5759 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
5760 // When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
5761 // mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
5762 m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
5763 m->retryGetAddr = m->timenow + mDNSPlatformOneSecond * 5;
5764 LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m->retryGetAddr - m->timenow, m->timenow);
5765 RecreateNATMappings(m);
5766 mDNS_Unlock(m);
5767 }
5768 }
5769
5770 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
5771 {
5772 DNSQuestion *q;
5773 AuthRecord *rr;
5774 NetworkInterfaceInfo *intf;
5775
5776 mDNS_Lock(m);
5777
5778 if (m->DelaySleep) goto notready;
5779
5780 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
5781 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
5782
5783 m->NextScheduledSPRetry = now + 0x40000000UL;
5784
5785 // See if we might need to retransmit any lost Sleep Proxy Registrations
5786 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5787 if (intf->NextSPSAttempt >= 0)
5788 {
5789 if (now - intf->NextSPSAttemptTime >= 0)
5790 {
5791 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
5792 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
5793 SendSPSRegistration(m, intf, zeroID);
5794 // Don't need to "goto notready" here, because if we do still have record registrations
5795 // that have not been acknowledged yet, we'll catch that in the record list scan below.
5796 }
5797 else
5798 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
5799 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
5800 }
5801
5802 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
5803 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5804 {
5805 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
5806 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
5807 {
5808 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
5809 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
5810 goto spsnotready;
5811 }
5812 }
5813
5814 // Scan list of registered records
5815 for (rr = m->ResourceRecords; rr; rr = rr->next)
5816 if (!AuthRecord_uDNS(rr))
5817 if (!mDNSOpaque64IsZero(&rr->updateIntID))
5818 { 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; }
5819
5820 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
5821 for (q = m->Questions; q; q = q->next)
5822 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
5823 {
5824 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5825 goto notready;
5826 }
5827
5828 // Scan list of registered records
5829 for (rr = m->ResourceRecords; rr; rr = rr->next)
5830 if (AuthRecord_uDNS(rr))
5831 {
5832 if (rr->state == regState_Refresh && rr->tcp)
5833 { 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; }
5834 #if APPLE_OSX_mDNSResponder
5835 if (!RecordReadyForSleep(m, rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
5836 #endif
5837 }
5838
5839 mDNS_Unlock(m);
5840 return mDNStrue;
5841
5842 spsnotready:
5843
5844 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
5845 // and allow up to ten seconds more to complete wide-area deregistration instead
5846 if (now - m->SleepLimit >= 0)
5847 {
5848 LogMsg("Failed to register with SPS, now sending goodbyes");
5849
5850 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5851 if (intf->NetWakeBrowse.ThisQInterval >= 0)
5852 {
5853 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
5854 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
5855 mDNS_DeactivateNetWake_internal(m, intf);
5856 }
5857
5858 for (rr = m->ResourceRecords; rr; rr = rr->next)
5859 if (!AuthRecord_uDNS(rr))
5860 if (!mDNSOpaque64IsZero(&rr->updateIntID))
5861 {
5862 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));
5863 rr->updateIntID = zeroOpaque64;
5864 }
5865
5866 // We'd really like to allow up to ten seconds more here,
5867 // but if we don't respond to the sleep notification within 30 seconds
5868 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
5869 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
5870 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
5871 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
5872 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
5873
5874 SendSleepGoodbyes(m);
5875 }
5876
5877 notready:
5878 mDNS_Unlock(m);
5879 return mDNSfalse;
5880 }
5881
5882 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
5883 {
5884 AuthRecord *ar;
5885
5886 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
5887 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
5888 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
5889 // and if that happens we don't want to just give up and go back to sleep and never try again.
5890 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
5891
5892 NATTraversalInfo *nat;
5893 for (nat = m->NATTraversals; nat; nat=nat->next)
5894 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
5895 {
5896 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
5897 if (e - t > 0) e = t;
5898 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
5899 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
5900 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
5901 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5902 nat->retryInterval / mDNSPlatformOneSecond,
5903 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5904 (t - now) / mDNSPlatformOneSecond);
5905 }
5906
5907 // This loop checks both the time we need to renew wide-area registrations,
5908 // and the time we need to renew Sleep Proxy registrations
5909 for (ar = m->ResourceRecords; ar; ar = ar->next)
5910 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
5911 {
5912 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
5913 if (e - t > 0) e = t;
5914 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
5915 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
5916 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5917 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5918 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
5919 }
5920
5921 return(e - now);
5922 }
5923
5924 // ***************************************************************************
5925 #if COMPILER_LIKES_PRAGMA_MARK
5926 #pragma mark -
5927 #pragma mark - Packet Reception Functions
5928 #endif
5929
5930 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
5931
5932 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
5933 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
5934 {
5935 mDNSu8 *responseptr = response->data;
5936 const mDNSu8 *const limit = response->data + sizeof(response->data);
5937 const mDNSu8 *ptr = query->data;
5938 AuthRecord *rr;
5939 mDNSu32 maxttl = 0x70000000;
5940 int i;
5941
5942 // Initialize the response fields so we can answer the questions
5943 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
5944
5945 // ***
5946 // *** 1. Write out the list of questions we are actually going to answer with this packet
5947 // ***
5948 if (LegacyQuery)
5949 {
5950 maxttl = kStaticCacheTTL;
5951 for (i=0; i<query->h.numQuestions; i++) // For each question...
5952 {
5953 DNSQuestion q;
5954 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
5955 if (!ptr) return(mDNSNULL);
5956
5957 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
5958 {
5959 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
5960 { // then put the question in the question section
5961 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
5962 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
5963 break; // break out of the ResponseRecords loop, and go on to the next question
5964 }
5965 }
5966 }
5967
5968 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
5969 }
5970
5971 // ***
5972 // *** 2. Write Answers
5973 // ***
5974 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5975 if (rr->NR_AnswerTo)
5976 {
5977 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
5978 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5979 if (p) responseptr = p;
5980 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
5981 }
5982
5983 // ***
5984 // *** 3. Write Additionals
5985 // ***
5986 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5987 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
5988 {
5989 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
5990 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5991 if (p) responseptr = p;
5992 else debugf("GenerateUnicastResponse: No more space for additionals");
5993 }
5994
5995 return(responseptr);
5996 }
5997
5998 // AuthRecord *our is our Resource Record
5999 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
6000 // Returns 0 if there is no conflict
6001 // Returns +1 if there was a conflict and we won
6002 // Returns -1 if there was a conflict and we lost and have to rename
6003 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
6004 {
6005 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
6006 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
6007 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
6008 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
6009
6010 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
6011 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
6012 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
6013 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
6014
6015 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
6016 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
6017 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
6018 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
6019
6020 LogMsg("CompareRData ERROR: Invalid state");
6021 return(-1);
6022 }
6023
6024 // See if we have an authoritative record that's identical to this packet record,
6025 // whose canonical DependentOn record is the specified master record.
6026 // The DependentOn pointer is typically used for the TXT record of service registrations
6027 // It indicates that there is no inherent conflict detection for the TXT record
6028 // -- it depends on the SRV record to resolve name conflicts
6029 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
6030 // pointer chain (if any) to make sure we reach the canonical DependentOn record
6031 // If the record has no DependentOn, then just return that record's pointer
6032 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6033 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
6034 {
6035 const AuthRecord *r1;
6036 for (r1 = m->ResourceRecords; r1; r1=r1->next)
6037 {
6038 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
6039 {
6040 const AuthRecord *r2 = r1;
6041 while (r2->DependentOn) r2 = r2->DependentOn;
6042 if (r2 == master) return(mDNStrue);
6043 }
6044 }
6045 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
6046 {
6047 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
6048 {
6049 const AuthRecord *r2 = r1;
6050 while (r2->DependentOn) r2 = r2->DependentOn;
6051 if (r2 == master) return(mDNStrue);
6052 }
6053 }
6054 return(mDNSfalse);
6055 }
6056
6057 // Find the canonical RRSet pointer for this RR received in a packet.
6058 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
6059 // pointers (if any) to make sure we return the canonical member of this name/type/class
6060 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6061 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
6062 {
6063 const AuthRecord *rr;
6064 for (rr = m->ResourceRecords; rr; rr=rr->next)
6065 {
6066 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
6067 {
6068 while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
6069 return(rr);
6070 }
6071 }
6072 return(mDNSNULL);
6073 }
6074
6075 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
6076 // as one of our records (our) but different rdata.
6077 // 1. If our record is not a type that's supposed to be unique, we don't care.
6078 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
6079 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
6080 // points to our record, ignore this conflict (e.g. the packet record matches one of our
6081 // TXT records, and that record is marked as dependent on 'our', its SRV record).
6082 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
6083 // are members of the same RRSet, then this is not a conflict.
6084 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
6085 {
6086 // If not supposed to be unique, not a conflict
6087 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
6088
6089 // If a dependent record, not a conflict
6090 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
6091 else
6092 {
6093 // If the pktrr matches a member of ourset, not a conflict
6094 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
6095 const AuthRecord *pktset = FindRRSet(m, pktrr);
6096 if (pktset == ourset) return(mDNSfalse);
6097
6098 // For records we're proxying, where we don't know the full
6099 // relationship between the records, having any matching record
6100 // in our AuthRecords list is sufficient evidence of non-conflict
6101 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
6102 }
6103
6104 // Okay, this is a conflict
6105 return(mDNStrue);
6106 }
6107
6108 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
6109 // the record list and/or question list.
6110 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6111 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
6112 DNSQuestion *q, AuthRecord *our)
6113 {
6114 int i;
6115 const mDNSu8 *ptr = LocateAuthorities(query, end);
6116 mDNSBool FoundUpdate = mDNSfalse;
6117
6118 for (i = 0; i < query->h.numAuthorities; i++)
6119 {
6120 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
6121 if (!ptr) break;
6122 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
6123 {
6124 FoundUpdate = mDNStrue;
6125 if (PacketRRConflict(m, our, &m->rec.r))
6126 {
6127 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
6128 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
6129 if (!result) result = CompareRData(our, &m->rec.r);
6130 if (result)
6131 {
6132 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
6133 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
6134 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
6135 }
6136 // 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.
6137 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
6138 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
6139 if (result < 0)
6140 {
6141 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
6142 our->ProbeCount = DefaultProbeCountForTypeUnique;
6143 our->AnnounceCount = InitialAnnounceCount;
6144 InitializeLastAPTime(m, our);
6145 goto exit;
6146 }
6147 }
6148 #if 0
6149 else
6150 {
6151 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
6152 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
6153 }
6154 #endif
6155 }
6156 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6157 }
6158 if (!FoundUpdate)
6159 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
6160 exit:
6161 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6162 }
6163
6164 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
6165 {
6166 mDNSu32 slot = HashSlot(pktrr->name);
6167 CacheGroup *cg = CacheGroupForRecord(m, slot, pktrr);
6168 CacheRecord *rr;
6169 mDNSBool match;
6170 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6171 {
6172 if (!pktrr->InterfaceID)
6173 {
6174 mDNSu16 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
6175 mDNSu16 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
6176 match = (id1 == id2);
6177 }
6178 else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
6179
6180 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
6181 }
6182 return(rr);
6183 }
6184
6185 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
6186 // to check our lists and discard any stale duplicates of this record we already have
6187 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
6188 {
6189 if (m->CurrentRecord)
6190 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
6191 m->CurrentRecord = thelist;
6192 while (m->CurrentRecord)
6193 {
6194 AuthRecord *const rr = m->CurrentRecord;
6195 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
6196 // Normally, the RDATA of the keepalive record will be different each time and hence we always
6197 // clean up the keepalive record.
6198 if (mDNS_KeepaliveRecord(&rr->resrec) || IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
6199 {
6200 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
6201 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
6202 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
6203 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
6204 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
6205 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
6206 }
6207 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
6208 // new records could have been added to the end of the list as a result of that call.
6209 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6210 m->CurrentRecord = rr->next;
6211 }
6212 }
6213
6214 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
6215 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
6216 {
6217 if (m->CurrentRecord)
6218 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
6219 m->CurrentRecord = thelist;
6220 while (m->CurrentRecord)
6221 {
6222 AuthRecord *const rr = m->CurrentRecord;
6223 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
6224 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
6225 {
6226 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
6227 {
6228 // We don't do this here because we know that the host is waking up at this point, so we don't send
6229 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
6230 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
6231 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
6232 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
6233 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
6234 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
6235 #endif
6236 }
6237 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
6238 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
6239 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
6240 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
6241 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
6242 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
6243 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
6244 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
6245 }
6246 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
6247 // new records could have been added to the end of the list as a result of that call.
6248 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6249 m->CurrentRecord = rr->next;
6250 }
6251 }
6252
6253 // ProcessQuery examines a received query to see if we have any answers to give
6254 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
6255 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
6256 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
6257 {
6258 mDNSBool FromLocalSubnet = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6259 AuthRecord *ResponseRecords = mDNSNULL;
6260 AuthRecord **nrp = &ResponseRecords;
6261
6262 #if POOF_ENABLED
6263 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
6264 CacheRecord **eap = &ExpectedAnswers;
6265 #endif // POOF_ENABLED
6266
6267 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
6268 DNSQuestion **dqp = &DupQuestions;
6269 mDNSs32 delayresponse = 0;
6270 mDNSBool SendLegacyResponse = mDNSfalse;
6271 const mDNSu8 *ptr;
6272 mDNSu8 *responseptr = mDNSNULL;
6273 AuthRecord *rr;
6274 int i;
6275
6276 // ***
6277 // *** 1. Look in Additional Section for an OPT record
6278 // ***
6279 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
6280 if (ptr)
6281 {
6282 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
6283 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
6284 {
6285 const rdataOPT *opt;
6286 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
6287 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
6288 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
6289 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
6290 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
6291 {
6292 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
6293 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
6294 }
6295 }
6296 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6297 }
6298
6299 // ***
6300 // *** 2. Parse Question Section and mark potential answers
6301 // ***
6302 ptr = query->data;
6303 for (i=0; i<query->h.numQuestions; i++) // For each question...
6304 {
6305 mDNSBool QuestionNeedsMulticastResponse;
6306 int NumAnswersForThisQuestion = 0;
6307 AuthRecord *NSECAnswer = mDNSNULL;
6308 DNSQuestion pktq, *q;
6309 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
6310 if (!ptr) goto exit;
6311
6312 // The only queries that *need* a multicast response are:
6313 // * Queries sent via multicast
6314 // * from port 5353
6315 // * that don't have the kDNSQClass_UnicastResponse bit set
6316 // These queries need multicast responses because other clients will:
6317 // * suppress their own identical questions when they see these questions, and
6318 // * expire their cache records if they don't see the expected responses
6319 // For other queries, we may still choose to send the occasional multicast response anyway,
6320 // to keep our neighbours caches warm, and for ongoing conflict detection.
6321 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
6322 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
6323 pktq.qclass &= ~kDNSQClass_UnicastResponse;
6324
6325 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
6326 // can result in user callbacks which may change the record list and/or question list.
6327 // Also note: we just mark potential answer records here, without trying to build the
6328 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
6329 // from that list while we're in the middle of trying to build it.
6330 if (m->CurrentRecord)
6331 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
6332 m->CurrentRecord = m->ResourceRecords;
6333 while (m->CurrentRecord)
6334 {
6335 rr = m->CurrentRecord;
6336 m->CurrentRecord = rr->next;
6337 if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
6338 {
6339 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
6340 {
6341 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
6342 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
6343 else if (ResourceRecordIsValidAnswer(rr))
6344 {
6345 NumAnswersForThisQuestion++;
6346 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
6347 // unicast answer back to the source, because timeliness in answering probes is important.
6348
6349 // Notes:
6350 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
6351 // NR_AnswerTo == (mDNSu8*)~1 means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
6352 // NR_AnswerTo == (mDNSu8*)~0 means "definitely answer via multicast" (can't downgrade to unicast later)
6353 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
6354 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
6355 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
6356 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
6357 {
6358 // We only mark this question for sending if it is at least one second since the last time we multicast it
6359 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
6360 // This is to guard against the case where someone blasts us with queries as fast as they can.
6361 if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
6362 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
6363 rr->NR_AnswerTo = (mDNSu8*)~0;
6364 }
6365 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : (mDNSu8*)~1;
6366 }
6367 }
6368 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
6369 {
6370 // If we don't have any answers for this question, but we do own another record with the same name,
6371 // then we'll want to mark it to generate an NSEC record on this interface
6372 if (!NSECAnswer) NSECAnswer = rr;
6373 }
6374 }
6375 }
6376
6377 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
6378 {
6379 NumAnswersForThisQuestion++;
6380 NSECAnswer->SendNSECNow = InterfaceID;
6381 m->NextScheduledResponse = m->timenow;
6382 }
6383
6384 // If we couldn't answer this question, someone else might be able to,
6385 // so use random delay on response to reduce collisions
6386 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
6387
6388 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6389 if (QuestionNeedsMulticastResponse)
6390 #else
6391 // We only do the following accelerated cache expiration and duplicate question suppression processing
6392 // for non-truncated multicast queries with multicast responses.
6393 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
6394 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
6395 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
6396 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
6397 #endif
6398 {
6399 #if POOF_ENABLED
6400 const mDNSu32 slot = HashSlot(&pktq.qname);
6401 CacheGroup *cg = CacheGroupForName(m, slot, pktq.qnamehash, &pktq.qname);
6402 CacheRecord *cr;
6403
6404 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
6405 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
6406 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6407 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
6408 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
6409 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
6410 if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
6411 if (!cr->NextInKAList && eap != &cr->NextInKAList)
6412 {
6413 *eap = cr;
6414 eap = &cr->NextInKAList;
6415 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6416 if (cr->MPUnansweredQ == 0 || m->timenow - cr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
6417 {
6418 // Although MPUnansweredQ is only really used for multi-packet query processing,
6419 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
6420 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
6421 cr->MPUnansweredQ++;
6422 cr->MPLastUnansweredQT = m->timenow;
6423 cr->MPExpectingKA = mDNStrue;
6424 }
6425 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
6426 }
6427 #endif // POOF_ENABLED
6428
6429 // Check if this question is the same as any of mine.
6430 // We only do this for non-truncated queries. Right now it would be too complicated to try
6431 // to keep track of duplicate suppression state between multiple packets, especially when we
6432 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
6433 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6434 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
6435 #endif
6436 for (q = m->Questions; q; q=q->next)
6437 if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
6438 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
6439 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
6440 if (q->qtype == pktq.qtype &&
6441 q->qclass == pktq.qclass &&
6442 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
6443 { *dqp = q; dqp = &q->NextInDQList; }
6444 }
6445 }
6446
6447 // ***
6448 // *** 3. Now we can safely build the list of marked answers
6449 // ***
6450 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
6451 if (rr->NR_AnswerTo) // If we marked the record...
6452 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
6453
6454 // ***
6455 // *** 4. Add additional records
6456 // ***
6457 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
6458
6459 // ***
6460 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
6461 // ***
6462 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
6463 {
6464 // Get the record...
6465 CacheRecord *ourcacherr;
6466 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
6467 if (!ptr) goto exit;
6468 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
6469 {
6470 // See if this Known-Answer suppresses any of our currently planned answers
6471 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6472 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
6473 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
6474
6475 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
6476 for (rr=m->ResourceRecords; rr; rr=rr->next)
6477 {
6478 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
6479 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
6480 {
6481 if (srcaddr->type == mDNSAddrType_IPv4)
6482 {
6483 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
6484 }
6485 else if (srcaddr->type == mDNSAddrType_IPv6)
6486 {
6487 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
6488 }
6489 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
6490 {
6491 rr->ImmedAnswer = mDNSNULL;
6492 rr->ImmedUnicast = mDNSfalse;
6493 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6494 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
6495 #endif
6496 }
6497 }
6498 }
6499
6500 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
6501
6502 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6503 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
6504 // 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).
6505 if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
6506 {
6507 ourcacherr->MPUnansweredKA++;
6508 ourcacherr->MPExpectingKA = mDNSfalse;
6509 }
6510 #endif
6511
6512 #if POOF_ENABLED
6513 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
6514 // any records that are suppressed by the Known Answer list in this packet.
6515 eap = &ExpectedAnswers;
6516 while (*eap)
6517 {
6518 CacheRecord *cr = *eap;
6519 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
6520 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
6521 else eap = &cr->NextInKAList;
6522 }
6523 #endif // POOF_ENABLED
6524
6525 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
6526 if (!ourcacherr)
6527 {
6528 dqp = &DupQuestions;
6529 while (*dqp)
6530 {
6531 DNSQuestion *q = *dqp;
6532 if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
6533 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
6534 else dqp = &q->NextInDQList;
6535 }
6536 }
6537 }
6538 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6539 }
6540
6541 // ***
6542 // *** 6. Cancel any additionals that were added because of now-deleted records
6543 // ***
6544 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6545 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
6546 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
6547
6548 // ***
6549 // *** 7. Mark the send flags on the records we plan to send
6550 // ***
6551 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6552 {
6553 if (rr->NR_AnswerTo)
6554 {
6555 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
6556 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
6557
6558 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
6559 if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0)
6560 {
6561 SendMulticastResponse = mDNStrue;
6562 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
6563 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
6564 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
6565 if (rr->NR_AnswerTo == (mDNSu8*)~1) rr->NR_AnswerTo = (mDNSu8*)~0;
6566 }
6567
6568 // If the client insists on a multicast response, then we'd better send one
6569 if (rr->NR_AnswerTo == (mDNSu8*)~0) SendMulticastResponse = mDNStrue;
6570 else if (rr->NR_AnswerTo == (mDNSu8*)~1) SendUnicastResponse = mDNStrue;
6571 else if (rr->NR_AnswerTo) SendLegacyResponse = mDNStrue;
6572
6573 if (SendMulticastResponse || SendUnicastResponse)
6574 {
6575 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6576 rr->ImmedAnswerMarkTime = m->timenow;
6577 #endif
6578 m->NextScheduledResponse = m->timenow;
6579 // If we're already planning to send this on another interface, just send it on all interfaces
6580 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
6581 rr->ImmedAnswer = mDNSInterfaceMark;
6582 else
6583 {
6584 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
6585 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
6586 if (srcaddr->type == mDNSAddrType_IPv4)
6587 {
6588 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
6589 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
6590 }
6591 else if (srcaddr->type == mDNSAddrType_IPv6)
6592 {
6593 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
6594 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
6595 }
6596 }
6597 }
6598 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
6599 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
6600 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
6601 // else, for a simple unique record reply, we can reply immediately; no need for delay
6602 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
6603 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
6604 }
6605 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == (mDNSu8*)~0)
6606 {
6607 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
6608 // If two clients on different interfaces do queries that invoke the same optional additional answer,
6609 // then the earlier client is out of luck
6610 rr->ImmedAdditional = InterfaceID;
6611 // No need to set m->NextScheduledResponse here
6612 // We'll send these additional records when we send them, or not, as the case may be
6613 }
6614 }
6615
6616 // ***
6617 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
6618 // ***
6619 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
6620 {
6621 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6622 mDNSs32 oldss = m->SuppressSending;
6623 if (oldss && delayresponse)
6624 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
6625 #endif
6626 // Pick a random delay:
6627 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
6628 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
6629 // This is an integer value, with resolution determined by the platform clock rate.
6630 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
6631 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
6632 // The +49 before dividing is to ensure we round up, not down, to ensure that even
6633 // on platforms where the native clock rate is less than fifty ticks per second,
6634 // we still guarantee that the final calculated delay is at least one platform tick.
6635 // We want to make sure we don't ever allow the delay to be zero ticks,
6636 // because if that happens we'll fail the Bonjour Conformance Test.
6637 // Our final computed delay is 20-120ms for normal delayed replies,
6638 // or 400-500ms in the case of multi-packet known-answer lists.
6639 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
6640 if (m->SuppressSending == 0) m->SuppressSending = 1;
6641 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6642 if (oldss && delayresponse)
6643 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
6644 #endif
6645 }
6646
6647 // ***
6648 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
6649 // ***
6650 if (SendLegacyResponse)
6651 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
6652
6653 exit:
6654 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6655
6656 // ***
6657 // *** 10. Finally, clear our link chains ready for use next time
6658 // ***
6659 while (ResponseRecords)
6660 {
6661 rr = ResponseRecords;
6662 ResponseRecords = rr->NextResponse;
6663 rr->NextResponse = mDNSNULL;
6664 rr->NR_AnswerTo = mDNSNULL;
6665 rr->NR_AdditionalTo = mDNSNULL;
6666 }
6667
6668 #if POOF_ENABLED
6669 while (ExpectedAnswers)
6670 {
6671 CacheRecord *cr = ExpectedAnswers;
6672 ExpectedAnswers = cr->NextInKAList;
6673 cr->NextInKAList = mDNSNULL;
6674
6675 // For non-truncated queries, we can definitively say that we should expect
6676 // to be seeing a response for any records still left in the ExpectedAnswers list
6677 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
6678 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond)
6679 {
6680 cr->UnansweredQueries++;
6681 cr->LastUnansweredTime = m->timenow;
6682 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6683 if (cr->UnansweredQueries > 1)
6684 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
6685 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6686 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
6687 SetNextCacheCheckTimeForRecord(m, cr);
6688 }
6689
6690 // If we've seen multiple unanswered queries for this record,
6691 // then mark it to expire in five seconds if we don't get a response by then.
6692 if (cr->UnansweredQueries >= MaxUnansweredQueries)
6693 {
6694 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6695 // Only show debugging message if this record was not about to expire anyway
6696 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6697 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6698 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6699 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
6700 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
6701 }
6702 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6703 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
6704 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
6705 // possible packet loss of up to 20% of the additional KA packets.)
6706 else if (cr->MPUnansweredQ * 4 > cr->MPUnansweredKA * 5 + 8)
6707 {
6708 // We want to do this conservatively.
6709 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
6710 // then we don't want them to all hit the network simultaneously with their final expiration queries.
6711 // By setting the record to expire in four minutes, we achieve two things:
6712 // (a) the 90-95% final expiration queries will be less bunched together
6713 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
6714 mDNSu32 remain = (mDNSu32)(RRExpireTime(cr) - m->timenow) / 4;
6715 if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
6716 remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
6717
6718 // Only show debugging message if this record was not about to expire anyway
6719 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6720 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6721 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6722
6723 if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
6724 cr->UnansweredQueries++; // Treat this as equivalent to one definite unanswered query
6725 cr->MPUnansweredQ = 0; // Clear MPQ/MPKA statistics
6726 cr->MPUnansweredKA = 0;
6727 cr->MPExpectingKA = mDNSfalse;
6728
6729 if (remain < kDefaultReconfirmTimeForNoAnswer)
6730 remain = kDefaultReconfirmTimeForNoAnswer;
6731 mDNS_Reconfirm_internal(m, cr, remain);
6732 }
6733 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
6734 }
6735 #endif // POOF_ENABLED
6736
6737 while (DupQuestions)
6738 {
6739 DNSQuestion *q = DupQuestions;
6740 DupQuestions = q->NextInDQList;
6741 q->NextInDQList = mDNSNULL;
6742 i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
6743 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
6744 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
6745 }
6746
6747 return(responseptr);
6748 }
6749
6750 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
6751 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6752 const mDNSInterfaceID InterfaceID)
6753 {
6754 mDNSu8 *responseend = mDNSNULL;
6755 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
6756 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6757
6758 if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
6759 {
6760 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6761 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
6762 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6763 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
6764 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
6765 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
6766 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
6767 return;
6768 }
6769
6770 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6771 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6772 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6773 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
6774 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
6775 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
6776 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
6777
6778 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
6779 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
6780
6781 if (responseend) // If responseend is non-null, that means we built a unicast response packet
6782 {
6783 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
6784 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
6785 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
6786 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
6787 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
6788 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
6789 }
6790 }
6791
6792 #if 0
6793 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
6794 {
6795 DNSServer *s;
6796 (void)m; // Unused
6797 (void)srcaddr; // Unused
6798 for (s = m->DNSServers; s; s = s->next)
6799 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
6800 return(mDNSfalse);
6801 }
6802 #endif
6803
6804 struct UDPSocket_struct
6805 {
6806 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
6807 };
6808
6809 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
6810 {
6811 DNSQuestion *q;
6812 for (q = m->Questions; q; q=q->next)
6813 {
6814 if (!tcp && !q->LocalSocket) continue;
6815 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
6816 mDNSSameOpaque16(q->TargetQID, id) &&
6817 q->qtype == question->qtype &&
6818 q->qclass == question->qclass &&
6819 q->qnamehash == question->qnamehash &&
6820 SameDomainName(&q->qname, &question->qname))
6821 return(q);
6822 }
6823 return(mDNSNULL);
6824 }
6825
6826 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
6827 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
6828 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
6829 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
6830 {
6831 DNSQuestion *q;
6832 (void)id;
6833 (void)srcaddr;
6834
6835 for (q = m->Questions; q; q=q->next)
6836 {
6837 if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
6838 {
6839 if (!mDNSOpaque16IsZero(q->TargetQID))
6840 {
6841 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
6842
6843 if (mDNSSameOpaque16(q->TargetQID, id))
6844 {
6845 mDNSIPPort srcp;
6846 if (!tcp)
6847 {
6848 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
6849 }
6850 else
6851 {
6852 srcp = q->tcpSrcPort;
6853 }
6854 if (mDNSSameIPPort(srcp, port)) return(q);
6855
6856 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
6857 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
6858 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
6859 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
6860 q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
6861 return(mDNSNULL);
6862 }
6863 }
6864 else
6865 {
6866 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
6867 return(q);
6868 }
6869 }
6870 }
6871 return(mDNSNULL);
6872 }
6873
6874 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
6875 // Currently this applies only to rdata types containing more than one domainname,
6876 // or types where the domainname is not the last item in the structure.
6877 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
6878 {
6879 switch (rr->rrtype)
6880 {
6881 case kDNSType_SOA: return sizeof(rdataSOA);
6882 case kDNSType_RP: return sizeof(rdataRP);
6883 case kDNSType_PX: return sizeof(rdataPX);
6884 default: return rr->rdlength;
6885 }
6886 }
6887
6888 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
6889 {
6890 CacheRecord *rr = mDNSNULL;
6891 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
6892
6893 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
6894
6895 //if (RDLength > InlineCacheRDSize)
6896 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
6897
6898 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
6899 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
6900 if (!rr) NoCacheAnswer(m, &m->rec.r);
6901 else
6902 {
6903 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
6904 *rr = m->rec.r; // Block copy the CacheRecord object
6905 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
6906 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
6907 rr->DelayDelivery = delay;
6908
6909 // If this is an oversized record with external storage allocated, copy rdata to external storage
6910 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
6911 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
6912 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
6913 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
6914 if (RDLength > InlineCacheRDSize)
6915 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
6916
6917 rr->next = mDNSNULL; // Clear 'next' pointer
6918 rr->nsec = mDNSNULL;
6919
6920 if (sourceAddress)
6921 rr->sourceAddress = *sourceAddress;
6922
6923 if (Add)
6924 {
6925 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
6926 cg->rrcache_tail = &(rr->next); // Advance tail pointer
6927 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
6928 }
6929 else
6930 {
6931 // Can't use the "cg->name" if we are not adding to the cache as the
6932 // CacheGroup may be released anytime if it is empty
6933 domainname *name = mDNSPlatformMemAllocate(DomainNameLength(cg->name));
6934 if (name)
6935 {
6936 AssignDomainName(name, cg->name);
6937 rr->resrec.name = name;
6938 }
6939 else
6940 {
6941 ReleaseCacheRecord(m, rr);
6942 NoCacheAnswer(m, &m->rec.r);
6943 rr = mDNSNULL;
6944 }
6945 }
6946 }
6947 return(rr);
6948 }
6949
6950 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
6951 {
6952 rr->TimeRcvd = m->timenow;
6953 rr->resrec.rroriginalttl = ttl;
6954 rr->UnansweredQueries = 0;
6955 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6956 rr->MPUnansweredQ = 0;
6957 rr->MPUnansweredKA = 0;
6958 rr->MPExpectingKA = mDNSfalse;
6959 #endif
6960 SetNextCacheCheckTimeForRecord(m, rr);
6961 }
6962
6963 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
6964 {
6965 CacheRecord *rr;
6966 const mDNSu32 slot = HashSlot(&q->qname);
6967 CacheGroup *cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
6968 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6969 if (rr->CRActiveQuestion == q)
6970 {
6971 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
6972 RefreshCacheRecord(m, rr, lease);
6973 }
6974 }
6975
6976 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
6977 {
6978 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
6979 else if (LLQType == uDNS_LLQ_Events)
6980 {
6981 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
6982 if (ttl == 0xFFFFFFFF) ttl = 0;
6983 else ttl = kLLQ_DefLease;
6984 }
6985 else // else not LLQ (standard uDNS response)
6986 {
6987 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
6988 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
6989 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
6990
6991 // Adjustment factor to avoid race condition:
6992 // Suppose real record as TTL of 3600, and our local caching server has held it for 3500 seconds, so it returns an aged TTL of 100.
6993 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
6994 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
6995 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
6996 // We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
6997 // the cached copy at our local caching server will already have expired, so the server will be forced
6998 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
6999 ttl += ttl/4 + 2;
7000
7001 // For mDNS, TTL zero means "delete this record"
7002 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
7003 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
7004 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
7005 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
7006 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
7007 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
7008 // (with the current code) result in the server having even less than three seconds to respond
7009 // before we deleted the record and reported a "remove" event to any active questions.
7010 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
7011 // then things really break (e.g. we end up making a negative cache entry).
7012 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
7013 if (ttl < 15) ttl = 15;
7014 }
7015
7016 return ttl;
7017 }
7018
7019 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
7020 // in m->rec.
7021 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist, DNSQuestion *q, mDNSBool *nseclist)
7022 {
7023 CacheRecord *const newcr = &m->rec.r;
7024 ResourceRecord *rr = &newcr->resrec;
7025 const CacheRecord *cr;
7026
7027 *nseclist = mDNSfalse;
7028 for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
7029 {
7030 domainname *target = GetRRDomainNameTarget(&cr->resrec);
7031 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
7032 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
7033 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
7034 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
7035 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
7036
7037 if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
7038 {
7039 LogInfo("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
7040 return (mDNStrue);
7041 }
7042 }
7043
7044 // Either the question requires validation or we are validating a response with DNSSEC in which case
7045 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
7046 // we receive NSECs for our query which does not match the qname and we need to cache in that case
7047 // too. nseclist is set if they have to be cached as part of the negative cache record.
7048 if (q && DNSSECQuestion(q))
7049 {
7050 mDNSBool same = SameDomainName(&q->qname, rr->name);
7051 if (same && (q->qtype == rr->rrtype || rr->rrtype == kDNSType_CNAME))
7052 {
7053 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q->qtype),
7054 CRDisplayString(m, newcr));
7055 return mDNStrue;
7056 }
7057 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
7058 // "nseclist" is set
7059 if (rr->rrtype == kDNSType_RRSIG)
7060 {
7061 RDataBody2 *const rdb = (RDataBody2 *)newcr->smallrdatastorage.data;
7062 rdataRRSig *rrsig = &rdb->rrsig;
7063 mDNSu16 typeCovered = swap16(rrsig->typeCovered);
7064
7065 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
7066 // would match the qtype and they are cached normally as they are not used to prove the
7067 // non-existence of any name. In that case, it is like any other normal dnssec validation
7068 // and hence nseclist should not be set.
7069
7070 if (same && ((typeCovered == q->qtype) || (typeCovered == kDNSType_CNAME)))
7071 {
7072 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m, newcr),
7073 DNSTypeName(q->qtype));
7074 return mDNStrue;
7075 }
7076 else if (typeCovered == kDNSType_NSEC)
7077 {
7078 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches NSEC type (nseclist = 1)", CRDisplayString(m, newcr));
7079 *nseclist = mDNStrue;
7080 return mDNStrue;
7081 }
7082 else return mDNSfalse;
7083 }
7084 if (rr->rrtype == kDNSType_NSEC)
7085 {
7086 if (!UNICAST_NSEC(rr))
7087 {
7088 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m, newcr));
7089 return mDNSfalse;
7090 }
7091 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m, newcr));
7092 *nseclist = mDNStrue;
7093 return mDNStrue;
7094 }
7095 }
7096 return mDNSfalse;
7097 }
7098
7099 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords)
7100 {
7101 CacheRecord *rp, *next;
7102
7103 for (rp = NSECRecords; rp; rp = next)
7104 {
7105 next = rp->next;
7106 ReleaseCacheRecord(m, rp);
7107 }
7108 }
7109
7110 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
7111 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, uDNS_LLQType LLQType, mDNSu8 rcode, CacheRecord *NSECRecords)
7112 {
7113 int i;
7114 const mDNSu8 *ptr = response->data;
7115 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
7116 {
7117 DNSQuestion q;
7118 DNSQuestion *qptr = mDNSNULL;
7119 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
7120 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
7121 {
7122 CacheRecord *rr, *neg = mDNSNULL;
7123 mDNSu32 slot = HashSlot(&q.qname);
7124 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
7125 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7126 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
7127 {
7128 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
7129 if (RRExpireTime(rr) - m->timenow > 0) break;
7130 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
7131 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
7132 }
7133 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
7134 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
7135 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
7136 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
7137 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
7138 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
7139 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
7140 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
7141 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
7142 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
7143 //
7144 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
7145 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
7146 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
7147 // case without creating the negative cache entries, we generate a negative response and let the layer above us
7148 // do the appropriate thing. This negative response is also needed for appending new search domains.
7149 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
7150 {
7151 if (!rr)
7152 {
7153 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
7154 m->CurrentQuestion = qptr;
7155 GenerateNegativeResponse(m);
7156 m->CurrentQuestion = mDNSNULL;
7157 }
7158 else LogInfo("mDNSCoreReceiveNoUnicastAnswers: Skipping check to see if we need to generate a negative cache entry for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
7159 }
7160 else
7161 {
7162 if (!rr)
7163 {
7164 // We start off assuming a negative caching TTL of 60 seconds
7165 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
7166 mDNSu32 negttl = 60;
7167 int repeat = 0;
7168 const domainname *name = &q.qname;
7169 mDNSu32 hash = q.qnamehash;
7170
7171 // Special case for our special Microsoft Active Directory "local SOA" check.
7172 // Some cheap home gateways don't include an SOA record in the authority section when
7173 // they send negative responses, so we don't know how long to cache the negative result.
7174 // Because we don't want to keep hitting the root name servers with our query to find
7175 // if we're on a network using Microsoft Active Directory using "local" as a private
7176 // internal top-level domain, we make sure to cache the negative result for at least one day.
7177 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
7178
7179 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
7180 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
7181 {
7182 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7183 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
7184 {
7185 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
7186 mDNSu32 ttl_s = soa->min;
7187 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
7188 // for the SOA record for ".", where the record is reported as non-cacheable
7189 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
7190 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
7191 ttl_s = m->rec.r.resrec.rroriginalttl;
7192 if (negttl < ttl_s) negttl = ttl_s;
7193
7194 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
7195 // with an Authority Section SOA record for d.com, then this is a hint that the authority
7196 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
7197 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
7198 if (q.qtype == kDNSType_SOA)
7199 {
7200 int qcount = CountLabels(&q.qname);
7201 int scount = CountLabels(m->rec.r.resrec.name);
7202 if (qcount - 1 > scount)
7203 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
7204 repeat = qcount - 1 - scount;
7205 }
7206 }
7207 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7208 }
7209
7210 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
7211 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
7212 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
7213 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
7214 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
7215 // so that we back off our polling rate and don't keep hitting the server continually.
7216 if (neg)
7217 {
7218 if (negttl < neg->resrec.rroriginalttl * 2)
7219 negttl = neg->resrec.rroriginalttl * 2;
7220 if (negttl > 3600)
7221 negttl = 3600;
7222 }
7223
7224 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
7225
7226 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
7227 if (neg)
7228 {
7229 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
7230 RefreshCacheRecord(m, neg, negttl);
7231 // When we created the cache for the first time and answered the question, the question's
7232 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
7233 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
7234 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
7235 // we should reset its question interval here to MaxQuestionInterval.
7236 ResetQuestionState(m, qptr);
7237 // Update the NSEC records again.
7238 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
7239 if (NSECRecords)
7240 {
7241 if (!AddNSECSForCacheRecord(m, NSECRecords, neg, rcode))
7242 {
7243 LogMsg("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s during refresh", CRDisplayString(m, neg));
7244 FreeNSECRecords(m, NSECRecords);
7245 }
7246 NSECRecords = mDNSNULL;
7247 }
7248 }
7249 else while (1)
7250 {
7251 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
7252 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
7253 if (NSECRecords && DNSSECQuestion(qptr))
7254 {
7255 CacheRecord *negcr;
7256 // Create the cache entry with delay and then add the NSEC records
7257 // to it and add it immediately.
7258 negcr = CreateNewCacheEntry(m, slot, cg, 1, mDNStrue, mDNSNULL);
7259 if (!AddNSECSForCacheRecord(m, NSECRecords, negcr, rcode))
7260 {
7261 LogMsg("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s", CRDisplayString(m, negcr));
7262 FreeNSECRecords(m, NSECRecords);
7263 }
7264 else LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord added neg NSEC for %s", CRDisplayString(m, negcr));
7265 NSECRecords = mDNSNULL;
7266 negcr->DelayDelivery = 0;
7267 CacheRecordDeferredAdd(m, negcr);
7268 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7269 break;
7270 }
7271 else
7272 {
7273 CreateNewCacheEntry(m, slot, cg, 0, mDNStrue, mDNSNULL); // We never need any delivery delay for these generated negative cache records
7274 }
7275 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7276 if (!repeat) break;
7277 repeat--;
7278 name = (const domainname *)(name->c + 1 + name->c[0]);
7279 hash = DomainNameHashValue(name);
7280 slot = HashSlot(name);
7281 cg = CacheGroupForName(m, slot, hash, name);
7282 }
7283 }
7284 }
7285 }
7286 }
7287 if (NSECRecords) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used"); FreeNSECRecords(m, NSECRecords); }
7288 }
7289
7290 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
7291 {
7292 AuthRecord *rrPtr = mDNSNULL;
7293 LogSPS("Stored Proxy records :");
7294 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
7295 {
7296 LogSPS("%s", ARDisplayString(m, rrPtr));
7297 }
7298 }
7299
7300 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
7301 {
7302 AuthRecord *rrPtr = mDNSNULL;
7303
7304 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
7305 {
7306 if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
7307 {
7308 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
7309 return mDNStrue;
7310 }
7311 }
7312 mDNSCorePrintStoredProxyRecords(m);
7313 return mDNSfalse;
7314 }
7315
7316 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
7317 // the record list and/or question list.
7318 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7319 // InterfaceID non-NULL tells us the interface this multicast response was received on
7320 // InterfaceID NULL tells us this was a unicast response
7321 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
7322 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
7323 const DNSMessage *const response, const mDNSu8 *end,
7324 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
7325 const mDNSInterfaceID InterfaceID)
7326 {
7327 int i;
7328 mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
7329 mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7330 DNSQuestion *llqMatch = mDNSNULL;
7331 DNSQuestion *unicastQuestion = mDNSNULL;
7332 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
7333
7334 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
7335 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
7336 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
7337 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
7338 CacheRecord **cfp = &CacheFlushRecords;
7339 CacheRecord *NSECRecords = mDNSNULL;
7340 CacheRecord *NSECCachePtr = mDNSNULL;
7341 CacheRecord **nsecp = &NSECRecords;
7342 mDNSBool nseclist;
7343 mDNSu8 rcode = '\0';
7344
7345 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
7346 // to guard against spoof responses, then the only credible protection against that is cryptographic
7347 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
7348 int firstauthority = response->h.numAnswers;
7349 int firstadditional = firstauthority + response->h.numAuthorities;
7350 int totalrecords = firstadditional + response->h.numAdditionals;
7351 const mDNSu8 *ptr = response->data;
7352 DNSServer *uDNSServer = mDNSNULL;
7353
7354 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
7355 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
7356 srcaddr, dstaddr, InterfaceID,
7357 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
7358 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
7359 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
7360 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
7361
7362 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
7363 // When a DNS client receives a reply with TC
7364 // set, it should ignore that response, and query again, using a
7365 // mechanism, such as a TCP connection, that will permit larger replies.
7366 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
7367 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
7368 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
7369 // <rdar://problem/6690034> Can't bind to Active Directory
7370 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
7371 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
7372 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
7373 // and not even do the TCP query.
7374 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
7375 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC)) return;
7376
7377 if (LLQType == uDNS_LLQ_Ignore) return;
7378
7379 // 1. We ignore questions (if any) in mDNS response packets
7380 // 2. If this is an LLQ response, we handle it much the same
7381 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
7382 // answer as being the authoritative complete RRSet, and respond by deleting all other
7383 // matching cache records that don't appear in this packet.
7384 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
7385 if (ResponseMCast || LLQType == uDNS_LLQ_Events || (response->h.flags.b[0] & kDNSFlag0_TC))
7386 ptr = LocateAnswers(response, end);
7387 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
7388 // in this response packet are immediately deemed to be invalid.
7389 else
7390 {
7391 mDNSBool failure, returnEarly;
7392 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
7393 failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
7394 returnEarly = mDNSfalse;
7395 // We could possibly combine this with the similar loop at the end of this function --
7396 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
7397 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
7398 // which it was received (or refreshed), and then at the end if we find any cache records which
7399 // answer questions in this packet's question section, but which aren't tagged with this packet's
7400 // packet number, then we deduce they are old and delete them
7401 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
7402 {
7403 DNSQuestion q, *qptr = mDNSNULL;
7404 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
7405 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
7406 {
7407 if (!failure)
7408 {
7409 CacheRecord *rr;
7410 // Remember the unicast question that we found, which we use to make caching
7411 // decisions later on in this function
7412 const mDNSu32 slot = HashSlot(&q.qname);
7413 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
7414 if (!mDNSOpaque16IsZero(response->h.id)) unicastQuestion = qptr;
7415 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7416 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
7417 {
7418 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
7419 rr->resrec.InterfaceID, CRDisplayString(m, rr));
7420 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
7421 rr->TimeRcvd = m->timenow - TicksTTL(rr) - 1;
7422 rr->UnansweredQueries = MaxUnansweredQueries;
7423 }
7424 }
7425 else
7426 {
7427 if (qptr)
7428 {
7429 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
7430 PenalizeDNSServer(m, qptr);
7431 }
7432 returnEarly = mDNStrue;
7433 }
7434 }
7435 }
7436 if (returnEarly)
7437 {
7438 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
7439 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
7440 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
7441 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
7442 // not goto exit because we won't have any CacheFlushRecords and we do not want to
7443 // generate negative cache entries (we want to query the next server)
7444 return;
7445 }
7446 }
7447
7448 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
7449 {
7450 // All responses sent via LL multicast are acceptable for caching
7451 // All responses received over our outbound TCP connections are acceptable for caching
7452 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType;
7453 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
7454 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
7455
7456 const mDNSu8 RecordType =
7457 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
7458 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
7459 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
7460 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
7461 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) { m->rec.r.resrec.RecordType = 0; continue; }
7462
7463 // Don't want to cache OPT or TSIG pseudo-RRs
7464 if (m->rec.r.resrec.rrtype == kDNSType_TSIG) { m->rec.r.resrec.RecordType = 0; continue; }
7465 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
7466 {
7467 const rdataOPT *opt;
7468 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7469 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7470 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7471 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7472 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7473 {
7474 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7475 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7476 }
7477 m->rec.r.resrec.RecordType = 0;
7478 continue;
7479 }
7480
7481 // if a CNAME record points to itself, then don't add it to the cache
7482 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
7483 {
7484 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
7485 m->rec.r.resrec.RecordType = 0;
7486 continue;
7487 }
7488
7489 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
7490 // In the case of active LLQs, we'll get remove events when the records actually do go away
7491 // In the case of polling LLQs, we assume the record remains valid until the next poll
7492 if (!mDNSOpaque16IsZero(response->h.id))
7493 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
7494
7495 // If response was not sent via LL multicast,
7496 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
7497 if (!ResponseMCast)
7498 {
7499 if (LLQType)
7500 {
7501 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
7502 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
7503 // queries to get ADD/RMV events. To lookup the question, we can't use
7504 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
7505 // has already matched the question using the 64 bit Id in the packet and we use that here.
7506
7507 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
7508 }
7509 else if (!AcceptableResponse || !dstaddr)
7510 {
7511 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
7512 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
7513 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
7514 // we create.
7515
7516 DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
7517
7518 // Intialize the DNS server on the resource record which will now filter what questions we answer with
7519 // this record.
7520 //
7521 // We could potentially lookup the DNS server based on the source address, but that may not work always
7522 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
7523 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
7524 // on the "id" and "source port", then this response answers the question and assume the response
7525 // came from the same DNS server that we sent the query to.
7526
7527 if (q != mDNSNULL)
7528 {
7529 AcceptableResponse = mDNStrue;
7530 if (!InterfaceID)
7531 {
7532 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
7533 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
7534 }
7535 }
7536 else
7537 {
7538 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
7539 // the question. The code below does that. So, make this record unacceptable for now
7540 if (!InterfaceID)
7541 {
7542 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
7543 AcceptableResponse = mDNSfalse;
7544 }
7545 }
7546 }
7547 }
7548
7549 // 1. Check that this packet resource record does not conflict with any of ours
7550 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
7551 {
7552 if (m->CurrentRecord)
7553 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7554 m->CurrentRecord = m->ResourceRecords;
7555 while (m->CurrentRecord)
7556 {
7557 AuthRecord *rr = m->CurrentRecord;
7558 m->CurrentRecord = rr->next;
7559 // We accept all multicast responses, and unicast responses resulting from queries we issued
7560 // For other unicast responses, this code accepts them only for responses with an
7561 // (apparently) local source address that pertain to a record of our own that's in probing state
7562 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
7563
7564 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
7565 {
7566 // ... check to see if type and rdata are identical
7567 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
7568 {
7569 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
7570 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
7571 {
7572 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
7573 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
7574 }
7575 else
7576 {
7577 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
7578 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
7579 }
7580 }
7581 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
7582 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
7583 {
7584 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7585 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
7586
7587 // If this record is marked DependentOn another record for conflict detection purposes,
7588 // then *that* record has to be bumped back to probing state to resolve the conflict
7589 if (rr->DependentOn)
7590 {
7591 while (rr->DependentOn) rr = rr->DependentOn;
7592 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
7593 }
7594
7595 // If we've just whacked this record's ProbeCount, don't need to do it again
7596 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
7597 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
7598 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
7599 LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
7600 else
7601 {
7602 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
7603 // If we'd previously verified this record, put it back to probing state and try again
7604 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
7605 {
7606 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
7607 rr->resrec.RecordType = kDNSRecordTypeUnique;
7608 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
7609 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
7610 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
7611 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
7612 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
7613 rr->AnnounceCount = InitialAnnounceCount;
7614 InitializeLastAPTime(m, rr);
7615 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
7616 }
7617 // If we're probing for this record, we just failed
7618 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7619 {
7620 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
7621 if (!mDNSCoreRegisteredProxyRecord(m, rr))
7622 {
7623 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
7624 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
7625 }
7626 }
7627 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
7628 // same machine giving different answers for the reverse mapping record, or there are two machines on the
7629 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
7630 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
7631 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
7632 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
7633 {
7634 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
7635 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
7636 }
7637 else
7638 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
7639 }
7640 }
7641 // Else, matching signature, different type or rdata, but not a considered a conflict.
7642 // If the packet record has the cache-flush bit set, then we check to see if we
7643 // have any record(s) of the same type that we should re-assert to rescue them
7644 // (see note about "multi-homing and bridged networks" at the end of this function).
7645 else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
7646 if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
7647 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
7648 }
7649 }
7650 }
7651
7652 nseclist = mDNSfalse;
7653 if (!AcceptableResponse)
7654 {
7655 AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords, unicastQuestion, &nseclist);
7656 if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
7657 }
7658
7659 // 2. See if we want to add this packet resource record to our cache
7660 // We only try to cache answers if we have a cache to put them in
7661 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
7662 if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
7663 if (m->rrcache_size && AcceptableResponse)
7664 {
7665 const mDNSu32 slot = HashSlot(m->rec.r.resrec.name);
7666 CacheGroup *cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
7667 CacheRecord *rr;
7668
7669 // 2a. Check if this packet resource record is already in our cache
7670 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7671 {
7672 mDNSBool match;
7673 // Resource record received via unicast, the resGroupID should match ?
7674 if (!InterfaceID)
7675 {
7676 mDNSu16 id1 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7677 mDNSu16 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
7678 match = (id1 == id2);
7679 }
7680 else
7681 match = (rr->resrec.InterfaceID == InterfaceID);
7682 // If we found this exact resource record, refresh its TTL
7683 if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
7684 {
7685 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
7686 verbosedebugf("Found record size %5d interface %p already in cache: %s",
7687 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
7688
7689 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
7690 {
7691 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
7692 if (rr->NextInCFList == mDNSNULL && cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
7693 { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
7694
7695 // If this packet record is marked unique, and our previous cached copy was not, then fix it
7696 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
7697 {
7698 DNSQuestion *q;
7699 for (q = m->Questions; q; q=q->next) if (ResourceRecordAnswersQuestion(&rr->resrec, q)) q->UniqueAnswers++;
7700 rr->resrec.RecordType = m->rec.r.resrec.RecordType;
7701 }
7702 }
7703
7704 if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
7705 {
7706 // If the rdata of the packet record differs in name capitalization from the record in our cache
7707 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
7708 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
7709 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
7710 rr->resrec.rroriginalttl = 0;
7711 rr->TimeRcvd = m->timenow;
7712 rr->UnansweredQueries = MaxUnansweredQueries;
7713 SetNextCacheCheckTimeForRecord(m, rr);
7714 LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m,rr));
7715 LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m,&m->rec.r));
7716 LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
7717 NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
7718 // DO NOT break out here -- we want to continue as if we never found it
7719 }
7720 else if (m->rec.r.resrec.rroriginalttl > 0)
7721 {
7722 DNSQuestion *q;
7723 //if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
7724 RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
7725
7726 // If we may have NSEC records returned with the answer (which we don't know yet as it
7727 // has not been processed), we need to cache them along with the first cache
7728 // record in the list that answers the question so that it can be used for validation
7729 // later.
7730 if (response->h.numAnswers && unicastQuestion && !NSECCachePtr)
7731 {
7732 LogInfo("mDNSCoreReceiveResponse: rescuing RR %s", CRDisplayString(m, rr));
7733 NSECCachePtr = rr;
7734 }
7735 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
7736 // polling the network once we get a valid response back. For the first time when a new
7737 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
7738 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
7739 // configuration changed, without flushing the cache, we reset the question interval here.
7740 // Currently, we do this for for both multicast and unicast questions as long as the record
7741 // type is unique. For unicast, resource record is always unique and for multicast it is
7742 // true for records like A etc. but not for PTR.
7743 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
7744 {
7745 for (q = m->Questions; q; q=q->next)
7746 {
7747 if (!q->DuplicateOf && !q->LongLived &&
7748 ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
7749 {
7750 ResetQuestionState(m, q);
7751 debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
7752 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
7753 }
7754 }
7755 }
7756 break;
7757 }
7758 else
7759 {
7760 // If the packet TTL is zero, that means we're deleting this record.
7761 // To give other hosts on the network a chance to protest, we push the deletion
7762 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
7763 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
7764 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
7765 // If record's current expiry time is more than a second from now, we set it to expire in one second.
7766 // If the record is already going to expire in less than one second anyway, we leave it alone --
7767 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
7768 debugf("DE for %s", CRDisplayString(m, rr));
7769 if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
7770 {
7771 rr->resrec.rroriginalttl = 1;
7772 rr->TimeRcvd = m->timenow;
7773 rr->UnansweredQueries = MaxUnansweredQueries;
7774 SetNextCacheCheckTimeForRecord(m, rr);
7775 }
7776 break;
7777 }
7778 }
7779 }
7780
7781 // If packet resource record not in our cache, add it now
7782 // (unless it is just a deletion of a record we never had, in which case we don't care)
7783 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
7784 {
7785 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
7786 const mDNSs32 delay = AddToCFList ? NonZeroTime(m->timenow + mDNSPlatformOneSecond) :
7787 CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash, slot);
7788 // If unique, assume we may have to delay delivery of this 'add' event.
7789 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
7790 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
7791 // to schedule an mDNS_Execute task at the appropriate time.
7792 rr = CreateNewCacheEntry(m, slot, cg, delay, !nseclist, srcaddr);
7793 if (rr)
7794 {
7795 // NSEC Records and its signatures are cached with the negative cache entry
7796 // which we should be creating below. It is also needed in the wildcard
7797 // expanded answer case and in that case it is cached along with the answer.
7798 if (nseclist) { *nsecp = rr; nsecp = &rr->next; }
7799 else if (AddToCFList) { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
7800 else if (rr->DelayDelivery) ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
7801 }
7802 }
7803 }
7804 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7805 }
7806
7807 exit:
7808 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7809
7810 // If we've just received one or more records with their cache flush bits set,
7811 // then scan that cache slot to see if there are any old stale records we need to flush
7812 while (CacheFlushRecords != (CacheRecord*)1)
7813 {
7814 CacheRecord *r1 = CacheFlushRecords, *r2;
7815 const mDNSu32 slot = HashSlot(r1->resrec.name);
7816 const CacheGroup *cg = CacheGroupForRecord(m, slot, &r1->resrec);
7817 CacheFlushRecords = CacheFlushRecords->NextInCFList;
7818 r1->NextInCFList = mDNSNULL;
7819
7820 // Look for records in the cache with the same signature as this new one with the cache flush
7821 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
7822 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
7823 // We make these TTL adjustments *only* for records that still have *more* than one second
7824 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
7825 // (and now has half a second remaining) could inadvertently get its life extended, by either
7826 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
7827 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
7828 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
7829 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
7830 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
7831 // To avoid this, we need to ensure that the cache flushing operation will only act to
7832 // *decrease* a record's remaining lifetime, never *increase* it.
7833 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
7834 {
7835 mDNSu16 id1;
7836 mDNSu16 id2;
7837 if (!r1->resrec.InterfaceID)
7838 {
7839 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
7840 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
7841 }
7842 else
7843 {
7844 id1 = id2 = 0;
7845 }
7846 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
7847 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
7848 // the new RRSIG that we received. Process only if the typeCovered matches.
7849 if ((r1->resrec.rrtype == r2->resrec.rrtype) && (r1->resrec.rrtype == kDNSType_RRSIG))
7850 {
7851 rdataRRSig *rrsig1 = (rdataRRSig *)(((RDataBody2 *)(r1->resrec.rdata->u.data))->data);
7852 rdataRRSig *rrsig2 = (rdataRRSig *)(((RDataBody2 *)(r2->resrec.rdata->u.data))->data);
7853 if (swap16(rrsig1->typeCovered) != swap16(rrsig2->typeCovered))
7854 {
7855 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
7856 DNSTypeName(swap16(rrsig1->typeCovered)), DNSTypeName(swap16(rrsig2->typeCovered)));
7857 continue;
7858 }
7859 }
7860
7861 // For Unicast (null InterfaceID) the resolver IDs should also match
7862 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
7863 (r1->resrec.InterfaceID || (id1 == id2)) &&
7864 r1->resrec.rrtype == r2->resrec.rrtype &&
7865 r1->resrec.rrclass == r2->resrec.rrclass)
7866 {
7867 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
7868 // else, if record is old, mark it to be flushed
7869 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
7870 {
7871 // If we find mismatched TTLs in an RRSet, correct them.
7872 // We only do this for records with a TTL of 2 or higher. It's possible to have a
7873 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
7874 // which we treat as a goodbye followed by an addition) and in that case it would be
7875 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
7876 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
7877 // because certain early Bonjour devices are known to have this specific mismatch, and
7878 // there's no point filling syslog with messages about something we already know about.
7879 // We also don't log this for uDNS responses, since a caching name server is obliged
7880 // to give us an aged TTL to correct for how long it has held the record,
7881 // so our received TTLs are expected to vary in that case
7882 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
7883 {
7884 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
7885 mDNSOpaque16IsZero(response->h.id))
7886 LogInfo("Correcting TTL from %4d to %4d for %s",
7887 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
7888 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
7889 }
7890 r2->TimeRcvd = m->timenow;
7891 }
7892 else // else, if record is old, mark it to be flushed
7893 {
7894 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
7895 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
7896 // We set stale records to expire in one second.
7897 // This gives the owner a chance to rescue it if necessary.
7898 // This is important in the case of multi-homing and bridged networks:
7899 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
7900 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
7901 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
7902 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
7903 // By delaying the deletion by one second, we give X a change to notice that this bridging has
7904 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
7905
7906 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
7907 // final expiration queries for this record.
7908
7909 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
7910 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
7911 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
7912 // <rdar://problem/5636422> Updating TXT records is too slow
7913 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
7914 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
7915 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
7916 {
7917 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
7918 r2->resrec.rroriginalttl = 0;
7919 }
7920 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
7921 {
7922 // We only set a record to expire in one second if it currently has *more* than a second to live
7923 // If it's already due to expire in a second or less, we just leave it alone
7924 r2->resrec.rroriginalttl = 1;
7925 r2->UnansweredQueries = MaxUnansweredQueries;
7926 r2->TimeRcvd = m->timenow - 1;
7927 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
7928 // that we marked for deletion via an explicit DE record
7929 }
7930 }
7931 SetNextCacheCheckTimeForRecord(m, r2);
7932 }
7933 }
7934
7935 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
7936 {
7937 // If we had a unicast question for this response with at least one positive answer and we
7938 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
7939 // signatures along with the cache record which will be used for validation later. If
7940 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
7941 // use that instead.
7942 if (response->h.numAnswers && unicastQuestion && NSECRecords)
7943 {
7944 if (!NSECCachePtr)
7945 {
7946 LogInfo("mDNSCoreReceiveResponse: Updating NSECCachePtr to %s", CRDisplayString(m, r1));
7947 NSECCachePtr = r1;
7948 }
7949 // Note: We need to do this before we call CacheRecordDeferredAdd as this
7950 // might start the verification process which needs these NSEC records
7951 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
7952 {
7953 LogMsg("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
7954 FreeNSECRecords(m, NSECRecords);
7955 }
7956 NSECRecords = mDNSNULL;
7957 NSECCachePtr = mDNSNULL;
7958 }
7959 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash, slot);
7960 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
7961 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
7962 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
7963 }
7964 }
7965
7966 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
7967 // update them now for future validations.
7968 if (NSECRecords && NSECCachePtr)
7969 {
7970 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m, NSECCachePtr));
7971 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
7972 {
7973 LogMsg("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
7974 FreeNSECRecords(m, NSECRecords);
7975 }
7976 NSECRecords = mDNSNULL;
7977 NSECCachePtr = mDNSNULL;
7978 }
7979
7980 // See if we need to generate negative cache entries for unanswered unicast questions
7981 mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, LLQType, rcode, NSECRecords);
7982 }
7983
7984 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
7985 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
7986 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
7987 // that warrants waking the sleeping host.
7988 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
7989
7990 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
7991 {
7992 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
7993 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
7994 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
7995 // simple, we use the same mechanism for both lists.
7996 if (!e->l[0])
7997 {
7998 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
7999 return;
8000 }
8001 m->CurrentRecord = thelist;
8002 while (m->CurrentRecord)
8003 {
8004 AuthRecord *const rr = m->CurrentRecord;
8005 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
8006 {
8007 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
8008 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
8009 }
8010 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
8011 m->CurrentRecord = rr->next;
8012 }
8013 }
8014
8015 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
8016 {
8017 if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
8018 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
8019 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
8020 }
8021
8022 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
8023 {
8024 if (result && result != mStatus_MemFree)
8025 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
8026
8027 if (result == mStatus_NameConflict)
8028 {
8029 mDNS_Lock(m);
8030 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
8031 if (ar->WakeUp.HMAC.l[0])
8032 {
8033 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password); // Send one wakeup magic packet
8034 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken
8035 }
8036 mDNS_Unlock(m);
8037 }
8038
8039 if (result == mStatus_NameConflict || result == mStatus_MemFree)
8040 {
8041 m->ProxyRecords--;
8042 mDNSPlatformMemFree(ar);
8043 mDNS_UpdateAllowSleep(m);
8044 }
8045 }
8046
8047 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
8048 {
8049 int hval;
8050 int value;
8051 int numBytes;
8052 int digitsProcessed;
8053 int zeroFillStart;
8054 int numColons;
8055 mDNSu8 v6addr[16];
8056
8057 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
8058 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
8059 //
8060 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
8061 // the result in "v6"
8062
8063 numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
8064 while (ptr < limit && *ptr != ' ')
8065 {
8066 hval = HexVal(*ptr);
8067 if (hval != -1)
8068 {
8069 value <<= 4;
8070 value |= hval;
8071 digitsProcessed = 1;
8072 }
8073 else if (*ptr == ':')
8074 {
8075 if (!digitsProcessed)
8076 {
8077 // If we have already seen a "::", we should not see one more. Handle the special
8078 // case of "::"
8079 if (numColons)
8080 {
8081 // if we never filled any bytes and the next character is space (we have reached the end)
8082 // we are done
8083 if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
8084 {
8085 mDNSPlatformMemZero(v6->b, 16);
8086 return ptr + 1;
8087 }
8088 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
8089 return mDNSNULL;
8090 }
8091
8092 // We processed "::". We need to fill zeroes later. For now, mark the
8093 // point where we will start filling zeroes from.
8094 zeroFillStart = numBytes;
8095 numColons++;
8096 }
8097 else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
8098 {
8099 // We have a trailing ":" i.e., no more characters after ":"
8100 LogMsg("GetValueForIPv6Addr: Trailing colon");
8101 return mDNSNULL;
8102 }
8103 else
8104 {
8105 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
8106 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
8107 // filled here is 12 and 13.
8108 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
8109
8110 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
8111 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
8112 digitsProcessed = value = 0;
8113
8114 // Make sure that we did not fill the 13th and 14th byte above
8115 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
8116 }
8117 }
8118 ptr++;
8119 }
8120
8121 // We should be processing the last set of bytes following the last ":" here
8122 if (!digitsProcessed)
8123 {
8124 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
8125 return mDNSNULL;
8126 }
8127
8128 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
8129 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
8130 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
8131
8132 if (zeroFillStart)
8133 {
8134 int i, j, n;
8135 for (i = 0; i < zeroFillStart; i++)
8136 v6->b[i] = v6addr[i];
8137 for (j = i, n = 0; n < 16 - numBytes; j++, n++)
8138 v6->b[j] = 0;
8139 for (; j < 16; i++, j++)
8140 v6->b[j] = v6addr[i];
8141 }
8142 else if (numBytes == 16)
8143 mDNSPlatformMemCopy(v6->b, v6addr, 16);
8144 else
8145 {
8146 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
8147 return mDNSNULL;
8148 }
8149 return ptr;
8150 }
8151
8152 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
8153 {
8154 int i;
8155 mDNSu32 val;
8156 int dots = 0;
8157
8158 val = 0;
8159 for (i = 0; ptr < limit && *ptr != ' '; ptr++)
8160 {
8161 if (*ptr >= '0' && *ptr <= '9')
8162 val = val * 10 + *ptr - '0';
8163 else if (*ptr == '.')
8164 {
8165 v4->b[dots++] = val;
8166 val = 0;
8167 }
8168 else
8169 {
8170 // We have a zero at the end and if we reached that, then we are done.
8171 if (*ptr == 0 && ptr == limit - 1 && dots == 3)
8172 {
8173 v4->b[dots] = val;
8174 return ptr + 1;
8175 }
8176 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
8177 }
8178 }
8179 if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
8180 v4->b[dots] = val;
8181 return ptr;
8182 }
8183
8184 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
8185 {
8186 int i;
8187 mDNSu32 val;
8188
8189 val = 0;
8190 for (i = 0; ptr < limit && *ptr != ' '; ptr++)
8191 {
8192 if (*ptr < '0' || *ptr > '9')
8193 {
8194 // We have a zero at the end and if we reached that, then we are done.
8195 if (*ptr == 0 && ptr == limit - 1)
8196 {
8197 *value = val;
8198 return ptr + 1;
8199 }
8200 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
8201 }
8202 val = val * 10 + *ptr - '0';
8203 }
8204 *value = val;
8205 return ptr;
8206 }
8207
8208 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSu32 *seq,
8209 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
8210 {
8211 if (ar->resrec.rrtype != kDNSType_NULL)
8212 return;
8213
8214 if (mDNS_KeepaliveRecord(&ar->resrec))
8215 {
8216 int len = ar->resrec.rdlength;
8217 mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
8218 mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
8219 mDNSu32 value;
8220
8221 while (ptr < limit)
8222 {
8223 mDNSu8 param = *ptr;
8224 mDNSu8 *p;
8225
8226 ptr += 2; // Skip the letter and the "="
8227 if (param == 'h')
8228 {
8229 laddr->type = mDNSAddrType_IPv4;
8230 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
8231 }
8232 else if (param == 'd')
8233 {
8234 raddr->type = mDNSAddrType_IPv4;
8235 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
8236 }
8237 if (param == 'H')
8238 {
8239 laddr->type = mDNSAddrType_IPv6;
8240 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
8241 }
8242 else if (param == 'D')
8243 {
8244 raddr->type = mDNSAddrType_IPv6;
8245 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
8246 }
8247 else
8248 {
8249 ptr = GetValueForKeepalive(ptr, limit, &value);
8250 }
8251 if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
8252
8253 p = (mDNSu8 *)&value;
8254 // Extract everything in network order so that it is easy for sending a keepalive and also
8255 // for matching incoming TCP packets
8256 switch (param)
8257 {
8258 case 't':
8259 *timeout = value;
8260 //if (*timeout < 120) *timeout = 120;
8261 break;
8262 case 'h':
8263 case 'H':
8264 case 'd':
8265 case 'D':
8266 break;
8267 case 'l':
8268 lport->NotAnInteger = p[0] << 8 | p[1];
8269 break;
8270 case 'r':
8271 rport->NotAnInteger = p[0] << 8 | p[1];
8272 break;
8273 case 's':
8274 value = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
8275 *seq = value;
8276 break;
8277 case 'a':
8278 value = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
8279 *ack = value;
8280 break;
8281 case 'w':
8282 *win = p[0] << 8 | p[1];
8283 break;
8284 default:
8285 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value\n");
8286 ptr = limit;
8287 break;
8288 }
8289 ptr++; // skip the space
8290 }
8291 }
8292 }
8293
8294 // 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
8295 // the clients need not retrieve this information from the auth record again.
8296 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr const* pladdr, const mDNSAddr const* praddr, const mDNSIPPort plport,
8297 const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
8298 {
8299 AuthRecord *ar;
8300 mDNSAddr laddr, raddr;
8301 mDNSIPPort lport, rport;
8302 mDNSu32 timeout, seq, ack;
8303 mDNSu16 win;
8304
8305 for (ar = m->ResourceRecords; ar; ar=ar->next)
8306 {
8307 timeout = seq = ack = 0;
8308 win = 0;
8309 laddr = raddr = zeroAddr;
8310 lport = rport = zeroIPPort;
8311
8312 if (!ar->WakeUp.HMAC.l[0]) continue;
8313
8314 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &seq, &ack, &lport, &rport, &win);
8315
8316 // Did we parse correctly ?
8317 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
8318 {
8319 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
8320 continue;
8321 }
8322
8323 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
8324 &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
8325
8326 // Does it match the incoming TCP packet ?
8327 if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
8328 {
8329 // returning in network order
8330 *rseq = seq;
8331 *rack = ack;
8332 return ar;
8333 }
8334 }
8335 return mDNSNULL;
8336 }
8337
8338 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
8339 {
8340 AuthRecord *ar;
8341
8342 for (ar = m->ResourceRecords; ar; ar=ar->next)
8343 {
8344 mDNSu32 timeout, seq, ack;
8345 mDNSu16 win;
8346 mDNSAddr laddr, raddr;
8347 mDNSIPPort lport, rport;
8348
8349 timeout = seq = ack = 0;
8350 win = 0;
8351
8352 laddr = raddr = zeroAddr;
8353 lport = rport = zeroIPPort;
8354
8355 if (!ar->WakeUp.HMAC.l[0]) continue;
8356
8357 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &seq, &ack, &lport, &rport, &win);
8358
8359 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
8360 {
8361 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
8362 continue;
8363 }
8364 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
8365
8366 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
8367 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
8368 if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
8369 {
8370 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
8371 ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
8372 }
8373 if (m->NextScheduledKA - ar->KATimeExpire > 0)
8374 m->NextScheduledKA = ar->KATimeExpire;
8375 }
8376 }
8377
8378 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
8379 const DNSMessage *const msg, const mDNSu8 *end,
8380 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8381 const mDNSInterfaceID InterfaceID)
8382 {
8383 int i;
8384 AuthRecord opt;
8385 mDNSu8 *p = m->omsg.data;
8386 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
8387 mDNSu32 updatelease = 0;
8388 const mDNSu8 *ptr;
8389
8390 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8391 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8392 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8393 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
8394 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
8395 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
8396 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
8397
8398 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
8399
8400 if (mDNS_PacketLoggingEnabled)
8401 DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
8402
8403 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
8404 if (ptr)
8405 {
8406 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
8407 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
8408 {
8409 const rdataOPT *o;
8410 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
8411 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
8412 {
8413 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
8414 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
8415 }
8416 }
8417 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8418 }
8419
8420 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
8421
8422 if (!updatelease || !owner.HMAC.l[0])
8423 {
8424 static int msgs = 0;
8425 if (msgs < 100)
8426 {
8427 msgs++;
8428 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
8429 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
8430 }
8431 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
8432 }
8433 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
8434 {
8435 static int msgs = 0;
8436 if (msgs < 100)
8437 {
8438 msgs++;
8439 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
8440 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
8441 }
8442 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
8443 }
8444 else
8445 {
8446 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
8447
8448 if (updatelease > 24 * 60 * 60)
8449 updatelease = 24 * 60 * 60;
8450
8451 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
8452 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
8453
8454 ptr = LocateAuthorities(msg, end);
8455 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
8456 {
8457 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8458 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
8459 {
8460 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
8461 AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
8462 if (!ar) { m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; break; }
8463 else
8464 {
8465 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
8466 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
8467 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
8468 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
8469 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
8470 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
8471 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
8472 ar->resrec.rdata->MaxRDLength = RDLengthMem;
8473 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
8474 ar->ForceMCast = mDNStrue;
8475 ar->WakeUp = owner;
8476 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
8477 {
8478 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
8479 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
8480 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
8481 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
8482 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
8483 }
8484 ar->TimeRcvd = m->timenow;
8485 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
8486 if (m->NextScheduledSPS - ar->TimeExpire > 0)
8487 m->NextScheduledSPS = ar->TimeExpire;
8488 ar->KATimeExpire = 0;
8489 mDNS_Register_internal(m, ar);
8490 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
8491 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
8492 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
8493 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
8494 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
8495 if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
8496 if (ar->resrec.rrtype == kDNSType_AAAA) ar->resrec.rroriginalttl = 0;
8497 m->ProxyRecords++;
8498 mDNS_UpdateAllowSleep(m);
8499 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
8500 }
8501 }
8502 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8503 }
8504
8505 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
8506 {
8507 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
8508 ClearProxyRecords(m, &owner, m->DuplicateRecords);
8509 ClearProxyRecords(m, &owner, m->ResourceRecords);
8510 }
8511 else
8512 {
8513 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
8514 opt.resrec.rrclass = NormalMaxDNSMessageData;
8515 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
8516 opt.resrec.rdestimate = sizeof(rdataOPT);
8517 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
8518 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
8519 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
8520 }
8521 }
8522
8523 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
8524 mDNS_SendKeepalives(m);
8525 }
8526
8527 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSInterfaceID InterfaceID)
8528 {
8529 if (InterfaceID)
8530 {
8531 mDNSu32 updatelease = 60 * 60; // If SPS fails to indicate lease time, assume one hour
8532 const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
8533 if (ptr)
8534 {
8535 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
8536 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
8537 {
8538 const rdataOPT *o;
8539 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
8540 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
8541 if (o->opt == kDNSOpt_Lease)
8542 {
8543 updatelease = o->u.updatelease;
8544 LogSPS("Sleep Proxy granted lease time %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
8545 }
8546 }
8547 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8548 }
8549
8550 if (m->CurrentRecord)
8551 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
8552 m->CurrentRecord = m->ResourceRecords;
8553 while (m->CurrentRecord)
8554 {
8555 AuthRecord *const rr = m->CurrentRecord;
8556 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
8557 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
8558 {
8559 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
8560 // Clear the updateid when we are done sending on all interfaces.
8561 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
8562 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
8563 bit_clr_opaque64(rr->updateIntID, scopeid);
8564 if (mDNSOpaque64IsZero(&rr->updateIntID))
8565 rr->updateid = zeroID;
8566 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
8567 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));
8568 if (rr->WakeUp.HMAC.l[0])
8569 {
8570 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
8571 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
8572 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
8573 }
8574 }
8575 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
8576 // new records could have been added to the end of the list as a result of that call.
8577 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
8578 m->CurrentRecord = rr->next;
8579 }
8580 }
8581 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
8582 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
8583 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
8584 }
8585
8586 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
8587 const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
8588 {
8589 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
8590 {
8591 LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
8592 #if ForceAlerts
8593 *(long*)0 = 0;
8594 #endif
8595 }
8596
8597 // Create empty resource record
8598 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
8599 cr->resrec.InterfaceID = InterfaceID;
8600 cr->resrec.rDNSServer = dnsserver;
8601 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
8602 cr->resrec.rrtype = rrtype;
8603 cr->resrec.rrclass = rrclass;
8604 cr->resrec.rroriginalttl = ttl_seconds;
8605 cr->resrec.rdlength = 0;
8606 cr->resrec.rdestimate = 0;
8607 cr->resrec.namehash = namehash;
8608 cr->resrec.rdatahash = 0;
8609 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
8610 cr->resrec.rdata->MaxRDLength = 0;
8611
8612 cr->NextInKAList = mDNSNULL;
8613 cr->TimeRcvd = m->timenow;
8614 cr->DelayDelivery = 0;
8615 cr->NextRequiredQuery = m->timenow;
8616 cr->LastUsed = m->timenow;
8617 cr->CRActiveQuestion = mDNSNULL;
8618 cr->UnansweredQueries = 0;
8619 cr->LastUnansweredTime = 0;
8620 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
8621 cr->MPUnansweredQ = 0;
8622 cr->MPLastUnansweredQT = 0;
8623 cr->MPUnansweredKA = 0;
8624 cr->MPExpectingKA = mDNSfalse;
8625 #endif
8626 cr->NextInCFList = mDNSNULL;
8627 cr->nsec = mDNSNULL;
8628 }
8629
8630 mDNSexport void mDNSCoreReceive(mDNS *const m, void *const pkt, const mDNSu8 *const end,
8631 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
8632 const mDNSInterfaceID InterfaceID)
8633 {
8634 mDNSInterfaceID ifid = InterfaceID;
8635 DNSMessage *msg = (DNSMessage *)pkt;
8636 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
8637 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
8638 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
8639 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
8640 mDNSu8 QR_OP;
8641 mDNSu8 *ptr = mDNSNULL;
8642 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
8643 if (TLS) dstaddr = mDNSNULL;
8644
8645 #ifndef UNICAST_DISABLED
8646 if (mDNSSameAddress(srcaddr, &m->Router))
8647 {
8648 #ifdef _LEGACY_NAT_TRAVERSAL_
8649 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
8650 {
8651 mDNS_Lock(m);
8652 LNT_ConfigureRouterInfo(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
8653 mDNS_Unlock(m);
8654 return;
8655 }
8656 #endif
8657 if (mDNSSameIPPort(srcport, NATPMPPort))
8658 {
8659 mDNS_Lock(m);
8660 uDNS_ReceiveNATPMPPacket(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
8661 mDNS_Unlock(m);
8662 return;
8663 }
8664 }
8665 #ifdef _LEGACY_NAT_TRAVERSAL_
8666 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
8667 #endif
8668
8669 #endif
8670 if ((unsigned)(end - (mDNSu8 *)pkt) < sizeof(DNSMessageHeader))
8671 {
8672 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt);
8673 return;
8674 }
8675 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
8676 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
8677 ptr = (mDNSu8 *)&msg->h.numQuestions;
8678 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
8679 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
8680 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
8681 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
8682
8683 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
8684
8685 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
8686 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
8687 if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
8688
8689 mDNS_Lock(m);
8690 m->PktNum++;
8691 #ifndef UNICAST_DISABLED
8692 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
8693 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
8694 {
8695 ifid = mDNSInterface_Any;
8696 if (mDNS_PacketLoggingEnabled)
8697 DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
8698 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
8699 // Note: mDNSCore also needs to get access to received unicast responses
8700 }
8701 #endif
8702 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
8703 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
8704 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
8705 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, InterfaceID);
8706 else
8707 {
8708 LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
8709 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt, InterfaceID);
8710 if (mDNS_LoggingEnabled)
8711 {
8712 int i = 0;
8713 while (i<end - (mDNSu8 *)pkt)
8714 {
8715 char buffer[128];
8716 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
8717 do if (i<end - (mDNSu8 *)pkt) p += mDNS_snprintf(p, sizeof(buffer), " %02X", ((mDNSu8 *)pkt)[i]);while (++i & 15);
8718 LogInfo("%s", buffer);
8719 }
8720 }
8721 }
8722 // Packet reception often causes a change to the task list:
8723 // 1. Inbound queries can cause us to need to send responses
8724 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
8725 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
8726 // 4. Response packets that answer questions may cause our client to issue new questions
8727 mDNS_Unlock(m);
8728 }
8729
8730 // ***************************************************************************
8731 #if COMPILER_LIKES_PRAGMA_MARK
8732 #pragma mark -
8733 #pragma mark - Searcher Functions
8734 #endif
8735
8736 // Targets are considered the same if both queries are untargeted, or
8737 // if both are targeted to the same address+port
8738 // (If Target address is zero, TargetPort is undefined)
8739 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
8740 (mDNSSameAddress(& (A)->Target, & (B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
8741
8742 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
8743 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
8744 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
8745 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
8746 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
8747 //
8748 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
8749 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
8750 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
8751 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
8752 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
8753 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
8754 // breaks this design principle.
8755
8756 // If IsLLQ(Q) is true, it means the question is both:
8757 // (a) long-lived and
8758 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
8759 // for multicast questions, we don't want to treat LongLived as anything special
8760 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
8761
8762 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
8763 {
8764 DNSQuestion *q;
8765 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
8766 // This prevents circular references, where two questions are each marked as a duplicate of the other.
8767 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
8768 // further in the list.
8769 for (q = m->Questions; q && q != question; q=q->next) // Scan our list for another question
8770 if (q->InterfaceID == question->InterfaceID && // with the same InterfaceID,
8771 SameQTarget(q, question) && // and same unicast/multicast target settings
8772 q->qtype == question->qtype && // type,
8773 q->qclass == question->qclass && // class,
8774 IsLLQ(q) == IsLLQ(question) && // and long-lived status matches
8775 (!q->AuthInfo || question->AuthInfo) && // to avoid deadlock, don't make public query dup of a private one
8776 (q->SuppressQuery == question->SuppressQuery) && // Questions that are suppressed/not suppressed
8777 (q->ValidationRequired == question->ValidationRequired) && // Questions that require DNSSEC validation
8778 (q->ValidatingResponse == question->ValidatingResponse) && // Questions that are validating responses using DNSSEC
8779 q->qnamehash == question->qnamehash &&
8780 SameDomainName(&q->qname, &question->qname)) // and name
8781 return(q);
8782 return(mDNSNULL);
8783 }
8784
8785 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
8786 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
8787 {
8788 DNSQuestion *q;
8789 DNSQuestion *first = mDNSNULL;
8790
8791 // This is referring to some other question as duplicate. No other question can refer to this
8792 // question as a duplicate.
8793 if (question->DuplicateOf)
8794 {
8795 LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
8796 question, question->qname.c, DNSTypeName(question->qtype),
8797 question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
8798 return;
8799 }
8800
8801 for (q = m->Questions; q; q=q->next) // Scan our list of questions
8802 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
8803 {
8804 q->DuplicateOf = first;
8805 if (!first)
8806 {
8807 first = q;
8808 // If q used to be a duplicate, but now is not,
8809 // then inherit the state from the question that's going away
8810 q->LastQTime = question->LastQTime;
8811 q->ThisQInterval = question->ThisQInterval;
8812 q->ExpectUnicastResp = question->ExpectUnicastResp;
8813 q->LastAnswerPktNum = question->LastAnswerPktNum;
8814 q->RecentAnswerPkts = question->RecentAnswerPkts;
8815 q->RequestUnicast = question->RequestUnicast;
8816 q->LastQTxTime = question->LastQTxTime;
8817 q->CNAMEReferrals = question->CNAMEReferrals;
8818 q->nta = question->nta;
8819 q->servAddr = question->servAddr;
8820 q->servPort = question->servPort;
8821 q->qDNSServer = question->qDNSServer;
8822 q->validDNSServers = question->validDNSServers;
8823 q->unansweredQueries = question->unansweredQueries;
8824 q->noServerResponse = question->noServerResponse;
8825 q->triedAllServersOnce = question->triedAllServersOnce;
8826
8827 q->TargetQID = question->TargetQID;
8828 q->LocalSocket = question->LocalSocket;
8829
8830 q->state = question->state;
8831 // q->tcp = question->tcp;
8832 q->ReqLease = question->ReqLease;
8833 q->expire = question->expire;
8834 q->ntries = question->ntries;
8835 q->id = question->id;
8836 q->ValidationState = question->ValidationState;
8837 q->ValidationStatus = question->ValidationStatus;
8838
8839 question->LocalSocket = mDNSNULL;
8840 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
8841 // question->tcp = mDNSNULL;
8842
8843 if (q->LocalSocket)
8844 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
8845
8846 if (q->nta)
8847 {
8848 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
8849 q->nta->ZoneDataContext = q;
8850 }
8851
8852 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
8853 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
8854
8855 if (question->state == LLQ_Established)
8856 {
8857 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
8858 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
8859 }
8860
8861 SetNextQueryTime(m,q);
8862 }
8863 }
8864 }
8865
8866 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
8867 {
8868 McastResolver **p = &m->McastResolvers;
8869 McastResolver *tmp = mDNSNULL;
8870
8871 if (!d) d = (const domainname *)"";
8872
8873 LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
8874
8875 if (m->mDNS_busy != m->mDNS_reentrancy+1)
8876 LogMsg("mDNS_AddMcastResolver: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
8877
8878 while (*p) // Check if we already have this {interface, domain} tuple registered
8879 {
8880 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
8881 {
8882 if (!((*p)->flags & DNSServer_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
8883 (*p)->flags &= ~DNSServer_FlagDelete;
8884 tmp = *p;
8885 *p = tmp->next;
8886 tmp->next = mDNSNULL;
8887 }
8888 else
8889 p=&(*p)->next;
8890 }
8891
8892 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
8893 else
8894 {
8895 // allocate, add to list
8896 *p = mDNSPlatformMemAllocate(sizeof(**p));
8897 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
8898 else
8899 {
8900 (*p)->interface = interface;
8901 (*p)->flags = DNSServer_FlagNew;
8902 (*p)->timeout = timeout;
8903 AssignDomainName(&(*p)->domain, d);
8904 (*p)->next = mDNSNULL;
8905 }
8906 }
8907 return(*p);
8908 }
8909
8910 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
8911 {
8912 mDNSs32 ptime = 0;
8913 if (server->penaltyTime != 0)
8914 {
8915 ptime = server->penaltyTime - m->timenow;
8916 if (ptime < 0)
8917 {
8918 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
8919 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
8920 // here
8921 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
8922 ptime, server->penaltyTime, m->timenow);
8923 server->penaltyTime = 0;
8924 ptime = 0;
8925 }
8926 }
8927 return ptime;
8928 }
8929
8930 //Checks to see whether the newname is a better match for the name, given the best one we have
8931 //seen so far (given in bestcount).
8932 //Returns -1 if the newname is not a better match
8933 //Returns 0 if the newname is the same as the old match
8934 //Returns 1 if the newname is a better match
8935 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
8936 int bestcount)
8937 {
8938 // If the name contains fewer labels than the new server's domain or the new name
8939 // contains fewer labels than the current best, then it can't possibly be a better match
8940 if (namecount < newcount || newcount < bestcount) return -1;
8941
8942 // If there is no match, return -1 and the caller will skip this newname for
8943 // selection
8944 //
8945 // If we find a match and the number of labels is the same as bestcount, then
8946 // we return 0 so that the caller can do additional logic to pick one of
8947 // the best based on some other factors e.g., penaltyTime
8948 //
8949 // If we find a match and the number of labels is more than bestcount, then we
8950 // return 1 so that the caller can pick this over the old one.
8951 //
8952 // Note: newcount can either be equal or greater than bestcount beause of the
8953 // check above.
8954
8955 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
8956 return bestcount == newcount ? 0 : 1;
8957 else
8958 return -1;
8959 }
8960
8961 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
8962 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
8963 // names. In that case, we give a default timeout of 5 seconds
8964 #define DEFAULT_MCAST_TIMEOUT 5
8965 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
8966 {
8967 McastResolver *curmatch = mDNSNULL;
8968 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
8969 McastResolver *curr;
8970 int bettermatch, currcount;
8971 for (curr = m->McastResolvers; curr; curr = curr->next)
8972 {
8973 currcount = CountLabels(&curr->domain);
8974 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
8975 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
8976 // the timeout value from the first one
8977 if (bettermatch == 1)
8978 {
8979 curmatch = curr;
8980 bestmatchlen = currcount;
8981 }
8982 }
8983 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
8984 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
8985 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
8986 }
8987
8988 // Returns true if it is a Domain Enumeration Query
8989 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
8990 {
8991 const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
8992 (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
8993 const domainname *d = qname;
8994 const mDNSu8 *label;
8995 int i = 0;
8996
8997 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
8998 if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
8999
9000 label = (const mDNSu8 *)d;
9001 while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
9002 {
9003 if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
9004 i++;
9005 }
9006 if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
9007 {
9008 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
9009 return mDNSfalse;
9010 }
9011 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
9012
9013 // CountLabels already verified the number of labels
9014 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label
9015 label = (const mDNSu8 *)d;
9016 if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
9017 {
9018 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
9019 return(mDNSfalse);
9020 }
9021 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
9022
9023 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label
9024 label = (const mDNSu8 *)d;
9025 if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
9026 {
9027 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
9028 return(mDNSfalse);
9029 }
9030 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
9031
9032 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
9033
9034 return mDNStrue;
9035 }
9036
9037 // Sets all the Valid DNS servers for a question
9038 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
9039 {
9040 DNSServer *curmatch = mDNSNULL;
9041 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
9042 DNSServer *curr;
9043 int bettermatch, currcount;
9044 int index = 0;
9045 mDNSu32 timeout = 0;
9046 mDNSBool DEQuery;
9047
9048 question->validDNSServers = zeroOpaque64;
9049 DEQuery = DomainEnumQuery(&question->qname);
9050 for (curr = m->DNSServers; curr; curr = curr->next)
9051 {
9052 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
9053 // skip servers that will soon be deleted
9054 if (curr->flags & DNSServer_FlagDelete)
9055 { debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
9056
9057 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
9058 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
9059 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
9060 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
9061 // match the scoped entries by mistake.
9062 //
9063 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
9064
9065 if (curr->scoped && curr->interface == mDNSInterface_Any)
9066 { debugf("SetValidDNSServers: Scoped DNS server %#a (Domain %##s) with Interface Any", &curr->addr, curr->domain.c); continue; }
9067
9068 currcount = CountLabels(&curr->domain);
9069 if ((!DEQuery || !curr->cellIntf) &&
9070 ((!curr->scoped && (!question->InterfaceID || (question->InterfaceID == mDNSInterface_Unicast))) ||
9071 (curr->interface == question->InterfaceID)))
9072 {
9073 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
9074
9075 // If we found a better match (bettermatch == 1) then clear all the bits
9076 // corresponding to the old DNSServers that we have may set before and start fresh.
9077 // If we find an equal match, then include that DNSServer also by setting the corresponding
9078 // bit
9079 if ((bettermatch == 1) || (bettermatch == 0))
9080 {
9081 curmatch = curr;
9082 bestmatchlen = currcount;
9083 if (bettermatch) { debugf("SetValidDNSServers: Resetting all the bits"); question->validDNSServers = zeroOpaque64; timeout = 0; }
9084 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
9085 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
9086 curr->interface);
9087 timeout += curr->timeout;
9088 if (DEQuery) debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->cellIntf);
9089 bit_set_opaque64(question->validDNSServers, index);
9090 }
9091 }
9092 index++;
9093 }
9094 question->noServerResponse = 0;
9095
9096 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
9097 question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
9098 // If there are no matching resolvers, then use the default value to timeout
9099 return (question->ValidatingResponse ? DEFAULT_UDNSSEC_TIMEOUT : timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
9100 }
9101
9102 // Get the Best server that matches a name. If you find penalized servers, look for the one
9103 // that will come out of the penalty box soon
9104 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSOpaque64 validBits, int *selected, mDNSBool nameMatch)
9105 {
9106 DNSServer *curmatch = mDNSNULL;
9107 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
9108 DNSServer *curr;
9109 mDNSs32 bestPenaltyTime, currPenaltyTime;
9110 int bettermatch, currcount;
9111 int index = 0;
9112 int currindex = -1;
9113
9114 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
9115 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
9116 for (curr = m->DNSServers; curr; curr = curr->next)
9117 {
9118 // skip servers that will soon be deleted
9119 if (curr->flags & DNSServer_FlagDelete)
9120 { debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
9121
9122 // Check if this is a valid DNSServer
9123 if (!bit_get_opaque64(validBits, index)) { debugf("GetBestServer: continuing for index %d", index); index++; continue; }
9124
9125 currcount = CountLabels(&curr->domain);
9126 currPenaltyTime = PenaltyTimeForServer(m, curr);
9127
9128 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
9129 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
9130
9131 // If there are multiple best servers for a given question, we will pick the first one
9132 // if none of them are penalized. If some of them are penalized in that list, we pick
9133 // the least penalized one. BetterMatchForName walks through all best matches and
9134 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
9135 // in the list when there are no penalized servers and least one among them
9136 // when there are some penalized servers
9137 //
9138 // Notes on InterfaceID matching:
9139 //
9140 // 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
9141 // is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
9142 // entries by "scoped" being false. These are like any other unscoped entries except that
9143 // if it is picked e.g., domain match, when the packet is sent out later, the packet will
9144 // be sent out on that interface. Theese entries can be matched by either specifying a
9145 // zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
9146 // the question will cause an extra check on matching the InterfaceID on the question
9147 // against the DNSServer.
9148 //
9149 // 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
9150 // is the new way of specifying an InterfaceID option for DNSServer. These will be considered
9151 // only when the question has non-zero interfaceID.
9152
9153 if ((!curr->scoped && !InterfaceID) || (curr->interface == InterfaceID))
9154 {
9155
9156 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
9157 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
9158 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
9159 // part and still do some redundant steps e.g., InterfaceID match
9160
9161 if (nameMatch) bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
9162 else bettermatch = 0;
9163
9164 // If we found a better match (bettermatch == 1) then we don't need to
9165 // compare penalty times. But if we found an equal match, then we compare
9166 // the penalty times to pick a better match
9167
9168 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
9169 { currindex = index; curmatch = curr; bestmatchlen = currcount; bestPenaltyTime = currPenaltyTime; }
9170 }
9171 index++;
9172 }
9173 if (selected) *selected = currindex;
9174 return curmatch;
9175 }
9176
9177 // Look up a DNS Server, matching by name and InterfaceID
9178 mDNSexport DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID)
9179 {
9180 DNSServer *curmatch = mDNSNULL;
9181 char *ifname = mDNSNULL; // for logging purposes only
9182 mDNSOpaque64 allValid;
9183
9184 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
9185 InterfaceID = mDNSNULL;
9186
9187 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
9188
9189 // By passing in all ones, we make sure that every DNS server is considered
9190 allValid.l[0] = allValid.l[1] = 0xFFFFFFFF;
9191
9192 curmatch = GetBestServer(m, name, InterfaceID, allValid, mDNSNULL, mDNStrue);
9193
9194 if (curmatch != mDNSNULL)
9195 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
9196 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
9197 InterfaceID, name);
9198 else
9199 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
9200
9201 return(curmatch);
9202 }
9203
9204 // Look up a DNS Server for a question within its valid DNSServer bits
9205 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
9206 {
9207 DNSServer *curmatch = mDNSNULL;
9208 char *ifname = mDNSNULL; // for logging purposes only
9209 mDNSInterfaceID InterfaceID = question->InterfaceID;
9210 const domainname *name = &question->qname;
9211 int currindex;
9212
9213 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
9214 InterfaceID = mDNSNULL;
9215
9216 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
9217
9218 if (!mDNSOpaque64IsZero(&question->validDNSServers))
9219 {
9220 curmatch = GetBestServer(m, name, InterfaceID, question->validDNSServers, &currindex, mDNSfalse);
9221 if (currindex != -1) bit_clr_opaque64(question->validDNSServers, currindex);
9222 }
9223
9224 if (curmatch != mDNSNULL)
9225 LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question, &curmatch->addr,
9226 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
9227 InterfaceID, name, DNSTypeName(question->qtype));
9228 else
9229 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question, ifname ? ifname : "None", InterfaceID, name, DNSTypeName(question->qtype));
9230
9231 return(curmatch);
9232 }
9233
9234
9235 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
9236 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
9237
9238 // Called in normal client context (lock not held)
9239 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
9240 {
9241 DNSQuestion *q;
9242 (void)n; // Unused
9243 mDNS_Lock(m);
9244 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
9245 for (q = m->Questions; q; q=q->next)
9246 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
9247 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
9248 #if APPLE_OSX_mDNSResponder
9249 UpdateAutoTunnelDomainStatuses(m);
9250 #endif
9251 mDNS_Unlock(m);
9252 }
9253
9254 mDNSlocal mDNSBool IsAutoTunnelAddress(mDNS *const m, const mDNSv6Addr a)
9255 {
9256 DomainAuthInfo *ai = mDNSNULL;
9257
9258 if (mDNSSameIPv6Address(a, m->AutoTunnelRelayAddr))
9259 return mDNStrue;
9260
9261 for (ai = m->AuthInfoList; ai; ai = ai->next)
9262 {
9263 if (!ai->deltime && ai->AutoTunnel && mDNSSameIPv6Address(a, ai->AutoTunnelInnerAddress))
9264 {
9265 return mDNStrue;
9266 }
9267 }
9268
9269 return mDNSfalse;
9270 }
9271
9272 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, domainname *qname, mDNSu16 qtype, mDNSInterfaceID InterfaceID)
9273 {
9274 NetworkInterfaceInfo *i;
9275 mDNSs32 iptype;
9276 DomainAuthInfo *AuthInfo;
9277
9278 if (qtype == kDNSType_A) iptype = mDNSAddrType_IPv4;
9279 else if (qtype == kDNSType_AAAA) iptype = mDNSAddrType_IPv6;
9280 else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname, DNSTypeName(qtype)); return mDNSfalse; }
9281
9282 // We still want the ability to be able to listen to the local services and hence
9283 // don't fail .local requests. We always have a loopback interface which we don't
9284 // check here.
9285 if (InterfaceID != mDNSInterface_Unicast && IsLocalDomain(qname)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname, DNSTypeName(qtype)); return mDNSfalse; }
9286
9287 // Skip Private domains as we have special addresses to get the hosts in the Private domain
9288 AuthInfo = GetAuthInfoForName_internal(m, qname);
9289 if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
9290 { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname, DNSTypeName(qtype)); return mDNSfalse; }
9291
9292 // Match on Type, Address and InterfaceID
9293 //
9294 // Check whether we are looking for a name that ends in .local, then presence of a link-local
9295 // address on the interface is sufficient.
9296 for (i = m->HostInterfaces; i; i = i->next)
9297 {
9298 if (i->ip.type != iptype) continue;
9299
9300 if (!InterfaceID || (InterfaceID == mDNSInterface_LocalOnly) || (InterfaceID == mDNSInterface_P2P) ||
9301 (InterfaceID == mDNSInterface_Unicast) || (i->InterfaceID == InterfaceID))
9302 {
9303 if (iptype == mDNSAddrType_IPv4 && !mDNSv4AddressIsLoopback(&i->ip.ip.v4) && !mDNSv4AddressIsLinkLocal(&i->ip.ip.v4))
9304 {
9305 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname, DNSTypeName(qtype),
9306 &i->ip.ip.v4);
9307 if (m->SleepState == SleepState_Sleeping)
9308 LogInfo("ShouldSuppressQuery: Would have returned true earlier");
9309 return mDNSfalse;
9310 }
9311 else if (iptype == mDNSAddrType_IPv6 &&
9312 !mDNSv6AddressIsLoopback(&i->ip.ip.v6) &&
9313 !mDNSv6AddressIsLinkLocal(&i->ip.ip.v6) &&
9314 !IsAutoTunnelAddress(m, i->ip.ip.v6))
9315 {
9316 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname, DNSTypeName(qtype),
9317 &i->ip.ip.v6);
9318 if (m->SleepState == SleepState_Sleeping)
9319 LogInfo("ShouldSuppressQuery: Would have returned true earlier");
9320 return mDNSfalse;
9321 }
9322 }
9323 }
9324 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname, DNSTypeName(qtype));
9325 return mDNStrue;
9326 }
9327
9328 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
9329 {
9330 CacheRecord *rr;
9331 mDNSu32 slot;
9332 CacheGroup *cg;
9333
9334 slot = HashSlot(&q->qname);
9335 cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
9336 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
9337 {
9338 // Don't deliver RMV events for negative records
9339 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
9340 {
9341 LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
9342 CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
9343 continue;
9344 }
9345
9346 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
9347 {
9348 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
9349 q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
9350
9351 q->CurrentAnswers--;
9352 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
9353 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
9354
9355 if (rr->CRActiveQuestion == q)
9356 {
9357 DNSQuestion *qptr;
9358 // If this was the active question for this cache entry, it was the one that was
9359 // responsible for keeping the cache entry fresh when the cache entry was reaching
9360 // its expiry. We need to handover the responsibility to someone else. Otherwise,
9361 // when the cache entry is about to expire, we won't find an active question
9362 // (pointed by CRActiveQuestion) to refresh the cache.
9363 for (qptr = m->Questions; qptr; qptr=qptr->next)
9364 if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
9365 break;
9366
9367 if (qptr)
9368 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
9369 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
9370 qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
9371
9372 rr->CRActiveQuestion = qptr; // Question used to be active; new value may or may not be null
9373 if (!qptr) m->rrcache_active--; // If no longer active, decrement rrcache_active count
9374 }
9375 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
9376 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
9377 }
9378 }
9379 }
9380
9381 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
9382 {
9383 DNSQuestion *q;
9384 for (q = m->NewQuestions; q; q = q->next)
9385 if (q == question) return mDNStrue;
9386 return mDNSfalse;
9387 }
9388
9389 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
9390 {
9391 AuthRecord *rr;
9392 mDNSu32 slot;
9393 AuthGroup *ag;
9394
9395 if (m->CurrentQuestion)
9396 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
9397 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
9398
9399 if (IsQuestionNew(m, q))
9400 {
9401 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
9402 return mDNStrue;
9403 }
9404 m->CurrentQuestion = q;
9405 slot = AuthHashSlot(&q->qname);
9406 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
9407 if (ag)
9408 {
9409 for (rr = ag->members; rr; rr=rr->next)
9410 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
9411 if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
9412 {
9413 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
9414 ARDisplayString(m, rr));
9415 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
9416 {
9417 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
9418 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
9419 q->CurrentAnswers, q->LOAddressAnswers);
9420 continue;
9421 }
9422 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again
9423 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
9424 }
9425 }
9426 m->CurrentQuestion = mDNSNULL;
9427 return mDNStrue;
9428 }
9429
9430 // Returns false if the question got deleted while delivering the RMV events
9431 // The caller should handle the case
9432 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
9433 {
9434 if (m->CurrentQuestion)
9435 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
9436 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
9437
9438 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
9439 // If this question was answered using local auth records, then you can't deliver RMVs using cache
9440 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
9441 {
9442 m->CurrentQuestion = q;
9443 CacheRecordRmvEventsForCurrentQuestion(m, q);
9444 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
9445 m->CurrentQuestion = mDNSNULL;
9446 }
9447 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
9448 return mDNStrue;
9449 }
9450
9451 // The caller should hold the lock
9452 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
9453 {
9454 DNSQuestion *q;
9455 DNSQuestion *restart = mDNSNULL;
9456
9457 // We look through all questions including new questions. During network change events,
9458 // we potentially restart questions here in this function that ends up as new questions,
9459 // which may be suppressed at this instance. Before it is handled we get another network
9460 // event that changes the status e.g., address becomes available. If we did not process
9461 // new questions, we would never change its SuppressQuery status.
9462 //
9463 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
9464 // application callback can potentially stop the current question (detected by CurrentQuestion) or
9465 // *any* other question which could be the next one that we may process here. RestartQuestion
9466 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
9467 // if the "next" question is stopped while the CurrentQuestion is stopped
9468 if (m->RestartQuestion)
9469 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
9470 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
9471 m->RestartQuestion = m->Questions;
9472 while (m->RestartQuestion)
9473 {
9474 q = m->RestartQuestion;
9475 m->RestartQuestion = q->next;
9476 if (!mDNSOpaque16IsZero(q->TargetQID) && q->SuppressUnusable)
9477 {
9478 mDNSBool old = q->SuppressQuery;
9479 q->SuppressQuery = ShouldSuppressQuery(m, &q->qname, q->qtype, q->InterfaceID);
9480 if (q->SuppressQuery != old)
9481 {
9482 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
9483 // LOddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
9484 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
9485
9486 if (q->SuppressQuery)
9487 {
9488 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
9489 // followed by a negative cache response. Temporarily turn off suppression so that
9490 // AnswerCurrentQuestionWithResourceRecord can answer the question
9491 q->SuppressQuery = mDNSfalse;
9492 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
9493 q->SuppressQuery = mDNStrue;
9494 }
9495
9496 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
9497 // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
9498 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
9499 // the restart will not be a duplicate ADD
9500 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
9501
9502 // There are two cases here.
9503 //
9504 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
9505 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
9506 // because when we get the response, if we had entries in the cache already, it will not answer
9507 // this question if the cache entry did not change. Hence, we need to restart
9508 // the query so that it can be answered from the cache.
9509 //
9510 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
9511 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
9512 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
9513 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
9514 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
9515 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
9516 // the question is not suppressed, we don't want two active questions sending packets on the wire.
9517 // This affects both efficiency and also the current design where there is only one active question
9518 // pointed to from a cache entry.
9519 //
9520 // We restart queries in a two step process by first calling stop and build a temporary list which we
9521 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
9522 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
9523 // will soon become the real question) including q->ThisQInterval which might be zero if it was
9524 // suppressed before. At the end when we have restarted all questions, none of them is active as each
9525 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
9526 //
9527 // It is much cleaner and less error prone to build a list of questions and restart at the end.
9528
9529 LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
9530 mDNS_StopQuery_internal(m, q);
9531 q->next = restart;
9532 restart = q;
9533 }
9534 }
9535 }
9536 while (restart)
9537 {
9538 q = restart;
9539 restart = restart->next;
9540 q->next = mDNSNULL;
9541 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
9542 mDNS_StartQuery_internal(m, q);
9543 }
9544 }
9545
9546 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
9547 {
9548 if (question->Target.type && !ValidQuestionTarget(question))
9549 {
9550 LogMsg("mDNS_StartQuery_internal: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
9551 question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
9552 question->Target.type = mDNSAddrType_None;
9553 }
9554
9555 if (!question->Target.type) question->TargetPort = zeroIPPort; // If no question->Target specified clear TargetPort
9556
9557 question->TargetQID =
9558 #ifndef UNICAST_DISABLED
9559 (question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
9560 #endif // UNICAST_DISABLED
9561 zeroID;
9562
9563 debugf("mDNS_StartQuery: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
9564
9565 if (m->rrcache_size == 0) // Can't do queries if we have no cache space allocated
9566 return(mStatus_NoCache);
9567 else
9568 {
9569 int i;
9570 DNSQuestion **q;
9571
9572 if (!ValidateDomainName(&question->qname))
9573 {
9574 LogMsg("Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
9575 return(mStatus_Invalid);
9576 }
9577
9578 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
9579 q = &m->Questions;
9580 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) q = &m->LocalOnlyQuestions;
9581 while (*q && *q != question) q=&(*q)->next;
9582
9583 if (*q)
9584 {
9585 LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
9586 question->qname.c, DNSTypeName(question->qtype), question);
9587 return(mStatus_AlreadyRegistered);
9588 }
9589
9590 *q = question;
9591
9592 // If this question is referencing a specific interface, verify it exists
9593 if (question->InterfaceID && question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_Unicast && question->InterfaceID != mDNSInterface_P2P)
9594 {
9595 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
9596 if (!intf)
9597 LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
9598 question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
9599 }
9600
9601 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
9602 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
9603 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
9604 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
9605 // that to go out immediately.
9606 question->next = mDNSNULL;
9607 question->qnamehash = DomainNameHashValue(&question->qname); // MUST do this before FindDuplicateQuestion()
9608 question->DelayAnswering = CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash, HashSlot(&question->qname));
9609 question->LastQTime = m->timenow;
9610 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
9611 question->ExpectUnicastResp = 0;
9612 question->LastAnswerPktNum = m->PktNum;
9613 question->RecentAnswerPkts = 0;
9614 question->CurrentAnswers = 0;
9615 question->LargeAnswers = 0;
9616 question->UniqueAnswers = 0;
9617 question->LOAddressAnswers = 0;
9618 question->FlappingInterface1 = mDNSNULL;
9619 question->FlappingInterface2 = mDNSNULL;
9620 // Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
9621 question->AuthInfo = GetAuthInfoForQuestion(m, question);
9622 if (question->SuppressUnusable)
9623 question->SuppressQuery = ShouldSuppressQuery(m, &question->qname, question->qtype, question->InterfaceID);
9624 else
9625 question->SuppressQuery = 0;
9626 question->DuplicateOf = FindDuplicateQuestion(m, question);
9627 question->NextInDQList = mDNSNULL;
9628 question->SendQNow = mDNSNULL;
9629 question->SendOnAll = mDNSfalse;
9630 question->RequestUnicast = 0;
9631 question->LastQTxTime = m->timenow;
9632 question->CNAMEReferrals = 0;
9633
9634 // We'll create our question->LocalSocket on demand, if needed.
9635 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
9636 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
9637 // NAT mapping for receiving inbound add/remove events.
9638 question->LocalSocket = mDNSNULL;
9639 question->qDNSServer = mDNSNULL;
9640 question->unansweredQueries = 0;
9641 question->nta = mDNSNULL;
9642 question->servAddr = zeroAddr;
9643 question->servPort = zeroIPPort;
9644 question->tcp = mDNSNULL;
9645 question->NoAnswer = NoAnswer_Normal;
9646
9647 question->state = LLQ_InitialRequest;
9648 question->ReqLease = 0;
9649 question->expire = 0;
9650 question->ntries = 0;
9651 question->id = zeroOpaque64;
9652 question->validDNSServers = zeroOpaque64;
9653 question->triedAllServersOnce = 0;
9654 question->noServerResponse = 0;
9655 question->StopTime = 0;
9656 if (question->WakeOnResolve)
9657 {
9658 question->WakeOnResolveCount = InitialWakeOnResolveCount;
9659 mDNS_PurgeBeforeResolve(m, question);
9660 }
9661 else
9662 question->WakeOnResolveCount = 0;
9663
9664 question->ValidationState = (question->ValidationRequired ? DNSSECValRequired : DNSSECValNotRequired);
9665 question->ValidationStatus = 0;
9666
9667
9668 if (question->DuplicateOf) question->AuthInfo = question->DuplicateOf->AuthInfo;
9669
9670 for (i=0; i<DupSuppressInfoSize; i++)
9671 question->DupSuppress[i].InterfaceID = mDNSNULL;
9672
9673 debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
9674 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
9675 NextQSendTime(question) - m->timenow,
9676 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
9677 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
9678
9679 if (question->DelayAnswering)
9680 LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
9681 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
9682
9683 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
9684 {
9685 if (!m->NewLocalOnlyQuestions) m->NewLocalOnlyQuestions = question;
9686 }
9687 else
9688 {
9689 if (!m->NewQuestions) m->NewQuestions = question;
9690
9691 // If the question's id is non-zero, then it's Wide Area
9692 // MUST NOT do this Wide Area setup until near the end of
9693 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
9694 // NS, etc.) and if we haven't finished setting up our own question and setting
9695 // m->NewQuestions if necessary then we could end up recursively re-entering
9696 // this routine with the question list data structures in an inconsistent state.
9697 if (!mDNSOpaque16IsZero(question->TargetQID))
9698 {
9699 // Duplicate questions should have the same DNSServers so that when we find
9700 // a matching resource record, all of them get the answers. Calling GetServerForQuestion
9701 // for the duplicate question may get a different DNS server from the original question
9702 mDNSu32 timeout = SetValidDNSServers(m, question);
9703 // We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
9704 // a networking change/search domain change that calls this function again we keep
9705 // reinitializing the timeout value which means it may never timeout. If this becomes
9706 // a common case in the future, we can easily fix this by adding extra state that
9707 // indicates that we have already set the StopTime.
9708 if (question->TimeoutQuestion)
9709 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
9710 if (question->DuplicateOf)
9711 {
9712 question->validDNSServers = question->DuplicateOf->validDNSServers;
9713 question->qDNSServer = question->DuplicateOf->qDNSServer;
9714 LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), Timeout %d, DNS Server %#a:%d",
9715 question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype), timeout,
9716 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
9717 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
9718 }
9719 else
9720 {
9721 question->qDNSServer = GetServerForQuestion(m, question);
9722 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
9723 question, question->qname.c, DNSTypeName(question->qtype), timeout,
9724 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
9725 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
9726 }
9727 // If we are talking to a server on the local host, unsupress the query. This happens if we have
9728 // a DNS server running locally while we don't have any interfaces UP.
9729 //
9730 // TBD: Re-organise the code so that we can move this logic to ShouldSuppressQuery
9731 if (question->SuppressQuery && question->qDNSServer && mDNSAddressIsLoopback(&question->qDNSServer->addr))
9732 {
9733 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s) unsuppressed due to local DNS Server %#a:%d",
9734 question, question->qname.c, DNSTypeName(question->qtype), &question->qDNSServer->addr,
9735 mDNSVal16(question->qDNSServer->port));
9736 question->SuppressQuery = 0;
9737 }
9738 ActivateUnicastQuery(m, question, mDNSfalse);
9739
9740 // If there is a negative cache entry for this question and if it does
9741 // not have cached nsecs, then we can't validate possibly. Hence, flush
9742 // them so that we can reissue the question again with EDNS0/DO bit set.
9743 if (!question->DuplicateOf && DNSSECQuestion(question))
9744 mDNS_CheckForCachedNSECS(m, question);
9745
9746 // If long-lived query, and we don't have our NAT mapping active, start it now
9747 if (question->LongLived && !m->LLQNAT.clientContext)
9748 {
9749 m->LLQNAT.Protocol = NATOp_MapUDP;
9750 m->LLQNAT.IntPort = m->UnicastPort4;
9751 m->LLQNAT.RequestedPort = m->UnicastPort4;
9752 m->LLQNAT.clientCallback = LLQNATCallback;
9753 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal is active
9754 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
9755 }
9756
9757 #if APPLE_OSX_mDNSResponder
9758 if (question->LongLived)
9759 UpdateAutoTunnelDomainStatuses(m);
9760 #endif
9761
9762 }
9763 else
9764 {
9765 if (question->TimeoutQuestion)
9766 question->StopTime = NonZeroTime(m->timenow + GetTimeoutForMcastQuestion(m, question) * mDNSPlatformOneSecond);
9767 }
9768 if (question->StopTime) SetNextQueryStopTime(m, question);
9769 SetNextQueryTime(m,question);
9770 }
9771
9772 return(mStatus_NoError);
9773 }
9774 }
9775
9776 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
9777 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
9778 {
9779 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
9780 // This function may be called anytime to free the zone information.The question may or may not have stopped.
9781 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
9782 // call it again
9783 if (nta->question.ThisQInterval != -1)
9784 {
9785 mDNS_StopQuery_internal(m, &nta->question);
9786 if (nta->question.ThisQInterval != -1)
9787 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
9788 }
9789 mDNSPlatformMemFree(nta);
9790 }
9791
9792 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
9793 {
9794 const mDNSu32 slot = HashSlot(&question->qname);
9795 CacheGroup *cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
9796 CacheRecord *rr;
9797 DNSQuestion **qp = &m->Questions;
9798
9799 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
9800
9801 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) qp = &m->LocalOnlyQuestions;
9802 while (*qp && *qp != question) qp=&(*qp)->next;
9803 if (*qp) *qp = (*qp)->next;
9804 else
9805 {
9806 #if !ForceAlerts
9807 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
9808 #endif
9809 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
9810 question->qname.c, DNSTypeName(question->qtype));
9811 #if ForceAlerts
9812 *(long*)0 = 0;
9813 #endif
9814 return(mStatus_BadReferenceErr);
9815 }
9816
9817 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
9818 UpdateQuestionDuplicates(m, question);
9819 // But don't trash ThisQInterval until afterwards.
9820 question->ThisQInterval = -1;
9821
9822 // If there are any cache records referencing this as their active question, then see if there is any
9823 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
9824 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
9825 {
9826 if (rr->CRActiveQuestion == question)
9827 {
9828 DNSQuestion *q;
9829 // Checking for ActiveQuestion filters questions that are suppressed also
9830 // as suppressed questions are not active
9831 for (q = m->Questions; q; q=q->next) // Scan our list of questions
9832 if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
9833 break;
9834 if (q)
9835 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
9836 "CurrentAnswers %d, SuppressQuery %d", q, CRDisplayString(m,rr), question->CurrentAnswers, q->CurrentAnswers, q->SuppressQuery);
9837 rr->CRActiveQuestion = q; // Question used to be active; new value may or may not be null
9838 if (!q) m->rrcache_active--; // If no longer active, decrement rrcache_active count
9839 }
9840 }
9841
9842 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
9843 // bump its pointer forward one question.
9844 if (m->CurrentQuestion == question)
9845 {
9846 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
9847 question->qname.c, DNSTypeName(question->qtype));
9848 m->CurrentQuestion = question->next;
9849 }
9850
9851 if (m->NewQuestions == question)
9852 {
9853 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
9854 question->qname.c, DNSTypeName(question->qtype));
9855 m->NewQuestions = question->next;
9856 }
9857
9858 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
9859
9860 if (m->RestartQuestion == question)
9861 {
9862 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
9863 question->qname.c, DNSTypeName(question->qtype));
9864 m->RestartQuestion = question->next;
9865 }
9866
9867 if (m->ValidationQuestion == question)
9868 {
9869 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
9870 question->qname.c, DNSTypeName(question->qtype));
9871 m->ValidationQuestion = question->next;
9872 }
9873
9874 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
9875 question->next = mDNSNULL;
9876
9877 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
9878
9879 // And finally, cancel any associated GetZoneData operation that's still running.
9880 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
9881 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
9882 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
9883 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
9884 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
9885 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
9886 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
9887 {
9888 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
9889 DNSQuestion *q;
9890 for (q = m->Questions; q; q=q->next)
9891 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
9892 if (!q)
9893 {
9894 if (!m->LLQNAT.clientContext) // Should never happen, but just in case...
9895 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
9896 else
9897 {
9898 LogInfo("Stopping LLQNAT");
9899 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
9900 m->LLQNAT.clientContext = mDNSNULL; // Means LLQ NAT Traversal not running
9901 }
9902 }
9903
9904 // If necessary, tell server it can delete this LLQ state
9905 if (question->state == LLQ_Established)
9906 {
9907 question->ReqLease = 0;
9908 sendLLQRefresh(m, question);
9909 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
9910 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
9911 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
9912 // we let that run out its natural course and complete asynchronously.
9913 if (question->tcp)
9914 {
9915 question->tcp->question = mDNSNULL;
9916 question->tcp = mDNSNULL;
9917 }
9918 }
9919 #if APPLE_OSX_mDNSResponder
9920 UpdateAutoTunnelDomainStatuses(m);
9921 #endif
9922 }
9923 // wait until we send the refresh above which needs the nta
9924 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
9925
9926 return(mStatus_NoError);
9927 }
9928
9929 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
9930 {
9931 mStatus status;
9932 mDNS_Lock(m);
9933 status = mDNS_StartQuery_internal(m, question);
9934 mDNS_Unlock(m);
9935 return(status);
9936 }
9937
9938 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
9939 {
9940 mStatus status;
9941 mDNS_Lock(m);
9942 status = mDNS_StopQuery_internal(m, question);
9943 mDNS_Unlock(m);
9944 return(status);
9945 }
9946
9947 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
9948 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
9949 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
9950 // specifically to catch and report if the client callback does try to make API calls
9951 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
9952 {
9953 mStatus status;
9954 DNSQuestion *qq;
9955 mDNS_Lock(m);
9956
9957 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
9958 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
9959
9960 status = mDNS_StopQuery_internal(m, question);
9961 if (status == mStatus_NoError && !qq)
9962 {
9963 const CacheRecord *rr;
9964 const mDNSu32 slot = HashSlot(&question->qname);
9965 CacheGroup *const cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
9966 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
9967 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
9968 if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
9969 {
9970 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
9971 if (question->QuestionCallback)
9972 question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
9973 }
9974 }
9975 mDNS_Unlock(m);
9976 return(status);
9977 }
9978
9979 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
9980 {
9981 mStatus status;
9982 mDNS_Lock(m);
9983 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
9984 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
9985 mDNS_Unlock(m);
9986 return(status);
9987 }
9988
9989 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
9990 {
9991 mStatus status = mStatus_BadReferenceErr;
9992 CacheRecord *cr;
9993 mDNS_Lock(m);
9994 cr = FindIdenticalRecordInCache(m, rr);
9995 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
9996 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
9997 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
9998 mDNS_Unlock(m);
9999 return(status);
10000 }
10001
10002 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
10003 const domainname *const srv, const domainname *const domain,
10004 const mDNSInterfaceID InterfaceID, mDNSu32 flags,
10005 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
10006 mDNSQuestionCallback *Callback, void *Context)
10007 {
10008 question->InterfaceID = InterfaceID;
10009 question->flags = flags;
10010 question->Target = zeroAddr;
10011 question->qtype = kDNSType_PTR;
10012 question->qclass = kDNSClass_IN;
10013 question->LongLived = mDNStrue;
10014 question->ExpectUnique = mDNSfalse;
10015 question->ForceMCast = ForceMCast;
10016 question->ReturnIntermed = mDNSfalse;
10017 question->SuppressUnusable = mDNSfalse;
10018 question->SearchListIndex = 0;
10019 question->AppendSearchDomains = 0;
10020 question->RetryWithSearchDomains = mDNSfalse;
10021 question->TimeoutQuestion = 0;
10022 question->WakeOnResolve = 0;
10023 question->UseBrackgroundTrafficClass = useBackgroundTrafficClass;
10024 question->ValidationRequired = 0;
10025 question->ValidatingResponse = 0;
10026 question->qnameOrig = mDNSNULL;
10027 question->QuestionCallback = Callback;
10028 question->QuestionContext = Context;
10029 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) return(mStatus_BadParamErr);
10030
10031 return(mDNS_StartQuery_internal(m, question));
10032 }
10033
10034 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
10035 const domainname *const srv, const domainname *const domain,
10036 const mDNSInterfaceID InterfaceID, mDNSu32 flags,
10037 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
10038 mDNSQuestionCallback *Callback, void *Context)
10039 {
10040 mStatus status;
10041 mDNS_Lock(m);
10042 status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
10043 mDNS_Unlock(m);
10044 return(status);
10045 }
10046
10047 mDNSlocal mDNSBool MachineHasActiveIPv6(mDNS *const m)
10048 {
10049 NetworkInterfaceInfo *intf;
10050 for (intf = m->HostInterfaces; intf; intf = intf->next)
10051 if (intf->ip.type == mDNSAddrType_IPv6) return(mDNStrue);
10052 return(mDNSfalse);
10053 }
10054
10055 mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
10056 {
10057 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
10058 mDNSBool PortChanged = !mDNSSameIPPort(query->info->port, answer->rdata->u.srv.port);
10059 if (!AddRecord) return;
10060 if (answer->rrtype != kDNSType_SRV) return;
10061
10062 query->info->port = answer->rdata->u.srv.port;
10063
10064 // If this is our first answer, then set the GotSRV flag and start the address query
10065 if (!query->GotSRV)
10066 {
10067 query->GotSRV = mDNStrue;
10068 query->qAv4.InterfaceID = answer->InterfaceID;
10069 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
10070 query->qAv6.InterfaceID = answer->InterfaceID;
10071 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
10072 mDNS_StartQuery(m, &query->qAv4);
10073 // Only do the AAAA query if this machine actually has IPv6 active
10074 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
10075 }
10076 // If this is not our first answer, only re-issue the address query if the target host name has changed
10077 else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
10078 !SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
10079 {
10080 mDNS_StopQuery(m, &query->qAv4);
10081 if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery(m, &query->qAv6);
10082 if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
10083 {
10084 // If we get here, it means:
10085 // 1. This is not our first SRV answer
10086 // 2. The interface ID is different, but the target host and port are the same
10087 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
10088 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
10089 query->qAv4.InterfaceID = query->qSRV.InterfaceID; // Will be mDNSInterface_Any, or a specific interface
10090 query->qAv6.InterfaceID = query->qSRV.InterfaceID;
10091 }
10092 else
10093 {
10094 query->qAv4.InterfaceID = answer->InterfaceID;
10095 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
10096 query->qAv6.InterfaceID = answer->InterfaceID;
10097 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
10098 }
10099 debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query->qAv4.qname.c, DNSTypeName(query->qAv4.qtype));
10100 mDNS_StartQuery(m, &query->qAv4);
10101 // Only do the AAAA query if this machine actually has IPv6 active
10102 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
10103 }
10104 else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
10105 {
10106 if (++query->Answers >= 100)
10107 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
10108 query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
10109 mDNSVal16(answer->rdata->u.srv.port));
10110 query->ServiceInfoQueryCallback(m, query);
10111 }
10112 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
10113 // callback function is allowed to do anything, including deleting this query and freeing its memory.
10114 }
10115
10116 mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
10117 {
10118 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
10119 if (!AddRecord) return;
10120 if (answer->rrtype != kDNSType_TXT) return;
10121 if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
10122
10123 query->GotTXT = mDNStrue;
10124 query->info->TXTlen = answer->rdlength;
10125 query->info->TXTinfo[0] = 0; // In case answer->rdlength is zero
10126 mDNSPlatformMemCopy(query->info->TXTinfo, answer->rdata->u.txt.c, answer->rdlength);
10127
10128 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
10129
10130 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
10131 // callback function is allowed to do anything, including deleting this query and freeing its memory.
10132 if (query->ServiceInfoQueryCallback && query->GotADD)
10133 {
10134 if (++query->Answers >= 100)
10135 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
10136 query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
10137 query->ServiceInfoQueryCallback(m, query);
10138 }
10139 }
10140
10141 mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
10142 {
10143 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
10144 //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
10145 if (!AddRecord) return;
10146
10147 if (answer->rrtype == kDNSType_A)
10148 {
10149 query->info->ip.type = mDNSAddrType_IPv4;
10150 query->info->ip.ip.v4 = answer->rdata->u.ipv4;
10151 }
10152 else if (answer->rrtype == kDNSType_AAAA)
10153 {
10154 query->info->ip.type = mDNSAddrType_IPv6;
10155 query->info->ip.ip.v6 = answer->rdata->u.ipv6;
10156 }
10157 else
10158 {
10159 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name->c, answer->rrtype, DNSTypeName(answer->rrtype));
10160 return;
10161 }
10162
10163 query->GotADD = mDNStrue;
10164 query->info->InterfaceID = answer->InterfaceID;
10165
10166 verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
10167
10168 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
10169 // callback function is allowed to do anything, including deleting this query and freeing its memory.
10170 if (query->ServiceInfoQueryCallback && query->GotTXT)
10171 {
10172 if (++query->Answers >= 100)
10173 debugf(answer->rrtype == kDNSType_A ?
10174 "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
10175 "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
10176 query->Answers, query->qSRV.qname.c, &answer->rdata->u.data);
10177 query->ServiceInfoQueryCallback(m, query);
10178 }
10179 }
10180
10181 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
10182 // If the query is not interface-specific, then InterfaceID may be zero
10183 // Each time the Callback is invoked, the remainder of the fields will have been filled in
10184 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
10185 mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
10186 ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
10187 {
10188 mStatus status;
10189 mDNS_Lock(m);
10190
10191 query->qSRV.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10192 query->qSRV.InterfaceID = info->InterfaceID;
10193 query->qSRV.flags = 0;
10194 query->qSRV.Target = zeroAddr;
10195 AssignDomainName(&query->qSRV.qname, &info->name);
10196 query->qSRV.qtype = kDNSType_SRV;
10197 query->qSRV.qclass = kDNSClass_IN;
10198 query->qSRV.LongLived = mDNSfalse;
10199 query->qSRV.ExpectUnique = mDNStrue;
10200 query->qSRV.ForceMCast = mDNSfalse;
10201 query->qSRV.ReturnIntermed = mDNSfalse;
10202 query->qSRV.SuppressUnusable = mDNSfalse;
10203 query->qSRV.SearchListIndex = 0;
10204 query->qSRV.AppendSearchDomains = 0;
10205 query->qSRV.RetryWithSearchDomains = mDNSfalse;
10206 query->qSRV.TimeoutQuestion = 0;
10207 query->qSRV.WakeOnResolve = 0;
10208 query->qSRV.UseBrackgroundTrafficClass = mDNSfalse;
10209 query->qSRV.ValidationRequired = 0;
10210 query->qSRV.ValidatingResponse = 0;
10211 query->qSRV.qnameOrig = mDNSNULL;
10212 query->qSRV.QuestionCallback = FoundServiceInfoSRV;
10213 query->qSRV.QuestionContext = query;
10214
10215 query->qTXT.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10216 query->qTXT.InterfaceID = info->InterfaceID;
10217 query->qTXT.flags = 0;
10218 query->qTXT.Target = zeroAddr;
10219 AssignDomainName(&query->qTXT.qname, &info->name);
10220 query->qTXT.qtype = kDNSType_TXT;
10221 query->qTXT.qclass = kDNSClass_IN;
10222 query->qTXT.LongLived = mDNSfalse;
10223 query->qTXT.ExpectUnique = mDNStrue;
10224 query->qTXT.ForceMCast = mDNSfalse;
10225 query->qTXT.ReturnIntermed = mDNSfalse;
10226 query->qTXT.SuppressUnusable = mDNSfalse;
10227 query->qTXT.SearchListIndex = 0;
10228 query->qTXT.AppendSearchDomains = 0;
10229 query->qTXT.RetryWithSearchDomains = mDNSfalse;
10230 query->qTXT.TimeoutQuestion = 0;
10231 query->qTXT.WakeOnResolve = 0;
10232 query->qTXT.UseBrackgroundTrafficClass = mDNSfalse;
10233 query->qTXT.ValidationRequired = 0;
10234 query->qTXT.ValidatingResponse = 0;
10235 query->qTXT.qnameOrig = mDNSNULL;
10236 query->qTXT.QuestionCallback = FoundServiceInfoTXT;
10237 query->qTXT.QuestionContext = query;
10238
10239 query->qAv4.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10240 query->qAv4.InterfaceID = info->InterfaceID;
10241 query->qAv4.flags = 0;
10242 query->qAv4.Target = zeroAddr;
10243 query->qAv4.qname.c[0] = 0;
10244 query->qAv4.qtype = kDNSType_A;
10245 query->qAv4.qclass = kDNSClass_IN;
10246 query->qAv4.LongLived = mDNSfalse;
10247 query->qAv4.ExpectUnique = mDNStrue;
10248 query->qAv4.ForceMCast = mDNSfalse;
10249 query->qAv4.ReturnIntermed = mDNSfalse;
10250 query->qAv4.SuppressUnusable = mDNSfalse;
10251 query->qAv4.SearchListIndex = 0;
10252 query->qAv4.AppendSearchDomains = 0;
10253 query->qAv4.RetryWithSearchDomains = mDNSfalse;
10254 query->qAv4.TimeoutQuestion = 0;
10255 query->qAv4.WakeOnResolve = 0;
10256 query->qAv4.UseBrackgroundTrafficClass = mDNSfalse;
10257 query->qAv4.ValidationRequired = 0;
10258 query->qAv4.ValidatingResponse = 0;
10259 query->qAv4.qnameOrig = mDNSNULL;
10260 query->qAv4.QuestionCallback = FoundServiceInfo;
10261 query->qAv4.QuestionContext = query;
10262
10263 query->qAv6.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10264 query->qAv6.InterfaceID = info->InterfaceID;
10265 query->qAv6.flags = 0;
10266 query->qAv6.Target = zeroAddr;
10267 query->qAv6.qname.c[0] = 0;
10268 query->qAv6.qtype = kDNSType_AAAA;
10269 query->qAv6.qclass = kDNSClass_IN;
10270 query->qAv6.LongLived = mDNSfalse;
10271 query->qAv6.ExpectUnique = mDNStrue;
10272 query->qAv6.ForceMCast = mDNSfalse;
10273 query->qAv6.ReturnIntermed = mDNSfalse;
10274 query->qAv6.SuppressUnusable = mDNSfalse;
10275 query->qAv6.SearchListIndex = 0;
10276 query->qAv6.AppendSearchDomains = 0;
10277 query->qAv6.RetryWithSearchDomains = mDNSfalse;
10278 query->qAv6.TimeoutQuestion = 0;
10279 query->qAv6.UseBrackgroundTrafficClass = mDNSfalse;
10280 query->qAv6.ValidationRequired = 0;
10281 query->qAv6.ValidatingResponse = 0;
10282 query->qAv6.qnameOrig = mDNSNULL;
10283 query->qAv6.QuestionCallback = FoundServiceInfo;
10284 query->qAv6.QuestionContext = query;
10285
10286 query->GotSRV = mDNSfalse;
10287 query->GotTXT = mDNSfalse;
10288 query->GotADD = mDNSfalse;
10289 query->Answers = 0;
10290
10291 query->info = info;
10292 query->ServiceInfoQueryCallback = Callback;
10293 query->ServiceInfoQueryContext = Context;
10294
10295 // info->name = Must already be set up by client
10296 // info->interface = Must already be set up by client
10297 info->ip = zeroAddr;
10298 info->port = zeroIPPort;
10299 info->TXTlen = 0;
10300
10301 // We use mDNS_StartQuery_internal here because we're already holding the lock
10302 status = mDNS_StartQuery_internal(m, &query->qSRV);
10303 if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
10304 if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
10305
10306 mDNS_Unlock(m);
10307 return(status);
10308 }
10309
10310 mDNSexport void mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *q)
10311 {
10312 mDNS_Lock(m);
10313 // We use mDNS_StopQuery_internal here because we're already holding the lock
10314 if (q->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qSRV);
10315 if (q->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qTXT);
10316 if (q->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv4);
10317 if (q->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv6);
10318 mDNS_Unlock(m);
10319 }
10320
10321 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
10322 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
10323 {
10324 question->InterfaceID = InterfaceID;
10325 question->flags = 0;
10326 question->Target = zeroAddr;
10327 question->qtype = kDNSType_PTR;
10328 question->qclass = kDNSClass_IN;
10329 question->LongLived = mDNSfalse;
10330 question->ExpectUnique = mDNSfalse;
10331 question->ForceMCast = mDNSfalse;
10332 question->ReturnIntermed = mDNSfalse;
10333 question->SuppressUnusable = mDNSfalse;
10334 question->SearchListIndex = 0;
10335 question->AppendSearchDomains = 0;
10336 question->RetryWithSearchDomains = mDNSfalse;
10337 question->TimeoutQuestion = 0;
10338 question->WakeOnResolve = 0;
10339 question->UseBrackgroundTrafficClass = mDNSfalse;
10340 question->ValidationRequired = 0;
10341 question->ValidatingResponse = 0;
10342 question->qnameOrig = mDNSNULL;
10343 question->QuestionCallback = Callback;
10344 question->QuestionContext = Context;
10345 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
10346 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
10347 if (!dom) dom = &localdomain;
10348 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
10349 return(mDNS_StartQuery(m, question));
10350 }
10351
10352 // ***************************************************************************
10353 #if COMPILER_LIKES_PRAGMA_MARK
10354 #pragma mark -
10355 #pragma mark - Responder Functions
10356 #endif
10357
10358 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
10359 {
10360 mStatus status;
10361 mDNS_Lock(m);
10362 status = mDNS_Register_internal(m, rr);
10363 mDNS_Unlock(m);
10364 return(status);
10365 }
10366
10367 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
10368 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
10369 {
10370 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
10371 {
10372 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
10373 return(mStatus_Invalid);
10374 }
10375
10376 mDNS_Lock(m);
10377
10378 // If TTL is unspecified, leave TTL unchanged
10379 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
10380
10381 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
10382 if (rr->NewRData)
10383 {
10384 RData *n = rr->NewRData;
10385 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
10386 if (rr->UpdateCallback)
10387 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
10388 }
10389
10390 rr->NewRData = newrdata;
10391 rr->newrdlength = newrdlength;
10392 rr->UpdateCallback = Callback;
10393
10394 #ifndef UNICAST_DISABLED
10395 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
10396 {
10397 mStatus status = uDNS_UpdateRecord(m, rr);
10398 // The caller frees the memory on error, don't retain stale pointers
10399 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
10400 mDNS_Unlock(m);
10401 return(status);
10402 }
10403 #endif
10404
10405 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
10406 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
10407 CompleteRDataUpdate(m, rr);
10408 else
10409 {
10410 rr->AnnounceCount = InitialAnnounceCount;
10411 InitializeLastAPTime(m, rr);
10412 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
10413 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
10414 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
10415 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
10416 if (rr->UpdateCredits <= 5)
10417 {
10418 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
10419 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
10420 rr->ThisAPInterval *= 4;
10421 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
10422 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
10423 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
10424 }
10425 rr->resrec.rroriginalttl = newttl;
10426 }
10427
10428 mDNS_Unlock(m);
10429 return(mStatus_NoError);
10430 }
10431
10432 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
10433 // the record list and/or question list.
10434 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
10435 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
10436 {
10437 mStatus status;
10438 mDNS_Lock(m);
10439 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10440 mDNS_Unlock(m);
10441 return(status);
10442 }
10443
10444 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
10445 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
10446
10447 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
10448 {
10449 NetworkInterfaceInfo *intf;
10450 for (intf = m->HostInterfaces; intf; intf = intf->next)
10451 if (intf->Advertise) break;
10452 return(intf);
10453 }
10454
10455 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
10456 {
10457 char buffer[MAX_REVERSE_MAPPING_NAME];
10458 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
10459 if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
10460
10461 // Send dynamic update for non-linklocal IPv4 Addresses
10462 mDNS_SetupResourceRecord(&set->RR_A, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNS_HostNameCallback, set);
10463 mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10464 mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10465
10466 #if ANSWER_REMOTE_HOSTNAME_QUERIES
10467 set->RR_A.AllowRemoteQuery = mDNStrue;
10468 set->RR_PTR.AllowRemoteQuery = mDNStrue;
10469 set->RR_HINFO.AllowRemoteQuery = mDNStrue;
10470 #endif
10471 // 1. Set up Address record to map from host name ("foo.local.") to IP address
10472 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
10473 AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
10474 if (set->ip.type == mDNSAddrType_IPv4)
10475 {
10476 set->RR_A.resrec.rrtype = kDNSType_A;
10477 set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
10478 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
10479 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
10480 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
10481 }
10482 else if (set->ip.type == mDNSAddrType_IPv6)
10483 {
10484 int i;
10485 set->RR_A.resrec.rrtype = kDNSType_AAAA;
10486 set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
10487 for (i = 0; i < 16; i++)
10488 {
10489 static const char hexValues[] = "0123456789ABCDEF";
10490 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
10491 buffer[i * 4 + 1] = '.';
10492 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
10493 buffer[i * 4 + 3] = '.';
10494 }
10495 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
10496 }
10497
10498 MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
10499 set->RR_PTR.AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
10500 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
10501
10502 set->RR_A.RRSet = &primary->RR_A; // May refer to self
10503
10504 mDNS_Register_internal(m, &set->RR_A);
10505 mDNS_Register_internal(m, &set->RR_PTR);
10506
10507 if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
10508 {
10509 mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
10510 AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
10511 set->RR_HINFO.DependentOn = &set->RR_A;
10512 mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
10513 p += 1 + (int)p[0];
10514 mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
10515 mDNS_Register_internal(m, &set->RR_HINFO);
10516 }
10517 else
10518 {
10519 debugf("Not creating HINFO record: platform support layer provided no information");
10520 set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
10521 }
10522 }
10523
10524 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
10525 {
10526 NetworkInterfaceInfo *intf;
10527
10528 // If we still have address records referring to this one, update them
10529 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
10530 AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
10531 for (intf = m->HostInterfaces; intf; intf = intf->next)
10532 if (intf->RR_A.RRSet == &set->RR_A)
10533 intf->RR_A.RRSet = A;
10534
10535 // Unregister these records.
10536 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
10537 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
10538 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
10539 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
10540 if (set->RR_A.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
10541 if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
10542 if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
10543 }
10544
10545 mDNSexport void mDNS_SetFQDN(mDNS *const m)
10546 {
10547 domainname newmname;
10548 NetworkInterfaceInfo *intf;
10549 AuthRecord *rr;
10550 newmname.c[0] = 0;
10551
10552 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
10553 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
10554
10555 mDNS_Lock(m);
10556
10557 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
10558 else
10559 {
10560 AssignDomainName(&m->MulticastHostname, &newmname);
10561
10562 // 1. Stop advertising our address records on all interfaces
10563 for (intf = m->HostInterfaces; intf; intf = intf->next)
10564 if (intf->Advertise) DeadvertiseInterface(m, intf);
10565
10566 // 2. Start advertising our address records using the new name
10567 for (intf = m->HostInterfaces; intf; intf = intf->next)
10568 if (intf->Advertise) AdvertiseInterface(m, intf);
10569 }
10570
10571 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
10572 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
10573 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
10574
10575 mDNS_Unlock(m);
10576 }
10577
10578 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
10579 {
10580 (void)rr; // Unused parameter
10581
10582 #if MDNS_DEBUGMSGS
10583 {
10584 char *msg = "Unknown result";
10585 if (result == mStatus_NoError) msg = "Name registered";
10586 else if (result == mStatus_NameConflict) msg = "Name conflict";
10587 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
10588 }
10589 #endif
10590
10591 if (result == mStatus_NoError)
10592 {
10593 // Notify the client that the host name is successfully registered
10594 if (m->MainCallback)
10595 m->MainCallback(m, mStatus_NoError);
10596 }
10597 else if (result == mStatus_NameConflict)
10598 {
10599 domainlabel oldlabel = m->hostlabel;
10600
10601 // 1. First give the client callback a chance to pick a new name
10602 if (m->MainCallback)
10603 m->MainCallback(m, mStatus_NameConflict);
10604
10605 // 2. If the client callback didn't do it, add (or increment) an index ourselves
10606 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
10607 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
10608 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
10609 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
10610
10611 // 3. Generate the FQDNs from the hostlabel,
10612 // and make sure all SRV records, etc., are updated to reference our new hostname
10613 mDNS_SetFQDN(m);
10614 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
10615 }
10616 else if (result == mStatus_MemFree)
10617 {
10618 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
10619 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
10620 debugf("mDNS_HostNameCallback: MemFree (ignored)");
10621 }
10622 else
10623 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c);
10624 }
10625
10626 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
10627 {
10628 NetworkInterfaceInfo *intf;
10629 active->IPv4Available = mDNSfalse;
10630 active->IPv6Available = mDNSfalse;
10631 for (intf = m->HostInterfaces; intf; intf = intf->next)
10632 if (intf->InterfaceID == active->InterfaceID)
10633 {
10634 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
10635 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
10636 }
10637 }
10638
10639 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
10640 {
10641 AuthRecord *rr;
10642 LogInfo("RestartRecordGetZoneData: ResourceRecords");
10643 for (rr = m->ResourceRecords; rr; rr=rr->next)
10644 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
10645 {
10646 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
10647 // Zero out the updateid so that if we have a pending response from the server, it won't
10648 // be accepted as a valid response. If we accept the response, we might free the new "nta"
10649 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
10650 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
10651 }
10652 }
10653
10654 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
10655 {
10656 int i;
10657 set->NetWakeBrowse.ThisQInterval = -1;
10658 for (i=0; i<3; i++)
10659 {
10660 set->NetWakeResolve[i].ThisQInterval = -1;
10661 set->SPSAddr[i].type = mDNSAddrType_None;
10662 }
10663 set->NextSPSAttempt = -1;
10664 set->NextSPSAttemptTime = m->timenow;
10665 }
10666
10667 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
10668 {
10669 NetworkInterfaceInfo *p = m->HostInterfaces;
10670 while (p && p != set) p=p->next;
10671 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
10672
10673 if (set->InterfaceActive)
10674 {
10675 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
10676 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
10677 }
10678 }
10679
10680 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
10681 {
10682 NetworkInterfaceInfo *p = m->HostInterfaces;
10683 while (p && p != set) p=p->next;
10684 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
10685
10686 if (set->NetWakeBrowse.ThisQInterval >= 0)
10687 {
10688 int i;
10689 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
10690
10691 // Stop our browse and resolve operations
10692 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
10693 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
10694
10695 // Make special call to the browse callback to let it know it can to remove all records for this interface
10696 if (m->SPSBrowseCallback)
10697 {
10698 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
10699 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
10700 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
10701 }
10702
10703 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
10704 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
10705 InitializeNetWakeState(m, set);
10706 }
10707 }
10708
10709 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
10710 {
10711 AuthRecord *rr;
10712 mDNSBool FirstOfType = mDNStrue;
10713 NetworkInterfaceInfo **p = &m->HostInterfaces;
10714
10715 if (!set->InterfaceID)
10716 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
10717
10718 if (!mDNSAddressIsValidNonZero(&set->mask))
10719 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
10720
10721 mDNS_Lock(m);
10722
10723 // Assume this interface will be active now, unless we find a duplicate already in the list
10724 set->InterfaceActive = mDNStrue;
10725 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
10726 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
10727
10728 InitializeNetWakeState(m, set);
10729
10730 // Scan list to see if this InterfaceID is already represented
10731 while (*p)
10732 {
10733 if (*p == set)
10734 {
10735 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
10736 mDNS_Unlock(m);
10737 return(mStatus_AlreadyRegistered);
10738 }
10739
10740 if ((*p)->InterfaceID == set->InterfaceID)
10741 {
10742 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
10743 set->InterfaceActive = mDNSfalse;
10744 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
10745 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
10746 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
10747 }
10748
10749 p=&(*p)->next;
10750 }
10751
10752 set->next = mDNSNULL;
10753 *p = set;
10754
10755 if (set->Advertise)
10756 AdvertiseInterface(m, set);
10757
10758 LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set->InterfaceID, set->ifname, &set->ip,
10759 set->InterfaceActive ?
10760 "not represented in list; marking active and retriggering queries" :
10761 "already represented in list; marking inactive for now");
10762
10763 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
10764
10765 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
10766 // giving the false impression that there's an active representative of this interface when there really isn't.
10767 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
10768 // even if we believe that we previously had an active representative of this interface.
10769 if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
10770 {
10771 DNSQuestion *q;
10772 // Normally, after an interface comes up, we pause half a second before beginning probing.
10773 // This is to guard against cases where there's rapid interface changes, where we could be confused by
10774 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
10775 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
10776 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
10777 // and think it's a conflicting answer to our probe.
10778 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
10779 const mDNSs32 probedelay = flapping ? mDNSPlatformOneSecond * 5 : mDNSPlatformOneSecond / 2;
10780 const mDNSu8 numannounce = flapping ? (mDNSu8)1 : InitialAnnounceCount;
10781
10782 // Use a small amount of randomness:
10783 // In the case of a network administrator turning on an Ethernet hub so that all the
10784 // connected machines establish link at exactly the same time, we don't want them all
10785 // to go and hit the network with identical queries at exactly the same moment.
10786 // We set a random delay of up to InitialQuestionInterval (1/3 second).
10787 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
10788 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
10789 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
10790 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
10791 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
10792 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
10793
10794 if (flapping) LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
10795
10796 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
10797 if (m->SuppressProbes == 0 ||
10798 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
10799 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
10800
10801 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
10802 // it here also handles the wake up case as the network link comes UP after waking causing
10803 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
10804 // that the network link comes UP after 60 seconds and we never set the OWNER option
10805 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
10806
10807 m->ClearSPSRecords = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
10808
10809 // Clear the flag that ignores IPv6 neighbor advertisements after 2 seconds.
10810 m->clearIgnoreNA = NonZeroTime(m->timenow + 2 * mDNSPlatformOneSecond);
10811
10812 LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
10813
10814 for (q = m->Questions; q; q=q->next) // Scan our list of questions
10815 if (mDNSOpaque16IsZero(q->TargetQID))
10816 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
10817 { // then reactivate this question
10818 // If flapping, delay between first and second queries is nine seconds instead of one second
10819 mDNSBool dodelay = flapping && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
10820 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
10821 mDNSs32 qdelay = dodelay ? mDNSPlatformOneSecond * 5 : 0;
10822 if (dodelay) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q->qname.c, DNSTypeName(q->qtype));
10823
10824 if (!q->ThisQInterval || q->ThisQInterval > initial)
10825 {
10826 q->ThisQInterval = initial;
10827 q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
10828 }
10829 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
10830 q->RecentAnswerPkts = 0;
10831 SetNextQueryTime(m,q);
10832 }
10833
10834 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
10835 // we now need them to re-probe if necessary, and then re-announce.
10836 for (rr = m->ResourceRecords; rr; rr=rr->next)
10837 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
10838 mDNSCoreRestartRegistration(m, rr, numannounce);
10839 }
10840
10841 RestartRecordGetZoneData(m);
10842
10843 CheckSuppressUnusableQuestions(m);
10844
10845 mDNS_UpdateAllowSleep(m);
10846
10847 mDNS_Unlock(m);
10848 return(mStatus_NoError);
10849 }
10850
10851 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
10852 // the record list and/or question list.
10853 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
10854 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
10855 {
10856 NetworkInterfaceInfo **p = &m->HostInterfaces;
10857 mDNSBool revalidate = mDNSfalse;
10858
10859 mDNS_Lock(m);
10860
10861 // Find this record in our list
10862 while (*p && *p != set) p=&(*p)->next;
10863 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
10864
10865 mDNS_DeactivateNetWake_internal(m, set);
10866
10867 // Unlink this record from our list
10868 *p = (*p)->next;
10869 set->next = mDNSNULL;
10870
10871 if (!set->InterfaceActive)
10872 {
10873 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
10874 NetworkInterfaceInfo *intf;
10875 for (intf = m->HostInterfaces; intf; intf = intf->next)
10876 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
10877 UpdateInterfaceProtocols(m, intf);
10878 }
10879 else
10880 {
10881 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, set->InterfaceID);
10882 if (intf)
10883 {
10884 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
10885 " making it active", set->InterfaceID, set->ifname, &set->ip);
10886 if (intf->InterfaceActive)
10887 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
10888 intf->InterfaceActive = mDNStrue;
10889 UpdateInterfaceProtocols(m, intf);
10890
10891 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
10892
10893 // See if another representative *of the same type* exists. If not, we mave have gone from
10894 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
10895 for (intf = m->HostInterfaces; intf; intf = intf->next)
10896 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
10897 break;
10898 if (!intf) revalidate = mDNStrue;
10899 }
10900 else
10901 {
10902 mDNSu32 slot;
10903 CacheGroup *cg;
10904 CacheRecord *rr;
10905 DNSQuestion *q;
10906 DNSServer *s;
10907
10908 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
10909 " marking questions etc. dormant", set->InterfaceID, set->ifname, &set->ip);
10910
10911 if (set->McastTxRx && flapping)
10912 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
10913
10914 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
10915 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
10916 for (q = m->Questions; q; q=q->next)
10917 {
10918 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
10919 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
10920 {
10921 q->FlappingInterface2 = q->FlappingInterface1;
10922 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
10923 }
10924 }
10925
10926 // 2. Flush any cache records received on this interface
10927 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
10928 FORALL_CACHERECORDS(slot, cg, rr)
10929 {
10930 if (rr->resrec.InterfaceID == set->InterfaceID)
10931 {
10932 // If this interface is deemed flapping,
10933 // postpone deleting the cache records in case the interface comes back again
10934 if (set->McastTxRx && flapping)
10935 {
10936 // For a flapping interface we want these record to go away after 30 seconds
10937 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
10938 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
10939 // if the interface does come back, any relevant questions will be reactivated anyway
10940 rr->UnansweredQueries = MaxUnansweredQueries;
10941 }
10942 else
10943 {
10944 mDNS_PurgeCacheResourceRecord(m, rr);
10945 }
10946 }
10947 }
10948
10949 // 3. Any DNS servers specific to this interface are now unusable
10950 for (s = m->DNSServers; s; s = s->next)
10951 if (s->interface == set->InterfaceID)
10952 {
10953 s->interface = mDNSInterface_Any;
10954 s->teststate = DNSServer_Disabled;
10955 }
10956 }
10957 }
10958
10959 // If we were advertising on this interface, deregister those address and reverse-lookup records now
10960 if (set->Advertise) DeadvertiseInterface(m, set);
10961
10962 // If we have any cache records received on this interface that went away, then re-verify them.
10963 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
10964 // giving the false impression that there's an active representative of this interface when there really isn't.
10965 // Don't need to do this when shutting down, because *all* interfaces are about to go away
10966 if (revalidate && !m->ShutdownTime)
10967 {
10968 mDNSu32 slot;
10969 CacheGroup *cg;
10970 CacheRecord *rr;
10971 FORALL_CACHERECORDS(slot, cg, rr)
10972 if (rr->resrec.InterfaceID == set->InterfaceID)
10973 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
10974 }
10975
10976 CheckSuppressUnusableQuestions(m);
10977
10978 mDNS_UpdateAllowSleep(m);
10979
10980 mDNS_Unlock(m);
10981 }
10982
10983 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
10984 {
10985 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
10986 (void)m; // Unused parameter
10987
10988 #if MDNS_DEBUGMSGS
10989 {
10990 char *msg = "Unknown result";
10991 if (result == mStatus_NoError) msg = "Name Registered";
10992 else if (result == mStatus_NameConflict) msg = "Name Conflict";
10993 else if (result == mStatus_MemFree) msg = "Memory Free";
10994 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
10995 }
10996 #endif
10997
10998 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
10999 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
11000
11001 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
11002 if (result == mStatus_NameConflict)
11003 {
11004 sr->Conflict = mDNStrue; // Record that this service set had a conflict
11005 mDNS_DeregisterService(m, sr); // Unlink the records from our list
11006 return;
11007 }
11008
11009 if (result == mStatus_MemFree)
11010 {
11011 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
11012 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
11013 // every record is finished cleaning up.
11014 mDNSu32 i;
11015 ExtraResourceRecord *e = sr->Extras;
11016
11017 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
11018 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
11019 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
11020 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
11021 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
11022
11023 while (e)
11024 {
11025 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
11026 e = e->next;
11027 }
11028
11029 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
11030 // then we can now report the NameConflict to the client
11031 if (sr->Conflict) result = mStatus_NameConflict;
11032
11033 }
11034
11035 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
11036 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
11037 // function is allowed to do anything, including deregistering this service and freeing its memory.
11038 if (sr->ServiceCallback)
11039 sr->ServiceCallback(m, sr, result);
11040 }
11041
11042 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
11043 {
11044 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
11045 if (sr->ServiceCallback)
11046 sr->ServiceCallback(m, sr, result);
11047 }
11048
11049
11050 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
11051 {
11052 AuthRecType artype;
11053
11054 if (InterfaceID == mDNSInterface_LocalOnly)
11055 artype = AuthRecordLocalOnly;
11056 else if (InterfaceID == mDNSInterface_P2P)
11057 artype = AuthRecordP2P;
11058 else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeP2P))
11059 artype = AuthRecordAnyIncludeP2P;
11060 else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeAWDL))
11061 artype = AuthRecordAnyIncludeAWDL;
11062 else
11063 artype = AuthRecordAny;
11064
11065 return artype;
11066 }
11067
11068 // Note:
11069 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
11070 // Type is service type (e.g. "_ipp._tcp.")
11071 // Domain is fully qualified domain name (i.e. ending with a null label)
11072 // We always register a TXT, even if it is empty (so that clients are not
11073 // left waiting forever looking for a nonexistent record.)
11074 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
11075 // then the default host name (m->MulticastHostname) is automatically used
11076 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
11077 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
11078 const domainlabel *const name, const domainname *const type, const domainname *const domain,
11079 const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
11080 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
11081 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
11082 {
11083 mStatus err;
11084 mDNSu32 i;
11085 mDNSu32 hostTTL;
11086 AuthRecType artype;
11087 mDNSu8 recordType = (flags & coreFlagKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
11088
11089 sr->ServiceCallback = Callback;
11090 sr->ServiceContext = Context;
11091 sr->Conflict = mDNSfalse;
11092
11093 sr->Extras = mDNSNULL;
11094 sr->NumSubTypes = NumSubTypes;
11095 sr->SubTypes = SubTypes;
11096
11097 artype = setAuthRecType(InterfaceID, flags);
11098
11099 // Initialize the AuthRecord objects to sane values
11100 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
11101 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
11102 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
11103
11104 if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
11105 hostTTL = kHostNameSmallTTL;
11106 else
11107 hostTTL = kHostNameTTL;
11108
11109 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
11110 mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
11111
11112 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
11113 if (mDNSIPPortIsZero(port))
11114 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
11115
11116 // If the client is registering an oversized TXT record,
11117 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
11118 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
11119 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
11120
11121 // Set up the record names
11122 // For now we only create an advisory record for the main type, not for subtypes
11123 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
11124 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
11125 return(mStatus_BadParamErr);
11126 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
11127 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
11128 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
11129
11130 // 1. Set up the ADV record rdata to advertise our service type
11131 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
11132
11133 // 2. Set up the PTR record rdata to point to our service name
11134 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
11135 // Note: uDNS registration code assumes that Additional1 points to the SRV record
11136 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
11137 sr->RR_PTR.Additional1 = &sr->RR_SRV;
11138 sr->RR_PTR.Additional2 = &sr->RR_TXT;
11139
11140 // 2a. Set up any subtype PTRs to point to our service name
11141 // If the client is using subtypes, it is the client's responsibility to have
11142 // already set the first label of the record name to the subtype being registered
11143 for (i=0; i<NumSubTypes; i++)
11144 {
11145 domainname st;
11146 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
11147 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
11148 AppendDomainName(&st, type);
11149 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
11150 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
11151 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
11152 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
11153 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
11154 }
11155
11156 // 3. Set up the SRV record rdata.
11157 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
11158 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
11159 sr->RR_SRV.resrec.rdata->u.srv.port = port;
11160
11161 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
11162 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
11163 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
11164
11165 // 4. Set up the TXT record rdata,
11166 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
11167 // Note: uDNS registration code assumes that DependentOn points to the SRV record
11168 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
11169 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
11170 {
11171 sr->RR_TXT.resrec.rdlength = txtlen;
11172 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
11173 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
11174 }
11175 sr->RR_TXT.DependentOn = &sr->RR_SRV;
11176
11177 mDNS_Lock(m);
11178 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
11179 // that if the SRV cannot find a target, rest of the records that belong to this service
11180 // will not be activated.
11181 err = mDNS_Register_internal(m, &sr->RR_SRV);
11182 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
11183 // any list and hence no need to deregister. We could probably do similar checks for other
11184 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
11185 if (err)
11186 {
11187 mDNS_Unlock(m);
11188 return err;
11189 }
11190 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
11191 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
11192 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
11193 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
11194 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
11195 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
11196 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
11197 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
11198 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
11199
11200 mDNS_Unlock(m);
11201
11202 if (err) mDNS_DeregisterService(m, sr);
11203 return(err);
11204 }
11205
11206 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
11207 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags)
11208 {
11209 ExtraResourceRecord **e;
11210 mStatus status;
11211 AuthRecType artype;
11212 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
11213
11214 artype = setAuthRecType(InterfaceID, flags);
11215
11216 extra->next = mDNSNULL;
11217 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
11218 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
11219 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
11220
11221 mDNS_Lock(m);
11222 e = &sr->Extras;
11223 while (*e) e = &(*e)->next;
11224
11225 if (ttl == 0) ttl = kStandardTTL;
11226
11227 extra->r.DependentOn = &sr->RR_SRV;
11228
11229 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
11230 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
11231
11232 status = mDNS_Register_internal(m, &extra->r);
11233 if (status == mStatus_NoError) *e = extra;
11234
11235 mDNS_Unlock(m);
11236 return(status);
11237 }
11238
11239 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
11240 mDNSRecordCallback MemFreeCallback, void *Context)
11241 {
11242 ExtraResourceRecord **e;
11243 mStatus status;
11244
11245 mDNS_Lock(m);
11246 e = &sr->Extras;
11247 while (*e && *e != extra) e = &(*e)->next;
11248 if (!*e)
11249 {
11250 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
11251 status = mStatus_BadReferenceErr;
11252 }
11253 else
11254 {
11255 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
11256 extra->r.RecordCallback = MemFreeCallback;
11257 extra->r.RecordContext = Context;
11258 *e = (*e)->next;
11259 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
11260 }
11261 mDNS_Unlock(m);
11262 return(status);
11263 }
11264
11265 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
11266 {
11267 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
11268 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
11269 domainlabel name1, name2;
11270 domainname type, domain;
11271 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
11272 ExtraResourceRecord *extras = sr->Extras;
11273 mStatus err;
11274
11275 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
11276 if (!newname)
11277 {
11278 name2 = name1;
11279 IncrementLabelSuffix(&name2, mDNStrue);
11280 newname = &name2;
11281 }
11282
11283 if (SameDomainName(&domain, &localdomain))
11284 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
11285 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
11286
11287 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
11288 host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
11289 sr->SubTypes, sr->NumSubTypes,
11290 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, 0);
11291
11292 // mDNS_RegisterService() just reset sr->Extras to NULL.
11293 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
11294 // through the old list of extra records, and re-add them to our freshly created service registration
11295 while (!err && extras)
11296 {
11297 ExtraResourceRecord *e = extras;
11298 extras = extras->next;
11299 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
11300 }
11301
11302 return(err);
11303 }
11304
11305 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
11306 // which may change the record list and/or question list.
11307 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
11308 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
11309 {
11310 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
11311 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
11312
11313 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
11314 {
11315 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
11316 return(mStatus_BadReferenceErr);
11317 }
11318 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
11319 {
11320 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
11321 // Avoid race condition:
11322 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
11323 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
11324 // If the client happens to deregister the service in the middle of that process, then
11325 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
11326 // instead of incorrectly promoting it to mStatus_NameConflict.
11327 // This race condition is exposed particularly when the conformance test generates
11328 // a whole batch of simultaneous conflicts across a range of services all advertised
11329 // using the same system default name, and if we don't take this precaution then
11330 // we end up incrementing m->nicelabel multiple times instead of just once.
11331 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
11332 sr->Conflict = mDNSfalse;
11333 return(mStatus_NoError);
11334 }
11335 else
11336 {
11337 mDNSu32 i;
11338 mStatus status;
11339 ExtraResourceRecord *e;
11340 mDNS_Lock(m);
11341 e = sr->Extras;
11342
11343 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
11344 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
11345 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
11346 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
11347
11348 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
11349
11350 // We deregister all of the extra records, but we leave the sr->Extras list intact
11351 // in case the client wants to do a RenameAndReregister and reinstate the registration
11352 while (e)
11353 {
11354 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
11355 e = e->next;
11356 }
11357
11358 for (i=0; i<sr->NumSubTypes; i++)
11359 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
11360
11361 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
11362 mDNS_Unlock(m);
11363 return(status);
11364 }
11365 }
11366
11367 // Create a registration that asserts that no such service exists with this name.
11368 // This can be useful where there is a given function is available through several protocols.
11369 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
11370 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
11371 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
11372 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
11373 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
11374 const domainlabel *const name, const domainname *const type, const domainname *const domain,
11375 const domainname *const host,
11376 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
11377 {
11378 AuthRecType artype;
11379
11380 artype = setAuthRecType(InterfaceID, flags);
11381
11382 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
11383 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
11384 rr->resrec.rdata->u.srv.priority = 0;
11385 rr->resrec.rdata->u.srv.weight = 0;
11386 rr->resrec.rdata->u.srv.port = zeroIPPort;
11387 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
11388 else rr->AutoTarget = Target_AutoHost;
11389 return(mDNS_Register(m, rr));
11390 }
11391
11392 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
11393 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
11394 {
11395 AuthRecType artype;
11396
11397 if (InterfaceID == mDNSInterface_LocalOnly)
11398 artype = AuthRecordLocalOnly;
11399 else if (InterfaceID == mDNSInterface_P2P)
11400 artype = AuthRecordP2P;
11401 else
11402 artype = AuthRecordAny;
11403 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
11404 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
11405 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
11406 return(mDNS_Register(m, rr));
11407 }
11408
11409 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
11410 {
11411 AuthRecord *r;
11412 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
11413 return mDNSfalse;
11414 }
11415
11416 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
11417 {
11418 DNSQuestion *q;
11419 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
11420 return mDNSfalse;
11421 }
11422
11423 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
11424 {
11425 mDNSOpaque16 id;
11426 int i;
11427
11428 for (i=0; i<10; i++)
11429 {
11430 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
11431 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
11432 }
11433
11434 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
11435
11436 return id;
11437 }
11438
11439 // ***************************************************************************
11440 #if COMPILER_LIKES_PRAGMA_MARK
11441 #pragma mark -
11442 #pragma mark - Sleep Proxy Server
11443 #endif
11444
11445 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
11446 {
11447 // If we see an ARP from a machine we think is sleeping, then either
11448 // (i) the machine has woken, or
11449 // (ii) it's just a stray old packet from before the machine slept
11450 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
11451 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
11452 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
11453 // 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*
11454 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
11455 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
11456
11457 rr->resrec.RecordType = kDNSRecordTypeUnique;
11458 rr->ProbeCount = DefaultProbeCountForTypeUnique;
11459
11460 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
11461 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
11462 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
11463 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
11464 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
11465 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
11466 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
11467 InitializeLastAPTime(m, rr);
11468 else
11469 {
11470 rr->AnnounceCount = InitialAnnounceCount;
11471 rr->ThisAPInterval = mDNSPlatformOneSecond;
11472 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
11473 SetNextAnnounceProbeTime(m, rr);
11474 }
11475 }
11476
11477 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
11478 {
11479 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
11480 AuthRecord *rr;
11481 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
11482 if (!intf) return;
11483
11484 mDNS_Lock(m);
11485
11486 // Pass 1:
11487 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
11488 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
11489 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
11490 // The times we might need to react to an ARP Announcement are:
11491 // (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
11492 // (ii) if it's a conflicting Announcement from another host
11493 // -- and we check for these in Pass 2 below.
11494 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
11495 {
11496 for (rr = m->ResourceRecords; rr; rr=rr->next)
11497 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
11498 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
11499 {
11500 static const char msg1[] = "ARP Req from owner -- re-probing";
11501 static const char msg2[] = "Ignoring ARP Request from ";
11502 static const char msg3[] = "Creating Local ARP Cache entry ";
11503 static const char msg4[] = "Answering ARP Request from ";
11504 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
11505 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
11506 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
11507 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
11508 intf->ifname, msg, &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
11509 if (msg == msg1) RestartARPProbing(m, rr);
11510 else if (msg == msg3) mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
11511 else if (msg == msg4) SendARP(m, 2, rr, &arp->tpa, &arp->sha, &arp->spa, &arp->sha);
11512 }
11513 }
11514
11515 // Pass 2:
11516 // 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.
11517 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
11518 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
11519 // 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.
11520 // If we see an apparently conflicting ARP, we check the sender hardware address:
11521 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
11522 // 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.
11523 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
11524 debugf("ARP from self for %.4a", &arp->tpa);
11525 else
11526 {
11527 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
11528 for (rr = m->ResourceRecords; rr; rr=rr->next)
11529 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
11530 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa))
11531 {
11532 RestartARPProbing(m, rr);
11533 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
11534 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
11535 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
11536 &arp->sha, &arp->spa, &arp->tpa, ARDisplayString(m, rr));
11537 else
11538 {
11539 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
11540 &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
11541 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
11542 }
11543 }
11544 }
11545
11546 mDNS_Unlock(m);
11547 }
11548
11549 /*
11550 // Option 1 is Source Link Layer Address Option
11551 // Option 2 is Target Link Layer Address Option
11552 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
11553 {
11554 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
11555 while (options < end)
11556 {
11557 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
11558 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
11559 options += options[1] * 8;
11560 }
11561 return mDNSNULL;
11562 }
11563 */
11564
11565 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
11566 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
11567 {
11568 AuthRecord *rr;
11569 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
11570 if (!intf) return;
11571
11572 mDNS_Lock(m);
11573
11574 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
11575 if (ndp->type == NDP_Sol)
11576 {
11577 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
11578 (void)end;
11579 for (rr = m->ResourceRecords; rr; rr=rr->next)
11580 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
11581 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
11582 {
11583 static const char msg1[] = "NDP Req from owner -- re-probing";
11584 static const char msg2[] = "Ignoring NDP Request from ";
11585 static const char msg3[] = "Creating Local NDP Cache entry ";
11586 static const char msg4[] = "Answering NDP Request from ";
11587 static const char msg5[] = "Answering NDP Probe from ";
11588 const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
11589 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
11590 sha && mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
11591 spa && mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
11592 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
11593 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
11594 if (msg == msg1) RestartARPProbing(m, rr);
11595 else if (msg == msg3)
11596 {
11597 if (!(m->KnownBugs & mDNS_KnownBug_LimitedIPv6))
11598 mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
11599 }
11600 else if (msg == msg4) SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha );
11601 else if (msg == msg5) SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
11602 }
11603 }
11604
11605 // 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.
11606 if (mDNSSameEthAddress(sha, &intf->MAC))
11607 debugf("NDP from self for %.16a", &ndp->target);
11608 else
11609 {
11610 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
11611 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
11612 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
11613 // Hence it is the NDP target address we care about, not the actual packet source address.
11614 if (ndp->type == NDP_Adv) spa = &ndp->target;
11615 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
11616 for (rr = m->ResourceRecords; rr; rr=rr->next)
11617 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
11618 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa))
11619 {
11620 RestartARPProbing(m, rr);
11621 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
11622 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
11623 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
11624 else
11625 {
11626 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
11627 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
11628 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
11629 }
11630 }
11631 }
11632
11633 mDNS_Unlock(m);
11634 }
11635
11636 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
11637 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
11638 {
11639 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
11640 mDNSBool wake = mDNSfalse;
11641 mDNSBool kaWake = mDNSfalse;
11642
11643 switch (protocol)
11644 {
11645 #define XX wake ? "Received" : "Ignoring", end-p
11646 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
11647 break;
11648
11649 case 0x06: {
11650 AuthRecord *kr;
11651 mDNSu32 seq, ack;
11652 #define TH_FIN 0x01
11653 #define TH_SYN 0x02
11654 #define TH_RST 0x04
11655
11656 kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
11657 if (kr)
11658 {
11659 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
11660 // Plan to wake if
11661 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
11662 // (b) packet that contains new data and acks a sequence number higher than the one
11663 // we have been sending in the keepalive
11664
11665 wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
11666 if (!wake)
11667 {
11668 mDNSu8 *ptr;
11669 mDNSu32 pseq, pack;
11670 mDNSBool data = mDNSfalse;
11671 mDNSu8 tcphlen;
11672
11673 // Convert to host order
11674 ptr = (mDNSu8 *)&seq;
11675 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
11676
11677 ptr = (mDNSu8 *)&ack;
11678 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
11679
11680 pseq = t->tcp.seq;
11681 ptr = (mDNSu8 *)&pseq;
11682 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
11683
11684 pack = t->tcp.ack;
11685 ptr = (mDNSu8 *)&pack;
11686 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
11687
11688 // If the other side is acking one more than our sequence number (keepalive is one
11689 // less than the last valid sequence sent) and it's sequence is more than what we
11690 // acked before
11691 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
11692 tcphlen = ((t->tcp.offset >> 4) * 4);
11693 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
11694 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
11695 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
11696 end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
11697 }
11698 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
11699 kaWake = wake;
11700 }
11701 else
11702 {
11703
11704 // Plan to wake if
11705 // (a) RST is not set, AND
11706 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
11707 wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
11708
11709 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
11710 // except for ssh connections, where we'll wake for plain data packets too
11711 if (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
11712
11713 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
11714 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
11715 (t->tcp.flags & 2) ? " SYN" : "",
11716 (t->tcp.flags & 1) ? " FIN" : "",
11717 (t->tcp.flags & 4) ? " RST" : "");
11718 }
11719 break;
11720 }
11721
11722 case 0x11: {
11723 #define ARD_AsNumber 3283
11724 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
11725 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
11726 if (udplen >= sizeof(UDPHeader))
11727 {
11728 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
11729 wake = mDNStrue;
11730
11731 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
11732 if (mDNSSameIPPort(port, IPSECPort))
11733 {
11734 // Specifically ignore NAT keepalive packets
11735 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
11736 else
11737 {
11738 // Skip over the Non-ESP Marker if present
11739 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
11740 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
11741 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
11742 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
11743 if ((ike->Version & 0x10) == 0x10)
11744 {
11745 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
11746 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
11747 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
11748 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
11749 }
11750 }
11751 }
11752
11753 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
11754 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
11755 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
11756 // UDP header (8 bytes)
11757 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
11758 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
11759
11760 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
11761 }
11762 }
11763 break;
11764
11765 case 0x3A: if (&t->bytes[len] <= end)
11766 {
11767 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
11768 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
11769 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
11770 }
11771 break;
11772
11773 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
11774 break;
11775 }
11776
11777 if (wake)
11778 {
11779 AuthRecord *rr, *r2;
11780
11781 mDNS_Lock(m);
11782 for (rr = m->ResourceRecords; rr; rr=rr->next)
11783 if (rr->resrec.InterfaceID == InterfaceID &&
11784 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
11785 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
11786 {
11787 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
11788 for (r2 = m->ResourceRecords; r2; r2=r2->next)
11789 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
11790 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
11791 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
11792 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
11793 break;
11794 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
11795 if (!r2 && kaWake) r2 = rr; // So that we wake for keepalive packets, even without a matching SRV record
11796 if (r2)
11797 {
11798 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
11799 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
11800 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
11801 }
11802 else
11803 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
11804 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
11805 }
11806 mDNS_Unlock(m);
11807 }
11808 }
11809
11810 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
11811 {
11812 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
11813 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
11814 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
11815 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
11816 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
11817
11818 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
11819 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
11820 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
11821 // since it points to a an address 14 bytes before pkt.
11822 const EthernetHeader *const eth = (const EthernetHeader *)p;
11823 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
11824 mDNSAddr src, dst;
11825 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
11826
11827 // Is ARP? Length must be at least 14 + 28 = 42 bytes
11828 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
11829 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
11830 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
11831 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
11832 {
11833 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
11834 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
11835 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
11836 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
11837 if (end >= trans + RequiredCapLen(pkt->v4.protocol))
11838 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, end, InterfaceID, 0);
11839 }
11840 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
11841 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
11842 {
11843 const mDNSu8 *const trans = p + 54;
11844 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
11845 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
11846 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
11847 if (end >= trans + RequiredCapLen(pkt->v6.pro))
11848 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
11849 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
11850 }
11851 }
11852
11853 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
11854 {
11855 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
11856 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
11857 }
11858
11859 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
11860 {
11861 if (result == mStatus_NameConflict)
11862 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
11863 else if (result == mStatus_MemFree)
11864 {
11865 if (m->SleepState)
11866 m->SPSState = 3;
11867 else
11868 {
11869 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
11870 if (m->SPSState)
11871 {
11872 domainlabel name;
11873 ConstructSleepProxyServerName(m, &name);
11874 mDNS_RegisterService(m, srs,
11875 &name, &SleepProxyServiceType, &localdomain,
11876 mDNSNULL, m->SPSSocket->port, // Host, port
11877 (mDNSu8 *)"", 1, // TXT data, length
11878 mDNSNULL, 0, // Subtypes (none)
11879 mDNSInterface_Any, // Interface ID
11880 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
11881 }
11882 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
11883 }
11884 }
11885 }
11886
11887 // Called with lock held
11888 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
11889 {
11890 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
11891 mDNS_DropLockBeforeCallback();
11892
11893 // If turning off SPS, close our socket
11894 // (Do this first, BEFORE calling mDNS_DeregisterService below)
11895 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
11896
11897 // If turning off, or changing type, deregister old name
11898 if (m->SPSState == 1 && sps != m->SPSType)
11899 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
11900
11901 // Record our new SPS parameters
11902 m->SPSType = sps;
11903 m->SPSPortability = port;
11904 m->SPSMarginalPower = marginalpower;
11905 m->SPSTotalPower = totpower;
11906 m->SPSFeatureFlags = features;
11907 // If turning on, open socket and advertise service
11908 if (sps)
11909 {
11910 if (!m->SPSSocket)
11911 {
11912 m->SPSSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
11913 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
11914 }
11915 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
11916 }
11917 else if (m->SPSState)
11918 {
11919 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
11920 m->NextScheduledSPS = m->timenow;
11921 }
11922 fail:
11923 mDNS_ReclaimLockAfterCallback();
11924 }
11925
11926 // ***************************************************************************
11927 #if COMPILER_LIKES_PRAGMA_MARK
11928 #pragma mark -
11929 #pragma mark - Startup and Shutdown
11930 #endif
11931
11932 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
11933 {
11934 if (storage && numrecords)
11935 {
11936 mDNSu32 i;
11937 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
11938 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
11939 storage[numrecords-1].next = m->rrcache_free;
11940 m->rrcache_free = storage;
11941 m->rrcache_size += numrecords;
11942 }
11943 }
11944
11945 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
11946 {
11947 mDNS_Lock(m);
11948 mDNS_GrowCache_internal(m, storage, numrecords);
11949 mDNS_Unlock(m);
11950 }
11951
11952 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
11953 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
11954 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
11955 {
11956 mDNSu32 slot;
11957 mDNSs32 timenow;
11958 mStatus result;
11959
11960 if (!rrcachestorage) rrcachesize = 0;
11961
11962 m->p = p;
11963 m->KnownBugs = 0;
11964 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
11965 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
11966 m->DivertMulticastAdvertisements = mDNSfalse;
11967 m->mDNSPlatformStatus = mStatus_Waiting;
11968 m->UnicastPort4 = zeroIPPort;
11969 m->UnicastPort6 = zeroIPPort;
11970 m->PrimaryMAC = zeroEthAddr;
11971 m->MainCallback = Callback;
11972 m->MainContext = Context;
11973 m->rec.r.resrec.RecordType = 0;
11974
11975 // For debugging: To catch and report locking failures
11976 m->mDNS_busy = 0;
11977 m->mDNS_reentrancy = 0;
11978 m->ShutdownTime = 0;
11979 m->lock_rrcache = 0;
11980 m->lock_Questions = 0;
11981 m->lock_Records = 0;
11982
11983 // Task Scheduling variables
11984 result = mDNSPlatformTimeInit();
11985 if (result != mStatus_NoError) return(result);
11986 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
11987 timenow = mDNS_TimeNow_NoLock(m);
11988
11989 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
11990 m->timenow_last = timenow;
11991 m->NextScheduledEvent = timenow;
11992 m->SuppressSending = timenow;
11993 m->NextCacheCheck = timenow + 0x78000000;
11994 m->NextScheduledQuery = timenow + 0x78000000;
11995 m->NextScheduledProbe = timenow + 0x78000000;
11996 m->NextScheduledResponse = timenow + 0x78000000;
11997 m->NextScheduledNATOp = timenow + 0x78000000;
11998 m->NextScheduledSPS = timenow + 0x78000000;
11999 m->NextScheduledKA = timenow + 0x78000000;
12000 m->NextScheduledStopTime = timenow + 0x78000000;
12001 m->RandomQueryDelay = 0;
12002 m->RandomReconfirmDelay = 0;
12003 m->PktNum = 0;
12004 m->LocalRemoveEvents = mDNSfalse;
12005 m->SleepState = SleepState_Awake;
12006 m->SleepSeqNum = 0;
12007 m->SystemWakeOnLANEnabled = mDNSfalse;
12008 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
12009 m->ClearSPSRecords = 0;
12010 m->clearIgnoreNA = NonZeroTime(timenow + 2 * mDNSPlatformOneSecond);
12011 m->DelaySleep = 0;
12012 m->SleepLimit = 0;
12013
12014 // These fields only required for mDNS Searcher...
12015 m->Questions = mDNSNULL;
12016 m->NewQuestions = mDNSNULL;
12017 m->CurrentQuestion = mDNSNULL;
12018 m->LocalOnlyQuestions = mDNSNULL;
12019 m->NewLocalOnlyQuestions = mDNSNULL;
12020 m->RestartQuestion = mDNSNULL;
12021 m->ValidationQuestion = mDNSNULL;
12022 m->rrcache_size = 0;
12023 m->rrcache_totalused = 0;
12024 m->rrcache_active = 0;
12025 m->rrcache_report = 10;
12026 m->rrcache_free = mDNSNULL;
12027
12028 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
12029 {
12030 m->rrcache_hash[slot] = mDNSNULL;
12031 m->rrcache_nextcheck[slot] = timenow + 0x78000000;;
12032 }
12033
12034 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
12035 m->rrauth.rrauth_free = mDNSNULL;
12036
12037 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
12038 m->rrauth.rrauth_hash[slot] = mDNSNULL;
12039
12040 // Fields below only required for mDNS Responder...
12041 m->hostlabel.c[0] = 0;
12042 m->nicelabel.c[0] = 0;
12043 m->MulticastHostname.c[0] = 0;
12044 m->HIHardware.c[0] = 0;
12045 m->HISoftware.c[0] = 0;
12046 m->ResourceRecords = mDNSNULL;
12047 m->DuplicateRecords = mDNSNULL;
12048 m->NewLocalRecords = mDNSNULL;
12049 m->NewLocalOnlyRecords = mDNSfalse;
12050 m->CurrentRecord = mDNSNULL;
12051 m->HostInterfaces = mDNSNULL;
12052 m->ProbeFailTime = 0;
12053 m->NumFailedProbes = 0;
12054 m->SuppressProbes = 0;
12055
12056 #ifndef UNICAST_DISABLED
12057 m->NextuDNSEvent = timenow + 0x78000000;
12058 m->NextSRVUpdate = timenow + 0x78000000;
12059
12060 m->DNSServers = mDNSNULL;
12061
12062 m->Router = zeroAddr;
12063 m->AdvertisedV4 = zeroAddr;
12064 m->AdvertisedV6 = zeroAddr;
12065
12066 m->AuthInfoList = mDNSNULL;
12067
12068 m->ReverseMap.ThisQInterval = -1;
12069 m->StaticHostname.c[0] = 0;
12070 m->FQDN.c[0] = 0;
12071 m->Hostnames = mDNSNULL;
12072 m->AutoTunnelNAT.clientContext = mDNSNULL;
12073
12074 m->StartWABQueries = mDNSfalse;
12075 m->mDNSHandlePeerEvents = mDNSfalse;
12076
12077 // NAT traversal fields
12078 m->NATTraversals = mDNSNULL;
12079 m->CurrentNATTraversal = mDNSNULL;
12080 m->retryIntervalGetAddr = 0; // delta between time sent and retry
12081 m->retryGetAddr = timenow + 0x78000000; // absolute time when we retry
12082 m->ExternalAddress = zerov4Addr;
12083
12084 m->NATMcastRecvskt = mDNSNULL;
12085 m->LastNATupseconds = 0;
12086 m->LastNATReplyLocalTime = timenow;
12087 m->LastNATMapResultCode = NATErr_None;
12088
12089 m->UPnPInterfaceID = 0;
12090 m->SSDPSocket = mDNSNULL;
12091 m->SSDPWANPPPConnection = mDNSfalse;
12092 m->UPnPRouterPort = zeroIPPort;
12093 m->UPnPSOAPPort = zeroIPPort;
12094 m->UPnPRouterURL = mDNSNULL;
12095 m->UPnPWANPPPConnection = mDNSfalse;
12096 m->UPnPSOAPURL = mDNSNULL;
12097 m->UPnPRouterAddressString = mDNSNULL;
12098 m->UPnPSOAPAddressString = mDNSNULL;
12099 m->SPSType = 0;
12100 m->SPSPortability = 0;
12101 m->SPSMarginalPower = 0;
12102 m->SPSTotalPower = 0;
12103 m->SPSFeatureFlags = 0;
12104 m->SPSState = 0;
12105 m->SPSProxyListChanged = mDNSNULL;
12106 m->SPSSocket = mDNSNULL;
12107 m->SPSBrowseCallback = mDNSNULL;
12108 m->ProxyRecords = 0;
12109
12110 #endif
12111
12112 #if APPLE_OSX_mDNSResponder
12113 m->TunnelClients = mDNSNULL;
12114
12115 #if !NO_WCF
12116 CHECK_WCF_FUNCTION(WCFConnectionNew)
12117 {
12118 m->WCF = WCFConnectionNew();
12119 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
12120 }
12121 #endif
12122
12123 #endif
12124
12125 result = mDNSPlatformInit(m);
12126
12127 #ifndef UNICAST_DISABLED
12128 // It's better to do this *after* the platform layer has set up the
12129 // interface list and security credentials
12130 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
12131 #endif
12132
12133 return(result);
12134 }
12135
12136 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
12137 {
12138 if (m->SPSState == 1)
12139 {
12140 domainlabel name, newname;
12141 domainname type, domain;
12142 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
12143 ConstructSleepProxyServerName(m, &newname);
12144 if (!SameDomainLabelCS(name.c, newname.c))
12145 {
12146 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
12147 // When SleepProxyServerCallback gets the mStatus_MemFree message,
12148 // it will reregister the service under the new name
12149 m->SPSState = 2;
12150 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
12151 }
12152 }
12153
12154 if (m->MainCallback)
12155 m->MainCallback(m, mStatus_ConfigChanged);
12156 }
12157
12158 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12159 {
12160 (void)m; // unused
12161 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
12162 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
12163 }
12164
12165 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
12166 {
12167 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
12168 cr->resrec.rrtype == kDNSType_A ||
12169 cr->resrec.rrtype == kDNSType_AAAA ||
12170 cr->resrec.rrtype == kDNSType_SRV;
12171
12172 (void) lameduck;
12173 (void) ptr;
12174 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
12175 purge ? "purging" : "reconfirming",
12176 lameduck ? "lame duck" : "new",
12177 ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
12178
12179 if (purge)
12180 {
12181 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
12182 mDNS_PurgeCacheResourceRecord(m, cr);
12183 }
12184 else
12185 {
12186 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
12187 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12188 }
12189 }
12190
12191 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
12192 {
12193 const mDNSu32 slot = HashSlot(&q->qname);
12194 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
12195 CacheRecord *rp;
12196
12197 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
12198 {
12199 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
12200 {
12201 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
12202 mDNS_PurgeCacheResourceRecord(m, rp);
12203 }
12204 }
12205 }
12206
12207 // If we need to validate the negative response, we need the NSECs to prove
12208 // the non-existence. If we don't have the cached NSECs, purge them so that
12209 // we can reissue the question with EDNS0/DO bit set.
12210 mDNSlocal void mDNS_CheckForCachedNSECS(mDNS *const m, DNSQuestion *q)
12211 {
12212 const mDNSu32 slot = HashSlot(&q->qname);
12213 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
12214 CacheRecord *rp;
12215
12216 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
12217 {
12218 if (SameNameRecordAnswersQuestion(&rp->resrec, q) &&
12219 rp->resrec.RecordType == kDNSRecordTypePacketNegative &&
12220 !rp->nsec)
12221 {
12222 LogInfo("mDNS_CheckForCachedNSECS: Flushing %s", CRDisplayString(m, rp));
12223 mDNS_PurgeCacheResourceRecord(m, rp);
12224 }
12225 }
12226 }
12227
12228 // Check for a positive unicast response to the question but with qtype
12229 mDNSexport mDNSBool mDNS_CheckForCacheRecord(mDNS *const m, DNSQuestion *q, mDNSu16 qtype)
12230 {
12231 DNSQuestion question;
12232 const mDNSu32 slot = HashSlot(&q->qname);
12233 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
12234 CacheRecord *rp;
12235
12236 // Create an identical question but with qtype
12237 mDNS_SetupQuestion(&question, q->InterfaceID, &q->qname, qtype, mDNSNULL, mDNSNULL);
12238 question.qDNSServer = q->qDNSServer;
12239
12240 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
12241 {
12242 if (!rp->resrec.InterfaceID && rp->resrec.RecordType != kDNSRecordTypePacketNegative &&
12243 SameNameRecordAnswersQuestion(&rp->resrec, &question))
12244 {
12245 LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m, rp));
12246 return mDNStrue;
12247 }
12248 }
12249 return mDNSfalse;
12250 }
12251
12252 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
12253 {
12254 DNSQuestion *qptr;
12255
12256 (void) m;
12257
12258 if (q->DuplicateOf)
12259 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
12260
12261 // Make sure all the duplicate questions point to the same DNSServer so that delivery
12262 // of events for all of them are consistent. Duplicates for a question are always inserted
12263 // after in the list.
12264 q->qDNSServer = new;
12265 for (qptr = q->next ; qptr; qptr = qptr->next)
12266 {
12267 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
12268 }
12269 }
12270
12271 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
12272 {
12273 mDNSu32 slot;
12274 CacheGroup *cg;
12275 CacheRecord *cr;
12276
12277 mDNSAddr v4, v6, r;
12278 domainname fqdn;
12279 DNSServer *ptr, **p = &m->DNSServers;
12280 const DNSServer *oldServers = m->DNSServers;
12281 DNSQuestion *q;
12282 McastResolver *mr, **mres = &m->McastResolvers;
12283
12284 debugf("uDNS_SetupDNSConfig: entry");
12285
12286 // Let the platform layer get the current DNS information
12287 // The m->StartWABQueries is set when we get the first domain enumeration query (no need to hit the network
12288 // with domain enumeration queries until we actually need that information). Even if it is not set, we still
12289 // need to setup the search domains so that we can append them to queries that need them.
12290
12291 uDNS_SetupSearchDomains(m, m->StartWABQueries ? UDNS_START_WAB_QUERY : 0);
12292
12293 mDNS_Lock(m);
12294
12295 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
12296 {
12297 ptr->penaltyTime = 0;
12298 ptr->flags |= DNSServer_FlagDelete;
12299 }
12300
12301 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
12302 // mcast resolvers. Today we get both mcast and ucast configuration using the same
12303 // API
12304 for (mr = m->McastResolvers; mr; mr = mr->next)
12305 mr->flags |= McastResolver_FlagDelete;
12306
12307 mDNSPlatformSetDNSConfig(m, mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL);
12308
12309 // For now, we just delete the mcast resolvers. We don't deal with cache or
12310 // questions here. Neither question nor cache point to mcast resolvers. Questions
12311 // do inherit the timeout values from mcast resolvers. But we don't bother
12312 // affecting them as they never change.
12313 while (*mres)
12314 {
12315 if (((*mres)->flags & DNSServer_FlagDelete) != 0)
12316 {
12317 mr = *mres;
12318 *mres = (*mres)->next;
12319 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
12320 mDNSPlatformMemFree(mr);
12321 }
12322 else
12323 {
12324 (*mres)->flags &= ~McastResolver_FlagNew;
12325 mres = &(*mres)->next;
12326 }
12327 }
12328
12329 // Update our qDNSServer pointers before we go and free the DNSServer object memory
12330 //
12331 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
12332 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
12333 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
12334 // DNSServers and flush the cache.
12335 //
12336 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
12337 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
12338 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
12339 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
12340 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
12341 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
12342 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
12343 // the same resGroupID.
12344 //
12345 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
12346 // of the old followed by ADD of the new records.
12347 //
12348 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
12349 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
12350 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
12351 //
12352 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
12353 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
12354 // non-scoped question and vice versa.
12355 //
12356 for (q = m->Questions; q; q=q->next)
12357 if (!mDNSOpaque16IsZero(q->TargetQID))
12358 {
12359 DNSServer *s, *t;
12360 DNSQuestion *qptr;
12361 if (q->DuplicateOf) continue;
12362 SetValidDNSServers(m, q);
12363 q->triedAllServersOnce = 0;
12364 s = GetServerForQuestion(m, q);
12365 t = q->qDNSServer;
12366 if (t != s)
12367 {
12368 // If DNS Server for this question has changed, reactivate it
12369 LogInfo("uDNS_SetupDNSConfig: Updating DNS Server from %#a:%d (%##s) to %#a:%d (%##s) for question %##s (%s) (scope:%p)",
12370 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
12371 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
12372 q->qname.c, DNSTypeName(q->qtype), q->InterfaceID);
12373
12374 DNSServerChangeForQuestion(m, q, s);
12375 q->unansweredQueries = 0;
12376 // We still need to pick a new DNSServer for the questions that have been
12377 // suppressed, but it is wrong to activate the query as DNS server change
12378 // could not possibly change the status of SuppressUnusable questions
12379 if (!QuerySuppressed(q))
12380 {
12381 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
12382 ActivateUnicastQuery(m, q, mDNStrue);
12383 // ActivateUnicastQuery is called for duplicate questions also as it does something
12384 // special for AutoTunnel questions
12385 for (qptr = q->next ; qptr; qptr = qptr->next)
12386 {
12387 if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
12388 }
12389 }
12390 }
12391 else
12392 {
12393 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
12394 q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
12395 for (qptr = q->next ; qptr; qptr = qptr->next)
12396 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
12397 }
12398 }
12399
12400 FORALL_CACHERECORDS(slot, cg, cr)
12401 {
12402 if (cr->resrec.InterfaceID) continue;
12403 // We just mark them for purge or reconfirm.
12404 //
12405 // The new DNSServer may be a scoped or non-scoped one. We use the active question's
12406 // InterfaceID for looking up the right DNS server
12407 ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL);
12408
12409 // Purge or Reconfirm if this cache entry would use the new DNS server
12410 if (ptr && (ptr != cr->resrec.rDNSServer))
12411 {
12412 // As the DNSServers for this cache record is not the same anymore, we don't
12413 // want any new questions to pick this old value. If there is no active question,
12414 // we can't possibly re-confirm, so purge in that case.
12415 if (cr->CRActiveQuestion == mDNSNULL)
12416 {
12417 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s, New DNS server %#a , Old DNS server %#a", CRDisplayString(m, cr),
12418 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
12419 mDNS_PurgeCacheResourceRecord(m, cr);
12420 }
12421 else
12422 {
12423 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", CRDisplayString(m, cr),
12424 &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ? &cr->resrec.rDNSServer->addr : mDNSNULL));
12425 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
12426 }
12427 }
12428 }
12429
12430 while (*p)
12431 {
12432 if (((*p)->flags & DNSServer_FlagDelete) != 0)
12433 {
12434 // Scan our cache, looking for uDNS records that we would have queried this server for.
12435 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
12436 // different DNS servers can give different answers to the same question.
12437 ptr = *p;
12438 FORALL_CACHERECORDS(slot, cg, cr)
12439 {
12440 if (cr->resrec.InterfaceID) continue;
12441 if (cr->resrec.rDNSServer == ptr)
12442 {
12443 // If we don't have an active question for this cache record, neither Purge can
12444 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
12445 // pointer on the record NULL so that we don't point to freed memory (We might dereference
12446 // DNSServer pointers from resource record for logging purposes).
12447 //
12448 // If there is an active question, point to its DNSServer as long as it does not point to the
12449 // freed one. We already went through the questions above and made them point at either the
12450 // new server or NULL if there is no server.
12451
12452 if (cr->CRActiveQuestion)
12453 {
12454 DNSQuestion *qptr = cr->CRActiveQuestion;
12455
12456 if (qptr->qDNSServer == ptr)
12457 {
12458 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) poining to DNSServer Address %#a"
12459 " to be freed", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID, &ptr->addr);
12460 qptr->validDNSServers = zeroOpaque64;
12461 qptr->qDNSServer = mDNSNULL;
12462 cr->resrec.rDNSServer = mDNSNULL;
12463 }
12464 else
12465 {
12466 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
12467 " resetting to question's DNSServer Address %#a", CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype),
12468 qptr->InterfaceID, &ptr->addr, (qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL));
12469 cr->resrec.rDNSServer = qptr->qDNSServer;
12470 }
12471 }
12472 else
12473 {
12474 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
12475 cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
12476 cr->resrec.rDNSServer = mDNSNULL;
12477 }
12478
12479 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
12480 }
12481 }
12482 *p = (*p)->next;
12483 debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
12484 mDNSPlatformMemFree(ptr);
12485 NumUnicastDNSServers--;
12486 }
12487 else
12488 {
12489 (*p)->flags &= ~DNSServer_FlagNew;
12490 p = &(*p)->next;
12491 }
12492 }
12493
12494 // 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).
12495 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
12496 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
12497 // 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.
12498 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
12499 {
12500 int count = 0;
12501 FORALL_CACHERECORDS(slot, cg, cr)
12502 {
12503 if (!cr->resrec.InterfaceID)
12504 {
12505 mDNS_PurgeCacheResourceRecord(m, cr);
12506 count++;
12507 }
12508 }
12509 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
12510 m->DNSServers ? "DNS server became" : "No DNS servers", count);
12511
12512 // Force anything that needs to get zone data to get that information again
12513 RestartRecordGetZoneData(m);
12514 }
12515
12516 // Did our FQDN change?
12517 if (!SameDomainName(&fqdn, &m->FQDN))
12518 {
12519 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
12520
12521 AssignDomainName(&m->FQDN, &fqdn);
12522
12523 if (m->FQDN.c[0])
12524 {
12525 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
12526 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
12527 }
12528 }
12529
12530 mDNS_Unlock(m);
12531
12532 // handle router and primary interface changes
12533 v4 = v6 = r = zeroAddr;
12534 v4.type = r.type = mDNSAddrType_IPv4;
12535
12536 if (mDNSPlatformGetPrimaryInterface(m, &v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
12537 {
12538 mDNS_SetPrimaryInterfaceInfo(m,
12539 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
12540 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
12541 !mDNSIPv4AddressIsZero(r.ip.v4) ? &r : mDNSNULL);
12542 }
12543 else
12544 {
12545 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
12546 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
12547 }
12548
12549 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
12550 return mStatus_NoError;
12551 }
12552
12553 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
12554 {
12555 m->mDNSPlatformStatus = result;
12556 if (m->MainCallback)
12557 {
12558 mDNS_Lock(m);
12559 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12560 m->MainCallback(m, mStatus_NoError);
12561 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12562 mDNS_Unlock(m);
12563 }
12564 }
12565
12566 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
12567 {
12568 m->CurrentRecord = start;
12569 while (m->CurrentRecord)
12570 {
12571 AuthRecord *rr = m->CurrentRecord;
12572 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
12573 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
12574 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
12575 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
12576 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
12577 else if (rr->AnnounceCount > 1)
12578 {
12579 rr->AnnounceCount = 1;
12580 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
12581 }
12582 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
12583 // new records could have been added to the end of the list as a result of that call.
12584 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
12585 m->CurrentRecord = rr->next;
12586 }
12587 }
12588
12589 mDNSexport void mDNS_StartExit(mDNS *const m)
12590 {
12591 NetworkInterfaceInfo *intf;
12592 AuthRecord *rr;
12593
12594 mDNS_Lock(m);
12595
12596 LogInfo("mDNS_StartExit");
12597 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
12598
12599 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
12600
12601 #if APPLE_OSX_mDNSResponder
12602 #if !NO_WCF
12603 CHECK_WCF_FUNCTION(WCFConnectionDealloc)
12604 {
12605 if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
12606 }
12607 #endif
12608 #endif
12609
12610 #ifndef UNICAST_DISABLED
12611 {
12612 SearchListElem *s;
12613 SuspendLLQs(m);
12614 // Don't need to do SleepRecordRegistrations() here
12615 // because we deregister all records and services later in this routine
12616 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
12617
12618 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
12619 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
12620 // and we may crash because the list still contains dangling pointers.
12621 for (s = SearchList; s; s = s->next)
12622 while (s->AuthRecs)
12623 {
12624 ARListElem *dereg = s->AuthRecs;
12625 s->AuthRecs = s->AuthRecs->next;
12626 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
12627 }
12628 }
12629 #endif
12630
12631 for (intf = m->HostInterfaces; intf; intf = intf->next)
12632 if (intf->Advertise)
12633 DeadvertiseInterface(m, intf);
12634
12635 // Shut down all our active NAT Traversals
12636 while (m->NATTraversals)
12637 {
12638 NATTraversalInfo *t = m->NATTraversals;
12639 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
12640
12641 // After stopping the NAT Traversal, we zero out the fields.
12642 // This has particularly important implications for our AutoTunnel records --
12643 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
12644 // handlers to just turn around and attempt to re-register those same records.
12645 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
12646 // to not do this.
12647 t->ExternalAddress = zerov4Addr;
12648 t->ExternalPort = zeroIPPort;
12649 t->RequestedPort = zeroIPPort;
12650 t->Lifetime = 0;
12651 t->Result = mStatus_NoError;
12652 }
12653
12654 // Make sure there are nothing but deregistering records remaining in the list
12655 if (m->CurrentRecord)
12656 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
12657
12658 // We're in the process of shutting down, so queries, etc. are no longer available.
12659 // Consequently, determining certain information, e.g. the uDNS update server's IP
12660 // address, will not be possible. The records on the main list are more likely to
12661 // already contain such information, so we deregister the duplicate records first.
12662 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
12663 DeregLoop(m, m->DuplicateRecords);
12664 LogInfo("mDNS_StartExit: Deregistering resource records");
12665 DeregLoop(m, m->ResourceRecords);
12666
12667 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
12668 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
12669 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
12670 {
12671 m->NextScheduledResponse = m->timenow;
12672 m->SuppressSending = 0;
12673 }
12674
12675 if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
12676 else LogInfo("mDNS_StartExit: No deregistering records remain");
12677
12678 for (rr = m->DuplicateRecords; rr; rr = rr->next)
12679 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
12680
12681 // If any deregistering records remain, send their deregistration announcements before we exit
12682 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
12683
12684 mDNS_Unlock(m);
12685
12686 LogInfo("mDNS_StartExit: done");
12687 }
12688
12689 mDNSexport void mDNS_FinalExit(mDNS *const m)
12690 {
12691 mDNSu32 rrcache_active = 0;
12692 mDNSu32 rrcache_totalused = 0;
12693 mDNSu32 slot;
12694 AuthRecord *rr;
12695
12696 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
12697 mDNSPlatformClose(m);
12698
12699 rrcache_totalused = m->rrcache_totalused;
12700 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
12701 {
12702 while (m->rrcache_hash[slot])
12703 {
12704 CacheGroup *cg = m->rrcache_hash[slot];
12705 while (cg->members)
12706 {
12707 CacheRecord *cr = cg->members;
12708 cg->members = cg->members->next;
12709 if (cr->CRActiveQuestion) rrcache_active++;
12710 ReleaseCacheRecord(m, cr);
12711 }
12712 cg->rrcache_tail = &cg->members;
12713 ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
12714 }
12715 }
12716 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
12717 if (rrcache_active != m->rrcache_active)
12718 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
12719
12720 for (rr = m->ResourceRecords; rr; rr = rr->next)
12721 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
12722
12723 LogInfo("mDNS_FinalExit: done");
12724 }