]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-320.5.1.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2006 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 * Formatting notes:
26 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
27 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
28 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
29 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
30 * therefore common sense dictates that if they are part of a compound statement then they
31 * should be indented to the same level as everything else in that compound statement.
32 * Indenting curly braces at the same level as the "if" implies that curly braces are
33 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
34 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
35 * understand why variable y is not of type "char*" just proves the point that poor code
36 * layout leads people to unfortunate misunderstandings about how the C language really works.)
37 */
38
39 #include "DNSCommon.h" // Defines general DNS untility routines
40 #include "uDNS.h" // Defines entry points into unicast-specific routines
41
42 // Disable certain benign warnings with Microsoft compilers
43 #if(defined(_MSC_VER))
44 // Disable "conditional expression is constant" warning for debug macros.
45 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
46 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
47 #pragma warning(disable:4127)
48
49 // Disable "assignment within conditional expression".
50 // Other compilers understand the convention that if you place the assignment expression within an extra pair
51 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
52 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
53 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
54 #pragma warning(disable:4706)
55 #endif
56
57 #if APPLE_OSX_mDNSResponder
58
59 #include <WebFilterDNS/WebFilterDNS.h>
60
61 #if ! NO_WCF
62 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
63 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
64
65 // Do we really need to define a macro for "if"?
66 #define CHECK_WCF_FUNCTION(X) if (X)
67 #endif // ! NO_WCF
68
69 #else
70
71 #define NO_WCF 1
72 #endif // APPLE_OSX_mDNSResponder
73
74 // Forward declarations
75 mDNSlocal void BeginSleepProcessing(mDNS *const m);
76 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
77 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password);
78 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
79 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
80 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
81
82 // ***************************************************************************
83 #if COMPILER_LIKES_PRAGMA_MARK
84 #pragma mark - Program Constants
85 #endif
86
87 #define NO_HINFO 1
88
89
90 // Any records bigger than this are considered 'large' records
91 #define SmallRecordLimit 1024
92
93 #define kMaxUpdateCredits 10
94 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
95
96 mDNSexport const char *const mDNS_DomainTypeNames[] =
97 {
98 "b._dns-sd._udp.", // Browse
99 "db._dns-sd._udp.", // Default Browse
100 "lb._dns-sd._udp.", // Automatic Browse
101 "r._dns-sd._udp.", // Registration
102 "dr._dns-sd._udp." // Default Registration
103 };
104
105 #ifdef UNICAST_DISABLED
106 #define uDNS_IsActiveQuery(q, u) mDNSfalse
107 #endif
108
109 // ***************************************************************************
110 #if COMPILER_LIKES_PRAGMA_MARK
111 #pragma mark -
112 #pragma mark - General Utility Functions
113 #endif
114
115 // If there is a authoritative LocalOnly record that answers questions of type A, AAAA and CNAME
116 // this returns true. Main use is to handle /etc/hosts records.
117 #define LORecordAnswersAddressType(rr) ((rr)->ARType == AuthRecordLocalOnly && \
118 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
119 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
120 (rr)->resrec.rrtype == kDNSType_CNAME))
121
122 #define FollowCNAME(q, rr, AddRecord) (AddRecord && (q)->qtype != kDNSType_CNAME && \
123 (rr)->RecordType != kDNSRecordTypePacketNegative && \
124 (rr)->rrtype == kDNSType_CNAME)
125
126 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
127 {
128 if (m->mDNS_busy != m->mDNS_reentrancy+1)
129 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
130
131 #if ForceAlerts
132 if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
133 #endif
134
135 if (m->NextScheduledStopTime - q->StopTime > 0)
136 m->NextScheduledStopTime = q->StopTime;
137 }
138
139 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
140 {
141 if (m->mDNS_busy != m->mDNS_reentrancy+1)
142 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
143
144 #if ForceAlerts
145 if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
146 #endif
147
148 if (ActiveQuestion(q))
149 {
150 // Depending on whether this is a multicast or unicast question we want to set either:
151 // m->NextScheduledQuery = NextQSendTime(q) or
152 // m->NextuDNSEvent = NextQSendTime(q)
153 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
154 if (*timer - NextQSendTime(q) > 0)
155 *timer = NextQSendTime(q);
156 }
157 }
158
159 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
160 {
161 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
162 unsigned int i;
163 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
164 #endif
165 e->next = r->rrauth_free;
166 r->rrauth_free = e;
167 r->rrauth_totalused--;
168 }
169
170 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
171 {
172 AuthEntity *e = (AuthEntity *)(*cp);
173 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp)->name->c);
174 if ((*cp)->rrauth_tail != &(*cp)->members)
175 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
176 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
177 (*cp)->name = mDNSNULL;
178 *cp = (*cp)->next; // Cut record from list
179 ReleaseAuthEntity(r, e);
180 }
181
182 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
183 {
184 AuthEntity *e = mDNSNULL;
185
186 if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
187 r->rrauth_lock = 1;
188
189 if (!r->rrauth_free)
190 {
191 // We allocate just one AuthEntity at a time because we need to be able
192 // free them all individually which normally happens when we parse /etc/hosts into
193 // AuthHash where we add the "new" entries and discard (free) the already added
194 // entries. If we allocate as chunks, we can't free them individually.
195 AuthEntity *storage = mDNSPlatformMemAllocate(sizeof(AuthEntity));
196 storage->next = mDNSNULL;
197 r->rrauth_free = storage;
198 }
199
200 // If we still have no free records, recycle all the records we can.
201 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
202 if (!r->rrauth_free)
203 {
204 mDNSu32 oldtotalused = r->rrauth_totalused;
205 mDNSu32 slot;
206 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
207 {
208 AuthGroup **cp = &r->rrauth_hash[slot];
209 while (*cp)
210 {
211 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
212 else ReleaseAuthGroup(r, cp);
213 }
214 }
215 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
216 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
217 }
218
219 if (r->rrauth_free) // If there are records in the free list, take one
220 {
221 e = r->rrauth_free;
222 r->rrauth_free = e->next;
223 if (++r->rrauth_totalused >= r->rrauth_report)
224 {
225 LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
226 if (r->rrauth_report < 100) r->rrauth_report += 10;
227 else if (r->rrauth_report < 1000) r->rrauth_report += 100;
228 else r->rrauth_report += 1000;
229 }
230 mDNSPlatformMemZero(e, sizeof(*e));
231 }
232
233 r->rrauth_lock = 0;
234
235 return(e);
236 }
237
238 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
239 {
240 AuthGroup *ag;
241 for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
242 if (ag->namehash == namehash && SameDomainName(ag->name, name))
243 break;
244 return(ag);
245 }
246
247 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
248 {
249 return(AuthGroupForName(r, slot, rr->namehash, rr->name));
250 }
251
252 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
253 {
254 mDNSu16 namelen = DomainNameLength(rr->name);
255 AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
256 if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
257 ag->next = r->rrauth_hash[slot];
258 ag->namehash = rr->namehash;
259 ag->members = mDNSNULL;
260 ag->rrauth_tail = &ag->members;
261 ag->name = (domainname*)ag->namestorage;
262 ag->NewLocalOnlyRecords = mDNSNULL;
263 if (namelen > InlineCacheGroupNameSize) ag->name = mDNSPlatformMemAllocate(namelen);
264 if (!ag->name)
265 {
266 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
267 ReleaseAuthEntity(r, (AuthEntity*)ag);
268 return(mDNSNULL);
269 }
270 AssignDomainName(ag->name, rr->name);
271
272 if (AuthGroupForRecord(r, slot, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
273 r->rrauth_hash[slot] = ag;
274 if (AuthGroupForRecord(r, slot, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
275
276 return(ag);
277 }
278
279 // Returns the AuthGroup in which the AuthRecord was inserted
280 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
281 {
282 AuthGroup *ag;
283 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
284 ag = AuthGroupForRecord(r, slot, &rr->resrec);
285 if (!ag) ag = GetAuthGroup(r, slot, &rr->resrec); // If we don't have a AuthGroup for this name, make one now
286 if (ag)
287 {
288 LogInfo("InsertAuthRecord: inserting auth record %s from table", ARDisplayString(m, rr));
289 *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list
290 ag->rrauth_tail = &(rr->next); // Advance tail pointer
291 }
292 return ag;
293 }
294
295 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
296 {
297 AuthGroup *a;
298 AuthGroup **ag = &a;
299 AuthRecord **rp;
300 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
301
302 a = AuthGroupForRecord(r, slot, &rr->resrec);
303 if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
304 rp = &(*ag)->members;
305 while (*rp)
306 {
307 if (*rp != rr)
308 rp=&(*rp)->next;
309 else
310 {
311 // We don't break here, so that we can set the tail below without tracking "prev" pointers
312
313 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
314 *rp = (*rp)->next; // Cut record from list
315 }
316 }
317 // TBD: If there are no more members, release authgroup ?
318 (*ag)->rrauth_tail = rp;
319 return a;
320 }
321
322 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
323 {
324 CacheGroup *cg;
325 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
326 if (cg->namehash == namehash && SameDomainName(cg->name, name))
327 break;
328 return(cg);
329 }
330
331 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
332 {
333 return(CacheGroupForName(m, slot, rr->namehash, rr->name));
334 }
335
336 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
337 {
338 NetworkInterfaceInfo *intf;
339
340 if (addr->type == mDNSAddrType_IPv4)
341 {
342 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
343 if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
344 for (intf = m->HostInterfaces; intf; intf = intf->next)
345 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
346 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
347 return(mDNStrue);
348 }
349
350 if (addr->type == mDNSAddrType_IPv6)
351 {
352 if (mDNSv6AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
353 for (intf = m->HostInterfaces; intf; intf = intf->next)
354 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
355 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
356 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
357 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
358 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
359 return(mDNStrue);
360 }
361
362 return(mDNSfalse);
363 }
364
365 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
366 {
367 NetworkInterfaceInfo *intf = m->HostInterfaces;
368 while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
369 return(intf);
370 }
371
372 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
373 {
374 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
375 return(intf ? intf->ifname : mDNSNULL);
376 }
377
378 // Caller should hold the lock
379 mDNSlocal void GenerateNegativeResponse(mDNS *const m)
380 {
381 DNSQuestion *q;
382 if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
383 q = m->CurrentQuestion;
384 LogInfo("GenerateNegativeResponse: Generating negative response for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
385
386 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, mDNSNULL);
387 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
388 if (m->CurrentQuestion == q) { q->ThisQInterval = 0; } // Deactivate this question
389 // Don't touch the question after this
390 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
391 }
392
393 mDNSlocal void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
394 {
395 const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
396 if (q->CNAMEReferrals >= 10 || selfref)
397 LogMsg("AnswerQuestionByFollowingCNAME: %p %##s (%s) NOT following CNAME referral %d%s for %s",
398 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
399 else
400 {
401 const mDNSu32 c = q->CNAMEReferrals + 1; // Stash a copy of the new q->CNAMEReferrals value
402
403 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
404 // themselves. Without that check we can get into a case where we have two duplicate questions,
405 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
406 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
407 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
408 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
409 // for either of them. This is not a problem for CNAME loops of two or more records because in
410 // those cases the newly re-appended question A has a different target name and therefore cannot be
411 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
412
413 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
414 // and track CNAMEs coming and going, we should really create a subordinate query here,
415 // which we would subsequently cancel and retract if the CNAME referral record were removed.
416 // In reality this is such a corner case we'll ignore it until someone actually needs it.
417
418 LogInfo("AnswerQuestionByFollowingCNAME: %p %##s (%s) following CNAME referral %d for %s",
419 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, RRDisplayString(m, rr));
420
421 mDNS_StopQuery_internal(m, q); // Stop old query
422 AssignDomainName(&q->qname, &rr->rdata->u.name); // Update qname
423 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
424 // If a unicast query results in a CNAME that points to a .local, we need to re-try
425 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
426 // to try this as unicast query even though it is a .local name
427 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
428 {
429 LogInfo("AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p %##s (%s) Record %s",
430 q, q->qname.c, DNSTypeName(q->qtype), RRDisplayString(m, rr));
431 q->InterfaceID = mDNSInterface_Unicast;
432 }
433 mDNS_StartQuery_internal(m, q); // start new query
434 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
435 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
436 q->CNAMEReferrals = c;
437 }
438 }
439
440 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
441 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
442 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
443 {
444 DNSQuestion *q = m->CurrentQuestion;
445 mDNSBool followcname;
446
447 if (!q)
448 {
449 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
450 return;
451 }
452
453 followcname = FollowCNAME(q, &rr->resrec, AddRecord);
454
455 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
456 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
457 {
458 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
459 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
460 return;
461 }
462
463 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
464 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
465 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
466 if (q->QuestionCallback && !q->NoAnswer)
467 {
468 q->CurrentAnswers += AddRecord ? 1 : -1;
469 if (LORecordAnswersAddressType(rr))
470 {
471 if (!followcname || q->ReturnIntermed)
472 {
473 // Don't send this packet on the wire as we answered from /etc/hosts
474 q->ThisQInterval = 0;
475 q->LOAddressAnswers += AddRecord ? 1 : -1;
476 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
477 }
478 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
479 // The callback above could have caused the question to stop. Detect that
480 // using m->CurrentQuestion
481 if (followcname && m->CurrentQuestion == q)
482 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
483 return;
484 }
485 else
486 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
487 }
488 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
489 }
490
491 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
492 {
493 if (m->CurrentQuestion)
494 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
495 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
496 m->CurrentQuestion = m->Questions;
497 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
498 {
499 mDNSBool answered;
500 DNSQuestion *q = m->CurrentQuestion;
501 if (RRAny(rr))
502 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
503 else
504 answered = LocalOnlyRecordAnswersQuestion(rr, q);
505 if (answered)
506 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
507 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
508 m->CurrentQuestion = q->next;
509 }
510 m->CurrentQuestion = mDNSNULL;
511 }
512
513 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
514 // delivers the appropriate add/remove events to listening questions:
515 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
516 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
517 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
518 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
519 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
520 //
521 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
522 // and by mDNS_Deregister_internal()
523
524 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
525 {
526 if (m->CurrentQuestion)
527 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
528 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
529
530 m->CurrentQuestion = m->LocalOnlyQuestions;
531 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
532 {
533 mDNSBool answered;
534 DNSQuestion *q = m->CurrentQuestion;
535 // We are called with both LocalOnly/P2P record or a regular AuthRecord
536 if (RRAny(rr))
537 answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
538 else
539 answered = LocalOnlyRecordAnswersQuestion(rr, q);
540 if (answered)
541 AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord); // MUST NOT dereference q again
542 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
543 m->CurrentQuestion = q->next;
544 }
545
546 m->CurrentQuestion = mDNSNULL;
547
548 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
549 if (rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P)
550 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, rr, AddRecord);
551
552 }
553
554 // ***************************************************************************
555 #if COMPILER_LIKES_PRAGMA_MARK
556 #pragma mark -
557 #pragma mark - Resource Record Utility Functions
558 #endif
559
560 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
561
562 #define ResourceRecordIsValidAnswer(RR) ( ((RR)-> resrec.RecordType & kDNSRecordTypeActiveMask) && \
563 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
564 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
565 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
566
567 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
568 (ResourceRecordIsValidAnswer(RR) && \
569 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
570
571 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
572 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
573
574 #define InitialAnnounceCount ((mDNSu8)8)
575
576 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
577 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
578 // and then if the machine fails to wake, 3 goodbye packets).
579 #define GoodbyeCount ((mDNSu8)3)
580 #define WakeupCount ((mDNSu8)18)
581
582 // Number of wakeups we send if WakeOnResolve is set in the question
583 #define InitialWakeOnResolveCount ((mDNSu8)3)
584
585 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
586 // This means that because the announce interval is doubled after sending the first packet, the first
587 // observed on-the-wire inter-packet interval between announcements is actually one second.
588 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
589 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
590 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
591 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
592
593 #define DefaultAPIntervalForRecordType(X) ((X) & kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
594 (X) & kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
595 (X) & kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
596
597 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
598 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
599 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
600 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
601
602 #define MaxUnansweredQueries 4
603
604 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
605 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
606 // TTL and rdata may differ.
607 // This is used for cache flush management:
608 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
609 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
610
611 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
612
613 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
614
615 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
616 {
617 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
618 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
619 if (r1->resrec.InterfaceID &&
620 r2->resrec.InterfaceID &&
621 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
622 return(mDNSBool)(
623 r1->resrec.rrclass == r2->resrec.rrclass &&
624 r1->resrec.namehash == r2->resrec.namehash &&
625 SameDomainName(r1->resrec.name, r2->resrec.name));
626 }
627
628 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
629 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
630 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
631 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
632 // so a response of any type should match, even if it is not actually the type the client plans to use.
633
634 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
635 // and require the rrtypes to match for the rdata to be considered potentially conflicting
636 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
637 {
638 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
639 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
640 if (pktrr->resrec.InterfaceID &&
641 authrr->resrec.InterfaceID &&
642 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
643 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
644 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
645 return(mDNSBool)(
646 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
647 pktrr->resrec.namehash == authrr->resrec.namehash &&
648 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
649 }
650
651 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
652 // This is the information that the requester believes to be correct.
653 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
654 // This is the information that we believe to be correct.
655 // We've already determined that we plan to give this answer on this interface
656 // (either the record is non-specific, or it is specific to this interface)
657 // so now we just need to check the name, type, class, rdata and TTL.
658 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
659 {
660 // If RR signature is different, or data is different, then don't suppress our answer
661 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
662
663 // If the requester's indicated TTL is less than half the real TTL,
664 // we need to give our answer before the requester's copy expires.
665 // If the requester's indicated TTL is at least half the real TTL,
666 // then we can suppress our answer this time.
667 // If the requester's indicated TTL is greater than the TTL we believe,
668 // then that's okay, and we don't need to do anything about it.
669 // (If two responders on the network are offering the same information,
670 // that's okay, and if they are offering the information with different TTLs,
671 // the one offering the lower TTL should defer to the one offering the higher TTL.)
672 return(mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
673 }
674
675 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
676 {
677 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
678 {
679 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
680 {
681 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
682 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
683 }
684 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
685 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
686 // Some defensive code:
687 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
688 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
689 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
690 if (m->NextScheduledProbe - m->timenow < 0)
691 m->NextScheduledProbe = m->timenow;
692 }
693 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
694 {
695 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
696 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
697 }
698 }
699
700 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
701 {
702 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
703 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
704
705 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
706 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
707 // records that are going to probe, then we delay its first announcement so that it will
708 // go out synchronized with the first announcement for the other records that *are* probing.
709 // This is a minor performance tweak that helps keep groups of related records synchronized together.
710 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
711 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
712 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
713 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
714 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
715
716 if (rr->ProbeCount)
717 {
718 // If we have no probe suppression time set, or it is in the past, set it now
719 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
720 {
721 // To allow us to aggregate probes when a group of services are registered together,
722 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
723 // 1/4 second wait; probe
724 // 1/4 second wait; probe
725 // 1/4 second wait; probe
726 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
727 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
728
729 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
730 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
731 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
732 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
733 m->SuppressProbes = m->timenow;
734
735 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
736 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
737 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
738 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
739 m->SuppressProbes = m->timenow;
740
741 // except... don't expect to be able to send before the m->SuppressSending timer fires
742 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
743 m->SuppressProbes = NonZeroTime(m->SuppressSending);
744
745 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
746 {
747 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
748 m->SuppressProbes - m->timenow,
749 m->NextScheduledProbe - m->timenow,
750 m->NextScheduledQuery - m->timenow,
751 m->SuppressSending,
752 m->SuppressSending - m->timenow);
753 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
754 }
755 }
756 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
757 }
758 else if (m->SuppressProbes && m->SuppressProbes - m->timenow >= 0)
759 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
760 else
761 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
762
763 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
764 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
765 // After three probes one second apart with no answer, we conclude the client is now sleeping
766 // and we can begin broadcasting our announcements to take over ownership of that IP address.
767 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
768 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
769 if (rr->AddressProxy.type) rr->LastAPTime = m->timenow;
770
771 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
772 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
773 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
774 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
775 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
776 if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
777 if (rr->WakeUp.HMAC.l[0] && rr->resrec.rrtype == kDNSType_AAAA)
778 rr->LastAPTime = m->timenow - rr->ThisAPInterval + mDNSPlatformOneSecond * 10;
779
780 // Set LastMCTime to now, to inhibit multicast responses
781 // (no need to send additional multicast responses when we're announcing anyway)
782 rr->LastMCTime = m->timenow;
783 rr->LastMCInterface = mDNSInterfaceMark;
784
785 SetNextAnnounceProbeTime(m, rr);
786 }
787
788 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
789 {
790 const domainname *target;
791 if (rr->AutoTarget)
792 {
793 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
794 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
795 // with the port number in our advertised SRV record automatically tracking the external mapped port.
796 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
797 if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
798 }
799
800 target = GetServiceTarget(m, rr);
801 if (!target || target->c[0] == 0)
802 {
803 // defer registration until we've got a target
804 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
805 rr->state = regState_NoTarget;
806 return mDNSNULL;
807 }
808 else
809 {
810 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
811 return target;
812 }
813 }
814
815 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
816 // Eventually we should unify this with GetServiceTarget() in uDNS.c
817 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
818 {
819 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
820 const domainname *newname = &m->MulticastHostname;
821
822 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
823
824 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
825 {
826 const domainname *const n = SetUnicastTargetToHostName(m, rr);
827 if (n) newname = n;
828 else { target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
829 }
830
831 if (target && SameDomainName(target, newname))
832 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
833
834 if (target && !SameDomainName(target, newname))
835 {
836 AssignDomainName(target, newname);
837 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
838
839 // If we're in the middle of probing this record, we need to start again,
840 // because changing its rdata may change the outcome of the tie-breaker.
841 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
842 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
843
844 // If we've announced this record, we really should send a goodbye packet for the old rdata before
845 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
846 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
847 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
848 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
849 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
850
851 rr->AnnounceCount = InitialAnnounceCount;
852 rr->RequireGoodbye = mDNSfalse;
853 InitializeLastAPTime(m, rr);
854 }
855 }
856
857 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
858 {
859 if (rr->RecordCallback)
860 {
861 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
862 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
863 rr->Acknowledged = mDNStrue;
864 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
865 rr->RecordCallback(m, rr, mStatus_NoError);
866 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
867 }
868 }
869
870 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
871 {
872 // Make sure that we don't activate the SRV record and associated service records, if it is in
873 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
874 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
875 // the target becomes available, the records will be reregistered.
876 if (rr->resrec.rrtype != kDNSType_SRV)
877 {
878 AuthRecord *srvRR = mDNSNULL;
879 if (rr->resrec.rrtype == kDNSType_PTR)
880 srvRR = rr->Additional1;
881 else if (rr->resrec.rrtype == kDNSType_TXT)
882 srvRR = rr->DependentOn;
883 if (srvRR)
884 {
885 if (srvRR->resrec.rrtype != kDNSType_SRV)
886 {
887 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
888 }
889 else
890 {
891 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
892 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
893 rr->state = srvRR->state;
894 }
895 }
896 }
897
898 if (rr->state == regState_NoTarget)
899 {
900 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
901 return;
902 }
903 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
904 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
905 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
906 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
907 // 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.
908 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
909 {
910 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
911 rr->state = regState_DeregPending;
912 }
913 else
914 {
915 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
916 rr->state = regState_Pending;
917 }
918 rr->ProbeCount = 0;
919 rr->AnnounceCount = 0;
920 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
921 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
922 rr->expire = 0; // Forget about all the leases, start fresh
923 rr->uselease = mDNStrue;
924 rr->updateid = zeroID;
925 rr->SRVChanged = mDNSfalse;
926 rr->updateError = mStatus_NoError;
927 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
928 // The records might already be registered with the server and hence could have NAT state.
929 if (rr->NATinfo.clientContext)
930 {
931 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
932 rr->NATinfo.clientContext = mDNSNULL;
933 }
934 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
935 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
936 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
937 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
938 }
939
940 // Two records qualify to be local duplicates if:
941 // (a) the RecordTypes are the same, or
942 // (b) one is Unique and the other Verified
943 // (c) either is in the process of deregistering
944 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
945 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
946 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
947
948 #define RecordIsLocalDuplicate(A,B) \
949 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
950
951 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
952 {
953 AuthGroup *a;
954 AuthGroup **ag = &a;
955 AuthRecord **rp;
956 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
957
958 a = AuthGroupForRecord(r, slot, &rr->resrec);
959 if (!a) return mDNSNULL;
960 rp = &(*ag)->members;
961 while (*rp)
962 {
963 if (!RecordIsLocalDuplicate(*rp, rr))
964 rp=&(*rp)->next;
965 else
966 {
967 if ((*rp)->resrec.RecordType == kDNSRecordTypeDeregistering)
968 {
969 (*rp)->AnnounceCount = 0;
970 rp=&(*rp)->next;
971 }
972 else return *rp;
973 }
974 }
975 return (mDNSNULL);
976 }
977
978 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
979 {
980 AuthGroup *a;
981 AuthGroup **ag = &a;
982 AuthRecord **rp;
983 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
984
985 a = AuthGroupForRecord(r, slot, &rr->resrec);
986 if (!a) return mDNSfalse;
987 rp = &(*ag)->members;
988 while (*rp)
989 {
990 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
991 const AuthRecord *s2 = (*rp)->RRSet ? (*rp)->RRSet : *rp;
992 if (s1 != s2 && SameResourceRecordSignature((*rp), rr) && !IdenticalSameNameRecord(&(*rp)->resrec, &rr->resrec))
993 return mDNStrue;
994 else
995 rp=&(*rp)->next;
996 }
997 return (mDNSfalse);
998 }
999
1000 // checks to see if "rr" is already present
1001 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1002 {
1003 AuthGroup *a;
1004 AuthGroup **ag = &a;
1005 AuthRecord **rp;
1006 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1007
1008 a = AuthGroupForRecord(r, slot, &rr->resrec);
1009 if (!a) return mDNSNULL;
1010 rp = &(*ag)->members;
1011 while (*rp)
1012 {
1013 if (*rp != rr)
1014 rp=&(*rp)->next;
1015 else
1016 {
1017 return *rp;
1018 }
1019 }
1020 return (mDNSNULL);
1021 }
1022
1023 // Exported so uDNS.c can call this
1024 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1025 {
1026 domainname *target = GetRRDomainNameTarget(&rr->resrec);
1027 AuthRecord *r;
1028 AuthRecord **p = &m->ResourceRecords;
1029 AuthRecord **d = &m->DuplicateRecords;
1030
1031 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1032 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1033
1034 if (!rr->resrec.RecordType)
1035 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1036
1037 if (m->ShutdownTime)
1038 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1039
1040 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1041 {
1042 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1043 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1044 {
1045 rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1046 rr->ARType = AuthRecordLocalOnly;
1047 }
1048 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1049 {
1050 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1051 if (intf && !intf->Advertise){ rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1052 }
1053 if (rr->resrec.InterfaceID != previousID)
1054 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1055 }
1056
1057 if (RRLocalOnly(rr))
1058 {
1059 if (CheckAuthSameRecord(&m->rrauth, rr))
1060 {
1061 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1062 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1063 return(mStatus_AlreadyRegistered);
1064 }
1065 }
1066 else
1067 {
1068 while (*p && *p != rr) p=&(*p)->next;
1069 if (*p)
1070 {
1071 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1072 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1073 return(mStatus_AlreadyRegistered);
1074 }
1075 }
1076
1077 while (*d && *d != rr) d=&(*d)->next;
1078 if (*d)
1079 {
1080 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1081 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1082 return(mStatus_AlreadyRegistered);
1083 }
1084
1085 if (rr->DependentOn)
1086 {
1087 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1088 rr->resrec.RecordType = kDNSRecordTypeVerified;
1089 else
1090 {
1091 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1092 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1093 return(mStatus_Invalid);
1094 }
1095 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1096 {
1097 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1098 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1099 return(mStatus_Invalid);
1100 }
1101 }
1102
1103 // If this resource record is referencing a specific interface, make sure it exists.
1104 // Skip checks for LocalOnly and P2P as they are not valid InterfaceIDs. Also, for scoped
1105 // entries in /etc/hosts skip that check as that interface may not be valid at this time.
1106 if (rr->resrec.InterfaceID && rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
1107 {
1108 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1109 if (!intf)
1110 {
1111 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr->resrec.InterfaceID);
1112 return(mStatus_BadReferenceErr);
1113 }
1114 }
1115
1116 rr->next = mDNSNULL;
1117
1118 // Field Group 1: The actual information pertaining to this resource record
1119 // Set up by client prior to call
1120
1121 // Field Group 2: Persistent metadata for Authoritative Records
1122 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1123 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1124 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1125 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1126 // rr->Callback = already set in mDNS_SetupResourceRecord
1127 // rr->Context = already set in mDNS_SetupResourceRecord
1128 // rr->RecordType = already set in mDNS_SetupResourceRecord
1129 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1130 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1131 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1132 if (rr->AutoTarget && target) target->c[0] = 0;
1133
1134 // Field Group 3: Transient state for Authoritative Records
1135 rr->Acknowledged = mDNSfalse;
1136 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1137 rr->AnnounceCount = InitialAnnounceCount;
1138 rr->RequireGoodbye = mDNSfalse;
1139 rr->AnsweredLocalQ = mDNSfalse;
1140 rr->IncludeInProbe = mDNSfalse;
1141 rr->ImmedUnicast = mDNSfalse;
1142 rr->SendNSECNow = mDNSNULL;
1143 rr->ImmedAnswer = mDNSNULL;
1144 rr->ImmedAdditional = mDNSNULL;
1145 rr->SendRNow = mDNSNULL;
1146 rr->v4Requester = zerov4Addr;
1147 rr->v6Requester = zerov6Addr;
1148 rr->NextResponse = mDNSNULL;
1149 rr->NR_AnswerTo = mDNSNULL;
1150 rr->NR_AdditionalTo = mDNSNULL;
1151 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1152 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1153 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1154 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1155 rr->NewRData = mDNSNULL;
1156 rr->newrdlength = 0;
1157 rr->UpdateCallback = mDNSNULL;
1158 rr->UpdateCredits = kMaxUpdateCredits;
1159 rr->NextUpdateCredit = 0;
1160 rr->UpdateBlocked = 0;
1161
1162 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1163 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1164
1165 // Field Group 4: Transient uDNS state for Authoritative Records
1166 rr->state = regState_Zero;
1167 rr->uselease = 0;
1168 rr->expire = 0;
1169 rr->Private = 0;
1170 rr->updateid = zeroID;
1171 rr->zone = rr->resrec.name;
1172 rr->nta = mDNSNULL;
1173 rr->tcp = mDNSNULL;
1174 rr->OrigRData = 0;
1175 rr->OrigRDLen = 0;
1176 rr->InFlightRData = 0;
1177 rr->InFlightRDLen = 0;
1178 rr->QueuedRData = 0;
1179 rr->QueuedRDLen = 0;
1180 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1181 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1182 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1183 // times with different values if the external NAT port changes during the lifetime of the service registration.
1184 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1185
1186 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1187 // rr->resrec.name->c = MUST be set by client
1188 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1189 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1190 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1191 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1192
1193 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1194 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1195 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1196 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1197
1198 if (rr->AutoTarget)
1199 {
1200 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1201 #ifndef UNICAST_DISABLED
1202 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1203 // 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.
1204 if (rr->state == regState_NoTarget)
1205 {
1206 // Initialize the target so that we don't crash while logging etc.
1207 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1208 if (tar) tar->c[0] = 0;
1209 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1210 }
1211 #endif
1212 }
1213 else
1214 {
1215 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
1216 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1217 }
1218
1219 if (!ValidateDomainName(rr->resrec.name))
1220 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1221
1222 // Don't do this until *after* we've set rr->resrec.rdlength
1223 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1224 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1225
1226 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
1227 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1228
1229 if (RRLocalOnly(rr))
1230 {
1231 // If this is supposed to be unique, make sure we don't have any name conflicts.
1232 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1233 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1234 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1235 // Hence, just bail out.
1236 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1237 {
1238 if (CheckAuthRecordConflict(&m->rrauth, rr))
1239 {
1240 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1241 return mStatus_NameConflict;
1242 }
1243 }
1244 }
1245
1246 // For uDNS records, we don't support duplicate checks at this time.
1247 #ifndef UNICAST_DISABLED
1248 if (AuthRecord_uDNS(rr))
1249 {
1250 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1251 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1252 // 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.
1253 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1254 while (*p) p=&(*p)->next;
1255 *p = rr;
1256 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1257 rr->ProbeCount = 0;
1258 rr->AnnounceCount = 0;
1259 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1260 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
1261 }
1262 #endif
1263
1264 // Now that we've finished building our new record, make sure it's not identical to one we already have
1265 if (RRLocalOnly(rr))
1266 {
1267 rr->ProbeCount = 0;
1268 rr->AnnounceCount = 0;
1269 r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1270 }
1271 else
1272 {
1273 for (r = m->ResourceRecords; r; r=r->next)
1274 if (RecordIsLocalDuplicate(r, rr))
1275 {
1276 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1277 else break;
1278 }
1279 }
1280
1281 if (r)
1282 {
1283 debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m,rr));
1284 *d = rr;
1285 // If the previous copy of this record is already verified unique,
1286 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1287 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1288 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1289 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1290 rr->ProbeCount = 0;
1291 }
1292 else
1293 {
1294 debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1295 if (RRLocalOnly(rr))
1296 {
1297 AuthGroup *ag;
1298 ag = InsertAuthRecord(m, &m->rrauth, rr);
1299 if (ag && !ag->NewLocalOnlyRecords) {
1300 m->NewLocalOnlyRecords = mDNStrue;
1301 ag->NewLocalOnlyRecords = rr;
1302 }
1303 // No probing for LocalOnly records, Acknowledge them right away
1304 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1305 AcknowledgeRecord(m, rr);
1306 return(mStatus_NoError);
1307 }
1308 else
1309 {
1310 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1311 *p = rr;
1312 }
1313 }
1314
1315 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
1316 {
1317 // For records that are not going to probe, acknowledge them right away
1318 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1319 AcknowledgeRecord(m, rr);
1320
1321 // Adding a record may affect whether or not we should sleep
1322 mDNS_UpdateAllowSleep(m);
1323 }
1324
1325 return(mStatus_NoError);
1326 }
1327
1328 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1329 {
1330 m->ProbeFailTime = m->timenow;
1331 m->NumFailedProbes++;
1332 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1333 // If a bunch of hosts have all been configured with the same name, then they'll all
1334 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1335 // up to name-10. After that they'll start adding random increments in the range 1-100,
1336 // so they're more likely to branch out in the available namespace and settle on a set of
1337 // unique names quickly. If after five more tries the host is still conflicting, then we
1338 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1339 if (m->NumFailedProbes >= 15)
1340 {
1341 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1342 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1343 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1344 }
1345 }
1346
1347 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1348 {
1349 RData *OldRData = rr->resrec.rdata;
1350 mDNSu16 OldRDLen = rr->resrec.rdlength;
1351 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
1352 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
1353 if (rr->UpdateCallback)
1354 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
1355 }
1356
1357 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1358 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1359 // Exported so uDNS.c can call this
1360 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1361 {
1362 AuthRecord *r2;
1363 mDNSu8 RecordType = rr->resrec.RecordType;
1364 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
1365 mDNSBool dupList = mDNSfalse;
1366
1367 if (RRLocalOnly(rr))
1368 {
1369 AuthGroup *a;
1370 AuthGroup **ag = &a;
1371 AuthRecord **rp;
1372 const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1373
1374 a = AuthGroupForRecord(&m->rrauth, slot, &rr->resrec);
1375 if (!a) return mDNSfalse;
1376 rp = &(*ag)->members;
1377 while (*rp && *rp != rr) rp=&(*rp)->next;
1378 p = rp;
1379 }
1380 else
1381 {
1382 while (*p && *p != rr) p=&(*p)->next;
1383 }
1384
1385 if (*p)
1386 {
1387 // We found our record on the main list. See if there are any duplicates that need special handling.
1388 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
1389 {
1390 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1391 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1392 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1393 }
1394 else
1395 {
1396 // Before we delete the record (and potentially send a goodbye packet)
1397 // first see if we have a record on the duplicate list ready to take over from it.
1398 AuthRecord **d = &m->DuplicateRecords;
1399 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1400 if (*d)
1401 {
1402 AuthRecord *dup = *d;
1403 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1404 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1405 *d = dup->next; // Cut replacement record from DuplicateRecords list
1406 if (RRLocalOnly(rr))
1407 {
1408 dup->next = mDNSNULL;
1409 if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1410 }
1411 else
1412 {
1413 dup->next = rr->next; // And then...
1414 rr->next = dup; // ... splice it in right after the record we're about to delete
1415 }
1416 dup->resrec.RecordType = rr->resrec.RecordType;
1417 dup->ProbeCount = rr->ProbeCount;
1418 dup->AnnounceCount = rr->AnnounceCount;
1419 dup->RequireGoodbye = rr->RequireGoodbye;
1420 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
1421 dup->ImmedAnswer = rr->ImmedAnswer;
1422 dup->ImmedUnicast = rr->ImmedUnicast;
1423 dup->ImmedAdditional = rr->ImmedAdditional;
1424 dup->v4Requester = rr->v4Requester;
1425 dup->v6Requester = rr->v6Requester;
1426 dup->ThisAPInterval = rr->ThisAPInterval;
1427 dup->LastAPTime = rr->LastAPTime;
1428 dup->LastMCTime = rr->LastMCTime;
1429 dup->LastMCInterface = rr->LastMCInterface;
1430 dup->Private = rr->Private;
1431 dup->state = rr->state;
1432 rr->RequireGoodbye = mDNSfalse;
1433 rr->AnsweredLocalQ = mDNSfalse;
1434 }
1435 }
1436 }
1437 else
1438 {
1439 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1440 p = &m->DuplicateRecords;
1441 while (*p && *p != rr) p=&(*p)->next;
1442 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1443 if (*p) { rr->RequireGoodbye = mDNSfalse; dupList = mDNStrue; }
1444 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1445 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1446 }
1447
1448 if (!*p)
1449 {
1450 // No need to log an error message if we already know this is a potentially repeated deregistration
1451 if (drt != mDNS_Dereg_repeat)
1452 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1453 return(mStatus_BadReferenceErr);
1454 }
1455
1456 // If this is a shared record and we've announced it at least once,
1457 // we need to retract that announcement before we delete the record
1458
1459 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1460 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1461 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1462 // mechanism to cope with the client callback modifying the question list while that's happening.
1463 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1464 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1465 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1466 // records, thereby invoking yet more callbacks, without limit.
1467 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1468 // actual goodbye packets.
1469
1470 #ifndef UNICAST_DISABLED
1471 if (AuthRecord_uDNS(rr))
1472 {
1473 if (rr->RequireGoodbye)
1474 {
1475 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1476 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1477 m->LocalRemoveEvents = mDNStrue;
1478 uDNS_DeregisterRecord(m, rr);
1479 // At this point unconditionally we bail out
1480 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1481 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1482 // process and will complete asynchronously. Either way we don't need to do anything more here.
1483 return(mStatus_NoError);
1484 }
1485 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1486 // from the server. In that case, if the records have been part of a group update, clear the
1487 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1488 rr->updateid = zeroID;
1489
1490 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1491 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1492 // This happens today when we turn on/off interface where we get multiple network transitions
1493 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1494 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1495 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1496 // NAT state here takes care of the case where we did not send goodbyes at all.
1497 if (rr->NATinfo.clientContext)
1498 {
1499 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1500 rr->NATinfo.clientContext = mDNSNULL;
1501 }
1502 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1503 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1504 }
1505 #endif // UNICAST_DISABLED
1506
1507 if (RecordType == kDNSRecordTypeUnregistered)
1508 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1509 else if (RecordType == kDNSRecordTypeDeregistering)
1510 {
1511 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1512 return(mStatus_BadReferenceErr);
1513 }
1514
1515 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1516 // We may want to consider changing this code so that we generate local-only question "rmv"
1517 // events (and maybe goodbye packets too) for unique records as well as for shared records
1518 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1519 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1520 // clause will execute here and the record will be cut from the list.
1521 if (rr->WakeUp.HMAC.l[0] ||
1522 (RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1523 {
1524 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1525 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1526 rr->resrec.rroriginalttl = 0;
1527 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1528 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
1529 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1530 m->LocalRemoveEvents = mDNStrue;
1531 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1532 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1533 }
1534 else
1535 {
1536 if (!dupList && RRLocalOnly(rr))
1537 {
1538 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1539 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1540 }
1541 else
1542 {
1543 *p = rr->next; // Cut this record from the list
1544 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1545 }
1546 // If someone is about to look at this, bump the pointer forward
1547 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
1548 rr->next = mDNSNULL;
1549
1550 // Should we generate local remove events here?
1551 // i.e. something like:
1552 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1553
1554 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1555 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1556
1557 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1558 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1559 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1560
1561 // If we have an update queued up which never executed, give the client a chance to free that memory
1562 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
1563
1564
1565 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1566 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1567 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1568 // so any attempt to touch rr after this is likely to lead to a crash.
1569 if (drt != mDNS_Dereg_conflict)
1570 {
1571 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1572 LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m, rr));
1573 if (rr->RecordCallback)
1574 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
1575 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1576 }
1577 else
1578 {
1579 RecordProbeFailure(m, rr);
1580 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1581 if (rr->RecordCallback)
1582 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
1583 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1584 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1585 // Note that with all the client callbacks going on, by the time we get here all the
1586 // records we marked may have been explicitly deregistered by the client anyway.
1587 r2 = m->DuplicateRecords;
1588 while (r2)
1589 {
1590 if (r2->ProbeCount != 0xFF) r2 = r2->next;
1591 else { mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict); r2 = m->DuplicateRecords; }
1592 }
1593 }
1594 }
1595 mDNS_UpdateAllowSleep(m);
1596 return(mStatus_NoError);
1597 }
1598
1599 // ***************************************************************************
1600 #if COMPILER_LIKES_PRAGMA_MARK
1601 #pragma mark -
1602 #pragma mark - Packet Sending Functions
1603 #endif
1604
1605 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1606 {
1607 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1608 {
1609 **nrpp = rr;
1610 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1611 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1612 // The referenced record will definitely be acceptable (by recursive application of this rule)
1613 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1614 rr->NR_AdditionalTo = add;
1615 *nrpp = &rr->NextResponse;
1616 }
1617 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1618 }
1619
1620 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1621 {
1622 AuthRecord *rr, *rr2;
1623 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
1624 {
1625 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1626 // later in the "for" loop, and we will follow further "additional" links then.)
1627 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1628 AddRecordToResponseList(nrpp, rr->Additional1, rr);
1629
1630 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
1631 AddRecordToResponseList(nrpp, rr->Additional2, rr);
1632
1633 // For SRV records, automatically add the Address record(s) for the target host
1634 if (rr->resrec.rrtype == kDNSType_SRV)
1635 {
1636 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1637 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1638 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1639 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
1640 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
1641 AddRecordToResponseList(nrpp, rr2, rr);
1642 }
1643 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
1644 {
1645 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1646 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1647 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1648 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
1649 SameDomainName(rr->resrec.name, rr2->resrec.name))
1650 AddRecordToResponseList(nrpp, rr2, rr);
1651 }
1652 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
1653 {
1654 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
1655 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1656 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
1657 }
1658 }
1659 }
1660
1661 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
1662 {
1663 AuthRecord *rr;
1664 AuthRecord *ResponseRecords = mDNSNULL;
1665 AuthRecord **nrp = &ResponseRecords;
1666
1667 // Make a list of all our records that need to be unicast to this destination
1668 for (rr = m->ResourceRecords; rr; rr=rr->next)
1669 {
1670 // If we find we can no longer unicast this answer, clear ImmedUnicast
1671 if (rr->ImmedAnswer == mDNSInterfaceMark ||
1672 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
1673 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
1674 rr->ImmedUnicast = mDNSfalse;
1675
1676 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
1677 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
1678 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
1679 {
1680 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
1681 rr->ImmedUnicast = mDNSfalse;
1682 rr->v4Requester = zerov4Addr;
1683 rr->v6Requester = zerov6Addr;
1684 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
1685 { rr->NR_AnswerTo = (mDNSu8*)~0; *nrp = rr; nrp = &rr->NextResponse; }
1686 }
1687 }
1688
1689 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
1690
1691 while (ResponseRecords)
1692 {
1693 mDNSu8 *responseptr = m->omsg.data;
1694 mDNSu8 *newptr;
1695 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1696
1697 // Put answers in the packet
1698 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
1699 {
1700 rr = ResponseRecords;
1701 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1702 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1703 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
1704 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1705 if (!newptr && m->omsg.h.numAnswers) break; // If packet full, send it now
1706 if (newptr) responseptr = newptr;
1707 ResponseRecords = rr->NextResponse;
1708 rr->NextResponse = mDNSNULL;
1709 rr->NR_AnswerTo = mDNSNULL;
1710 rr->NR_AdditionalTo = mDNSNULL;
1711 rr->RequireGoodbye = mDNStrue;
1712 }
1713
1714 // Add additionals, if there's space
1715 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
1716 {
1717 rr = ResponseRecords;
1718 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1719 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1720 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
1721 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1722
1723 if (newptr) responseptr = newptr;
1724 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
1725 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
1726 ResponseRecords = rr->NextResponse;
1727 rr->NextResponse = mDNSNULL;
1728 rr->NR_AnswerTo = mDNSNULL;
1729 rr->NR_AdditionalTo = mDNSNULL;
1730 }
1731
1732 if (m->omsg.h.numAnswers)
1733 mDNSSendDNSMessage(m, &m->omsg, responseptr, mDNSInterface_Any, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL);
1734 }
1735 }
1736
1737 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1738 // and the client's mStatus_MemFree callback will have been invoked
1739 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
1740 {
1741 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
1742 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
1743 // it should go ahead and immediately dispose of this registration
1744 rr->resrec.RecordType = kDNSRecordTypeShared;
1745 rr->RequireGoodbye = mDNSfalse;
1746 rr->WakeUp.HMAC = zeroEthAddr;
1747 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1748 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
1749 }
1750
1751 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
1752 // any deregistering records that remain in the m->ResourceRecords list.
1753 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
1754 // which may change the record list and/or question list.
1755 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1756 mDNSlocal void DiscardDeregistrations(mDNS *const m)
1757 {
1758 if (m->CurrentRecord)
1759 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
1760 m->CurrentRecord = m->ResourceRecords;
1761
1762 while (m->CurrentRecord)
1763 {
1764 AuthRecord *rr = m->CurrentRecord;
1765 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1766 CompleteDeregistration(m, rr); // Don't touch rr after this
1767 else
1768 m->CurrentRecord = rr->next;
1769 }
1770 }
1771
1772 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
1773 {
1774 int i, val = 0;
1775 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
1776 for (i=1; i<=src[0]; i++)
1777 {
1778 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
1779 val = val * 10 + src[i] - '0';
1780 }
1781 if (val > 255) return(mStatus_Invalid);
1782 *dst = (mDNSu8)val;
1783 return(mStatus_NoError);
1784 }
1785
1786 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
1787 {
1788 int skip = CountLabels(name) - 6;
1789 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
1790 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
1791 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
1792 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
1793 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
1794 a->type = mDNSAddrType_IPv4;
1795 return(mStatus_NoError);
1796 }
1797
1798 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
1799 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
1800 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
1801
1802 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
1803 {
1804 int i, h, l;
1805 const domainname *n;
1806
1807 int skip = CountLabels(name) - 34;
1808 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
1809
1810 n = SkipLeadingLabels(name, skip);
1811 for (i=0; i<16; i++)
1812 {
1813 if (n->c[0] != 1) return mStatus_Invalid;
1814 l = HexVal(n->c[1]);
1815 n = (const domainname *)(n->c + 2);
1816
1817 if (n->c[0] != 1) return mStatus_Invalid;
1818 h = HexVal(n->c[1]);
1819 n = (const domainname *)(n->c + 2);
1820
1821 if (l<0 || h<0) return mStatus_Invalid;
1822 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
1823 }
1824
1825 a->type = mDNSAddrType_IPv6;
1826 return(mStatus_NoError);
1827 }
1828
1829 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
1830 {
1831 int skip = CountLabels(name) - 2;
1832 if (skip >= 0)
1833 {
1834 const domainname *suffix = SkipLeadingLabels(name, skip);
1835 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
1836 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
1837 }
1838 return(mDNSAddrType_None);
1839 }
1840
1841 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
1842 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
1843 {
1844 int i;
1845 mDNSu8 *ptr = m->omsg.data;
1846 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1847 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1848
1849 // 0x00 Destination address
1850 for (i=0; i<6; i++) *ptr++ = dst->b[i];
1851
1852 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1853 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
1854
1855 // 0x0C ARP Ethertype (0x0806)
1856 *ptr++ = 0x08; *ptr++ = 0x06;
1857
1858 // 0x0E ARP header
1859 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
1860 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
1861 *ptr++ = 6; // Hardware address length
1862 *ptr++ = 4; // Protocol address length
1863 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
1864
1865 // 0x16 Sender hardware address (our MAC address)
1866 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
1867
1868 // 0x1C Sender protocol address
1869 for (i=0; i<4; i++) *ptr++ = spa->b[i];
1870
1871 // 0x20 Target hardware address
1872 for (i=0; i<6; i++) *ptr++ = tha->b[i];
1873
1874 // 0x26 Target protocol address
1875 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
1876
1877 // 0x2A Total ARP Packet length 42 bytes
1878 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
1879 }
1880
1881 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
1882 {
1883 const mDNSu16 *ptr = data;
1884 while (length > 0) { length -= 2; sum += *ptr++; }
1885 sum = (sum & 0xFFFF) + (sum >> 16);
1886 sum = (sum & 0xFFFF) + (sum >> 16);
1887 return(sum != 0xFFFF ? sum : 0);
1888 }
1889
1890 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
1891 {
1892 IPv6PseudoHeader ph;
1893 ph.src = *src;
1894 ph.dst = *dst;
1895 ph.len.b[0] = length >> 24;
1896 ph.len.b[1] = length >> 16;
1897 ph.len.b[2] = length >> 8;
1898 ph.len.b[3] = length;
1899 ph.pro.b[0] = 0;
1900 ph.pro.b[1] = 0;
1901 ph.pro.b[2] = 0;
1902 ph.pro.b[3] = protocol;
1903 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
1904 }
1905
1906 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
1907 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
1908 {
1909 int i;
1910 mDNSOpaque16 checksum;
1911 mDNSu8 *ptr = m->omsg.data;
1912 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
1913 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
1914 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
1915 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] } };
1916 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
1917 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1918 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1919
1920 // 0x00 Destination address
1921 for (i=0; i<6; i++) *ptr++ = dst->b[i];
1922 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
1923 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
1924 // link with a pointless link-layer multicast.
1925 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
1926 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
1927 // *ptr++ = 0x33;
1928 // *ptr++ = 0x33;
1929 // *ptr++ = 0xFF;
1930 // *ptr++ = tpa->b[0xD];
1931 // *ptr++ = tpa->b[0xE];
1932 // *ptr++ = tpa->b[0xF];
1933
1934 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1935 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1936
1937 // 0x0C IPv6 Ethertype (0x86DD)
1938 *ptr++ = 0x86; *ptr++ = 0xDD;
1939
1940 // 0x0E IPv6 header
1941 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
1942 *ptr++ = 0x00; *ptr++ = 0x20; // Length
1943 *ptr++ = 0x3A; // Protocol == ICMPv6
1944 *ptr++ = 0xFF; // Hop Limit
1945
1946 // 0x16 Sender IPv6 address
1947 for (i=0; i<16; i++) *ptr++ = spa->b[i];
1948
1949 // 0x26 Destination IPv6 address
1950 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
1951
1952 // 0x36 NDP header
1953 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
1954 *ptr++ = 0x00; // Code
1955 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
1956 *ptr++ = flags;
1957 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
1958
1959 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
1960 {
1961 // 0x3E NDP target.
1962 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
1963 // 0x4E Source Link-layer Address
1964 // <http://www.ietf.org/rfc/rfc2461.txt>
1965 // MUST NOT be included when the source IP address is the unspecified address.
1966 // Otherwise, on link layers that have addresses this option MUST be included
1967 // in multicast solicitations and SHOULD be included in unicast solicitations.
1968 if (!mDNSIPv6AddressIsZero(*spa))
1969 {
1970 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
1971 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
1972 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1973 }
1974 }
1975 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
1976 {
1977 // 0x3E NDP target.
1978 for (i=0; i<16; i++) *ptr++ = spa->b[i];
1979 // 0x4E Target Link-layer Address
1980 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
1981 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
1982 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1983 }
1984
1985 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
1986 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
1987 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
1988 m->omsg.data[0x38] = checksum.b[0];
1989 m->omsg.data[0x39] = checksum.b[1];
1990
1991 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
1992 }
1993
1994 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
1995 {
1996 owner->u.owner.vers = 0;
1997 owner->u.owner.seq = m->SleepSeqNum;
1998 owner->u.owner.HMAC = m->PrimaryMAC;
1999 owner->u.owner.IMAC = intf->MAC;
2000 owner->u.owner.password = zeroEthAddr;
2001
2002 // Don't try to compute the optlen until *after* we've set up the data fields
2003 // 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
2004 owner->opt = kDNSOpt_Owner;
2005 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2006 }
2007
2008 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2009 {
2010 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2011 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2012 }
2013
2014 // Note about acceleration of announcements to facilitate automatic coalescing of
2015 // multiple independent threads of announcements into a single synchronized thread:
2016 // The announcements in the packet may be at different stages of maturity;
2017 // One-second interval, two-second interval, four-second interval, and so on.
2018 // After we've put in all the announcements that are due, we then consider
2019 // whether there are other nearly-due announcements that are worth accelerating.
2020 // To be eligible for acceleration, a record MUST NOT be older (further along
2021 // its timeline) than the most mature record we've already put in the packet.
2022 // In other words, younger records can have their timelines accelerated to catch up
2023 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2024 // Older records cannot have their timelines accelerated; this would just widen
2025 // the gap between them and their younger bretheren and get them even more out of sync.
2026
2027 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2028 // the record list and/or question list.
2029 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2030 mDNSlocal void SendResponses(mDNS *const m)
2031 {
2032 int pktcount = 0;
2033 AuthRecord *rr, *r2;
2034 mDNSs32 maxExistingAnnounceInterval = 0;
2035 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2036
2037 m->NextScheduledResponse = m->timenow + 0x78000000;
2038
2039 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2040
2041 for (rr = m->ResourceRecords; rr; rr=rr->next)
2042 if (rr->ImmedUnicast)
2043 {
2044 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2045 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2046 v4.ip.v4 = rr->v4Requester;
2047 v6.ip.v6 = rr->v6Requester;
2048 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2049 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2050 if (rr->ImmedUnicast)
2051 {
2052 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2053 rr->ImmedUnicast = mDNSfalse;
2054 }
2055 }
2056
2057 // ***
2058 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2059 // ***
2060
2061 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2062 for (rr = m->ResourceRecords; rr; rr=rr->next)
2063 {
2064 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2065 if (TimeToAnnounceThisRecord(rr, m->timenow))
2066 {
2067 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2068 {
2069 if (!rr->WakeUp.HMAC.l[0])
2070 {
2071 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
2072 }
2073 else
2074 {
2075 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2076 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
2077 for (r2 = rr; r2; r2=r2->next)
2078 if (r2->AnnounceCount && r2->resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC))
2079 {
2080 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2081 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2082 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2083 {
2084 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2085 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2086 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2087 }
2088 r2->LastAPTime = m->timenow;
2089 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2090 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2091 }
2092 }
2093 }
2094 else if (ResourceRecordIsValidAnswer(rr))
2095 {
2096 if (rr->AddressProxy.type)
2097 {
2098 rr->AnnounceCount--;
2099 rr->ThisAPInterval *= 2;
2100 rr->LastAPTime = m->timenow;
2101 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2102 {
2103 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2104 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2105 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2106 }
2107 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2108 {
2109 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2110 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2111 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2112 }
2113 }
2114 else
2115 {
2116 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2117 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2118 maxExistingAnnounceInterval = rr->ThisAPInterval;
2119 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2120 }
2121 }
2122 }
2123 }
2124
2125 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2126 // Eligible records that are more than half-way to their announcement time are accelerated
2127 for (rr = m->ResourceRecords; rr; rr=rr->next)
2128 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2129 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2130 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2131 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
2132 ResourceRecordIsValidAnswer(rr)))
2133 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2134
2135 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2136 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2137 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2138 // then all that means is that it won't get sent -- which would not be the end of the world.
2139 for (rr = m->ResourceRecords; rr; rr=rr->next)
2140 {
2141 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2142 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
2143 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
2144 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
2145 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
2146 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
2147 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2148 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2149 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
2150 // We also make sure we send the DeviceInfo TXT record too, if necessary
2151 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2152 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2153 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2154 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2155 {
2156 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2157 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2158 }
2159 }
2160
2161 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2162 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2163 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2164 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2165 // -- 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
2166 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2167 for (rr = m->ResourceRecords; rr; rr=rr->next)
2168 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2169 {
2170 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
2171 {
2172 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2173 if (ResourceRecordIsValidAnswer(r2))
2174 if (r2->ImmedAnswer != mDNSInterfaceMark &&
2175 r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(r2, rr))
2176 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2177 }
2178 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
2179 {
2180 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2181 if (ResourceRecordIsValidAnswer(r2))
2182 if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(r2, rr))
2183 r2->ImmedAdditional = rr->ImmedAdditional;
2184 }
2185 }
2186
2187 // Now set SendRNow state appropriately
2188 for (rr = m->ResourceRecords; rr; rr=rr->next)
2189 {
2190 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
2191 {
2192 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2193 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
2194 rr->LastMCTime = m->timenow;
2195 rr->LastMCInterface = rr->ImmedAnswer;
2196 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2197 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2198 {
2199 rr->AnnounceCount--;
2200 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2201 rr->ThisAPInterval *= 2;
2202 rr->LastAPTime = m->timenow;
2203 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2204 }
2205 }
2206 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
2207 {
2208 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
2209 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
2210 rr->LastMCTime = m->timenow;
2211 rr->LastMCInterface = rr->ImmedAnswer;
2212 }
2213 SetNextAnnounceProbeTime(m, rr);
2214 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2215 }
2216
2217 // ***
2218 // *** 2. Loop through interface list, sending records as appropriate
2219 // ***
2220
2221 while (intf)
2222 {
2223 const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2224 int numDereg = 0;
2225 int numAnnounce = 0;
2226 int numAnswer = 0;
2227 mDNSu8 *responseptr = m->omsg.data;
2228 mDNSu8 *newptr;
2229 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2230
2231 // First Pass. Look for:
2232 // 1. Deregistering records that need to send their goodbye packet
2233 // 2. Updated records that need to retract their old data
2234 // 3. Answers and announcements we need to send
2235 for (rr = m->ResourceRecords; rr; rr=rr->next)
2236 {
2237
2238 // Skip this interface if the record InterfaceID is *Any and the record is not
2239 // appropriate for the interface type.
2240 if ((rr->SendRNow == intf->InterfaceID) &&
2241 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf)))
2242 {
2243 LogInfo("SendResponses: Not Sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
2244 rr->SendRNow = GetNextActiveInterfaceID(intf);
2245 }
2246 else if (rr->SendRNow == intf->InterfaceID)
2247 {
2248 RData *OldRData = rr->resrec.rdata;
2249 mDNSu16 oldrdlength = rr->resrec.rdlength;
2250 mDNSu8 active = (mDNSu8)
2251 (rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
2252 (m->SleepState != SleepState_Sleeping || intf->SPSAddr[0].type || intf->SPSAddr[1].type || intf->SPSAddr[2].type));
2253 newptr = mDNSNULL;
2254 if (rr->NewRData && active)
2255 {
2256 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2257 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2258 {
2259 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2260 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2261 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
2262 }
2263 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2264 }
2265
2266 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2267 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2268 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2269 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2270 if (newptr)
2271 {
2272 responseptr = newptr;
2273 rr->RequireGoodbye = active;
2274 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2275 else if (rr->LastAPTime == m->timenow) numAnnounce++; else numAnswer++;
2276 }
2277
2278 if (rr->NewRData && active)
2279 SetNewRData(&rr->resrec, OldRData, oldrdlength);
2280
2281 // The first time through (pktcount==0), if this record is verified unique
2282 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2283 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2284 rr->SendNSECNow = mDNSInterfaceMark;
2285
2286 if (newptr) // If succeeded in sending, advance to next interface
2287 {
2288 // If sending on all interfaces, go to next interface; else we're finished now
2289 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2290 rr->SendRNow = GetNextActiveInterfaceID(intf);
2291 else
2292 rr->SendRNow = mDNSNULL;
2293 }
2294 }
2295 }
2296
2297 // Second Pass. Add additional records, if there's space.
2298 newptr = responseptr;
2299 for (rr = m->ResourceRecords; rr; rr=rr->next)
2300 if (rr->ImmedAdditional == intf->InterfaceID)
2301 if (ResourceRecordIsValidAnswer(rr))
2302 {
2303 // If we have at least one answer already in the packet, then plan to add additionals too
2304 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2305
2306 // If we're not planning to send any additionals, but this record is a unique one, then
2307 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2308 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2309 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2310 {
2311 const AuthRecord *a;
2312 for (a = m->ResourceRecords; a; a=a->next)
2313 if (a->LastMCTime == m->timenow &&
2314 a->LastMCInterface == intf->InterfaceID &&
2315 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2316 }
2317 if (!SendAdditional) // If we don't want to send this after all,
2318 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
2319 else if (newptr) // Else, try to add it if we can
2320 {
2321 // The first time through (pktcount==0), if this record is verified unique
2322 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2323 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2324 rr->SendNSECNow = mDNSInterfaceMark;
2325
2326 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2327 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2328 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2329 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2330 if (newptr)
2331 {
2332 responseptr = newptr;
2333 rr->ImmedAdditional = mDNSNULL;
2334 rr->RequireGoodbye = mDNStrue;
2335 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2336 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2337 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2338 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2339 rr->LastMCTime = m->timenow;
2340 rr->LastMCInterface = intf->InterfaceID;
2341 }
2342 }
2343 }
2344
2345 // Third Pass. Add NSEC records, if there's space.
2346 // When we're generating an NSEC record in response to a specify query for that type
2347 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2348 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2349 for (rr = m->ResourceRecords; rr; rr=rr->next)
2350 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2351 {
2352 AuthRecord nsec;
2353 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2354 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2355 AssignDomainName(&nsec.namestorage, rr->resrec.name);
2356 mDNSPlatformMemZero(nsec.rdatastorage.u.nsec.bitmap, sizeof(nsec.rdatastorage.u.nsec.bitmap));
2357 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2358 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2359 {
2360 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2361 else nsec.rdatastorage.u.nsec.bitmap[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2362 }
2363 newptr = responseptr;
2364 if (!r2) // If we successfully built our NSEC record, add it to the packet now
2365 {
2366 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2367 if (newptr) responseptr = newptr;
2368 }
2369
2370 // If we successfully put the NSEC record, clear the SendNSECNow flag
2371 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2372 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2373 {
2374 rr->SendNSECNow = mDNSNULL;
2375 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2376 for (r2 = rr->next; r2; r2=r2->next)
2377 if (SameResourceRecordNameClassInterface(r2, rr))
2378 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2379 r2->SendNSECNow = mDNSNULL;
2380 }
2381 }
2382
2383 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2384 {
2385 // If we have data to send, add OWNER option if necessary, then send packet
2386
2387 if (OwnerRecordSpace)
2388 {
2389 AuthRecord opt;
2390 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2391 opt.resrec.rrclass = NormalMaxDNSMessageData;
2392 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
2393 opt.resrec.rdestimate = sizeof(rdataOPT);
2394 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2395 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2396 if (newptr) { responseptr = newptr; LogSPS("SendResponses put %s", ARDisplayString(m, &opt)); }
2397 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2398 LogSPS("SendResponses: No space in packet for Owner OPT record (%d/%d/%d/%d) %s",
2399 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2400 else
2401 LogMsg("SendResponses: How did we fail to have space for Owner OPT record (%d/%d/%d/%d) %s",
2402 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2403 }
2404
2405 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2406 numDereg, numDereg == 1 ? "" : "s",
2407 numAnnounce, numAnnounce == 1 ? "" : "s",
2408 numAnswer, numAnswer == 1 ? "" : "s",
2409 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2410
2411 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
2412 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
2413 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2414 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
2415 // There might be more things to send on this interface, so go around one more time and try again.
2416 }
2417 else // Nothing more to send on this interface; go to next
2418 {
2419 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
2420 #if MDNS_DEBUGMSGS && 0
2421 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2422 debugf(msg, intf, next);
2423 #endif
2424 intf = next;
2425 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2426 }
2427 }
2428
2429 // ***
2430 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2431 // ***
2432
2433 if (m->CurrentRecord)
2434 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2435 m->CurrentRecord = m->ResourceRecords;
2436 while (m->CurrentRecord)
2437 {
2438 rr = m->CurrentRecord;
2439 m->CurrentRecord = rr->next;
2440
2441 if (rr->SendRNow)
2442 {
2443 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
2444 LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr->SendRNow, rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
2445 rr->SendRNow = mDNSNULL;
2446 }
2447
2448 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2449 {
2450 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
2451
2452 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
2453 {
2454 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
2455 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
2456 }
2457 else
2458 {
2459 rr->ImmedAnswer = mDNSNULL;
2460 rr->ImmedUnicast = mDNSfalse;
2461 rr->v4Requester = zerov4Addr;
2462 rr->v6Requester = zerov6Addr;
2463 }
2464 }
2465 }
2466 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
2467 }
2468
2469 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2470 // so we want to be lazy about how frequently we do it.
2471 // 1. If a cache record is currently referenced by *no* active questions,
2472 // then we don't mind expiring it up to a minute late (who will know?)
2473 // 2. Else, if a cache record is due for some of its final expiration queries,
2474 // we'll allow them to be late by up to 2% of the TTL
2475 // 3. Else, if a cache record has completed all its final expiration queries without success,
2476 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2477 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2478 // so allow at most 1/10 second lateness
2479 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2480 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2481 #define CacheCheckGracePeriod(RR) ( \
2482 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
2483 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
2484 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
2485 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
2486
2487 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2488
2489 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
2490 {
2491 if (m->rrcache_nextcheck[slot] - event > 0)
2492 m->rrcache_nextcheck[slot] = event;
2493 if (m->NextCacheCheck - event > 0)
2494 m->NextCacheCheck = event;
2495 }
2496
2497 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2498 // rr->TimeRcvd
2499 // rr->resrec.rroriginalttl
2500 // rr->UnansweredQueries
2501 // rr->CRActiveQuestion
2502 mDNSlocal void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
2503 {
2504 rr->NextRequiredQuery = RRExpireTime(rr);
2505
2506 // If we have an active question, then see if we want to schedule a refresher query for this record.
2507 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2508 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
2509 {
2510 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
2511 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
2512 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2513 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
2514 }
2515
2516 ScheduleNextCacheCheckTime(m, HashSlot(rr->resrec.name), NextCacheCheckEvent(rr));
2517 }
2518
2519 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
2520 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
2521 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
2522 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 30)
2523
2524 mDNSlocal mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
2525 {
2526 if (interval < kMinimumReconfirmTime)
2527 interval = kMinimumReconfirmTime;
2528 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
2529 interval = 0x10000000;
2530
2531 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2532 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
2533 {
2534 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2535 // For all the reconfirmations in a given batch, we want to use the same random value
2536 // so that the reconfirmation questions can be grouped into a single query packet
2537 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(0x3FFFFFFF);
2538 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
2539 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
2540 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
2541 SetNextCacheCheckTimeForRecord(m, rr);
2542 }
2543 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2544 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
2545 return(mStatus_NoError);
2546 }
2547
2548 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
2549
2550 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2551 // It also appends to the list of known answer records that need to be included,
2552 // and updates the forcast for the size of the known answer section.
2553 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
2554 CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
2555 {
2556 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353;
2557 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2558 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
2559 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
2560 if (!newptr)
2561 {
2562 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2563 return(mDNSfalse);
2564 }
2565 else
2566 {
2567 mDNSu32 forecast = *answerforecast;
2568 const mDNSu32 slot = HashSlot(&q->qname);
2569 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2570 CacheRecord *rr;
2571 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
2572
2573 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
2574 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2575 !(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
2576 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not already in the known answer list
2577 rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
2578 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
2579 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
2580 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
2581 {
2582 // We don't want to include unique records in the Known Answer section. The Known Answer section
2583 // is intended to suppress floods of shared-record replies from many other devices on the network.
2584 // That concept really does not apply to unique records, and indeed if we do send a query for
2585 // which we have a unique record already in our cache, then including that unique record as a
2586 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2587
2588 *ka = rr; // Link this record into our known answer chain
2589 ka = &rr->NextInKAList;
2590 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2591 forecast += 12 + rr->resrec.rdestimate;
2592 // If we're trying to put more than one question in this packet, and it doesn't fit
2593 // then undo that last question and try again next time
2594 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
2595 {
2596 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
2597 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data);
2598 query->h.numQuestions--;
2599 ka = *kalistptrptr; // Go back to where we started and retract these answer records
2600 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
2601 return(mDNSfalse); // Return false, so we'll try again in the next packet
2602 }
2603 }
2604
2605 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2606 *queryptr = newptr; // Update the packet pointer
2607 *answerforecast = forecast; // Update the forecast
2608 *kalistptrptr = ka; // Update the known answer list pointer
2609 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
2610
2611 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // For every resource record in our cache,
2612 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2613 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not in the known answer list
2614 SameNameRecordAnswersQuestion(&rr->resrec, q)) // which answers our question
2615 {
2616 rr->UnansweredQueries++; // indicate that we're expecting a response
2617 rr->LastUnansweredTime = m->timenow;
2618 SetNextCacheCheckTimeForRecord(m, rr);
2619 }
2620
2621 return(mDNStrue);
2622 }
2623 }
2624
2625 // When we have a query looking for a specified name, but there appear to be no answers with
2626 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
2627 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
2628 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
2629 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
2630 // A typical reconfirmation scenario might go like this:
2631 // Depth 0: Name "myhost.local" has no address records
2632 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
2633 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
2634 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
2635 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
2636 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
2637 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
2638 {
2639 mDNSu32 slot;
2640 CacheGroup *cg;
2641 CacheRecord *cr;
2642 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
2643 FORALL_CACHERECORDS(slot, cg, cr)
2644 {
2645 domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
2646 if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
2647 {
2648 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
2649 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
2650 if (depth < 5) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
2651 }
2652 }
2653 }
2654
2655 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
2656 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
2657 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
2658 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
2659 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
2660 {
2661 CacheGroup *const cg = CacheGroupForName(m, HashSlot(name), namehash, name);
2662 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
2663 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
2664 return(cr);
2665 }
2666
2667 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
2668 {
2669 CacheGroup *const cg = CacheGroupForName(m, HashSlot(&q->qname), q->qnamehash, &q->qname);
2670 const CacheRecord *cr, *bestcr = mDNSNULL;
2671 mDNSu32 bestmetric = 1000000;
2672 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
2673 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
2674 if (cr != c0 && cr != c1) // that's not one we've seen before,
2675 if (SameNameRecordAnswersQuestion(&cr->resrec, q)) // and answers our browse query,
2676 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
2677 {
2678 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
2679 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
2680 }
2681 return(bestcr);
2682 }
2683
2684 // Finds the three best Sleep Proxies we currently have in our cache
2685 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
2686 {
2687 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
2688 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
2689 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
2690 }
2691
2692 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
2693 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
2694 {
2695 int i;
2696 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2697 }
2698
2699 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
2700 {
2701 int i;
2702 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2703 }
2704
2705 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
2706 {
2707 int i;
2708 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
2709 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
2710 for (i=0; i<DupSuppressInfoSize; i++)
2711 if (ds[i].InterfaceID == intf->InterfaceID)
2712 {
2713 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
2714 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
2715 if (v4 && v6) return(mDNStrue);
2716 }
2717 return(mDNSfalse);
2718 }
2719
2720 mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
2721 {
2722 int i, j;
2723
2724 // See if we have this one in our list somewhere already
2725 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
2726
2727 // If not, find a slot we can re-use
2728 if (i >= DupSuppressInfoSize)
2729 {
2730 i = 0;
2731 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
2732 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
2733 i = j;
2734 }
2735
2736 // Record the info about this query we saw
2737 ds[i].Time = Time;
2738 ds[i].InterfaceID = InterfaceID;
2739 ds[i].Type = Type;
2740
2741 return(i);
2742 }
2743
2744 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
2745 {
2746 int len, i, cnt;
2747 mDNSInterfaceID InterfaceID = q->InterfaceID;
2748 domainname *d = &q->qname;
2749
2750 // We can't send magic packets without knowing which interface to send it on.
2751 if (InterfaceID == mDNSInterface_Any || InterfaceID == mDNSInterface_LocalOnly || InterfaceID == mDNSInterface_P2P)
2752 {
2753 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
2754 return;
2755 }
2756
2757 // Split MAC@IPAddress and pass them separately
2758 len = d->c[0];
2759 i = 1;
2760 cnt = 0;
2761 for (i = 1; i < len; i++)
2762 {
2763 if (d->c[i] == '@')
2764 {
2765 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
2766 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
2767 if (cnt != 5)
2768 {
2769 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
2770 return;
2771 }
2772 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
2773 {
2774 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
2775 return;
2776 }
2777 if ((len - i) > (int)(sizeof(IPAddr) - 1))
2778 {
2779 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
2780 return;
2781 }
2782 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
2783 EthAddr[i - 1] = 0;
2784 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
2785 IPAddr[len - i] = 0;
2786 mDNSPlatformSendWakeupPacket(m, InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
2787 return;
2788 }
2789 else if (d->c[i] == ':')
2790 cnt++;
2791 }
2792 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
2793 }
2794
2795
2796 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
2797 {
2798 // If more than 90% of the way to the query time, we should unconditionally accelerate it
2799 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
2800 return(mDNStrue);
2801
2802 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
2803 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
2804 {
2805 // We forecast: qname (n) type (2) class (2)
2806 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
2807 const mDNSu32 slot = HashSlot(&q->qname);
2808 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2809 const CacheRecord *rr;
2810 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
2811 if (rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
2812 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
2813 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
2814 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0)// and we'll ask at least once again before NextRequiredQuery
2815 {
2816 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2817 forecast += 12 + rr->resrec.rdestimate;
2818 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
2819 }
2820 return(mDNStrue);
2821 }
2822
2823 return(mDNSfalse);
2824 }
2825
2826 // How Standard Queries are generated:
2827 // 1. The Question Section contains the question
2828 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
2829
2830 // How Probe Queries are generated:
2831 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
2832 // if some other host is already using *any* records with this name, we want to know about it.
2833 // 2. The Authority Section contains the proposed values we intend to use for one or more
2834 // of our records with that name (analogous to the Update section of DNS Update packets)
2835 // because if some other host is probing at the same time, we each want to know what the other is
2836 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
2837
2838 mDNSlocal void SendQueries(mDNS *const m)
2839 {
2840 mDNSu32 slot;
2841 CacheGroup *cg;
2842 CacheRecord *cr;
2843 AuthRecord *ar;
2844 int pktcount = 0;
2845 DNSQuestion *q;
2846 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
2847 mDNSs32 maxExistingQuestionInterval = 0;
2848 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2849 CacheRecord *KnownAnswerList = mDNSNULL;
2850
2851 // 1. If time for a query, work out what we need to do
2852
2853 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
2854 // to their NextRequiredQuery to be worth batching them together with this one
2855 FORALL_CACHERECORDS(slot, cg, cr)
2856 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
2857 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
2858 {
2859 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
2860 q = cr->CRActiveQuestion;
2861 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
2862 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
2863 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
2864 if (q->Target.type) q->SendQNow = mDNSInterfaceMark; // If targeted query, mark it
2865 else if (!mDNSOpaque16IsZero(q->TargetQID)) { q->LastQTime = m->timenow - q->ThisQInterval; cr->UnansweredQueries++; }
2866 else if (q->SendQNow == mDNSNULL) q->SendQNow = cr->resrec.InterfaceID;
2867 else if (q->SendQNow != cr->resrec.InterfaceID) q->SendQNow = mDNSInterfaceMark;
2868 }
2869
2870 // Scan our list of questions to see which:
2871 // *WideArea* queries need to be sent
2872 // *unicast* queries need to be sent
2873 // *multicast* queries we're definitely going to send
2874 if (m->CurrentQuestion)
2875 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2876 m->CurrentQuestion = m->Questions;
2877 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
2878 {
2879 q = m->CurrentQuestion;
2880 if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
2881 {
2882 mDNSu8 *qptr = m->omsg.data;
2883 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
2884
2885 // 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
2886 if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
2887 if (q->LocalSocket)
2888 {
2889 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
2890 qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
2891 mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL);
2892 q->ThisQInterval *= QuestionIntervalStep;
2893 }
2894 if (q->ThisQInterval > MaxQuestionInterval)
2895 q->ThisQInterval = MaxQuestionInterval;
2896 q->LastQTime = m->timenow;
2897 q->LastQTxTime = m->timenow;
2898 q->RecentAnswerPkts = 0;
2899 q->SendQNow = mDNSNULL;
2900 q->ExpectUnicastResp = NonZeroTime(m->timenow);
2901 }
2902 else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
2903 {
2904 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2905 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
2906 if (maxExistingQuestionInterval < q->ThisQInterval)
2907 maxExistingQuestionInterval = q->ThisQInterval;
2908 }
2909 // If m->CurrentQuestion wasn't modified out from under us, advance it now
2910 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
2911 // m->CurrentQuestion point to the right question
2912 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
2913 }
2914 while (m->CurrentQuestion)
2915 {
2916 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2917 m->CurrentQuestion = m->CurrentQuestion->next;
2918 }
2919 m->CurrentQuestion = mDNSNULL;
2920
2921 // Scan our list of questions
2922 // (a) to see if there are any more that are worth accelerating, and
2923 // (b) to update the state variables for *all* the questions we're going to send
2924 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
2925 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
2926 // 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.
2927 m->NextScheduledQuery = m->timenow + 0x78000000;
2928 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
2929 {
2930 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow ||
2931 (!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
2932 {
2933 // If at least halfway to next query time, advance to next interval
2934 // If less than halfway to next query time, then
2935 // treat this as logically a repeat of the last transmission, without advancing the interval
2936 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
2937 {
2938 //LogInfo("Accelerating %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2939 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
2940 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
2941 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
2942 q->ThisQInterval *= QuestionIntervalStep;
2943 if (q->ThisQInterval > MaxQuestionInterval)
2944 q->ThisQInterval = MaxQuestionInterval;
2945 else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
2946 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
2947 {
2948 // Generally don't need to log this.
2949 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
2950 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
2951 // and when there simply happen to be no instances of the service the client is looking
2952 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
2953 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
2954 q->qname.c, DNSTypeName(q->qtype));
2955 // Sending third query, and no answers yet; time to begin doubting the source
2956 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
2957 }
2958 }
2959
2960 // Mark for sending. (If no active interfaces, then don't even try.)
2961 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
2962 if (q->SendOnAll)
2963 {
2964 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
2965 q->LastQTime = m->timenow;
2966 }
2967
2968 // If we recorded a duplicate suppression for this question less than half an interval ago,
2969 // then we consider it recent enough that we don't need to do an identical query ourselves.
2970 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
2971
2972 q->LastQTxTime = m->timenow;
2973 q->RecentAnswerPkts = 0;
2974 if (q->RequestUnicast) q->RequestUnicast--;
2975 }
2976 // For all questions (not just the ones we're sending) check what the next scheduled event will be
2977 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
2978 SetNextQueryTime(m,q);
2979 }
2980
2981 // 2. Scan our authoritative RR list to see what probes we might need to send
2982
2983 m->NextScheduledProbe = m->timenow + 0x78000000;
2984
2985 if (m->CurrentRecord)
2986 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2987 m->CurrentRecord = m->ResourceRecords;
2988 while (m->CurrentRecord)
2989 {
2990 ar = m->CurrentRecord;
2991 m->CurrentRecord = ar->next;
2992 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
2993 {
2994 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
2995 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
2996 {
2997 SetNextAnnounceProbeTime(m, ar);
2998 }
2999 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3000 else if (ar->ProbeCount)
3001 {
3002 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3003 {
3004 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3005 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3006 }
3007 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3008 {
3009 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3010 // IPv6 source = zero
3011 // No target hardware address
3012 // IPv6 target address is address we're probing
3013 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3014 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3015 }
3016 // Mark for sending. (If no active interfaces, then don't even try.)
3017 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3018 ar->LastAPTime = m->timenow;
3019 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3020 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3021 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3022 ar->ProbeCount = DefaultProbeCountForTypeUnique;
3023 ar->ProbeCount--;
3024 SetNextAnnounceProbeTime(m, ar);
3025 if (ar->ProbeCount == 0)
3026 {
3027 // If this is the last probe for this record, then see if we have any matching records
3028 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3029 AuthRecord *r2;
3030 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3031 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3032 r2->ProbeCount = 0;
3033 // ... then acknowledge this record to the client.
3034 // We do this optimistically, just as we're about to send the third probe.
3035 // This helps clients that both advertise and browse, and want to filter themselves
3036 // from the browse results list, because it helps ensure that the registration
3037 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3038 // A potential downside is that we could deliver a registration confirmation and then find out
3039 // moments later that there's a name conflict, but applications have to be prepared to handle
3040 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3041 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3042 }
3043 }
3044 // else, if it has now finished probing, move it to state Verified,
3045 // and update m->NextScheduledResponse so it will be announced
3046 else
3047 {
3048 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
3049 ar->resrec.RecordType = kDNSRecordTypeVerified;
3050 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3051 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3052 SetNextAnnounceProbeTime(m, ar);
3053 }
3054 }
3055 }
3056 m->CurrentRecord = m->DuplicateRecords;
3057 while (m->CurrentRecord)
3058 {
3059 ar = m->CurrentRecord;
3060 m->CurrentRecord = ar->next;
3061 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3062 AcknowledgeRecord(m, ar);
3063 }
3064
3065 // 3. Now we know which queries and probes we're sending,
3066 // go through our interface list sending the appropriate queries on each interface
3067 while (intf)
3068 {
3069 const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3070 mDNSu8 *queryptr = m->omsg.data;
3071 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3072 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3073 if (!KnownAnswerList)
3074 {
3075 // Start a new known-answer list
3076 CacheRecord **kalistptr = &KnownAnswerList;
3077 mDNSu32 answerforecast = OwnerRecordSpace; // We start by assuming we'll need at least enough space to put the Owner Option
3078
3079 // Put query questions in this packet
3080 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3081 {
3082 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3083 {
3084 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3085 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
3086 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3087
3088 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3089 if (SuppressOnThisInterface(q->DupSuppress, intf) ||
3090 BuildQuestion(m, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3091 {
3092 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3093 if (q->WakeOnResolveCount)
3094 {
3095 mDNSSendWakeOnResolve(m, q);
3096 q->WakeOnResolveCount--;
3097 }
3098 }
3099 }
3100 }
3101
3102 // Put probe questions in this packet
3103 for (ar = m->ResourceRecords; ar; ar=ar->next)
3104 if (ar->SendRNow == intf->InterfaceID)
3105 {
3106 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353;
3107 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3108 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3109 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3110 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3111 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, (mDNSu16)(ar->resrec.rrclass | ucbit));
3112 if (newptr)
3113 {
3114 queryptr = newptr;
3115 answerforecast = forecast;
3116 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3117 ar->IncludeInProbe = mDNStrue;
3118 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d",
3119 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount);
3120 }
3121 }
3122 }
3123
3124 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3125 while (KnownAnswerList)
3126 {
3127 CacheRecord *ka = KnownAnswerList;
3128 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3129 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers,
3130 &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd, m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace);
3131 if (newptr)
3132 {
3133 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3134 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3135 queryptr = newptr;
3136 KnownAnswerList = ka->NextInKAList;
3137 ka->NextInKAList = mDNSNULL;
3138 }
3139 else
3140 {
3141 // If we ran out of space and we have more than one question in the packet, that's an error --
3142 // we shouldn't have put more than one question if there was a risk of us running out of space.
3143 if (m->omsg.h.numQuestions > 1)
3144 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3145 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3146 break;
3147 }
3148 }
3149
3150 for (ar = m->ResourceRecords; ar; ar=ar->next)
3151 if (ar->IncludeInProbe)
3152 {
3153 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3154 ar->IncludeInProbe = mDNSfalse;
3155 if (newptr) queryptr = newptr;
3156 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3157 }
3158
3159 if (queryptr > m->omsg.data)
3160 {
3161 if (OwnerRecordSpace)
3162 {
3163 AuthRecord opt;
3164 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3165 opt.resrec.rrclass = NormalMaxDNSMessageData;
3166 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
3167 opt.resrec.rdestimate = sizeof(rdataOPT);
3168 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3169 LogSPS("SendQueries putting %s", ARDisplayString(m, &opt));
3170 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3171 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3172 if (!queryptr)
3173 LogMsg("SendQueries: How did we fail to have space for the OPT record (%d/%d/%d/%d) %s",
3174 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3175 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3176 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3177 LogMsg("SendQueries: Why did we generate oversized packet with OPT record %p %p %p (%d/%d/%d/%d) %s",
3178 m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr,
3179 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3180 }
3181
3182 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3183 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3184 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
3185 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
3186 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
3187 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3188 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
3189 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
3190 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3191 if (++pktcount >= 1000)
3192 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3193 // There might be more records left in the known answer list, or more questions to send
3194 // on this interface, so go around one more time and try again.
3195 }
3196 else // Nothing more to send on this interface; go to next
3197 {
3198 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3199 #if MDNS_DEBUGMSGS && 0
3200 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
3201 debugf(msg, intf, next);
3202 #endif
3203 intf = next;
3204 }
3205 }
3206
3207 // 4. Final housekeeping
3208
3209 // 4a. Debugging check: Make sure we announced all our records
3210 for (ar = m->ResourceRecords; ar; ar=ar->next)
3211 if (ar->SendRNow)
3212 {
3213 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
3214 LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar->SendRNow, ar->resrec.InterfaceID, ARDisplayString(m, ar));
3215 ar->SendRNow = mDNSNULL;
3216 }
3217
3218 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3219 // that their interface which went away might come back again, the logic will want to send queries
3220 // for those records, but we can't because their interface isn't here any more, so to keep the
3221 // state machine ticking over we just pretend we did so.
3222 // If the interface does not come back in time, the cache record will expire naturally
3223 FORALL_CACHERECORDS(slot, cg, cr)
3224 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3225 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3226 {
3227 cr->UnansweredQueries++;
3228 cr->CRActiveQuestion->SendQNow = mDNSNULL;
3229 SetNextCacheCheckTimeForRecord(m, cr);
3230 }
3231
3232 // 4c. Debugging check: Make sure we sent all our planned questions
3233 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3234 // we legitimately couldn't send because the interface is no longer available
3235 for (q = m->Questions; q; q=q->next)
3236 if (q->SendQNow)
3237 {
3238 DNSQuestion *x;
3239 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
3240 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));
3241 q->SendQNow = mDNSNULL;
3242 }
3243 }
3244
3245 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password)
3246 {
3247 int i, j;
3248 mDNSu8 *ptr = m->omsg.data;
3249 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
3250 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
3251
3252 // 0x00 Destination address
3253 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3254
3255 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
3256 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
3257
3258 // 0x0C Ethertype (0x0842)
3259 *ptr++ = 0x08;
3260 *ptr++ = 0x42;
3261
3262 // 0x0E Wakeup sync sequence
3263 for (i=0; i<6; i++) *ptr++ = 0xFF;
3264
3265 // 0x14 Wakeup data
3266 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3267
3268 // 0x74 Password
3269 for (i=0; i<6; i++) *ptr++ = password->b[i];
3270
3271 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3272
3273 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
3274 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
3275 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
3276 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
3277 // So, we send one of each, unicast first, then broadcast second.
3278 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
3279 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3280 }
3281
3282 // ***************************************************************************
3283 #if COMPILER_LIKES_PRAGMA_MARK
3284 #pragma mark -
3285 #pragma mark - RR List Management & Task Management
3286 #endif
3287
3288 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
3289 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
3290 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
3291 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
3292 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
3293 {
3294 DNSQuestion *const q = m->CurrentQuestion;
3295 mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
3296
3297 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
3298 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
3299
3300 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
3301 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
3302 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
3303 // we check to see if that query already has a unique local answer.
3304 if (q->LOAddressAnswers)
3305 {
3306 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
3307 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
3308 q->LOAddressAnswers);
3309 return;
3310 }
3311
3312 if (QuerySuppressed(q))
3313 {
3314 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
3315 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
3316 // that are timing out, which we know are answered with Negative cache record when timing out.
3317 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
3318 return;
3319 }
3320
3321 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
3322 // may be called twice, once when the record is received, and again when it's time to notify local clients.
3323 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
3324
3325 rr->LastUsed = m->timenow;
3326 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
3327 {
3328 if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
3329 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
3330 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
3331 rr->CRActiveQuestion = q; // We know q is non-null
3332 SetNextCacheCheckTimeForRecord(m, rr);
3333 }
3334
3335 // If this is:
3336 // (a) a no-cache add, where we've already done at least one 'QM' query, or
3337 // (b) a normal add, where we have at least one unique-type answer,
3338 // then there's no need to keep polling the network.
3339 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
3340 // We do this for mDNS questions and uDNS one-shot questions, but not for
3341 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
3342 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
3343 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
3344 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
3345 {
3346 q->LastQTime = m->timenow;
3347 q->LastQTxTime = m->timenow;
3348 q->RecentAnswerPkts = 0;
3349 q->ThisQInterval = MaxQuestionInterval;
3350 q->RequestUnicast = mDNSfalse;
3351 debugf("AnswerCurrentQuestionWithResourceRecord: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3352 }
3353
3354 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
3355
3356 // Only deliver negative answers if client has explicitly requested them
3357 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
3358 if (!AddRecord || !q->ReturnIntermed) return;
3359
3360 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
3361 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
3362 {
3363 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
3364 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
3365 {
3366 CacheRecord neg;
3367 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
3368 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
3369 }
3370 else
3371 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
3372 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3373 }
3374 // Note: Proceed with caution here because client callback function is allowed to do anything,
3375 // including starting/stopping queries, registering/deregistering records, etc.
3376
3377 if (followcname && m->CurrentQuestion == q)
3378 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
3379 }
3380
3381 // New Questions are answered through AnswerNewQuestion. But there may not have been any
3382 // matching cache records for the questions when it is called. There are two possibilities.
3383 //
3384 // 1) There are no cache records
3385 // 2) There are cache records but the DNSServers between question and cache record don't match.
3386 //
3387 // In the case of (1), where there are no cache records and later we add them when we get a response,
3388 // CacheRecordAdd/CacheRecordDeferredAdd will take care of adding the cache and delivering the ADD
3389 // events to the application. If we already have a cache entry, then no ADD events are delivered
3390 // unless the RDATA has changed
3391 //
3392 // In the case of (2) where we had the cache records and did not answer because of the DNSServer mismatch,
3393 // we need to answer them whenever we change the DNSServer. But we can't do it at the instant the DNSServer
3394 // changes because when we do the callback, the question can get deleted and the calling function would not
3395 // know how to handle it. So, we run this function from mDNS_Execute to handle DNSServer changes on the
3396 // question
3397
3398 mDNSlocal void AnswerQuestionsForDNSServerChanges(mDNS *const m)
3399 {
3400 DNSQuestion *q;
3401 DNSQuestion *qnext;
3402 CacheRecord *rr;
3403 mDNSu32 slot;
3404 CacheGroup *cg;
3405
3406 if (m->CurrentQuestion)
3407 LogMsg("AnswerQuestionsForDNSServerChanges: ERROR m->CurrentQuestion already set: %##s (%s)",
3408 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3409
3410 for (q = m->Questions; q && q != m->NewQuestions; q = qnext)
3411 {
3412 qnext = q->next;
3413
3414 // multicast or DNSServers did not change.
3415 if (mDNSOpaque16IsZero(q->TargetQID)) continue;
3416 if (!q->deliverAddEvents) continue;
3417
3418 // We are going to look through the cache for this question since it changed
3419 // its DNSserver last time. Reset it so that we don't call them again. Calling
3420 // them again will deliver duplicate events to the application
3421 q->deliverAddEvents = mDNSfalse;
3422 if (QuerySuppressed(q)) continue;
3423 m->CurrentQuestion = q;
3424 slot = HashSlot(&q->qname);
3425 cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3426 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3427 {
3428 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
3429 {
3430 LogInfo("AnswerQuestionsForDNSServerChanges: Calling AnswerCurrentQuestionWithResourceRecord for question %p %##s using resource record %s",
3431 q, q->qname.c, CRDisplayString(m, rr));
3432 // When this question penalizes a DNS server and has no more DNS servers to pick, we normally
3433 // deliver a negative cache response and suspend the question for 60 seconds (see uDNS_CheckCurrentQuestion).
3434 // But sometimes we may already find the negative cache entry and deliver that here as the process
3435 // of changing DNS servers. When the cache entry is about to expire, we will resend the question and
3436 // that time, we need to make sure that we have a valid DNS server. Otherwise, we will deliver
3437 // a negative cache response without trying the server.
3438 if (!q->qDNSServer && !q->DuplicateOf && rr->resrec.RecordType == kDNSRecordTypePacketNegative)
3439 {
3440 DNSQuestion *qptr;
3441 SetValidDNSServers(m, q);
3442 q->qDNSServer = GetServerForQuestion(m, q);
3443 for (qptr = q->next ; qptr; qptr = qptr->next)
3444 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
3445 }
3446 q->CurrentAnswers++;
3447 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3448 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3449 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3450 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3451 }
3452 }
3453 }
3454 m->CurrentQuestion = mDNSNULL;
3455 }
3456
3457 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
3458 {
3459 rr->DelayDelivery = 0;
3460 if (m->CurrentQuestion)
3461 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
3462 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3463 m->CurrentQuestion = m->Questions;
3464 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3465 {
3466 DNSQuestion *q = m->CurrentQuestion;
3467 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3468 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3469 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3470 m->CurrentQuestion = q->next;
3471 }
3472 m->CurrentQuestion = mDNSNULL;
3473 }
3474
3475 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSu32 slot)
3476 {
3477 const mDNSs32 threshhold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
3478 const mDNSs32 start = m->timenow - 0x10000000;
3479 mDNSs32 delay = start;
3480 CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
3481 const CacheRecord *rr;
3482 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3483 if (threshhold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
3484 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
3485 delay = RRExpireTime(rr);
3486 if (delay - start > 0) return(NonZeroTime(delay));
3487 else return(0);
3488 }
3489
3490 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
3491 // If new questions are created as a result of invoking client callbacks, they will be added to
3492 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3493 // rr is a new CacheRecord just received into our cache
3494 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3495 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3496 // which may change the record list and/or question list.
3497 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3498 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
3499 {
3500 DNSQuestion *q;
3501
3502 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
3503 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
3504 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3505 {
3506 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3507 {
3508 // If this question is one that's actively sending queries, and it's received ten answers within one
3509 // second of sending the last query packet, then that indicates some radical network topology change,
3510 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
3511 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3512 // because we will anyway send another query within a few seconds. The first reset query is sent out
3513 // randomized over the next four seconds to reduce possible synchronization between machines.
3514 if (q->LastAnswerPktNum != m->PktNum)
3515 {
3516 q->LastAnswerPktNum = m->PktNum;
3517 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
3518 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
3519 {
3520 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3521 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
3522 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
3523 q->ThisQInterval = InitialQuestionInterval;
3524 SetNextQueryTime(m,q);
3525 }
3526 }
3527 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
3528 DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
3529 &rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
3530 rr->resrec.rDNSServer->port : zeroIPPort), q);
3531 q->CurrentAnswers++;
3532 q->unansweredQueries = 0;
3533 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3534 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3535 if (q->CurrentAnswers > 4000)
3536 {
3537 static int msgcount = 0;
3538 if (msgcount++ < 10)
3539 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3540 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
3541 rr->resrec.rroriginalttl = 0;
3542 rr->UnansweredQueries = MaxUnansweredQueries;
3543 }
3544 }
3545 }
3546
3547 if (!rr->DelayDelivery)
3548 {
3549 if (m->CurrentQuestion)
3550 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3551 m->CurrentQuestion = m->Questions;
3552 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3553 {
3554 q = m->CurrentQuestion;
3555 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3556 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3557 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3558 m->CurrentQuestion = q->next;
3559 }
3560 m->CurrentQuestion = mDNSNULL;
3561 }
3562
3563 SetNextCacheCheckTimeForRecord(m, rr);
3564 }
3565
3566 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3567 // If new questions are created as a result of invoking client callbacks, they will be added to
3568 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3569 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3570 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3571 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3572 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3573 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3574 // which may change the record list and/or question list.
3575 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3576 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
3577 {
3578 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
3579 if (m->CurrentQuestion)
3580 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3581 m->CurrentQuestion = m->Questions;
3582 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
3583 // since we're not caching the record and we'll get no opportunity to do this later
3584 while (m->CurrentQuestion)
3585 {
3586 DNSQuestion *q = m->CurrentQuestion;
3587 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3588 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
3589 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3590 m->CurrentQuestion = q->next;
3591 }
3592 m->CurrentQuestion = mDNSNULL;
3593 }
3594
3595 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3596 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3597 // If new questions are created as a result of invoking client callbacks, they will be added to
3598 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3599 // rr is an existing cache CacheRecord that just expired and is being deleted
3600 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3601 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3602 // which may change the record list and/or question list.
3603 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3604 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
3605 {
3606 if (m->CurrentQuestion)
3607 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3608 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3609 m->CurrentQuestion = m->Questions;
3610
3611 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3612 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3613 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3614 {
3615 DNSQuestion *q = m->CurrentQuestion;
3616 // When a question enters suppressed state, we generate RMV events and generate a negative
3617 // response. A cache may be present that answers this question e.g., cache entry generated
3618 // before the question became suppressed. We need to skip the suppressed questions here as
3619 // the RMV event has already been generated.
3620 if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
3621 {
3622 verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
3623 q->FlappingInterface1 = mDNSNULL;
3624 q->FlappingInterface2 = mDNSNULL;
3625
3626 // When a question changes DNS server, it is marked with deliverAddEvents if we find any
3627 // cache entry corresponding to the new DNS server. Before we deliver the ADD event, the
3628 // cache entry may be removed in which case CurrentAnswers can be zero.
3629 if (q->deliverAddEvents && !q->CurrentAnswers)
3630 {
3631 LogInfo("CacheRecordRmv: Question %p %##s (%s) deliverAddEvents set, DNSServer %#a:%d",
3632 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3633 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3634 m->CurrentQuestion = q->next;
3635 continue;
3636 }
3637 if (q->CurrentAnswers == 0)
3638 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3639 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3640 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3641 else
3642 {
3643 q->CurrentAnswers--;
3644 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
3645 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
3646 }
3647 if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
3648 {
3649 if (q->CurrentAnswers == 0)
3650 {
3651 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3652 q->qname.c, DNSTypeName(q->qtype));
3653 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3654 }
3655 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
3656 }
3657 }
3658 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3659 m->CurrentQuestion = q->next;
3660 }
3661 m->CurrentQuestion = mDNSNULL;
3662 }
3663
3664 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
3665 {
3666 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3667 unsigned int i;
3668 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
3669 #endif
3670 e->next = m->rrcache_free;
3671 m->rrcache_free = e;
3672 m->rrcache_totalused--;
3673 }
3674
3675 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
3676 {
3677 CacheEntity *e = (CacheEntity *)(*cp);
3678 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3679 if ((*cp)->rrcache_tail != &(*cp)->members)
3680 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3681 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
3682 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3683 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
3684 (*cp)->name = mDNSNULL;
3685 *cp = (*cp)->next; // Cut record from list
3686 ReleaseCacheEntity(m, e);
3687 }
3688
3689 mDNSlocal void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
3690 {
3691 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3692 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
3693 r->resrec.rdata = mDNSNULL;
3694 ReleaseCacheEntity(m, (CacheEntity *)r);
3695 }
3696
3697 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3698 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3699 // callbacks for old records are delivered before callbacks for newer records.
3700 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
3701 {
3702 CacheRecord **rp = &cg->members;
3703
3704 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3705 m->lock_rrcache = 1;
3706
3707 while (*rp)
3708 {
3709 CacheRecord *const rr = *rp;
3710 mDNSs32 event = RRExpireTime(rr);
3711 if (m->timenow - event >= 0) // If expired, delete it
3712 {
3713 *rp = rr->next; // Cut it from the list
3714 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3715 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
3716 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
3717 {
3718 DNSQuestion *q = rr->CRActiveQuestion;
3719 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3720 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3721 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3722 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3723 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3724 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3725 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
3726 if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
3727 {
3728 q->ThisQInterval = InitialQuestionInterval;
3729 q->LastQTime = m->timenow - q->ThisQInterval;
3730 SetNextQueryTime(m, q);
3731 }
3732 CacheRecordRmv(m, rr);
3733 m->rrcache_active--;
3734 }
3735 ReleaseCacheRecord(m, rr);
3736 }
3737 else // else, not expired; see if we need to query
3738 {
3739 // If waiting to delay delivery, do nothing until then
3740 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
3741 event = rr->DelayDelivery;
3742 else
3743 {
3744 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
3745 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3746 {
3747 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
3748 event = NextCacheCheckEvent(rr); // then just record when we want the next query
3749 else // else trigger our question to go out now
3750 {
3751 // Set NextScheduledQuery to timenow so that SendQueries() will run.
3752 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
3753 m->NextScheduledQuery = m->timenow;
3754 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3755 // which will correctly update m->NextCacheCheck for us.
3756 event = m->timenow + 0x3FFFFFFF;
3757 }
3758 }
3759 }
3760 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3761 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
3762 if (m->rrcache_nextcheck[slot] - event > 0)
3763 m->rrcache_nextcheck[slot] = event;
3764 rp = &rr->next;
3765 }
3766 }
3767 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
3768 cg->rrcache_tail = rp;
3769 m->lock_rrcache = 0;
3770 }
3771
3772 mDNSlocal void AnswerNewQuestion(mDNS *const m)
3773 {
3774 mDNSBool ShouldQueryImmediately = mDNStrue;
3775 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
3776 mDNSu32 slot = HashSlot(&q->qname);
3777 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3778 AuthRecord *lr;
3779 AuthGroup *ag;
3780 mDNSBool AnsweredFromCache = mDNSfalse;
3781
3782 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3783
3784 if (cg) CheckCacheExpiration(m, slot, cg);
3785 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
3786 m->NewQuestions = q->next;
3787 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3788 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3789 //
3790 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3791 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
3792 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3793 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3794 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3795 // advanced it), that means the question was deleted, so we no longer need to worry about answering
3796 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3797 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
3798 //
3799 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
3800 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3801 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3802 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3803
3804 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3805 // This should be safe, because calling the client's question callback may cause the
3806 // question list to be modified, but should not ever cause the rrcache list to be modified.
3807 // If the client's question callback deletes the question, then m->CurrentQuestion will
3808 // be advanced, and we'll exit out of the loop
3809 m->lock_rrcache = 1;
3810 if (m->CurrentQuestion)
3811 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3812 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3813 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
3814
3815 if (q->NoAnswer == NoAnswer_Fail)
3816 {
3817 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3818 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
3819 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
3820 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
3821 // Don't touch the question if it has been stopped already
3822 if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
3823 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
3824 }
3825 if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit; }
3826
3827 // See if we want to tell it about LocalOnly records
3828 if (m->CurrentRecord)
3829 LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3830 slot = AuthHashSlot(&q->qname);
3831 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
3832 if (ag)
3833 {
3834 m->CurrentRecord = ag->members;
3835 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
3836 {
3837 AuthRecord *rr = m->CurrentRecord;
3838 m->CurrentRecord = rr->next;
3839 //
3840 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
3841 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
3842 //
3843 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
3844 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
3845 // we handle both mDNSInterface_Any and scoped questions.
3846
3847 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && q->InterfaceID == mDNSInterface_Any))
3848 if (LocalOnlyRecordAnswersQuestion(rr, q))
3849 {
3850 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
3851 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3852 }
3853 }
3854 }
3855 m->CurrentRecord = mDNSNULL;
3856
3857 if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit; }
3858
3859 if (q->LOAddressAnswers)
3860 {
3861 LogInfo("AnswerNewQuestion: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
3862 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
3863 goto exit;
3864 }
3865
3866 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
3867 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
3868 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
3869 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
3870 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
3871 if (ag)
3872 {
3873 lr = ag->NewLocalOnlyRecords;
3874 while (lr)
3875 {
3876 if (LORecordAnswersAddressType(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
3877 {
3878 LogInfo("AnswerNewQuestion: Question %p %##s (%s) will be answered using new local auth records "
3879 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
3880 goto exit;
3881 }
3882 lr = lr->next;
3883 }
3884 }
3885
3886
3887 // If we are not supposed to answer this question, generate a negative response.
3888 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
3889 if (QuerySuppressed(q)) { q->SuppressQuery = mDNSfalse; GenerateNegativeResponse(m); q->SuppressQuery = mDNStrue; }
3890 else
3891 {
3892 CacheRecord *rr;
3893 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3894 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
3895 {
3896 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
3897 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
3898 if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
3899 {
3900 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
3901 rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
3902 continue; // Go to next one in loop
3903 }
3904
3905 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
3906 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
3907 if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
3908 ShouldQueryImmediately = mDNSfalse;
3909 q->CurrentAnswers++;
3910 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3911 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3912 AnsweredFromCache = mDNStrue;
3913 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3914 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3915 }
3916 else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
3917 ShouldQueryImmediately = mDNSfalse;
3918 }
3919 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
3920 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
3921 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
3922
3923 // Neither a local record nor a cache entry could answer this question. If this question need to be retried
3924 // with search domains, generate a negative response which will now retry after appending search domains.
3925 // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
3926 // we will retry with search domains.
3927 if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
3928 {
3929 LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3930 GenerateNegativeResponse(m);
3931 }
3932
3933 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
3934
3935 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
3936 // Hence we don't execute the following block of code for those cases.
3937 if (ShouldQueryImmediately && ActiveQuestion(q))
3938 {
3939 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3940 q->ThisQInterval = InitialQuestionInterval;
3941 q->LastQTime = m->timenow - q->ThisQInterval;
3942 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
3943 {
3944 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
3945 if (!m->RandomQueryDelay)
3946 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
3947 q->LastQTime += m->RandomQueryDelay;
3948 }
3949 }
3950
3951 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
3952 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
3953 // answers for this question until *after* its scheduled transmission time, in which case
3954 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
3955 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
3956 SetNextQueryTime(m,q);
3957
3958 exit:
3959 m->CurrentQuestion = mDNSNULL;
3960 m->lock_rrcache = 0;
3961 }
3962
3963 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
3964 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
3965 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
3966 {
3967 mDNSu32 slot;
3968 AuthGroup *ag;
3969 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
3970 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
3971
3972 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3973
3974 if (m->CurrentQuestion)
3975 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3976 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3977 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
3978
3979 if (m->CurrentRecord)
3980 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3981
3982 // 1. First walk the LocalOnly records answering the LocalOnly question
3983 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
3984 // walk the ResourceRecords list delivering the answers
3985 slot = AuthHashSlot(&q->qname);
3986 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
3987 if (ag)
3988 {
3989 m->CurrentRecord = ag->members;
3990 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
3991 {
3992 AuthRecord *rr = m->CurrentRecord;
3993 m->CurrentRecord = rr->next;
3994 if (LocalOnlyRecordAnswersQuestion(rr, q))
3995 {
3996 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
3997 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3998 }
3999 }
4000 }
4001
4002 if (m->CurrentQuestion == q)
4003 {
4004 m->CurrentRecord = m->ResourceRecords;
4005
4006 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
4007 {
4008 AuthRecord *rr = m->CurrentRecord;
4009 m->CurrentRecord = rr->next;
4010 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4011 {
4012 AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4013 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4014 }
4015 }
4016 }
4017
4018 m->CurrentQuestion = mDNSNULL;
4019 m->CurrentRecord = mDNSNULL;
4020 }
4021
4022 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
4023 {
4024 CacheEntity *e = mDNSNULL;
4025
4026 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
4027 m->lock_rrcache = 1;
4028
4029 // If we have no free records, ask the client layer to give us some more memory
4030 if (!m->rrcache_free && m->MainCallback)
4031 {
4032 if (m->rrcache_totalused != m->rrcache_size)
4033 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4034 m->rrcache_totalused, m->rrcache_size);
4035
4036 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4037 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4038 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
4039 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
4040 // and recycle them, instead of allocating more memory.
4041 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
4042 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4043 m->rrcache_size, m->rrcache_active);
4044 else
4045 {
4046 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
4047 m->MainCallback(m, mStatus_GrowCache);
4048 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4049 }
4050 }
4051
4052 // If we still have no free records, recycle all the records we can.
4053 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4054 if (!m->rrcache_free)
4055 {
4056 mDNSu32 oldtotalused = m->rrcache_totalused;
4057 mDNSu32 slot;
4058 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4059 {
4060 CacheGroup **cp = &m->rrcache_hash[slot];
4061 while (*cp)
4062 {
4063 CacheRecord **rp = &(*cp)->members;
4064 while (*rp)
4065 {
4066 // Records that answer still-active questions are not candidates for recycling
4067 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
4068 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
4069 rp=&(*rp)->next;
4070 else
4071 {
4072 CacheRecord *rr = *rp;
4073 *rp = (*rp)->next; // Cut record from list
4074 ReleaseCacheRecord(m, rr);
4075 }
4076 }
4077 if ((*cp)->rrcache_tail != rp)
4078 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
4079 (*cp)->rrcache_tail = rp;
4080 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
4081 else ReleaseCacheGroup(m, cp);
4082 }
4083 }
4084 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
4085 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
4086 }
4087
4088 if (m->rrcache_free) // If there are records in the free list, take one
4089 {
4090 e = m->rrcache_free;
4091 m->rrcache_free = e->next;
4092 if (++m->rrcache_totalused >= m->rrcache_report)
4093 {
4094 LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
4095 if (m->rrcache_report < 100) m->rrcache_report += 10;
4096 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
4097 else m->rrcache_report += 1000;
4098 }
4099 mDNSPlatformMemZero(e, sizeof(*e));
4100 }
4101
4102 m->lock_rrcache = 0;
4103
4104 return(e);
4105 }
4106
4107 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
4108 {
4109 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
4110 if (r)
4111 {
4112 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
4113 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
4114 {
4115 r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
4116 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
4117 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
4118 }
4119 }
4120 return(r);
4121 }
4122
4123 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
4124 {
4125 mDNSu16 namelen = DomainNameLength(rr->name);
4126 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
4127 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
4128 cg->next = m->rrcache_hash[slot];
4129 cg->namehash = rr->namehash;
4130 cg->members = mDNSNULL;
4131 cg->rrcache_tail = &cg->members;
4132 cg->name = (domainname*)cg->namestorage;
4133 //LogMsg("GetCacheGroup: %-10s %d-byte cache name %##s",
4134 // (namelen > InlineCacheGroupNameSize) ? "Allocating" : "Inline", namelen, rr->name->c);
4135 if (namelen > InlineCacheGroupNameSize) cg->name = mDNSPlatformMemAllocate(namelen);
4136 if (!cg->name)
4137 {
4138 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
4139 ReleaseCacheEntity(m, (CacheEntity*)cg);
4140 return(mDNSNULL);
4141 }
4142 AssignDomainName(cg->name, rr->name);
4143
4144 if (CacheGroupForRecord(m, slot, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
4145 m->rrcache_hash[slot] = cg;
4146 if (CacheGroupForRecord(m, slot, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
4147
4148 return(cg);
4149 }
4150
4151 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
4152 {
4153 if (m->mDNS_busy != m->mDNS_reentrancy+1)
4154 LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
4155 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4156 // a positive answer using an expired record (e.g. from an interface that has gone away).
4157 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4158 // summary deletion without giving the proper callback to any questions that are monitoring it.
4159 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4160 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
4161 rr->UnansweredQueries = MaxUnansweredQueries;
4162 rr->resrec.rroriginalttl = 0;
4163 SetNextCacheCheckTimeForRecord(m, rr);
4164 }
4165
4166 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
4167 {
4168 mDNSs32 time;
4169 mDNSPlatformLock(m);
4170 if (m->mDNS_busy)
4171 {
4172 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
4173 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
4174 }
4175
4176 if (m->timenow) time = m->timenow;
4177 else time = mDNS_TimeNow_NoLock(m);
4178 mDNSPlatformUnlock(m);
4179 return(time);
4180 }
4181
4182 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
4183 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
4184 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
4185 #define SetSPSProxyListChanged(X) do { \
4186 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
4187 m->SPSProxyListChanged = (X); } while(0)
4188
4189 // Called from mDNS_Execute() to expire stale proxy records
4190 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
4191 {
4192 m->CurrentRecord = list;
4193 while (m->CurrentRecord)
4194 {
4195 AuthRecord *rr = m->CurrentRecord;
4196 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
4197 {
4198 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
4199 // so we need to cease proxying for *all* records we may have, expired or not.
4200 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
4201 {
4202 if (m->NextScheduledSPS - rr->TimeExpire > 0)
4203 m->NextScheduledSPS = rr->TimeExpire;
4204 }
4205 else // else proxy record expired, so remove it
4206 {
4207 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
4208 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
4209 SetSPSProxyListChanged(rr->resrec.InterfaceID);
4210 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4211 // Don't touch rr after this -- memory may have been free'd
4212 }
4213 }
4214 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4215 // new records could have been added to the end of the list as a result of that call.
4216 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
4217 m->CurrentRecord = rr->next;
4218 }
4219 }
4220
4221 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
4222 {
4223 while (m->CurrentRecord)
4224 {
4225 AuthRecord *rr = m->CurrentRecord;
4226 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
4227 {
4228 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
4229 rr->resrec.RecordType = kDNSRecordTypeShared;
4230 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
4231 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
4232 {
4233 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
4234 rr->AnsweredLocalQ = mDNSfalse;
4235 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
4236 // For LocalOnly records, we don't do that and hence we need to do that here.
4237 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
4238 }
4239 }
4240 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
4241 m->CurrentRecord = rr->next;
4242 }
4243 }
4244
4245 mDNSlocal void TimeoutQuestions(mDNS *const m)
4246 {
4247 m->NextScheduledStopTime = m->timenow + 0x3FFFFFFF;
4248 if (m->CurrentQuestion)
4249 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
4250 DNSTypeName(m->CurrentQuestion->qtype));
4251 m->CurrentQuestion = m->Questions;
4252 while (m->CurrentQuestion)
4253 {
4254 DNSQuestion *const q = m->CurrentQuestion;
4255 if (q->StopTime)
4256 {
4257 if (m->timenow - q->StopTime >= 0)
4258 {
4259 LogInfo("TimeoutQuestions: question %##s timed out, time %d", q->qname.c, m->timenow - q->StopTime);
4260 GenerateNegativeResponse(m);
4261 if (m->CurrentQuestion == q) q->StopTime = 0;
4262 }
4263 else
4264 {
4265 if (m->NextScheduledStopTime - q->StopTime > 0)
4266 m->NextScheduledStopTime = q->StopTime;
4267 }
4268 }
4269 // If m->CurrentQuestion wasn't modified out from under us, advance it now
4270 // We can't do this at the start of the loop because GenerateNegativeResponse
4271 // depends on having m->CurrentQuestion point to the right question
4272 if (m->CurrentQuestion == q)
4273 m->CurrentQuestion = q->next;
4274 }
4275 m->CurrentQuestion = mDNSNULL;
4276 }
4277
4278 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
4279 {
4280 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
4281
4282 if (m->timenow - m->NextScheduledEvent >= 0)
4283 {
4284 int i;
4285 AuthRecord *head, *tail;
4286 mDNSu32 slot;
4287 AuthGroup *ag;
4288
4289 verbosedebugf("mDNS_Execute");
4290
4291 if (m->CurrentQuestion)
4292 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
4293 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4294
4295 if (m->CurrentRecord)
4296 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
4297
4298 // 1. If we're past the probe suppression time, we can clear it
4299 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
4300
4301 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4302 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
4303
4304 // 3. Purge our cache of stale old records
4305 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
4306 {
4307 mDNSu32 numchecked = 0;
4308 m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
4309 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4310 {
4311 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
4312 {
4313 CacheGroup **cp = &m->rrcache_hash[slot];
4314 m->rrcache_nextcheck[slot] = m->timenow + 0x3FFFFFFF;
4315 while (*cp)
4316 {
4317 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
4318 numchecked++;
4319 CheckCacheExpiration(m, slot, *cp);
4320 if ((*cp)->members) cp=&(*cp)->next;
4321 else ReleaseCacheGroup(m, cp);
4322 }
4323 }
4324 // Even if we didn't need to actually check this slot yet, still need to
4325 // factor its nextcheck time into our overall NextCacheCheck value
4326 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
4327 m->NextCacheCheck = m->rrcache_nextcheck[slot];
4328 }
4329 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
4330 }
4331
4332 if (m->timenow - m->NextScheduledSPS >= 0)
4333 {
4334 m->NextScheduledSPS = m->timenow + 0x3FFFFFFF;
4335 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
4336 CheckProxyRecords(m, m->ResourceRecords);
4337 }
4338
4339 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
4340
4341 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
4342 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0) m->AnnounceOwner = 0;
4343
4344 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
4345 {
4346 m->DelaySleep = 0;
4347 if (m->SleepState == SleepState_Transferring)
4348 {
4349 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
4350 BeginSleepProcessing(m);
4351 }
4352 }
4353
4354 // 4. See if we can answer any of our new local questions from the cache
4355 for (i=0; m->NewQuestions && i<1000; i++)
4356 {
4357 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
4358 AnswerNewQuestion(m);
4359 }
4360 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4361
4362 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
4363 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
4364 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
4365 {
4366 m->LocalRemoveEvents = mDNSfalse;
4367 m->CurrentRecord = m->ResourceRecords;
4368 CheckRmvEventsForLocalRecords(m);
4369 // Walk the LocalOnly records and deliver the RMV events
4370 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4371 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4372 {
4373 m->CurrentRecord = ag->members;
4374 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
4375 }
4376 }
4377
4378 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
4379
4380 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
4381 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4382
4383 head = tail = mDNSNULL;
4384 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
4385 {
4386 AuthRecord *rr = m->NewLocalRecords;
4387 m->NewLocalRecords = m->NewLocalRecords->next;
4388 if (LocalRecordReady(rr))
4389 {
4390 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4391 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4392 }
4393 else if (!rr->next)
4394 {
4395 // If we have just one record that is not ready, we don't have to unlink and
4396 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
4397 // terminate and set the NewLocalRecords to rr.
4398 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
4399 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
4400 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
4401
4402 head = rr;
4403 }
4404 else
4405 {
4406 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
4407 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
4408 // if this is the first record we are skipping, move to the end of the list.
4409 // if we have already skipped records before, append it at the end.
4410 while (*p && *p != rr) p=&(*p)->next;
4411 if (*p) *p = rr->next; // Cut this record from the list
4412 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
4413 if (!head)
4414 {
4415 while (*p) p=&(*p)->next;
4416 *p = rr;
4417 head = tail = rr;
4418 }
4419 else
4420 {
4421 tail->next = rr;
4422 tail = rr;
4423 }
4424 rr->next = mDNSNULL;
4425 }
4426 }
4427 m->NewLocalRecords = head;
4428 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
4429
4430 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
4431
4432 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
4433 // to our local questions
4434 if (m->NewLocalOnlyRecords)
4435 {
4436 m->NewLocalOnlyRecords = mDNSfalse;
4437 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4438 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4439 {
4440 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
4441 {
4442 AuthRecord *rr = ag->NewLocalOnlyRecords;
4443 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
4444 // LocalOnly records should always be ready as they never probe
4445 if (LocalRecordReady(rr))
4446 {
4447 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4448 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4449 }
4450 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
4451 }
4452 // We limit about 100 per AuthGroup that can be serviced at a time
4453 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
4454 }
4455 }
4456
4457 // 5. Some questions may have picked a new DNS server and the cache may answer these questions now.
4458 AnswerQuestionsForDNSServerChanges(m);
4459
4460 // 6. See what packets we need to send
4461 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
4462 DiscardDeregistrations(m);
4463 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
4464 {
4465 // If the platform code is ready, and we're not suppressing packet generation right now
4466 // then send our responses, probes, and questions.
4467 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
4468 // We send queries next, because there might be final-stage probes that complete their probing here, causing
4469 // them to advance to announcing state, and we want those to be included in any announcements we send out.
4470 // Finally, we send responses, including the previously mentioned records that just completed probing.
4471 m->SuppressSending = 0;
4472
4473 // 7. Send Query packets. This may cause some probing records to advance to announcing state
4474 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
4475 if (m->timenow - m->NextScheduledQuery >= 0)
4476 {
4477 DNSQuestion *q;
4478 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
4479 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
4480 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
4481 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4482 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
4483 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4484 }
4485 if (m->timenow - m->NextScheduledProbe >= 0)
4486 {
4487 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
4488 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
4489 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
4490 }
4491
4492 // 8. Send Response packets, including probing records just advanced to announcing state
4493 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
4494 if (m->timenow - m->NextScheduledResponse >= 0)
4495 {
4496 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4497 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
4498 }
4499 }
4500
4501 // Clear RandomDelay values, ready to pick a new different value next time
4502 m->RandomQueryDelay = 0;
4503 m->RandomReconfirmDelay = 0;
4504
4505 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
4506 #ifndef UNICAST_DISABLED
4507 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
4508 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
4509 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
4510 #endif
4511 }
4512
4513 // Note about multi-threaded systems:
4514 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4515 // performing mDNS API operations that change our next scheduled event time.
4516 //
4517 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
4518 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4519 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4520 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4521 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4522 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4523 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4524 // without blocking. This avoids the race condition between the signal from the other thread arriving
4525 // just *before* or just *after* the main thread enters the blocking primitive.
4526 //
4527 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4528 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4529 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4530 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4531 // by the time it gets to the timer callback function).
4532
4533 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4534 return(m->NextScheduledEvent);
4535 }
4536
4537 mDNSlocal void SuspendLLQs(mDNS *m)
4538 {
4539 DNSQuestion *q;
4540 for (q = m->Questions; q; q = q->next)
4541 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
4542 { q->ReqLease = 0; sendLLQRefresh(m, q); }
4543 }
4544
4545 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
4546 {
4547 AuthRecord *rr;
4548 mDNSu32 slot;
4549 AuthGroup *ag;
4550
4551 slot = AuthHashSlot(&q->qname);
4552 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4553 if (ag)
4554 {
4555 for (rr = ag->members; rr; rr=rr->next)
4556 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
4557 if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
4558 {
4559 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
4560 return mDNStrue;
4561 }
4562 }
4563 return mDNSfalse;
4564 }
4565
4566 // ActivateUnicastQuery() is called from three places:
4567 // 1. When a new question is created
4568 // 2. On wake from sleep
4569 // 3. When the DNS configuration changes
4570 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
4571 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
4572 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
4573 {
4574 // For now this AutoTunnel stuff is specific to Mac OS X.
4575 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
4576 #if APPLE_OSX_mDNSResponder
4577 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
4578 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
4579 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
4580 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
4581 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
4582 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
4583
4584 if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
4585 !SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
4586 {
4587 question->NoAnswer = NoAnswer_Suspended;
4588 AddNewClientTunnel(m, question);
4589 return;
4590 }
4591 #endif // APPLE_OSX_mDNSResponder
4592
4593 if (!question->DuplicateOf)
4594 {
4595 debugf("ActivateUnicastQuery: %##s %s%s%s",
4596 question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
4597 question->CNAMEReferrals = 0;
4598 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
4599 if (question->LongLived)
4600 {
4601 question->state = LLQ_InitialRequest;
4602 question->id = zeroOpaque64;
4603 question->servPort = zeroIPPort;
4604 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
4605 }
4606 // If the question has local answers, then we don't want answers from outside
4607 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
4608 {
4609 question->ThisQInterval = InitialQuestionInterval;
4610 question->LastQTime = m->timenow - question->ThisQInterval;
4611 SetNextQueryTime(m, question);
4612 }
4613 }
4614 }
4615
4616 // Caller should hold the lock
4617 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
4618 CallbackBeforeStartQuery BeforeStartCallback, void *context)
4619 {
4620 DNSQuestion *q;
4621 DNSQuestion *restart = mDNSNULL;
4622
4623 if (!m->mDNS_busy) LogMsg("mDNSCoreRestartAddressQueries: ERROR!! Lock not held");
4624
4625 // 1. Flush the cache records
4626 if (flushCacheRecords) flushCacheRecords(m);
4627
4628 // 2. Even though we may have purged the cache records above, before it can generate RMV event
4629 // we are going to stop the question. Hence we need to deliver the RMV event before we
4630 // stop the question.
4631 //
4632 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
4633 // application callback can potentially stop the current question (detected by CurrentQuestion) or
4634 // *any* other question which could be the next one that we may process here. RestartQuestion
4635 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
4636 // if the "next" question is stopped while the CurrentQuestion is stopped
4637
4638 if (m->RestartQuestion)
4639 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
4640 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
4641
4642 m->RestartQuestion = m->Questions;
4643 while (m->RestartQuestion)
4644 {
4645 q = m->RestartQuestion;
4646 m->RestartQuestion = q->next;
4647 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
4648 // question) through their "nta" pointer. Normally when the original query stops, it stops the
4649 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
4650 // question followed by the original query that refers to this GetZoneData question, we will end up
4651 // freeing the GetZoneData question and then start the "freed" question at the end.
4652
4653 if (IsGetZoneDataQuestion(q))
4654 {
4655 DNSQuestion *refq = q->next;
4656 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4657 // debug stuff, we just try to find the referencing question and don't do much with it
4658 while (refq)
4659 {
4660 if (q == &refq->nta->question)
4661 {
4662 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
4663 }
4664 refq = refq->next;
4665 }
4666 continue;
4667 }
4668
4669 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
4670 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
4671
4672 // If the search domains did not change, then we restart all the queries. Otherwise, only
4673 // for queries for which we "might" have appended search domains ("might" because we may
4674 // find results before we apply search domains even though AppendSearchDomains is set to 1)
4675 if (!SearchDomainsChanged || q->AppendSearchDomains)
4676 {
4677 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
4678 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
4679 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
4680 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
4681 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
4682 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
4683 // for the original query using these cache entries as ADDs were never delivered using these cache
4684 // entries and hence this order is needed.
4685
4686 // If the query is suppressed, the RMV events won't be delivered
4687 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
4688
4689 // SuppressQuery status does not affect questions that are answered using local records
4690 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
4691
4692 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
4693 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
4694 mDNS_StopQuery_internal(m, q);
4695 // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
4696 // and then search domains should be appended. At the beginning, qnameOrig was NULL.
4697 if (q->qnameOrig)
4698 {
4699 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
4700 AssignDomainName(&q->qname, q->qnameOrig);
4701 mDNSPlatformMemFree(q->qnameOrig);
4702 q->qnameOrig = mDNSNULL;
4703 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
4704 }
4705 q->SearchListIndex = 0;
4706 q->next = restart;
4707 restart = q;
4708 }
4709 }
4710
4711 // 3. Callback before we start the query
4712 if (BeforeStartCallback) BeforeStartCallback(m, context);
4713
4714 // 4. Restart all the stopped queries
4715 while (restart)
4716 {
4717 q = restart;
4718 restart = restart->next;
4719 q->next = mDNSNULL;
4720 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4721 mDNS_StartQuery_internal(m, q);
4722 }
4723 }
4724
4725 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
4726 {
4727 DNSQuestion *q;
4728
4729 #ifndef UNICAST_DISABLED
4730 // Retrigger all our uDNS questions
4731 if (m->CurrentQuestion)
4732 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
4733 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4734 m->CurrentQuestion = m->Questions;
4735 while (m->CurrentQuestion)
4736 {
4737 q = m->CurrentQuestion;
4738 m->CurrentQuestion = m->CurrentQuestion->next;
4739 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
4740 }
4741 #endif
4742
4743 // Retrigger all our mDNS questions
4744 for (q = m->Questions; q; q=q->next) // Scan our list of questions
4745 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
4746 {
4747 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
4748 q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
4749 q->LastQTime = m->timenow - q->ThisQInterval;
4750 q->RecentAnswerPkts = 0;
4751 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
4752 m->NextScheduledQuery = m->timenow;
4753 }
4754 }
4755
4756 // ***************************************************************************
4757 #if COMPILER_LIKES_PRAGMA_MARK
4758 #pragma mark -
4759 #pragma mark - Power Management (Sleep/Wake)
4760 #endif
4761
4762 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
4763 {
4764 #ifndef IDLESLEEPCONTROL_DISABLED
4765 mDNSBool allowSleep = mDNStrue;
4766 char reason[128];
4767
4768 reason[0] = 0;
4769
4770 if (m->SystemSleepOnlyIfWakeOnLAN)
4771 {
4772 // Don't sleep if we are a proxy for any services
4773 if (m->ProxyRecords)
4774 {
4775 allowSleep = mDNSfalse;
4776 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
4777 LogInfo("Sleep disabled because we are proxying %d records", m->ProxyRecords);
4778 }
4779
4780 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
4781 {
4782 // Scan the list of active interfaces
4783 NetworkInterfaceInfo *intf;
4784 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4785 {
4786 if (intf->McastTxRx && !intf->Loopback)
4787 {
4788 // Disallow sleep if this interface doesn't support NetWake
4789 if (!intf->NetWake)
4790 {
4791 allowSleep = mDNSfalse;
4792 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
4793 LogInfo("Sleep disabled because %s does not support NetWake", intf->ifname);
4794 break;
4795 }
4796
4797 // Disallow sleep if there is no sleep proxy server
4798 if (FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL) == mDNSNULL)
4799 {
4800 allowSleep = mDNSfalse;
4801 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
4802 LogInfo("Sleep disabled because %s has no sleep proxy", intf->ifname);
4803 break;
4804 }
4805 }
4806 }
4807 }
4808 }
4809
4810 // Call the platform code to enable/disable sleep
4811 mDNSPlatformSetAllowSleep(m, allowSleep, reason);
4812 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
4813 }
4814
4815 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
4816 {
4817 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
4818 const int sps = intf->NextSPSAttempt / 3;
4819 AuthRecord *rr;
4820
4821 if (!intf->SPSAddr[sps].type)
4822 {
4823 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
4824 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
4825 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
4826 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
4827 goto exit;
4828 }
4829
4830 // Mark our mDNS records (not unicast records) for transfer to SPS
4831 if (mDNSOpaque16IsZero(id))
4832 for (rr = m->ResourceRecords; rr; rr=rr->next)
4833 if (rr->resrec.RecordType > kDNSRecordTypeDeregistering)
4834 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
4835 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
4836 rr->SendRNow = mDNSInterfaceMark; // mark it now
4837
4838 while (1)
4839 {
4840 mDNSu8 *p = m->omsg.data;
4841 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
4842 // For now we follow that same logic for SPS registrations too.
4843 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
4844 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
4845 InitializeDNSMessage(&m->omsg.h, mDNSOpaque16IsZero(id) ? mDNS_NewMessageID(m) : id, UpdateReqFlags);
4846
4847 for (rr = m->ResourceRecords; rr; rr=rr->next)
4848 if (rr->SendRNow || (!mDNSOpaque16IsZero(id) && !AuthRecord_uDNS(rr) && mDNSSameOpaque16(rr->updateid, id) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0))
4849 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
4850 {
4851 mDNSu8 *newptr;
4852 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
4853 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
4854 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
4855 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
4856 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
4857 if (!newptr)
4858 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
4859 else
4860 {
4861 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, rr));
4862 rr->SendRNow = mDNSNULL;
4863 rr->ThisAPInterval = mDNSPlatformOneSecond;
4864 rr->LastAPTime = m->timenow;
4865 rr->updateid = m->omsg.h.id;
4866 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4867 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
4868 p = newptr;
4869 }
4870 }
4871
4872 if (!m->omsg.h.mDNS_numUpdates) break;
4873 else
4874 {
4875 AuthRecord opt;
4876 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
4877 opt.resrec.rrclass = NormalMaxDNSMessageData;
4878 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
4879 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
4880 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
4881 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
4882 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
4883 if (!owner->HMAC.l[0]) // If no owner data,
4884 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information
4885 else // otherwise, use the owner data we were given
4886 {
4887 opt.resrec.rdata->u.opt[1].u.owner = *owner;
4888 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner;
4889 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
4890 }
4891 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
4892 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4893 if (!p)
4894 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
4895 else
4896 {
4897 mStatus err;
4898
4899 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
4900 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
4901 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
4902 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL);
4903 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
4904 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv6 && intf->NetWakeResolve[sps].ThisQInterval == -1)
4905 {
4906 LogSPS("SendSPSRegistration %d %##s failed to send to IPv6 address; will try IPv4 instead", sps, intf->NetWakeResolve[sps].qname.c);
4907 intf->NetWakeResolve[sps].qtype = kDNSType_A;
4908 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
4909 return;
4910 }
4911 }
4912 }
4913 }
4914
4915 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
4916
4917 exit:
4918 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
4919 }
4920
4921 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
4922 {
4923 AuthRecord *ar;
4924 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
4925 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
4926 return mDNStrue;
4927 }
4928
4929 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
4930 {
4931 AuthRecord *ar;
4932 OwnerOptData owner = zeroOwner;
4933
4934 SendSPSRegistrationForOwner(m, intf, id, &owner);
4935
4936 for (ar = m->ResourceRecords; ar; ar=ar->next)
4937 {
4938 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
4939 {
4940 owner = ar->WakeUp;
4941 SendSPSRegistrationForOwner(m, intf, id, &owner);
4942 }
4943 }
4944 }
4945
4946 // RetrySPSRegistrations is called from SendResponses, with the lock held
4947 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
4948 {
4949 AuthRecord *rr;
4950 NetworkInterfaceInfo *intf;
4951
4952 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
4953 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4954 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
4955 intf->NextSPSAttemptTime++;
4956
4957 // Retry any record registrations that are due
4958 for (rr = m->ResourceRecords; rr; rr=rr->next)
4959 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4960 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4961 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID)
4962 {
4963 LogSPS("RetrySPSRegistrations: %s", ARDisplayString(m, rr));
4964 SendSPSRegistration(m, intf, rr->updateid);
4965 }
4966
4967 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
4968 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4969 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
4970 intf->NextSPSAttempt++;
4971 }
4972
4973 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
4974 {
4975 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
4976 int sps = (int)(question - intf->NetWakeResolve);
4977 (void)m; // Unused
4978 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
4979
4980 if (!AddRecord) return; // Don't care about REMOVE events
4981 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
4982
4983 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
4984
4985 if (answer->rrtype == kDNSType_SRV)
4986 {
4987 // 1. Got the SRV record; now look up the target host's IPv6 link-local address
4988 mDNS_StopQuery(m, question);
4989 intf->SPSPort[sps] = answer->rdata->u.srv.port;
4990 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
4991 question->qtype = kDNSType_AAAA;
4992 mDNS_StartQuery(m, question);
4993 }
4994 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
4995 {
4996 // 2. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
4997 mDNS_StopQuery(m, question);
4998 question->ThisQInterval = -1;
4999 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
5000 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
5001 mDNS_Lock(m);
5002 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
5003 mDNS_Unlock(m);
5004 }
5005 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == 0)
5006 {
5007 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
5008 mDNS_StopQuery(m, question);
5009 LogSPS("NetWakeResolve: SPS %d %##s has no IPv6 address, will try IPv4 instead", sps, question->qname.c);
5010 question->qtype = kDNSType_A;
5011 mDNS_StartQuery(m, question);
5012 }
5013 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
5014 {
5015 // 4. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
5016 mDNS_StopQuery(m, question);
5017 question->ThisQInterval = -1;
5018 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
5019 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
5020 mDNS_Lock(m);
5021 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
5022 mDNS_Unlock(m);
5023 }
5024 }
5025
5026 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
5027 {
5028 AuthRecord *rr;
5029 for (rr = m->ResourceRecords; rr; rr=rr->next)
5030 if (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort))
5031 return mDNStrue;
5032 return mDNSfalse;
5033 }
5034
5035 mDNSlocal void SendSleepGoodbyes(mDNS *const m)
5036 {
5037 AuthRecord *rr;
5038 m->SleepState = SleepState_Sleeping;
5039
5040 #ifndef UNICAST_DISABLED
5041 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
5042 #endif /* UNICAST_DISABLED */
5043
5044 // Mark all the records we need to deregister and send them
5045 for (rr = m->ResourceRecords; rr; rr=rr->next)
5046 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
5047 rr->ImmedAnswer = mDNSInterfaceMark;
5048 SendResponses(m);
5049 }
5050
5051 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
5052 mDNSlocal void BeginSleepProcessing(mDNS *const m)
5053 {
5054 mDNSBool SendGoodbyes = mDNStrue;
5055 const CacheRecord *sps[3] = { mDNSNULL };
5056
5057 m->NextScheduledSPRetry = m->timenow;
5058
5059 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
5060 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
5061 else // If we have at least one advertised service
5062 {
5063 NetworkInterfaceInfo *intf;
5064 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5065 {
5066 if (!intf->NetWake) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
5067 #if APPLE_OSX_mDNSResponder
5068 else if (ActivateLocalProxy(m, intf->ifname) == mStatus_NoError)
5069 {
5070 SendGoodbyes = mDNSfalse;
5071 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
5072 // This will leave m->SleepState set to SleepState_Transferring,
5073 // which is okay because with no outstanding resolves, or updates in flight,
5074 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
5075 }
5076 #endif // APPLE_OSX_mDNSResponder
5077 else
5078 {
5079 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
5080 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
5081 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
5082 else
5083 {
5084 int i;
5085 SendGoodbyes = mDNSfalse;
5086 intf->NextSPSAttempt = 0;
5087 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
5088 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
5089 for (i=0; i<3; i++)
5090 {
5091 #if ForceAlerts
5092 if (intf->SPSAddr[i].type)
5093 { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); *(long*)0 = 0; }
5094 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
5095 { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); *(long*)0 = 0; }
5096 #endif
5097 intf->SPSAddr[i].type = mDNSAddrType_None;
5098 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
5099 intf->NetWakeResolve[i].ThisQInterval = -1;
5100 if (sps[i])
5101 {
5102 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
5103 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
5104 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
5105 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
5106 }
5107 }
5108 }
5109 }
5110 }
5111 }
5112
5113 if (SendGoodbyes) // If we didn't find even one Sleep Proxy
5114 {
5115 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
5116 SendSleepGoodbyes(m);
5117 }
5118 }
5119
5120 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
5121 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
5122 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
5123 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
5124 {
5125 AuthRecord *rr;
5126
5127 LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
5128
5129 if (sleep && !m->SleepState) // Going to sleep
5130 {
5131 mDNS_Lock(m);
5132 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
5133 if (m->SPSSocket)
5134 {
5135 mDNSu8 oldstate = m->SPSState;
5136 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
5137 m->SPSState = 2;
5138 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
5139 mDNS_ReclaimLockAfterCallback();
5140 }
5141
5142 m->SleepState = SleepState_Transferring;
5143 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
5144 {
5145 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
5146 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
5147 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
5148 }
5149 else
5150 {
5151 m->DelaySleep = 0;
5152 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
5153 BeginSleepProcessing(m);
5154 }
5155
5156 #ifndef UNICAST_DISABLED
5157 SuspendLLQs(m);
5158 #endif
5159 mDNS_Unlock(m);
5160 // RemoveAutoTunnel6Record needs to be called outside the lock, as it grabs the lock also.
5161 #if APPLE_OSX_mDNSResponder
5162 RemoveAutoTunnel6Record(m);
5163 #endif
5164 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
5165 m->SleepState == SleepState_Transferring ? "Transferring" :
5166 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
5167 }
5168 else if (!sleep) // Waking up
5169 {
5170 mDNSu32 slot;
5171 CacheGroup *cg;
5172 CacheRecord *cr;
5173 NetworkInterfaceInfo *intf;
5174
5175 mDNS_Lock(m);
5176 // Reset SleepLimit back to 0 now that we're awake again.
5177 m->SleepLimit = 0;
5178
5179 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
5180 if (m->SleepState != SleepState_Awake)
5181 {
5182 m->SleepState = SleepState_Awake;
5183 m->SleepSeqNum++;
5184 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
5185 // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
5186 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
5187 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
5188 m->DelaySleep = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 16);
5189 }
5190
5191 if (m->SPSState == 3)
5192 {
5193 m->SPSState = 0;
5194 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower);
5195 }
5196
5197 // In case we gave up waiting and went to sleep before we got an ack from the Sleep Proxy,
5198 // on wake we go through our record list and clear updateid back to zero
5199 for (rr = m->ResourceRecords; rr; rr=rr->next) rr->updateid = zeroID;
5200
5201 // ... and the same for NextSPSAttempt
5202 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
5203
5204 // Restart unicast and multicast queries
5205 mDNSCoreRestartQueries(m);
5206
5207 // and reactivtate service registrations
5208 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
5209 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
5210
5211 // 2. Re-validate our cache records
5212 FORALL_CACHERECORDS(slot, cg, cr)
5213 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
5214
5215 // 3. Retrigger probing and announcing for all our authoritative records
5216 for (rr = m->ResourceRecords; rr; rr=rr->next)
5217 if (AuthRecord_uDNS(rr))
5218 {
5219 ActivateUnicastRegistration(m, rr);
5220 }
5221 else
5222 {
5223 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5224 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5225 rr->AnnounceCount = InitialAnnounceCount;
5226 rr->SendNSECNow = mDNSNULL;
5227 InitializeLastAPTime(m, rr);
5228 }
5229
5230 // 4. Refresh NAT mappings
5231 // We don't want to have to assume that all hardware can necessarily keep accurate
5232 // track of passage of time while asleep, so on wake we refresh our NAT mappings
5233 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
5234 // When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
5235 // mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
5236 m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
5237 m->retryGetAddr = m->timenow + mDNSPlatformOneSecond * 5;
5238 LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m->retryGetAddr - m->timenow, m->timenow);
5239 RecreateNATMappings(m);
5240 mDNS_Unlock(m);
5241 }
5242 }
5243
5244 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
5245 {
5246 DNSQuestion *q;
5247 AuthRecord *rr;
5248 NetworkInterfaceInfo *intf;
5249
5250 mDNS_Lock(m);
5251
5252 if (m->DelaySleep) goto notready;
5253
5254 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
5255 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
5256
5257 m->NextScheduledSPRetry = now + 0x40000000UL;
5258
5259 // See if we might need to retransmit any lost Sleep Proxy Registrations
5260 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5261 if (intf->NextSPSAttempt >= 0)
5262 {
5263 if (now - intf->NextSPSAttemptTime >= 0)
5264 {
5265 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
5266 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
5267 SendSPSRegistration(m, intf, zeroID);
5268 // Don't need to "goto notready" here, because if we do still have record registrations
5269 // that have not been acknowledged yet, we'll catch that in the record list scan below.
5270 }
5271 else
5272 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
5273 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
5274 }
5275
5276 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
5277 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5278 {
5279 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
5280 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
5281 {
5282 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
5283 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
5284 goto spsnotready;
5285 }
5286 }
5287
5288 // Scan list of registered records
5289 for (rr = m->ResourceRecords; rr; rr = rr->next)
5290 if (!AuthRecord_uDNS(rr))
5291 if (!mDNSOpaque16IsZero(rr->updateid))
5292 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto spsnotready; }
5293
5294 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
5295 for (q = m->Questions; q; q = q->next)
5296 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
5297 {
5298 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5299 goto notready;
5300 }
5301
5302 // Scan list of registered records
5303 for (rr = m->ResourceRecords; rr; rr = rr->next)
5304 if (AuthRecord_uDNS(rr))
5305 {
5306 if (rr->state == regState_Refresh && rr->tcp)
5307 { LogSPS("mDNSCoreReadyForSleep: waiting for Record Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto notready; }
5308 #if APPLE_OSX_mDNSResponder
5309 if (!RecordReadyForSleep(m, rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
5310 #endif
5311 }
5312
5313 mDNS_Unlock(m);
5314 return mDNStrue;
5315
5316 spsnotready:
5317
5318 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
5319 // and allow up to ten seconds more to complete wide-area deregistration instead
5320 if (now - m->SleepLimit >= 0)
5321 {
5322 LogMsg("Failed to register with SPS, now sending goodbyes");
5323
5324 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5325 if (intf->NetWakeBrowse.ThisQInterval >= 0)
5326 {
5327 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
5328 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
5329 mDNS_DeactivateNetWake_internal(m, intf);
5330 }
5331
5332 for (rr = m->ResourceRecords; rr; rr = rr->next)
5333 if (!AuthRecord_uDNS(rr))
5334 if (!mDNSOpaque16IsZero(rr->updateid))
5335 {
5336 LogSPS("ReadyForSleep clearing updateid for %s", ARDisplayString(m, rr));
5337 rr->updateid = zeroID;
5338 }
5339
5340 // We'd really like to allow up to ten seconds more here,
5341 // but if we don't respond to the sleep notification within 30 seconds
5342 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
5343 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
5344 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
5345 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
5346 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
5347
5348 SendSleepGoodbyes(m);
5349 }
5350
5351 notready:
5352 mDNS_Unlock(m);
5353 return mDNSfalse;
5354 }
5355
5356 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
5357 {
5358 AuthRecord *ar;
5359
5360 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
5361 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
5362 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
5363 // and if that happens we don't want to just give up and go back to sleep and never try again.
5364 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
5365
5366 NATTraversalInfo *nat;
5367 for (nat = m->NATTraversals; nat; nat=nat->next)
5368 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
5369 {
5370 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
5371 if (e - t > 0) e = t;
5372 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
5373 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
5374 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
5375 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5376 nat->retryInterval / mDNSPlatformOneSecond,
5377 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5378 (t - now) / mDNSPlatformOneSecond);
5379 }
5380
5381 // This loop checks both the time we need to renew wide-area registrations,
5382 // and the time we need to renew Sleep Proxy registrations
5383 for (ar = m->ResourceRecords; ar; ar = ar->next)
5384 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
5385 {
5386 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
5387 if (e - t > 0) e = t;
5388 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
5389 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
5390 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5391 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5392 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
5393 }
5394
5395 return(e - now);
5396 }
5397
5398 // ***************************************************************************
5399 #if COMPILER_LIKES_PRAGMA_MARK
5400 #pragma mark -
5401 #pragma mark - Packet Reception Functions
5402 #endif
5403
5404 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
5405
5406 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
5407 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
5408 {
5409 mDNSu8 *responseptr = response->data;
5410 const mDNSu8 *const limit = response->data + sizeof(response->data);
5411 const mDNSu8 *ptr = query->data;
5412 AuthRecord *rr;
5413 mDNSu32 maxttl = 0x70000000;
5414 int i;
5415
5416 // Initialize the response fields so we can answer the questions
5417 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
5418
5419 // ***
5420 // *** 1. Write out the list of questions we are actually going to answer with this packet
5421 // ***
5422 if (LegacyQuery)
5423 {
5424 maxttl = kStaticCacheTTL;
5425 for (i=0; i<query->h.numQuestions; i++) // For each question...
5426 {
5427 DNSQuestion q;
5428 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
5429 if (!ptr) return(mDNSNULL);
5430
5431 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
5432 {
5433 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
5434 { // then put the question in the question section
5435 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
5436 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
5437 break; // break out of the ResponseRecords loop, and go on to the next question
5438 }
5439 }
5440 }
5441
5442 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
5443 }
5444
5445 // ***
5446 // *** 2. Write Answers
5447 // ***
5448 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5449 if (rr->NR_AnswerTo)
5450 {
5451 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
5452 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5453 if (p) responseptr = p;
5454 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
5455 }
5456
5457 // ***
5458 // *** 3. Write Additionals
5459 // ***
5460 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5461 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
5462 {
5463 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
5464 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5465 if (p) responseptr = p;
5466 else debugf("GenerateUnicastResponse: No more space for additionals");
5467 }
5468
5469 return(responseptr);
5470 }
5471
5472 // AuthRecord *our is our Resource Record
5473 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
5474 // Returns 0 if there is no conflict
5475 // Returns +1 if there was a conflict and we won
5476 // Returns -1 if there was a conflict and we lost and have to rename
5477 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
5478 {
5479 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
5480 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
5481 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
5482 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
5483
5484 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
5485 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
5486 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
5487 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
5488
5489 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
5490 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
5491 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
5492 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
5493
5494 LogMsg("CompareRData ERROR: Invalid state");
5495 return(-1);
5496 }
5497
5498 // See if we have an authoritative record that's identical to this packet record,
5499 // whose canonical DependentOn record is the specified master record.
5500 // The DependentOn pointer is typically used for the TXT record of service registrations
5501 // It indicates that there is no inherent conflict detection for the TXT record
5502 // -- it depends on the SRV record to resolve name conflicts
5503 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
5504 // pointer chain (if any) to make sure we reach the canonical DependentOn record
5505 // If the record has no DependentOn, then just return that record's pointer
5506 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
5507 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
5508 {
5509 const AuthRecord *r1;
5510 for (r1 = m->ResourceRecords; r1; r1=r1->next)
5511 {
5512 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
5513 {
5514 const AuthRecord *r2 = r1;
5515 while (r2->DependentOn) r2 = r2->DependentOn;
5516 if (r2 == master) return(mDNStrue);
5517 }
5518 }
5519 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
5520 {
5521 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
5522 {
5523 const AuthRecord *r2 = r1;
5524 while (r2->DependentOn) r2 = r2->DependentOn;
5525 if (r2 == master) return(mDNStrue);
5526 }
5527 }
5528 return(mDNSfalse);
5529 }
5530
5531 // Find the canonical RRSet pointer for this RR received in a packet.
5532 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
5533 // pointers (if any) to make sure we return the canonical member of this name/type/class
5534 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
5535 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
5536 {
5537 const AuthRecord *rr;
5538 for (rr = m->ResourceRecords; rr; rr=rr->next)
5539 {
5540 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
5541 {
5542 while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
5543 return(rr);
5544 }
5545 }
5546 return(mDNSNULL);
5547 }
5548
5549 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
5550 // as one of our records (our) but different rdata.
5551 // 1. If our record is not a type that's supposed to be unique, we don't care.
5552 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
5553 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
5554 // points to our record, ignore this conflict (e.g. the packet record matches one of our
5555 // TXT records, and that record is marked as dependent on 'our', its SRV record).
5556 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
5557 // are members of the same RRSet, then this is not a conflict.
5558 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
5559 {
5560 // If not supposed to be unique, not a conflict
5561 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
5562
5563 // If a dependent record, not a conflict
5564 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
5565 else
5566 {
5567 // If the pktrr matches a member of ourset, not a conflict
5568 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
5569 const AuthRecord *pktset = FindRRSet(m, pktrr);
5570 if (pktset == ourset) return(mDNSfalse);
5571
5572 // For records we're proxying, where we don't know the full
5573 // relationship between the records, having any matching record
5574 // in our AuthRecords list is sufficient evidence of non-conflict
5575 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
5576 }
5577
5578 // Okay, this is a conflict
5579 return(mDNStrue);
5580 }
5581
5582 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
5583 // the record list and/or question list.
5584 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5585 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
5586 DNSQuestion *q, AuthRecord *our)
5587 {
5588 int i;
5589 const mDNSu8 *ptr = LocateAuthorities(query, end);
5590 mDNSBool FoundUpdate = mDNSfalse;
5591
5592 for (i = 0; i < query->h.numAuthorities; i++)
5593 {
5594 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
5595 if (!ptr) break;
5596 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
5597 {
5598 FoundUpdate = mDNStrue;
5599 if (PacketRRConflict(m, our, &m->rec.r))
5600 {
5601 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
5602 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
5603 if (!result) result = CompareRData(our, &m->rec.r);
5604 if (result)
5605 {
5606 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
5607 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
5608 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
5609 }
5610 // 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.
5611 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
5612 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
5613 if (result < 0)
5614 {
5615 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
5616 our->ProbeCount = DefaultProbeCountForTypeUnique;
5617 our->AnnounceCount = InitialAnnounceCount;
5618 InitializeLastAPTime(m, our);
5619 goto exit;
5620 }
5621 }
5622 #if 0
5623 else
5624 {
5625 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
5626 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
5627 }
5628 #endif
5629 }
5630 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5631 }
5632 if (!FoundUpdate)
5633 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
5634 exit:
5635 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5636 }
5637
5638 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
5639 {
5640 mDNSu32 slot = HashSlot(pktrr->name);
5641 CacheGroup *cg = CacheGroupForRecord(m, slot, pktrr);
5642 CacheRecord *rr;
5643 mDNSBool match;
5644 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
5645 {
5646 match = !pktrr->InterfaceID ? pktrr->rDNSServer == rr->resrec.rDNSServer : pktrr->InterfaceID == rr->resrec.InterfaceID;
5647 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
5648 }
5649 return(rr);
5650 }
5651
5652 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
5653 // to check our lists and discard any stale duplicates of this record we already have
5654 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
5655 {
5656 if (m->CurrentRecord)
5657 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5658 m->CurrentRecord = thelist;
5659 while (m->CurrentRecord)
5660 {
5661 AuthRecord *const rr = m->CurrentRecord;
5662 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
5663 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
5664 {
5665 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
5666 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
5667 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
5668 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
5669 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5670 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
5671 }
5672 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5673 // new records could have been added to the end of the list as a result of that call.
5674 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5675 m->CurrentRecord = rr->next;
5676 }
5677 }
5678
5679 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
5680 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
5681 {
5682 if (m->CurrentRecord)
5683 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5684 m->CurrentRecord = thelist;
5685 while (m->CurrentRecord)
5686 {
5687 AuthRecord *const rr = m->CurrentRecord;
5688 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
5689 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
5690 {
5691 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
5692 {
5693 // We don't do this here because we know that the host is waking up at this point, so we don't send
5694 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
5695 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
5696 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
5697 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
5698 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
5699 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
5700 #endif
5701 }
5702 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
5703 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
5704 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
5705 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
5706 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
5707 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
5708 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5709 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
5710 }
5711 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5712 // new records could have been added to the end of the list as a result of that call.
5713 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5714 m->CurrentRecord = rr->next;
5715 }
5716 }
5717
5718 // ProcessQuery examines a received query to see if we have any answers to give
5719 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
5720 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
5721 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
5722 {
5723 mDNSBool FromLocalSubnet = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
5724 AuthRecord *ResponseRecords = mDNSNULL;
5725 AuthRecord **nrp = &ResponseRecords;
5726 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
5727 CacheRecord **eap = &ExpectedAnswers;
5728 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
5729 DNSQuestion **dqp = &DupQuestions;
5730 mDNSs32 delayresponse = 0;
5731 mDNSBool SendLegacyResponse = mDNSfalse;
5732 const mDNSu8 *ptr;
5733 mDNSu8 *responseptr = mDNSNULL;
5734 AuthRecord *rr;
5735 int i;
5736
5737 // ***
5738 // *** 1. Look in Additional Section for an OPT record
5739 // ***
5740 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
5741 if (ptr)
5742 {
5743 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
5744 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
5745 {
5746 const rdataOPT *opt;
5747 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
5748 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
5749 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
5750 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
5751 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
5752 {
5753 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
5754 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
5755 }
5756 }
5757 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5758 }
5759
5760 // ***
5761 // *** 2. Parse Question Section and mark potential answers
5762 // ***
5763 ptr = query->data;
5764 for (i=0; i<query->h.numQuestions; i++) // For each question...
5765 {
5766 mDNSBool QuestionNeedsMulticastResponse;
5767 int NumAnswersForThisQuestion = 0;
5768 AuthRecord *NSECAnswer = mDNSNULL;
5769 DNSQuestion pktq, *q;
5770 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
5771 if (!ptr) goto exit;
5772
5773 // The only queries that *need* a multicast response are:
5774 // * Queries sent via multicast
5775 // * from port 5353
5776 // * that don't have the kDNSQClass_UnicastResponse bit set
5777 // These queries need multicast responses because other clients will:
5778 // * suppress their own identical questions when they see these questions, and
5779 // * expire their cache records if they don't see the expected responses
5780 // For other queries, we may still choose to send the occasional multicast response anyway,
5781 // to keep our neighbours caches warm, and for ongoing conflict detection.
5782 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
5783 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
5784 pktq.qclass &= ~kDNSQClass_UnicastResponse;
5785
5786 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
5787 // can result in user callbacks which may change the record list and/or question list.
5788 // Also note: we just mark potential answer records here, without trying to build the
5789 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
5790 // from that list while we're in the middle of trying to build it.
5791 if (m->CurrentRecord)
5792 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5793 m->CurrentRecord = m->ResourceRecords;
5794 while (m->CurrentRecord)
5795 {
5796 rr = m->CurrentRecord;
5797 m->CurrentRecord = rr->next;
5798 if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
5799 {
5800 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
5801 {
5802 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
5803 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
5804 else if (ResourceRecordIsValidAnswer(rr))
5805 {
5806 NumAnswersForThisQuestion++;
5807 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
5808 // unicast answer back to the source, because timeliness in answering probes is important.
5809
5810 // Notes:
5811 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
5812 // NR_AnswerTo == (mDNSu8*)~1 means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
5813 // NR_AnswerTo == (mDNSu8*)~0 means "definitely answer via multicast" (can't downgrade to unicast later)
5814 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
5815 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
5816 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
5817 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
5818 {
5819 // We only mark this question for sending if it is at least one second since the last time we multicast it
5820 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
5821 // This is to guard against the case where someone blasts us with queries as fast as they can.
5822 if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
5823 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
5824 rr->NR_AnswerTo = (mDNSu8*)~0;
5825 }
5826 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : (mDNSu8*)~1;
5827 }
5828 }
5829 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
5830 {
5831 // If we don't have any answers for this question, but we do own another record with the same name,
5832 // then we'll want to mark it to generate an NSEC record on this interface
5833 if (!NSECAnswer) NSECAnswer = rr;
5834 }
5835 }
5836 }
5837
5838 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
5839 {
5840 NumAnswersForThisQuestion++;
5841 NSECAnswer->SendNSECNow = InterfaceID;
5842 m->NextScheduledResponse = m->timenow;
5843 }
5844
5845 // If we couldn't answer this question, someone else might be able to,
5846 // so use random delay on response to reduce collisions
5847 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
5848
5849 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5850 if (QuestionNeedsMulticastResponse)
5851 #else
5852 // We only do the following accelerated cache expiration and duplicate question suppression processing
5853 // for non-truncated multicast queries with multicast responses.
5854 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
5855 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
5856 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
5857 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
5858 #endif
5859 {
5860 const mDNSu32 slot = HashSlot(&pktq.qname);
5861 CacheGroup *cg = CacheGroupForName(m, slot, pktq.qnamehash, &pktq.qname);
5862 CacheRecord *cr;
5863
5864 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5865 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5866 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5867 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5868 #endif
5869 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5870 if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
5871 if (!cr->NextInKAList && eap != &cr->NextInKAList)
5872 {
5873 *eap = cr;
5874 eap = &cr->NextInKAList;
5875 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5876 if (cr->MPUnansweredQ == 0 || m->timenow - cr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
5877 {
5878 // Although MPUnansweredQ is only really used for multi-packet query processing,
5879 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5880 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5881 cr->MPUnansweredQ++;
5882 cr->MPLastUnansweredQT = m->timenow;
5883 cr->MPExpectingKA = mDNStrue;
5884 }
5885 #endif
5886 }
5887
5888 // Check if this question is the same as any of mine.
5889 // We only do this for non-truncated queries. Right now it would be too complicated to try
5890 // to keep track of duplicate suppression state between multiple packets, especially when we
5891 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5892 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5893 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5894 #endif
5895 for (q = m->Questions; q; q=q->next)
5896 if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
5897 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
5898 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
5899 if (q->qtype == pktq.qtype &&
5900 q->qclass == pktq.qclass &&
5901 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
5902 { *dqp = q; dqp = &q->NextInDQList; }
5903 }
5904 }
5905
5906 // ***
5907 // *** 3. Now we can safely build the list of marked answers
5908 // ***
5909 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
5910 if (rr->NR_AnswerTo) // If we marked the record...
5911 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
5912
5913 // ***
5914 // *** 4. Add additional records
5915 // ***
5916 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
5917
5918 // ***
5919 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
5920 // ***
5921 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
5922 {
5923 // Get the record...
5924 CacheRecord *ourcacherr;
5925 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
5926 if (!ptr) goto exit;
5927 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
5928 {
5929 // See if this Known-Answer suppresses any of our currently planned answers
5930 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5931 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5932 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
5933
5934 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5935 for (rr=m->ResourceRecords; rr; rr=rr->next)
5936 {
5937 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5938 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5939 {
5940 if (srcaddr->type == mDNSAddrType_IPv4)
5941 {
5942 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
5943 }
5944 else if (srcaddr->type == mDNSAddrType_IPv6)
5945 {
5946 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
5947 }
5948 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
5949 {
5950 rr->ImmedAnswer = mDNSNULL;
5951 rr->ImmedUnicast = mDNSfalse;
5952 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5953 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
5954 #endif
5955 }
5956 }
5957 }
5958
5959 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
5960
5961 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5962 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5963 // 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).
5964 if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
5965 {
5966 ourcacherr->MPUnansweredKA++;
5967 ourcacherr->MPExpectingKA = mDNSfalse;
5968 }
5969 #endif
5970
5971 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
5972 // any records that are suppressed by the Known Answer list in this packet.
5973 eap = &ExpectedAnswers;
5974 while (*eap)
5975 {
5976 CacheRecord *cr = *eap;
5977 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
5978 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
5979 else eap = &cr->NextInKAList;
5980 }
5981
5982 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5983 if (!ourcacherr)
5984 {
5985 dqp = &DupQuestions;
5986 while (*dqp)
5987 {
5988 DNSQuestion *q = *dqp;
5989 if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
5990 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
5991 else dqp = &q->NextInDQList;
5992 }
5993 }
5994 }
5995 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5996 }
5997
5998 // ***
5999 // *** 6. Cancel any additionals that were added because of now-deleted records
6000 // ***
6001 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6002 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
6003 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
6004
6005 // ***
6006 // *** 7. Mark the send flags on the records we plan to send
6007 // ***
6008 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6009 {
6010 if (rr->NR_AnswerTo)
6011 {
6012 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
6013 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
6014
6015 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
6016 if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0)
6017 {
6018 SendMulticastResponse = mDNStrue;
6019 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
6020 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
6021 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
6022 if (rr->NR_AnswerTo == (mDNSu8*)~1) rr->NR_AnswerTo = (mDNSu8*)~0;
6023 }
6024
6025 // If the client insists on a multicast response, then we'd better send one
6026 if (rr->NR_AnswerTo == (mDNSu8*)~0) SendMulticastResponse = mDNStrue;
6027 else if (rr->NR_AnswerTo == (mDNSu8*)~1) SendUnicastResponse = mDNStrue;
6028 else if (rr->NR_AnswerTo) SendLegacyResponse = mDNStrue;
6029
6030 if (SendMulticastResponse || SendUnicastResponse)
6031 {
6032 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6033 rr->ImmedAnswerMarkTime = m->timenow;
6034 #endif
6035 m->NextScheduledResponse = m->timenow;
6036 // If we're already planning to send this on another interface, just send it on all interfaces
6037 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
6038 rr->ImmedAnswer = mDNSInterfaceMark;
6039 else
6040 {
6041 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
6042 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
6043 if (srcaddr->type == mDNSAddrType_IPv4)
6044 {
6045 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
6046 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
6047 }
6048 else if (srcaddr->type == mDNSAddrType_IPv6)
6049 {
6050 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
6051 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
6052 }
6053 }
6054 }
6055 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
6056 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
6057 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
6058 // else, for a simple unique record reply, we can reply immediately; no need for delay
6059 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
6060 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
6061 }
6062 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == (mDNSu8*)~0)
6063 {
6064 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
6065 // If two clients on different interfaces do queries that invoke the same optional additional answer,
6066 // then the earlier client is out of luck
6067 rr->ImmedAdditional = InterfaceID;
6068 // No need to set m->NextScheduledResponse here
6069 // We'll send these additional records when we send them, or not, as the case may be
6070 }
6071 }
6072
6073 // ***
6074 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
6075 // ***
6076 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
6077 {
6078 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6079 mDNSs32 oldss = m->SuppressSending;
6080 if (oldss && delayresponse)
6081 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
6082 #endif
6083 // Pick a random delay:
6084 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
6085 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
6086 // This is an integer value, with resolution determined by the platform clock rate.
6087 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
6088 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
6089 // The +49 before dividing is to ensure we round up, not down, to ensure that even
6090 // on platforms where the native clock rate is less than fifty ticks per second,
6091 // we still guarantee that the final calculated delay is at least one platform tick.
6092 // We want to make sure we don't ever allow the delay to be zero ticks,
6093 // because if that happens we'll fail the Bonjour Conformance Test.
6094 // Our final computed delay is 20-120ms for normal delayed replies,
6095 // or 400-500ms in the case of multi-packet known-answer lists.
6096 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
6097 if (m->SuppressSending == 0) m->SuppressSending = 1;
6098 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6099 if (oldss && delayresponse)
6100 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
6101 #endif
6102 }
6103
6104 // ***
6105 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
6106 // ***
6107 if (SendLegacyResponse)
6108 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
6109
6110 exit:
6111 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6112
6113 // ***
6114 // *** 10. Finally, clear our link chains ready for use next time
6115 // ***
6116 while (ResponseRecords)
6117 {
6118 rr = ResponseRecords;
6119 ResponseRecords = rr->NextResponse;
6120 rr->NextResponse = mDNSNULL;
6121 rr->NR_AnswerTo = mDNSNULL;
6122 rr->NR_AdditionalTo = mDNSNULL;
6123 }
6124
6125 while (ExpectedAnswers)
6126 {
6127 CacheRecord *cr = ExpectedAnswers;
6128 ExpectedAnswers = cr->NextInKAList;
6129 cr->NextInKAList = mDNSNULL;
6130
6131 // For non-truncated queries, we can definitively say that we should expect
6132 // to be seeing a response for any records still left in the ExpectedAnswers list
6133 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
6134 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond)
6135 {
6136 cr->UnansweredQueries++;
6137 cr->LastUnansweredTime = m->timenow;
6138 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6139 if (cr->UnansweredQueries > 1)
6140 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
6141 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6142 #endif
6143 SetNextCacheCheckTimeForRecord(m, cr);
6144 }
6145
6146 // If we've seen multiple unanswered queries for this record,
6147 // then mark it to expire in five seconds if we don't get a response by then.
6148 if (cr->UnansweredQueries >= MaxUnansweredQueries)
6149 {
6150 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6151 // Only show debugging message if this record was not about to expire anyway
6152 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6153 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6154 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6155 #endif
6156 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
6157 }
6158 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6159 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
6160 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
6161 // possible packet loss of up to 20% of the additional KA packets.)
6162 else if (cr->MPUnansweredQ * 4 > cr->MPUnansweredKA * 5 + 8)
6163 {
6164 // We want to do this conservatively.
6165 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
6166 // then we don't want them to all hit the network simultaneously with their final expiration queries.
6167 // By setting the record to expire in four minutes, we achieve two things:
6168 // (a) the 90-95% final expiration queries will be less bunched together
6169 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
6170 mDNSu32 remain = (mDNSu32)(RRExpireTime(cr) - m->timenow) / 4;
6171 if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
6172 remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
6173
6174 // Only show debugging message if this record was not about to expire anyway
6175 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6176 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6177 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6178
6179 if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
6180 cr->UnansweredQueries++; // Treat this as equivalent to one definite unanswered query
6181 cr->MPUnansweredQ = 0; // Clear MPQ/MPKA statistics
6182 cr->MPUnansweredKA = 0;
6183 cr->MPExpectingKA = mDNSfalse;
6184
6185 if (remain < kDefaultReconfirmTimeForNoAnswer)
6186 remain = kDefaultReconfirmTimeForNoAnswer;
6187 mDNS_Reconfirm_internal(m, cr, remain);
6188 }
6189 #endif
6190 }
6191
6192 while (DupQuestions)
6193 {
6194 DNSQuestion *q = DupQuestions;
6195 DupQuestions = q->NextInDQList;
6196 q->NextInDQList = mDNSNULL;
6197 i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
6198 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
6199 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
6200 }
6201
6202 return(responseptr);
6203 }
6204
6205 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
6206 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6207 const mDNSInterfaceID InterfaceID)
6208 {
6209 mDNSu8 *responseend = mDNSNULL;
6210 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
6211 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6212
6213 if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
6214 {
6215 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6216 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
6217 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6218 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
6219 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
6220 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
6221 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
6222 return;
6223 }
6224
6225 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6226 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6227 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6228 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
6229 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
6230 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
6231 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
6232
6233 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
6234 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
6235
6236 if (responseend) // If responseend is non-null, that means we built a unicast response packet
6237 {
6238 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
6239 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
6240 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
6241 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
6242 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
6243 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL);
6244 }
6245 }
6246
6247 #if 0
6248 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
6249 {
6250 DNSServer *s;
6251 (void)m; // Unused
6252 (void)srcaddr; // Unused
6253 for (s = m->DNSServers; s; s = s->next)
6254 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
6255 return(mDNSfalse);
6256 }
6257 #endif
6258
6259 struct UDPSocket_struct
6260 {
6261 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
6262 };
6263
6264 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
6265 {
6266 DNSQuestion *q;
6267 for (q = m->Questions; q; q=q->next)
6268 {
6269 if (!tcp && !q->LocalSocket) continue;
6270 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
6271 mDNSSameOpaque16(q->TargetQID, id) &&
6272 q->qtype == question->qtype &&
6273 q->qclass == question->qclass &&
6274 q->qnamehash == question->qnamehash &&
6275 SameDomainName(&q->qname, &question->qname))
6276 return(q);
6277 }
6278 return(mDNSNULL);
6279 }
6280
6281 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
6282 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
6283 {
6284 DNSQuestion *q;
6285 (void)id;
6286 (void)srcaddr;
6287
6288 // Unicast records have zero as InterfaceID
6289 if (rr->resrec.InterfaceID) return mDNSNULL;
6290
6291 for (q = m->Questions; q; q=q->next)
6292 {
6293 if (!q->DuplicateOf && UnicastResourceRecordAnswersQuestion(&rr->resrec, q))
6294 {
6295 if (!mDNSOpaque16IsZero(q->TargetQID))
6296 {
6297 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
6298
6299 if (mDNSSameOpaque16(q->TargetQID, id))
6300 {
6301 mDNSIPPort srcp;
6302 if (!tcp)
6303 {
6304 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
6305 }
6306 else
6307 {
6308 srcp = q->tcpSrcPort;
6309 }
6310 if (mDNSSameIPPort(srcp, port)) return(q);
6311
6312 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
6313 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
6314 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
6315 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
6316 q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
6317 return(mDNSNULL);
6318 }
6319 }
6320 else
6321 {
6322 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
6323 return(q);
6324 }
6325 }
6326 }
6327 return(mDNSNULL);
6328 }
6329
6330 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
6331 // Currently this applies only to rdata types containing more than one domainname,
6332 // or types where the domainname is not the last item in the structure.
6333 // In addition, NSEC currently requires less space for in-memory storage than its in-packet representation.
6334 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
6335 {
6336 switch (rr->rrtype)
6337 {
6338 case kDNSType_SOA: return sizeof(rdataSOA);
6339 case kDNSType_RP: return sizeof(rdataRP);
6340 case kDNSType_PX: return sizeof(rdataPX);
6341 case kDNSType_NSEC:return sizeof(rdataNSEC);
6342 default: return rr->rdlength;
6343 }
6344 }
6345
6346 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay)
6347 {
6348 CacheRecord *rr = mDNSNULL;
6349 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
6350
6351 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
6352
6353 //if (RDLength > InlineCacheRDSize)
6354 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
6355
6356 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
6357 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
6358 if (!rr) NoCacheAnswer(m, &m->rec.r);
6359 else
6360 {
6361 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
6362 *rr = m->rec.r; // Block copy the CacheRecord object
6363 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
6364 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
6365 rr->DelayDelivery = delay;
6366
6367 // If this is an oversized record with external storage allocated, copy rdata to external storage
6368 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
6369 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
6370 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
6371 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
6372 if (RDLength > InlineCacheRDSize)
6373 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
6374
6375 rr->next = mDNSNULL; // Clear 'next' pointer
6376 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
6377 cg->rrcache_tail = &(rr->next); // Advance tail pointer
6378
6379 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
6380 }
6381 return(rr);
6382 }
6383
6384 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
6385 {
6386 rr->TimeRcvd = m->timenow;
6387 rr->resrec.rroriginalttl = ttl;
6388 rr->UnansweredQueries = 0;
6389 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6390 rr->MPUnansweredQ = 0;
6391 rr->MPUnansweredKA = 0;
6392 rr->MPExpectingKA = mDNSfalse;
6393 #endif
6394 SetNextCacheCheckTimeForRecord(m, rr);
6395 }
6396
6397 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
6398 {
6399 CacheRecord *rr;
6400 const mDNSu32 slot = HashSlot(&q->qname);
6401 CacheGroup *cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
6402 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6403 if (rr->CRActiveQuestion == q)
6404 {
6405 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
6406 RefreshCacheRecord(m, rr, lease);
6407 }
6408 }
6409
6410 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
6411 {
6412 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
6413 else if (LLQType == uDNS_LLQ_Events)
6414 {
6415 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
6416 if (ttl == 0xFFFFFFFF) ttl = 0;
6417 else ttl = kLLQ_DefLease;
6418 }
6419 else // else not LLQ (standard uDNS response)
6420 {
6421 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
6422 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
6423 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
6424
6425 // Adjustment factor to avoid race condition:
6426 // 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.
6427 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
6428 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
6429 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
6430 // We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
6431 // the cached copy at our local caching server will already have expired, so the server will be forced
6432 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
6433 ttl += ttl/4 + 2;
6434
6435 // For mDNS, TTL zero means "delete this record"
6436 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
6437 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
6438 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
6439 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
6440 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
6441 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
6442 // (with the current code) result in the server having even less than three seconds to respond
6443 // before we deleted the record and reported a "remove" event to any active questions.
6444 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
6445 // then things really break (e.g. we end up making a negative cache entry).
6446 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
6447 if (ttl < 15) ttl = 15;
6448 }
6449
6450 return ttl;
6451 }
6452
6453 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
6454 // the record list and/or question list.
6455 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6456 // InterfaceID non-NULL tells us the interface this multicast response was received on
6457 // InterfaceID NULL tells us this was a unicast response
6458 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
6459 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
6460 const DNSMessage *const response, const mDNSu8 *end,
6461 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6462 const mDNSInterfaceID InterfaceID)
6463 {
6464 int i;
6465 mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
6466 mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6467 DNSQuestion *llqMatch = mDNSNULL;
6468 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
6469
6470 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
6471 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
6472 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
6473 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
6474 CacheRecord **cfp = &CacheFlushRecords;
6475
6476 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
6477 // to guard against spoof responses, then the only credible protection against that is cryptographic
6478 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
6479 int firstauthority = response->h.numAnswers;
6480 int firstadditional = firstauthority + response->h.numAuthorities;
6481 int totalrecords = firstadditional + response->h.numAdditionals;
6482 const mDNSu8 *ptr = response->data;
6483 DNSServer *uDNSServer = mDNSNULL;
6484
6485 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
6486 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
6487 srcaddr, dstaddr, InterfaceID,
6488 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
6489 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
6490 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
6491 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
6492
6493 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
6494 // When a DNS client receives a reply with TC
6495 // set, it should ignore that response, and query again, using a
6496 // mechanism, such as a TCP connection, that will permit larger replies.
6497 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
6498 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
6499 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
6500 // <rdar://problem/6690034> Can't bind to Active Directory
6501 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
6502 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
6503 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
6504 // and not even do the TCP query.
6505 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
6506 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC)) return;
6507
6508 if (LLQType == uDNS_LLQ_Ignore) return;
6509
6510 // 1. We ignore questions (if any) in mDNS response packets
6511 // 2. If this is an LLQ response, we handle it much the same
6512 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
6513 // answer as being the authoritative complete RRSet, and respond by deleting all other
6514 // matching cache records that don't appear in this packet.
6515 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
6516 if (ResponseMCast || LLQType == uDNS_LLQ_Events || (response->h.flags.b[0] & kDNSFlag0_TC))
6517 ptr = LocateAnswers(response, end);
6518 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
6519 // in this response packet are immediately deemed to be invalid.
6520 else
6521 {
6522 mDNSu8 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
6523 mDNSBool failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
6524 mDNSBool returnEarly = mDNSfalse;
6525 // We could possibly combine this with the similar loop at the end of this function --
6526 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
6527 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
6528 // which it was received (or refreshed), and then at the end if we find any cache records which
6529 // answer questions in this packet's question section, but which aren't tagged with this packet's
6530 // packet number, then we deduce they are old and delete them
6531 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
6532 {
6533 DNSQuestion q, *qptr = mDNSNULL;
6534 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
6535 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
6536 {
6537 if (!failure)
6538 {
6539 CacheRecord *rr;
6540 const mDNSu32 slot = HashSlot(&q.qname);
6541 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
6542 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6543 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
6544 {
6545 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
6546 rr->resrec.InterfaceID, CRDisplayString(m, rr));
6547 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
6548 rr->TimeRcvd = m->timenow - TicksTTL(rr) - 1;
6549 rr->UnansweredQueries = MaxUnansweredQueries;
6550 }
6551 }
6552 else
6553 {
6554 if (qptr)
6555 {
6556 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
6557 PenalizeDNSServer(m, qptr);
6558 }
6559 returnEarly = mDNStrue;
6560 }
6561 }
6562 }
6563 if (returnEarly)
6564 {
6565 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
6566 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
6567 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
6568 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
6569 // not goto exit because we won't have any CacheFlushRecords and we do not want to
6570 // generate negative cache entries (we want to query the next server)
6571 return;
6572 }
6573 }
6574
6575 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
6576 {
6577 // All responses sent via LL multicast are acceptable for caching
6578 // All responses received over our outbound TCP connections are acceptable for caching
6579 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType;
6580 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
6581 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
6582
6583 const mDNSu8 RecordType =
6584 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
6585 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
6586 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
6587 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
6588 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) { m->rec.r.resrec.RecordType = 0; continue; }
6589
6590 // Don't want to cache OPT or TSIG pseudo-RRs
6591 if (m->rec.r.resrec.rrtype == kDNSType_TSIG) { m->rec.r.resrec.RecordType = 0; continue; }
6592 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
6593 {
6594 const rdataOPT *opt;
6595 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
6596 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
6597 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
6598 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
6599 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
6600 {
6601 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
6602 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
6603 }
6604 m->rec.r.resrec.RecordType = 0;
6605 continue;
6606 }
6607
6608 // if a CNAME record points to itself, then don't add it to the cache
6609 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
6610 {
6611 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
6612 m->rec.r.resrec.RecordType = 0;
6613 continue;
6614 }
6615
6616 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
6617 // In the case of active LLQs, we'll get remove events when the records actually do go away
6618 // In the case of polling LLQs, we assume the record remains valid until the next poll
6619 if (!mDNSOpaque16IsZero(response->h.id))
6620 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
6621
6622 // If response was not sent via LL multicast,
6623 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
6624 if (!ResponseMCast)
6625 {
6626 if (LLQType)
6627 {
6628 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
6629 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
6630 // queries to get ADD/RMV events. To lookup the question, we can't use
6631 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
6632 // has already matched the question using the 64 bit Id in the packet and we use that here.
6633
6634 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
6635 }
6636 else if (!AcceptableResponse || !dstaddr)
6637 {
6638 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
6639 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
6640 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
6641 // we create.
6642
6643 DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
6644
6645 // Intialize the DNS server on the resource record which will now filter what questions we answer with
6646 // this record.
6647 //
6648 // We could potentially lookup the DNS server based on the source address, but that may not work always
6649 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
6650 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
6651 // on the "id" and "source port", then this response answers the question and assume the response
6652 // came from the same DNS server that we sent the query to.
6653
6654 if (q != mDNSNULL)
6655 {
6656 AcceptableResponse = mDNStrue;
6657 if (!InterfaceID)
6658 {
6659 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
6660 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
6661 }
6662 }
6663 else
6664 {
6665 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
6666 // the question. The code below does that. So, make this record unacceptable for now
6667 if (!InterfaceID)
6668 {
6669 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
6670 AcceptableResponse = mDNSfalse;
6671 }
6672 }
6673 }
6674 }
6675
6676 // 1. Check that this packet resource record does not conflict with any of ours
6677 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
6678 {
6679 if (m->CurrentRecord)
6680 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
6681 m->CurrentRecord = m->ResourceRecords;
6682 while (m->CurrentRecord)
6683 {
6684 AuthRecord *rr = m->CurrentRecord;
6685 m->CurrentRecord = rr->next;
6686 // We accept all multicast responses, and unicast responses resulting from queries we issued
6687 // For other unicast responses, this code accepts them only for responses with an
6688 // (apparently) local source address that pertain to a record of our own that's in probing state
6689 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
6690
6691 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
6692 {
6693 // ... check to see if type and rdata are identical
6694 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
6695 {
6696 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
6697 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
6698 {
6699 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
6700 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
6701 }
6702 else
6703 {
6704 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
6705 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
6706 }
6707 }
6708 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
6709 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
6710 {
6711 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
6712 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr-> resrec.rdatahash, ARDisplayString(m, rr));
6713
6714 // If this record is marked DependentOn another record for conflict detection purposes,
6715 // then *that* record has to be bumped back to probing state to resolve the conflict
6716 if (rr->DependentOn)
6717 {
6718 while (rr->DependentOn) rr = rr->DependentOn;
6719 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr-> resrec.rdatahash, ARDisplayString(m, rr));
6720 }
6721
6722 // If we've just whacked this record's ProbeCount, don't need to do it again
6723 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
6724 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
6725 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
6726 LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
6727 else
6728 {
6729 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
6730 // If we'd previously verified this record, put it back to probing state and try again
6731 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
6732 {
6733 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
6734 rr->resrec.RecordType = kDNSRecordTypeUnique;
6735 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
6736 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
6737 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
6738 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
6739 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
6740 rr->AnnounceCount = InitialAnnounceCount;
6741 InitializeLastAPTime(m, rr);
6742 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
6743 }
6744 // If we're probing for this record, we just failed
6745 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
6746 {
6747 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
6748 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6749 }
6750 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
6751 // same machine giving different answers for the reverse mapping record, or there are two machines on the
6752 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
6753 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
6754 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
6755 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
6756 {
6757 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
6758 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6759 }
6760 else
6761 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
6762 }
6763 }
6764 // Else, matching signature, different type or rdata, but not a considered a conflict.
6765 // If the packet record has the cache-flush bit set, then we check to see if we
6766 // have any record(s) of the same type that we should re-assert to rescue them
6767 // (see note about "multi-homing and bridged networks" at the end of this function).
6768 else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
6769 if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
6770 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
6771 }
6772 }
6773 }
6774
6775 if (!AcceptableResponse)
6776 {
6777 const CacheRecord *cr;
6778 for (cr = CacheFlushRecords; cr != (CacheRecord*)1; cr = cr->NextInCFList)
6779 {
6780 domainname *target = GetRRDomainNameTarget(&cr->resrec);
6781 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
6782 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
6783 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
6784 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
6785 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
6786
6787 if (target && cr->resrec.rdatahash == m->rec.r.resrec.namehash && SameDomainName(target, m->rec.r.resrec.name))
6788 {
6789 debugf("mDNSCoreReceiveResponse: Found a matching entry for %##s in the CacheFlushRecords", m->rec.r.resrec.name->c);
6790 AcceptableResponse = mDNStrue;
6791 m->rec.r.resrec.rDNSServer = uDNSServer;
6792 break;
6793 }
6794 }
6795 }
6796
6797 // 2. See if we want to add this packet resource record to our cache
6798 // We only try to cache answers if we have a cache to put them in
6799 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
6800 if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
6801 if (m->rrcache_size && AcceptableResponse)
6802 {
6803 const mDNSu32 slot = HashSlot(m->rec.r.resrec.name);
6804 CacheGroup *cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
6805 CacheRecord *rr;
6806
6807 // 2a. Check if this packet resource record is already in our cache
6808 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6809 {
6810 mDNSBool match = !InterfaceID ? m->rec.r.resrec.rDNSServer == rr->resrec.rDNSServer : rr->resrec.InterfaceID == InterfaceID;
6811 // If we found this exact resource record, refresh its TTL
6812 if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
6813 {
6814 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
6815 verbosedebugf("Found record size %5d interface %p already in cache: %s",
6816 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
6817
6818 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6819 {
6820 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
6821 if (rr->NextInCFList == mDNSNULL && cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
6822 { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6823
6824 // If this packet record is marked unique, and our previous cached copy was not, then fix it
6825 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
6826 {
6827 DNSQuestion *q;
6828 for (q = m->Questions; q; q=q->next) if (ResourceRecordAnswersQuestion(&rr->resrec, q)) q->UniqueAnswers++;
6829 rr->resrec.RecordType = m->rec.r.resrec.RecordType;
6830 }
6831 }
6832
6833 if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
6834 {
6835 // If the rdata of the packet record differs in name capitalization from the record in our cache
6836 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
6837 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
6838 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
6839 rr->resrec.rroriginalttl = 0;
6840 rr->TimeRcvd = m->timenow;
6841 rr->UnansweredQueries = MaxUnansweredQueries;
6842 SetNextCacheCheckTimeForRecord(m, rr);
6843 LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m,rr));
6844 LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m,&m->rec.r));
6845 LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
6846 NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
6847 // DO NOT break out here -- we want to continue as if we never found it
6848 }
6849 else if (m->rec.r.resrec.rroriginalttl > 0)
6850 {
6851 DNSQuestion *q;
6852 //if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
6853 RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
6854
6855 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
6856 // polling the network once we get a valid response back. For the first time when a new
6857 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
6858 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
6859 // configuration changed, without flushing the cache, we reset the question interval here.
6860 // Currently, we do this for for both multicast and unicast questions as long as the record
6861 // type is unique. For unicast, resource record is always unique and for multicast it is
6862 // true for records like A etc. but not for PTR.
6863 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6864 {
6865 for (q = m->Questions; q; q=q->next)
6866 {
6867 if (!q->DuplicateOf && !q->LongLived &&
6868 ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
6869 {
6870 q->LastQTime = m->timenow;
6871 q->LastQTxTime = m->timenow;
6872 q->RecentAnswerPkts = 0;
6873 q->ThisQInterval = MaxQuestionInterval;
6874 q->RequestUnicast = mDNSfalse;
6875 q->unansweredQueries = 0;
6876 debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
6877 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
6878 }
6879 }
6880 }
6881 break;
6882 }
6883 else
6884 {
6885 // If the packet TTL is zero, that means we're deleting this record.
6886 // To give other hosts on the network a chance to protest, we push the deletion
6887 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
6888 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
6889 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
6890 // If record's current expiry time is more than a second from now, we set it to expire in one second.
6891 // If the record is already going to expire in less than one second anyway, we leave it alone --
6892 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
6893 debugf("DE for %s", CRDisplayString(m, rr));
6894 if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
6895 {
6896 rr->resrec.rroriginalttl = 1;
6897 rr->TimeRcvd = m->timenow;
6898 rr->UnansweredQueries = MaxUnansweredQueries;
6899 SetNextCacheCheckTimeForRecord(m, rr);
6900 }
6901 break;
6902 }
6903 }
6904 }
6905
6906 // If packet resource record not in our cache, add it now
6907 // (unless it is just a deletion of a record we never had, in which case we don't care)
6908 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
6909 {
6910 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
6911 const mDNSs32 delay = AddToCFList ? NonZeroTime(m->timenow + mDNSPlatformOneSecond) :
6912 CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash, slot);
6913 // If unique, assume we may have to delay delivery of this 'add' event.
6914 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
6915 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
6916 // to schedule an mDNS_Execute task at the appropriate time.
6917 rr = CreateNewCacheEntry(m, slot, cg, delay);
6918 if (rr)
6919 {
6920 if (AddToCFList) { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6921 else if (rr->DelayDelivery) ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
6922 }
6923 }
6924 }
6925 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6926 }
6927
6928 exit:
6929 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6930
6931 // If we've just received one or more records with their cache flush bits set,
6932 // then scan that cache slot to see if there are any old stale records we need to flush
6933 while (CacheFlushRecords != (CacheRecord*)1)
6934 {
6935 CacheRecord *r1 = CacheFlushRecords, *r2;
6936 const mDNSu32 slot = HashSlot(r1->resrec.name);
6937 const CacheGroup *cg = CacheGroupForRecord(m, slot, &r1->resrec);
6938 CacheFlushRecords = CacheFlushRecords->NextInCFList;
6939 r1->NextInCFList = mDNSNULL;
6940
6941 // Look for records in the cache with the same signature as this new one with the cache flush
6942 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
6943 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
6944 // We make these TTL adjustments *only* for records that still have *more* than one second
6945 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
6946 // (and now has half a second remaining) could inadvertently get its life extended, by either
6947 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
6948 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
6949 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
6950 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
6951 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
6952 // To avoid this, we need to ensure that the cache flushing operation will only act to
6953 // *decrease* a record's remaining lifetime, never *increase* it.
6954 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
6955 // For Unicast (null InterfaceID) the DNSservers should also match
6956 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
6957 (r1->resrec.InterfaceID || (r1->resrec.rDNSServer == r2->resrec.rDNSServer)) &&
6958 r1->resrec.rrtype == r2->resrec.rrtype &&
6959 r1->resrec.rrclass == r2->resrec.rrclass)
6960 {
6961 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
6962 // else, if record is old, mark it to be flushed
6963 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
6964 {
6965 // If we find mismatched TTLs in an RRSet, correct them.
6966 // We only do this for records with a TTL of 2 or higher. It's possible to have a
6967 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
6968 // which we treat as a goodbye followed by an addition) and in that case it would be
6969 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
6970 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
6971 // because certain early Bonjour devices are known to have this specific mismatch, and
6972 // there's no point filling syslog with messages about something we already know about.
6973 // We also don't log this for uDNS responses, since a caching name server is obliged
6974 // to give us an aged TTL to correct for how long it has held the record,
6975 // so our received TTLs are expected to vary in that case
6976 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
6977 {
6978 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
6979 mDNSOpaque16IsZero(response->h.id))
6980 LogInfo("Correcting TTL from %4d to %4d for %s",
6981 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
6982 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
6983 }
6984 r2->TimeRcvd = m->timenow;
6985 }
6986 else // else, if record is old, mark it to be flushed
6987 {
6988 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
6989 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
6990 // We set stale records to expire in one second.
6991 // This gives the owner a chance to rescue it if necessary.
6992 // This is important in the case of multi-homing and bridged networks:
6993 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
6994 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
6995 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
6996 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
6997 // By delaying the deletion by one second, we give X a change to notice that this bridging has
6998 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
6999
7000 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
7001 // final expiration queries for this record.
7002
7003 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
7004 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
7005 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
7006 // <rdar://problem/5636422> Updating TXT records is too slow
7007 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
7008 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
7009 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
7010 {
7011 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
7012 r2->resrec.rroriginalttl = 0;
7013 }
7014 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
7015 {
7016 // We only set a record to expire in one second if it currently has *more* than a second to live
7017 // If it's already due to expire in a second or less, we just leave it alone
7018 r2->resrec.rroriginalttl = 1;
7019 r2->UnansweredQueries = MaxUnansweredQueries;
7020 r2->TimeRcvd = m->timenow - 1;
7021 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
7022 // that we marked for deletion via an explicit DE record
7023 }
7024 }
7025 SetNextCacheCheckTimeForRecord(m, r2);
7026 }
7027
7028 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
7029 {
7030 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash, slot);
7031 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
7032 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
7033 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
7034 }
7035 }
7036
7037 // See if we need to generate negative cache entries for unanswered unicast questions
7038 ptr = response->data;
7039 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
7040 {
7041 DNSQuestion q;
7042 DNSQuestion *qptr = mDNSNULL;
7043 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
7044 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
7045 {
7046 CacheRecord *rr, *neg = mDNSNULL;
7047 mDNSu32 slot = HashSlot(&q.qname);
7048 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
7049 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7050 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
7051 {
7052 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
7053 if (RRExpireTime(rr) - m->timenow > 0) break;
7054 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
7055 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
7056 }
7057 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
7058 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
7059 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
7060 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
7061 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
7062 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
7063 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
7064 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
7065 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
7066 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
7067 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
7068 {
7069 // If we did not find a positive answer and we can append search domains to this question,
7070 // generate a negative response (without creating a cache entry) to append search domains.
7071 if (qptr->AppendSearchDomains && !rr)
7072 {
7073 LogInfo("mDNSCoreReceiveResponse: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
7074 m->CurrentQuestion = qptr;
7075 GenerateNegativeResponse(m);
7076 m->CurrentQuestion = mDNSNULL;
7077 }
7078 else LogInfo("mDNSCoreReceiveResponse: Skipping check to see if we need to generate a negative cache entry for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
7079 }
7080 else
7081 {
7082 if (!rr)
7083 {
7084 // We start off assuming a negative caching TTL of 60 seconds
7085 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
7086 mDNSu32 negttl = 60;
7087 int repeat = 0;
7088 const domainname *name = &q.qname;
7089 mDNSu32 hash = q.qnamehash;
7090
7091 // Special case for our special Microsoft Active Directory "local SOA" check.
7092 // Some cheap home gateways don't include an SOA record in the authority section when
7093 // they send negative responses, so we don't know how long to cache the negative result.
7094 // Because we don't want to keep hitting the root name servers with our query to find
7095 // if we're on a network using Microsoft Active Directory using "local" as a private
7096 // internal top-level domain, we make sure to cache the negative result for at least one day.
7097 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
7098
7099 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
7100 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
7101 {
7102 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7103 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
7104 {
7105 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
7106 mDNSu32 ttl_s = soa->min;
7107 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
7108 // for the SOA record for ".", where the record is reported as non-cacheable
7109 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
7110 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
7111 ttl_s = m->rec.r.resrec.rroriginalttl;
7112 if (negttl < ttl_s) negttl = ttl_s;
7113
7114 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
7115 // with an Authority Section SOA record for d.com, then this is a hint that the authority
7116 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
7117 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
7118 if (q.qtype == kDNSType_SOA)
7119 {
7120 int qcount = CountLabels(&q.qname);
7121 int scount = CountLabels(m->rec.r.resrec.name);
7122 if (qcount - 1 > scount)
7123 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
7124 repeat = qcount - 1 - scount;
7125 }
7126 }
7127 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7128 }
7129
7130 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
7131 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
7132 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
7133 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
7134 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
7135 // so that we back off our polling rate and don't keep hitting the server continually.
7136 if (neg)
7137 {
7138 if (negttl < neg->resrec.rroriginalttl * 2)
7139 negttl = neg->resrec.rroriginalttl * 2;
7140 if (negttl > 3600)
7141 negttl = 3600;
7142 }
7143
7144 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
7145
7146 // If we already had a negative cache entry just update it, else make one or more new negative cache entries
7147 if (neg)
7148 {
7149 debugf("Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
7150 RefreshCacheRecord(m, neg, negttl);
7151 }
7152 else while (1)
7153 {
7154 debugf("mDNSCoreReceiveResponse making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
7155 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
7156 CreateNewCacheEntry(m, slot, cg, 0); // We never need any delivery delay for these generated negative cache records
7157 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7158 if (!repeat) break;
7159 repeat--;
7160 name = (const domainname *)(name->c + 1 + name->c[0]);
7161 hash = DomainNameHashValue(name);
7162 slot = HashSlot(name);
7163 cg = CacheGroupForName(m, slot, hash, name);
7164 }
7165 }
7166 }
7167 }
7168 }
7169 }
7170
7171 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
7172 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
7173 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
7174 // that warrants waking the sleeping host.
7175 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
7176
7177 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
7178 {
7179 // We don't need to use the m->CurrentRecord mechanism here because the target HMAC is nonzero,
7180 // so all we're doing is marking the record to generate a few wakeup packets
7181 AuthRecord *rr;
7182 if (!e->l[0]) { LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero"); return; }
7183 for (rr = thelist; rr; rr = rr->next)
7184 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
7185 {
7186 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
7187 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7188 }
7189 }
7190
7191 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
7192 {
7193 if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
7194 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
7195 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
7196 }
7197
7198 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
7199 {
7200 if (result && result != mStatus_MemFree)
7201 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
7202
7203 if (result == mStatus_NameConflict)
7204 {
7205 mDNS_Lock(m);
7206 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
7207 if (ar->WakeUp.HMAC.l[0])
7208 {
7209 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password); // Send one wakeup magic packet
7210 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken
7211 }
7212 mDNS_Unlock(m);
7213 }
7214
7215 if (result == mStatus_NameConflict || result == mStatus_MemFree)
7216 {
7217 m->ProxyRecords--;
7218 mDNSPlatformMemFree(ar);
7219 mDNS_UpdateAllowSleep(m);
7220 }
7221 }
7222
7223 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
7224 const DNSMessage *const msg, const mDNSu8 *end,
7225 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
7226 const mDNSInterfaceID InterfaceID)
7227 {
7228 int i;
7229 AuthRecord opt;
7230 mDNSu8 *p = m->omsg.data;
7231 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
7232 mDNSu32 updatelease = 0;
7233 const mDNSu8 *ptr;
7234
7235 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7236 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
7237 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7238 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
7239 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
7240 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
7241 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
7242
7243 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
7244
7245 if (mDNS_PacketLoggingEnabled)
7246 DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
7247
7248 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
7249 if (ptr)
7250 {
7251 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
7252 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7253 {
7254 const rdataOPT *o;
7255 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7256 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
7257 {
7258 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
7259 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
7260 }
7261 }
7262 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7263 }
7264
7265 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
7266
7267 if (!updatelease || !owner.HMAC.l[0])
7268 {
7269 static int msgs = 0;
7270 if (msgs < 100)
7271 {
7272 msgs++;
7273 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
7274 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
7275 }
7276 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
7277 }
7278 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
7279 {
7280 static int msgs = 0;
7281 if (msgs < 100)
7282 {
7283 msgs++;
7284 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
7285 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
7286 }
7287 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
7288 }
7289 else
7290 {
7291 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
7292
7293 if (updatelease > 24 * 60 * 60)
7294 updatelease = 24 * 60 * 60;
7295
7296 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
7297 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
7298
7299 ptr = LocateAuthorities(msg, end);
7300 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
7301 {
7302 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7303 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7304 {
7305 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
7306 AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
7307 if (!ar) { m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; break; }
7308 else
7309 {
7310 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
7311 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
7312 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
7313 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
7314 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
7315 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
7316 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
7317 ar->resrec.rdata->MaxRDLength = RDLengthMem;
7318 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
7319 ar->ForceMCast = mDNStrue;
7320 ar->WakeUp = owner;
7321 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
7322 {
7323 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
7324 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
7325 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
7326 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
7327 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
7328 }
7329 ar->TimeRcvd = m->timenow;
7330 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
7331 if (m->NextScheduledSPS - ar->TimeExpire > 0)
7332 m->NextScheduledSPS = ar->TimeExpire;
7333 mDNS_Register_internal(m, ar);
7334 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
7335 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
7336 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
7337 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
7338 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
7339 if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
7340 if (ar->resrec.rrtype == kDNSType_AAAA) ar->resrec.rroriginalttl = 0;
7341 m->ProxyRecords++;
7342 mDNS_UpdateAllowSleep(m);
7343 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
7344 }
7345 }
7346 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7347 }
7348
7349 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
7350 {
7351 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
7352 ClearProxyRecords(m, &owner, m->DuplicateRecords);
7353 ClearProxyRecords(m, &owner, m->ResourceRecords);
7354 }
7355 else
7356 {
7357 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
7358 opt.resrec.rrclass = NormalMaxDNSMessageData;
7359 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
7360 opt.resrec.rdestimate = sizeof(rdataOPT);
7361 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
7362 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
7363 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
7364 }
7365 }
7366
7367 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
7368 }
7369
7370 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSInterfaceID InterfaceID)
7371 {
7372 if (InterfaceID)
7373 {
7374 mDNSu32 updatelease = 60 * 60; // If SPS fails to indicate lease time, assume one hour
7375 const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
7376 if (ptr)
7377 {
7378 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
7379 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7380 {
7381 const rdataOPT *o;
7382 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7383 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
7384 if (o->opt == kDNSOpt_Lease)
7385 {
7386 updatelease = o->u.updatelease;
7387 LogSPS("Sleep Proxy granted lease time %4d seconds", updatelease);
7388 }
7389 }
7390 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7391 }
7392
7393 if (m->CurrentRecord)
7394 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7395 m->CurrentRecord = m->ResourceRecords;
7396 while (m->CurrentRecord)
7397 {
7398 AuthRecord *const rr = m->CurrentRecord;
7399 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
7400 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
7401 {
7402 rr->updateid = zeroID;
7403 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
7404 LogSPS("Sleep Proxy %s record %5d %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", updatelease, ARDisplayString(m,rr));
7405 if (rr->WakeUp.HMAC.l[0])
7406 {
7407 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7408 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
7409 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7410 }
7411 }
7412 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7413 // new records could have been added to the end of the list as a result of that call.
7414 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7415 m->CurrentRecord = rr->next;
7416 }
7417 }
7418 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
7419 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
7420 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
7421 }
7422
7423 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
7424 const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
7425 {
7426 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
7427 {
7428 LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
7429 #if ForceAlerts
7430 *(long*)0 = 0;
7431 #endif
7432 }
7433
7434 // Create empty resource record
7435 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
7436 cr->resrec.InterfaceID = InterfaceID;
7437 cr->resrec.rDNSServer = dnsserver;
7438 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
7439 cr->resrec.rrtype = rrtype;
7440 cr->resrec.rrclass = rrclass;
7441 cr->resrec.rroriginalttl = ttl_seconds;
7442 cr->resrec.rdlength = 0;
7443 cr->resrec.rdestimate = 0;
7444 cr->resrec.namehash = namehash;
7445 cr->resrec.rdatahash = 0;
7446 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
7447 cr->resrec.rdata->MaxRDLength = 0;
7448
7449 cr->NextInKAList = mDNSNULL;
7450 cr->TimeRcvd = m->timenow;
7451 cr->DelayDelivery = 0;
7452 cr->NextRequiredQuery = m->timenow;
7453 cr->LastUsed = m->timenow;
7454 cr->CRActiveQuestion = mDNSNULL;
7455 cr->UnansweredQueries = 0;
7456 cr->LastUnansweredTime = 0;
7457 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7458 cr->MPUnansweredQ = 0;
7459 cr->MPLastUnansweredQT = 0;
7460 cr->MPUnansweredKA = 0;
7461 cr->MPExpectingKA = mDNSfalse;
7462 #endif
7463 cr->NextInCFList = mDNSNULL;
7464 }
7465
7466 mDNSexport void mDNSCoreReceive(mDNS *const m, void *const pkt, const mDNSu8 *const end,
7467 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
7468 const mDNSInterfaceID InterfaceID)
7469 {
7470 mDNSInterfaceID ifid = InterfaceID;
7471 DNSMessage *msg = (DNSMessage *)pkt;
7472 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
7473 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
7474 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
7475 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
7476 mDNSu8 QR_OP;
7477 mDNSu8 *ptr = mDNSNULL;
7478 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
7479 if (TLS) dstaddr = mDNSNULL;
7480
7481 #ifndef UNICAST_DISABLED
7482 if (mDNSSameAddress(srcaddr, &m->Router))
7483 {
7484 #ifdef _LEGACY_NAT_TRAVERSAL_
7485 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
7486 {
7487 mDNS_Lock(m);
7488 LNT_ConfigureRouterInfo(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
7489 mDNS_Unlock(m);
7490 return;
7491 }
7492 #endif
7493 if (mDNSSameIPPort(srcport, NATPMPPort))
7494 {
7495 mDNS_Lock(m);
7496 uDNS_ReceiveNATPMPPacket(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
7497 mDNS_Unlock(m);
7498 return;
7499 }
7500 }
7501 #ifdef _LEGACY_NAT_TRAVERSAL_
7502 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
7503 #endif
7504
7505 #endif
7506 if ((unsigned)(end - (mDNSu8 *)pkt) < sizeof(DNSMessageHeader))
7507 {
7508 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt);
7509 return;
7510 }
7511 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
7512 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
7513 ptr = (mDNSu8 *)&msg->h.numQuestions;
7514 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
7515 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
7516 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
7517 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
7518
7519 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
7520
7521 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
7522 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
7523 if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
7524
7525 mDNS_Lock(m);
7526 m->PktNum++;
7527 #ifndef UNICAST_DISABLED
7528 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
7529 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
7530 {
7531 ifid = mDNSInterface_Any;
7532 if (mDNS_PacketLoggingEnabled)
7533 DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
7534 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
7535 // Note: mDNSCore also needs to get access to received unicast responses
7536 }
7537 #endif
7538 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
7539 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
7540 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
7541 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, InterfaceID);
7542 else
7543 {
7544 LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
7545 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt, InterfaceID);
7546 if (mDNS_LoggingEnabled)
7547 {
7548 int i = 0;
7549 while (i<end - (mDNSu8 *)pkt)
7550 {
7551 char buffer[128];
7552 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
7553 do if (i<end - (mDNSu8 *)pkt) p += mDNS_snprintf(p, sizeof(buffer), " %02X", ((mDNSu8 *)pkt)[i]); while (++i & 15);
7554 LogInfo("%s", buffer);
7555 }
7556 }
7557 }
7558 // Packet reception often causes a change to the task list:
7559 // 1. Inbound queries can cause us to need to send responses
7560 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
7561 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
7562 // 4. Response packets that answer questions may cause our client to issue new questions
7563 mDNS_Unlock(m);
7564 }
7565
7566 // ***************************************************************************
7567 #if COMPILER_LIKES_PRAGMA_MARK
7568 #pragma mark -
7569 #pragma mark - Searcher Functions
7570 #endif
7571
7572 // Targets are considered the same if both queries are untargeted, or
7573 // if both are targeted to the same address+port
7574 // (If Target address is zero, TargetPort is undefined)
7575 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
7576 (mDNSSameAddress(&(A)->Target, &(B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
7577
7578 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
7579 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
7580 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
7581 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
7582 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
7583 //
7584 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
7585 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
7586 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
7587 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
7588 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
7589 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
7590 // breaks this design principle.
7591
7592 // If IsLLQ(Q) is true, it means the question is both:
7593 // (a) long-lived and
7594 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
7595 // for multicast questions, we don't want to treat LongLived as anything special
7596 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
7597
7598 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
7599 {
7600 DNSQuestion *q;
7601 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
7602 // This prevents circular references, where two questions are each marked as a duplicate of the other.
7603 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
7604 // further in the list.
7605 for (q = m->Questions; q && q != question; q=q->next) // Scan our list for another question
7606 if (q->InterfaceID == question->InterfaceID && // with the same InterfaceID,
7607 SameQTarget(q, question) && // and same unicast/multicast target settings
7608 q->qtype == question->qtype && // type,
7609 q->qclass == question->qclass && // class,
7610 IsLLQ(q) == IsLLQ(question) && // and long-lived status matches
7611 (!q->AuthInfo || question->AuthInfo) && // to avoid deadlock, don't make public query dup of a private one
7612 (q->SuppressQuery == question->SuppressQuery) && // Questions that are suppressed/not suppressed
7613 q->qnamehash == question->qnamehash &&
7614 SameDomainName(&q->qname, &question->qname)) // and name
7615 return(q);
7616 return(mDNSNULL);
7617 }
7618
7619 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
7620 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
7621 {
7622 DNSQuestion *q;
7623 DNSQuestion *first = mDNSNULL;
7624
7625 // This is referring to some other question as duplicate. No other question can refer to this
7626 // question as a duplicate.
7627 if (question->DuplicateOf)
7628 {
7629 LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
7630 question, question->qname.c, DNSTypeName(question->qtype),
7631 question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
7632 return;
7633 }
7634
7635 for (q = m->Questions; q; q=q->next) // Scan our list of questions
7636 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
7637 {
7638 q->DuplicateOf = first;
7639 if (!first)
7640 {
7641 first = q;
7642 // If q used to be a duplicate, but now is not,
7643 // then inherit the state from the question that's going away
7644 q->LastQTime = question->LastQTime;
7645 q->ThisQInterval = question->ThisQInterval;
7646 q->ExpectUnicastResp = question->ExpectUnicastResp;
7647 q->LastAnswerPktNum = question->LastAnswerPktNum;
7648 q->RecentAnswerPkts = question->RecentAnswerPkts;
7649 q->RequestUnicast = question->RequestUnicast;
7650 q->LastQTxTime = question->LastQTxTime;
7651 q->CNAMEReferrals = question->CNAMEReferrals;
7652 q->nta = question->nta;
7653 q->servAddr = question->servAddr;
7654 q->servPort = question->servPort;
7655 q->qDNSServer = question->qDNSServer;
7656 q->validDNSServers = question->validDNSServers;
7657 q->unansweredQueries = question->unansweredQueries;
7658 q->noServerResponse = question->noServerResponse;
7659 q->triedAllServersOnce = question->triedAllServersOnce;
7660
7661 q->TargetQID = question->TargetQID;
7662 q->LocalSocket = question->LocalSocket;
7663
7664 q->state = question->state;
7665 // q->tcp = question->tcp;
7666 q->ReqLease = question->ReqLease;
7667 q->expire = question->expire;
7668 q->ntries = question->ntries;
7669 q->id = question->id;
7670
7671 question->LocalSocket = mDNSNULL;
7672 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
7673 // question->tcp = mDNSNULL;
7674
7675 if (q->LocalSocket)
7676 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7677
7678 if (q->nta)
7679 {
7680 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7681 q->nta->ZoneDataContext = q;
7682 }
7683
7684 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
7685 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
7686
7687 if (question->state == LLQ_Established)
7688 {
7689 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7690 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
7691 }
7692
7693 SetNextQueryTime(m,q);
7694 }
7695 }
7696 }
7697
7698 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
7699 {
7700 McastResolver **p = &m->McastResolvers;
7701 McastResolver *tmp = mDNSNULL;
7702
7703 if (!d) d = (const domainname *)"";
7704
7705 LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
7706
7707 if (m->mDNS_busy != m->mDNS_reentrancy+1)
7708 LogMsg("mDNS_AddMcastResolver: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
7709
7710 while (*p) // Check if we already have this {interface, domain} tuple registered
7711 {
7712 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
7713 {
7714 if (!((*p)->flags & DNSServer_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
7715 (*p)->flags &= ~DNSServer_FlagDelete;
7716 tmp = *p;
7717 *p = tmp->next;
7718 tmp->next = mDNSNULL;
7719 }
7720 else
7721 p=&(*p)->next;
7722 }
7723
7724 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
7725 else
7726 {
7727 // allocate, add to list
7728 *p = mDNSPlatformMemAllocate(sizeof(**p));
7729 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
7730 else
7731 {
7732 (*p)->interface = interface;
7733 (*p)->flags = DNSServer_FlagNew;
7734 (*p)->timeout = timeout;
7735 AssignDomainName(&(*p)->domain, d);
7736 (*p)->next = mDNSNULL;
7737 }
7738 }
7739 return(*p);
7740 }
7741
7742 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
7743 {
7744 mDNSs32 ptime = 0;
7745 if (server->penaltyTime != 0)
7746 {
7747 ptime = server->penaltyTime - m->timenow;
7748 if (ptime < 0)
7749 {
7750 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
7751 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
7752 // here
7753 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
7754 ptime, server->penaltyTime, m->timenow);
7755 server->penaltyTime = 0;
7756 ptime = 0;
7757 }
7758 }
7759 return ptime;
7760 }
7761
7762 //Checks to see whether the newname is a better match for the name, given the best one we have
7763 //seen so far (given in bestcount).
7764 //Returns -1 if the newname is not a better match
7765 //Returns 0 if the newname is the same as the old match
7766 //Returns 1 if the newname is a better match
7767 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
7768 int bestcount)
7769 {
7770 // If the name contains fewer labels than the new server's domain or the new name
7771 // contains fewer labels than the current best, then it can't possibly be a better match
7772 if (namecount < newcount || newcount < bestcount) return -1;
7773
7774 // If there is no match, return -1 and the caller will skip this newname for
7775 // selection
7776 //
7777 // If we find a match and the number of labels is the same as bestcount, then
7778 // we return 0 so that the caller can do additional logic to pick one of
7779 // the best based on some other factors e.g., penaltyTime
7780 //
7781 // If we find a match and the number of labels is more than bestcount, then we
7782 // return 1 so that the caller can pick this over the old one.
7783 //
7784 // Note: newcount can either be equal or greater than bestcount beause of the
7785 // check above.
7786
7787 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
7788 return bestcount == newcount ? 0 : 1;
7789 else
7790 return -1;
7791 }
7792
7793 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
7794 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
7795 // names. In that case, we give a default timeout of 5 seconds
7796 #define DEFAULT_MCAST_TIMEOUT 5
7797 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
7798 {
7799 McastResolver *curmatch = mDNSNULL;
7800 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
7801 McastResolver *curr;
7802 int bettermatch, currcount;
7803 for (curr = m->McastResolvers; curr; curr = curr->next)
7804 {
7805 currcount = CountLabels(&curr->domain);
7806 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
7807 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
7808 // the timeout value from the first one
7809 if (bettermatch == 1)
7810 {
7811 curmatch = curr;
7812 bestmatchlen = currcount;
7813 }
7814 }
7815 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
7816 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
7817 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
7818 }
7819
7820 // Sets all the Valid DNS servers for a question
7821 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
7822 {
7823 DNSServer *curmatch = mDNSNULL;
7824 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
7825 DNSServer *curr;
7826 int bettermatch, currcount;
7827 int index = 0;
7828 mDNSu32 timeout = 0;
7829
7830 question->validDNSServers = zeroOpaque64;
7831 for (curr = m->DNSServers; curr; curr = curr->next)
7832 {
7833 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
7834 // skip servers that will soon be deleted
7835 if (curr->flags & DNSServer_FlagDelete)
7836 { debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
7837
7838 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
7839 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
7840 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
7841 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
7842 // match the scoped entries by mistake.
7843 //
7844 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
7845
7846 if (curr->scoped && curr->interface == mDNSInterface_Any)
7847 { debugf("SetValidDNSServers: Scoped DNS server %#a (Domain %##s) with Interface Any", &curr->addr, curr->domain.c); continue; }
7848
7849 currcount = CountLabels(&curr->domain);
7850 if ((!curr->scoped && (!question->InterfaceID || (question->InterfaceID == mDNSInterface_Unicast))) || (curr->interface == question->InterfaceID))
7851 {
7852 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
7853
7854 // If we found a better match (bettermatch == 1) then clear all the bits
7855 // corresponding to the old DNSServers that we have may set before and start fresh.
7856 // If we find an equal match, then include that DNSServer also by setting the corresponding
7857 // bit
7858 if ((bettermatch == 1) || (bettermatch == 0))
7859 {
7860 curmatch = curr;
7861 bestmatchlen = currcount;
7862 if (bettermatch) { debugf("SetValidDNSServers: Resetting all the bits"); question->validDNSServers = zeroOpaque64; timeout = 0; }
7863 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
7864 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
7865 curr->interface);
7866 timeout += curr->timeout;
7867 bit_set_opaque64(question->validDNSServers, index);
7868 }
7869 }
7870 index++;
7871 }
7872 question->noServerResponse = 0;
7873
7874 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
7875 question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
7876 // If there are no matching resolvers, then use the default value to timeout
7877 return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
7878 }
7879
7880 // Get the Best server that matches a name. If you find penalized servers, look for the one
7881 // that will come out of the penalty box soon
7882 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSOpaque64 validBits, int *selected, mDNSBool nameMatch)
7883 {
7884 DNSServer *curmatch = mDNSNULL;
7885 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
7886 DNSServer *curr;
7887 mDNSs32 bestPenaltyTime, currPenaltyTime;
7888 int bettermatch, currcount;
7889 int index = 0;
7890 int currindex = -1;
7891
7892 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
7893 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
7894 for (curr = m->DNSServers; curr; curr = curr->next)
7895 {
7896 // skip servers that will soon be deleted
7897 if (curr->flags & DNSServer_FlagDelete)
7898 { debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
7899
7900 // Check if this is a valid DNSServer
7901 if (!bit_get_opaque64(validBits, index)) { debugf("GetBestServer: continuing for index %d", index); index++; continue; }
7902
7903 currcount = CountLabels(&curr->domain);
7904 currPenaltyTime = PenaltyTimeForServer(m, curr);
7905
7906 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
7907 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
7908
7909 // If there are multiple best servers for a given question, we will pick the first one
7910 // if none of them are penalized. If some of them are penalized in that list, we pick
7911 // the least penalized one. BetterMatchForName walks through all best matches and
7912 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
7913 // in the list when there are no penalized servers and least one among them
7914 // when there are some penalized servers
7915 //
7916 // Notes on InterfaceID matching:
7917 //
7918 // 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
7919 // is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
7920 // entries by "scoped" being false. These are like any other unscoped entries except that
7921 // if it is picked e.g., domain match, when the packet is sent out later, the packet will
7922 // be sent out on that interface. Theese entries can be matched by either specifying a
7923 // zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
7924 // the question will cause an extra check on matching the InterfaceID on the question
7925 // against the DNSServer.
7926 //
7927 // 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
7928 // is the new way of specifying an InterfaceID option for DNSServer. These will be considered
7929 // only when the question has non-zero interfaceID.
7930
7931 if ((!curr->scoped && !InterfaceID) || (curr->interface == InterfaceID))
7932 {
7933
7934 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
7935 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
7936 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
7937 // part and still do some redundant steps e.g., InterfaceID match
7938
7939 if (nameMatch) bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
7940 else bettermatch = 0;
7941
7942 // If we found a better match (bettermatch == 1) then we don't need to
7943 // compare penalty times. But if we found an equal match, then we compare
7944 // the penalty times to pick a better match
7945
7946 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
7947 { currindex = index; curmatch = curr; bestmatchlen = currcount; bestPenaltyTime = currPenaltyTime; }
7948 }
7949 index++;
7950 }
7951 if (selected) *selected = currindex;
7952 return curmatch;
7953 }
7954
7955 // Look up a DNS Server, matching by name and InterfaceID
7956 mDNSexport DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID)
7957 {
7958 DNSServer *curmatch = mDNSNULL;
7959 char *ifname = mDNSNULL; // for logging purposes only
7960 mDNSOpaque64 allValid;
7961
7962 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
7963 InterfaceID = mDNSNULL;
7964
7965 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
7966
7967 // By passing in all ones, we make sure that every DNS server is considered
7968 allValid.l[0] = allValid.l[1] = 0xFFFFFFFF;
7969
7970 curmatch = GetBestServer(m, name, InterfaceID, allValid, mDNSNULL, mDNStrue);
7971
7972 if (curmatch != mDNSNULL)
7973 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
7974 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
7975 InterfaceID, name);
7976 else
7977 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
7978
7979 return(curmatch);
7980 }
7981
7982 // Look up a DNS Server for a question within its valid DNSServer bits
7983 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
7984 {
7985 DNSServer *curmatch = mDNSNULL;
7986 char *ifname = mDNSNULL; // for logging purposes only
7987 mDNSInterfaceID InterfaceID = question->InterfaceID;
7988 const domainname *name = &question->qname;
7989 int currindex;
7990
7991 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
7992 InterfaceID = mDNSNULL;
7993
7994 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
7995
7996 if (!mDNSOpaque64IsZero(&question->validDNSServers))
7997 {
7998 curmatch = GetBestServer(m, name, InterfaceID, question->validDNSServers, &currindex, mDNSfalse);
7999 if (currindex != -1) bit_clr_opaque64(question->validDNSServers, currindex);
8000 }
8001
8002 if (curmatch != mDNSNULL)
8003 LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question, &curmatch->addr,
8004 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
8005 InterfaceID, name, DNSTypeName(question->qtype));
8006 else
8007 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question, ifname ? ifname : "None", InterfaceID, name, DNSTypeName(question->qtype));
8008
8009 return(curmatch);
8010 }
8011
8012
8013 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
8014 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
8015
8016 // Called in normal client context (lock not held)
8017 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
8018 {
8019 DNSQuestion *q;
8020 (void)n; // Unused
8021 mDNS_Lock(m);
8022 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
8023 for (q = m->Questions; q; q=q->next)
8024 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
8025 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
8026 #if APPLE_OSX_mDNSResponder
8027 UpdateAutoTunnelDomainStatuses(m);
8028 #endif
8029 mDNS_Unlock(m);
8030 }
8031
8032 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, domainname *qname, mDNSu16 qtype, mDNSInterfaceID InterfaceID)
8033 {
8034 NetworkInterfaceInfo *i;
8035 mDNSs32 iptype;
8036 DomainAuthInfo *AuthInfo;
8037
8038 if (qtype == kDNSType_A) iptype = mDNSAddrType_IPv4;
8039 else if (qtype == kDNSType_AAAA) iptype = mDNSAddrType_IPv6;
8040 else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname, DNSTypeName(qtype)); return mDNSfalse; }
8041
8042 // We still want the ability to be able to listen to the local services and hence
8043 // don't fail .local requests. We always have a loopback interface which we don't
8044 // check here.
8045 if (InterfaceID != mDNSInterface_Unicast && IsLocalDomain(qname)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname, DNSTypeName(qtype)); return mDNSfalse; }
8046
8047 // Skip Private domains as we have special addresses to get the hosts in the Private domain
8048 AuthInfo = GetAuthInfoForName_internal(m, qname);
8049 if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
8050 { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname, DNSTypeName(qtype)); return mDNSfalse; }
8051
8052 // Match on Type, Address and InterfaceID
8053 //
8054 // Check whether we are looking for a name that ends in .local, then presence of a link-local
8055 // address on the interface is sufficient.
8056 for (i = m->HostInterfaces; i; i = i->next)
8057 {
8058 if (i->ip.type != iptype) continue;
8059
8060 if (!InterfaceID || (InterfaceID == mDNSInterface_LocalOnly) || (InterfaceID == mDNSInterface_P2P) ||
8061 (InterfaceID == mDNSInterface_Unicast) || (i->InterfaceID == InterfaceID))
8062 {
8063 if (iptype == mDNSAddrType_IPv4 && !mDNSv4AddressIsLoopback(&i->ip.ip.v4) && !mDNSv4AddressIsLinkLocal(&i->ip.ip.v4))
8064 {
8065 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname, DNSTypeName(qtype),
8066 &i->ip.ip.v4);
8067 return mDNSfalse;
8068 }
8069 else if (iptype == mDNSAddrType_IPv6 &&
8070 !mDNSv6AddressIsLoopback(&i->ip.ip.v6) &&
8071 !mDNSv6AddressIsLinkLocal(&i->ip.ip.v6) &&
8072 !mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelHostAddr) &&
8073 !mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelRelayAddrOut))
8074 {
8075 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname, DNSTypeName(qtype),
8076 &i->ip.ip.v6);
8077 return mDNSfalse;
8078 }
8079 }
8080 }
8081 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname, DNSTypeName(qtype));
8082 return mDNStrue;
8083 }
8084
8085 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
8086 {
8087 CacheRecord *rr;
8088 mDNSu32 slot;
8089 CacheGroup *cg;
8090
8091 slot = HashSlot(&q->qname);
8092 cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
8093 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8094 {
8095 // Don't deliver RMV events for negative records
8096 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
8097 {
8098 LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
8099 CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
8100 continue;
8101 }
8102
8103 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
8104 {
8105 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
8106 q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
8107
8108 q->CurrentAnswers--;
8109 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
8110 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
8111
8112 if (rr->CRActiveQuestion == q)
8113 {
8114 DNSQuestion *qptr;
8115 // If this was the active question for this cache entry, it was the one that was
8116 // responsible for keeping the cache entry fresh when the cache entry was reaching
8117 // its expiry. We need to handover the responsibility to someone else. Otherwise,
8118 // when the cache entry is about to expire, we won't find an active question
8119 // (pointed by CRActiveQuestion) to refresh the cache.
8120 for (qptr = m->Questions; qptr; qptr=qptr->next)
8121 if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
8122 break;
8123
8124 if (qptr)
8125 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
8126 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
8127 qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
8128
8129 rr->CRActiveQuestion = qptr; // Question used to be active; new value may or may not be null
8130 if (!qptr) m->rrcache_active--; // If no longer active, decrement rrcache_active count
8131 }
8132 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
8133 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
8134 }
8135 }
8136 }
8137
8138 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
8139 {
8140 DNSQuestion *q;
8141 for (q = m->NewQuestions; q; q = q->next)
8142 if (q == question) return mDNStrue;
8143 return mDNSfalse;
8144 }
8145
8146 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
8147 {
8148 AuthRecord *rr;
8149 mDNSu32 slot;
8150 AuthGroup *ag;
8151
8152 if (m->CurrentQuestion)
8153 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
8154 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
8155
8156 if (IsQuestionNew(m, q))
8157 {
8158 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
8159 return mDNStrue;
8160 }
8161 m->CurrentQuestion = q;
8162 slot = AuthHashSlot(&q->qname);
8163 ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
8164 if (ag)
8165 {
8166 for (rr = ag->members; rr; rr=rr->next)
8167 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
8168 if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
8169 {
8170 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
8171 ARDisplayString(m, rr));
8172 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
8173 {
8174 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
8175 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
8176 q->CurrentAnswers, q->LOAddressAnswers);
8177 continue;
8178 }
8179 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again
8180 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
8181 }
8182 }
8183 m->CurrentQuestion = mDNSNULL;
8184 return mDNStrue;
8185 }
8186
8187 // Returns false if the question got deleted while delivering the RMV events
8188 // The caller should handle the case
8189 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
8190 {
8191 if (m->CurrentQuestion)
8192 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
8193 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
8194
8195 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
8196 // If this question was answered using local auth records, then you can't deliver RMVs using cache
8197 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
8198 {
8199 m->CurrentQuestion = q;
8200 CacheRecordRmvEventsForCurrentQuestion(m, q);
8201 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
8202 m->CurrentQuestion = mDNSNULL;
8203 }
8204 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
8205 return mDNStrue;
8206 }
8207
8208 // The caller should hold the lock
8209 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
8210 {
8211 DNSQuestion *q;
8212 DNSQuestion *restart = mDNSNULL;
8213
8214 // We look through all questions including new questions. During network change events,
8215 // we potentially restart questions here in this function that ends up as new questions,
8216 // which may be suppressed at this instance. Before it is handled we get another network
8217 // event that changes the status e.g., address becomes available. If we did not process
8218 // new questions, we would never change its SuppressQuery status.
8219 //
8220 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
8221 // application callback can potentially stop the current question (detected by CurrentQuestion) or
8222 // *any* other question which could be the next one that we may process here. RestartQuestion
8223 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
8224 // if the "next" question is stopped while the CurrentQuestion is stopped
8225 if (m->RestartQuestion)
8226 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
8227 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
8228 m->RestartQuestion = m->Questions;
8229 while (m->RestartQuestion)
8230 {
8231 q = m->RestartQuestion;
8232 m->RestartQuestion = q->next;
8233 if (!mDNSOpaque16IsZero(q->TargetQID) && q->SuppressUnusable)
8234 {
8235 mDNSBool old = q->SuppressQuery;
8236 q->SuppressQuery = ShouldSuppressQuery(m, &q->qname, q->qtype, q->InterfaceID);
8237 if (q->SuppressQuery != old)
8238 {
8239 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
8240 // LOddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
8241 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
8242
8243 if (q->SuppressQuery)
8244 {
8245 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
8246 // followed by a negative cache response. Temporarily turn off suppression so that
8247 // AnswerCurrentQuestionWithResourceRecord can answer the question
8248 q->SuppressQuery = mDNSfalse;
8249 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
8250 q->SuppressQuery = mDNStrue;
8251 }
8252
8253 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
8254 // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
8255 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
8256 // the restart will not be a duplicate ADD
8257 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
8258
8259 // There are two cases here.
8260 //
8261 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
8262 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
8263 // because when we get the response, if we had entries in the cache already, it will not answer
8264 // this question if the cache entry did not change. Hence, we need to restart
8265 // the query so that it can be answered from the cache.
8266 //
8267 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
8268 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
8269 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
8270 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
8271 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
8272 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
8273 // the question is not suppressed, we don't want two active questions sending packets on the wire.
8274 // This affects both efficiency and also the current design where there is only one active question
8275 // pointed to from a cache entry.
8276 //
8277 // We restart queries in a two step process by first calling stop and build a temporary list which we
8278 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
8279 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
8280 // will soon become the real question) including q->ThisQInterval which might be zero if it was
8281 // suppressed before. At the end when we have restarted all questions, none of them is active as each
8282 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
8283 //
8284 // It is much cleaner and less error prone to build a list of questions and restart at the end.
8285
8286 LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8287 mDNS_StopQuery_internal(m, q);
8288 q->next = restart;
8289 restart = q;
8290 }
8291 }
8292 }
8293 while (restart)
8294 {
8295 q = restart;
8296 restart = restart->next;
8297 q->next = mDNSNULL;
8298 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8299 mDNS_StartQuery_internal(m, q);
8300 }
8301 }
8302
8303 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
8304 {
8305 if (question->Target.type && !ValidQuestionTarget(question))
8306 {
8307 LogMsg("mDNS_StartQuery_internal: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
8308 question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
8309 question->Target.type = mDNSAddrType_None;
8310 }
8311
8312 if (!question->Target.type) question->TargetPort = zeroIPPort; // If no question->Target specified clear TargetPort
8313
8314 question->TargetQID =
8315 #ifndef UNICAST_DISABLED
8316 (question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
8317 #endif // UNICAST_DISABLED
8318 zeroID;
8319
8320 debugf("mDNS_StartQuery: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8321
8322 if (m->rrcache_size == 0) // Can't do queries if we have no cache space allocated
8323 return(mStatus_NoCache);
8324 else
8325 {
8326 int i;
8327 DNSQuestion **q;
8328
8329 if (!ValidateDomainName(&question->qname))
8330 {
8331 LogMsg("Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8332 return(mStatus_Invalid);
8333 }
8334
8335 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
8336 q = &m->Questions;
8337 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) q = &m->LocalOnlyQuestions;
8338 while (*q && *q != question) q=&(*q)->next;
8339
8340 if (*q)
8341 {
8342 LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
8343 question->qname.c, DNSTypeName(question->qtype), question);
8344 return(mStatus_AlreadyRegistered);
8345 }
8346
8347 *q = question;
8348
8349 // If this question is referencing a specific interface, verify it exists
8350 if (question->InterfaceID && question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_Unicast && question->InterfaceID != mDNSInterface_P2P)
8351 {
8352 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
8353 if (!intf)
8354 LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
8355 question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
8356 }
8357
8358 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
8359 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
8360 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
8361 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
8362 // that to go out immediately.
8363 question->next = mDNSNULL;
8364 question->qnamehash = DomainNameHashValue(&question->qname); // MUST do this before FindDuplicateQuestion()
8365 question->DelayAnswering = CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash, HashSlot(&question->qname));
8366 question->LastQTime = m->timenow;
8367 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
8368 question->ExpectUnicastResp = 0;
8369 question->LastAnswerPktNum = m->PktNum;
8370 question->RecentAnswerPkts = 0;
8371 question->CurrentAnswers = 0;
8372 question->LargeAnswers = 0;
8373 question->UniqueAnswers = 0;
8374 question->LOAddressAnswers = 0;
8375 question->FlappingInterface1 = mDNSNULL;
8376 question->FlappingInterface2 = mDNSNULL;
8377 // Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
8378 question->AuthInfo = GetAuthInfoForQuestion(m, question);
8379 if (question->SuppressUnusable)
8380 question->SuppressQuery = ShouldSuppressQuery(m, &question->qname, question->qtype, question->InterfaceID);
8381 else
8382 question->SuppressQuery = 0;
8383 question->DuplicateOf = FindDuplicateQuestion(m, question);
8384 question->NextInDQList = mDNSNULL;
8385 question->SendQNow = mDNSNULL;
8386 question->SendOnAll = mDNSfalse;
8387 question->RequestUnicast = 0;
8388 question->LastQTxTime = m->timenow;
8389 question->CNAMEReferrals = 0;
8390
8391 // We'll create our question->LocalSocket on demand, if needed.
8392 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
8393 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
8394 // NAT mapping for receiving inbound add/remove events.
8395 question->LocalSocket = mDNSNULL;
8396 question->deliverAddEvents = mDNSfalse;
8397 question->qDNSServer = mDNSNULL;
8398 question->unansweredQueries = 0;
8399 question->nta = mDNSNULL;
8400 question->servAddr = zeroAddr;
8401 question->servPort = zeroIPPort;
8402 question->tcp = mDNSNULL;
8403 question->NoAnswer = NoAnswer_Normal;
8404
8405 question->state = LLQ_InitialRequest;
8406 question->ReqLease = 0;
8407 question->expire = 0;
8408 question->ntries = 0;
8409 question->id = zeroOpaque64;
8410 question->validDNSServers = zeroOpaque64;
8411 question->triedAllServersOnce = 0;
8412 question->noServerResponse = 0;
8413 question->StopTime = 0;
8414 if (question->WakeOnResolve)
8415 {
8416 question->WakeOnResolveCount = InitialWakeOnResolveCount;
8417 mDNS_PurgeBeforeResolve(m, question);
8418 }
8419 else
8420 question->WakeOnResolveCount = 0;
8421
8422 if (question->DuplicateOf) question->AuthInfo = question->DuplicateOf->AuthInfo;
8423
8424 for (i=0; i<DupSuppressInfoSize; i++)
8425 question->DupSuppress[i].InterfaceID = mDNSNULL;
8426
8427 debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
8428 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
8429 NextQSendTime(question) - m->timenow,
8430 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
8431 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
8432
8433 if (question->DelayAnswering)
8434 LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
8435 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
8436
8437 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
8438 {
8439 if (!m->NewLocalOnlyQuestions) m->NewLocalOnlyQuestions = question;
8440 }
8441 else
8442 {
8443 if (!m->NewQuestions) m->NewQuestions = question;
8444
8445 // If the question's id is non-zero, then it's Wide Area
8446 // MUST NOT do this Wide Area setup until near the end of
8447 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
8448 // NS, etc.) and if we haven't finished setting up our own question and setting
8449 // m->NewQuestions if necessary then we could end up recursively re-entering
8450 // this routine with the question list data structures in an inconsistent state.
8451 if (!mDNSOpaque16IsZero(question->TargetQID))
8452 {
8453 // Duplicate questions should have the same DNSServers so that when we find
8454 // a matching resource record, all of them get the answers. Calling GetServerForQuestion
8455 // for the duplicate question may get a different DNS server from the original question
8456 mDNSu32 timeout = SetValidDNSServers(m, question);
8457 // We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
8458 // a networking change/search domain change that calls this function again we keep
8459 // reinitializing the timeout value which means it may never timeout. If this becomes
8460 // a common case in the future, we can easily fix this by adding extra state that
8461 // indicates that we have already set the StopTime.
8462 if (question->TimeoutQuestion)
8463 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
8464 if (question->DuplicateOf)
8465 {
8466 question->validDNSServers = question->DuplicateOf->validDNSServers;
8467 question->qDNSServer = question->DuplicateOf->qDNSServer;
8468 LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), Timeout %d, DNS Server %#a:%d",
8469 question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype), timeout,
8470 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
8471 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
8472 }
8473 else
8474 {
8475 question->qDNSServer = GetServerForQuestion(m, question);
8476 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
8477 question, question->qname.c, DNSTypeName(question->qtype), timeout,
8478 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
8479 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
8480 }
8481 ActivateUnicastQuery(m, question, mDNSfalse);
8482
8483 // If long-lived query, and we don't have our NAT mapping active, start it now
8484 if (question->LongLived && !m->LLQNAT.clientContext)
8485 {
8486 m->LLQNAT.Protocol = NATOp_MapUDP;
8487 m->LLQNAT.IntPort = m->UnicastPort4;
8488 m->LLQNAT.RequestedPort = m->UnicastPort4;
8489 m->LLQNAT.clientCallback = LLQNATCallback;
8490 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal is active
8491 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
8492 }
8493
8494 #if APPLE_OSX_mDNSResponder
8495 if (question->LongLived)
8496 UpdateAutoTunnelDomainStatuses(m);
8497 #endif
8498
8499 }
8500 else
8501 {
8502 if (question->TimeoutQuestion)
8503 question->StopTime = NonZeroTime(m->timenow + GetTimeoutForMcastQuestion(m, question) * mDNSPlatformOneSecond);
8504 }
8505 if (question->StopTime) SetNextQueryStopTime(m, question);
8506 SetNextQueryTime(m,question);
8507 }
8508
8509 return(mStatus_NoError);
8510 }
8511 }
8512
8513 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
8514 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
8515 {
8516 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
8517 // This function may be called anytime to free the zone information.The question may or may not have stopped.
8518 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
8519 // call it again
8520 if (nta->question.ThisQInterval != -1)
8521 {
8522 mDNS_StopQuery_internal(m, &nta->question);
8523 if (nta->question.ThisQInterval != -1)
8524 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
8525 }
8526 mDNSPlatformMemFree(nta);
8527 }
8528
8529 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
8530 {
8531 const mDNSu32 slot = HashSlot(&question->qname);
8532 CacheGroup *cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
8533 CacheRecord *rr;
8534 DNSQuestion **qp = &m->Questions;
8535
8536 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8537
8538 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) qp = &m->LocalOnlyQuestions;
8539 while (*qp && *qp != question) qp=&(*qp)->next;
8540 if (*qp) *qp = (*qp)->next;
8541 else
8542 {
8543 #if !ForceAlerts
8544 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
8545 #endif
8546 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
8547 question->qname.c, DNSTypeName(question->qtype));
8548 #if ForceAlerts
8549 *(long*)0 = 0;
8550 #endif
8551 return(mStatus_BadReferenceErr);
8552 }
8553
8554 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
8555 UpdateQuestionDuplicates(m, question);
8556 // But don't trash ThisQInterval until afterwards.
8557 question->ThisQInterval = -1;
8558
8559 // If there are any cache records referencing this as their active question, then see if there is any
8560 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
8561 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8562 {
8563 if (rr->CRActiveQuestion == question)
8564 {
8565 DNSQuestion *q;
8566 // Checking for ActiveQuestion filters questions that are suppressed also
8567 // as suppressed questions are not active
8568 for (q = m->Questions; q; q=q->next) // Scan our list of questions
8569 if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
8570 break;
8571 if (q)
8572 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
8573 "CurrentAnswers %d, SuppressQuery %d", q, CRDisplayString(m,rr), question->CurrentAnswers, q->CurrentAnswers, q->SuppressQuery);
8574 rr->CRActiveQuestion = q; // Question used to be active; new value may or may not be null
8575 if (!q) m->rrcache_active--; // If no longer active, decrement rrcache_active count
8576 }
8577 }
8578
8579 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
8580 // bump its pointer forward one question.
8581 if (m->CurrentQuestion == question)
8582 {
8583 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
8584 question->qname.c, DNSTypeName(question->qtype));
8585 m->CurrentQuestion = question->next;
8586 }
8587
8588 if (m->NewQuestions == question)
8589 {
8590 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
8591 question->qname.c, DNSTypeName(question->qtype));
8592 m->NewQuestions = question->next;
8593 }
8594
8595 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
8596
8597 if (m->RestartQuestion == question)
8598 {
8599 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
8600 question->qname.c, DNSTypeName(question->qtype));
8601 m->RestartQuestion = question->next;
8602 }
8603
8604 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
8605 question->next = mDNSNULL;
8606
8607 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
8608
8609 // And finally, cancel any associated GetZoneData operation that's still running.
8610 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
8611 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
8612 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
8613 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
8614 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
8615 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
8616 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
8617 {
8618 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
8619 DNSQuestion *q;
8620 for (q = m->Questions; q; q=q->next)
8621 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
8622 if (!q)
8623 {
8624 if (!m->LLQNAT.clientContext) // Should never happen, but just in case...
8625 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
8626 else
8627 {
8628 LogInfo("Stopping LLQNAT");
8629 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
8630 m->LLQNAT.clientContext = mDNSNULL; // Means LLQ NAT Traversal not running
8631 }
8632 }
8633
8634 // If necessary, tell server it can delete this LLQ state
8635 if (question->state == LLQ_Established)
8636 {
8637 question->ReqLease = 0;
8638 sendLLQRefresh(m, question);
8639 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
8640 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
8641 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
8642 // we let that run out its natural course and complete asynchronously.
8643 if (question->tcp)
8644 {
8645 question->tcp->question = mDNSNULL;
8646 question->tcp = mDNSNULL;
8647 }
8648 }
8649 #if APPLE_OSX_mDNSResponder
8650 UpdateAutoTunnelDomainStatuses(m);
8651 #endif
8652 }
8653 // wait until we send the refresh above which needs the nta
8654 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
8655
8656 return(mStatus_NoError);
8657 }
8658
8659 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
8660 {
8661 mStatus status;
8662 mDNS_Lock(m);
8663 status = mDNS_StartQuery_internal(m, question);
8664 mDNS_Unlock(m);
8665 return(status);
8666 }
8667
8668 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
8669 {
8670 mStatus status;
8671 mDNS_Lock(m);
8672 status = mDNS_StopQuery_internal(m, question);
8673 mDNS_Unlock(m);
8674 return(status);
8675 }
8676
8677 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
8678 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
8679 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
8680 // specifically to catch and report if the client callback does try to make API calls
8681 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
8682 {
8683 mStatus status;
8684 DNSQuestion *qq;
8685 mDNS_Lock(m);
8686
8687 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
8688 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
8689
8690 status = mDNS_StopQuery_internal(m, question);
8691 if (status == mStatus_NoError && !qq)
8692 {
8693 const CacheRecord *rr;
8694 const mDNSu32 slot = HashSlot(&question->qname);
8695 CacheGroup *const cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
8696 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8697 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8698 if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
8699 {
8700 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
8701 if (question->QuestionCallback)
8702 question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
8703 }
8704 }
8705 mDNS_Unlock(m);
8706 return(status);
8707 }
8708
8709 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
8710 {
8711 mStatus status;
8712 mDNS_Lock(m);
8713 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8714 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
8715 mDNS_Unlock(m);
8716 return(status);
8717 }
8718
8719 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
8720 {
8721 mStatus status = mStatus_BadReferenceErr;
8722 CacheRecord *cr;
8723 mDNS_Lock(m);
8724 cr = FindIdenticalRecordInCache(m, rr);
8725 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
8726 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8727 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
8728 mDNS_Unlock(m);
8729 return(status);
8730 }
8731
8732 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
8733 const domainname *const srv, const domainname *const domain,
8734 const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
8735 {
8736 question->InterfaceID = InterfaceID;
8737 question->Target = zeroAddr;
8738 question->qtype = kDNSType_PTR;
8739 question->qclass = kDNSClass_IN;
8740 question->LongLived = mDNStrue;
8741 question->ExpectUnique = mDNSfalse;
8742 question->ForceMCast = ForceMCast;
8743 question->ReturnIntermed = mDNSfalse;
8744 question->SuppressUnusable = mDNSfalse;
8745 question->SearchListIndex = 0;
8746 question->AppendSearchDomains = 0;
8747 question->RetryWithSearchDomains = mDNSfalse;
8748 question->TimeoutQuestion = 0;
8749 question->WakeOnResolve = 0;
8750 question->qnameOrig = mDNSNULL;
8751 question->QuestionCallback = Callback;
8752 question->QuestionContext = Context;
8753 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) return(mStatus_BadParamErr);
8754
8755 return(mDNS_StartQuery_internal(m, question));
8756 }
8757
8758 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
8759 const domainname *const srv, const domainname *const domain,
8760 const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
8761 {
8762 mStatus status;
8763 mDNS_Lock(m);
8764 status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, ForceMCast, Callback, Context);
8765 mDNS_Unlock(m);
8766 return(status);
8767 }
8768
8769 mDNSlocal mDNSBool MachineHasActiveIPv6(mDNS *const m)
8770 {
8771 NetworkInterfaceInfo *intf;
8772 for (intf = m->HostInterfaces; intf; intf = intf->next)
8773 if (intf->ip.type == mDNSAddrType_IPv6) return(mDNStrue);
8774 return(mDNSfalse);
8775 }
8776
8777 mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8778 {
8779 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8780 mDNSBool PortChanged = !mDNSSameIPPort(query->info->port, answer->rdata->u.srv.port);
8781 if (!AddRecord) return;
8782 if (answer->rrtype != kDNSType_SRV) return;
8783
8784 query->info->port = answer->rdata->u.srv.port;
8785
8786 // If this is our first answer, then set the GotSRV flag and start the address query
8787 if (!query->GotSRV)
8788 {
8789 query->GotSRV = mDNStrue;
8790 query->qAv4.InterfaceID = answer->InterfaceID;
8791 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
8792 query->qAv6.InterfaceID = answer->InterfaceID;
8793 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
8794 mDNS_StartQuery(m, &query->qAv4);
8795 // Only do the AAAA query if this machine actually has IPv6 active
8796 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
8797 }
8798 // If this is not our first answer, only re-issue the address query if the target host name has changed
8799 else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
8800 !SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
8801 {
8802 mDNS_StopQuery(m, &query->qAv4);
8803 if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery(m, &query->qAv6);
8804 if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
8805 {
8806 // If we get here, it means:
8807 // 1. This is not our first SRV answer
8808 // 2. The interface ID is different, but the target host and port are the same
8809 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
8810 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
8811 query->qAv4.InterfaceID = query->qSRV.InterfaceID; // Will be mDNSInterface_Any, or a specific interface
8812 query->qAv6.InterfaceID = query->qSRV.InterfaceID;
8813 }
8814 else
8815 {
8816 query->qAv4.InterfaceID = answer->InterfaceID;
8817 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
8818 query->qAv6.InterfaceID = answer->InterfaceID;
8819 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
8820 }
8821 debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query->qAv4.qname.c, DNSTypeName(query->qAv4.qtype));
8822 mDNS_StartQuery(m, &query->qAv4);
8823 // Only do the AAAA query if this machine actually has IPv6 active
8824 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
8825 }
8826 else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
8827 {
8828 if (++query->Answers >= 100)
8829 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
8830 query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
8831 mDNSVal16(answer->rdata->u.srv.port));
8832 query->ServiceInfoQueryCallback(m, query);
8833 }
8834 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8835 // callback function is allowed to do anything, including deleting this query and freeing its memory.
8836 }
8837
8838 mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8839 {
8840 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8841 if (!AddRecord) return;
8842 if (answer->rrtype != kDNSType_TXT) return;
8843 if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
8844
8845 query->GotTXT = mDNStrue;
8846 query->info->TXTlen = answer->rdlength;
8847 query->info->TXTinfo[0] = 0; // In case answer->rdlength is zero
8848 mDNSPlatformMemCopy(query->info->TXTinfo, answer->rdata->u.txt.c, answer->rdlength);
8849
8850 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
8851
8852 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8853 // callback function is allowed to do anything, including deleting this query and freeing its memory.
8854 if (query->ServiceInfoQueryCallback && query->GotADD)
8855 {
8856 if (++query->Answers >= 100)
8857 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
8858 query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
8859 query->ServiceInfoQueryCallback(m, query);
8860 }
8861 }
8862
8863 mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8864 {
8865 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8866 //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
8867 if (!AddRecord) return;
8868
8869 if (answer->rrtype == kDNSType_A)
8870 {
8871 query->info->ip.type = mDNSAddrType_IPv4;
8872 query->info->ip.ip.v4 = answer->rdata->u.ipv4;
8873 }
8874 else if (answer->rrtype == kDNSType_AAAA)
8875 {
8876 query->info->ip.type = mDNSAddrType_IPv6;
8877 query->info->ip.ip.v6 = answer->rdata->u.ipv6;
8878 }
8879 else
8880 {
8881 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name->c, answer->rrtype, DNSTypeName(answer->rrtype));
8882 return;
8883 }
8884
8885 query->GotADD = mDNStrue;
8886 query->info->InterfaceID = answer->InterfaceID;
8887
8888 verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
8889
8890 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8891 // callback function is allowed to do anything, including deleting this query and freeing its memory.
8892 if (query->ServiceInfoQueryCallback && query->GotTXT)
8893 {
8894 if (++query->Answers >= 100)
8895 debugf(answer->rrtype == kDNSType_A ?
8896 "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
8897 "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
8898 query->Answers, query->qSRV.qname.c, &answer->rdata->u.data);
8899 query->ServiceInfoQueryCallback(m, query);
8900 }
8901 }
8902
8903 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
8904 // If the query is not interface-specific, then InterfaceID may be zero
8905 // Each time the Callback is invoked, the remainder of the fields will have been filled in
8906 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
8907 mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
8908 ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
8909 {
8910 mStatus status;
8911 mDNS_Lock(m);
8912
8913 query->qSRV.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
8914 query->qSRV.InterfaceID = info->InterfaceID;
8915 query->qSRV.Target = zeroAddr;
8916 AssignDomainName(&query->qSRV.qname, &info->name);
8917 query->qSRV.qtype = kDNSType_SRV;
8918 query->qSRV.qclass = kDNSClass_IN;
8919 query->qSRV.LongLived = mDNSfalse;
8920 query->qSRV.ExpectUnique = mDNStrue;
8921 query->qSRV.ForceMCast = mDNSfalse;
8922 query->qSRV.ReturnIntermed = mDNSfalse;
8923 query->qSRV.SuppressUnusable = mDNSfalse;
8924 query->qSRV.SearchListIndex = 0;
8925 query->qSRV.AppendSearchDomains = 0;
8926 query->qSRV.RetryWithSearchDomains = mDNSfalse;
8927 query->qSRV.TimeoutQuestion = 0;
8928 query->qSRV.WakeOnResolve = 0;
8929 query->qSRV.qnameOrig = mDNSNULL;
8930 query->qSRV.QuestionCallback = FoundServiceInfoSRV;
8931 query->qSRV.QuestionContext = query;
8932
8933 query->qTXT.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
8934 query->qTXT.InterfaceID = info->InterfaceID;
8935 query->qTXT.Target = zeroAddr;
8936 AssignDomainName(&query->qTXT.qname, &info->name);
8937 query->qTXT.qtype = kDNSType_TXT;
8938 query->qTXT.qclass = kDNSClass_IN;
8939 query->qTXT.LongLived = mDNSfalse;
8940 query->qTXT.ExpectUnique = mDNStrue;
8941 query->qTXT.ForceMCast = mDNSfalse;
8942 query->qTXT.ReturnIntermed = mDNSfalse;
8943 query->qTXT.SuppressUnusable = mDNSfalse;
8944 query->qTXT.SearchListIndex = 0;
8945 query->qTXT.AppendSearchDomains = 0;
8946 query->qTXT.RetryWithSearchDomains = mDNSfalse;
8947 query->qTXT.TimeoutQuestion = 0;
8948 query->qTXT.WakeOnResolve = 0;
8949 query->qTXT.qnameOrig = mDNSNULL;
8950 query->qTXT.QuestionCallback = FoundServiceInfoTXT;
8951 query->qTXT.QuestionContext = query;
8952
8953 query->qAv4.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
8954 query->qAv4.InterfaceID = info->InterfaceID;
8955 query->qAv4.Target = zeroAddr;
8956 query->qAv4.qname.c[0] = 0;
8957 query->qAv4.qtype = kDNSType_A;
8958 query->qAv4.qclass = kDNSClass_IN;
8959 query->qAv4.LongLived = mDNSfalse;
8960 query->qAv4.ExpectUnique = mDNStrue;
8961 query->qAv4.ForceMCast = mDNSfalse;
8962 query->qAv4.ReturnIntermed = mDNSfalse;
8963 query->qAv4.SuppressUnusable = mDNSfalse;
8964 query->qAv4.SearchListIndex = 0;
8965 query->qAv4.AppendSearchDomains = 0;
8966 query->qAv4.RetryWithSearchDomains = mDNSfalse;
8967 query->qAv4.TimeoutQuestion = 0;
8968 query->qAv4.WakeOnResolve = 0;
8969 query->qAv4.qnameOrig = mDNSNULL;
8970 query->qAv4.QuestionCallback = FoundServiceInfo;
8971 query->qAv4.QuestionContext = query;
8972
8973 query->qAv6.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
8974 query->qAv6.InterfaceID = info->InterfaceID;
8975 query->qAv6.Target = zeroAddr;
8976 query->qAv6.qname.c[0] = 0;
8977 query->qAv6.qtype = kDNSType_AAAA;
8978 query->qAv6.qclass = kDNSClass_IN;
8979 query->qAv6.LongLived = mDNSfalse;
8980 query->qAv6.ExpectUnique = mDNStrue;
8981 query->qAv6.ForceMCast = mDNSfalse;
8982 query->qAv6.ReturnIntermed = mDNSfalse;
8983 query->qAv6.SuppressUnusable = mDNSfalse;
8984 query->qAv6.SearchListIndex = 0;
8985 query->qAv6.AppendSearchDomains = 0;
8986 query->qAv6.RetryWithSearchDomains = mDNSfalse;
8987 query->qAv6.TimeoutQuestion = 0;
8988 query->qAv6.WakeOnResolve = 0;
8989 query->qAv6.qnameOrig = mDNSNULL;
8990 query->qAv6.QuestionCallback = FoundServiceInfo;
8991 query->qAv6.QuestionContext = query;
8992
8993 query->GotSRV = mDNSfalse;
8994 query->GotTXT = mDNSfalse;
8995 query->GotADD = mDNSfalse;
8996 query->Answers = 0;
8997
8998 query->info = info;
8999 query->ServiceInfoQueryCallback = Callback;
9000 query->ServiceInfoQueryContext = Context;
9001
9002 // info->name = Must already be set up by client
9003 // info->interface = Must already be set up by client
9004 info->ip = zeroAddr;
9005 info->port = zeroIPPort;
9006 info->TXTlen = 0;
9007
9008 // We use mDNS_StartQuery_internal here because we're already holding the lock
9009 status = mDNS_StartQuery_internal(m, &query->qSRV);
9010 if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
9011 if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
9012
9013 mDNS_Unlock(m);
9014 return(status);
9015 }
9016
9017 mDNSexport void mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *q)
9018 {
9019 mDNS_Lock(m);
9020 // We use mDNS_StopQuery_internal here because we're already holding the lock
9021 if (q->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qSRV);
9022 if (q->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qTXT);
9023 if (q->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv4);
9024 if (q->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv6);
9025 mDNS_Unlock(m);
9026 }
9027
9028 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
9029 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
9030 {
9031 question->InterfaceID = InterfaceID;
9032 question->Target = zeroAddr;
9033 question->qtype = kDNSType_PTR;
9034 question->qclass = kDNSClass_IN;
9035 question->LongLived = mDNSfalse;
9036 question->ExpectUnique = mDNSfalse;
9037 question->ForceMCast = mDNSfalse;
9038 question->ReturnIntermed = mDNSfalse;
9039 question->SuppressUnusable = mDNSfalse;
9040 question->SearchListIndex = 0;
9041 question->AppendSearchDomains = 0;
9042 question->RetryWithSearchDomains = mDNSfalse;
9043 question->TimeoutQuestion = 0;
9044 question->WakeOnResolve = 0;
9045 question->qnameOrig = mDNSNULL;
9046 question->QuestionCallback = Callback;
9047 question->QuestionContext = Context;
9048 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
9049 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
9050 if (!dom) dom = &localdomain;
9051 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
9052 return(mDNS_StartQuery(m, question));
9053 }
9054
9055 // ***************************************************************************
9056 #if COMPILER_LIKES_PRAGMA_MARK
9057 #pragma mark -
9058 #pragma mark - Responder Functions
9059 #endif
9060
9061 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
9062 {
9063 mStatus status;
9064 mDNS_Lock(m);
9065 status = mDNS_Register_internal(m, rr);
9066 mDNS_Unlock(m);
9067 return(status);
9068 }
9069
9070 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
9071 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
9072 {
9073 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
9074 {
9075 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
9076 return(mStatus_Invalid);
9077 }
9078
9079 mDNS_Lock(m);
9080
9081 // If TTL is unspecified, leave TTL unchanged
9082 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
9083
9084 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
9085 if (rr->NewRData)
9086 {
9087 RData *n = rr->NewRData;
9088 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
9089 if (rr->UpdateCallback)
9090 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
9091 }
9092
9093 rr->NewRData = newrdata;
9094 rr->newrdlength = newrdlength;
9095 rr->UpdateCallback = Callback;
9096
9097 #ifndef UNICAST_DISABLED
9098 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
9099 {
9100 mStatus status = uDNS_UpdateRecord(m, rr);
9101 // The caller frees the memory on error, don't retain stale pointers
9102 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
9103 mDNS_Unlock(m);
9104 return(status);
9105 }
9106 #endif
9107
9108 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
9109 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
9110 CompleteRDataUpdate(m, rr);
9111 else
9112 {
9113 rr->AnnounceCount = InitialAnnounceCount;
9114 InitializeLastAPTime(m, rr);
9115 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
9116 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
9117 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
9118 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
9119 if (rr->UpdateCredits <= 5)
9120 {
9121 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
9122 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
9123 rr->ThisAPInterval *= 4;
9124 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
9125 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
9126 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
9127 }
9128 rr->resrec.rroriginalttl = newttl;
9129 }
9130
9131 mDNS_Unlock(m);
9132 return(mStatus_NoError);
9133 }
9134
9135 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
9136 // the record list and/or question list.
9137 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9138 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
9139 {
9140 mStatus status;
9141 mDNS_Lock(m);
9142 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9143 mDNS_Unlock(m);
9144 return(status);
9145 }
9146
9147 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
9148 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
9149
9150 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
9151 {
9152 NetworkInterfaceInfo *intf;
9153 for (intf = m->HostInterfaces; intf; intf = intf->next)
9154 if (intf->Advertise) break;
9155 return(intf);
9156 }
9157
9158 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
9159 {
9160 char buffer[MAX_REVERSE_MAPPING_NAME];
9161 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
9162 if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
9163
9164 // Send dynamic update for non-linklocal IPv4 Addresses
9165 mDNS_SetupResourceRecord(&set->RR_A, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNS_HostNameCallback, set);
9166 mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
9167 mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
9168
9169 #if ANSWER_REMOTE_HOSTNAME_QUERIES
9170 set->RR_A .AllowRemoteQuery = mDNStrue;
9171 set->RR_PTR .AllowRemoteQuery = mDNStrue;
9172 set->RR_HINFO.AllowRemoteQuery = mDNStrue;
9173 #endif
9174 // 1. Set up Address record to map from host name ("foo.local.") to IP address
9175 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
9176 AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
9177 if (set->ip.type == mDNSAddrType_IPv4)
9178 {
9179 set->RR_A.resrec.rrtype = kDNSType_A;
9180 set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
9181 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
9182 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
9183 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
9184 }
9185 else if (set->ip.type == mDNSAddrType_IPv6)
9186 {
9187 int i;
9188 set->RR_A.resrec.rrtype = kDNSType_AAAA;
9189 set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
9190 for (i = 0; i < 16; i++)
9191 {
9192 static const char hexValues[] = "0123456789ABCDEF";
9193 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
9194 buffer[i * 4 + 1] = '.';
9195 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
9196 buffer[i * 4 + 3] = '.';
9197 }
9198 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
9199 }
9200
9201 MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
9202 set->RR_PTR.AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
9203 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
9204
9205 set->RR_A.RRSet = &primary->RR_A; // May refer to self
9206
9207 mDNS_Register_internal(m, &set->RR_A);
9208 mDNS_Register_internal(m, &set->RR_PTR);
9209
9210 if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
9211 {
9212 mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
9213 AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
9214 set->RR_HINFO.DependentOn = &set->RR_A;
9215 mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
9216 p += 1 + (int)p[0];
9217 mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
9218 mDNS_Register_internal(m, &set->RR_HINFO);
9219 }
9220 else
9221 {
9222 debugf("Not creating HINFO record: platform support layer provided no information");
9223 set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
9224 }
9225 }
9226
9227 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
9228 {
9229 NetworkInterfaceInfo *intf;
9230
9231 // If we still have address records referring to this one, update them
9232 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
9233 AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
9234 for (intf = m->HostInterfaces; intf; intf = intf->next)
9235 if (intf->RR_A.RRSet == &set->RR_A)
9236 intf->RR_A.RRSet = A;
9237
9238 // Unregister these records.
9239 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
9240 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
9241 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
9242 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
9243 if (set->RR_A. resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
9244 if (set->RR_PTR. resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
9245 if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
9246 }
9247
9248 mDNSexport void mDNS_SetFQDN(mDNS *const m)
9249 {
9250 domainname newmname;
9251 NetworkInterfaceInfo *intf;
9252 AuthRecord *rr;
9253 newmname.c[0] = 0;
9254
9255 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
9256 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
9257
9258 mDNS_Lock(m);
9259
9260 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
9261 else
9262 {
9263 AssignDomainName(&m->MulticastHostname, &newmname);
9264
9265 // 1. Stop advertising our address records on all interfaces
9266 for (intf = m->HostInterfaces; intf; intf = intf->next)
9267 if (intf->Advertise) DeadvertiseInterface(m, intf);
9268
9269 // 2. Start advertising our address records using the new name
9270 for (intf = m->HostInterfaces; intf; intf = intf->next)
9271 if (intf->Advertise) AdvertiseInterface(m, intf);
9272 }
9273
9274 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
9275 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
9276 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
9277
9278 mDNS_Unlock(m);
9279 }
9280
9281 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9282 {
9283 (void)rr; // Unused parameter
9284
9285 #if MDNS_DEBUGMSGS
9286 {
9287 char *msg = "Unknown result";
9288 if (result == mStatus_NoError) msg = "Name registered";
9289 else if (result == mStatus_NameConflict) msg = "Name conflict";
9290 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
9291 }
9292 #endif
9293
9294 if (result == mStatus_NoError)
9295 {
9296 // Notify the client that the host name is successfully registered
9297 if (m->MainCallback)
9298 m->MainCallback(m, mStatus_NoError);
9299 }
9300 else if (result == mStatus_NameConflict)
9301 {
9302 domainlabel oldlabel = m->hostlabel;
9303
9304 // 1. First give the client callback a chance to pick a new name
9305 if (m->MainCallback)
9306 m->MainCallback(m, mStatus_NameConflict);
9307
9308 // 2. If the client callback didn't do it, add (or increment) an index ourselves
9309 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
9310 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
9311 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
9312 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
9313
9314 // 3. Generate the FQDNs from the hostlabel,
9315 // and make sure all SRV records, etc., are updated to reference our new hostname
9316 mDNS_SetFQDN(m);
9317 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
9318 }
9319 else if (result == mStatus_MemFree)
9320 {
9321 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
9322 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
9323 debugf("mDNS_HostNameCallback: MemFree (ignored)");
9324 }
9325 else
9326 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c);
9327 }
9328
9329 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
9330 {
9331 NetworkInterfaceInfo *intf;
9332 active->IPv4Available = mDNSfalse;
9333 active->IPv6Available = mDNSfalse;
9334 for (intf = m->HostInterfaces; intf; intf = intf->next)
9335 if (intf->InterfaceID == active->InterfaceID)
9336 {
9337 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
9338 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
9339 }
9340 }
9341
9342 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
9343 {
9344 AuthRecord *rr;
9345 LogInfo("RestartRecordGetZoneData: ResourceRecords");
9346 for (rr = m->ResourceRecords; rr; rr=rr->next)
9347 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
9348 {
9349 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
9350 // Zero out the updateid so that if we have a pending response from the server, it won't
9351 // be accepted as a valid response. If we accept the response, we might free the new "nta"
9352 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
9353 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
9354 }
9355 }
9356
9357 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
9358 {
9359 int i;
9360 set->NetWakeBrowse.ThisQInterval = -1;
9361 for (i=0; i<3; i++)
9362 {
9363 set->NetWakeResolve[i].ThisQInterval = -1;
9364 set->SPSAddr[i].type = mDNSAddrType_None;
9365 }
9366 set->NextSPSAttempt = -1;
9367 set->NextSPSAttemptTime = m->timenow;
9368 }
9369
9370 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
9371 {
9372 NetworkInterfaceInfo *p = m->HostInterfaces;
9373 while (p && p != set) p=p->next;
9374 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
9375
9376 if (set->InterfaceActive)
9377 {
9378 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
9379 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, mDNSfalse, m->SPSBrowseCallback, set);
9380 }
9381 }
9382
9383 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
9384 {
9385 NetworkInterfaceInfo *p = m->HostInterfaces;
9386 while (p && p != set) p=p->next;
9387 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
9388
9389 if (set->NetWakeBrowse.ThisQInterval >= 0)
9390 {
9391 int i;
9392 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
9393
9394 // Stop our browse and resolve operations
9395 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
9396 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
9397
9398 // Make special call to the browse callback to let it know it can to remove all records for this interface
9399 if (m->SPSBrowseCallback)
9400 {
9401 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
9402 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
9403 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
9404 }
9405
9406 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
9407 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
9408 InitializeNetWakeState(m, set);
9409 }
9410 }
9411
9412 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
9413 {
9414 AuthRecord *rr;
9415 mDNSBool FirstOfType = mDNStrue;
9416 NetworkInterfaceInfo **p = &m->HostInterfaces;
9417
9418 if (!set->InterfaceID)
9419 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
9420
9421 if (!mDNSAddressIsValidNonZero(&set->mask))
9422 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
9423
9424 mDNS_Lock(m);
9425
9426 // Assume this interface will be active now, unless we find a duplicate already in the list
9427 set->InterfaceActive = mDNStrue;
9428 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
9429 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
9430
9431 InitializeNetWakeState(m, set);
9432
9433 // Scan list to see if this InterfaceID is already represented
9434 while (*p)
9435 {
9436 if (*p == set)
9437 {
9438 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
9439 mDNS_Unlock(m);
9440 return(mStatus_AlreadyRegistered);
9441 }
9442
9443 if ((*p)->InterfaceID == set->InterfaceID)
9444 {
9445 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
9446 set->InterfaceActive = mDNSfalse;
9447 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
9448 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
9449 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
9450 }
9451
9452 p=&(*p)->next;
9453 }
9454
9455 set->next = mDNSNULL;
9456 *p = set;
9457
9458 if (set->Advertise)
9459 AdvertiseInterface(m, set);
9460
9461 LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set->InterfaceID, set->ifname, &set->ip,
9462 set->InterfaceActive ?
9463 "not represented in list; marking active and retriggering queries" :
9464 "already represented in list; marking inactive for now");
9465
9466 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
9467
9468 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
9469 // giving the false impression that there's an active representative of this interface when there really isn't.
9470 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
9471 // even if we believe that we previously had an active representative of this interface.
9472 if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
9473 {
9474 DNSQuestion *q;
9475 // Normally, after an interface comes up, we pause half a second before beginning probing.
9476 // This is to guard against cases where there's rapid interface changes, where we could be confused by
9477 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
9478 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
9479 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
9480 // and think it's a conflicting answer to our probe.
9481 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
9482 const mDNSs32 probedelay = flapping ? mDNSPlatformOneSecond * 5 : mDNSPlatformOneSecond / 2;
9483 const mDNSu8 numannounce = flapping ? (mDNSu8)1 : InitialAnnounceCount;
9484
9485 // Use a small amount of randomness:
9486 // In the case of a network administrator turning on an Ethernet hub so that all the
9487 // connected machines establish link at exactly the same time, we don't want them all
9488 // to go and hit the network with identical queries at exactly the same moment.
9489 // We set a random delay of up to InitialQuestionInterval (1/3 second).
9490 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
9491 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
9492 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
9493 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
9494 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
9495 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
9496
9497 if (flapping) LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
9498
9499 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
9500 if (m->SuppressProbes == 0 ||
9501 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
9502 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
9503
9504 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
9505 // it here also handles the wake up case as the network link comes UP after waking causing
9506 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
9507 // that the network link comes UP after 60 seconds and we never set the OWNER option
9508 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
9509 LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
9510
9511 for (q = m->Questions; q; q=q->next) // Scan our list of questions
9512 if (mDNSOpaque16IsZero(q->TargetQID))
9513 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
9514 { // then reactivate this question
9515 // If flapping, delay between first and second queries is nine seconds instead of one second
9516 mDNSBool dodelay = flapping && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
9517 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
9518 mDNSs32 qdelay = dodelay ? mDNSPlatformOneSecond * 5 : 0;
9519 if (dodelay) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q->qname.c, DNSTypeName(q->qtype));
9520
9521 if (!q->ThisQInterval || q->ThisQInterval > initial)
9522 {
9523 q->ThisQInterval = initial;
9524 q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
9525 }
9526 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
9527 q->RecentAnswerPkts = 0;
9528 SetNextQueryTime(m,q);
9529 }
9530
9531 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
9532 // we now need them to re-probe if necessary, and then re-announce.
9533 for (rr = m->ResourceRecords; rr; rr=rr->next)
9534 if (!AuthRecord_uDNS(rr))
9535 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
9536 {
9537 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
9538 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
9539 if (rr->AnnounceCount < numannounce) rr->AnnounceCount = numannounce;
9540 rr->SendNSECNow = mDNSNULL;
9541 InitializeLastAPTime(m, rr);
9542 }
9543 }
9544
9545 RestartRecordGetZoneData(m);
9546
9547 CheckSuppressUnusableQuestions(m);
9548
9549 mDNS_UpdateAllowSleep(m);
9550
9551 mDNS_Unlock(m);
9552 return(mStatus_NoError);
9553 }
9554
9555 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
9556 // the record list and/or question list.
9557 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9558 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
9559 {
9560 NetworkInterfaceInfo **p = &m->HostInterfaces;
9561 mDNSBool revalidate = mDNSfalse;
9562
9563 mDNS_Lock(m);
9564
9565 // Find this record in our list
9566 while (*p && *p != set) p=&(*p)->next;
9567 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
9568
9569 mDNS_DeactivateNetWake_internal(m, set);
9570
9571 // Unlink this record from our list
9572 *p = (*p)->next;
9573 set->next = mDNSNULL;
9574
9575 if (!set->InterfaceActive)
9576 {
9577 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
9578 NetworkInterfaceInfo *intf;
9579 for (intf = m->HostInterfaces; intf; intf = intf->next)
9580 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
9581 UpdateInterfaceProtocols(m, intf);
9582 }
9583 else
9584 {
9585 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, set->InterfaceID);
9586 if (intf)
9587 {
9588 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
9589 " making it active", set->InterfaceID, set->ifname, &set->ip);
9590 if (intf->InterfaceActive)
9591 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
9592 intf->InterfaceActive = mDNStrue;
9593 UpdateInterfaceProtocols(m, intf);
9594
9595 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
9596
9597 // See if another representative *of the same type* exists. If not, we mave have gone from
9598 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
9599 for (intf = m->HostInterfaces; intf; intf = intf->next)
9600 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
9601 break;
9602 if (!intf) revalidate = mDNStrue;
9603 }
9604 else
9605 {
9606 mDNSu32 slot;
9607 CacheGroup *cg;
9608 CacheRecord *rr;
9609 DNSQuestion *q;
9610 DNSServer *s;
9611
9612 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
9613 " marking questions etc. dormant", set->InterfaceID, set->ifname, &set->ip);
9614
9615 if (set->McastTxRx && flapping)
9616 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
9617
9618 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
9619 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
9620 for (q = m->Questions; q; q=q->next)
9621 {
9622 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
9623 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
9624 {
9625 q->FlappingInterface2 = q->FlappingInterface1;
9626 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
9627 }
9628 }
9629
9630 // 2. Flush any cache records received on this interface
9631 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
9632 FORALL_CACHERECORDS(slot, cg, rr)
9633 if (rr->resrec.InterfaceID == set->InterfaceID)
9634 {
9635 // If this interface is deemed flapping,
9636 // postpone deleting the cache records in case the interface comes back again
9637 if (set->McastTxRx && flapping)
9638 {
9639 // For a flapping interface we want these record to go away after 30 seconds
9640 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
9641 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
9642 // if the interface does come back, any relevant questions will be reactivated anyway
9643 rr->UnansweredQueries = MaxUnansweredQueries;
9644 }
9645 else
9646 mDNS_PurgeCacheResourceRecord(m, rr);
9647 }
9648
9649 // 3. Any DNS servers specific to this interface are now unusable
9650 for (s = m->DNSServers; s; s = s->next)
9651 if (s->interface == set->InterfaceID)
9652 {
9653 s->interface = mDNSInterface_Any;
9654 s->teststate = DNSServer_Disabled;
9655 }
9656 }
9657 }
9658
9659 // If we were advertising on this interface, deregister those address and reverse-lookup records now
9660 if (set->Advertise) DeadvertiseInterface(m, set);
9661
9662 // If we have any cache records received on this interface that went away, then re-verify them.
9663 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
9664 // giving the false impression that there's an active representative of this interface when there really isn't.
9665 // Don't need to do this when shutting down, because *all* interfaces are about to go away
9666 if (revalidate && !m->ShutdownTime)
9667 {
9668 mDNSu32 slot;
9669 CacheGroup *cg;
9670 CacheRecord *rr;
9671 FORALL_CACHERECORDS(slot, cg, rr)
9672 if (rr->resrec.InterfaceID == set->InterfaceID)
9673 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
9674 }
9675
9676 CheckSuppressUnusableQuestions(m);
9677
9678 mDNS_UpdateAllowSleep(m);
9679
9680 mDNS_Unlock(m);
9681 }
9682
9683 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9684 {
9685 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
9686 (void)m; // Unused parameter
9687
9688 #if MDNS_DEBUGMSGS
9689 {
9690 char *msg = "Unknown result";
9691 if (result == mStatus_NoError) msg = "Name Registered";
9692 else if (result == mStatus_NameConflict) msg = "Name Conflict";
9693 else if (result == mStatus_MemFree) msg = "Memory Free";
9694 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
9695 }
9696 #endif
9697
9698 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
9699 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
9700
9701 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
9702 if (result == mStatus_NameConflict)
9703 {
9704 sr->Conflict = mDNStrue; // Record that this service set had a conflict
9705 mDNS_DeregisterService(m, sr); // Unlink the records from our list
9706 return;
9707 }
9708
9709 if (result == mStatus_MemFree)
9710 {
9711 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
9712 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
9713 // every record is finished cleaning up.
9714 mDNSu32 i;
9715 ExtraResourceRecord *e = sr->Extras;
9716
9717 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9718 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9719 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9720 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9721 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
9722
9723 while (e)
9724 {
9725 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9726 e = e->next;
9727 }
9728
9729 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
9730 // then we can now report the NameConflict to the client
9731 if (sr->Conflict) result = mStatus_NameConflict;
9732
9733 }
9734
9735 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered": "Registered"), sr->RR_PTR.resrec.name->c);
9736 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
9737 // function is allowed to do anything, including deregistering this service and freeing its memory.
9738 if (sr->ServiceCallback)
9739 sr->ServiceCallback(m, sr, result);
9740 }
9741
9742 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9743 {
9744 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
9745 if (sr->ServiceCallback)
9746 sr->ServiceCallback(m, sr, result);
9747 }
9748
9749 // Note:
9750 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
9751 // Type is service type (e.g. "_ipp._tcp.")
9752 // Domain is fully qualified domain name (i.e. ending with a null label)
9753 // We always register a TXT, even if it is empty (so that clients are not
9754 // left waiting forever looking for a nonexistent record.)
9755 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
9756 // then the default host name (m->MulticastHostname) is automatically used
9757 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
9758 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
9759 const domainlabel *const name, const domainname *const type, const domainname *const domain,
9760 const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
9761 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
9762 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
9763 {
9764 mStatus err;
9765 mDNSu32 i;
9766 mDNSu32 hostTTL;
9767 AuthRecType artype;
9768 mDNSu8 recordType = (flags & regFlagKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
9769
9770 sr->ServiceCallback = Callback;
9771 sr->ServiceContext = Context;
9772 sr->Conflict = mDNSfalse;
9773
9774 sr->Extras = mDNSNULL;
9775 sr->NumSubTypes = NumSubTypes;
9776 sr->SubTypes = SubTypes;
9777
9778 if (InterfaceID == mDNSInterface_LocalOnly)
9779 artype = AuthRecordLocalOnly;
9780 else if (InterfaceID == mDNSInterface_P2P)
9781 artype = AuthRecordP2P;
9782 else if ((InterfaceID == mDNSInterface_Any) && (flags & regFlagIncludeP2P))
9783 artype = AuthRecordAnyIncludeP2P;
9784 else
9785 artype = AuthRecordAny;
9786
9787 // Initialize the AuthRecord objects to sane values
9788 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
9789 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
9790 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
9791
9792 if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
9793 hostTTL = kHostNameSmallTTL;
9794 else
9795 hostTTL = kHostNameTTL;
9796
9797 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
9798 mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
9799
9800 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
9801 if (mDNSIPPortIsZero(port))
9802 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, (flags & regFlagIncludeP2P)));
9803
9804 // If the client is registering an oversized TXT record,
9805 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
9806 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
9807 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
9808
9809 // Set up the record names
9810 // For now we only create an advisory record for the main type, not for subtypes
9811 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
9812 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
9813 return(mStatus_BadParamErr);
9814 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
9815 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
9816 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
9817
9818 // 1. Set up the ADV record rdata to advertise our service type
9819 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
9820
9821 // 2. Set up the PTR record rdata to point to our service name
9822 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
9823 // Note: uDNS registration code assumes that Additional1 points to the SRV record
9824 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
9825 sr->RR_PTR.Additional1 = &sr->RR_SRV;
9826 sr->RR_PTR.Additional2 = &sr->RR_TXT;
9827
9828 // 2a. Set up any subtype PTRs to point to our service name
9829 // If the client is using subtypes, it is the client's responsibility to have
9830 // already set the first label of the record name to the subtype being registered
9831 for (i=0; i<NumSubTypes; i++)
9832 {
9833 domainname st;
9834 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
9835 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
9836 AppendDomainName(&st, type);
9837 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
9838 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
9839 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
9840 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
9841 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
9842 }
9843
9844 // 3. Set up the SRV record rdata.
9845 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
9846 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
9847 sr->RR_SRV.resrec.rdata->u.srv.port = port;
9848
9849 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
9850 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
9851 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
9852
9853 // 4. Set up the TXT record rdata,
9854 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
9855 // Note: uDNS registration code assumes that DependentOn points to the SRV record
9856 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
9857 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
9858 {
9859 sr->RR_TXT.resrec.rdlength = txtlen;
9860 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
9861 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
9862 }
9863 sr->RR_TXT.DependentOn = &sr->RR_SRV;
9864
9865 mDNS_Lock(m);
9866 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
9867 // that if the SRV cannot find a target, rest of the records that belong to this service
9868 // will not be activated.
9869 err = mDNS_Register_internal(m, &sr->RR_SRV);
9870 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
9871 // any list and hence no need to deregister. We could probably do similar checks for other
9872 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
9873 if (err)
9874 {
9875 mDNS_Unlock(m);
9876 return err;
9877 }
9878 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
9879 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
9880 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
9881 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
9882 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
9883 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
9884 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
9885 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
9886 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
9887
9888 mDNS_Unlock(m);
9889
9890 if (err) mDNS_DeregisterService(m, sr);
9891 return(err);
9892 }
9893
9894 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
9895 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 includeP2P)
9896 {
9897 ExtraResourceRecord **e;
9898 mStatus status;
9899 AuthRecType artype;
9900 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
9901
9902 if (InterfaceID == mDNSInterface_LocalOnly)
9903 artype = AuthRecordLocalOnly;
9904 if (InterfaceID == mDNSInterface_P2P)
9905 artype = AuthRecordP2P;
9906 else if ((InterfaceID == mDNSInterface_Any) && includeP2P)
9907 artype = AuthRecordAnyIncludeP2P;
9908 else
9909 artype = AuthRecordAny;
9910
9911 extra->next = mDNSNULL;
9912 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
9913 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
9914 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
9915
9916 mDNS_Lock(m);
9917 e = &sr->Extras;
9918 while (*e) e = &(*e)->next;
9919
9920 if (ttl == 0) ttl = kStandardTTL;
9921
9922 extra->r.DependentOn = &sr->RR_SRV;
9923
9924 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
9925 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
9926
9927 status = mDNS_Register_internal(m, &extra->r);
9928 if (status == mStatus_NoError) *e = extra;
9929
9930 mDNS_Unlock(m);
9931 return(status);
9932 }
9933
9934 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
9935 mDNSRecordCallback MemFreeCallback, void *Context)
9936 {
9937 ExtraResourceRecord **e;
9938 mStatus status;
9939
9940 mDNS_Lock(m);
9941 e = &sr->Extras;
9942 while (*e && *e != extra) e = &(*e)->next;
9943 if (!*e)
9944 {
9945 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
9946 status = mStatus_BadReferenceErr;
9947 }
9948 else
9949 {
9950 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
9951 extra->r.RecordCallback = MemFreeCallback;
9952 extra->r.RecordContext = Context;
9953 *e = (*e)->next;
9954 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
9955 }
9956 mDNS_Unlock(m);
9957 return(status);
9958 }
9959
9960 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
9961 {
9962 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
9963 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
9964 domainlabel name1, name2;
9965 domainname type, domain;
9966 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
9967 ExtraResourceRecord *extras = sr->Extras;
9968 mStatus err;
9969
9970 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
9971 if (!newname)
9972 {
9973 name2 = name1;
9974 IncrementLabelSuffix(&name2, mDNStrue);
9975 newname = &name2;
9976 }
9977
9978 if (SameDomainName(&domain, &localdomain))
9979 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
9980 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
9981
9982 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
9983 host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
9984 sr->SubTypes, sr->NumSubTypes,
9985 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, 0);
9986
9987 // mDNS_RegisterService() just reset sr->Extras to NULL.
9988 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
9989 // through the old list of extra records, and re-add them to our freshly created service registration
9990 while (!err && extras)
9991 {
9992 ExtraResourceRecord *e = extras;
9993 extras = extras->next;
9994 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
9995 }
9996
9997 return(err);
9998 }
9999
10000 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
10001 // which may change the record list and/or question list.
10002 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
10003 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
10004 {
10005 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
10006 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
10007
10008 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
10009 {
10010 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
10011 return(mStatus_BadReferenceErr);
10012 }
10013 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
10014 {
10015 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
10016 // Avoid race condition:
10017 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
10018 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
10019 // If the client happens to deregister the service in the middle of that process, then
10020 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
10021 // instead of incorrectly promoting it to mStatus_NameConflict.
10022 // This race condition is exposed particularly when the conformance test generates
10023 // a whole batch of simultaneous conflicts across a range of services all advertised
10024 // using the same system default name, and if we don't take this precaution then
10025 // we end up incrementing m->nicelabel multiple times instead of just once.
10026 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
10027 sr->Conflict = mDNSfalse;
10028 return(mStatus_NoError);
10029 }
10030 else
10031 {
10032 mDNSu32 i;
10033 mStatus status;
10034 ExtraResourceRecord *e;
10035 mDNS_Lock(m);
10036 e = sr->Extras;
10037
10038 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
10039 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
10040 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
10041 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
10042
10043 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
10044
10045 // We deregister all of the extra records, but we leave the sr->Extras list intact
10046 // in case the client wants to do a RenameAndReregister and reinstate the registration
10047 while (e)
10048 {
10049 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
10050 e = e->next;
10051 }
10052
10053 for (i=0; i<sr->NumSubTypes; i++)
10054 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
10055
10056 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
10057 mDNS_Unlock(m);
10058 return(status);
10059 }
10060 }
10061
10062 // Create a registration that asserts that no such service exists with this name.
10063 // This can be useful where there is a given function is available through several protocols.
10064 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
10065 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
10066 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
10067 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
10068 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
10069 const domainlabel *const name, const domainname *const type, const domainname *const domain,
10070 const domainname *const host,
10071 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSBool includeP2P)
10072 {
10073 AuthRecType artype;
10074
10075 if (InterfaceID == mDNSInterface_LocalOnly)
10076 artype = AuthRecordLocalOnly;
10077 else if (InterfaceID == mDNSInterface_P2P)
10078 artype = AuthRecordP2P;
10079 else if ((InterfaceID == mDNSInterface_Any) && includeP2P)
10080 artype = AuthRecordAnyIncludeP2P;
10081 else
10082 artype = AuthRecordAny;
10083
10084 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
10085 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
10086 rr->resrec.rdata->u.srv.priority = 0;
10087 rr->resrec.rdata->u.srv.weight = 0;
10088 rr->resrec.rdata->u.srv.port = zeroIPPort;
10089 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
10090 else rr->AutoTarget = Target_AutoHost;
10091 return(mDNS_Register(m, rr));
10092 }
10093
10094 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
10095 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
10096 {
10097 AuthRecType artype;
10098
10099 if (InterfaceID == mDNSInterface_LocalOnly)
10100 artype = AuthRecordLocalOnly;
10101 else if (InterfaceID == mDNSInterface_P2P)
10102 artype = AuthRecordP2P;
10103 else
10104 artype = AuthRecordAny;
10105 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
10106 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
10107 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
10108 return(mDNS_Register(m, rr));
10109 }
10110
10111 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
10112 {
10113 AuthRecord *r;
10114 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
10115 return mDNSfalse;
10116 }
10117
10118 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
10119 {
10120 DNSQuestion *q;
10121 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
10122 return mDNSfalse;
10123 }
10124
10125 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
10126 {
10127 mDNSOpaque16 id;
10128 int i;
10129
10130 for (i=0; i<10; i++)
10131 {
10132 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
10133 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
10134 }
10135
10136 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
10137
10138 return id;
10139 }
10140
10141 // ***************************************************************************
10142 #if COMPILER_LIKES_PRAGMA_MARK
10143 #pragma mark -
10144 #pragma mark - Sleep Proxy Server
10145 #endif
10146
10147 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
10148 {
10149 // If we see an ARP from a machine we think is sleeping, then either
10150 // (i) the machine has woken, or
10151 // (ii) it's just a stray old packet from before the machine slept
10152 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
10153 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
10154 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
10155 // 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*
10156 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
10157 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
10158
10159 rr->resrec.RecordType = kDNSRecordTypeUnique;
10160 rr->ProbeCount = DefaultProbeCountForTypeUnique;
10161
10162 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
10163 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
10164 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
10165 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
10166 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
10167 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
10168 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
10169 InitializeLastAPTime(m, rr);
10170 else
10171 {
10172 rr->AnnounceCount = InitialAnnounceCount;
10173 rr->ThisAPInterval = mDNSPlatformOneSecond;
10174 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
10175 SetNextAnnounceProbeTime(m, rr);
10176 }
10177 }
10178
10179 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
10180 {
10181 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
10182 AuthRecord *rr;
10183 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
10184 if (!intf) return;
10185
10186 mDNS_Lock(m);
10187
10188 // Pass 1:
10189 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
10190 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
10191 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
10192 // The times we might need to react to an ARP Announcement are:
10193 // (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
10194 // (ii) if it's a conflicting Announcement from another host
10195 // -- and we check for these in Pass 2 below.
10196 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
10197 {
10198 for (rr = m->ResourceRecords; rr; rr=rr->next)
10199 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10200 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
10201 {
10202 static const char msg1[] = "ARP Req from owner -- re-probing";
10203 static const char msg2[] = "Ignoring ARP Request from ";
10204 static const char msg3[] = "Creating Local ARP Cache entry ";
10205 static const char msg4[] = "Answering ARP Request from ";
10206 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
10207 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
10208 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
10209 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
10210 intf->ifname, msg, &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10211 if (msg == msg1) RestartARPProbing(m, rr);
10212 else if (msg == msg3) mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
10213 else if (msg == msg4) SendARP(m, 2, rr, &arp->tpa, &arp->sha, &arp->spa, &arp->sha);
10214 }
10215 }
10216
10217 // Pass 2:
10218 // 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.
10219 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
10220 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
10221 // 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.
10222 // If we see an apparently conflicting ARP, we check the sender hardware address:
10223 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
10224 // 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.
10225 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
10226 debugf("ARP from self for %.4a", &arp->tpa);
10227 else
10228 {
10229 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
10230 for (rr = m->ResourceRecords; rr; rr=rr->next)
10231 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10232 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa))
10233 {
10234 RestartARPProbing(m, rr);
10235 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
10236 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
10237 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
10238 &arp->sha, &arp->spa, &arp->tpa, ARDisplayString(m, rr));
10239 else
10240 {
10241 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
10242 &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10243 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10244 }
10245 }
10246 }
10247
10248 mDNS_Unlock(m);
10249 }
10250
10251 /*
10252 // Option 1 is Source Link Layer Address Option
10253 // Option 2 is Target Link Layer Address Option
10254 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
10255 {
10256 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
10257 while (options < end)
10258 {
10259 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
10260 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
10261 options += options[1] * 8;
10262 }
10263 return mDNSNULL;
10264 }
10265 */
10266
10267 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
10268 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
10269 {
10270 AuthRecord *rr;
10271 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
10272 if (!intf) return;
10273
10274 mDNS_Lock(m);
10275
10276 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
10277 if (ndp->type == NDP_Sol)
10278 {
10279 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
10280 (void)end;
10281 for (rr = m->ResourceRecords; rr; rr=rr->next)
10282 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10283 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
10284 {
10285 static const char msg1[] = "NDP Req from owner -- re-probing";
10286 static const char msg2[] = "Ignoring NDP Request from ";
10287 static const char msg3[] = "Creating Local NDP Cache entry ";
10288 static const char msg4[] = "Answering NDP Request from ";
10289 static const char msg5[] = "Answering NDP Probe from ";
10290 const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
10291 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
10292 sha && mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
10293 spa && mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
10294 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
10295 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10296 if (msg == msg1) RestartARPProbing(m, rr);
10297 else if (msg == msg3)
10298 {
10299 if (!(m->KnownBugs & mDNS_KnownBug_LimitedIPv6))
10300 mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
10301 }
10302 else if (msg == msg4) SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha );
10303 else if (msg == msg5) SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
10304 }
10305 }
10306
10307 // 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.
10308 if (mDNSSameEthAddress(sha, &intf->MAC))
10309 debugf("NDP from self for %.16a", &ndp->target);
10310 else
10311 {
10312 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
10313 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
10314 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
10315 // Hence it is the NDP target address we care about, not the actual packet source address.
10316 if (ndp->type == NDP_Adv) spa = &ndp->target;
10317 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
10318 for (rr = m->ResourceRecords; rr; rr=rr->next)
10319 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10320 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa))
10321 {
10322 RestartARPProbing(m, rr);
10323 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
10324 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
10325 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
10326 else
10327 {
10328 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
10329 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10330 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10331 }
10332 }
10333 }
10334
10335 mDNS_Unlock(m);
10336 }
10337
10338 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
10339 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
10340 {
10341 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
10342 mDNSBool wake = mDNSfalse;
10343
10344 switch (protocol)
10345 {
10346 #define XX wake ? "Received" : "Ignoring", end-p
10347 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
10348 break;
10349
10350 case 0x06: {
10351 #define SSH_AsNumber 22
10352 static const mDNSIPPort SSH = { { SSH_AsNumber >> 8, SSH_AsNumber & 0xFF } };
10353
10354 // Plan to wake if
10355 // (a) RST is not set, AND
10356 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
10357 wake = (!(t->tcp.flags & 4) && (t->tcp.flags & 3) != 1);
10358
10359 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
10360 // except for ssh connections, where we'll wake for plain data packets too
10361 if (!mDNSSameIPPort(port, SSH) && !(t->tcp.flags & 2)) wake = mDNSfalse;
10362
10363 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
10364 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
10365 (t->tcp.flags & 2) ? " SYN" : "",
10366 (t->tcp.flags & 1) ? " FIN" : "",
10367 (t->tcp.flags & 4) ? " RST" : "");
10368 }
10369 break;
10370
10371 case 0x11: {
10372 #define ARD_AsNumber 3283
10373 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
10374 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
10375 if (udplen >= sizeof(UDPHeader))
10376 {
10377 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
10378 wake = mDNStrue;
10379
10380 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
10381 if (mDNSSameIPPort(port, IPSECPort))
10382 {
10383 // Specifically ignore NAT keepalive packets
10384 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
10385 else
10386 {
10387 // Skip over the Non-ESP Marker if present
10388 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
10389 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
10390 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
10391 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
10392 if ((ike->Version & 0x10) == 0x10)
10393 {
10394 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
10395 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
10396 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
10397 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
10398 }
10399 }
10400 }
10401
10402 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
10403 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
10404 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
10405 // UDP header (8 bytes)
10406 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
10407 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
10408
10409 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
10410 }
10411 }
10412 break;
10413
10414 case 0x3A: if (&t->bytes[len] <= end)
10415 {
10416 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
10417 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
10418 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
10419 }
10420 break;
10421
10422 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
10423 break;
10424 }
10425
10426 if (wake)
10427 {
10428 AuthRecord *rr, *r2;
10429
10430 mDNS_Lock(m);
10431 for (rr = m->ResourceRecords; rr; rr=rr->next)
10432 if (rr->resrec.InterfaceID == InterfaceID &&
10433 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10434 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
10435 {
10436 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
10437 for (r2 = m->ResourceRecords; r2; r2=r2->next)
10438 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
10439 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
10440 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
10441 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
10442 break;
10443 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
10444 if (r2)
10445 {
10446 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
10447 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
10448 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10449 }
10450 else
10451 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
10452 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
10453 }
10454 mDNS_Unlock(m);
10455 }
10456 }
10457
10458 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
10459 {
10460 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
10461 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
10462 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
10463 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
10464 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
10465
10466 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
10467 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
10468 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
10469 // since it points to a an address 14 bytes before pkt.
10470 const EthernetHeader *const eth = (const EthernetHeader *)p;
10471 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
10472 mDNSAddr src, dst;
10473 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
10474
10475 // Is ARP? Length must be at least 14 + 28 = 42 bytes
10476 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
10477 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
10478 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
10479 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
10480 {
10481 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
10482 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
10483 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
10484 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
10485 if (end >= trans + RequiredCapLen(pkt->v4.protocol))
10486 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, end, InterfaceID, 0);
10487 }
10488 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
10489 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
10490 {
10491 const mDNSu8 *const trans = p + 54;
10492 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
10493 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
10494 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
10495 if (end >= trans + RequiredCapLen(pkt->v6.pro))
10496 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
10497 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
10498 }
10499 }
10500
10501 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
10502 {
10503 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d %#s",
10504 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, &m->nicelabel);
10505 }
10506
10507 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
10508 {
10509 if (result == mStatus_NameConflict)
10510 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
10511 else if (result == mStatus_MemFree)
10512 {
10513 if (m->SleepState)
10514 m->SPSState = 3;
10515 else
10516 {
10517 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
10518 if (m->SPSState)
10519 {
10520 domainlabel name;
10521 ConstructSleepProxyServerName(m, &name);
10522 mDNS_RegisterService(m, srs,
10523 &name, &SleepProxyServiceType, &localdomain,
10524 mDNSNULL, m->SPSSocket->port, // Host, port
10525 (mDNSu8 *)"", 1, // TXT data, length
10526 mDNSNULL, 0, // Subtypes (none)
10527 mDNSInterface_Any, // Interface ID
10528 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
10529 }
10530 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
10531 }
10532 }
10533 }
10534
10535 // Called with lock held
10536 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower)
10537 {
10538 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
10539 mDNS_DropLockBeforeCallback();
10540
10541 // If turning off SPS, close our socket
10542 // (Do this first, BEFORE calling mDNS_DeregisterService below)
10543 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
10544
10545 // If turning off, or changing type, deregister old name
10546 if (m->SPSState == 1 && sps != m->SPSType)
10547 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
10548
10549 // Record our new SPS parameters
10550 m->SPSType = sps;
10551 m->SPSPortability = port;
10552 m->SPSMarginalPower = marginalpower;
10553 m->SPSTotalPower = totpower;
10554
10555 // If turning on, open socket and advertise service
10556 if (sps)
10557 {
10558 if (!m->SPSSocket)
10559 {
10560 m->SPSSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
10561 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
10562 }
10563 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
10564 }
10565 else if (m->SPSState)
10566 {
10567 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
10568 m->NextScheduledSPS = m->timenow;
10569 }
10570 fail:
10571 mDNS_ReclaimLockAfterCallback();
10572 }
10573
10574 // ***************************************************************************
10575 #if COMPILER_LIKES_PRAGMA_MARK
10576 #pragma mark -
10577 #pragma mark - Startup and Shutdown
10578 #endif
10579
10580 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
10581 {
10582 if (storage && numrecords)
10583 {
10584 mDNSu32 i;
10585 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
10586 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
10587 storage[numrecords-1].next = m->rrcache_free;
10588 m->rrcache_free = storage;
10589 m->rrcache_size += numrecords;
10590 }
10591 }
10592
10593 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
10594 {
10595 mDNS_Lock(m);
10596 mDNS_GrowCache_internal(m, storage, numrecords);
10597 mDNS_Unlock(m);
10598 }
10599
10600 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
10601 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
10602 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
10603 {
10604 mDNSu32 slot;
10605 mDNSs32 timenow;
10606 mStatus result;
10607
10608 if (!rrcachestorage) rrcachesize = 0;
10609
10610 m->p = p;
10611 m->KnownBugs = 0;
10612 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
10613 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
10614 m->DivertMulticastAdvertisements = mDNSfalse;
10615 m->mDNSPlatformStatus = mStatus_Waiting;
10616 m->UnicastPort4 = zeroIPPort;
10617 m->UnicastPort6 = zeroIPPort;
10618 m->PrimaryMAC = zeroEthAddr;
10619 m->MainCallback = Callback;
10620 m->MainContext = Context;
10621 m->rec.r.resrec.RecordType = 0;
10622
10623 // For debugging: To catch and report locking failures
10624 m->mDNS_busy = 0;
10625 m->mDNS_reentrancy = 0;
10626 m->ShutdownTime = 0;
10627 m->lock_rrcache = 0;
10628 m->lock_Questions = 0;
10629 m->lock_Records = 0;
10630
10631 // Task Scheduling variables
10632 result = mDNSPlatformTimeInit();
10633 if (result != mStatus_NoError) return(result);
10634 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
10635 timenow = mDNS_TimeNow_NoLock(m);
10636
10637 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
10638 m->timenow_last = timenow;
10639 m->NextScheduledEvent = timenow;
10640 m->SuppressSending = timenow;
10641 m->NextCacheCheck = timenow + 0x78000000;
10642 m->NextScheduledQuery = timenow + 0x78000000;
10643 m->NextScheduledProbe = timenow + 0x78000000;
10644 m->NextScheduledResponse = timenow + 0x78000000;
10645 m->NextScheduledNATOp = timenow + 0x78000000;
10646 m->NextScheduledSPS = timenow + 0x78000000;
10647 m->NextScheduledStopTime = timenow + 0x78000000;
10648 m->RandomQueryDelay = 0;
10649 m->RandomReconfirmDelay = 0;
10650 m->PktNum = 0;
10651 m->LocalRemoveEvents = mDNSfalse;
10652 m->SleepState = SleepState_Awake;
10653 m->SleepSeqNum = 0;
10654 m->SystemWakeOnLANEnabled = mDNSfalse;
10655 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
10656 m->DelaySleep = 0;
10657 m->SleepLimit = 0;
10658
10659 // These fields only required for mDNS Searcher...
10660 m->Questions = mDNSNULL;
10661 m->NewQuestions = mDNSNULL;
10662 m->CurrentQuestion = mDNSNULL;
10663 m->LocalOnlyQuestions = mDNSNULL;
10664 m->NewLocalOnlyQuestions = mDNSNULL;
10665 m->RestartQuestion = mDNSNULL;
10666 m->rrcache_size = 0;
10667 m->rrcache_totalused = 0;
10668 m->rrcache_active = 0;
10669 m->rrcache_report = 10;
10670 m->rrcache_free = mDNSNULL;
10671
10672 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
10673 {
10674 m->rrcache_hash[slot] = mDNSNULL;
10675 m->rrcache_nextcheck[slot] = timenow + 0x78000000;;
10676 }
10677
10678 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
10679 m->rrauth.rrauth_free = mDNSNULL;
10680
10681 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
10682 m->rrauth.rrauth_hash[slot] = mDNSNULL;
10683
10684 // Fields below only required for mDNS Responder...
10685 m->hostlabel.c[0] = 0;
10686 m->nicelabel.c[0] = 0;
10687 m->MulticastHostname.c[0] = 0;
10688 m->HIHardware.c[0] = 0;
10689 m->HISoftware.c[0] = 0;
10690 m->ResourceRecords = mDNSNULL;
10691 m->DuplicateRecords = mDNSNULL;
10692 m->NewLocalRecords = mDNSNULL;
10693 m->NewLocalOnlyRecords = mDNSfalse;
10694 m->CurrentRecord = mDNSNULL;
10695 m->HostInterfaces = mDNSNULL;
10696 m->ProbeFailTime = 0;
10697 m->NumFailedProbes = 0;
10698 m->SuppressProbes = 0;
10699
10700 #ifndef UNICAST_DISABLED
10701 m->NextuDNSEvent = timenow + 0x78000000;
10702 m->NextSRVUpdate = timenow + 0x78000000;
10703
10704 m->DNSServers = mDNSNULL;
10705
10706 m->Router = zeroAddr;
10707 m->AdvertisedV4 = zeroAddr;
10708 m->AdvertisedV6 = zeroAddr;
10709
10710 m->AuthInfoList = mDNSNULL;
10711
10712 m->ReverseMap.ThisQInterval = -1;
10713 m->StaticHostname.c[0] = 0;
10714 m->FQDN.c[0] = 0;
10715 m->Hostnames = mDNSNULL;
10716 m->AutoTunnelHostAddr.b[0] = 0;
10717 m->AutoTunnelHostAddrActive = mDNSfalse;
10718 m->AutoTunnelLabel.c[0] = 0;
10719
10720 m->StartWABQueries = mDNSfalse;
10721 m->RegisterAutoTunnel6 = mDNStrue;
10722
10723 // NAT traversal fields
10724 m->NATTraversals = mDNSNULL;
10725 m->CurrentNATTraversal = mDNSNULL;
10726 m->retryIntervalGetAddr = 0; // delta between time sent and retry
10727 m->retryGetAddr = timenow + 0x78000000; // absolute time when we retry
10728 m->ExternalAddress = zerov4Addr;
10729
10730 m->NATMcastRecvskt = mDNSNULL;
10731 m->LastNATupseconds = 0;
10732 m->LastNATReplyLocalTime = timenow;
10733 m->LastNATMapResultCode = NATErr_None;
10734
10735 m->UPnPInterfaceID = 0;
10736 m->SSDPSocket = mDNSNULL;
10737 m->SSDPWANPPPConnection = mDNSfalse;
10738 m->UPnPRouterPort = zeroIPPort;
10739 m->UPnPSOAPPort = zeroIPPort;
10740 m->UPnPRouterURL = mDNSNULL;
10741 m->UPnPWANPPPConnection = mDNSfalse;
10742 m->UPnPSOAPURL = mDNSNULL;
10743 m->UPnPRouterAddressString = mDNSNULL;
10744 m->UPnPSOAPAddressString = mDNSNULL;
10745 m->SPSType = 0;
10746 m->SPSPortability = 0;
10747 m->SPSMarginalPower = 0;
10748 m->SPSTotalPower = 0;
10749 m->SPSState = 0;
10750 m->SPSProxyListChanged = mDNSNULL;
10751 m->SPSSocket = mDNSNULL;
10752 m->SPSBrowseCallback = mDNSNULL;
10753 m->ProxyRecords = 0;
10754
10755 #endif
10756
10757 #if APPLE_OSX_mDNSResponder
10758 m->TunnelClients = mDNSNULL;
10759
10760 #if ! NO_WCF
10761 CHECK_WCF_FUNCTION(WCFConnectionNew)
10762 {
10763 m->WCF = WCFConnectionNew();
10764 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
10765 }
10766 #endif
10767
10768 #endif
10769
10770 result = mDNSPlatformInit(m);
10771
10772 #ifndef UNICAST_DISABLED
10773 // It's better to do this *after* the platform layer has set up the
10774 // interface list and security credentials
10775 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
10776 #endif
10777
10778 return(result);
10779 }
10780
10781 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
10782 {
10783 if (m->SPSState == 1)
10784 {
10785 domainlabel name, newname;
10786 domainname type, domain;
10787 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
10788 ConstructSleepProxyServerName(m, &newname);
10789 if (!SameDomainLabelCS(name.c, newname.c))
10790 {
10791 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
10792 // When SleepProxyServerCallback gets the mStatus_MemFree message,
10793 // it will reregister the service under the new name
10794 m->SPSState = 2;
10795 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
10796 }
10797 }
10798
10799 if (m->MainCallback)
10800 m->MainCallback(m, mStatus_ConfigChanged);
10801 }
10802
10803 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
10804 {
10805 (void)m; // unused
10806 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
10807 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
10808 }
10809
10810 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
10811 {
10812 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
10813 cr->resrec.rrtype == kDNSType_A ||
10814 cr->resrec.rrtype == kDNSType_AAAA ||
10815 cr->resrec.rrtype == kDNSType_SRV;
10816
10817 (void) lameduck;
10818 (void) ptr;
10819 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
10820 purge ? "purging" : "reconfirming",
10821 lameduck ? "lame duck" : "new",
10822 ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
10823
10824 if (purge)
10825 {
10826 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
10827 mDNS_PurgeCacheResourceRecord(m, cr);
10828 }
10829 else
10830 {
10831 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
10832 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
10833 }
10834 }
10835
10836 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
10837 {
10838 const mDNSu32 slot = HashSlot(&q->qname);
10839 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
10840 CacheRecord *rp;
10841
10842 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10843 {
10844 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10845 {
10846 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
10847 mDNS_PurgeCacheResourceRecord(m, rp);
10848 }
10849 }
10850 }
10851
10852 mDNSlocal void CacheRecordResetDNSServer(mDNS *const m, DNSQuestion *q, DNSServer *new)
10853 {
10854 const mDNSu32 slot = HashSlot(&q->qname);
10855 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
10856 CacheRecord *rp;
10857 mDNSBool found = mDNSfalse;
10858 mDNSBool foundNew = mDNSfalse;
10859 DNSServer *old = q->qDNSServer;
10860 mDNSBool newQuestion = IsQuestionNew(m, q);
10861 DNSQuestion *qptr;
10862
10863 // This function is called when the DNSServer is updated to the new question. There may already be
10864 // some cache entries matching the old DNSServer and/or new DNSServer. There are four cases. In the
10865 // following table, "Yes" denotes that a cache entry was found for old/new DNSServer.
10866 //
10867 // old DNSServer new DNSServer
10868 //
10869 // Case 1 Yes Yes
10870 // Case 2 No Yes
10871 // Case 3 Yes No
10872 // Case 4 No No
10873 //
10874 // Case 1: There are cache entries for both old and new DNSServer. We handle this case by simply
10875 // expiring the old Cache entries, deliver a RMV event (if an ADD event was delivered before)
10876 // followed by the ADD event of the cache entries corresponding to the new server. This
10877 // case happens when we pick a DNSServer, issue a query and get a valid response and create
10878 // cache entries after which it stops responding. Another query (non-duplicate) picks a different
10879 // DNSServer and creates identical cache entries (perhaps through records in Additional records).
10880 // Now if the first one expires and tries to pick the new DNSServer (the original DNSServer
10881 // is not responding) we will find cache entries corresponding to both DNSServers.
10882 //
10883 // Case 2: There are no cache entries for the old DNSServer but there are some for the new DNSServer.
10884 // This means we should deliver an ADD event. Normally ADD events are delivered by
10885 // AnswerNewQuestion if it is a new question. So, we check to see if it is a new question
10886 // and if so, leave it to AnswerNewQuestion to deliver it. Otherwise, we use
10887 // AnswerQuestionsForDNSServerChanges to deliver the ADD event. This case happens when a
10888 // question picks a DNS server for which AnswerNewQuestion could not deliver an answer even
10889 // though there were potential cache entries but DNSServer did not match. Now when we
10890 // pick a new DNSServer, those cache entries may answer this question.
10891 //
10892 // Case 3: There are the cache entries for the old DNSServer but none for the new. We just move
10893 // the old cache entries to point to the new DNSServer and the caller is expected to
10894 // do a purge or reconfirm to delete or validate the RDATA. We don't need to do anything
10895 // special for delivering ADD events, as it should have been done/will be done by
10896 // AnswerNewQuestion. This case happens when we picked a DNSServer, sent the query and
10897 // got a response and the cache is expired now and we are reissuing the question but the
10898 // original DNSServer does not respond.
10899 //
10900 // Case 4: There are no cache entries either for the old or for the new DNSServer. There is nothing
10901 // much we can do here.
10902 //
10903 // Case 2 and 3 are the most common while case 4 is possible when no DNSServers are working. Case 1
10904 // is relatively less likely to happen in practice
10905
10906 // Temporarily set the DNSServer to look for the matching records for the new DNSServer.
10907 q->qDNSServer = new;
10908 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10909 {
10910 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10911 {
10912 LogInfo("CacheRecordResetDNSServer: Found cache record %##s for new DNSServer address: %#a", rp->resrec.name->c,
10913 (rp->resrec.rDNSServer != mDNSNULL ? &rp->resrec.rDNSServer->addr : mDNSNULL));
10914 foundNew = mDNStrue;
10915 break;
10916 }
10917 }
10918 q->qDNSServer = old;
10919
10920 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10921 {
10922 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10923 {
10924 // Case1
10925 found = mDNStrue;
10926 if (foundNew)
10927 {
10928 LogInfo("CacheRecordResetDNSServer: Flushing Resourcerecord %##s, before:%#a, after:%#a", rp->resrec.name->c,
10929 (rp->resrec.rDNSServer != mDNSNULL ? &rp->resrec.rDNSServer->addr : mDNSNULL),
10930 (new != mDNSNULL ? &new->addr : mDNSNULL));
10931 mDNS_PurgeCacheResourceRecord(m, rp);
10932 if (newQuestion)
10933 {
10934 // "q" is not a duplicate question. If it is a newQuestion, then the CRActiveQuestion can't be
10935 // possibly set as it is set only when we deliver the ADD event to the question.
10936 if (rp->CRActiveQuestion != mDNSNULL)
10937 {
10938 LogMsg("CacheRecordResetDNSServer: ERROR!!: CRActiveQuestion %p set, current question %p, name %##s", rp->CRActiveQuestion, q, q->qname.c);
10939 rp->CRActiveQuestion = mDNSNULL;
10940 }
10941 // if this is a new question, then we never delivered an ADD yet, so don't deliver the RMV.
10942 continue;
10943 }
10944 }
10945 LogInfo("CacheRecordResetDNSServer: resetting cache record %##s DNSServer address before:%#a,"
10946 " after:%#a, CRActiveQuestion %p", rp->resrec.name->c, (rp->resrec.rDNSServer != mDNSNULL ?
10947 &rp->resrec.rDNSServer->addr : mDNSNULL), (new != mDNSNULL ? &new->addr : mDNSNULL),
10948 rp->CRActiveQuestion);
10949 // Though we set it to the new DNS server, the caller is *assumed* to do either a purge
10950 // or reconfirm or send out questions to the "new" server to verify whether the cached
10951 // RDATA is valid
10952 rp->resrec.rDNSServer = new;
10953 }
10954 }
10955
10956 // Case 1 and Case 2
10957 if ((found && foundNew) || (!found && foundNew))
10958 {
10959 if (newQuestion)
10960 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
10961 else if (QuerySuppressed(q))
10962 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for suppressed question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
10963 else
10964 {
10965 LogInfo("CacheRecordResetDNSServer: deliverAddEvents set for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
10966 q->deliverAddEvents = mDNStrue;
10967 for (qptr = q->next; qptr; qptr = qptr->next)
10968 if (qptr->DuplicateOf == q) qptr->deliverAddEvents = mDNStrue;
10969 }
10970 return;
10971 }
10972
10973 // Case 3 and Case 4
10974 return;
10975 }
10976
10977 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
10978 {
10979 DNSQuestion *qptr;
10980
10981 // 1. Whenever we change the DNS server, we change the message identifier also so that response
10982 // from the old server is not accepted as a response from the new server but only messages
10983 // from the new server are accepted as valid responses. We do it irrespective of whether "new"
10984 // is NULL or not. It is possible that we send two queries, no responses, pick a new DNS server
10985 // which is NULL and now the response comes back and will try to penalize the DNS server which
10986 // is NULL. By setting the messageID here, we will not accept that as a valid response.
10987
10988 q->TargetQID = mDNS_NewMessageID(m);
10989
10990 // 2. Move the old cache records to point them at the new DNSServer so that we can deliver the ADD/RMV events
10991 // appropriately. At any point in time, we want all the cache records point only to one DNSServer for a given
10992 // question. "DNSServer" here is the DNSServer object and not the DNS server itself. It is possible to
10993 // have the same DNS server address in two objects, one scoped and another not scoped. But, the cache is per
10994 // DNSServer object. By maintaining the question and the cache entries point to the same DNSServer
10995 // always, the cache maintenance and delivery of ADD/RMV events becomes simpler.
10996 //
10997 // CacheRecordResetDNSServer should be called only once for the non-duplicate question as once the cache
10998 // entries are moved to point to the new DNSServer, we don't need to call it for the duplicate question
10999 // and it is wrong to call for the duplicate question as it's decision to mark deliverAddevents will be
11000 // incorrect.
11001
11002 if (q->DuplicateOf)
11003 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
11004 else
11005 CacheRecordResetDNSServer(m, q, new);
11006
11007 // 3. Make sure all the duplicate questions point to the same DNSServer so that delivery
11008 // of events for all of them are consistent. Duplicates for a question are always inserted
11009 // after in the list.
11010 q->qDNSServer = new;
11011 for (qptr = q->next ; qptr; qptr = qptr->next)
11012 {
11013 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
11014 }
11015 }
11016
11017 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
11018 {
11019 mDNSu32 slot;
11020 CacheGroup *cg;
11021 CacheRecord *cr;
11022
11023 mDNSAddr v4, v6, r;
11024 domainname fqdn;
11025 DNSServer *ptr, **p = &m->DNSServers;
11026 const DNSServer *oldServers = m->DNSServers;
11027 DNSQuestion *q;
11028 McastResolver *mr, **mres = &m->McastResolvers;
11029
11030 debugf("uDNS_SetupDNSConfig: entry");
11031
11032 // Let the platform layer get the current DNS information
11033 // The m->StartWABQueries is set when we get the first domain enumeration query (no need to hit the network
11034 // with domain enumeration queries until we actually need that information). Even if it is not set, we still
11035 // need to setup the search domains so that we can append them to queries that need them.
11036
11037 uDNS_SetupSearchDomains(m, m->StartWABQueries ? UDNS_START_WAB_QUERY : 0);
11038
11039 mDNS_Lock(m);
11040
11041 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
11042 {
11043 ptr->penaltyTime = 0;
11044 ptr->flags |= DNSServer_FlagDelete;
11045 }
11046
11047 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
11048 // mcast resolvers. Today we get both mcast and ucast configuration using the same
11049 // API
11050 for (mr = m->McastResolvers; mr; mr = mr->next)
11051 mr->flags |= McastResolver_FlagDelete;
11052
11053 mDNSPlatformSetDNSConfig(m, mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL);
11054
11055 // For now, we just delete the mcast resolvers. We don't deal with cache or
11056 // questions here. Neither question nor cache point to mcast resolvers. Questions
11057 // do inherit the timeout values from mcast resolvers. But we don't bother
11058 // affecting them as they never change.
11059 while (*mres)
11060 {
11061 if (((*mres)->flags & DNSServer_FlagDelete) != 0)
11062 {
11063 mr = *mres;
11064 *mres = (*mres)->next;
11065 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
11066 mDNSPlatformMemFree(mr);
11067 }
11068 else
11069 {
11070 (*mres)->flags &= ~McastResolver_FlagNew;
11071 mres = &(*mres)->next;
11072 }
11073 }
11074
11075 // Mark the records to be flushed that match a new resolver. We need to do this before
11076 // we walk the questions below where we change the DNSServer pointer of the cache
11077 // record
11078 FORALL_CACHERECORDS(slot, cg, cr)
11079 {
11080 if (cr->resrec.InterfaceID) continue;
11081
11082 // We just mark them for purge or reconfirm. We can't affect the DNSServer pointer
11083 // here as the code below that calls CacheRecordResetDNSServer relies on this
11084 //
11085 // The new DNSServer may be a scoped or non-scoped one. We use the active question's
11086 // InterfaceID for looking up the right DNS server
11087 ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL);
11088
11089 // Purge or Reconfirm if this cache entry would use the new DNS server
11090 if (ptr && (ptr != cr->resrec.rDNSServer))
11091 {
11092 // As the DNSServers for this cache record is not the same anymore, we don't
11093 // want any new questions to pick this old value
11094 if (cr->CRActiveQuestion == mDNSNULL)
11095 {
11096 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s", CRDisplayString(m, cr));
11097 mDNS_PurgeCacheResourceRecord(m, cr);
11098 }
11099 else
11100 {
11101 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s", CRDisplayString(m, cr));
11102 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
11103 }
11104 }
11105 }
11106 // Update our qDNSServer pointers before we go and free the DNSServer object memory
11107 for (q = m->Questions; q; q=q->next)
11108 if (!mDNSOpaque16IsZero(q->TargetQID))
11109 {
11110 DNSServer *s, *t;
11111 DNSQuestion *qptr;
11112 if (q->DuplicateOf) continue;
11113 SetValidDNSServers(m, q);
11114 q->triedAllServersOnce = 0;
11115 s = GetServerForQuestion(m, q);
11116 t = q->qDNSServer;
11117 if (t != s)
11118 {
11119 // If DNS Server for this question has changed, reactivate it
11120 debugf("uDNS_SetupDNSConfig: Updating DNS Server from %p %#a:%d (%##s) to %p %#a:%d (%##s) for %##s (%s)",
11121 t, t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
11122 s, s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
11123 q->qname.c, DNSTypeName(q->qtype));
11124
11125 // After we reset the DNSServer pointer on the cache records here, three things could happen:
11126 //
11127 // 1) The query gets sent out and when the actual response comes back later it is possible
11128 // that the response has the same RDATA, in which case we update our cache entry.
11129 // If the response is different, then the entry will expire and a new entry gets added.
11130 // For the latter case to generate a RMV followed by ADD events, we need to reset the DNS
11131 // server here to match the question and the cache record.
11132 //
11133 // 2) We might have marked the cache entries for purge above and for us to be able to generate the RMV
11134 // events for the questions, the DNSServer on the question should match the Cache Record
11135 //
11136 // 3) We might have marked the cache entries for reconfirm above, for which we send the query out which is
11137 // the same as the first case above.
11138
11139 DNSServerChangeForQuestion(m, q, s);
11140 q->unansweredQueries = 0;
11141 // We still need to pick a new DNSServer for the questions that have been
11142 // suppressed, but it is wrong to activate the query as DNS server change
11143 // could not possibly change the status of SuppressUnusable questions
11144 if (!QuerySuppressed(q))
11145 {
11146 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11147 ActivateUnicastQuery(m, q, mDNStrue);
11148 // ActivateUnicastQuery is called for duplicate questions also as it does something
11149 // special for AutoTunnel questions
11150 for (qptr = q->next ; qptr; qptr = qptr->next)
11151 {
11152 if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
11153 }
11154 }
11155 }
11156 else
11157 {
11158 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
11159 q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
11160 for (qptr = q->next ; qptr; qptr = qptr->next)
11161 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
11162 }
11163 }
11164
11165 while (*p)
11166 {
11167 if (((*p)->flags & DNSServer_FlagDelete) != 0)
11168 {
11169 // Scan our cache, looking for uDNS records that we would have queried this server for.
11170 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
11171 // different DNS servers can give different answers to the same question.
11172 ptr = *p;
11173 FORALL_CACHERECORDS(slot, cg, cr)
11174 {
11175 if (cr->resrec.InterfaceID) continue;
11176 if (cr->resrec.rDNSServer == ptr)
11177 {
11178 // If we don't have an active question for this cache record, neither Purge can
11179 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
11180 // pointer on the record NULL so that we don't point to freed memory (We might dereference
11181 // DNSServer pointers from resource record for logging purposes).
11182 //
11183 // If there is an active question, point to its DNSServer as long as it does not point to the
11184 // freed one. We already went through the questions above and made them point at either the
11185 // new server or NULL if there is no server and also affected the cache entries that match
11186 // this question. Hence, whenever we hit a resource record with a DNSServer that is just
11187 // about to be deleted, we should never have an active question. The code below just tries to
11188 // be careful logging messages if we ever hit this case.
11189
11190 if (cr->CRActiveQuestion)
11191 {
11192 DNSQuestion *qptr = cr->CRActiveQuestion;
11193 if (qptr->qDNSServer == mDNSNULL)
11194 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) with DNSServer Address NULL, Server to be deleted %#a",
11195 CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), &ptr->addr);
11196 else
11197 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) DNSServer Address %#a, Server to be deleted %#a",
11198 CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr, &ptr->addr);
11199
11200 if (qptr->qDNSServer == ptr)
11201 {
11202 qptr->validDNSServers = zeroOpaque64;
11203 qptr->qDNSServer = mDNSNULL;
11204 cr->resrec.rDNSServer = mDNSNULL;
11205 }
11206 else
11207 {
11208 cr->resrec.rDNSServer = qptr->qDNSServer;
11209 }
11210 }
11211 else
11212 {
11213 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
11214 cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
11215 cr->resrec.rDNSServer = mDNSNULL;
11216 }
11217
11218 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
11219 }
11220 }
11221 *p = (*p)->next;
11222 debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
11223 mDNSPlatformMemFree(ptr);
11224 NumUnicastDNSServers--;
11225 }
11226 else
11227 {
11228 (*p)->flags &= ~DNSServer_FlagNew;
11229 p = &(*p)->next;
11230 }
11231 }
11232
11233 // 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).
11234 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
11235 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
11236 // 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.
11237 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
11238 {
11239 int count = 0;
11240 FORALL_CACHERECORDS(slot, cg, cr) if (!cr->resrec.InterfaceID) { mDNS_PurgeCacheResourceRecord(m, cr); count++; }
11241 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
11242 m->DNSServers ? "DNS server became" : "No DNS servers", count);
11243
11244 // Force anything that needs to get zone data to get that information again
11245 RestartRecordGetZoneData(m);
11246 }
11247
11248 // Did our FQDN change?
11249 if (!SameDomainName(&fqdn, &m->FQDN))
11250 {
11251 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
11252
11253 AssignDomainName(&m->FQDN, &fqdn);
11254
11255 if (m->FQDN.c[0])
11256 {
11257 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
11258 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
11259 }
11260 }
11261
11262 mDNS_Unlock(m);
11263
11264 // handle router and primary interface changes
11265 v4 = v6 = r = zeroAddr;
11266 v4.type = r.type = mDNSAddrType_IPv4;
11267
11268 if (mDNSPlatformGetPrimaryInterface(m, &v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
11269 {
11270 mDNS_SetPrimaryInterfaceInfo(m,
11271 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
11272 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
11273 !mDNSIPv4AddressIsZero(r .ip.v4) ? &r : mDNSNULL);
11274 }
11275 else
11276 {
11277 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
11278 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
11279 }
11280
11281 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
11282 return mStatus_NoError;
11283 }
11284
11285 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
11286 {
11287 m->mDNSPlatformStatus = result;
11288 if (m->MainCallback)
11289 {
11290 mDNS_Lock(m);
11291 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
11292 m->MainCallback(m, mStatus_NoError);
11293 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
11294 mDNS_Unlock(m);
11295 }
11296 }
11297
11298 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
11299 {
11300 m->CurrentRecord = start;
11301 while (m->CurrentRecord)
11302 {
11303 AuthRecord *rr = m->CurrentRecord;
11304 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
11305 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
11306 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
11307 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
11308 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
11309 else if (rr->AnnounceCount > 1)
11310 {
11311 rr->AnnounceCount = 1;
11312 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
11313 }
11314 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
11315 // new records could have been added to the end of the list as a result of that call.
11316 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
11317 m->CurrentRecord = rr->next;
11318 }
11319 }
11320
11321 mDNSexport void mDNS_StartExit(mDNS *const m)
11322 {
11323 NetworkInterfaceInfo *intf;
11324 AuthRecord *rr;
11325
11326 mDNS_Lock(m);
11327
11328 LogInfo("mDNS_StartExit");
11329 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
11330
11331 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0);
11332
11333 #if APPLE_OSX_mDNSResponder
11334 #if ! NO_WCF
11335 CHECK_WCF_FUNCTION(WCFConnectionDealloc)
11336 {
11337 if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
11338 }
11339 #endif
11340 #endif
11341
11342 #ifndef UNICAST_DISABLED
11343 {
11344 SearchListElem *s;
11345 SuspendLLQs(m);
11346 // Don't need to do SleepRecordRegistrations() here
11347 // because we deregister all records and services later in this routine
11348 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
11349
11350 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
11351 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
11352 // and we may crash because the list still contains dangling pointers.
11353 for (s = SearchList; s; s = s->next)
11354 while (s->AuthRecs)
11355 {
11356 ARListElem *dereg = s->AuthRecs;
11357 s->AuthRecs = s->AuthRecs->next;
11358 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
11359 }
11360 }
11361 #endif
11362
11363 for (intf = m->HostInterfaces; intf; intf = intf->next)
11364 if (intf->Advertise)
11365 DeadvertiseInterface(m, intf);
11366
11367 // Shut down all our active NAT Traversals
11368 while (m->NATTraversals)
11369 {
11370 NATTraversalInfo *t = m->NATTraversals;
11371 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
11372
11373 // After stopping the NAT Traversal, we zero out the fields.
11374 // This has particularly important implications for our AutoTunnel records --
11375 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
11376 // handlers to just turn around and attempt to re-register those same records.
11377 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
11378 // to not do this.
11379 t->ExternalAddress = zerov4Addr;
11380 t->ExternalPort = zeroIPPort;
11381 t->RequestedPort = zeroIPPort;
11382 t->Lifetime = 0;
11383 t->Result = mStatus_NoError;
11384 }
11385
11386 // Make sure there are nothing but deregistering records remaining in the list
11387 if (m->CurrentRecord)
11388 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
11389
11390 // We're in the process of shutting down, so queries, etc. are no longer available.
11391 // Consequently, determining certain information, e.g. the uDNS update server's IP
11392 // address, will not be possible. The records on the main list are more likely to
11393 // already contain such information, so we deregister the duplicate records first.
11394 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
11395 DeregLoop(m, m->DuplicateRecords);
11396 LogInfo("mDNS_StartExit: Deregistering resource records");
11397 DeregLoop(m, m->ResourceRecords);
11398
11399 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
11400 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
11401 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
11402 {
11403 m->NextScheduledResponse = m->timenow;
11404 m->SuppressSending = 0;
11405 }
11406
11407 if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
11408 else LogInfo("mDNS_StartExit: No deregistering records remain");
11409
11410 for (rr = m->DuplicateRecords; rr; rr = rr->next)
11411 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
11412
11413 // If any deregistering records remain, send their deregistration announcements before we exit
11414 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
11415
11416 mDNS_Unlock(m);
11417
11418 LogInfo("mDNS_StartExit: done");
11419 }
11420
11421 mDNSexport void mDNS_FinalExit(mDNS *const m)
11422 {
11423 mDNSu32 rrcache_active = 0;
11424 mDNSu32 rrcache_totalused = 0;
11425 mDNSu32 slot;
11426 AuthRecord *rr;
11427
11428 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
11429 mDNSPlatformClose(m);
11430
11431 rrcache_totalused = m->rrcache_totalused;
11432 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
11433 {
11434 while (m->rrcache_hash[slot])
11435 {
11436 CacheGroup *cg = m->rrcache_hash[slot];
11437 while (cg->members)
11438 {
11439 CacheRecord *cr = cg->members;
11440 cg->members = cg->members->next;
11441 if (cr->CRActiveQuestion) rrcache_active++;
11442 ReleaseCacheRecord(m, cr);
11443 }
11444 cg->rrcache_tail = &cg->members;
11445 ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
11446 }
11447 }
11448 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
11449 if (rrcache_active != m->rrcache_active)
11450 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
11451
11452 for (rr = m->ResourceRecords; rr; rr = rr->next)
11453 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
11454
11455 LogInfo("mDNS_FinalExit: done");
11456 }