xref: /netbsd-src/external/apache2/mDNSResponder/dist/mDNSCore/mDNS.c (revision a6f3f22f245acb8ee3bbf6871d7dce989204fa97)
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.v6)) 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 		if (m->NextScheduledResponse - m->timenow < 0)
699 			m->NextScheduledResponse = m->timenow;
700 	}
701 
702 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
703 	{
704 	// For reverse-mapping Sleep Proxy PTR records, probe interval is one second
705 	rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
706 
707 	// * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
708 	// * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
709 	//   records that are going to probe, then we delay its first announcement so that it will
710 	//   go out synchronized with the first announcement for the other records that *are* probing.
711 	//   This is a minor performance tweak that helps keep groups of related records synchronized together.
712 	//   The addition of "interval / 2" is to make sure that, in the event that any of the probes are
713 	//   delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
714 	//   When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
715 	//   because they will meet the criterion of being at least half-way to their scheduled announcement time.
716 	// * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
717 
718 	if (rr->ProbeCount)
719 		{
720 		// If we have no probe suppression time set, or it is in the past, set it now
721 		if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
722 			{
723 			// To allow us to aggregate probes when a group of services are registered together,
724 			// the first probe is delayed 1/4 second. This means the common-case behaviour is:
725 			// 1/4 second wait; probe
726 			// 1/4 second wait; probe
727 			// 1/4 second wait; probe
728 			// 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
729 			m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
730 
731 			// If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
732 			if (m->SuppressProbes - m->NextScheduledProbe >= 0)
733 				m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
734 			if (m->SuppressProbes - m->timenow < 0)		// Make sure we don't set m->SuppressProbes excessively in the past
735 				m->SuppressProbes = m->timenow;
736 
737 			// If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
738 			if (m->SuppressProbes - m->NextScheduledQuery >= 0)
739 				m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
740 			if (m->SuppressProbes - m->timenow < 0)		// Make sure we don't set m->SuppressProbes excessively in the past
741 				m->SuppressProbes = m->timenow;
742 
743 			// except... don't expect to be able to send before the m->SuppressSending timer fires
744 			if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
745 				m->SuppressProbes = NonZeroTime(m->SuppressSending);
746 
747 			if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
748 				{
749 				LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
750 					m->SuppressProbes     - m->timenow,
751 					m->NextScheduledProbe - m->timenow,
752 					m->NextScheduledQuery - m->timenow,
753 					m->SuppressSending,
754 					m->SuppressSending    - m->timenow);
755 				m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
756 				}
757 			}
758 		rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
759 		}
760 	else if (m->SuppressProbes && m->SuppressProbes - m->timenow >= 0)
761 		rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
762 	else
763 		rr->LastAPTime = m->timenow - rr->ThisAPInterval;
764 
765 	// For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
766 	// wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
767 	// After three probes one second apart with no answer, we conclude the client is now sleeping
768 	// and we can begin broadcasting our announcements to take over ownership of that IP address.
769 	// If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
770 	// (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
771 	if (rr->AddressProxy.type) rr->LastAPTime = m->timenow;
772 
773 	// Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
774 	// but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
775 	// Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
776 	// Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
777 	// new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
778 	if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
779 		if (rr->WakeUp.HMAC.l[0] && rr->resrec.rrtype == kDNSType_AAAA)
780 			rr->LastAPTime = m->timenow - rr->ThisAPInterval + mDNSPlatformOneSecond * 10;
781 
782 	// Set LastMCTime to now, to inhibit multicast responses
783 	// (no need to send additional multicast responses when we're announcing anyway)
784 	rr->LastMCTime      = m->timenow;
785 	rr->LastMCInterface = mDNSInterfaceMark;
786 
787 	SetNextAnnounceProbeTime(m, rr);
788 	}
789 
790 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
791 	{
792 	const domainname *target;
793 	if (rr->AutoTarget)
794 		{
795 		// For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
796 		// advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
797 		// with the port number in our advertised SRV record automatically tracking the external mapped port.
798 		DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
799 		if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
800 		}
801 
802 	target = GetServiceTarget(m, rr);
803 	if (!target || target->c[0] == 0)
804 		{
805 		// defer registration until we've got a target
806 		LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
807 		rr->state = regState_NoTarget;
808 		return mDNSNULL;
809 		}
810 	else
811 		{
812 		LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
813 		return target;
814 		}
815 	}
816 
817 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
818 // Eventually we should unify this with GetServiceTarget() in uDNS.c
819 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
820 	{
821 	domainname *const target = GetRRDomainNameTarget(&rr->resrec);
822 	const domainname *newname = &m->MulticastHostname;
823 
824 	if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
825 
826 	if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
827 		{
828 		const domainname *const n = SetUnicastTargetToHostName(m, rr);
829 		if (n) newname = n;
830 		else { target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
831 		}
832 
833 	if (target && SameDomainName(target, newname))
834 		debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
835 
836 	if (target && !SameDomainName(target, newname))
837 		{
838 		AssignDomainName(target, newname);
839 		SetNewRData(&rr->resrec, mDNSNULL, 0);		// Update rdlength, rdestimate, rdatahash
840 
841 		// If we're in the middle of probing this record, we need to start again,
842 		// because changing its rdata may change the outcome of the tie-breaker.
843 		// (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
844 		rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
845 
846 		// If we've announced this record, we really should send a goodbye packet for the old rdata before
847 		// changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
848 		// so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
849 		if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
850 			debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
851 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
852 
853 		rr->AnnounceCount  = InitialAnnounceCount;
854 		rr->RequireGoodbye = mDNSfalse;
855 		InitializeLastAPTime(m, rr);
856 		}
857 	}
858 
859 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
860 	{
861 	if (rr->RecordCallback)
862 		{
863 		// CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
864 		// is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
865 		rr->Acknowledged = mDNStrue;
866 		mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
867 		rr->RecordCallback(m, rr, mStatus_NoError);
868 		mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
869 		}
870 	}
871 
872 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
873 	{
874 	// Make sure that we don't activate the SRV record and associated service records, if it is in
875 	// NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
876 	// We should not activate any of the other reords (PTR, TXT) that are part of the service. When
877 	// the target becomes available, the records will be reregistered.
878 	if (rr->resrec.rrtype != kDNSType_SRV)
879 		{
880 		AuthRecord *srvRR = mDNSNULL;
881 		if (rr->resrec.rrtype == kDNSType_PTR)
882 			srvRR = rr->Additional1;
883 		else if (rr->resrec.rrtype == kDNSType_TXT)
884 			srvRR = rr->DependentOn;
885 		if (srvRR)
886 			{
887 			if (srvRR->resrec.rrtype != kDNSType_SRV)
888 				{
889 				LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
890 				}
891 			else
892 				{
893 				LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
894 					ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
895 				rr->state = srvRR->state;
896 				}
897 			}
898 		}
899 
900 	if (rr->state == regState_NoTarget)
901 		{
902 		LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
903 		return;
904 		}
905 	// When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
906 	// the service/record was being deregistered. In that case, we should not try to register again. For the cases where
907 	// the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
908 	// was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
909 	// 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.
910 	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
911 		{
912 		LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
913 		rr->state = regState_DeregPending;
914 		}
915 	else
916 		{
917 		LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
918 		rr->state = regState_Pending;
919 		}
920 	rr->ProbeCount     = 0;
921 	rr->AnnounceCount  = 0;
922 	rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
923 	rr->LastAPTime     = m->timenow - rr->ThisAPInterval;
924 	rr->expire         = 0;	// Forget about all the leases, start fresh
925 	rr->uselease       = mDNStrue;
926 	rr->updateid       = zeroID;
927 	rr->SRVChanged     = mDNSfalse;
928 	rr->updateError    = mStatus_NoError;
929 	// RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
930 	// The records might already be registered with the server and hence could have NAT state.
931 	if (rr->NATinfo.clientContext)
932 		{
933 		mDNS_StopNATOperation_internal(m, &rr->NATinfo);
934 		rr->NATinfo.clientContext = mDNSNULL;
935 		}
936 	if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
937 	if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
938 	if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
939 		m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
940 	}
941 
942 // Two records qualify to be local duplicates if:
943 // (a) the RecordTypes are the same, or
944 // (b) one is Unique and the other Verified
945 // (c) either is in the process of deregistering
946 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
947 	((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
948 	((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
949 
950 #define RecordIsLocalDuplicate(A,B) \
951 	((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
952 
953 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
954 	{
955 	AuthGroup *a;
956 	AuthGroup **ag = &a;
957 	AuthRecord **rp;
958 	const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
959 
960 	a = AuthGroupForRecord(r, slot, &rr->resrec);
961 	if (!a) return mDNSNULL;
962 	rp = &(*ag)->members;
963 	while (*rp)
964 		{
965 		if (!RecordIsLocalDuplicate(*rp, rr))
966 			rp=&(*rp)->next;
967 		else
968 			{
969 			if ((*rp)->resrec.RecordType == kDNSRecordTypeDeregistering)
970 				{
971 				(*rp)->AnnounceCount = 0;
972 				rp=&(*rp)->next;
973 				}
974 			else return *rp;
975 			}
976 		}
977 	return (mDNSNULL);
978 	}
979 
980 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
981 	{
982 	AuthGroup *a;
983 	AuthGroup **ag = &a;
984 	AuthRecord **rp;
985 	const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
986 
987 	a = AuthGroupForRecord(r, slot, &rr->resrec);
988 	if (!a) return mDNSfalse;
989 	rp = &(*ag)->members;
990 	while (*rp)
991 		{
992 		const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
993 		const AuthRecord *s2 = (*rp)->RRSet ? (*rp)->RRSet : *rp;
994 		if (s1 != s2 && SameResourceRecordSignature((*rp), rr) && !IdenticalSameNameRecord(&(*rp)->resrec, &rr->resrec))
995 			return mDNStrue;
996 		else
997 			rp=&(*rp)->next;
998 		}
999 	return (mDNSfalse);
1000 	}
1001 
1002 // checks to see if "rr" is already present
1003 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1004 	{
1005 	AuthGroup *a;
1006 	AuthGroup **ag = &a;
1007 	AuthRecord **rp;
1008 	const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1009 
1010 	a = AuthGroupForRecord(r, slot, &rr->resrec);
1011 	if (!a) return mDNSNULL;
1012 	rp = &(*ag)->members;
1013 	while (*rp)
1014 		{
1015 		if (*rp != rr)
1016 			rp=&(*rp)->next;
1017 		else
1018 			{
1019 			return *rp;
1020 			}
1021 		}
1022 	return (mDNSNULL);
1023 	}
1024 
1025 // Exported so uDNS.c can call this
1026 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1027 	{
1028 	domainname *target = GetRRDomainNameTarget(&rr->resrec);
1029 	AuthRecord *r;
1030 	AuthRecord **p = &m->ResourceRecords;
1031 	AuthRecord **d = &m->DuplicateRecords;
1032 
1033 	if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1034 		{ LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1035 
1036 	if (!rr->resrec.RecordType)
1037 		{ LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1038 
1039 	if (m->ShutdownTime)
1040 		{ LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1041 
1042 	if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1043 		{
1044 		mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1045 		if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1046 			{
1047 			rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1048 			rr->ARType = AuthRecordLocalOnly;
1049 			}
1050 		if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1051 			{
1052 			NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1053 			if (intf && !intf->Advertise){ rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1054 			}
1055 		if (rr->resrec.InterfaceID != previousID)
1056 			LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1057 		}
1058 
1059 	if (RRLocalOnly(rr))
1060 		{
1061 		if (CheckAuthSameRecord(&m->rrauth, rr))
1062 			{
1063 			LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1064 				rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1065 			return(mStatus_AlreadyRegistered);
1066 			}
1067 		}
1068 	else
1069 		{
1070 		while (*p && *p != rr) p=&(*p)->next;
1071 		if (*p)
1072 			{
1073 			LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1074 				rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1075 			return(mStatus_AlreadyRegistered);
1076 			}
1077 		}
1078 
1079 	while (*d && *d != rr) d=&(*d)->next;
1080 	if (*d)
1081 		{
1082 		LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1083 				rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1084 		return(mStatus_AlreadyRegistered);
1085 		}
1086 
1087 	if (rr->DependentOn)
1088 		{
1089 		if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1090 			rr->resrec.RecordType =  kDNSRecordTypeVerified;
1091 		else
1092 			{
1093 			LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1094 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1095 			return(mStatus_Invalid);
1096 			}
1097 		if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1098 			{
1099 			LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1100 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1101 			return(mStatus_Invalid);
1102 			}
1103 		}
1104 
1105 	// If this resource record is referencing a specific interface, make sure it exists.
1106 	// Skip checks for LocalOnly and P2P as they are not valid InterfaceIDs. Also, for scoped
1107 	// entries in /etc/hosts skip that check as that interface may not be valid at this time.
1108 	if (rr->resrec.InterfaceID && rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
1109 		{
1110 		NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1111 		if (!intf)
1112 			{
1113 			debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr->resrec.InterfaceID);
1114 			return(mStatus_BadReferenceErr);
1115 			}
1116 		}
1117 
1118 	rr->next = mDNSNULL;
1119 
1120 	// Field Group 1: The actual information pertaining to this resource record
1121 	// Set up by client prior to call
1122 
1123 	// Field Group 2: Persistent metadata for Authoritative Records
1124 //	rr->Additional1       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1125 //	rr->Additional2       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1126 //	rr->DependentOn       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1127 //	rr->RRSet             = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1128 //	rr->Callback          = already set      in mDNS_SetupResourceRecord
1129 //	rr->Context           = already set      in mDNS_SetupResourceRecord
1130 //	rr->RecordType        = already set      in mDNS_SetupResourceRecord
1131 //	rr->HostTarget        = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1132 //	rr->AllowRemoteQuery  = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1133 	// Make sure target is not uninitialized data, or we may crash writing debugging log messages
1134 	if (rr->AutoTarget && target) target->c[0] = 0;
1135 
1136 	// Field Group 3: Transient state for Authoritative Records
1137 	rr->Acknowledged      = mDNSfalse;
1138 	rr->ProbeCount        = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1139 	rr->AnnounceCount     = InitialAnnounceCount;
1140 	rr->RequireGoodbye    = mDNSfalse;
1141 	rr->AnsweredLocalQ    = mDNSfalse;
1142 	rr->IncludeInProbe    = mDNSfalse;
1143 	rr->ImmedUnicast      = mDNSfalse;
1144 	rr->SendNSECNow       = mDNSNULL;
1145 	rr->ImmedAnswer       = mDNSNULL;
1146 	rr->ImmedAdditional   = mDNSNULL;
1147 	rr->SendRNow          = mDNSNULL;
1148 	rr->v4Requester       = zerov4Addr;
1149 	rr->v6Requester       = zerov6Addr;
1150 	rr->NextResponse      = mDNSNULL;
1151 	rr->NR_AnswerTo       = mDNSNULL;
1152 	rr->NR_AdditionalTo   = mDNSNULL;
1153 	if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1154 //	rr->LastAPTime        = Set for us in InitializeLastAPTime()
1155 //	rr->LastMCTime        = Set for us in InitializeLastAPTime()
1156 //	rr->LastMCInterface   = Set for us in InitializeLastAPTime()
1157 	rr->NewRData          = mDNSNULL;
1158 	rr->newrdlength       = 0;
1159 	rr->UpdateCallback    = mDNSNULL;
1160 	rr->UpdateCredits     = kMaxUpdateCredits;
1161 	rr->NextUpdateCredit  = 0;
1162 	rr->UpdateBlocked     = 0;
1163 
1164 	// For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1165 	if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1166 
1167 	// Field Group 4: Transient uDNS state for Authoritative Records
1168 	rr->state             = regState_Zero;
1169 	rr->uselease          = 0;
1170 	rr->expire            = 0;
1171 	rr->Private           = 0;
1172 	rr->updateid          = zeroID;
1173 	rr->zone              = rr->resrec.name;
1174 	rr->nta               = mDNSNULL;
1175 	rr->tcp               = mDNSNULL;
1176 	rr->OrigRData         = 0;
1177 	rr->OrigRDLen         = 0;
1178 	rr->InFlightRData     = 0;
1179 	rr->InFlightRDLen     = 0;
1180 	rr->QueuedRData       = 0;
1181 	rr->QueuedRDLen       = 0;
1182 	//mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1183 	// We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1184 	// request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1185 	// times with different values if the external NAT port changes during the lifetime of the service registration.
1186 	//if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1187 
1188 //	rr->resrec.interface         = already set in mDNS_SetupResourceRecord
1189 //	rr->resrec.name->c           = MUST be set by client
1190 //	rr->resrec.rrtype            = already set in mDNS_SetupResourceRecord
1191 //	rr->resrec.rrclass           = already set in mDNS_SetupResourceRecord
1192 //	rr->resrec.rroriginalttl     = already set in mDNS_SetupResourceRecord
1193 //	rr->resrec.rdata             = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1194 
1195 	// BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1196 	// since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1197 	// Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1198 	if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1199 
1200 	if (rr->AutoTarget)
1201 		{
1202 		SetTargetToHostName(m, rr);	// Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1203 #ifndef UNICAST_DISABLED
1204 		// If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1205 		// 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.
1206 		if (rr->state == regState_NoTarget)
1207 			{
1208 			// Initialize the target so that we don't crash while logging etc.
1209 			domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1210 			if (tar) tar->c[0] = 0;
1211 			LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1212 			}
1213 #endif
1214 		}
1215 	else
1216 		{
1217 		rr->resrec.rdlength   = GetRDLength(&rr->resrec, mDNSfalse);
1218 		rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1219 		}
1220 
1221 	if (!ValidateDomainName(rr->resrec.name))
1222 		{ LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1223 
1224 	// Don't do this until *after* we've set rr->resrec.rdlength
1225 	if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1226 		{ LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1227 
1228 	rr->resrec.namehash   = DomainNameHashValue(rr->resrec.name);
1229 	rr->resrec.rdatahash  = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1230 
1231 	if (RRLocalOnly(rr))
1232 		{
1233 		// If this is supposed to be unique, make sure we don't have any name conflicts.
1234 		// If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1235 		// (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1236 		// complications and not clear whether there are any benefits. See rdar:9304275 for details.
1237 		// Hence, just bail out.
1238 		if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1239 			{
1240 			if (CheckAuthRecordConflict(&m->rrauth, rr))
1241 				{
1242 				LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1243 				return mStatus_NameConflict;
1244 				}
1245 			}
1246 		}
1247 
1248 	// For uDNS records, we don't support duplicate checks at this time.
1249 #ifndef UNICAST_DISABLED
1250 	if (AuthRecord_uDNS(rr))
1251 		{
1252 		if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1253 		// When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1254 		// 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.
1255 		// Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1256 		while (*p) p=&(*p)->next;
1257 		*p = rr;
1258 		if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1259 		rr->ProbeCount    = 0;
1260 		rr->AnnounceCount = 0;
1261 		if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1262 		return(mStatus_NoError);			// <--- Note: For unicast records, code currently bails out at this point
1263 		}
1264 #endif
1265 
1266 	// Now that we've finished building our new record, make sure it's not identical to one we already have
1267 	if (RRLocalOnly(rr))
1268 		{
1269 		rr->ProbeCount    = 0;
1270 		rr->AnnounceCount = 0;
1271 		r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1272 		}
1273 	else
1274 		{
1275 		for (r = m->ResourceRecords; r; r=r->next)
1276 			if (RecordIsLocalDuplicate(r, rr))
1277 				{
1278 				if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1279 				else break;
1280 				}
1281 		}
1282 
1283 	if (r)
1284 		{
1285 		debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m,rr));
1286 		*d = rr;
1287 		// If the previous copy of this record is already verified unique,
1288 		// then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1289 		// Setting ProbeCount to zero will cause SendQueries() to advance this record to
1290 		// kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1291 		if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1292 			rr->ProbeCount = 0;
1293 		}
1294 	else
1295 		{
1296 		debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1297 		if (RRLocalOnly(rr))
1298 			{
1299 			AuthGroup *ag;
1300 			ag = InsertAuthRecord(m, &m->rrauth, rr);
1301 			if (ag && !ag->NewLocalOnlyRecords) {
1302 				m->NewLocalOnlyRecords = mDNStrue;
1303 				ag->NewLocalOnlyRecords = rr;
1304 			}
1305 			// No probing for LocalOnly records, Acknowledge them right away
1306 			if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1307 			AcknowledgeRecord(m, rr);
1308 			return(mStatus_NoError);
1309 			}
1310 		else
1311 			{
1312 			if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1313 			*p = rr;
1314 			}
1315 		}
1316 
1317 	if (!AuthRecord_uDNS(rr))	// This check is superfluous, given that for unicast records we (currently) bail out above
1318 		{
1319 		// For records that are not going to probe, acknowledge them right away
1320 		if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1321 			AcknowledgeRecord(m, rr);
1322 
1323 		// Adding a record may affect whether or not we should sleep
1324 		mDNS_UpdateAllowSleep(m);
1325 		}
1326 
1327 	return(mStatus_NoError);
1328 	}
1329 
1330 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1331 	{
1332 	m->ProbeFailTime = m->timenow;
1333 	m->NumFailedProbes++;
1334 	// If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1335 	// If a bunch of hosts have all been configured with the same name, then they'll all
1336 	// conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1337 	// up to name-10. After that they'll start adding random increments in the range 1-100,
1338 	// so they're more likely to branch out in the available namespace and settle on a set of
1339 	// unique names quickly. If after five more tries the host is still conflicting, then we
1340 	// may have a serious problem, so we start rate-limiting so we don't melt down the network.
1341 	if (m->NumFailedProbes >= 15)
1342 		{
1343 		m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1344 		LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1345 			m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1346 		}
1347 	}
1348 
1349 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1350 	{
1351 	RData *OldRData = rr->resrec.rdata;
1352 	mDNSu16 OldRDLen = rr->resrec.rdlength;
1353 	SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);	// Update our rdata
1354 	rr->NewRData = mDNSNULL;									// Clear the NewRData pointer ...
1355 	if (rr->UpdateCallback)
1356 		rr->UpdateCallback(m, rr, OldRData, OldRDLen);			// ... and let the client know
1357 	}
1358 
1359 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1360 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1361 // Exported so uDNS.c can call this
1362 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1363 	{
1364 	AuthRecord *r2;
1365 	mDNSu8 RecordType = rr->resrec.RecordType;
1366 	AuthRecord **p = &m->ResourceRecords;	// Find this record in our list of active records
1367 	mDNSBool dupList = mDNSfalse;
1368 
1369 	if (RRLocalOnly(rr))
1370 		{
1371 		AuthGroup *a;
1372 		AuthGroup **ag = &a;
1373 		AuthRecord **rp;
1374 		const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1375 
1376 		a = AuthGroupForRecord(&m->rrauth, slot, &rr->resrec);
1377 		if (!a) return mDNSfalse;
1378 		rp = &(*ag)->members;
1379 		while (*rp && *rp != rr) rp=&(*rp)->next;
1380 		p = rp;
1381 		}
1382 	else
1383 		{
1384 		while (*p && *p != rr) p=&(*p)->next;
1385 		}
1386 
1387 	if (*p)
1388 		{
1389 		// We found our record on the main list. See if there are any duplicates that need special handling.
1390 		if (drt == mDNS_Dereg_conflict)		// If this was a conflict, see that all duplicates get the same treatment
1391 			{
1392 			// Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1393 			// deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1394 			for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1395 			}
1396 		else
1397 			{
1398 			// Before we delete the record (and potentially send a goodbye packet)
1399 			// first see if we have a record on the duplicate list ready to take over from it.
1400 			AuthRecord **d = &m->DuplicateRecords;
1401 			while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1402 			if (*d)
1403 				{
1404 				AuthRecord *dup = *d;
1405 				debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1406 					dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1407 				*d        = dup->next;		// Cut replacement record from DuplicateRecords list
1408 				if (RRLocalOnly(rr))
1409 					{
1410 					dup->next = mDNSNULL;
1411 					if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1412 					}
1413 				else
1414 					{
1415 					dup->next = rr->next;		// And then...
1416 					rr->next  = dup;			// ... splice it in right after the record we're about to delete
1417 					}
1418 				dup->resrec.RecordType        = rr->resrec.RecordType;
1419 				dup->ProbeCount      = rr->ProbeCount;
1420 				dup->AnnounceCount   = rr->AnnounceCount;
1421 				dup->RequireGoodbye  = rr->RequireGoodbye;
1422 				dup->AnsweredLocalQ  = rr->AnsweredLocalQ;
1423 				dup->ImmedAnswer     = rr->ImmedAnswer;
1424 				dup->ImmedUnicast    = rr->ImmedUnicast;
1425 				dup->ImmedAdditional = rr->ImmedAdditional;
1426 				dup->v4Requester     = rr->v4Requester;
1427 				dup->v6Requester     = rr->v6Requester;
1428 				dup->ThisAPInterval  = rr->ThisAPInterval;
1429 				dup->LastAPTime      = rr->LastAPTime;
1430 				dup->LastMCTime      = rr->LastMCTime;
1431 				dup->LastMCInterface = rr->LastMCInterface;
1432 				dup->Private         = rr->Private;
1433 				dup->state           = rr->state;
1434 				rr->RequireGoodbye = mDNSfalse;
1435 				rr->AnsweredLocalQ = mDNSfalse;
1436 				}
1437 			}
1438 		}
1439 	else
1440 		{
1441 		// We didn't find our record on the main list; try the DuplicateRecords list instead.
1442 		p = &m->DuplicateRecords;
1443 		while (*p && *p != rr) p=&(*p)->next;
1444 		// If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1445 		if (*p) { rr->RequireGoodbye = mDNSfalse; dupList = mDNStrue; }
1446 		if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1447 			rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1448 		}
1449 
1450 	if (!*p)
1451 		{
1452 		// No need to log an error message if we already know this is a potentially repeated deregistration
1453 		if (drt != mDNS_Dereg_repeat)
1454 			LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1455 		return(mStatus_BadReferenceErr);
1456 		}
1457 
1458 	// If this is a shared record and we've announced it at least once,
1459 	// we need to retract that announcement before we delete the record
1460 
1461 	// If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1462 	// it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1463 	// The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1464 	// mechanism to cope with the client callback modifying the question list while that's happening.
1465 	// However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1466 	// which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1467 	// More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1468 	// records, thereby invoking yet more callbacks, without limit.
1469 	// The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1470 	// actual goodbye packets.
1471 
1472 #ifndef UNICAST_DISABLED
1473 	if (AuthRecord_uDNS(rr))
1474 		{
1475 		if (rr->RequireGoodbye)
1476 			{
1477 			if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1478 			rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
1479 			m->LocalRemoveEvents     = mDNStrue;
1480 			uDNS_DeregisterRecord(m, rr);
1481 			// At this point unconditionally we bail out
1482 			// Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1483 			// which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1484 			// process and will complete asynchronously. Either way we don't need to do anything more here.
1485 			return(mStatus_NoError);
1486 			}
1487 		// Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1488 		// from the server. In that case, if the records have been part of a group update, clear the
1489 		// state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1490 		rr->updateid = zeroID;
1491 
1492 		// We defer cleaning up NAT state only after sending goodbyes. This is important because
1493 		// RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1494 		// This happens today when we turn on/off interface where we get multiple network transitions
1495 		// and RestartRecordGetZoneData triggers re-registration of the resource records even though
1496 		// they may be in Registered state which causes NAT information to be setup multiple times. Defering
1497 		// the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1498 		// NAT state here takes care of the case where we did not send goodbyes at all.
1499 		if (rr->NATinfo.clientContext)
1500 			{
1501 			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1502 			rr->NATinfo.clientContext = mDNSNULL;
1503 			}
1504 		if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1505 		if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
1506 		}
1507 #endif // UNICAST_DISABLED
1508 
1509 	if      (RecordType == kDNSRecordTypeUnregistered)
1510 		LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1511 	else if (RecordType == kDNSRecordTypeDeregistering)
1512 		{
1513 		LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1514 		return(mStatus_BadReferenceErr);
1515 		}
1516 
1517 	// <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1518 	// We may want to consider changing this code so that we generate local-only question "rmv"
1519 	// events (and maybe goodbye packets too) for unique records as well as for shared records
1520 	// Note: If we change the logic for this "if" statement, need to ensure that the code in
1521 	// CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1522 	// clause will execute here and the record will be cut from the list.
1523 	if (rr->WakeUp.HMAC.l[0] ||
1524 		(RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1525 		{
1526 		verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1527 		rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
1528 		rr->resrec.rroriginalttl = 0;
1529 		rr->AnnounceCount        = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1530 		rr->ThisAPInterval       = mDNSPlatformOneSecond * 2;
1531 		rr->LastAPTime           = m->timenow - rr->ThisAPInterval;
1532 		m->LocalRemoveEvents     = mDNStrue;
1533 		if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1534 			m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1535 		}
1536 	else
1537 		{
1538 		if (!dupList && RRLocalOnly(rr))
1539 			{
1540 			AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1541 			if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1542 			}
1543 		else
1544 			{
1545 			*p = rr->next;					// Cut this record from the list
1546 			if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1547 			}
1548 		// If someone is about to look at this, bump the pointer forward
1549 		if (m->CurrentRecord   == rr) m->CurrentRecord   = rr->next;
1550 		rr->next = mDNSNULL;
1551 
1552 		// Should we generate local remove events here?
1553 		// i.e. something like:
1554 		// if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1555 
1556 		verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1557 		rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1558 
1559 		if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1560 			debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1561 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1562 
1563 		// If we have an update queued up which never executed, give the client a chance to free that memory
1564 		if (rr->NewRData) CompleteRDataUpdate(m, rr);	// Update our rdata, clear the NewRData pointer, and return memory to the client
1565 
1566 
1567 		// CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1568 		// is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1569 		// In this case the likely client action to the mStatus_MemFree message is to free the memory,
1570 		// so any attempt to touch rr after this is likely to lead to a crash.
1571 		if (drt != mDNS_Dereg_conflict)
1572 			{
1573 			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
1574 			LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m, rr));
1575 			if (rr->RecordCallback)
1576 				rr->RecordCallback(m, rr, mStatus_MemFree);			// MUST NOT touch rr after this
1577 			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
1578 			}
1579 		else
1580 			{
1581 			RecordProbeFailure(m, rr);
1582 			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
1583 			if (rr->RecordCallback)
1584 				rr->RecordCallback(m, rr, mStatus_NameConflict);	// MUST NOT touch rr after this
1585 			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
1586 			// Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1587 			// Note that with all the client callbacks going on, by the time we get here all the
1588 			// records we marked may have been explicitly deregistered by the client anyway.
1589 			r2 = m->DuplicateRecords;
1590 			while (r2)
1591 				{
1592 				if (r2->ProbeCount != 0xFF) r2 = r2->next;
1593 				else { mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict); r2 = m->DuplicateRecords; }
1594 				}
1595 			}
1596 		}
1597 	mDNS_UpdateAllowSleep(m);
1598 	return(mStatus_NoError);
1599 	}
1600 
1601 // ***************************************************************************
1602 #if COMPILER_LIKES_PRAGMA_MARK
1603 #pragma mark -
1604 #pragma mark - Packet Sending Functions
1605 #endif
1606 
1607 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1608 	{
1609 	if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1610 		{
1611 		**nrpp = rr;
1612 		// NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1613 		// If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1614 		// The referenced record will definitely be acceptable (by recursive application of this rule)
1615 		if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1616 		rr->NR_AdditionalTo = add;
1617 		*nrpp = &rr->NextResponse;
1618 		}
1619 	debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1620 	}
1621 
1622 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1623 	{
1624 	AuthRecord  *rr, *rr2;
1625 	for (rr=ResponseRecords; rr; rr=rr->NextResponse)			// For each record we plan to put
1626 		{
1627 		// (Note: This is an "if", not a "while". If we add a record, we'll find it again
1628 		// later in the "for" loop, and we will follow further "additional" links then.)
1629 		if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1630 			AddRecordToResponseList(nrpp, rr->Additional1, rr);
1631 
1632 		if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
1633 			AddRecordToResponseList(nrpp, rr->Additional2, rr);
1634 
1635 		// For SRV records, automatically add the Address record(s) for the target host
1636 		if (rr->resrec.rrtype == kDNSType_SRV)
1637 			{
1638 			for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)					// Scan list of resource records
1639 				if (RRTypeIsAddressType(rr2->resrec.rrtype) &&					// For all address records (A/AAAA) ...
1640 					ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&	// ... which are valid for answer ...
1641 					rr->resrec.rdatahash == rr2->resrec.namehash &&			// ... whose name is the name of the SRV target
1642 					SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
1643 					AddRecordToResponseList(nrpp, rr2, rr);
1644 			}
1645 		else if (RRTypeIsAddressType(rr->resrec.rrtype))	// For A or AAAA, put counterpart as additional
1646 			{
1647 			for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)					// Scan list of resource records
1648 				if (RRTypeIsAddressType(rr2->resrec.rrtype) &&					// For all address records (A/AAAA) ...
1649 					ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&	// ... which are valid for answer ...
1650 					rr->resrec.namehash == rr2->resrec.namehash &&				// ... and have the same name
1651 					SameDomainName(rr->resrec.name, rr2->resrec.name))
1652 					AddRecordToResponseList(nrpp, rr2, rr);
1653 			}
1654 		else if (rr->resrec.rrtype == kDNSType_PTR)			// For service PTR, see if we want to add DeviceInfo record
1655 			{
1656 			if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
1657 				SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1658 				AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
1659 			}
1660 		}
1661 	}
1662 
1663 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
1664 	{
1665 	AuthRecord *rr;
1666 	AuthRecord  *ResponseRecords = mDNSNULL;
1667 	AuthRecord **nrp             = &ResponseRecords;
1668 	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
1669 
1670 	// Make a list of all our records that need to be unicast to this destination
1671 	for (rr = m->ResourceRecords; rr; rr=rr->next)
1672 		{
1673 		// If we find we can no longer unicast this answer, clear ImmedUnicast
1674 		if (rr->ImmedAnswer == mDNSInterfaceMark               ||
1675 			mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
1676 			mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr)  )
1677 			rr->ImmedUnicast = mDNSfalse;
1678 
1679 		if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
1680 			{
1681 			if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
1682 				(dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
1683 				{
1684 				rr->ImmedAnswer  = mDNSNULL;				// Clear the state fields
1685 				rr->ImmedUnicast = mDNSfalse;
1686 				rr->v4Requester  = zerov4Addr;
1687 				rr->v6Requester  = zerov6Addr;
1688 
1689 				// Only sent records registered for P2P over P2P interfaces
1690 				if (intf && !mDNSPlatformValidRecordForInterface(rr, intf))
1691 					{
1692 					LogInfo("SendDelayedUnicastResponse: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, InterfaceID));
1693 					continue;
1694 					}
1695 
1696 				if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse)	// rr->NR_AnswerTo
1697 					{ rr->NR_AnswerTo = (mDNSu8*)~0; *nrp = rr; nrp = &rr->NextResponse; }
1698 				}
1699 			}
1700 		}
1701 
1702 	AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
1703 
1704 	while (ResponseRecords)
1705 		{
1706 		mDNSu8 *responseptr = m->omsg.data;
1707 		mDNSu8 *newptr;
1708 		InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1709 
1710 		// Put answers in the packet
1711 		while (ResponseRecords && ResponseRecords->NR_AnswerTo)
1712 			{
1713 			rr = ResponseRecords;
1714 			if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1715 				rr->resrec.rrclass |= kDNSClass_UniqueRRSet;		// Temporarily set the cache flush bit so PutResourceRecord will set it
1716 			newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
1717 			rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;			// Make sure to clear cache flush bit back to normal state
1718 			if (!newptr && m->omsg.h.numAnswers) break;	// If packet full, send it now
1719 			if (newptr) responseptr = newptr;
1720 			ResponseRecords = rr->NextResponse;
1721 			rr->NextResponse    = mDNSNULL;
1722 			rr->NR_AnswerTo     = mDNSNULL;
1723 			rr->NR_AdditionalTo = mDNSNULL;
1724 			rr->RequireGoodbye  = mDNStrue;
1725 			}
1726 
1727 		// Add additionals, if there's space
1728 		while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
1729 			{
1730 			rr = ResponseRecords;
1731 			if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1732 				rr->resrec.rrclass |= kDNSClass_UniqueRRSet;		// Temporarily set the cache flush bit so PutResourceRecord will set it
1733 			newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
1734 			rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;			// Make sure to clear cache flush bit back to normal state
1735 
1736 			if (newptr) responseptr = newptr;
1737 			if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
1738 			else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
1739 			ResponseRecords = rr->NextResponse;
1740 			rr->NextResponse    = mDNSNULL;
1741 			rr->NR_AnswerTo     = mDNSNULL;
1742 			rr->NR_AdditionalTo = mDNSNULL;
1743 			}
1744 
1745 		if (m->omsg.h.numAnswers)
1746 			mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL);
1747 		}
1748 	}
1749 
1750 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1751 // and the client's mStatus_MemFree callback will have been invoked
1752 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
1753 	{
1754 	LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
1755 	// Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
1756 	// it should go ahead and immediately dispose of this registration
1757 	rr->resrec.RecordType = kDNSRecordTypeShared;
1758 	rr->RequireGoodbye    = mDNSfalse;
1759 	rr->WakeUp.HMAC       = zeroEthAddr;
1760 	if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1761 	mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);		// Don't touch rr after this
1762 	}
1763 
1764 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
1765 // any deregistering records that remain in the m->ResourceRecords list.
1766 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
1767 // which may change the record list and/or question list.
1768 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1769 mDNSlocal void DiscardDeregistrations(mDNS *const m)
1770 	{
1771 	if (m->CurrentRecord)
1772 		LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
1773 	m->CurrentRecord = m->ResourceRecords;
1774 
1775 	while (m->CurrentRecord)
1776 		{
1777 		AuthRecord *rr = m->CurrentRecord;
1778 		if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1779 			CompleteDeregistration(m, rr);		// Don't touch rr after this
1780 		else
1781 			m->CurrentRecord = rr->next;
1782 		}
1783 	}
1784 
1785 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
1786 	{
1787 	int i, val = 0;
1788 	if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
1789 	for (i=1; i<=src[0]; i++)
1790 		{
1791 		if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
1792 		val = val * 10 + src[i] - '0';
1793 		}
1794 	if (val > 255) return(mStatus_Invalid);
1795 	*dst = (mDNSu8)val;
1796 	return(mStatus_NoError);
1797 	}
1798 
1799 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
1800 	{
1801 	int skip = CountLabels(name) - 6;
1802 	if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
1803 	if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
1804 		GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
1805 		GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
1806 		GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
1807 	a->type = mDNSAddrType_IPv4;
1808 	return(mStatus_NoError);
1809 	}
1810 
1811 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :   \
1812 					((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :   \
1813 					((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
1814 
1815 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
1816 	{
1817 	int i, h, l;
1818 	const domainname *n;
1819 
1820 	int skip = CountLabels(name) - 34;
1821 	if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
1822 
1823 	n = SkipLeadingLabels(name, skip);
1824 	for (i=0; i<16; i++)
1825 		{
1826 		if (n->c[0] != 1) return mStatus_Invalid;
1827 		l = HexVal(n->c[1]);
1828 		n = (const domainname *)(n->c + 2);
1829 
1830 		if (n->c[0] != 1) return mStatus_Invalid;
1831 		h = HexVal(n->c[1]);
1832 		n = (const domainname *)(n->c + 2);
1833 
1834 		if (l<0 || h<0) return mStatus_Invalid;
1835 		a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
1836 		}
1837 
1838 	a->type = mDNSAddrType_IPv6;
1839 	return(mStatus_NoError);
1840 	}
1841 
1842 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
1843 	{
1844 	int skip = CountLabels(name) - 2;
1845 	if (skip >= 0)
1846 		{
1847 		const domainname *suffix = SkipLeadingLabels(name, skip);
1848 		if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
1849 		if (SameDomainName(suffix, (const domainname*)"\x3" "ip6"     "\x4" "arpa")) return mDNSAddrType_IPv6;
1850 		}
1851 	return(mDNSAddrType_None);
1852 	}
1853 
1854 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
1855 	const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
1856 	{
1857 	int i;
1858 	mDNSu8 *ptr = m->omsg.data;
1859 	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1860 	if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1861 
1862 	// 0x00 Destination address
1863 	for (i=0; i<6; i++) *ptr++ = dst->b[i];
1864 
1865 	// 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1866 	for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
1867 
1868 	// 0x0C ARP Ethertype (0x0806)
1869 	*ptr++ = 0x08; *ptr++ = 0x06;
1870 
1871 	// 0x0E ARP header
1872 	*ptr++ = 0x00; *ptr++ = 0x01;	// Hardware address space; Ethernet = 1
1873 	*ptr++ = 0x08; *ptr++ = 0x00;	// Protocol address space; IP = 0x0800
1874 	*ptr++ = 6;						// Hardware address length
1875 	*ptr++ = 4;						// Protocol address length
1876 	*ptr++ = 0x00; *ptr++ = op;		// opcode; Request = 1, Response = 2
1877 
1878 	// 0x16 Sender hardware address (our MAC address)
1879 	for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
1880 
1881 	// 0x1C Sender protocol address
1882 	for (i=0; i<4; i++) *ptr++ = spa->b[i];
1883 
1884 	// 0x20 Target hardware address
1885 	for (i=0; i<6; i++) *ptr++ = tha->b[i];
1886 
1887 	// 0x26 Target protocol address
1888 	for (i=0; i<4; i++) *ptr++ = tpa->b[i];
1889 
1890 	// 0x2A Total ARP Packet length 42 bytes
1891 	mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
1892 	}
1893 
1894 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
1895 	{
1896 	const mDNSu16 *ptr = data;
1897 	while (length > 0) { length -= 2; sum += *ptr++; }
1898 	sum = (sum & 0xFFFF) + (sum >> 16);
1899 	sum = (sum & 0xFFFF) + (sum >> 16);
1900 	return(sum != 0xFFFF ? sum : 0);
1901 	}
1902 
1903 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
1904 	{
1905 	IPv6PseudoHeader ph;
1906 	ph.src = *src;
1907 	ph.dst = *dst;
1908 	ph.len.b[0] = length >> 24;
1909 	ph.len.b[1] = length >> 16;
1910 	ph.len.b[2] = length >> 8;
1911 	ph.len.b[3] = length;
1912 	ph.pro.b[0] = 0;
1913 	ph.pro.b[1] = 0;
1914 	ph.pro.b[2] = 0;
1915 	ph.pro.b[3] = protocol;
1916 	return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
1917 	}
1918 
1919 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
1920 	const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
1921 	{
1922 	int i;
1923 	mDNSOpaque16 checksum;
1924 	mDNSu8 *ptr = m->omsg.data;
1925 	// Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
1926 	// appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
1927 	// at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
1928 	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] } };
1929 	const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
1930 	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1931 	if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1932 
1933 	// 0x00 Destination address
1934 	for (i=0; i<6; i++) *ptr++ = dst->b[i];
1935 	// Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
1936 	// Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
1937 	// link with a pointless link-layer multicast.
1938 	// Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
1939 	// Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
1940 	// *ptr++ = 0x33;
1941 	// *ptr++ = 0x33;
1942 	// *ptr++ = 0xFF;
1943 	// *ptr++ = tpa->b[0xD];
1944 	// *ptr++ = tpa->b[0xE];
1945 	// *ptr++ = tpa->b[0xF];
1946 
1947 	// 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1948 	for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1949 
1950 	// 0x0C IPv6 Ethertype (0x86DD)
1951 	*ptr++ = 0x86; *ptr++ = 0xDD;
1952 
1953 	// 0x0E IPv6 header
1954 	*ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;		// Version, Traffic Class, Flow Label
1955 	*ptr++ = 0x00; *ptr++ = 0x20;									// Length
1956 	*ptr++ = 0x3A;													// Protocol == ICMPv6
1957 	*ptr++ = 0xFF;													// Hop Limit
1958 
1959 	// 0x16 Sender IPv6 address
1960 	for (i=0; i<16; i++) *ptr++ = spa->b[i];
1961 
1962 	// 0x26 Destination IPv6 address
1963 	for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
1964 
1965 	// 0x36 NDP header
1966 	*ptr++ = op;					// 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
1967 	*ptr++ = 0x00;					// Code
1968 	*ptr++ = 0x00; *ptr++ = 0x00;	// Checksum placeholder (0x38, 0x39)
1969 	*ptr++ = flags;
1970 	*ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
1971 
1972 	if (op == NDP_Sol)	// Neighbor Solicitation. The NDP "target" is the address we seek.
1973 		{
1974 		// 0x3E NDP target.
1975 		for (i=0; i<16; i++) *ptr++ = tpa->b[i];
1976 		// 0x4E Source Link-layer Address
1977 		// <http://www.ietf.org/rfc/rfc2461.txt>
1978 		// MUST NOT be included when the source IP address is the unspecified address.
1979 		// Otherwise, on link layers that have addresses this option MUST be included
1980 		// in multicast solicitations and SHOULD be included in unicast solicitations.
1981 		if (!mDNSIPv6AddressIsZero(*spa))
1982 			{
1983 			*ptr++ = NDP_SrcLL;	// Option Type 1 == Source Link-layer Address
1984 			*ptr++ = 0x01;		// Option length 1 (in units of 8 octets)
1985 			for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1986 			}
1987 		}
1988 	else			// Neighbor Advertisement. The NDP "target" is the address we're giving information about.
1989 		{
1990 		// 0x3E NDP target.
1991 		for (i=0; i<16; i++) *ptr++ = spa->b[i];
1992 		// 0x4E Target Link-layer Address
1993 		*ptr++ = NDP_TgtLL;	// Option Type 2 == Target Link-layer Address
1994 		*ptr++ = 0x01;		// Option length 1 (in units of 8 octets)
1995 		for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1996 		}
1997 
1998 	// 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
1999 	m->omsg.data[0x13] = ptr - &m->omsg.data[0x36];		// Compute actual length
2000 	checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2001 	m->omsg.data[0x38] = checksum.b[0];
2002 	m->omsg.data[0x39] = checksum.b[1];
2003 
2004 	mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2005 	}
2006 
2007 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2008 	{
2009 	owner->u.owner.vers     = 0;
2010 	owner->u.owner.seq      = m->SleepSeqNum;
2011 	owner->u.owner.HMAC     = m->PrimaryMAC;
2012 	owner->u.owner.IMAC     = intf->MAC;
2013 	owner->u.owner.password = zeroEthAddr;
2014 
2015 	// Don't try to compute the optlen until *after* we've set up the data fields
2016 	// 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
2017 	owner->opt              = kDNSOpt_Owner;
2018 	owner->optlen           = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2019 	}
2020 
2021 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2022 	{
2023 	if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2024 	else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2025 	}
2026 
2027 // Note about acceleration of announcements to facilitate automatic coalescing of
2028 // multiple independent threads of announcements into a single synchronized thread:
2029 // The announcements in the packet may be at different stages of maturity;
2030 // One-second interval, two-second interval, four-second interval, and so on.
2031 // After we've put in all the announcements that are due, we then consider
2032 // whether there are other nearly-due announcements that are worth accelerating.
2033 // To be eligible for acceleration, a record MUST NOT be older (further along
2034 // its timeline) than the most mature record we've already put in the packet.
2035 // In other words, younger records can have their timelines accelerated to catch up
2036 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2037 // Older records cannot have their timelines accelerated; this would just widen
2038 // the gap between them and their younger bretheren and get them even more out of sync.
2039 
2040 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2041 // the record list and/or question list.
2042 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2043 mDNSlocal void SendResponses(mDNS *const m)
2044 	{
2045 	int pktcount = 0;
2046 	AuthRecord *rr, *r2;
2047 	mDNSs32 maxExistingAnnounceInterval = 0;
2048 	const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2049 
2050 	m->NextScheduledResponse = m->timenow + 0x78000000;
2051 
2052 	if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2053 
2054 	for (rr = m->ResourceRecords; rr; rr=rr->next)
2055 		if (rr->ImmedUnicast)
2056 			{
2057 			mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2058 			mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2059 			v4.ip.v4 = rr->v4Requester;
2060 			v6.ip.v6 = rr->v6Requester;
2061 			if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2062 			if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2063 			if (rr->ImmedUnicast)
2064 				{
2065 				LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2066 				rr->ImmedUnicast = mDNSfalse;
2067 				}
2068 			}
2069 
2070 	// ***
2071 	// *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2072 	// ***
2073 
2074 	// Run through our list of records, and decide which ones we're going to announce on all interfaces
2075 	for (rr = m->ResourceRecords; rr; rr=rr->next)
2076 		{
2077 		while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2078 		if (TimeToAnnounceThisRecord(rr, m->timenow))
2079 			{
2080 			if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2081 				{
2082 				if (!rr->WakeUp.HMAC.l[0])
2083 					{
2084 					if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark;		// Send goodbye packet on all interfaces
2085 					}
2086 				else
2087 					{
2088 					LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2089 					SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
2090 					for (r2 = rr; r2; r2=r2->next)
2091 						if (r2->AnnounceCount && r2->resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC))
2092 							{
2093 							// For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2094 							// owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2095 							if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2096 								{
2097 								LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2098 									r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2099 								SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2100 								}
2101 							r2->LastAPTime = m->timenow;
2102 							// After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2103 							if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2104 							}
2105 					}
2106 				}
2107 			else if (ResourceRecordIsValidAnswer(rr))
2108 				{
2109 				if (rr->AddressProxy.type)
2110 					{
2111 					rr->AnnounceCount--;
2112 					rr->ThisAPInterval *= 2;
2113 					rr->LastAPTime = m->timenow;
2114 					if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2115 						{
2116 						LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2117 							rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2118 						SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2119 						}
2120 					else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2121 						{
2122 						LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2123 							rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2124 						SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2125 						}
2126 					}
2127 				else
2128 					{
2129 					rr->ImmedAnswer = mDNSInterfaceMark;		// Send on all interfaces
2130 					if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2131 						maxExistingAnnounceInterval = rr->ThisAPInterval;
2132 					if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2133 					}
2134 				}
2135 			}
2136 		}
2137 
2138 	// Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2139 	// Eligible records that are more than half-way to their announcement time are accelerated
2140 	for (rr = m->ResourceRecords; rr; rr=rr->next)
2141 		if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2142 			(rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2143 			TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2144 			!rr->AddressProxy.type && 					// Don't include ARP Annoucements when considering which records to accelerate
2145 			ResourceRecordIsValidAnswer(rr)))
2146 			rr->ImmedAnswer = mDNSInterfaceMark;		// Send on all interfaces
2147 
2148 	// When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2149 	// Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2150 	// which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2151 	// then all that means is that it won't get sent -- which would not be the end of the world.
2152 	for (rr = m->ResourceRecords; rr; rr=rr->next)
2153 		{
2154 		if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2155 			for (r2=m->ResourceRecords; r2; r2=r2->next)				// Scan list of resource records
2156 				if (RRTypeIsAddressType(r2->resrec.rrtype) &&			// For all address records (A/AAAA) ...
2157 					ResourceRecordIsValidAnswer(r2) &&					// ... which are valid for answer ...
2158 					rr->LastMCTime - r2->LastMCTime >= 0 &&				// ... which we have not sent recently ...
2159 					rr->resrec.rdatahash == r2->resrec.namehash &&		// ... whose name is the name of the SRV target
2160 					SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2161 					(rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2162 					r2->ImmedAdditional = r2->resrec.InterfaceID;		// ... then mark this address record for sending too
2163 		// We also make sure we send the DeviceInfo TXT record too, if necessary
2164 		// We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2165 		// DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2166 		if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2167 			if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2168 				{
2169 				if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2170 				else                            m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2171 				}
2172 		}
2173 
2174 	// If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2175 	// the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2176 	// then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2177 	// record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2178 	// -- 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
2179 	// -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2180 	for (rr = m->ResourceRecords; rr; rr=rr->next)
2181 		if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2182 			{
2183 			if (rr->ImmedAnswer)			// If we're sending this as answer, see that its whole RRSet is similarly marked
2184 				{
2185 				for (r2 = m->ResourceRecords; r2; r2=r2->next)
2186 					if (ResourceRecordIsValidAnswer(r2))
2187 						if (r2->ImmedAnswer != mDNSInterfaceMark &&
2188 							r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(r2, rr))
2189 							r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2190 				}
2191 			else if (rr->ImmedAdditional)	// If we're sending this as additional, see that its whole RRSet is similarly marked
2192 				{
2193 				for (r2 = m->ResourceRecords; r2; r2=r2->next)
2194 					if (ResourceRecordIsValidAnswer(r2))
2195 						if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(r2, rr))
2196 							r2->ImmedAdditional = rr->ImmedAdditional;
2197 				}
2198 			}
2199 
2200 	// Now set SendRNow state appropriately
2201 	for (rr = m->ResourceRecords; rr; rr=rr->next)
2202 		{
2203 		if (rr->ImmedAnswer == mDNSInterfaceMark)		// Sending this record on all appropriate interfaces
2204 			{
2205 			rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2206 			rr->ImmedAdditional = mDNSNULL;				// No need to send as additional if sending as answer
2207 			rr->LastMCTime      = m->timenow;
2208 			rr->LastMCInterface = rr->ImmedAnswer;
2209 			// If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2210 			if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2211 				{
2212 				rr->AnnounceCount--;
2213 				if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2214 					rr->ThisAPInterval *= 2;
2215 				rr->LastAPTime = m->timenow;
2216 				debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2217 				}
2218 			}
2219 		else if (rr->ImmedAnswer)						// Else, just respond to a single query on single interface:
2220 			{
2221 			rr->SendRNow        = rr->ImmedAnswer;		// Just respond on that interface
2222 			rr->ImmedAdditional = mDNSNULL;				// No need to send as additional too
2223 			rr->LastMCTime      = m->timenow;
2224 			rr->LastMCInterface = rr->ImmedAnswer;
2225 			}
2226 		SetNextAnnounceProbeTime(m, rr);
2227 		//if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2228 		}
2229 
2230 	// ***
2231 	// *** 2. Loop through interface list, sending records as appropriate
2232 	// ***
2233 
2234 	while (intf)
2235 		{
2236 		const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2237 		int numDereg    = 0;
2238 		int numAnnounce = 0;
2239 		int numAnswer   = 0;
2240 		mDNSu8 *responseptr = m->omsg.data;
2241 		mDNSu8 *newptr;
2242 		InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2243 
2244 		// First Pass. Look for:
2245 		// 1. Deregistering records that need to send their goodbye packet
2246 		// 2. Updated records that need to retract their old data
2247 		// 3. Answers and announcements we need to send
2248 		for (rr = m->ResourceRecords; rr; rr=rr->next)
2249 			{
2250 
2251 			// Skip this interface if the record InterfaceID is *Any and the record is not
2252 			// appropriate for the interface type.
2253 			if ((rr->SendRNow == intf->InterfaceID) &&
2254 				((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf)))
2255 				{
2256 					LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
2257 					rr->SendRNow = GetNextActiveInterfaceID(intf);
2258 				}
2259 			else if (rr->SendRNow == intf->InterfaceID)
2260 				{
2261 				RData  *OldRData    = rr->resrec.rdata;
2262 				mDNSu16 oldrdlength = rr->resrec.rdlength;
2263 				mDNSu8 active = (mDNSu8)
2264 					(rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
2265 					(m->SleepState != SleepState_Sleeping || intf->SPSAddr[0].type || intf->SPSAddr[1].type || intf->SPSAddr[2].type));
2266 				newptr = mDNSNULL;
2267 				if (rr->NewRData && active)
2268 					{
2269 					// See if we should send a courtesy "goodbye" for the old data before we replace it.
2270 					if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2271 						{
2272 						newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2273 						if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2274 						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
2275 						}
2276 					SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2277 					}
2278 
2279 				if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2280 					rr->resrec.rrclass |= kDNSClass_UniqueRRSet;		// Temporarily set the cache flush bit so PutResourceRecord will set it
2281 				newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2282 				rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;			// Make sure to clear cache flush bit back to normal state
2283 				if (newptr)
2284 					{
2285 					responseptr = newptr;
2286 					rr->RequireGoodbye = active;
2287 					if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2288 					else if (rr->LastAPTime == m->timenow) numAnnounce++; else numAnswer++;
2289 					}
2290 
2291 				if (rr->NewRData && active)
2292 					SetNewRData(&rr->resrec, OldRData, oldrdlength);
2293 
2294 				// The first time through (pktcount==0), if this record is verified unique
2295 				// (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2296 				if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2297 					rr->SendNSECNow = mDNSInterfaceMark;
2298 
2299 				if (newptr)		// If succeeded in sending, advance to next interface
2300 					{
2301 					// If sending on all interfaces, go to next interface; else we're finished now
2302 					if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2303 						rr->SendRNow = GetNextActiveInterfaceID(intf);
2304 					else
2305 						rr->SendRNow = mDNSNULL;
2306 					}
2307 				}
2308 			}
2309 
2310 		// Second Pass. Add additional records, if there's space.
2311 		newptr = responseptr;
2312 		for (rr = m->ResourceRecords; rr; rr=rr->next)
2313 			if (rr->ImmedAdditional == intf->InterfaceID)
2314 				if (ResourceRecordIsValidAnswer(rr))
2315 					{
2316 					// If we have at least one answer already in the packet, then plan to add additionals too
2317 					mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2318 
2319 					// If we're not planning to send any additionals, but this record is a unique one, then
2320 					// make sure we haven't already sent any other members of its RRSet -- if we have, then they
2321 					// will have had the cache flush bit set, so now we need to finish the job and send the rest.
2322 					if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2323 						{
2324 						const AuthRecord *a;
2325 						for (a = m->ResourceRecords; a; a=a->next)
2326 							if (a->LastMCTime      == m->timenow &&
2327 								a->LastMCInterface == intf->InterfaceID &&
2328 								SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2329 						}
2330 					if (!SendAdditional)					// If we don't want to send this after all,
2331 						rr->ImmedAdditional = mDNSNULL;		// then cancel its ImmedAdditional field
2332 					else if (newptr)						// Else, try to add it if we can
2333 						{
2334 						// The first time through (pktcount==0), if this record is verified unique
2335 						// (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2336 						if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2337 							rr->SendNSECNow = mDNSInterfaceMark;
2338 
2339 						if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2340 							rr->resrec.rrclass |= kDNSClass_UniqueRRSet;	// Temporarily set the cache flush bit so PutResourceRecord will set it
2341 						newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2342 						rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;		// Make sure to clear cache flush bit back to normal state
2343 						if (newptr)
2344 							{
2345 							responseptr = newptr;
2346 							rr->ImmedAdditional = mDNSNULL;
2347 							rr->RequireGoodbye = mDNStrue;
2348 							// If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2349 							// This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2350 							// when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2351 							// all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2352 							rr->LastMCTime      = m->timenow;
2353 							rr->LastMCInterface = intf->InterfaceID;
2354 							}
2355 						}
2356 					}
2357 
2358 		// Third Pass. Add NSEC records, if there's space.
2359 		// When we're generating an NSEC record in response to a specify query for that type
2360 		// (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2361 		// not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2362 		for (rr = m->ResourceRecords; rr; rr=rr->next)
2363 			if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2364 				{
2365 				AuthRecord nsec;
2366 				mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2367 				nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2368 				AssignDomainName(&nsec.namestorage, rr->resrec.name);
2369 				mDNSPlatformMemZero(nsec.rdatastorage.u.nsec.bitmap, sizeof(nsec.rdatastorage.u.nsec.bitmap));
2370 				for (r2 = m->ResourceRecords; r2; r2=r2->next)
2371 					if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2372 						{
2373 						if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2374 						else nsec.rdatastorage.u.nsec.bitmap[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2375 						}
2376 				newptr = responseptr;
2377 				if (!r2)	// If we successfully built our NSEC record, add it to the packet now
2378 					{
2379 					newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2380 					if (newptr) responseptr = newptr;
2381 					}
2382 
2383 				// If we successfully put the NSEC record, clear the SendNSECNow flag
2384 				// If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2385 				if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2386 					{
2387 					rr->SendNSECNow = mDNSNULL;
2388 					// Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2389 					for (r2 = rr->next; r2; r2=r2->next)
2390 						if (SameResourceRecordNameClassInterface(r2, rr))
2391 							if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2392 								r2->SendNSECNow = mDNSNULL;
2393 					}
2394 				}
2395 
2396 		if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2397 			{
2398 			// If we have data to send, add OWNER option if necessary, then send packet
2399 
2400 			if (OwnerRecordSpace)
2401 				{
2402 				AuthRecord opt;
2403 				mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2404 				opt.resrec.rrclass    = NormalMaxDNSMessageData;
2405 				opt.resrec.rdlength   = sizeof(rdataOPT);	// One option in this OPT record
2406 				opt.resrec.rdestimate = sizeof(rdataOPT);
2407 				SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2408 				newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2409 				if (newptr) { responseptr = newptr; LogSPS("SendResponses put   %s", ARDisplayString(m, &opt)); }
2410 				else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2411 					LogSPS("SendResponses: No space in packet for Owner OPT record (%d/%d/%d/%d) %s",
2412 						m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2413 				else
2414 					LogMsg("SendResponses: How did we fail to have space for Owner OPT record (%d/%d/%d/%d) %s",
2415 						m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2416 				}
2417 
2418 			debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2419 				numDereg,                 numDereg                 == 1 ? "" : "s",
2420 				numAnnounce,              numAnnounce              == 1 ? "" : "s",
2421 				numAnswer,                numAnswer                == 1 ? "" : "s",
2422 				m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2423 
2424 			if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
2425 			if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
2426 			if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2427 			if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
2428 			// There might be more things to send on this interface, so go around one more time and try again.
2429 			}
2430 		else	// Nothing more to send on this interface; go to next
2431 			{
2432 			const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
2433 			#if MDNS_DEBUGMSGS && 0
2434 			const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2435 			debugf(msg, intf, next);
2436 			#endif
2437 			intf = next;
2438 			pktcount = 0;		// When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2439 			}
2440 		}
2441 
2442 	// ***
2443 	// *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2444 	// ***
2445 
2446 	if (m->CurrentRecord)
2447 		LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2448 	m->CurrentRecord = m->ResourceRecords;
2449 	while (m->CurrentRecord)
2450 		{
2451 		rr = m->CurrentRecord;
2452 		m->CurrentRecord = rr->next;
2453 
2454 		if (rr->SendRNow)
2455 			{
2456 			if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
2457 				LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr->SendRNow, rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
2458 			rr->SendRNow = mDNSNULL;
2459 			}
2460 
2461 		if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2462 			{
2463 			if (rr->NewRData) CompleteRDataUpdate(m, rr);	// Update our rdata, clear the NewRData pointer, and return memory to the client
2464 
2465 			if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
2466 				{
2467 				// For Unicast, when we get the response from the server, we will call CompleteDeregistration
2468 				if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr);		// Don't touch rr after this
2469 				}
2470 			else
2471 				{
2472 				rr->ImmedAnswer  = mDNSNULL;
2473 				rr->ImmedUnicast = mDNSfalse;
2474 				rr->v4Requester  = zerov4Addr;
2475 				rr->v6Requester  = zerov6Addr;
2476 				}
2477 			}
2478 		}
2479 	verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
2480 	}
2481 
2482 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2483 // so we want to be lazy about how frequently we do it.
2484 // 1. If a cache record is currently referenced by *no* active questions,
2485 //    then we don't mind expiring it up to a minute late (who will know?)
2486 // 2. Else, if a cache record is due for some of its final expiration queries,
2487 //    we'll allow them to be late by up to 2% of the TTL
2488 // 3. Else, if a cache record has completed all its final expiration queries without success,
2489 //    and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2490 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2491 //    so allow at most 1/10 second lateness
2492 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2493 //    (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2494 #define CacheCheckGracePeriod(RR) (                                                   \
2495 	((RR)->CRActiveQuestion == mDNSNULL            ) ? (60 * mDNSPlatformOneSecond) : \
2496 	((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50)            : \
2497 	((RR)->resrec.rroriginalttl > 10               ) ? (mDNSPlatformOneSecond)      : \
2498 	((RR)->resrec.rroriginalttl > 0                ) ? (mDNSPlatformOneSecond/10)   : 0)
2499 
2500 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2501 
2502 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
2503 	{
2504 	if (m->rrcache_nextcheck[slot] - event > 0)
2505 		m->rrcache_nextcheck[slot] = event;
2506 	if (m->NextCacheCheck          - event > 0)
2507 		m->NextCacheCheck          = event;
2508 	}
2509 
2510 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2511 // rr->TimeRcvd
2512 // rr->resrec.rroriginalttl
2513 // rr->UnansweredQueries
2514 // rr->CRActiveQuestion
2515 mDNSlocal void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
2516 	{
2517 	rr->NextRequiredQuery = RRExpireTime(rr);
2518 
2519 	// If we have an active question, then see if we want to schedule a refresher query for this record.
2520 	// Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2521 	if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
2522 		{
2523 		rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
2524 		rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
2525 		verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2526 			(rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
2527 		}
2528 
2529 	ScheduleNextCacheCheckTime(m, HashSlot(rr->resrec.name), NextCacheCheckEvent(rr));
2530 	}
2531 
2532 #define kMinimumReconfirmTime                     ((mDNSu32)mDNSPlatformOneSecond *  5)
2533 #define kDefaultReconfirmTimeForWake              ((mDNSu32)mDNSPlatformOneSecond *  5)
2534 #define kDefaultReconfirmTimeForNoAnswer          ((mDNSu32)mDNSPlatformOneSecond *  5)
2535 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 30)
2536 
2537 mDNSlocal mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
2538 	{
2539 	if (interval < kMinimumReconfirmTime)
2540 		interval = kMinimumReconfirmTime;
2541 	if (interval > 0x10000000)	// Make sure interval doesn't overflow when we multiply by four below
2542 		interval = 0x10000000;
2543 
2544 	// If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2545 	if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
2546 		{
2547 		// Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2548 		// For all the reconfirmations in a given batch, we want to use the same random value
2549 		// so that the reconfirmation questions can be grouped into a single query packet
2550 		if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(0x3FFFFFFF);
2551 		interval += m->RandomReconfirmDelay % ((interval/3) + 1);
2552 		rr->TimeRcvd          = m->timenow - (mDNSs32)interval * 3;
2553 		rr->resrec.rroriginalttl     = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
2554 		SetNextCacheCheckTimeForRecord(m, rr);
2555 		}
2556 	debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2557 		RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
2558 	return(mStatus_NoError);
2559 	}
2560 
2561 #define MaxQuestionInterval         (3600 * mDNSPlatformOneSecond)
2562 
2563 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2564 // It also appends to the list of known answer records that need to be included,
2565 // and updates the forcast for the size of the known answer section.
2566 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
2567 	CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
2568 	{
2569 	mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353;
2570 	mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2571 	const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
2572 	mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
2573 	if (!newptr)
2574 		{
2575 		debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2576 		return(mDNSfalse);
2577 		}
2578 	else
2579 		{
2580 		mDNSu32 forecast = *answerforecast;
2581 		const mDNSu32 slot = HashSlot(&q->qname);
2582 		const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2583 		CacheRecord *rr;
2584 		CacheRecord **ka = *kalistptrptr;	// Make a working copy of the pointer we're going to update
2585 
2586 		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)				// If we have a resource record in our cache,
2587 			if (rr->resrec.InterfaceID == q->SendQNow &&					// received on this interface
2588 				!(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) &&		// which is a shared (i.e. not unique) record type
2589 				rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList &&	// which is not already in the known answer list
2590 				rr->resrec.rdlength <= SmallRecordLimit &&					// which is small enough to sensibly fit in the packet
2591 				SameNameRecordAnswersQuestion(&rr->resrec, q) &&			// which answers our question
2592 				rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >				// and its half-way-to-expiry time is at least 1 second away
2593 												mDNSPlatformOneSecond)		// (also ensures we never include goodbye records with TTL=1)
2594 				{
2595 				// We don't want to include unique records in the Known Answer section. The Known Answer section
2596 				// is intended to suppress floods of shared-record replies from many other devices on the network.
2597 				// That concept really does not apply to unique records, and indeed if we do send a query for
2598 				// which we have a unique record already in our cache, then including that unique record as a
2599 				// Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2600 
2601 				*ka = rr;	// Link this record into our known answer chain
2602 				ka = &rr->NextInKAList;
2603 				// We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2604 				forecast += 12 + rr->resrec.rdestimate;
2605 				// If we're trying to put more than one question in this packet, and it doesn't fit
2606 				// then undo that last question and try again next time
2607 				if (query->h.numQuestions > 1 && newptr + forecast >= limit)
2608 					{
2609 					debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
2610 						q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data);
2611 					query->h.numQuestions--;
2612 					ka = *kalistptrptr;		// Go back to where we started and retract these answer records
2613 					while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
2614 					return(mDNSfalse);		// Return false, so we'll try again in the next packet
2615 					}
2616 				}
2617 
2618 		// Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2619 		*queryptr        = newptr;				// Update the packet pointer
2620 		*answerforecast  = forecast;			// Update the forecast
2621 		*kalistptrptr    = ka;					// Update the known answer list pointer
2622 		if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
2623 
2624 		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)				// For every resource record in our cache,
2625 			if (rr->resrec.InterfaceID == q->SendQNow &&					// received on this interface
2626 				rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList &&	// which is not in the known answer list
2627 				SameNameRecordAnswersQuestion(&rr->resrec, q))				// which answers our question
2628 					{
2629 					rr->UnansweredQueries++;								// indicate that we're expecting a response
2630 					rr->LastUnansweredTime = m->timenow;
2631 					SetNextCacheCheckTimeForRecord(m, rr);
2632 					}
2633 
2634 		return(mDNStrue);
2635 		}
2636 	}
2637 
2638 // When we have a query looking for a specified name, but there appear to be no answers with
2639 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
2640 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
2641 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
2642 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
2643 // A typical reconfirmation scenario might go like this:
2644 // Depth 0: Name "myhost.local" has no address records
2645 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
2646 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
2647 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
2648 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
2649 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
2650 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
2651 	{
2652 	mDNSu32 slot;
2653 	CacheGroup *cg;
2654 	CacheRecord *cr;
2655 	debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
2656 	FORALL_CACHERECORDS(slot, cg, cr)
2657 		{
2658 		domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
2659 		if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
2660 			{
2661 			LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
2662 			mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
2663 			if (depth < 5) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
2664 			}
2665 		}
2666 	}
2667 
2668 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
2669 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
2670 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
2671 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
2672 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
2673 	{
2674 	CacheGroup *const cg = CacheGroupForName(m, HashSlot(name), namehash, name);
2675 	const CacheRecord *cr = cg ? cg->members : mDNSNULL;
2676 	while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
2677 	return(cr);
2678 	}
2679 
2680 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
2681 	{
2682 	CacheGroup *const cg = CacheGroupForName(m, HashSlot(&q->qname), q->qnamehash, &q->qname);
2683 	const CacheRecord *cr, *bestcr = mDNSNULL;
2684 	mDNSu32 bestmetric = 1000000;
2685 	for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
2686 		if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6)						// If record is PTR type, with long enough name,
2687 			if (cr != c0 && cr != c1)															// that's not one we've seen before,
2688 				if (SameNameRecordAnswersQuestion(&cr->resrec, q))								// and answers our browse query,
2689 					if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec))	// and is not our own advertised service...
2690 						{
2691 						mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
2692 						if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
2693 						}
2694 	return(bestcr);
2695 	}
2696 
2697 // Finds the three best Sleep Proxies we currently have in our cache
2698 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
2699 	{
2700 	sps[0] =                      FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
2701 	sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   mDNSNULL);
2702 	sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   sps[1]);
2703 	}
2704 
2705 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
2706 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
2707 	{
2708 	int i;
2709 	for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2710 	}
2711 
2712 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
2713 	{
2714 	int i;
2715 	for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2716 	}
2717 
2718 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
2719 	{
2720 	int i;
2721 	mDNSBool v4 = !intf->IPv4Available;		// If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
2722 	mDNSBool v6 = !intf->IPv6Available;		// If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
2723 	for (i=0; i<DupSuppressInfoSize; i++)
2724 		if (ds[i].InterfaceID == intf->InterfaceID)
2725 			{
2726 			if      (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
2727 			else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
2728 			if (v4 && v6) return(mDNStrue);
2729 			}
2730 	return(mDNSfalse);
2731 	}
2732 
2733 mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
2734 	{
2735 	int i, j;
2736 
2737 	// See if we have this one in our list somewhere already
2738 	for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
2739 
2740 	// If not, find a slot we can re-use
2741 	if (i >= DupSuppressInfoSize)
2742 		{
2743 		i = 0;
2744 		for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
2745 			if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
2746 				i = j;
2747 		}
2748 
2749 	// Record the info about this query we saw
2750 	ds[i].Time        = Time;
2751 	ds[i].InterfaceID = InterfaceID;
2752 	ds[i].Type        = Type;
2753 
2754 	return(i);
2755 	}
2756 
2757 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
2758 	{
2759 	int len, i, cnt;
2760 	mDNSInterfaceID InterfaceID = q->InterfaceID;
2761 	domainname *d = &q->qname;
2762 
2763 	// We can't send magic packets without knowing which interface to send it on.
2764 	if (InterfaceID == mDNSInterface_Any || InterfaceID == mDNSInterface_LocalOnly || InterfaceID == mDNSInterface_P2P)
2765 		{
2766 		LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
2767 		return;
2768 		}
2769 
2770 	// Split MAC@IPAddress and pass them separately
2771 	len = d->c[0];
2772 	i = 1;
2773 	cnt = 0;
2774 	for (i = 1; i < len; i++)
2775 		{
2776 		if (d->c[i] == '@')
2777 			{
2778 			char EthAddr[18];	// ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
2779 			char IPAddr[47];    // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
2780 			if (cnt != 5)
2781 				{
2782 				LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
2783 				return;
2784 				}
2785 			if ((i - 1) > (int) (sizeof(EthAddr) - 1))
2786 				{
2787 				LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
2788 				return;
2789 				}
2790 			if ((len - i) > (int)(sizeof(IPAddr) - 1))
2791 				{
2792 				LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
2793 				return;
2794 				}
2795 			mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
2796 			EthAddr[i - 1] = 0;
2797 			mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
2798 			IPAddr[len - i] = 0;
2799 			mDNSPlatformSendWakeupPacket(m, InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
2800 			return;
2801 			}
2802 		else if (d->c[i] == ':')
2803 			cnt++;
2804 		}
2805 	LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
2806 	}
2807 
2808 
2809 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
2810 	{
2811 	// If more than 90% of the way to the query time, we should unconditionally accelerate it
2812 	if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
2813 		return(mDNStrue);
2814 
2815 	// If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
2816 	if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
2817 		{
2818 		// We forecast: qname (n) type (2) class (2)
2819 		mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
2820 		const mDNSu32 slot = HashSlot(&q->qname);
2821 		const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2822 		const CacheRecord *rr;
2823 		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)				// If we have a resource record in our cache,
2824 			if (rr->resrec.rdlength <= SmallRecordLimit &&					// which is small enough to sensibly fit in the packet
2825 				SameNameRecordAnswersQuestion(&rr->resrec, q) &&			// which answers our question
2826 				rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 &&			// and it is less than half-way to expiry
2827 				rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0)// and we'll ask at least once again before NextRequiredQuery
2828 				{
2829 				// We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2830 				forecast += 12 + rr->resrec.rdestimate;
2831 				if (forecast >= 512) return(mDNSfalse);	// If this would add 512 bytes or more to the packet, don't accelerate
2832 				}
2833 		return(mDNStrue);
2834 		}
2835 
2836 	return(mDNSfalse);
2837 	}
2838 
2839 // How Standard Queries are generated:
2840 // 1. The Question Section contains the question
2841 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
2842 
2843 // How Probe Queries are generated:
2844 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
2845 // if some other host is already using *any* records with this name, we want to know about it.
2846 // 2. The Authority Section contains the proposed values we intend to use for one or more
2847 // of our records with that name (analogous to the Update section of DNS Update packets)
2848 // because if some other host is probing at the same time, we each want to know what the other is
2849 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
2850 
2851 mDNSlocal void SendQueries(mDNS *const m)
2852 	{
2853 	mDNSu32 slot;
2854 	CacheGroup *cg;
2855 	CacheRecord *cr;
2856 	AuthRecord *ar;
2857 	int pktcount = 0;
2858 	DNSQuestion *q;
2859 	// For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
2860 	mDNSs32 maxExistingQuestionInterval = 0;
2861 	const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2862 	CacheRecord *KnownAnswerList = mDNSNULL;
2863 
2864 	// 1. If time for a query, work out what we need to do
2865 
2866 	// We're expecting to send a query anyway, so see if any expiring cache records are close enough
2867 	// to their NextRequiredQuery to be worth batching them together with this one
2868 	FORALL_CACHERECORDS(slot, cg, cr)
2869 		if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
2870 			if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
2871 				{
2872 				debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
2873 				q = cr->CRActiveQuestion;
2874 				ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
2875 				// For uDNS queries (TargetQID non-zero) we adjust LastQTime,
2876 				// and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
2877 				if      (q->Target.type)                        q->SendQNow = mDNSInterfaceMark;	// If targeted query, mark it
2878 				else if (!mDNSOpaque16IsZero(q->TargetQID))     { q->LastQTime = m->timenow - q->ThisQInterval; cr->UnansweredQueries++; }
2879 				else if (q->SendQNow == mDNSNULL)               q->SendQNow = cr->resrec.InterfaceID;
2880 				else if (q->SendQNow != cr->resrec.InterfaceID) q->SendQNow = mDNSInterfaceMark;
2881 				}
2882 
2883 	// Scan our list of questions to see which:
2884 	//     *WideArea*  queries need to be sent
2885 	//     *unicast*   queries need to be sent
2886 	//     *multicast* queries we're definitely going to send
2887 	if (m->CurrentQuestion)
2888 		LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2889 	m->CurrentQuestion = m->Questions;
2890 	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
2891 		{
2892 		q = m->CurrentQuestion;
2893 		if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
2894 			{
2895 			mDNSu8       *qptr        = m->omsg.data;
2896 			const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
2897 
2898 			// 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
2899 			if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
2900 			if (q->LocalSocket)
2901 				{
2902 				InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
2903 				qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
2904 				mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL);
2905 				q->ThisQInterval    *= QuestionIntervalStep;
2906 				}
2907 			if (q->ThisQInterval > MaxQuestionInterval)
2908 				q->ThisQInterval = MaxQuestionInterval;
2909 			q->LastQTime         = m->timenow;
2910 			q->LastQTxTime       = m->timenow;
2911 			q->RecentAnswerPkts  = 0;
2912 			q->SendQNow          = mDNSNULL;
2913 			q->ExpectUnicastResp = NonZeroTime(m->timenow);
2914 			}
2915 		else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
2916 			{
2917 			//LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2918 			q->SendQNow = mDNSInterfaceMark;		// Mark this question for sending on all interfaces
2919 			if (maxExistingQuestionInterval < q->ThisQInterval)
2920 				maxExistingQuestionInterval = q->ThisQInterval;
2921 			}
2922 		// If m->CurrentQuestion wasn't modified out from under us, advance it now
2923 		// We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
2924 		// m->CurrentQuestion point to the right question
2925 		if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
2926 		}
2927 	while (m->CurrentQuestion)
2928 		{
2929 		LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2930 		m->CurrentQuestion = m->CurrentQuestion->next;
2931 		}
2932 	m->CurrentQuestion = mDNSNULL;
2933 
2934 	// Scan our list of questions
2935 	// (a) to see if there are any more that are worth accelerating, and
2936 	// (b) to update the state variables for *all* the questions we're going to send
2937 	// Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
2938 	// which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
2939 	// 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.
2940 	m->NextScheduledQuery = m->timenow + 0x78000000;
2941 	for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
2942 		{
2943 		if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow ||
2944 			(!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
2945 			{
2946 			// If at least halfway to next query time, advance to next interval
2947 			// If less than halfway to next query time, then
2948 			// treat this as logically a repeat of the last transmission, without advancing the interval
2949 			if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
2950 				{
2951 				//LogInfo("Accelerating %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2952 				q->SendQNow = mDNSInterfaceMark;	// Mark this question for sending on all interfaces
2953 				debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
2954 					q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
2955 				q->ThisQInterval *= QuestionIntervalStep;
2956 				if (q->ThisQInterval > MaxQuestionInterval)
2957 					q->ThisQInterval = MaxQuestionInterval;
2958 				else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
2959 						!(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
2960 					{
2961 					// Generally don't need to log this.
2962 					// It's not especially noteworthy if a query finds no results -- this usually happens for domain
2963 					// enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
2964 					// and when there simply happen to be no instances of the service the client is looking
2965 					// for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
2966 					debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
2967 						q->qname.c, DNSTypeName(q->qtype));
2968 					// Sending third query, and no answers yet; time to begin doubting the source
2969 					ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
2970 					}
2971 				}
2972 
2973 			// Mark for sending. (If no active interfaces, then don't even try.)
2974 			q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
2975 			if (q->SendOnAll)
2976 				{
2977 				q->SendQNow  = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
2978 				q->LastQTime = m->timenow;
2979 				}
2980 
2981 			// If we recorded a duplicate suppression for this question less than half an interval ago,
2982 			// then we consider it recent enough that we don't need to do an identical query ourselves.
2983 			ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
2984 
2985 			q->LastQTxTime      = m->timenow;
2986 			q->RecentAnswerPkts = 0;
2987 			if (q->RequestUnicast) q->RequestUnicast--;
2988 			}
2989 		// For all questions (not just the ones we're sending) check what the next scheduled event will be
2990 		// We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
2991 		SetNextQueryTime(m,q);
2992 		}
2993 
2994 	// 2. Scan our authoritative RR list to see what probes we might need to send
2995 
2996 	m->NextScheduledProbe = m->timenow + 0x78000000;
2997 
2998 	if (m->CurrentRecord)
2999 		LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3000 	m->CurrentRecord = m->ResourceRecords;
3001 	while (m->CurrentRecord)
3002 		{
3003 		ar = m->CurrentRecord;
3004 		m->CurrentRecord = ar->next;
3005 		if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique)	// For all records that are still probing...
3006 			{
3007 			// 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3008 			if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3009 				{
3010 				SetNextAnnounceProbeTime(m, ar);
3011 				}
3012 			// 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3013 			else if (ar->ProbeCount)
3014 				{
3015 				if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3016 					{
3017 					LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3018 					SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3019 					}
3020 				else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3021 					{
3022 					LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3023 					// IPv6 source = zero
3024 					// No target hardware address
3025 					// IPv6 target address is address we're probing
3026 					// Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3027 					SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3028 					}
3029 				// Mark for sending. (If no active interfaces, then don't even try.)
3030 				ar->SendRNow   = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3031 				ar->LastAPTime = m->timenow;
3032 				// When we have a late conflict that resets a record to probing state we use a special marker value greater
3033 				// than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3034 				if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3035 					ar->ProbeCount = DefaultProbeCountForTypeUnique;
3036 				ar->ProbeCount--;
3037 				SetNextAnnounceProbeTime(m, ar);
3038 				if (ar->ProbeCount == 0)
3039 					{
3040 					// If this is the last probe for this record, then see if we have any matching records
3041 					// on our duplicate list which should similarly have their ProbeCount cleared to zero...
3042 					AuthRecord *r2;
3043 					for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3044 						if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3045 							r2->ProbeCount = 0;
3046 					// ... then acknowledge this record to the client.
3047 					// We do this optimistically, just as we're about to send the third probe.
3048 					// This helps clients that both advertise and browse, and want to filter themselves
3049 					// from the browse results list, because it helps ensure that the registration
3050 					// confirmation will be delivered 1/4 second *before* the browse "add" event.
3051 					// A potential downside is that we could deliver a registration confirmation and then find out
3052 					// moments later that there's a name conflict, but applications have to be prepared to handle
3053 					// late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3054 					if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3055 					}
3056 				}
3057 			// else, if it has now finished probing, move it to state Verified,
3058 			// and update m->NextScheduledResponse so it will be announced
3059 			else
3060 				{
3061 				if (!ar->Acknowledged) AcknowledgeRecord(m, ar);	// Defensive, just in case it got missed somehow
3062 				ar->resrec.RecordType     = kDNSRecordTypeVerified;
3063 				ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3064 				ar->LastAPTime     = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3065 				SetNextAnnounceProbeTime(m, ar);
3066 				}
3067 			}
3068 		}
3069 	m->CurrentRecord = m->DuplicateRecords;
3070 	while (m->CurrentRecord)
3071 		{
3072 		ar = m->CurrentRecord;
3073 		m->CurrentRecord = ar->next;
3074 		if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3075 			AcknowledgeRecord(m, ar);
3076 		}
3077 
3078 	// 3. Now we know which queries and probes we're sending,
3079 	// go through our interface list sending the appropriate queries on each interface
3080 	while (intf)
3081 		{
3082 		const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3083 		mDNSu8 *queryptr = m->omsg.data;
3084 		InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3085 		if (KnownAnswerList) verbosedebugf("SendQueries:   KnownAnswerList set... Will continue from previous packet");
3086 		if (!KnownAnswerList)
3087 			{
3088 			// Start a new known-answer list
3089 			CacheRecord **kalistptr = &KnownAnswerList;
3090 			mDNSu32 answerforecast = OwnerRecordSpace;		// We start by assuming we'll need at least enough space to put the Owner Option
3091 
3092 			// Put query questions in this packet
3093 			for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3094 				{
3095 				if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3096 					{
3097 					debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3098 						SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting    ",
3099 						q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3100 
3101 					// If we're suppressing this question, or we successfully put it, update its SendQNow state
3102 					if (SuppressOnThisInterface(q->DupSuppress, intf) ||
3103 						BuildQuestion(m, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3104 						{
3105 						q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3106 						if (q->WakeOnResolveCount)
3107 							{
3108 							mDNSSendWakeOnResolve(m, q);
3109 							q->WakeOnResolveCount--;
3110 							}
3111 						}
3112 					}
3113 				}
3114 
3115 			// Put probe questions in this packet
3116 			for (ar = m->ResourceRecords; ar; ar=ar->next)
3117 				if (ar->SendRNow == intf->InterfaceID)
3118 					{
3119 					mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353;
3120 					mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3121 					const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3122 					// We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3123 					mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3124 					mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, (mDNSu16)(ar->resrec.rrclass | ucbit));
3125 					if (newptr)
3126 						{
3127 						queryptr       = newptr;
3128 						answerforecast = forecast;
3129 						ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3130 						ar->IncludeInProbe = mDNStrue;
3131 						verbosedebugf("SendQueries:   Put Question %##s (%s) probecount %d",
3132 							ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount);
3133 						}
3134 					}
3135 			}
3136 
3137 		// Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3138 		while (KnownAnswerList)
3139 			{
3140 			CacheRecord *ka = KnownAnswerList;
3141 			mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3142 			mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers,
3143 				&ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd, m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace);
3144 			if (newptr)
3145 				{
3146 				verbosedebugf("SendQueries:   Put %##s (%s) at %d - %d",
3147 					ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3148 				queryptr = newptr;
3149 				KnownAnswerList = ka->NextInKAList;
3150 				ka->NextInKAList = mDNSNULL;
3151 				}
3152 			else
3153 				{
3154 				// If we ran out of space and we have more than one question in the packet, that's an error --
3155 				// we shouldn't have put more than one question if there was a risk of us running out of space.
3156 				if (m->omsg.h.numQuestions > 1)
3157 					LogMsg("SendQueries:   Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3158 				m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3159 				break;
3160 				}
3161 			}
3162 
3163 		for (ar = m->ResourceRecords; ar; ar=ar->next)
3164 			if (ar->IncludeInProbe)
3165 				{
3166 				mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3167 				ar->IncludeInProbe = mDNSfalse;
3168 				if (newptr) queryptr = newptr;
3169 				else LogMsg("SendQueries:   How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3170 				}
3171 
3172 		if (queryptr > m->omsg.data)
3173 			{
3174 			if (OwnerRecordSpace)
3175 				{
3176 				AuthRecord opt;
3177 				mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3178 				opt.resrec.rrclass    = NormalMaxDNSMessageData;
3179 				opt.resrec.rdlength   = sizeof(rdataOPT);	// One option in this OPT record
3180 				opt.resrec.rdestimate = sizeof(rdataOPT);
3181 				SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3182 				LogSPS("SendQueries putting %s", ARDisplayString(m, &opt));
3183 				queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3184 					&opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3185 				if (!queryptr)
3186 					LogMsg("SendQueries: How did we fail to have space for the OPT record (%d/%d/%d/%d) %s",
3187 						m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3188 				if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3189 					if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3190 						LogMsg("SendQueries: Why did we generate oversized packet with OPT record %p %p %p (%d/%d/%d/%d) %s",
3191 							m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr,
3192 							m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3193 				}
3194 
3195 			if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3196 				LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3197 			debugf("SendQueries:   Sending %d Question%s %d Answer%s %d Update%s on %p",
3198 				m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
3199 				m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
3200 				m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3201 			if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
3202 			if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
3203 			if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3204 			if (++pktcount >= 1000)
3205 				{ LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3206 			// There might be more records left in the known answer list, or more questions to send
3207 			// on this interface, so go around one more time and try again.
3208 			}
3209 		else	// Nothing more to send on this interface; go to next
3210 			{
3211 			const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3212 			#if MDNS_DEBUGMSGS && 0
3213 			const char *const msg = next ? "SendQueries:   Nothing more on %p; moving to %p" : "SendQueries:   Nothing more on %p";
3214 			debugf(msg, intf, next);
3215 			#endif
3216 			intf = next;
3217 			}
3218 		}
3219 
3220 	// 4. Final housekeeping
3221 
3222 	// 4a. Debugging check: Make sure we announced all our records
3223 	for (ar = m->ResourceRecords; ar; ar=ar->next)
3224 		if (ar->SendRNow)
3225 			{
3226 			if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
3227 				LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar->SendRNow, ar->resrec.InterfaceID, ARDisplayString(m, ar));
3228 			ar->SendRNow = mDNSNULL;
3229 			}
3230 
3231 	// 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3232 	// that their interface which went away might come back again, the logic will want to send queries
3233 	// for those records, but we can't because their interface isn't here any more, so to keep the
3234 	// state machine ticking over we just pretend we did so.
3235 	// If the interface does not come back in time, the cache record will expire naturally
3236 	FORALL_CACHERECORDS(slot, cg, cr)
3237 		if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3238 			if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3239 				{
3240 				cr->UnansweredQueries++;
3241 				cr->CRActiveQuestion->SendQNow = mDNSNULL;
3242 				SetNextCacheCheckTimeForRecord(m, cr);
3243 				}
3244 
3245 	// 4c. Debugging check: Make sure we sent all our planned questions
3246 	// Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3247 	// we legitimately couldn't send because the interface is no longer available
3248 	for (q = m->Questions; q; q=q->next)
3249 		if (q->SendQNow)
3250 			{
3251 			DNSQuestion *x;
3252 			for (x = m->NewQuestions; x; x=x->next) if (x == q) break;	// Check if this question is a NewQuestion
3253 			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));
3254 			q->SendQNow = mDNSNULL;
3255 			}
3256 	}
3257 
3258 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password)
3259 	{
3260 	int i, j;
3261 	mDNSu8 *ptr = m->omsg.data;
3262 	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
3263 	if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
3264 
3265 	// 0x00 Destination address
3266 	for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3267 
3268 	// 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
3269 	for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
3270 
3271 	// 0x0C Ethertype (0x0842)
3272 	*ptr++ = 0x08;
3273 	*ptr++ = 0x42;
3274 
3275 	// 0x0E Wakeup sync sequence
3276 	for (i=0; i<6; i++) *ptr++ = 0xFF;
3277 
3278 	// 0x14 Wakeup data
3279 	for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3280 
3281 	// 0x74 Password
3282 	for (i=0; i<6; i++) *ptr++ = password->b[i];
3283 
3284 	mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3285 
3286 	// For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
3287 	// broadcast is the only reliable way to get a wakeup packet to the intended target machine.
3288 	// For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
3289 	// key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
3290 	// So, we send one of each, unicast first, then broadcast second.
3291 	for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
3292 	mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3293 	}
3294 
3295 // ***************************************************************************
3296 #if COMPILER_LIKES_PRAGMA_MARK
3297 #pragma mark -
3298 #pragma mark - RR List Management & Task Management
3299 #endif
3300 
3301 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
3302 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
3303 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
3304 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
3305 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
3306 	{
3307 	DNSQuestion *const q = m->CurrentQuestion;
3308 	mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
3309 
3310 	verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
3311 		q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
3312 
3313 	// Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
3314 	// But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
3315 	// send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
3316 	// we check to see if that query already has a unique local answer.
3317 	if (q->LOAddressAnswers)
3318 		{
3319 		LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
3320 			"LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
3321 			q->LOAddressAnswers);
3322 		return;
3323 		}
3324 
3325 	if (QuerySuppressed(q))
3326 		{
3327 		// If the query is suppressed, then we don't want to answer from the cache. But if this query is
3328 		// supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
3329 		// that are timing out, which we know are answered with Negative cache record when timing out.
3330 		if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
3331 			return;
3332 		}
3333 
3334 	// Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
3335 	// may be called twice, once when the record is received, and again when it's time to notify local clients.
3336 	// If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
3337 
3338 	rr->LastUsed = m->timenow;
3339 	if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
3340 		{
3341 		if (!rr->CRActiveQuestion) m->rrcache_active++;	// If not previously active, increment rrcache_active count
3342 		debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
3343 			rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
3344 		rr->CRActiveQuestion = q;						// We know q is non-null
3345 		SetNextCacheCheckTimeForRecord(m, rr);
3346 		}
3347 
3348 	// If this is:
3349 	// (a) a no-cache add, where we've already done at least one 'QM' query, or
3350 	// (b) a normal add, where we have at least one unique-type answer,
3351 	// then there's no need to keep polling the network.
3352 	// (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
3353 	// We do this for mDNS questions and uDNS one-shot questions, but not for
3354 	// uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
3355 	if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
3356 		(AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
3357 		if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
3358 			{
3359 			q->LastQTime        = m->timenow;
3360 			q->LastQTxTime      = m->timenow;
3361 			q->RecentAnswerPkts = 0;
3362 			q->ThisQInterval    = MaxQuestionInterval;
3363 			q->RequestUnicast   = mDNSfalse;
3364 			debugf("AnswerCurrentQuestionWithResourceRecord: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3365 			}
3366 
3367 	if (rr->DelayDelivery) return;		// We'll come back later when CacheRecordDeferredAdd() calls us
3368 
3369 	// Only deliver negative answers if client has explicitly requested them
3370 	if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
3371 		if (!AddRecord || !q->ReturnIntermed) return;
3372 
3373 	// For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
3374 	if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
3375 		{
3376 		mDNS_DropLockBeforeCallback();		// Allow client (and us) to legally make mDNS API calls
3377 		if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
3378 			{
3379 			CacheRecord neg;
3380 			MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
3381 			q->QuestionCallback(m, q, &neg.resrec, AddRecord);
3382 			}
3383 		else
3384 			q->QuestionCallback(m, q, &rr->resrec, AddRecord);
3385 		mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
3386 		}
3387 	// Note: Proceed with caution here because client callback function is allowed to do anything,
3388 	// including starting/stopping queries, registering/deregistering records, etc.
3389 
3390 	if (followcname && m->CurrentQuestion == q)
3391 		AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
3392 	}
3393 
3394 // New Questions are answered through AnswerNewQuestion. But there may not have been any
3395 // matching cache records for the questions when it is called. There are two possibilities.
3396 //
3397 // 1) There are no cache records
3398 // 2) There are cache records but the DNSServers between question and cache record don't match.
3399 //
3400 // In the case of (1), where there are no cache records and later we add them when we get a response,
3401 // CacheRecordAdd/CacheRecordDeferredAdd will take care of adding the cache and delivering the ADD
3402 // events to the application. If we already have a cache entry, then no ADD events are delivered
3403 // unless the RDATA has changed
3404 //
3405 // In the case of (2) where we had the cache records and did not answer because of the DNSServer mismatch,
3406 // we need to answer them whenever we change the DNSServer.  But we can't do it at the instant the DNSServer
3407 // changes because when we do the callback, the question can get deleted and the calling function would not
3408 // know how to handle it. So, we run this function from mDNS_Execute to handle DNSServer changes on the
3409 // question
3410 
3411 mDNSlocal void AnswerQuestionsForDNSServerChanges(mDNS *const m)
3412 	{
3413 	DNSQuestion *q;
3414 	DNSQuestion *qnext;
3415 	CacheRecord *rr;
3416 	mDNSu32 slot;
3417 	CacheGroup *cg;
3418 
3419 	if (m->CurrentQuestion)
3420 		LogMsg("AnswerQuestionsForDNSServerChanges: ERROR m->CurrentQuestion already set: %##s (%s)",
3421 				m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3422 
3423 	for (q = m->Questions; q && q != m->NewQuestions; q = qnext)
3424 		{
3425 		qnext = q->next;
3426 
3427 		// multicast or DNSServers did not change.
3428 		if (mDNSOpaque16IsZero(q->TargetQID)) continue;
3429 		if (!q->deliverAddEvents) continue;
3430 
3431 		// We are going to look through the cache for this question since it changed
3432 		// its DNSserver last time. Reset it so that we don't call them again. Calling
3433 		// them again will deliver duplicate events to the application
3434 		q->deliverAddEvents = mDNSfalse;
3435 		if (QuerySuppressed(q)) continue;
3436 		m->CurrentQuestion = q;
3437 		slot = HashSlot(&q->qname);
3438 		cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3439 		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3440 			{
3441 			if (SameNameRecordAnswersQuestion(&rr->resrec, q))
3442 				{
3443 				LogInfo("AnswerQuestionsForDNSServerChanges: Calling AnswerCurrentQuestionWithResourceRecord for question %p %##s using resource record %s",
3444 					q, q->qname.c, CRDisplayString(m, rr));
3445 				// When this question penalizes a DNS server and has no more DNS servers to pick, we normally
3446 				// deliver a negative cache response and suspend the question for 60 seconds (see uDNS_CheckCurrentQuestion).
3447 				// But sometimes we may already find the negative cache entry and deliver that here as the process
3448 				// of changing DNS servers. When the cache entry is about to expire, we will resend the question and
3449 				// that time, we need to make sure that we have a valid DNS server. Otherwise, we will deliver
3450 				// a negative cache response without trying the server.
3451 				if (!q->qDNSServer && !q->DuplicateOf && rr->resrec.RecordType == kDNSRecordTypePacketNegative)
3452 					{
3453 					DNSQuestion *qptr;
3454 					SetValidDNSServers(m, q);
3455 					q->qDNSServer = GetServerForQuestion(m, q);
3456 					for (qptr = q->next ; qptr; qptr = qptr->next)
3457 						if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
3458 					}
3459 				q->CurrentAnswers++;
3460 				if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3461 				if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3462 				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3463 				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
3464 				}
3465 			}
3466 		}
3467 		m->CurrentQuestion = mDNSNULL;
3468 	}
3469 
3470 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
3471 	{
3472 	rr->DelayDelivery = 0;
3473 	if (m->CurrentQuestion)
3474 		LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
3475 			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3476 	m->CurrentQuestion = m->Questions;
3477 	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3478 		{
3479 		DNSQuestion *q = m->CurrentQuestion;
3480 		if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3481 			AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3482 		if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3483 			m->CurrentQuestion = q->next;
3484 		}
3485 	m->CurrentQuestion = mDNSNULL;
3486 	}
3487 
3488 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSu32 slot)
3489 	{
3490 	const mDNSs32 threshhold = m->timenow + mDNSPlatformOneSecond;	// See if there are any records expiring within one second
3491 	const mDNSs32 start      = m->timenow - 0x10000000;
3492 	mDNSs32 delay = start;
3493 	CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
3494 	const CacheRecord *rr;
3495 	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3496 		if (threshhold - RRExpireTime(rr) >= 0)		// If we have records about to expire within a second
3497 			if (delay - RRExpireTime(rr) < 0)		// then delay until after they've been deleted
3498 				delay = RRExpireTime(rr);
3499 	if (delay - start > 0) return(NonZeroTime(delay));
3500 	else return(0);
3501 	}
3502 
3503 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
3504 // If new questions are created as a result of invoking client callbacks, they will be added to
3505 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3506 // rr is a new CacheRecord just received into our cache
3507 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3508 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3509 // which may change the record list and/or question list.
3510 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3511 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
3512 	{
3513 	DNSQuestion *q;
3514 
3515 	// We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
3516 	// counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
3517 	for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3518 		{
3519 		if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3520 			{
3521 			// If this question is one that's actively sending queries, and it's received ten answers within one
3522 			// second of sending the last query packet, then that indicates some radical network topology change,
3523 			// so reset its exponential backoff back to the start. We must be at least at the eight-second interval
3524 			// to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3525 			// because we will anyway send another query within a few seconds. The first reset query is sent out
3526 			// randomized over the next four seconds to reduce possible synchronization between machines.
3527 			if (q->LastAnswerPktNum != m->PktNum)
3528 				{
3529 				q->LastAnswerPktNum = m->PktNum;
3530 				if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
3531 					q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
3532 					{
3533 					LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3534 						q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
3535 					q->LastQTime      = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
3536 					q->ThisQInterval  = InitialQuestionInterval;
3537 					SetNextQueryTime(m,q);
3538 					}
3539 				}
3540 			verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
3541 				DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
3542 				&rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
3543 				rr->resrec.rDNSServer->port : zeroIPPort), q);
3544 			q->CurrentAnswers++;
3545 			q->unansweredQueries = 0;
3546 			if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3547 			if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3548 			if (q->CurrentAnswers > 4000)
3549 				{
3550 				static int msgcount = 0;
3551 				if (msgcount++ < 10)
3552 					LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3553 						q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
3554 				rr->resrec.rroriginalttl = 0;
3555 				rr->UnansweredQueries = MaxUnansweredQueries;
3556 				}
3557 			}
3558 		}
3559 
3560 	if (!rr->DelayDelivery)
3561 		{
3562 		if (m->CurrentQuestion)
3563 			LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3564 		m->CurrentQuestion = m->Questions;
3565 		while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3566 			{
3567 			q = m->CurrentQuestion;
3568 			if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3569 				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3570 			if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3571 				m->CurrentQuestion = q->next;
3572 			}
3573 		m->CurrentQuestion = mDNSNULL;
3574 		}
3575 
3576 	SetNextCacheCheckTimeForRecord(m, rr);
3577 	}
3578 
3579 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3580 // If new questions are created as a result of invoking client callbacks, they will be added to
3581 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3582 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3583 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3584 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3585 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3586 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3587 // which may change the record list and/or question list.
3588 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3589 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
3590 	{
3591 	LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
3592 	if (m->CurrentQuestion)
3593 		LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3594 	m->CurrentQuestion = m->Questions;
3595 	// We do this for *all* questions, not stopping when we get to m->NewQuestions,
3596 	// since we're not caching the record and we'll get no opportunity to do this later
3597 	while (m->CurrentQuestion)
3598 		{
3599 		DNSQuestion *q = m->CurrentQuestion;
3600 		if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3601 			AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache);	// QC_addnocache means "don't expect remove events for this"
3602 		if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3603 			m->CurrentQuestion = q->next;
3604 		}
3605 	m->CurrentQuestion = mDNSNULL;
3606 	}
3607 
3608 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3609 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3610 // If new questions are created as a result of invoking client callbacks, they will be added to
3611 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3612 // rr is an existing cache CacheRecord that just expired and is being deleted
3613 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3614 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3615 // which may change the record list and/or question list.
3616 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3617 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
3618 	{
3619 	if (m->CurrentQuestion)
3620 		LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3621 			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3622 	m->CurrentQuestion = m->Questions;
3623 
3624 	// We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3625 	// will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3626 	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3627 		{
3628 		DNSQuestion *q = m->CurrentQuestion;
3629 		// When a question enters suppressed state, we generate RMV events and generate a negative
3630 		// response. A cache may be present that answers this question e.g., cache entry generated
3631 		// before the question became suppressed. We need to skip the suppressed questions here as
3632 		// the RMV event has already been generated.
3633 		if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
3634 			{
3635 			verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
3636 			q->FlappingInterface1 = mDNSNULL;
3637 			q->FlappingInterface2 = mDNSNULL;
3638 
3639 			// When a question changes DNS server, it is marked with deliverAddEvents if we find any
3640 			// cache entry corresponding to the new DNS server. Before we deliver the ADD event, the
3641 			// cache entry may be removed in which case CurrentAnswers can be zero.
3642 			if (q->deliverAddEvents && !q->CurrentAnswers)
3643 				{
3644 				LogInfo("CacheRecordRmv: Question %p %##s (%s) deliverAddEvents set, DNSServer %#a:%d",
3645 					q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3646 					mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3647 				m->CurrentQuestion = q->next;
3648 				continue;
3649 				}
3650 			if (q->CurrentAnswers == 0)
3651 				LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3652 					q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3653 					mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3654 			else
3655 				{
3656 				q->CurrentAnswers--;
3657 				if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
3658 				if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
3659 				}
3660 			if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
3661 				{
3662 				if (q->CurrentAnswers == 0)
3663 					{
3664 					LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3665 						q->qname.c, DNSTypeName(q->qtype));
3666 					ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3667 					}
3668 				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
3669 				}
3670 			}
3671 		if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3672 			m->CurrentQuestion = q->next;
3673 		}
3674 	m->CurrentQuestion = mDNSNULL;
3675 	}
3676 
3677 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
3678 	{
3679 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3680 	unsigned int i;
3681 	for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
3682 #endif
3683 	e->next = m->rrcache_free;
3684 	m->rrcache_free = e;
3685 	m->rrcache_totalused--;
3686 	}
3687 
3688 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
3689 	{
3690 	CacheEntity *e = (CacheEntity *)(*cp);
3691 	//LogMsg("ReleaseCacheGroup:  Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3692 	if ((*cp)->rrcache_tail != &(*cp)->members)
3693 		LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3694 	//if ((*cp)->name != (domainname*)((*cp)->namestorage))
3695 	//	LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3696 	if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
3697 	(*cp)->name = mDNSNULL;
3698 	*cp = (*cp)->next;			// Cut record from list
3699 	ReleaseCacheEntity(m, e);
3700 	}
3701 
3702 mDNSlocal void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
3703 	{
3704 	//LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3705 	if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
3706 	r->resrec.rdata = mDNSNULL;
3707 	ReleaseCacheEntity(m, (CacheEntity *)r);
3708 	}
3709 
3710 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3711 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3712 // callbacks for old records are delivered before callbacks for newer records.
3713 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
3714 	{
3715 	CacheRecord **rp = &cg->members;
3716 
3717 	if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3718 	m->lock_rrcache = 1;
3719 
3720 	while (*rp)
3721 		{
3722 		CacheRecord *const rr = *rp;
3723 		mDNSs32 event = RRExpireTime(rr);
3724 		if (m->timenow - event >= 0)	// If expired, delete it
3725 			{
3726 			*rp = rr->next;				// Cut it from the list
3727 			verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3728 				m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
3729 			if (rr->CRActiveQuestion)	// If this record has one or more active questions, tell them it's going away
3730 				{
3731 				DNSQuestion *q = rr->CRActiveQuestion;
3732 				// When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3733 				// then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3734 				// before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3735 				// not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3736 				// a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3737 				// MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3738 				// don't ressurect them as they will deliver duplicate "No such Record" ADD events
3739 				if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
3740 					{
3741 					q->ThisQInterval = InitialQuestionInterval;
3742 					q->LastQTime     = m->timenow - q->ThisQInterval;
3743 					SetNextQueryTime(m, q);
3744 					}
3745 				CacheRecordRmv(m, rr);
3746 				m->rrcache_active--;
3747 				}
3748 			ReleaseCacheRecord(m, rr);
3749 			}
3750 		else							// else, not expired; see if we need to query
3751 			{
3752 			// If waiting to delay delivery, do nothing until then
3753 			if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
3754 				event = rr->DelayDelivery;
3755 			else
3756 				{
3757 				if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
3758 				if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3759 					{
3760 					if (m->timenow - rr->NextRequiredQuery < 0)		// If not yet time for next query
3761 						event = NextCacheCheckEvent(rr);			// then just record when we want the next query
3762 					else											// else trigger our question to go out now
3763 						{
3764 						// Set NextScheduledQuery to timenow so that SendQueries() will run.
3765 						// SendQueries() will see that we have records close to expiration, and send FEQs for them.
3766 						m->NextScheduledQuery = m->timenow;
3767 						// After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3768 						// which will correctly update m->NextCacheCheck for us.
3769 						event = m->timenow + 0x3FFFFFFF;
3770 						}
3771 					}
3772 				}
3773 			verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3774 				(event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
3775 			if (m->rrcache_nextcheck[slot] - event > 0)
3776 				m->rrcache_nextcheck[slot] = event;
3777 			rp = &rr->next;
3778 			}
3779 		}
3780 	if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
3781 	cg->rrcache_tail = rp;
3782 	m->lock_rrcache = 0;
3783 	}
3784 
3785 mDNSlocal void AnswerNewQuestion(mDNS *const m)
3786 	{
3787 	mDNSBool ShouldQueryImmediately = mDNStrue;
3788 	DNSQuestion *const q = m->NewQuestions;		// Grab the question we're going to answer
3789 	mDNSu32 slot = HashSlot(&q->qname);
3790 	CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3791 	AuthRecord *lr;
3792 	AuthGroup *ag;
3793 	mDNSBool AnsweredFromCache = mDNSfalse;
3794 
3795 	verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3796 
3797 	if (cg) CheckCacheExpiration(m, slot, cg);
3798 	if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
3799 	m->NewQuestions = q->next;
3800 	// Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3801 	// then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3802 	//
3803 	// Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3804 	// client callbacks, which may delete their own or any other question. Our mechanism for detecting
3805 	// whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3806 	// value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3807 	// that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3808 	// advanced it), that means the question was deleted, so we no longer need to worry about answering
3809 	// it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3810 	// values we computed for slot and cg are now stale and relate to a question that no longer exists).
3811 	//
3812 	// We can't use the usual m->CurrentQuestion mechanism for this because  CacheRecordDeferredAdd() and
3813 	// CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3814 	// Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3815 	// deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3816 
3817 	if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3818 	// This should be safe, because calling the client's question callback may cause the
3819 	// question list to be modified, but should not ever cause the rrcache list to be modified.
3820 	// If the client's question callback deletes the question, then m->CurrentQuestion will
3821 	// be advanced, and we'll exit out of the loop
3822 	m->lock_rrcache = 1;
3823 	if (m->CurrentQuestion)
3824 		LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3825 			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3826 	m->CurrentQuestion = q;		// Indicate which question we're answering, so we'll know if it gets deleted
3827 
3828 	if (q->NoAnswer == NoAnswer_Fail)
3829 		{
3830 		LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3831 		MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
3832 		q->NoAnswer = NoAnswer_Normal;		// Temporarily turn off answer suppression
3833 		AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
3834 		// Don't touch the question if it has been stopped already
3835 		if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail;		// Restore NoAnswer state
3836 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
3837 		}
3838 	if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit; }
3839 
3840 	// See if we want to tell it about LocalOnly records
3841 	if (m->CurrentRecord)
3842 		LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3843 	slot = AuthHashSlot(&q->qname);
3844 	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
3845 	if (ag)
3846 		{
3847 		m->CurrentRecord = ag->members;
3848 		while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
3849 			{
3850 			AuthRecord *rr = m->CurrentRecord;
3851 			m->CurrentRecord = rr->next;
3852 			//
3853 			// If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
3854 			// to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
3855 			//
3856 			// We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
3857 			// details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
3858 			// we handle both mDNSInterface_Any and scoped questions.
3859 
3860 			if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && q->InterfaceID == mDNSInterface_Any))
3861 				if (LocalOnlyRecordAnswersQuestion(rr, q))
3862 					{
3863 					AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
3864 					if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
3865 					}
3866 			}
3867 		}
3868 	m->CurrentRecord = mDNSNULL;
3869 
3870 	if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit; }
3871 
3872 	if (q->LOAddressAnswers)
3873 		{
3874 		LogInfo("AnswerNewQuestion: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
3875 			q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
3876 		goto exit;
3877 		}
3878 
3879 	// Before we go check the cache and ship this query on the wire, we have to be sure that there are
3880 	// no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
3881 	// need to just peek at them to see whether it will answer this question. If it would answer, pretend
3882 	// that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
3883 	// when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
3884 	if (ag)
3885 		{
3886 		lr = ag->NewLocalOnlyRecords;
3887 		while (lr)
3888 			{
3889 			if (LORecordAnswersAddressType(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
3890 				{
3891 				LogInfo("AnswerNewQuestion: Question %p %##s (%s) will be answered using new local auth records "
3892 					" LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
3893 				goto exit;
3894 				}
3895 			lr = lr->next;
3896 			}
3897 		}
3898 
3899 
3900 	// If we are not supposed to answer this question, generate a negative response.
3901 	// Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
3902 	if (QuerySuppressed(q)) { q->SuppressQuery = mDNSfalse; GenerateNegativeResponse(m); q->SuppressQuery = mDNStrue; }
3903 	else
3904 		{
3905 		CacheRecord *rr;
3906 		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3907 			if (SameNameRecordAnswersQuestion(&rr->resrec, q))
3908 				{
3909 				// SecsSinceRcvd is whole number of elapsed seconds, rounded down
3910 				mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
3911 				if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
3912 					{
3913 					LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
3914 						rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
3915 					continue;	// Go to next one in loop
3916 					}
3917 
3918 				// If this record set is marked unique, then that means we can reasonably assume we have the whole set
3919 				// -- we don't need to rush out on the network and query immediately to see if there are more answers out there
3920 				if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
3921 					ShouldQueryImmediately = mDNSfalse;
3922 				q->CurrentAnswers++;
3923 				if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3924 				if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3925 				AnsweredFromCache = mDNStrue;
3926 				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3927 				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
3928 				}
3929 			else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
3930 				ShouldQueryImmediately = mDNSfalse;
3931 		}
3932 	// We don't use LogInfo for this "Question deleted" message because it happens so routinely that
3933 	// it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
3934 	if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
3935 
3936 	// Neither a local record nor a cache entry could answer this question. If this question need to be retried
3937 	// with search domains, generate a negative response which will now retry after appending search domains.
3938 	// If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
3939 	// we will retry with search domains.
3940 	if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
3941 		{
3942 		LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3943 		GenerateNegativeResponse(m);
3944 		}
3945 
3946 	if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
3947 
3948 	// Note: When a query gets suppressed or retried with search domains, we de-activate the question.
3949 	// Hence we don't execute the following block of code for those cases.
3950 	if (ShouldQueryImmediately && ActiveQuestion(q))
3951 		{
3952 		debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3953 		q->ThisQInterval  = InitialQuestionInterval;
3954 		q->LastQTime      = m->timenow - q->ThisQInterval;
3955 		if (mDNSOpaque16IsZero(q->TargetQID))		// For mDNS, spread packets to avoid a burst of simultaneous queries
3956 			{
3957 			// Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
3958 			if (!m->RandomQueryDelay)
3959 				m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
3960 			q->LastQTime += m->RandomQueryDelay;
3961 			}
3962 		}
3963 
3964 	// IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
3965 	// In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
3966 	// answers for this question until *after* its scheduled transmission time, in which case
3967 	// m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
3968 	// ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
3969 	SetNextQueryTime(m,q);
3970 
3971 exit:
3972 	m->CurrentQuestion = mDNSNULL;
3973 	m->lock_rrcache = 0;
3974 	}
3975 
3976 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
3977 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
3978 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
3979 	{
3980 	mDNSu32 slot;
3981 	AuthGroup *ag;
3982 	DNSQuestion *q = m->NewLocalOnlyQuestions;		// Grab the question we're going to answer
3983 	m->NewLocalOnlyQuestions = q->next;				// Advance NewLocalOnlyQuestions to the next (if any)
3984 
3985 	debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3986 
3987 	if (m->CurrentQuestion)
3988 		LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3989 			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3990 	m->CurrentQuestion = q;		// Indicate which question we're answering, so we'll know if it gets deleted
3991 
3992 	if (m->CurrentRecord)
3993 		LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3994 
3995 	// 1. First walk the LocalOnly records answering the LocalOnly question
3996 	// 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
3997 	//    walk the ResourceRecords list delivering the answers
3998 	slot = AuthHashSlot(&q->qname);
3999 	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4000 	if (ag)
4001 		{
4002 		m->CurrentRecord = ag->members;
4003 		while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4004 			{
4005 			AuthRecord *rr = m->CurrentRecord;
4006 			m->CurrentRecord = rr->next;
4007 			if (LocalOnlyRecordAnswersQuestion(rr, q))
4008 				{
4009 				AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4010 				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
4011 				}
4012 			}
4013 		}
4014 
4015 	if (m->CurrentQuestion == q)
4016 		{
4017 		m->CurrentRecord = m->ResourceRecords;
4018 
4019 		while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
4020 			{
4021 			AuthRecord *rr = m->CurrentRecord;
4022 			m->CurrentRecord = rr->next;
4023 			if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4024 				{
4025 				AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4026 				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
4027 				}
4028 			}
4029 		}
4030 
4031 	m->CurrentQuestion = mDNSNULL;
4032 	m->CurrentRecord   = mDNSNULL;
4033 	}
4034 
4035 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
4036 	{
4037 	CacheEntity *e = mDNSNULL;
4038 
4039 	if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
4040 	m->lock_rrcache = 1;
4041 
4042 	// If we have no free records, ask the client layer to give us some more memory
4043 	if (!m->rrcache_free && m->MainCallback)
4044 		{
4045 		if (m->rrcache_totalused != m->rrcache_size)
4046 			LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4047 				m->rrcache_totalused, m->rrcache_size);
4048 
4049 		// We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4050 		// number of bogus records so that we keep growing our cache until the machine runs out of memory.
4051 		// To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
4052 		// and we're actively using less than 1/32 of that cache, then we purge all the unused records
4053 		// and recycle them, instead of allocating more memory.
4054 		if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
4055 			LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4056 				m->rrcache_size, m->rrcache_active);
4057 		else
4058 			{
4059 			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
4060 			m->MainCallback(m, mStatus_GrowCache);
4061 			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
4062 			}
4063 		}
4064 
4065 	// If we still have no free records, recycle all the records we can.
4066 	// Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4067 	if (!m->rrcache_free)
4068 		{
4069 		mDNSu32 oldtotalused = m->rrcache_totalused;
4070 		mDNSu32 slot;
4071 		for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4072 			{
4073 			CacheGroup **cp = &m->rrcache_hash[slot];
4074 			while (*cp)
4075 				{
4076 				CacheRecord **rp = &(*cp)->members;
4077 				while (*rp)
4078 					{
4079 					// Records that answer still-active questions are not candidates for recycling
4080 					// Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
4081 					if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
4082 						rp=&(*rp)->next;
4083 					else
4084 						{
4085 						CacheRecord *rr = *rp;
4086 						*rp = (*rp)->next;			// Cut record from list
4087 						ReleaseCacheRecord(m, rr);
4088 						}
4089 					}
4090 				if ((*cp)->rrcache_tail != rp)
4091 					verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
4092 				(*cp)->rrcache_tail = rp;
4093 				if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
4094 				else ReleaseCacheGroup(m, cp);
4095 				}
4096 			}
4097 		LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
4098 			oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
4099 		}
4100 
4101 	if (m->rrcache_free)	// If there are records in the free list, take one
4102 		{
4103 		e = m->rrcache_free;
4104 		m->rrcache_free = e->next;
4105 		if (++m->rrcache_totalused >= m->rrcache_report)
4106 			{
4107 			LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
4108 			if      (m->rrcache_report <  100) m->rrcache_report += 10;
4109 			else if (m->rrcache_report < 1000) m->rrcache_report += 100;
4110 			else                               m->rrcache_report += 1000;
4111 			}
4112 		mDNSPlatformMemZero(e, sizeof(*e));
4113 		}
4114 
4115 	m->lock_rrcache = 0;
4116 
4117 	return(e);
4118 	}
4119 
4120 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
4121 	{
4122 	CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
4123 	if (r)
4124 		{
4125 		r->resrec.rdata = (RData*)&r->smallrdatastorage;	// By default, assume we're usually going to be using local storage
4126 		if (RDLength > InlineCacheRDSize)			// If RDLength is too big, allocate extra storage
4127 			{
4128 			r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
4129 			if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
4130 			else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
4131 			}
4132 		}
4133 	return(r);
4134 	}
4135 
4136 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
4137 	{
4138 	mDNSu16 namelen = DomainNameLength(rr->name);
4139 	CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
4140 	if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
4141 	cg->next         = m->rrcache_hash[slot];
4142 	cg->namehash     = rr->namehash;
4143 	cg->members      = mDNSNULL;
4144 	cg->rrcache_tail = &cg->members;
4145 	cg->name         = (domainname*)cg->namestorage;
4146 	//LogMsg("GetCacheGroup: %-10s %d-byte cache name %##s",
4147 	//	(namelen > InlineCacheGroupNameSize) ? "Allocating" : "Inline", namelen, rr->name->c);
4148 	if (namelen > InlineCacheGroupNameSize) cg->name = mDNSPlatformMemAllocate(namelen);
4149 	if (!cg->name)
4150 		{
4151 		LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
4152 		ReleaseCacheEntity(m, (CacheEntity*)cg);
4153 		return(mDNSNULL);
4154 		}
4155 	AssignDomainName(cg->name, rr->name);
4156 
4157 	if (CacheGroupForRecord(m, slot, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
4158 	m->rrcache_hash[slot] = cg;
4159 	if (CacheGroupForRecord(m, slot, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
4160 
4161 	return(cg);
4162 	}
4163 
4164 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
4165 	{
4166 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
4167 		LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
4168 	// Make sure we mark this record as thoroughly expired -- we don't ever want to give
4169 	// a positive answer using an expired record (e.g. from an interface that has gone away).
4170 	// We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4171 	// summary deletion without giving the proper callback to any questions that are monitoring it.
4172 	// By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4173 	rr->TimeRcvd          = m->timenow - mDNSPlatformOneSecond * 60;
4174 	rr->UnansweredQueries = MaxUnansweredQueries;
4175 	rr->resrec.rroriginalttl     = 0;
4176 	SetNextCacheCheckTimeForRecord(m, rr);
4177 	}
4178 
4179 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
4180 	{
4181 	mDNSs32 time;
4182 	mDNSPlatformLock(m);
4183 	if (m->mDNS_busy)
4184 		{
4185 		LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
4186 		if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
4187 		}
4188 
4189 	if (m->timenow) time = m->timenow;
4190 	else            time = mDNS_TimeNow_NoLock(m);
4191 	mDNSPlatformUnlock(m);
4192 	return(time);
4193 	}
4194 
4195 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
4196 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
4197 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
4198 #define SetSPSProxyListChanged(X) do { \
4199 	if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
4200 	m->SPSProxyListChanged = (X); } while(0)
4201 
4202 // Called from mDNS_Execute() to expire stale proxy records
4203 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
4204 	{
4205 	m->CurrentRecord = list;
4206 	while (m->CurrentRecord)
4207 		{
4208 		AuthRecord *rr = m->CurrentRecord;
4209 		if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
4210 			{
4211 			// If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
4212 			// so we need to cease proxying for *all* records we may have, expired or not.
4213 			if (m->SPSSocket && m->timenow - rr->TimeExpire < 0)	// If proxy record not expired yet, update m->NextScheduledSPS
4214 				{
4215 				if (m->NextScheduledSPS - rr->TimeExpire > 0)
4216 					m->NextScheduledSPS = rr->TimeExpire;
4217 				}
4218 			else													// else proxy record expired, so remove it
4219 				{
4220 				LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
4221 					m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
4222 				SetSPSProxyListChanged(rr->resrec.InterfaceID);
4223 				mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4224 				// Don't touch rr after this -- memory may have been free'd
4225 				}
4226 			}
4227 		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4228 		// new records could have been added to the end of the list as a result of that call.
4229 		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
4230 			m->CurrentRecord = rr->next;
4231 		}
4232 	}
4233 
4234 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
4235 	{
4236 	while (m->CurrentRecord)
4237 		{
4238 		AuthRecord *rr = m->CurrentRecord;
4239 		if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
4240 			{
4241 			debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
4242 			rr->resrec.RecordType = kDNSRecordTypeShared;
4243 			AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
4244 			if (m->CurrentRecord == rr)	// If rr still exists in list, restore its state now
4245 				{
4246 				rr->resrec.RecordType = kDNSRecordTypeDeregistering;
4247 				rr->AnsweredLocalQ = mDNSfalse;
4248 				// SendResponses normally calls CompleteDeregistration after sending goodbyes.
4249 				// For LocalOnly records, we don't do that and hence we need to do that here.
4250 				if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
4251 				}
4252 			}
4253 		if (m->CurrentRecord == rr)		// If m->CurrentRecord was not auto-advanced, do it ourselves now
4254 			m->CurrentRecord = rr->next;
4255 		}
4256 	}
4257 
4258 mDNSlocal void TimeoutQuestions(mDNS *const m)
4259 	{
4260 	m->NextScheduledStopTime = m->timenow + 0x3FFFFFFF;
4261 	if (m->CurrentQuestion)
4262 		LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
4263 			DNSTypeName(m->CurrentQuestion->qtype));
4264 	m->CurrentQuestion = m->Questions;
4265 	while (m->CurrentQuestion)
4266 		{
4267 		DNSQuestion *const q = m->CurrentQuestion;
4268 		if (q->StopTime)
4269 			{
4270 			if (m->timenow - q->StopTime >= 0)
4271 				{
4272 				LogInfo("TimeoutQuestions: question %##s timed out, time %d", q->qname.c, m->timenow - q->StopTime);
4273 				GenerateNegativeResponse(m);
4274 				if (m->CurrentQuestion == q) q->StopTime = 0;
4275 				}
4276 			else
4277 				{
4278 				if (m->NextScheduledStopTime - q->StopTime > 0)
4279 					m->NextScheduledStopTime = q->StopTime;
4280 				}
4281 			}
4282 		// If m->CurrentQuestion wasn't modified out from under us, advance it now
4283 		// We can't do this at the start of the loop because GenerateNegativeResponse
4284 		// depends on having m->CurrentQuestion point to the right question
4285 		if (m->CurrentQuestion == q)
4286 			m->CurrentQuestion = q->next;
4287 		}
4288 	m->CurrentQuestion = mDNSNULL;
4289 	}
4290 
4291 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
4292 	{
4293 	mDNS_Lock(m);	// Must grab lock before trying to read m->timenow
4294 
4295 	if (m->timenow - m->NextScheduledEvent >= 0)
4296 		{
4297 		int i;
4298 		AuthRecord *head, *tail;
4299 		mDNSu32 slot;
4300 		AuthGroup *ag;
4301 
4302 		verbosedebugf("mDNS_Execute");
4303 
4304 		if (m->CurrentQuestion)
4305 			LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
4306 				m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4307 
4308 		if (m->CurrentRecord)
4309 			LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
4310 
4311 		// 1. If we're past the probe suppression time, we can clear it
4312 		if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
4313 
4314 		// 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4315 		if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
4316 
4317 		// 3. Purge our cache of stale old records
4318 		if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
4319 			{
4320 			mDNSu32 numchecked = 0;
4321 			m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
4322 			for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4323 				{
4324 				if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
4325 					{
4326 					CacheGroup **cp = &m->rrcache_hash[slot];
4327 					m->rrcache_nextcheck[slot] = m->timenow + 0x3FFFFFFF;
4328 					while (*cp)
4329 						{
4330 						debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
4331 						numchecked++;
4332 						CheckCacheExpiration(m, slot, *cp);
4333 						if ((*cp)->members) cp=&(*cp)->next;
4334 						else ReleaseCacheGroup(m, cp);
4335 						}
4336 					}
4337 				// Even if we didn't need to actually check this slot yet, still need to
4338 				// factor its nextcheck time into our overall NextCacheCheck value
4339 				if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
4340 					m->NextCacheCheck = m->rrcache_nextcheck[slot];
4341 				}
4342 			debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
4343 			}
4344 
4345 		if (m->timenow - m->NextScheduledSPS >= 0)
4346 			{
4347 			m->NextScheduledSPS = m->timenow + 0x3FFFFFFF;
4348 			CheckProxyRecords(m, m->DuplicateRecords);	// Clear m->DuplicateRecords first, then m->ResourceRecords
4349 			CheckProxyRecords(m, m->ResourceRecords);
4350 			}
4351 
4352 		SetSPSProxyListChanged(mDNSNULL);		// Perform any deferred BPF reconfiguration now
4353 
4354 		// Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
4355 		if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0) m->AnnounceOwner = 0;
4356 
4357 		if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
4358 			{
4359 			m->DelaySleep = 0;
4360 			if (m->SleepState == SleepState_Transferring)
4361 				{
4362 				LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
4363 				BeginSleepProcessing(m);
4364 				}
4365 			}
4366 
4367 		// 4. See if we can answer any of our new local questions from the cache
4368 		for (i=0; m->NewQuestions && i<1000; i++)
4369 			{
4370 			if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
4371 			AnswerNewQuestion(m);
4372 			}
4373 		if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4374 
4375 		// Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
4376 		// we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
4377 		for (i=0; i<1000 && m->LocalRemoveEvents; i++)
4378 			{
4379 			m->LocalRemoveEvents = mDNSfalse;
4380 			m->CurrentRecord = m->ResourceRecords;
4381 			CheckRmvEventsForLocalRecords(m);
4382 			// Walk the LocalOnly records and deliver the RMV events
4383 			for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4384 				for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4385 					{
4386 					m->CurrentRecord = ag->members;
4387 					if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
4388 					}
4389 			}
4390 
4391 		if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
4392 
4393 		for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
4394 		if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4395 
4396 		head = tail = mDNSNULL;
4397 		for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
4398 			{
4399 			AuthRecord *rr = m->NewLocalRecords;
4400 			m->NewLocalRecords = m->NewLocalRecords->next;
4401 			if (LocalRecordReady(rr))
4402 				{
4403 				debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4404 				AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4405 				}
4406 			else if (!rr->next)
4407 				{
4408 				// If we have just one record that is not ready, we don't have to unlink and
4409 				// reinsert. As the NewLocalRecords will be NULL for this case, the loop will
4410 				// terminate and set the NewLocalRecords to rr.
4411 				debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
4412 				if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
4413 					LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
4414 
4415 				head = rr;
4416 				}
4417 			else
4418 				{
4419 				AuthRecord **p = &m->ResourceRecords;	// Find this record in our list of active records
4420 				debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
4421 				// if this is the first record we are skipping, move to the end of the list.
4422 				// if we have already skipped records before, append it at the end.
4423 				while (*p && *p != rr) p=&(*p)->next;
4424 				if (*p) *p = rr->next;					// Cut this record from the list
4425 				else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
4426 				if (!head)
4427 					{
4428 					while (*p) p=&(*p)->next;
4429 					*p = rr;
4430 					head = tail = rr;
4431 					}
4432 				else
4433 					{
4434 					tail->next = rr;
4435 					tail = rr;
4436 					}
4437 				rr->next = mDNSNULL;
4438 				}
4439 			}
4440 		m->NewLocalRecords = head;
4441 		debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
4442 
4443 		if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
4444 
4445 		// Check to see if we have any new LocalOnly/P2P records to examine for delivering
4446 		// to our local questions
4447 		if (m->NewLocalOnlyRecords)
4448 			{
4449 			m->NewLocalOnlyRecords = mDNSfalse;
4450 			for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4451 				for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4452 					{
4453 					for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
4454 						{
4455 						AuthRecord *rr = ag->NewLocalOnlyRecords;
4456 						ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
4457 						// LocalOnly records should always be ready as they never probe
4458 						if (LocalRecordReady(rr))
4459 							{
4460 							debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4461 							AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4462 							}
4463 						else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
4464 						}
4465 					// We limit about 100 per AuthGroup that can be serviced at a time
4466 					if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
4467 					}
4468 			}
4469 
4470 		// 5. Some questions may have picked a new DNS server and the cache may answer these questions now.
4471 		AnswerQuestionsForDNSServerChanges(m);
4472 
4473 		// 6. See what packets we need to send
4474 		if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
4475 			DiscardDeregistrations(m);
4476 		if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
4477 			{
4478 			// If the platform code is ready, and we're not suppressing packet generation right now
4479 			// then send our responses, probes, and questions.
4480 			// We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
4481 			// We send queries next, because there might be final-stage probes that complete their probing here, causing
4482 			// them to advance to announcing state, and we want those to be included in any announcements we send out.
4483 			// Finally, we send responses, including the previously mentioned records that just completed probing.
4484 			m->SuppressSending = 0;
4485 
4486 			// 7. Send Query packets. This may cause some probing records to advance to announcing state
4487 			if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
4488 			if (m->timenow - m->NextScheduledQuery >= 0)
4489 				{
4490 				DNSQuestion *q;
4491 				LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
4492 					m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
4493 				m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
4494 				for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4495 					if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
4496 						LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4497 				}
4498 			if (m->timenow - m->NextScheduledProbe >= 0)
4499 				{
4500 				debugf("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
4501 					m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
4502 				m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
4503 				}
4504 
4505 			// 8. Send Response packets, including probing records just advanced to announcing state
4506 			if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
4507 			if (m->timenow - m->NextScheduledResponse >= 0)
4508 				{
4509 				debugf("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4510 				m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
4511 				}
4512 			}
4513 
4514 		// Clear RandomDelay values, ready to pick a new different value next time
4515 		m->RandomQueryDelay     = 0;
4516 		m->RandomReconfirmDelay = 0;
4517 
4518 		if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
4519 #ifndef UNICAST_DISABLED
4520 		if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
4521 		if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
4522 		if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
4523 #endif
4524 		}
4525 
4526 	// Note about multi-threaded systems:
4527 	// On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4528 	// performing mDNS API operations that change our next scheduled event time.
4529 	//
4530 	// On multi-threaded systems (like the current Windows implementation) that have a single main thread
4531 	// calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4532 	// of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4533 	// signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4534 	// more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4535 	// in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4536 	// does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4537 	// without blocking. This avoids the race condition between the signal from the other thread arriving
4538 	// just *before* or just *after* the main thread enters the blocking primitive.
4539 	//
4540 	// On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4541 	// with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4542 	// set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4543 	// callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4544 	// by the time it gets to the timer callback function).
4545 
4546 	mDNS_Unlock(m);		// Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4547 	return(m->NextScheduledEvent);
4548 	}
4549 
4550 mDNSlocal void SuspendLLQs(mDNS *m)
4551 	{
4552 	DNSQuestion *q;
4553 	for (q = m->Questions; q; q = q->next)
4554 		if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
4555 			{ q->ReqLease = 0; sendLLQRefresh(m, q); }
4556 	}
4557 
4558 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
4559 	{
4560 	AuthRecord *rr;
4561 	mDNSu32 slot;
4562 	AuthGroup *ag;
4563 
4564 	slot = AuthHashSlot(&q->qname);
4565 	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4566 	if (ag)
4567 		{
4568 		for (rr = ag->members; rr; rr=rr->next)
4569 			// Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
4570 			if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
4571 				{
4572 				LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
4573 				return mDNStrue;
4574 				}
4575 		}
4576 	return mDNSfalse;
4577 	}
4578 
4579 // ActivateUnicastQuery() is called from three places:
4580 // 1. When a new question is created
4581 // 2. On wake from sleep
4582 // 3. When the DNS configuration changes
4583 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
4584 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
4585 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
4586 	{
4587 	// For now this AutoTunnel stuff is specific to Mac OS X.
4588 	// In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
4589 #if APPLE_OSX_mDNSResponder
4590 	// Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
4591 	// Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
4592 	// caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
4593 	// To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
4594 	// returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
4595 	// as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
4596 
4597 	if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
4598 		!SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
4599 		{
4600 		question->NoAnswer = NoAnswer_Suspended;
4601 		AddNewClientTunnel(m, question);
4602 		return;
4603 		}
4604 #endif // APPLE_OSX_mDNSResponder
4605 
4606 	if (!question->DuplicateOf)
4607 		{
4608 		debugf("ActivateUnicastQuery: %##s %s%s%s",
4609 			question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
4610 		question->CNAMEReferrals = 0;
4611 		if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
4612 		if (question->LongLived)
4613 			{
4614 			question->state = LLQ_InitialRequest;
4615 			question->id = zeroOpaque64;
4616 			question->servPort = zeroIPPort;
4617 			if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
4618 			}
4619 		// If the question has local answers, then we don't want answers from outside
4620 		if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
4621 			{
4622 			question->ThisQInterval = InitialQuestionInterval;
4623 			question->LastQTime     = m->timenow - question->ThisQInterval;
4624 			SetNextQueryTime(m, question);
4625 			}
4626 		}
4627 	}
4628 
4629 // Caller should hold the lock
4630 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
4631 	CallbackBeforeStartQuery BeforeStartCallback, void *context)
4632 	{
4633 	DNSQuestion *q;
4634 	DNSQuestion *restart = mDNSNULL;
4635 
4636 	if (!m->mDNS_busy) LogMsg("mDNSCoreRestartAddressQueries: ERROR!! Lock not held");
4637 
4638 	// 1. Flush the cache records
4639 	if (flushCacheRecords) flushCacheRecords(m);
4640 
4641 	// 2. Even though we may have purged the cache records above, before it can generate RMV event
4642 	// we are going to stop the question. Hence we need to deliver the RMV event before we
4643 	// stop the question.
4644 	//
4645 	// CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
4646 	// application callback can potentially stop the current question (detected by CurrentQuestion) or
4647 	// *any* other question which could be the next one that we may process here. RestartQuestion
4648 	// points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
4649 	// if the "next" question is stopped while the CurrentQuestion is stopped
4650 
4651 	if (m->RestartQuestion)
4652 		LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
4653 			m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
4654 
4655 	m->RestartQuestion = m->Questions;
4656 	while (m->RestartQuestion)
4657 		{
4658 		q = m->RestartQuestion;
4659 		m->RestartQuestion = q->next;
4660 		// GetZoneData questions are referenced by other questions (original query that started the GetZoneData
4661 		// question)  through their "nta" pointer. Normally when the original query stops, it stops the
4662 		// GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
4663 		// question followed by the original query that refers to this GetZoneData question, we will end up
4664 		// freeing the GetZoneData question and then start the "freed" question at the end.
4665 
4666 		if (IsGetZoneDataQuestion(q))
4667 			{
4668 			DNSQuestion *refq = q->next;
4669 			LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4670 			// debug stuff, we just try to find the referencing question and don't do much with it
4671 			while (refq)
4672 				{
4673 				if (q == &refq->nta->question)
4674 					{
4675 					LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
4676 					}
4677 				refq = refq->next;
4678 				}
4679 			continue;
4680 			}
4681 
4682 		// This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
4683 		if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
4684 
4685 		// If the search domains did not change, then we restart all the queries. Otherwise, only
4686 		// for queries for which we "might" have appended search domains ("might" because we may
4687 		// find results before we apply search domains even though AppendSearchDomains is set to 1)
4688 		if (!SearchDomainsChanged || q->AppendSearchDomains)
4689 			{
4690 			// NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
4691 			// LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
4692 			// LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
4693 			// /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
4694 			// But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
4695 			// it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
4696 			// for the original query using these cache entries as ADDs were never delivered using these cache
4697 			// entries and hence this order is needed.
4698 
4699 			// If the query is suppressed, the RMV events won't be delivered
4700 			if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
4701 
4702 			// SuppressQuery status does not affect questions that are answered using local records
4703 			if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
4704 
4705 			LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
4706 				q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
4707 			mDNS_StopQuery_internal(m, q);
4708 			// Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
4709 			// and then search domains should be appended. At the beginning, qnameOrig was NULL.
4710 			if (q->qnameOrig)
4711 				{
4712 				LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
4713 				AssignDomainName(&q->qname, q->qnameOrig);
4714 				mDNSPlatformMemFree(q->qnameOrig);
4715 				q->qnameOrig = mDNSNULL;
4716 				q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
4717 				}
4718 			q->SearchListIndex = 0;
4719 			q->next = restart;
4720 			restart = q;
4721 			}
4722 		}
4723 
4724 	// 3. Callback before we start the query
4725 	if (BeforeStartCallback) BeforeStartCallback(m, context);
4726 
4727 	// 4. Restart all the stopped queries
4728 	while (restart)
4729 		{
4730 		q = restart;
4731 		restart = restart->next;
4732 		q->next = mDNSNULL;
4733 		LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4734 		mDNS_StartQuery_internal(m, q);
4735 		}
4736 	}
4737 
4738 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
4739 	{
4740 	DNSQuestion *q;
4741 
4742 #ifndef UNICAST_DISABLED
4743 	// Retrigger all our uDNS questions
4744 	if (m->CurrentQuestion)
4745 		LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
4746 			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4747 	m->CurrentQuestion = m->Questions;
4748 	while (m->CurrentQuestion)
4749 		{
4750 		q = m->CurrentQuestion;
4751 		m->CurrentQuestion = m->CurrentQuestion->next;
4752 		if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
4753 		}
4754 #endif
4755 
4756 	// Retrigger all our mDNS questions
4757 	for (q = m->Questions; q; q=q->next)				// Scan our list of questions
4758 		if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
4759 			{
4760 			q->ThisQInterval    = InitialQuestionInterval;	// MUST be > zero for an active question
4761 			q->RequestUnicast   = 2;						// Set to 2 because is decremented once *before* we check it
4762 			q->LastQTime        = m->timenow - q->ThisQInterval;
4763 			q->RecentAnswerPkts = 0;
4764 			ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
4765 			m->NextScheduledQuery = m->timenow;
4766 			}
4767 	}
4768 
4769 // ***************************************************************************
4770 #if COMPILER_LIKES_PRAGMA_MARK
4771 #pragma mark -
4772 #pragma mark - Power Management (Sleep/Wake)
4773 #endif
4774 
4775 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
4776 	{
4777 #ifndef IDLESLEEPCONTROL_DISABLED
4778 	mDNSBool allowSleep = mDNStrue;
4779 	char     reason[128];
4780 
4781 	reason[0] = 0;
4782 
4783 	if (m->SystemSleepOnlyIfWakeOnLAN)
4784 		{
4785 		// Don't sleep if we are a proxy for any services
4786 		if (m->ProxyRecords)
4787 			{
4788 			allowSleep = mDNSfalse;
4789 			mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
4790 			LogInfo("Sleep disabled because we are proxying %d records", m->ProxyRecords);
4791 			}
4792 
4793 		if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
4794 			{
4795 			// Scan the list of active interfaces
4796 			NetworkInterfaceInfo *intf;
4797 			for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4798 				{
4799 				if (intf->McastTxRx && !intf->Loopback)
4800 					{
4801 					// Disallow sleep if this interface doesn't support NetWake
4802 					if (!intf->NetWake)
4803 						{
4804 						allowSleep = mDNSfalse;
4805 						mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
4806 						LogInfo("Sleep disabled because %s does not support NetWake", intf->ifname);
4807 						break;
4808 						}
4809 
4810 					// Disallow sleep if there is no sleep proxy server
4811 					if (FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL) == mDNSNULL)
4812 						{
4813 						allowSleep = mDNSfalse;
4814 						mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
4815 						LogInfo("Sleep disabled because %s has no sleep proxy", intf->ifname);
4816 						break;
4817 						}
4818 					}
4819 				}
4820 			}
4821 		}
4822 
4823 	// Call the platform code to enable/disable sleep
4824 	mDNSPlatformSetAllowSleep(m, allowSleep, reason);
4825 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
4826 	}
4827 
4828 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
4829 	{
4830 	const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
4831 	const int sps = intf->NextSPSAttempt / 3;
4832 	AuthRecord *rr;
4833 
4834 	if (!intf->SPSAddr[sps].type)
4835 		{
4836 		intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
4837 		if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
4838 			m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
4839 		LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
4840 		goto exit;
4841 		}
4842 
4843 	// Mark our mDNS records (not unicast records) for transfer to SPS
4844 	if (mDNSOpaque16IsZero(id))
4845 		for (rr = m->ResourceRecords; rr; rr=rr->next)
4846 			if (rr->resrec.RecordType > kDNSRecordTypeDeregistering)
4847 				if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
4848 					if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
4849 						rr->SendRNow = mDNSInterfaceMark;	// mark it now
4850 
4851 	while (1)
4852 		{
4853 		mDNSu8 *p = m->omsg.data;
4854 		// To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
4855 		// For now we follow that same logic for SPS registrations too.
4856 		// If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
4857 		// initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
4858 		InitializeDNSMessage(&m->omsg.h, mDNSOpaque16IsZero(id) ? mDNS_NewMessageID(m) : id, UpdateReqFlags);
4859 
4860 		for (rr = m->ResourceRecords; rr; rr=rr->next)
4861 			if (rr->SendRNow || (!mDNSOpaque16IsZero(id) && !AuthRecord_uDNS(rr) && mDNSSameOpaque16(rr->updateid, id) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0))
4862 				if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
4863 					{
4864 					mDNSu8 *newptr;
4865 					const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
4866 					if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
4867 						rr->resrec.rrclass |= kDNSClass_UniqueRRSet;	// Temporarily set the 'unique' bit so PutResourceRecord will set it
4868 					newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
4869 					rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;		// Make sure to clear 'unique' bit back to normal state
4870 					if (!newptr)
4871 						LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
4872 					else
4873 						{
4874 						LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, rr));
4875 						rr->SendRNow       = mDNSNULL;
4876 						rr->ThisAPInterval = mDNSPlatformOneSecond;
4877 						rr->LastAPTime     = m->timenow;
4878 						rr->updateid       = m->omsg.h.id;
4879 						if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4880 							m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
4881 						p = newptr;
4882 						}
4883 					}
4884 
4885 		if (!m->omsg.h.mDNS_numUpdates) break;
4886 		else
4887 			{
4888 			AuthRecord opt;
4889 			mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
4890 			opt.resrec.rrclass    = NormalMaxDNSMessageData;
4891 			opt.resrec.rdlength   = sizeof(rdataOPT) * 2;	// Two options in this OPT record
4892 			opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
4893 			opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
4894 			opt.resrec.rdata->u.opt[0].optlen        = DNSOpt_LeaseData_Space - 4;
4895 			opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
4896 			if (!owner->HMAC.l[0])											// If no owner data,
4897 				SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]);		// use our own interface information
4898 			else															// otherwise, use the owner data we were given
4899 				{
4900 				opt.resrec.rdata->u.opt[1].u.owner = *owner;
4901 				opt.resrec.rdata->u.opt[1].opt     = kDNSOpt_Owner;
4902 				opt.resrec.rdata->u.opt[1].optlen  = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
4903 				}
4904 			LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
4905 			p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4906 			if (!p)
4907 				LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
4908 			else
4909 				{
4910 				mStatus err;
4911 
4912 				LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
4913 					mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
4914 				// if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID;	// For simulating packet loss
4915 				err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL);
4916 				if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
4917 				if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv6 && intf->NetWakeResolve[sps].ThisQInterval == -1)
4918 					{
4919 					LogSPS("SendSPSRegistration %d %##s failed to send to IPv6 address; will try IPv4 instead", sps, intf->NetWakeResolve[sps].qname.c);
4920 					intf->NetWakeResolve[sps].qtype = kDNSType_A;
4921 					mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
4922 					return;
4923 					}
4924 				}
4925 			}
4926 		}
4927 
4928 	intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10;		// If successful, update NextSPSAttemptTime
4929 
4930 exit:
4931 	if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
4932 	}
4933 
4934 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
4935 	{
4936 	AuthRecord *ar;
4937 	for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
4938 		if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
4939 	return mDNStrue;
4940 	}
4941 
4942 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
4943 	{
4944 	AuthRecord *ar;
4945 	OwnerOptData owner = zeroOwner;
4946 
4947 	SendSPSRegistrationForOwner(m, intf, id, &owner);
4948 
4949 	for (ar = m->ResourceRecords; ar; ar=ar->next)
4950 		{
4951 		if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
4952 			{
4953 			owner = ar->WakeUp;
4954 			SendSPSRegistrationForOwner(m, intf, id, &owner);
4955 			}
4956 		}
4957 	}
4958 
4959 // RetrySPSRegistrations is called from SendResponses, with the lock held
4960 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
4961 	{
4962 	AuthRecord *rr;
4963 	NetworkInterfaceInfo *intf;
4964 
4965 	// First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
4966 	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4967 		if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
4968 			intf->NextSPSAttemptTime++;
4969 
4970 	// Retry any record registrations that are due
4971 	for (rr = m->ResourceRecords; rr; rr=rr->next)
4972 		if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4973 			for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4974 				if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID)
4975 					{
4976 					LogSPS("RetrySPSRegistrations: %s", ARDisplayString(m, rr));
4977 					SendSPSRegistration(m, intf, rr->updateid);
4978 					}
4979 
4980 	// For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
4981 	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4982 		if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
4983 			intf->NextSPSAttempt++;
4984 	}
4985 
4986 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
4987 	{
4988 	NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
4989 	int sps = (int)(question - intf->NetWakeResolve);
4990 	(void)m;			// Unused
4991 	LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
4992 
4993 	if (!AddRecord) return;												// Don't care about REMOVE events
4994 	if (answer->rrtype != question->qtype) return;						// Don't care about CNAMEs
4995 
4996 	// if (answer->rrtype == kDNSType_AAAA && sps == 0) return;	// To test failing to resolve sleep proxy's address
4997 
4998 	if (answer->rrtype == kDNSType_SRV)
4999 		{
5000 		// 1. Got the SRV record; now look up the target host's IPv6 link-local address
5001 		mDNS_StopQuery(m, question);
5002 		intf->SPSPort[sps] = answer->rdata->u.srv.port;
5003 		AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
5004 		question->qtype = kDNSType_AAAA;
5005 		mDNS_StartQuery(m, question);
5006 		}
5007 	else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
5008 		{
5009 		// 2. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
5010 		mDNS_StopQuery(m, question);
5011 		question->ThisQInterval = -1;
5012 		intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
5013 		intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
5014 		mDNS_Lock(m);
5015 		if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);	// If we're ready for this result, use it now
5016 		mDNS_Unlock(m);
5017 		}
5018 	else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == 0)
5019 		{
5020 		// 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
5021 		mDNS_StopQuery(m, question);
5022 		LogSPS("NetWakeResolve: SPS %d %##s has no IPv6 address, will try IPv4 instead", sps, question->qname.c);
5023 		question->qtype = kDNSType_A;
5024 		mDNS_StartQuery(m, question);
5025 		}
5026 	else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
5027 		{
5028 		// 4. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
5029 		mDNS_StopQuery(m, question);
5030 		question->ThisQInterval = -1;
5031 		intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
5032 		intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
5033 		mDNS_Lock(m);
5034 		if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);	// If we're ready for this result, use it now
5035 		mDNS_Unlock(m);
5036 		}
5037 	}
5038 
5039 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
5040 	{
5041 	AuthRecord *rr;
5042 	for (rr = m->ResourceRecords; rr; rr=rr->next)
5043 		if (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort))
5044 			return mDNStrue;
5045 	return mDNSfalse;
5046 	}
5047 
5048 mDNSlocal void SendSleepGoodbyes(mDNS *const m)
5049 	{
5050 	AuthRecord *rr;
5051 	m->SleepState = SleepState_Sleeping;
5052 
5053 #ifndef UNICAST_DISABLED
5054 	SleepRecordRegistrations(m);	// If we have no SPS, need to deregister our uDNS records
5055 #endif /* UNICAST_DISABLED */
5056 
5057 	// Mark all the records we need to deregister and send them
5058 	for (rr = m->ResourceRecords; rr; rr=rr->next)
5059 		if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
5060 			rr->ImmedAnswer = mDNSInterfaceMark;
5061 	SendResponses(m);
5062 	}
5063 
5064 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
5065 mDNSlocal void BeginSleepProcessing(mDNS *const m)
5066 	{
5067 	mDNSBool SendGoodbyes = mDNStrue;
5068 	const CacheRecord *sps[3] = { mDNSNULL };
5069 
5070 	m->NextScheduledSPRetry = m->timenow;
5071 
5072 	if      (!m->SystemWakeOnLANEnabled)                  LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
5073 	else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
5074 	else	// If we have at least one advertised service
5075 		{
5076 		NetworkInterfaceInfo *intf;
5077 		for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5078 			{
5079 			if (!intf->NetWake) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
5080 #if APPLE_OSX_mDNSResponder
5081 			else if (ActivateLocalProxy(m, intf->ifname) == mStatus_NoError)
5082 				{
5083 				SendGoodbyes = mDNSfalse;
5084 				LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
5085 				// This will leave m->SleepState set to SleepState_Transferring,
5086 				// which is okay because with no outstanding resolves, or updates in flight,
5087 				// mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
5088 				}
5089 #endif // APPLE_OSX_mDNSResponder
5090 			else
5091 				{
5092 				FindSPSInCache(m, &intf->NetWakeBrowse, sps);
5093 				if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
5094 					intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
5095 				else
5096 					{
5097 					int i;
5098 					SendGoodbyes = mDNSfalse;
5099 					intf->NextSPSAttempt = 0;
5100 					intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
5101 					// Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
5102 					for (i=0; i<3; i++)
5103 						{
5104 #if ForceAlerts
5105 						if (intf->SPSAddr[i].type)
5106 							{ LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); *(long*)0 = 0; }
5107 						if (intf->NetWakeResolve[i].ThisQInterval >= 0)
5108 							{ LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); *(long*)0 = 0; }
5109 #endif
5110 						intf->SPSAddr[i].type = mDNSAddrType_None;
5111 						if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
5112 						intf->NetWakeResolve[i].ThisQInterval = -1;
5113 						if (sps[i])
5114 							{
5115 							LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
5116 							mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
5117 							intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
5118 							mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
5119 							}
5120 						}
5121 					}
5122 				}
5123 			}
5124 		}
5125 
5126 	if (SendGoodbyes)	// If we didn't find even one Sleep Proxy
5127 		{
5128 		LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
5129 		SendSleepGoodbyes(m);
5130 		}
5131 	}
5132 
5133 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
5134 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
5135 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
5136 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
5137 	{
5138 	AuthRecord *rr;
5139 
5140 	LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
5141 
5142 	if (sleep && !m->SleepState)		// Going to sleep
5143 		{
5144 		mDNS_Lock(m);
5145 		// If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
5146 		if (m->SPSSocket)
5147 			{
5148 			mDNSu8 oldstate = m->SPSState;
5149 			mDNS_DropLockBeforeCallback();		// mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
5150 			m->SPSState = 2;
5151 			if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
5152 			mDNS_ReclaimLockAfterCallback();
5153 			}
5154 
5155 		m->SleepState = SleepState_Transferring;
5156 		if (m->SystemWakeOnLANEnabled && m->DelaySleep)
5157 			{
5158 			// If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
5159 			LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
5160 			m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
5161 			}
5162 		else
5163 			{
5164 			m->DelaySleep = 0;
5165 			m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
5166 			BeginSleepProcessing(m);
5167 			}
5168 
5169 #ifndef UNICAST_DISABLED
5170 		SuspendLLQs(m);
5171 #endif
5172 		mDNS_Unlock(m);
5173 		// RemoveAutoTunnel6Record needs to be called outside the lock, as it grabs the lock also.
5174 #if APPLE_OSX_mDNSResponder
5175 		RemoveAutoTunnel6Record(m);
5176 #endif
5177 		LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
5178 			m->SleepState == SleepState_Transferring ? "Transferring" :
5179 			m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?", m->SleepSeqNum);
5180 		}
5181 	else if (!sleep)		// Waking up
5182 		{
5183 		mDNSu32 slot;
5184 		CacheGroup *cg;
5185 		CacheRecord *cr;
5186 		NetworkInterfaceInfo *intf;
5187 
5188 		mDNS_Lock(m);
5189 		// Reset SleepLimit back to 0 now that we're awake again.
5190 		m->SleepLimit = 0;
5191 
5192 		// If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
5193 		if (m->SleepState != SleepState_Awake)
5194 			{
5195 			m->SleepState = SleepState_Awake;
5196 			m->SleepSeqNum++;
5197 			// If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
5198 			// then we enforce a minimum delay of 16 seconds before we begin sleep processing.
5199 			// This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
5200 			// before we make our determination of whether there's a Sleep Proxy out there we should register with.
5201 			m->DelaySleep = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 16);
5202 			}
5203 
5204 		if (m->SPSState == 3)
5205 			{
5206 			m->SPSState = 0;
5207 			mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower);
5208 			}
5209 
5210 		// In case we gave up waiting and went to sleep before we got an ack from the Sleep Proxy,
5211 		// on wake we go through our record list and clear updateid back to zero
5212 		for (rr = m->ResourceRecords; rr; rr=rr->next) rr->updateid = zeroID;
5213 
5214 		// ... and the same for NextSPSAttempt
5215 		for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
5216 
5217 		// Restart unicast and multicast queries
5218 		mDNSCoreRestartQueries(m);
5219 
5220 		// and reactivtate service registrations
5221 		m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
5222 		LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
5223 
5224 		// 2. Re-validate our cache records
5225 		FORALL_CACHERECORDS(slot, cg, cr)
5226 			mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
5227 
5228 		// 3. Retrigger probing and announcing for all our authoritative records
5229 		for (rr = m->ResourceRecords; rr; rr=rr->next)
5230 			if (AuthRecord_uDNS(rr))
5231 				{
5232 				ActivateUnicastRegistration(m, rr);
5233 				}
5234 			else
5235 				{
5236 				if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5237 				rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5238 				rr->AnnounceCount  = InitialAnnounceCount;
5239 				rr->SendNSECNow    = mDNSNULL;
5240 				InitializeLastAPTime(m, rr);
5241 				}
5242 
5243 		// 4. Refresh NAT mappings
5244 		// We don't want to have to assume that all hardware can necessarily keep accurate
5245 		// track of passage of time while asleep, so on wake we refresh our NAT mappings
5246 		// We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
5247 		// When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
5248 		// mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
5249 		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
5250 		m->retryGetAddr         = m->timenow + mDNSPlatformOneSecond * 5;
5251 		LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m->retryGetAddr - m->timenow, m->timenow);
5252 		RecreateNATMappings(m);
5253 		mDNS_Unlock(m);
5254 		}
5255 	}
5256 
5257 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
5258 	{
5259 	DNSQuestion *q;
5260 	AuthRecord *rr;
5261 	NetworkInterfaceInfo *intf;
5262 
5263 	mDNS_Lock(m);
5264 
5265 	if (m->DelaySleep) goto notready;
5266 
5267 	// If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
5268 	if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
5269 
5270 	m->NextScheduledSPRetry = now + 0x40000000UL;
5271 
5272 	// See if we might need to retransmit any lost Sleep Proxy Registrations
5273 	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5274 		if (intf->NextSPSAttempt >= 0)
5275 			{
5276 			if (now - intf->NextSPSAttemptTime >= 0)
5277 				{
5278 				LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
5279 					intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
5280 				SendSPSRegistration(m, intf, zeroID);
5281 				// Don't need to "goto notready" here, because if we do still have record registrations
5282 				// that have not been acknowledged yet, we'll catch that in the record list scan below.
5283 				}
5284 			else
5285 				if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
5286 					m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
5287 			}
5288 
5289 	// Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
5290 	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5291 		{
5292 		int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
5293 		if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
5294 			{
5295 			LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
5296 				intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
5297 			goto spsnotready;
5298 			}
5299 		}
5300 
5301 	// Scan list of registered records
5302 	for (rr = m->ResourceRecords; rr; rr = rr->next)
5303 		if (!AuthRecord_uDNS(rr))
5304 			if (!mDNSOpaque16IsZero(rr->updateid))
5305 				{ LogSPS("mDNSCoreReadyForSleep: waiting for SPS Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto spsnotready; }
5306 
5307 	// Scan list of private LLQs, and make sure they've all completed their handshake with the server
5308 	for (q = m->Questions; q; q = q->next)
5309 		if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
5310 			{
5311 			LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5312 			goto notready;
5313 			}
5314 
5315 	// Scan list of registered records
5316 	for (rr = m->ResourceRecords; rr; rr = rr->next)
5317 		if (AuthRecord_uDNS(rr))
5318 			{
5319 			if (rr->state == regState_Refresh && rr->tcp)
5320 				{ LogSPS("mDNSCoreReadyForSleep: waiting for Record Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto notready; }
5321 			#if APPLE_OSX_mDNSResponder
5322 			if (!RecordReadyForSleep(m, rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
5323 			#endif
5324 			}
5325 
5326 	mDNS_Unlock(m);
5327 	return mDNStrue;
5328 
5329 spsnotready:
5330 
5331 	// If we failed to complete sleep proxy registration within ten seconds, we give up on that
5332 	// and allow up to ten seconds more to complete wide-area deregistration instead
5333 	if (now - m->SleepLimit >= 0)
5334 		{
5335 		LogMsg("Failed to register with SPS, now sending goodbyes");
5336 
5337 		for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5338 			if (intf->NetWakeBrowse.ThisQInterval >= 0)
5339 				{
5340 				LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
5341 					intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
5342 				mDNS_DeactivateNetWake_internal(m, intf);
5343 				}
5344 
5345 		for (rr = m->ResourceRecords; rr; rr = rr->next)
5346 			if (!AuthRecord_uDNS(rr))
5347 				if (!mDNSOpaque16IsZero(rr->updateid))
5348 					{
5349 					LogSPS("ReadyForSleep clearing updateid for %s", ARDisplayString(m, rr));
5350 					rr->updateid = zeroID;
5351 					}
5352 
5353 		// We'd really like to allow up to ten seconds more here,
5354 		// but if we don't respond to the sleep notification within 30 seconds
5355 		// we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
5356 		// Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
5357 		// more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
5358 		// If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
5359 		m->SleepLimit = now + mDNSPlatformOneSecond * 1;
5360 
5361 		SendSleepGoodbyes(m);
5362 		}
5363 
5364 notready:
5365 	mDNS_Unlock(m);
5366 	return mDNSfalse;
5367 	}
5368 
5369 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
5370 	{
5371 	AuthRecord *ar;
5372 
5373 	// Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
5374 	// failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
5375 	// E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
5376 	// and if that happens we don't want to just give up and go back to sleep and never try again.
5377 	mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond);		// Sleep for at most 120 minutes
5378 
5379 	NATTraversalInfo *nat;
5380 	for (nat = m->NATTraversals; nat; nat=nat->next)
5381 		if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
5382 			{
5383 			mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10;		// Wake up when 90% of the way to the expiry time
5384 			if (e - t > 0) e = t;
5385 			LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
5386 				nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
5387 				mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
5388 				nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5389 				nat->retryInterval / mDNSPlatformOneSecond,
5390 				nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5391 				(t - now) / mDNSPlatformOneSecond);
5392 			}
5393 
5394 	// This loop checks both the time we need to renew wide-area registrations,
5395 	// and the time we need to renew Sleep Proxy registrations
5396 	for (ar = m->ResourceRecords; ar; ar = ar->next)
5397 		if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
5398 			{
5399 			mDNSs32 t = ar->expire - (ar->expire - now) / 10;		// Wake up when 90% of the way to the expiry time
5400 			if (e - t > 0) e = t;
5401 			LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
5402 				ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
5403 				(ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5404 				ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5405 				(t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
5406 			}
5407 
5408 	return(e - now);
5409 	}
5410 
5411 // ***************************************************************************
5412 #if COMPILER_LIKES_PRAGMA_MARK
5413 #pragma mark -
5414 #pragma mark - Packet Reception Functions
5415 #endif
5416 
5417 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
5418 
5419 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
5420 	const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
5421 	{
5422 	mDNSu8          *responseptr     = response->data;
5423 	const mDNSu8    *const limit     = response->data + sizeof(response->data);
5424 	const mDNSu8    *ptr             = query->data;
5425 	AuthRecord  *rr;
5426 	mDNSu32          maxttl = 0x70000000;
5427 	int i;
5428 
5429 	// Initialize the response fields so we can answer the questions
5430 	InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
5431 
5432 	// ***
5433 	// *** 1. Write out the list of questions we are actually going to answer with this packet
5434 	// ***
5435 	if (LegacyQuery)
5436 		{
5437 		maxttl = kStaticCacheTTL;
5438 		for (i=0; i<query->h.numQuestions; i++)						// For each question...
5439 			{
5440 			DNSQuestion q;
5441 			ptr = getQuestion(query, ptr, end, InterfaceID, &q);	// get the question...
5442 			if (!ptr) return(mDNSNULL);
5443 
5444 			for (rr=ResponseRecords; rr; rr=rr->NextResponse)		// and search our list of proposed answers
5445 				{
5446 				if (rr->NR_AnswerTo == ptr)							// If we're going to generate a record answering this question
5447 					{												// then put the question in the question section
5448 					responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
5449 					if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
5450 					break;		// break out of the ResponseRecords loop, and go on to the next question
5451 					}
5452 				}
5453 			}
5454 
5455 		if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
5456 		}
5457 
5458 	// ***
5459 	// *** 2. Write Answers
5460 	// ***
5461 	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5462 		if (rr->NR_AnswerTo)
5463 			{
5464 			mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
5465 				maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5466 			if (p) responseptr = p;
5467 			else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
5468 			}
5469 
5470 	// ***
5471 	// *** 3. Write Additionals
5472 	// ***
5473 	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5474 		if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
5475 			{
5476 			mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
5477 				maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5478 			if (p) responseptr = p;
5479 			else debugf("GenerateUnicastResponse: No more space for additionals");
5480 			}
5481 
5482 	return(responseptr);
5483 	}
5484 
5485 // AuthRecord *our is our Resource Record
5486 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
5487 // Returns 0 if there is no conflict
5488 // Returns +1 if there was a conflict and we won
5489 // Returns -1 if there was a conflict and we lost and have to rename
5490 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
5491 	{
5492 	mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
5493 	mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
5494 	if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
5495 	if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
5496 
5497 	ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
5498 	pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
5499 	while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
5500 	if (ourptr >= ourend && pktptr >= pktend) return(0);			// If data identical, not a conflict
5501 
5502 	if (ourptr >= ourend) return(-1);								// Our data ran out first; We lost
5503 	if (pktptr >= pktend) return(+1);								// Packet data ran out first; We won
5504 	if (*pktptr > *ourptr) return(-1);								// Our data is numerically lower; We lost
5505 	if (*pktptr < *ourptr) return(+1);								// Packet data is numerically lower; We won
5506 
5507 	LogMsg("CompareRData ERROR: Invalid state");
5508 	return(-1);
5509 	}
5510 
5511 // See if we have an authoritative record that's identical to this packet record,
5512 // whose canonical DependentOn record is the specified master record.
5513 // The DependentOn pointer is typically used for the TXT record of service registrations
5514 // It indicates that there is no inherent conflict detection for the TXT record
5515 // -- it depends on the SRV record to resolve name conflicts
5516 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
5517 // pointer chain (if any) to make sure we reach the canonical DependentOn record
5518 // If the record has no DependentOn, then just return that record's pointer
5519 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
5520 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
5521 	{
5522 	const AuthRecord *r1;
5523 	for (r1 = m->ResourceRecords; r1; r1=r1->next)
5524 		{
5525 		if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
5526 			{
5527 			const AuthRecord *r2 = r1;
5528 			while (r2->DependentOn) r2 = r2->DependentOn;
5529 			if (r2 == master) return(mDNStrue);
5530 			}
5531 		}
5532 	for (r1 = m->DuplicateRecords; r1; r1=r1->next)
5533 		{
5534 		if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
5535 			{
5536 			const AuthRecord *r2 = r1;
5537 			while (r2->DependentOn) r2 = r2->DependentOn;
5538 			if (r2 == master) return(mDNStrue);
5539 			}
5540 		}
5541 	return(mDNSfalse);
5542 	}
5543 
5544 // Find the canonical RRSet pointer for this RR received in a packet.
5545 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
5546 // pointers (if any) to make sure we return the canonical member of this name/type/class
5547 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
5548 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
5549 	{
5550 	const AuthRecord *rr;
5551 	for (rr = m->ResourceRecords; rr; rr=rr->next)
5552 		{
5553 		if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
5554 			{
5555 			while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
5556 			return(rr);
5557 			}
5558 		}
5559 	return(mDNSNULL);
5560 	}
5561 
5562 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
5563 // as one of our records (our) but different rdata.
5564 // 1. If our record is not a type that's supposed to be unique, we don't care.
5565 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
5566 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
5567 //     points to our record, ignore this conflict (e.g. the packet record matches one of our
5568 //     TXT records, and that record is marked as dependent on 'our', its SRV record).
5569 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
5570 //    are members of the same RRSet, then this is not a conflict.
5571 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
5572 	{
5573 	// If not supposed to be unique, not a conflict
5574 	if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
5575 
5576 	// If a dependent record, not a conflict
5577 	if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
5578 	else
5579 		{
5580 		// If the pktrr matches a member of ourset, not a conflict
5581 		const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
5582 		const AuthRecord *pktset = FindRRSet(m, pktrr);
5583 		if (pktset == ourset) return(mDNSfalse);
5584 
5585 		// For records we're proxying, where we don't know the full
5586 		// relationship between the records, having any matching record
5587 		// in our AuthRecords list is sufficient evidence of non-conflict
5588 		if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
5589 		}
5590 
5591 	// Okay, this is a conflict
5592 	return(mDNStrue);
5593 	}
5594 
5595 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
5596 // the record list and/or question list.
5597 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5598 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
5599 	DNSQuestion *q, AuthRecord *our)
5600 	{
5601 	int i;
5602 	const mDNSu8 *ptr = LocateAuthorities(query, end);
5603 	mDNSBool FoundUpdate = mDNSfalse;
5604 
5605 	for (i = 0; i < query->h.numAuthorities; i++)
5606 		{
5607 		ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
5608 		if (!ptr) break;
5609 		if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
5610 			{
5611 			FoundUpdate = mDNStrue;
5612 			if (PacketRRConflict(m, our, &m->rec.r))
5613 				{
5614 				int result          = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
5615 				if (!result) result = (int)our->resrec.rrtype  - (int)m->rec.r.resrec.rrtype;
5616 				if (!result) result = CompareRData(our, &m->rec.r);
5617 				if (result)
5618 					{
5619 					const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
5620 					LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
5621 					LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
5622 					}
5623 				// 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.
5624 				// Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
5625 				// If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
5626 				if (result < 0)
5627 					{
5628 					m->SuppressProbes   = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
5629 					our->ProbeCount     = DefaultProbeCountForTypeUnique;
5630 					our->AnnounceCount  = InitialAnnounceCount;
5631 					InitializeLastAPTime(m, our);
5632 					goto exit;
5633 					}
5634 				}
5635 #if 0
5636 			else
5637 				{
5638 				LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
5639 				LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign:  %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
5640 				}
5641 #endif
5642 			}
5643 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
5644 		}
5645 	if (!FoundUpdate)
5646 		LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
5647 exit:
5648 	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
5649 	}
5650 
5651 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
5652 	{
5653 	mDNSu32 slot = HashSlot(pktrr->name);
5654 	CacheGroup *cg = CacheGroupForRecord(m, slot, pktrr);
5655 	CacheRecord *rr;
5656 	mDNSBool match;
5657 	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
5658 		{
5659 		match = !pktrr->InterfaceID ? pktrr->rDNSServer == rr->resrec.rDNSServer : pktrr->InterfaceID == rr->resrec.InterfaceID;
5660 		if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
5661 		}
5662 	return(rr);
5663 	}
5664 
5665 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
5666 // to check our lists and discard any stale duplicates of this record we already have
5667 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
5668 	{
5669 	if (m->CurrentRecord)
5670 		LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5671 	m->CurrentRecord = thelist;
5672 	while (m->CurrentRecord)
5673 		{
5674 		AuthRecord *const rr = m->CurrentRecord;
5675 		if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
5676 			if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
5677 				{
5678 				LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
5679 					m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
5680 				rr->WakeUp.HMAC = zeroEthAddr;	// Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
5681 				rr->RequireGoodbye = mDNSfalse;	// and we don't want to send goodbye for it
5682 				mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5683 				SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
5684 				}
5685 		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5686 		// new records could have been added to the end of the list as a result of that call.
5687 		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5688 			m->CurrentRecord = rr->next;
5689 		}
5690 	}
5691 
5692 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
5693 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
5694 	{
5695 	if (m->CurrentRecord)
5696 		LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5697 	m->CurrentRecord = thelist;
5698 	while (m->CurrentRecord)
5699 		{
5700 		AuthRecord *const rr = m->CurrentRecord;
5701 		if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
5702 			if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
5703 				{
5704 				if (rr->AddressProxy.type == mDNSAddrType_IPv6)
5705 					{
5706 					// We don't do this here because we know that the host is waking up at this point, so we don't send
5707 					// Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
5708 					// saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
5709 					#if MDNS_USE_Unsolicited_Neighbor_Advertisements
5710 					LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
5711 						&rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
5712 					SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
5713 					#endif
5714 					}
5715 				LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
5716 					m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
5717 					&rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
5718 				if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
5719 				rr->WakeUp.HMAC = zeroEthAddr;	// Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
5720 				rr->RequireGoodbye = mDNSfalse;	// and we don't want to send goodbye for it, since real host is now back and functional
5721 				mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5722 				SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
5723 				}
5724 		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5725 		// new records could have been added to the end of the list as a result of that call.
5726 		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5727 			m->CurrentRecord = rr->next;
5728 		}
5729 	}
5730 
5731 // ProcessQuery examines a received query to see if we have any answers to give
5732 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
5733 	const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
5734 	mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
5735 	{
5736 	mDNSBool      FromLocalSubnet    = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
5737 	AuthRecord   *ResponseRecords    = mDNSNULL;
5738 	AuthRecord  **nrp                = &ResponseRecords;
5739 	CacheRecord  *ExpectedAnswers    = mDNSNULL;			// Records in our cache we expect to see updated
5740 	CacheRecord **eap                = &ExpectedAnswers;
5741 	DNSQuestion  *DupQuestions       = mDNSNULL;			// Our questions that are identical to questions in this packet
5742 	DNSQuestion **dqp                = &DupQuestions;
5743 	mDNSs32       delayresponse      = 0;
5744 	mDNSBool      SendLegacyResponse = mDNSfalse;
5745 	const mDNSu8 *ptr;
5746 	mDNSu8       *responseptr        = mDNSNULL;
5747 	AuthRecord   *rr;
5748 	int i;
5749 
5750 	// ***
5751 	// *** 1. Look in Additional Section for an OPT record
5752 	// ***
5753 	ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
5754 	if (ptr)
5755 		{
5756 		ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
5757 		if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
5758 			{
5759 			const rdataOPT *opt;
5760 			const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
5761 			// Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
5762 			// delete all our own AuthRecords (which are identified by having zero MAC tags on them).
5763 			for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
5764 				if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
5765 					{
5766 					ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
5767 					ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
5768 					}
5769 			}
5770 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
5771 		}
5772 
5773 	// ***
5774 	// *** 2. Parse Question Section and mark potential answers
5775 	// ***
5776 	ptr = query->data;
5777 	for (i=0; i<query->h.numQuestions; i++)						// For each question...
5778 		{
5779 		mDNSBool QuestionNeedsMulticastResponse;
5780 		int NumAnswersForThisQuestion = 0;
5781 		AuthRecord *NSECAnswer = mDNSNULL;
5782 		DNSQuestion pktq, *q;
5783 		ptr = getQuestion(query, ptr, end, InterfaceID, &pktq);	// get the question...
5784 		if (!ptr) goto exit;
5785 
5786 		// The only queries that *need* a multicast response are:
5787 		// * Queries sent via multicast
5788 		// * from port 5353
5789 		// * that don't have the kDNSQClass_UnicastResponse bit set
5790 		// These queries need multicast responses because other clients will:
5791 		// * suppress their own identical questions when they see these questions, and
5792 		// * expire their cache records if they don't see the expected responses
5793 		// For other queries, we may still choose to send the occasional multicast response anyway,
5794 		// to keep our neighbours caches warm, and for ongoing conflict detection.
5795 		QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
5796 		// Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
5797 		pktq.qclass &= ~kDNSQClass_UnicastResponse;
5798 
5799 		// Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
5800 		// can result in user callbacks which may change the record list and/or question list.
5801 		// Also note: we just mark potential answer records here, without trying to build the
5802 		// "ResponseRecords" list, because we don't want to risk user callbacks deleting records
5803 		// from that list while we're in the middle of trying to build it.
5804 		if (m->CurrentRecord)
5805 			LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5806 		m->CurrentRecord = m->ResourceRecords;
5807 		while (m->CurrentRecord)
5808 			{
5809 			rr = m->CurrentRecord;
5810 			m->CurrentRecord = rr->next;
5811 			if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
5812 				{
5813 				if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
5814 					{
5815 					if (rr->resrec.RecordType == kDNSRecordTypeUnique)
5816 						ResolveSimultaneousProbe(m, query, end, &pktq, rr);
5817 					else if (ResourceRecordIsValidAnswer(rr))
5818 						{
5819 						NumAnswersForThisQuestion++;
5820 						// Note: We should check here if this is a probe-type query, and if so, generate an immediate
5821 						// unicast answer back to the source, because timeliness in answering probes is important.
5822 
5823 						// Notes:
5824 						// NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
5825 						// NR_AnswerTo == (mDNSu8*)~1             means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
5826 						// NR_AnswerTo == (mDNSu8*)~0             means "definitely answer via multicast" (can't downgrade to unicast later)
5827 						// If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
5828 						// but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
5829 						// then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
5830 						if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
5831 							{
5832 							// We only mark this question for sending if it is at least one second since the last time we multicast it
5833 							// on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
5834 							// This is to guard against the case where someone blasts us with queries as fast as they can.
5835 							if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
5836 								(rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
5837 								rr->NR_AnswerTo = (mDNSu8*)~0;
5838 							}
5839 						else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : (mDNSu8*)~1;
5840 						}
5841 					}
5842 				else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
5843 					{
5844 					// If we don't have any answers for this question, but we do own another record with the same name,
5845 					// then we'll want to mark it to generate an NSEC record on this interface
5846 					if (!NSECAnswer) NSECAnswer = rr;
5847 					}
5848 				}
5849 			}
5850 
5851 		if (NumAnswersForThisQuestion == 0 && NSECAnswer)
5852 			{
5853 			NumAnswersForThisQuestion++;
5854 			NSECAnswer->SendNSECNow = InterfaceID;
5855 			m->NextScheduledResponse = m->timenow;
5856 			}
5857 
5858 		// If we couldn't answer this question, someone else might be able to,
5859 		// so use random delay on response to reduce collisions
5860 		if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond;	// Divided by 50 = 20ms
5861 
5862 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5863 		if (QuestionNeedsMulticastResponse)
5864 #else
5865 		// We only do the following accelerated cache expiration and duplicate question suppression processing
5866 		// for non-truncated multicast queries with multicast responses.
5867 		// For any query generating a unicast response we don't do this because we can't assume we will see the response.
5868 		// For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
5869 		// known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
5870 		if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
5871 #endif
5872 			{
5873 			const mDNSu32 slot = HashSlot(&pktq.qname);
5874 			CacheGroup *cg = CacheGroupForName(m, slot, pktq.qnamehash, &pktq.qname);
5875 			CacheRecord *cr;
5876 
5877 			// Make a list indicating which of our own cache records we expect to see updated as a result of this query
5878 			// Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5879 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5880 			if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5881 #endif
5882 				for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5883 					if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
5884 						if (!cr->NextInKAList && eap != &cr->NextInKAList)
5885 							{
5886 							*eap = cr;
5887 							eap = &cr->NextInKAList;
5888 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5889 							if (cr->MPUnansweredQ == 0 || m->timenow - cr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
5890 								{
5891 								// Although MPUnansweredQ is only really used for multi-packet query processing,
5892 								// we increment it for both single-packet and multi-packet queries, so that it stays in sync
5893 								// with the MPUnansweredKA value, which by necessity is incremented for both query types.
5894 								cr->MPUnansweredQ++;
5895 								cr->MPLastUnansweredQT = m->timenow;
5896 								cr->MPExpectingKA = mDNStrue;
5897 								}
5898 #endif
5899 							}
5900 
5901 			// Check if this question is the same as any of mine.
5902 			// We only do this for non-truncated queries. Right now it would be too complicated to try
5903 			// to keep track of duplicate suppression state between multiple packets, especially when we
5904 			// can't guarantee to receive all of the Known Answer packets that go with a particular query.
5905 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5906 			if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5907 #endif
5908 				for (q = m->Questions; q; q=q->next)
5909 					if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
5910 						if (!q->InterfaceID || q->InterfaceID == InterfaceID)
5911 							if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
5912 								if (q->qtype == pktq.qtype &&
5913 									q->qclass == pktq.qclass &&
5914 									q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
5915 									{ *dqp = q; dqp = &q->NextInDQList; }
5916 			}
5917 		}
5918 
5919 	// ***
5920 	// *** 3. Now we can safely build the list of marked answers
5921 	// ***
5922 	for (rr = m->ResourceRecords; rr; rr=rr->next)				// Now build our list of potential answers
5923 		if (rr->NR_AnswerTo)									// If we marked the record...
5924 			AddRecordToResponseList(&nrp, rr, mDNSNULL);		// ... add it to the list
5925 
5926 	// ***
5927 	// *** 4. Add additional records
5928 	// ***
5929 	AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
5930 
5931 	// ***
5932 	// *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
5933 	// ***
5934 	for (i=0; i<query->h.numAnswers; i++)						// For each record in the query's answer section...
5935 		{
5936 		// Get the record...
5937 		CacheRecord *ourcacherr;
5938 		ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
5939 		if (!ptr) goto exit;
5940 		if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
5941 			{
5942 			// See if this Known-Answer suppresses any of our currently planned answers
5943 			for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5944 				if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5945 					{ rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
5946 
5947 			// See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5948 			for (rr=m->ResourceRecords; rr; rr=rr->next)
5949 				{
5950 				// If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5951 				if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5952 					{
5953 					if (srcaddr->type == mDNSAddrType_IPv4)
5954 						{
5955 						if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
5956 						}
5957 					else if (srcaddr->type == mDNSAddrType_IPv6)
5958 						{
5959 						if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
5960 						}
5961 					if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
5962 						{
5963 						rr->ImmedAnswer  = mDNSNULL;
5964 						rr->ImmedUnicast = mDNSfalse;
5965 	#if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5966 						LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
5967 	#endif
5968 						}
5969 					}
5970 				}
5971 
5972 			ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
5973 
5974 	#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5975 			// See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5976 			// 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).
5977 			if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
5978 				{
5979 				ourcacherr->MPUnansweredKA++;
5980 				ourcacherr->MPExpectingKA = mDNSfalse;
5981 				}
5982 	#endif
5983 
5984 			// Having built our ExpectedAnswers list from the questions in this packet, we then remove
5985 			// any records that are suppressed by the Known Answer list in this packet.
5986 			eap = &ExpectedAnswers;
5987 			while (*eap)
5988 				{
5989 				CacheRecord *cr = *eap;
5990 				if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
5991 					{ *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
5992 				else eap = &cr->NextInKAList;
5993 				}
5994 
5995 			// See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5996 			if (!ourcacherr)
5997 				{
5998 				dqp = &DupQuestions;
5999 				while (*dqp)
6000 					{
6001 					DNSQuestion *q = *dqp;
6002 					if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
6003 						{ *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
6004 					else dqp = &q->NextInDQList;
6005 					}
6006 				}
6007 			}
6008 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6009 		}
6010 
6011 	// ***
6012 	// *** 6. Cancel any additionals that were added because of now-deleted records
6013 	// ***
6014 	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6015 		if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
6016 			{ rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
6017 
6018 	// ***
6019 	// *** 7. Mark the send flags on the records we plan to send
6020 	// ***
6021 	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6022 		{
6023 		if (rr->NR_AnswerTo)
6024 			{
6025 			mDNSBool SendMulticastResponse = mDNSfalse;		// Send modern multicast response
6026 			mDNSBool SendUnicastResponse   = mDNSfalse;		// Send modern unicast response (not legacy unicast response)
6027 
6028 			// If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
6029 			if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0)
6030 				{
6031 				SendMulticastResponse = mDNStrue;
6032 				// If this record was marked for modern (delayed) unicast response, then mark it as promoted to
6033 				// multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
6034 				// If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
6035 				if (rr->NR_AnswerTo == (mDNSu8*)~1) rr->NR_AnswerTo = (mDNSu8*)~0;
6036 				}
6037 
6038 			// If the client insists on a multicast response, then we'd better send one
6039 			if      (rr->NR_AnswerTo == (mDNSu8*)~0) SendMulticastResponse = mDNStrue;
6040 			else if (rr->NR_AnswerTo == (mDNSu8*)~1) SendUnicastResponse   = mDNStrue;
6041 			else if (rr->NR_AnswerTo)                SendLegacyResponse    = mDNStrue;
6042 
6043 			if (SendMulticastResponse || SendUnicastResponse)
6044 				{
6045 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6046 				rr->ImmedAnswerMarkTime = m->timenow;
6047 #endif
6048 				m->NextScheduledResponse = m->timenow;
6049 				// If we're already planning to send this on another interface, just send it on all interfaces
6050 				if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
6051 					rr->ImmedAnswer = mDNSInterfaceMark;
6052 				else
6053 					{
6054 					rr->ImmedAnswer = InterfaceID;			// Record interface to send it on
6055 					if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
6056 					if (srcaddr->type == mDNSAddrType_IPv4)
6057 						{
6058 						if      (mDNSIPv4AddressIsZero(rr->v4Requester))                rr->v4Requester = srcaddr->ip.v4;
6059 						else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
6060 						}
6061 					else if (srcaddr->type == mDNSAddrType_IPv6)
6062 						{
6063 						if      (mDNSIPv6AddressIsZero(rr->v6Requester))                rr->v6Requester = srcaddr->ip.v6;
6064 						else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
6065 						}
6066 					}
6067 				}
6068 			// If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
6069 			// so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
6070 			// else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
6071 			// else, for a simple unique record reply, we can reply immediately; no need for delay
6072 			if      (query->h.flags.b[0] & kDNSFlag0_TC)            delayresponse = mDNSPlatformOneSecond * 20;	// Divided by 50 = 400ms
6073 			else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond;		// Divided by 50 = 20ms
6074 			}
6075 		else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == (mDNSu8*)~0)
6076 			{
6077 			// Since additional records are an optimization anyway, we only ever send them on one interface at a time
6078 			// If two clients on different interfaces do queries that invoke the same optional additional answer,
6079 			// then the earlier client is out of luck
6080 			rr->ImmedAdditional = InterfaceID;
6081 			// No need to set m->NextScheduledResponse here
6082 			// We'll send these additional records when we send them, or not, as the case may be
6083 			}
6084 		}
6085 
6086 	// ***
6087 	// *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
6088 	// ***
6089 	if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
6090 		{
6091 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6092 		mDNSs32 oldss = m->SuppressSending;
6093 		if (oldss && delayresponse)
6094 			LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
6095 #endif
6096 		// Pick a random delay:
6097 		// We start with the base delay chosen above (typically either 1 second or 20 seconds),
6098 		// and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
6099 		// This is an integer value, with resolution determined by the platform clock rate.
6100 		// We then divide that by 50 to get the delay value in ticks. We defer the division until last
6101 		// to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
6102 		// The +49 before dividing is to ensure we round up, not down, to ensure that even
6103 		// on platforms where the native clock rate is less than fifty ticks per second,
6104 		// we still guarantee that the final calculated delay is at least one platform tick.
6105 		// We want to make sure we don't ever allow the delay to be zero ticks,
6106 		// because if that happens we'll fail the Bonjour Conformance Test.
6107 		// Our final computed delay is 20-120ms for normal delayed replies,
6108 		// or 400-500ms in the case of multi-packet known-answer lists.
6109 		m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
6110 		if (m->SuppressSending == 0) m->SuppressSending = 1;
6111 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6112 		if (oldss && delayresponse)
6113 			LogMsg("Set     SuppressSending to   %5ld", m->SuppressSending - m->timenow);
6114 #endif
6115 		}
6116 
6117 	// ***
6118 	// *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
6119 	// ***
6120 	if (SendLegacyResponse)
6121 		responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
6122 
6123 exit:
6124 	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6125 
6126 	// ***
6127 	// *** 10. Finally, clear our link chains ready for use next time
6128 	// ***
6129 	while (ResponseRecords)
6130 		{
6131 		rr = ResponseRecords;
6132 		ResponseRecords = rr->NextResponse;
6133 		rr->NextResponse    = mDNSNULL;
6134 		rr->NR_AnswerTo     = mDNSNULL;
6135 		rr->NR_AdditionalTo = mDNSNULL;
6136 		}
6137 
6138 	while (ExpectedAnswers)
6139 		{
6140 		CacheRecord *cr = ExpectedAnswers;
6141 		ExpectedAnswers = cr->NextInKAList;
6142 		cr->NextInKAList = mDNSNULL;
6143 
6144 		// For non-truncated queries, we can definitively say that we should expect
6145 		// to be seeing a response for any records still left in the ExpectedAnswers list
6146 		if (!(query->h.flags.b[0] & kDNSFlag0_TC))
6147 			if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond)
6148 				{
6149 				cr->UnansweredQueries++;
6150 				cr->LastUnansweredTime = m->timenow;
6151 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6152 				if (cr->UnansweredQueries > 1)
6153 					debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
6154 						cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6155 #endif
6156 				SetNextCacheCheckTimeForRecord(m, cr);
6157 				}
6158 
6159 		// If we've seen multiple unanswered queries for this record,
6160 		// then mark it to expire in five seconds if we don't get a response by then.
6161 		if (cr->UnansweredQueries >= MaxUnansweredQueries)
6162 			{
6163 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6164 			// Only show debugging message if this record was not about to expire anyway
6165 			if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6166 				debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6167 					cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6168 #endif
6169 			mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
6170 			}
6171 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6172 		// Make a guess, based on the multi-packet query / known answer counts, whether we think we
6173 		// should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
6174 		// possible packet loss of up to 20% of the additional KA packets.)
6175 		else if (cr->MPUnansweredQ * 4 > cr->MPUnansweredKA * 5 + 8)
6176 			{
6177 			// We want to do this conservatively.
6178 			// If there are so many machines on the network that they have to use multi-packet known-answer lists,
6179 			// then we don't want them to all hit the network simultaneously with their final expiration queries.
6180 			// By setting the record to expire in four minutes, we achieve two things:
6181 			// (a) the 90-95% final expiration queries will be less bunched together
6182 			// (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
6183 			mDNSu32 remain = (mDNSu32)(RRExpireTime(cr) - m->timenow) / 4;
6184 			if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
6185 				remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
6186 
6187 			// Only show debugging message if this record was not about to expire anyway
6188 			if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6189 				debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6190 					cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6191 
6192 			if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
6193 				cr->UnansweredQueries++;	// Treat this as equivalent to one definite unanswered query
6194 			cr->MPUnansweredQ  = 0;			// Clear MPQ/MPKA statistics
6195 			cr->MPUnansweredKA = 0;
6196 			cr->MPExpectingKA  = mDNSfalse;
6197 
6198 			if (remain < kDefaultReconfirmTimeForNoAnswer)
6199 				remain = kDefaultReconfirmTimeForNoAnswer;
6200 			mDNS_Reconfirm_internal(m, cr, remain);
6201 			}
6202 #endif
6203 		}
6204 
6205 	while (DupQuestions)
6206 		{
6207 		DNSQuestion *q = DupQuestions;
6208 		DupQuestions = q->NextInDQList;
6209 		q->NextInDQList = mDNSNULL;
6210 		i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
6211 		debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
6212 			srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
6213 		}
6214 
6215 	return(responseptr);
6216 	}
6217 
6218 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
6219 	const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6220 	const mDNSInterfaceID InterfaceID)
6221 	{
6222 	mDNSu8    *responseend = mDNSNULL;
6223 	mDNSBool   QueryWasLocalUnicast = srcaddr && dstaddr &&
6224 		!mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6225 
6226 	if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
6227 		{
6228 		LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6229 			"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
6230 			srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6231 			msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
6232 			msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
6233 			msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
6234 			msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
6235 		return;
6236 		}
6237 
6238 	verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6239 		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6240 		srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6241 		msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
6242 		msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
6243 		msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
6244 		msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
6245 
6246 	responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
6247 		!mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
6248 
6249 	if (responseend)	// If responseend is non-null, that means we built a unicast response packet
6250 		{
6251 		debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
6252 			m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
6253 			m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
6254 			m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
6255 			srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
6256 		mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL);
6257 		}
6258 	}
6259 
6260 #if 0
6261 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
6262 	{
6263 	DNSServer *s;
6264 	(void)m; // Unused
6265 	(void)srcaddr; // Unused
6266 	for (s = m->DNSServers; s; s = s->next)
6267 		if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
6268 	return(mDNSfalse);
6269 	}
6270 #endif
6271 
6272 struct UDPSocket_struct
6273 	{
6274 	mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
6275 	};
6276 
6277 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
6278 	{
6279 	DNSQuestion *q;
6280 	for (q = m->Questions; q; q=q->next)
6281 		{
6282 		if (!tcp && !q->LocalSocket) continue;
6283 		if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port)     &&
6284 			mDNSSameOpaque16(q->TargetQID,         id)       &&
6285 			q->qtype                  == question->qtype     &&
6286 			q->qclass                 == question->qclass    &&
6287 			q->qnamehash              == question->qnamehash &&
6288 			SameDomainName(&q->qname, &question->qname))
6289 			return(q);
6290 		}
6291 	return(mDNSNULL);
6292 	}
6293 
6294 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
6295 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
6296 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
6297 	const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
6298 	{
6299 	DNSQuestion *q;
6300 	(void)id;
6301 	(void)srcaddr;
6302 
6303 	for (q = m->Questions; q; q=q->next)
6304 		{
6305 		if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
6306 			{
6307 			if (!mDNSOpaque16IsZero(q->TargetQID))
6308 				{
6309 				debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
6310 
6311 				if (mDNSSameOpaque16(q->TargetQID, id))
6312 					{
6313 					mDNSIPPort srcp;
6314 					if (!tcp)
6315 						{
6316 						srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
6317 						}
6318 					else
6319 						{
6320 						srcp = q->tcpSrcPort;
6321 						}
6322 					if (mDNSSameIPPort(srcp, port)) return(q);
6323 
6324 				//	if (mDNSSameAddress(srcaddr, &q->Target))                   return(mDNStrue);
6325 				//	if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
6326 				//	if (TrustedSource(m, srcaddr))                              return(mDNStrue);
6327 					LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
6328 						q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
6329 					return(mDNSNULL);
6330 					}
6331 				}
6332 			else
6333 				{
6334 				if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
6335 					return(q);
6336 				}
6337 			}
6338 		}
6339 	return(mDNSNULL);
6340 	}
6341 
6342 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
6343 // Currently this applies only to rdata types containing more than one domainname,
6344 // or types where the domainname is not the last item in the structure.
6345 // In addition, NSEC currently requires less space for in-memory storage than its in-packet representation.
6346 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
6347 	{
6348 	switch (rr->rrtype)
6349 		{
6350 		case kDNSType_SOA: return sizeof(rdataSOA);
6351 		case kDNSType_RP:  return sizeof(rdataRP);
6352 		case kDNSType_PX:  return sizeof(rdataPX);
6353 		case kDNSType_NSEC:return sizeof(rdataNSEC);
6354 		default:           return rr->rdlength;
6355 		}
6356 	}
6357 
6358 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay)
6359 	{
6360 	CacheRecord *rr = mDNSNULL;
6361 	mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
6362 
6363 	if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
6364 
6365 	//if (RDLength > InlineCacheRDSize)
6366 	//	LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
6367 
6368 	if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec);	// If we don't have a CacheGroup for this name, make one now
6369 	if (cg)  rr = GetCacheRecord(m, cg, RDLength);	// Make a cache record, being careful not to recycle cg
6370 	if (!rr) NoCacheAnswer(m, &m->rec.r);
6371 	else
6372 		{
6373 		RData *saveptr = rr->resrec.rdata;		// Save the rr->resrec.rdata pointer
6374 		*rr = m->rec.r;							// Block copy the CacheRecord object
6375 		rr->resrec.rdata  = saveptr;				// Restore rr->resrec.rdata after the structure assignment
6376 		rr->resrec.name   = cg->name;			// And set rr->resrec.name to point into our CacheGroup header
6377 		rr->DelayDelivery = delay;
6378 
6379 		// If this is an oversized record with external storage allocated, copy rdata to external storage
6380 		if      (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
6381 			LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
6382 		else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
6383 			LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
6384 		if (RDLength > InlineCacheRDSize)
6385 			mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
6386 
6387 		rr->next = mDNSNULL;					// Clear 'next' pointer
6388 		*(cg->rrcache_tail) = rr;				// Append this record to tail of cache slot list
6389 		cg->rrcache_tail = &(rr->next);			// Advance tail pointer
6390 
6391 		CacheRecordAdd(m, rr);	// CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
6392 		}
6393 	return(rr);
6394 	}
6395 
6396 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
6397 	{
6398 	rr->TimeRcvd             = m->timenow;
6399 	rr->resrec.rroriginalttl = ttl;
6400 	rr->UnansweredQueries = 0;
6401 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6402 	rr->MPUnansweredQ     = 0;
6403 	rr->MPUnansweredKA    = 0;
6404 	rr->MPExpectingKA     = mDNSfalse;
6405 #endif
6406 	SetNextCacheCheckTimeForRecord(m, rr);
6407 	}
6408 
6409 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
6410 	{
6411 	CacheRecord *rr;
6412 	const mDNSu32 slot = HashSlot(&q->qname);
6413 	CacheGroup *cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
6414 	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6415 		if (rr->CRActiveQuestion == q)
6416 			{
6417 			//LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
6418 			RefreshCacheRecord(m, rr, lease);
6419 			}
6420 	}
6421 
6422 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl)		// TTL in seconds
6423 	{
6424 	if      (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
6425 	else if (LLQType == uDNS_LLQ_Events)
6426 		{
6427 		// If the TTL is -1 for uDNS LLQ event packet, that means "remove"
6428 		if (ttl == 0xFFFFFFFF) ttl = 0;
6429 		else                   ttl = kLLQ_DefLease;
6430 		}
6431 	else	// else not LLQ (standard uDNS response)
6432 		{
6433 		// The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
6434 		// also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
6435 		if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
6436 
6437 		// Adjustment factor to avoid race condition:
6438 		// 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.
6439 		// If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
6440 		// 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
6441 		// To avoid this, we extend the record's effective TTL to give it a little extra grace period.
6442 		// We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
6443 		// the cached copy at our local caching server will already have expired, so the server will be forced
6444 		// to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
6445 		ttl += ttl/4 + 2;
6446 
6447 		// For mDNS, TTL zero means "delete this record"
6448 		// For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
6449 		// For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
6450 		// This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
6451 		// respectively, and then if we get no response, delete the record from the cache at 15 seconds.
6452 		// This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
6453 		// and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
6454 		// (with the current code) result in the server having even less than three seconds to respond
6455 		// before we deleted the record and reported a "remove" event to any active questions.
6456 		// Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
6457 		// then things really break (e.g. we end up making a negative cache entry).
6458 		// In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
6459 		if (ttl < 15) ttl = 15;
6460 		}
6461 
6462 	return ttl;
6463 	}
6464 
6465 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
6466 // the record list and/or question list.
6467 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6468 // InterfaceID non-NULL tells us the interface this multicast response was received on
6469 // InterfaceID NULL tells us this was a unicast response
6470 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
6471 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
6472 	const DNSMessage *const response, const mDNSu8 *end,
6473 	const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6474 	const mDNSInterfaceID InterfaceID)
6475 	{
6476 	int i;
6477 	mDNSBool ResponseMCast    = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
6478 	mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6479 	DNSQuestion *llqMatch = mDNSNULL;
6480 	uDNS_LLQType LLQType      = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
6481 
6482 	// "(CacheRecord*)1" is a special (non-zero) end-of-list marker
6483 	// We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
6484 	// set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
6485 	CacheRecord *CacheFlushRecords = (CacheRecord*)1;
6486 	CacheRecord **cfp = &CacheFlushRecords;
6487 
6488 	// All records in a DNS response packet are treated as equally valid statements of truth. If we want
6489 	// to guard against spoof responses, then the only credible protection against that is cryptographic
6490 	// security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
6491 	int firstauthority  =                   response->h.numAnswers;
6492 	int firstadditional = firstauthority  + response->h.numAuthorities;
6493 	int totalrecords    = firstadditional + response->h.numAdditionals;
6494 	const mDNSu8 *ptr   = response->data;
6495 	DNSServer *uDNSServer = mDNSNULL;
6496 
6497 	debugf("Received Response from %#-15a addressed to %#-15a on %p with "
6498 		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
6499 		srcaddr, dstaddr, InterfaceID,
6500 		response->h.numQuestions,   response->h.numQuestions   == 1 ? ", "   : "s,",
6501 		response->h.numAnswers,     response->h.numAnswers     == 1 ? ", "   : "s,",
6502 		response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
6503 		response->h.numAdditionals, response->h.numAdditionals == 1 ? " "    : "s", end - response->data, LLQType);
6504 
6505 	// According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
6506 	//    When a DNS client receives a reply with TC
6507 	//    set, it should ignore that response, and query again, using a
6508 	//    mechanism, such as a TCP connection, that will permit larger replies.
6509 	// It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
6510 	// delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
6511 	// failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
6512 	// <rdar://problem/6690034> Can't bind to Active Directory
6513 	// In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
6514 	// abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
6515 	// Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
6516 	// and not even do the TCP query.
6517 	// Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
6518 	if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC)) return;
6519 
6520 	if (LLQType == uDNS_LLQ_Ignore) return;
6521 
6522 	// 1. We ignore questions (if any) in mDNS response packets
6523 	// 2. If this is an LLQ response, we handle it much the same
6524 	// 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
6525 	//    answer as being the authoritative complete RRSet, and respond by deleting all other
6526 	//    matching cache records that don't appear in this packet.
6527 	// Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
6528 	if (ResponseMCast || LLQType == uDNS_LLQ_Events || (response->h.flags.b[0] & kDNSFlag0_TC))
6529 		ptr = LocateAnswers(response, end);
6530 	// Otherwise, for one-shot queries, any answers in our cache that are not also contained
6531 	// in this response packet are immediately deemed to be invalid.
6532 	else
6533 		{
6534 		mDNSu8 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
6535 		mDNSBool failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
6536 		mDNSBool returnEarly = mDNSfalse;
6537 		// We could possibly combine this with the similar loop at the end of this function --
6538 		// instead of tagging cache records here and then rescuing them if we find them in the answer section,
6539 		// we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
6540 		// which it was received (or refreshed), and then at the end if we find any cache records which
6541 		// answer questions in this packet's question section, but which aren't tagged with this packet's
6542 		// packet number, then we deduce they are old and delete them
6543 		for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
6544 			{
6545 			DNSQuestion q, *qptr = mDNSNULL;
6546 			ptr = getQuestion(response, ptr, end, InterfaceID, &q);
6547 			if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
6548 				{
6549 				if (!failure)
6550 					{
6551 					CacheRecord *rr;
6552 					const mDNSu32 slot = HashSlot(&q.qname);
6553 					CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
6554 					for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6555 						if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
6556 							{
6557 							debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
6558 								rr->resrec.InterfaceID, CRDisplayString(m, rr));
6559 							// Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
6560 							rr->TimeRcvd          = m->timenow - TicksTTL(rr) - 1;
6561 							rr->UnansweredQueries = MaxUnansweredQueries;
6562 							}
6563 					}
6564 				else
6565 					{
6566 					if (qptr)
6567 						{
6568 						LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
6569 						PenalizeDNSServer(m, qptr);
6570 						}
6571 					returnEarly = mDNStrue;
6572 					}
6573 				}
6574 			}
6575 		if (returnEarly)
6576 			{
6577 			LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
6578 				response->h.numAnswers,     response->h.numAnswers     == 1 ? ", " : "s,",
6579 				response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
6580 				response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
6581 			// not goto exit because we won't have any CacheFlushRecords and we do not want to
6582 			// generate negative cache entries (we want to query the next server)
6583 			return;
6584 			}
6585 		}
6586 
6587 	for (i = 0; i < totalrecords && ptr && ptr < end; i++)
6588 		{
6589 		// All responses sent via LL multicast are acceptable for caching
6590 		// All responses received over our outbound TCP connections are acceptable for caching
6591 		mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType;
6592 		// (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
6593 		// to any specific question -- any code reading records from the cache needs to make that determination for itself.)
6594 
6595 		const mDNSu8 RecordType =
6596 			(i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns  :
6597 			(i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
6598 		ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
6599 		if (!ptr) goto exit;		// Break out of the loop and clean up our CacheFlushRecords list before exiting
6600 		if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) { m->rec.r.resrec.RecordType = 0; continue; }
6601 
6602 		// Don't want to cache OPT or TSIG pseudo-RRs
6603 		if (m->rec.r.resrec.rrtype == kDNSType_TSIG) { m->rec.r.resrec.RecordType = 0; continue; }
6604 		if (m->rec.r.resrec.rrtype == kDNSType_OPT)
6605 			{
6606 			const rdataOPT *opt;
6607 			const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
6608 			// Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
6609 			// delete all our own AuthRecords (which are identified by having zero MAC tags on them).
6610 			for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
6611 				if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
6612 					{
6613 					ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
6614 					ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
6615 					}
6616 			m->rec.r.resrec.RecordType = 0;
6617 			continue;
6618 			}
6619 
6620 		// if a CNAME record points to itself, then don't add it to the cache
6621 		if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
6622 			{
6623 			LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
6624 			m->rec.r.resrec.RecordType = 0;
6625 			continue;
6626 			}
6627 
6628 		// When we receive uDNS LLQ responses, we assume a long cache lifetime --
6629 		// In the case of active LLQs, we'll get remove events when the records actually do go away
6630 		// In the case of polling LLQs, we assume the record remains valid until the next poll
6631 		if (!mDNSOpaque16IsZero(response->h.id))
6632 			m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
6633 
6634 		// If response was not sent via LL multicast,
6635 		// then see if it answers a recent query of ours, which would also make it acceptable for caching.
6636 		if (!ResponseMCast)
6637 			{
6638 			if (LLQType)
6639 				{
6640 				// For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
6641 				// Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
6642 				// queries to get ADD/RMV events. To lookup the question, we can't use
6643 				// ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
6644 				// has already matched the question using the 64 bit Id in the packet and we use that here.
6645 
6646 				if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
6647 				}
6648 			else if (!AcceptableResponse || !dstaddr)
6649 				{
6650 				// For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
6651 				// that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
6652 				// Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
6653 				// we create.
6654 
6655 				DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
6656 
6657 				// Intialize the DNS server on the resource record which will now filter what questions we answer with
6658 				// this record.
6659 				//
6660 				// We could potentially lookup the DNS server based on the source address, but that may not work always
6661 				// and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
6662 				// from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
6663 				// on the "id" and "source port", then this response answers the question and assume the response
6664 				// came from the same DNS server that we sent the query to.
6665 
6666 				if (q != mDNSNULL)
6667 					{
6668 					AcceptableResponse = mDNStrue;
6669 					if (!InterfaceID)
6670 						{
6671 						debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
6672 						m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
6673 						}
6674 					}
6675 				else
6676 					{
6677 					// If we can't find a matching question, we need to see whether we have seen records earlier that matched
6678 					// the question. The code below does that. So, make this record unacceptable for now
6679 					if (!InterfaceID)
6680 						{
6681 						debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
6682 						AcceptableResponse = mDNSfalse;
6683 						}
6684 					}
6685 				}
6686 			}
6687 
6688 		// 1. Check that this packet resource record does not conflict with any of ours
6689 		if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
6690 			{
6691 			if (m->CurrentRecord)
6692 				LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
6693 			m->CurrentRecord = m->ResourceRecords;
6694 			while (m->CurrentRecord)
6695 				{
6696 				AuthRecord *rr = m->CurrentRecord;
6697 				m->CurrentRecord = rr->next;
6698 				// We accept all multicast responses, and unicast responses resulting from queries we issued
6699 				// For other unicast responses, this code accepts them only for responses with an
6700 				// (apparently) local source address that pertain to a record of our own that's in probing state
6701 				if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
6702 
6703 				if (PacketRRMatchesSignature(&m->rec.r, rr))		// If interface, name, type (if shared record) and class match...
6704 					{
6705 					// ... check to see if type and rdata are identical
6706 					if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
6707 						{
6708 						// If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
6709 						if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
6710 							{
6711 							// If we were planning to send on this -- and only this -- interface, then we don't need to any more
6712 							if      (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
6713 							}
6714 						else
6715 							{
6716 							if      (rr->ImmedAnswer == mDNSNULL)    { rr->ImmedAnswer = InterfaceID;       m->NextScheduledResponse = m->timenow; }
6717 							else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
6718 							}
6719 						}
6720 					// else, the packet RR has different type or different rdata -- check to see if this is a conflict
6721 					else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
6722 						{
6723 						LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
6724 						LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->     resrec.rdatahash, ARDisplayString(m, rr));
6725 
6726 						// If this record is marked DependentOn another record for conflict detection purposes,
6727 						// then *that* record has to be bumped back to probing state to resolve the conflict
6728 						if (rr->DependentOn)
6729 							{
6730 							while (rr->DependentOn) rr = rr->DependentOn;
6731 							LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->     resrec.rdatahash, ARDisplayString(m, rr));
6732 							}
6733 
6734 						// If we've just whacked this record's ProbeCount, don't need to do it again
6735 						if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
6736 							LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
6737 						else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
6738 							LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
6739 						else
6740 							{
6741 							LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
6742 							// If we'd previously verified this record, put it back to probing state and try again
6743 							if (rr->resrec.RecordType == kDNSRecordTypeVerified)
6744 								{
6745 								LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
6746 								rr->resrec.RecordType     = kDNSRecordTypeUnique;
6747 								// We set ProbeCount to one more than the usual value so we know we've already touched this record.
6748 								// This is because our single probe for "example-name.local" could yield a response with (say) two A records and
6749 								// three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
6750 								// This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
6751 								rr->ProbeCount     = DefaultProbeCountForTypeUnique + 1;
6752 								rr->AnnounceCount  = InitialAnnounceCount;
6753 								InitializeLastAPTime(m, rr);
6754 								RecordProbeFailure(m, rr);	// Repeated late conflicts also cause us to back off to the slower probing rate
6755 								}
6756 							// If we're probing for this record, we just failed
6757 							else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
6758 								{
6759 								LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
6760 								mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6761 								}
6762 							// We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
6763 							// same machine giving different answers for the reverse mapping record, or there are two machines on the
6764 							// network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
6765 							// to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
6766 							// record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
6767 							else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
6768 								{
6769 								LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
6770 								mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6771 								}
6772 							else
6773 								LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
6774 							}
6775 						}
6776 					// Else, matching signature, different type or rdata, but not a considered a conflict.
6777 					// If the packet record has the cache-flush bit set, then we check to see if we
6778 					// have any record(s) of the same type that we should re-assert to rescue them
6779 					// (see note about "multi-homing and bridged networks" at the end of this function).
6780 					else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
6781 						if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
6782 							{ rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
6783 					}
6784 				}
6785 			}
6786 
6787 		if (!AcceptableResponse)
6788 			{
6789 			const CacheRecord *cr;
6790 			for (cr = CacheFlushRecords; cr != (CacheRecord*)1; cr = cr->NextInCFList)
6791 				{
6792 				domainname *target = GetRRDomainNameTarget(&cr->resrec);
6793 				// When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
6794 				// match the question and we already created a cache entry in the previous pass of this loop. Now when we process
6795 				// the A record, it does not match the question because the record name here is the CNAME. Hence we try to
6796 				// match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
6797 				// DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
6798 
6799 				if (target && cr->resrec.rdatahash == m->rec.r.resrec.namehash && SameDomainName(target, m->rec.r.resrec.name))
6800 					{
6801 					debugf("mDNSCoreReceiveResponse: Found a matching entry for %##s in the CacheFlushRecords", m->rec.r.resrec.name->c);
6802 					AcceptableResponse = mDNStrue;
6803 					m->rec.r.resrec.rDNSServer = uDNSServer;
6804 					break;
6805 					}
6806 				}
6807 			}
6808 
6809 		// 2. See if we want to add this packet resource record to our cache
6810 		// We only try to cache answers if we have a cache to put them in
6811 		// Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
6812 		if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
6813 		if (m->rrcache_size && AcceptableResponse)
6814 			{
6815 			const mDNSu32 slot = HashSlot(m->rec.r.resrec.name);
6816 			CacheGroup *cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
6817 			CacheRecord *rr;
6818 
6819 			// 2a. Check if this packet resource record is already in our cache
6820 			for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6821 				{
6822 				mDNSBool match = !InterfaceID ? m->rec.r.resrec.rDNSServer == rr->resrec.rDNSServer : rr->resrec.InterfaceID == InterfaceID;
6823 				// If we found this exact resource record, refresh its TTL
6824 				if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
6825 					{
6826 					if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
6827 						verbosedebugf("Found record size %5d interface %p already in cache: %s",
6828 							m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
6829 
6830 					if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6831 						{
6832 						// If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
6833 						if (rr->NextInCFList == mDNSNULL && cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
6834 							{ *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6835 
6836 						// If this packet record is marked unique, and our previous cached copy was not, then fix it
6837 						if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
6838 							{
6839 							DNSQuestion *q;
6840 							for (q = m->Questions; q; q=q->next) if (ResourceRecordAnswersQuestion(&rr->resrec, q)) q->UniqueAnswers++;
6841 							rr->resrec.RecordType = m->rec.r.resrec.RecordType;
6842 							}
6843 						}
6844 
6845 					if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
6846 						{
6847 						// If the rdata of the packet record differs in name capitalization from the record in our cache
6848 						// then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
6849 						// a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
6850 						// <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
6851 						rr->resrec.rroriginalttl = 0;
6852 						rr->TimeRcvd = m->timenow;
6853 						rr->UnansweredQueries = MaxUnansweredQueries;
6854 						SetNextCacheCheckTimeForRecord(m, rr);
6855 						LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m,rr));
6856 						LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m,&m->rec.r));
6857 						LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
6858 							NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
6859 						// DO NOT break out here -- we want to continue as if we never found it
6860 						}
6861 					else if (m->rec.r.resrec.rroriginalttl > 0)
6862 						{
6863 						DNSQuestion *q;
6864 						//if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
6865 						RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
6866 
6867 						// We have to reset the question interval to MaxQuestionInterval so that we don't keep
6868 						// polling the network once we get a valid response back. For the first time when a new
6869 						// cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
6870 						// Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
6871 						// configuration changed, without flushing the cache, we reset the question interval here.
6872 						// Currently, we do this for for both multicast and unicast questions as long as the record
6873 						// type is unique. For unicast, resource record is always unique and for multicast it is
6874 						// true for records like A etc. but not for PTR.
6875 						if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6876 							{
6877 							for (q = m->Questions; q; q=q->next)
6878 								{
6879 								if (!q->DuplicateOf && !q->LongLived &&
6880 									ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
6881 									{
6882 									q->LastQTime        = m->timenow;
6883 									q->LastQTxTime      = m->timenow;
6884 									q->RecentAnswerPkts = 0;
6885 									q->ThisQInterval    = MaxQuestionInterval;
6886 									q->RequestUnicast   = mDNSfalse;
6887 									q->unansweredQueries = 0;
6888 									debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
6889 									break;		// Why break here? Aren't there other questions we might want to look at?-- SC July 2010
6890 									}
6891 								}
6892 							}
6893 						break;
6894 						}
6895 					else
6896 						{
6897 						// If the packet TTL is zero, that means we're deleting this record.
6898 						// To give other hosts on the network a chance to protest, we push the deletion
6899 						// out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
6900 						// Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
6901 						// lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
6902 						// If record's current expiry time is more than a second from now, we set it to expire in one second.
6903 						// If the record is already going to expire in less than one second anyway, we leave it alone --
6904 						// we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
6905 						debugf("DE for %s", CRDisplayString(m, rr));
6906 						if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
6907 							{
6908 							rr->resrec.rroriginalttl = 1;
6909 							rr->TimeRcvd = m->timenow;
6910 							rr->UnansweredQueries = MaxUnansweredQueries;
6911 							SetNextCacheCheckTimeForRecord(m, rr);
6912 							}
6913 						break;
6914 						}
6915 					}
6916 				}
6917 
6918 			// If packet resource record not in our cache, add it now
6919 			// (unless it is just a deletion of a record we never had, in which case we don't care)
6920 			if (!rr && m->rec.r.resrec.rroriginalttl > 0)
6921 				{
6922 				const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
6923 				const mDNSs32 delay = AddToCFList ? NonZeroTime(m->timenow + mDNSPlatformOneSecond) :
6924 					CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash, slot);
6925 				// If unique, assume we may have to delay delivery of this 'add' event.
6926 				// Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
6927 				// to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
6928 				// to schedule an mDNS_Execute task at the appropriate time.
6929 				rr = CreateNewCacheEntry(m, slot, cg, delay);
6930 				if (rr)
6931 					{
6932 					if (AddToCFList) { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6933 					else if (rr->DelayDelivery) ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
6934 					}
6935 				}
6936 			}
6937 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6938 		}
6939 
6940 exit:
6941 	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6942 
6943 	// If we've just received one or more records with their cache flush bits set,
6944 	// then scan that cache slot to see if there are any old stale records we need to flush
6945 	while (CacheFlushRecords != (CacheRecord*)1)
6946 		{
6947 		CacheRecord *r1 = CacheFlushRecords, *r2;
6948 		const mDNSu32 slot = HashSlot(r1->resrec.name);
6949 		const CacheGroup *cg = CacheGroupForRecord(m, slot, &r1->resrec);
6950 		CacheFlushRecords = CacheFlushRecords->NextInCFList;
6951 		r1->NextInCFList = mDNSNULL;
6952 
6953 		// Look for records in the cache with the same signature as this new one with the cache flush
6954 		// bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
6955 		// (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
6956 		// We make these TTL adjustments *only* for records that still have *more* than one second
6957 		// remaining to live. Otherwise, a record that we tagged for deletion half a second ago
6958 		// (and now has half a second remaining) could inadvertently get its life extended, by either
6959 		// (a) if we got an explicit goodbye packet half a second ago, the record would be considered
6960 		// "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
6961 		// or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
6962 		// in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
6963 		// If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
6964 		// To avoid this, we need to ensure that the cache flushing operation will only act to
6965 		// *decrease* a record's remaining lifetime, never *increase* it.
6966 		for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
6967 			// For Unicast (null InterfaceID) the DNSservers should also match
6968 			if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
6969 				(r1->resrec.InterfaceID || (r1->resrec.rDNSServer == r2->resrec.rDNSServer)) &&
6970 				r1->resrec.rrtype      == r2->resrec.rrtype &&
6971 				r1->resrec.rrclass     == r2->resrec.rrclass)
6972 				{
6973 				// If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
6974 				// else, if record is old, mark it to be flushed
6975 				if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
6976 					{
6977 					// If we find mismatched TTLs in an RRSet, correct them.
6978 					// We only do this for records with a TTL of 2 or higher. It's possible to have a
6979 					// goodbye announcement with the cache flush bit set (or a case-change on record rdata,
6980 					// which we treat as a goodbye followed by an addition) and in that case it would be
6981 					// inappropriate to synchronize all the other records to a TTL of 0 (or 1).
6982 					// We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
6983 					// because certain early Bonjour devices are known to have this specific mismatch, and
6984 					// there's no point filling syslog with messages about something we already know about.
6985 					// We also don't log this for uDNS responses, since a caching name server is obliged
6986 					// to give us an aged TTL to correct for how long it has held the record,
6987 					// so our received TTLs are expected to vary in that case
6988 					if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
6989 						{
6990 						if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
6991 							mDNSOpaque16IsZero(response->h.id))
6992 							LogInfo("Correcting TTL from %4d to %4d for %s",
6993 								r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
6994 						r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
6995 						}
6996 					r2->TimeRcvd = m->timenow;
6997 					}
6998 				else				// else, if record is old, mark it to be flushed
6999 					{
7000 					verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
7001 					verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
7002 					// We set stale records to expire in one second.
7003 					// This gives the owner a chance to rescue it if necessary.
7004 					// This is important in the case of multi-homing and bridged networks:
7005 					//   Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
7006 					//   bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
7007 					//   set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
7008 					//   will promptly delete their cached copies of the (still valid) Ethernet IP address record.
7009 					//   By delaying the deletion by one second, we give X a change to notice that this bridging has
7010 					//   happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
7011 
7012 					// We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
7013 					// final expiration queries for this record.
7014 
7015 					// If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
7016 					// flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
7017 					// one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
7018 					// <rdar://problem/5636422> Updating TXT records is too slow
7019 					// We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
7020 					// which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
7021 					if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
7022 						{
7023 						LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
7024 						r2->resrec.rroriginalttl = 0;
7025 						}
7026 					else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
7027 						{
7028 						// We only set a record to expire in one second if it currently has *more* than a second to live
7029 						// If it's already due to expire in a second or less, we just leave it alone
7030 						r2->resrec.rroriginalttl = 1;
7031 						r2->UnansweredQueries = MaxUnansweredQueries;
7032 						r2->TimeRcvd = m->timenow - 1;
7033 						// We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
7034 						// that we marked for deletion via an explicit DE record
7035 						}
7036 					}
7037 				SetNextCacheCheckTimeForRecord(m, r2);
7038 				}
7039 
7040 		if (r1->DelayDelivery)	// If we were planning to delay delivery of this record, see if we still need to
7041 			{
7042 			r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash, slot);
7043 			// If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
7044 			if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
7045 			else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
7046 			}
7047 		}
7048 
7049 	// See if we need to generate negative cache entries for unanswered unicast questions
7050 	ptr = response->data;
7051 	for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
7052 		{
7053 		DNSQuestion q;
7054 		DNSQuestion *qptr = mDNSNULL;
7055 		ptr = getQuestion(response, ptr, end, InterfaceID, &q);
7056 		if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
7057 			{
7058 			CacheRecord *rr, *neg = mDNSNULL;
7059 			mDNSu32 slot = HashSlot(&q.qname);
7060 			CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
7061 			for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7062 				if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
7063 					{
7064 					// 1. If we got a fresh answer to this query, then don't need to generate a negative entry
7065 					if (RRExpireTime(rr) - m->timenow > 0) break;
7066 					// 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
7067 					if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
7068 					}
7069 			// When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
7070 			// Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
7071 			// Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
7072 			// (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
7073 			// This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
7074 			// suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
7075 			// The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
7076 			// *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
7077 			// in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
7078 			// negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
7079 			//
7080 			// By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
7081 			// response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
7082 			// be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
7083 			// case without creating the negative cache entries, we generate a negative response and let the layer above us
7084 			// do the appropriate thing. This negative response is also needed for appending new search domains.
7085 			if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
7086 				{
7087 				if (!rr)
7088 					{
7089 					LogInfo("mDNSCoreReceiveResponse: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
7090 					m->CurrentQuestion = qptr;
7091 					GenerateNegativeResponse(m);
7092 					m->CurrentQuestion = mDNSNULL;
7093 					}
7094 				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));
7095 				}
7096 			else
7097 				{
7098 				if (!rr)
7099 					{
7100 					// We start off assuming a negative caching TTL of 60 seconds
7101 					// but then look to see if we can find an SOA authority record to tell us a better value we should be using
7102 					mDNSu32 negttl = 60;
7103 					int repeat = 0;
7104 					const domainname *name = &q.qname;
7105 					mDNSu32           hash = q.qnamehash;
7106 
7107 					// Special case for our special Microsoft Active Directory "local SOA" check.
7108 					// Some cheap home gateways don't include an SOA record in the authority section when
7109 					// they send negative responses, so we don't know how long to cache the negative result.
7110 					// Because we don't want to keep hitting the root name servers with our query to find
7111 					// if we're on a network using Microsoft Active Directory using "local" as a private
7112 					// internal top-level domain, we make sure to cache the negative result for at least one day.
7113 					if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
7114 
7115 					// If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
7116 					if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
7117 						{
7118 						ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7119 						if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
7120 							{
7121 							const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
7122 							mDNSu32 ttl_s = soa->min;
7123 							// We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
7124 							// for the SOA record for ".", where the record is reported as non-cacheable
7125 							// (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
7126 							if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
7127 								ttl_s = m->rec.r.resrec.rroriginalttl;
7128 							if (negttl < ttl_s) negttl = ttl_s;
7129 
7130 							// Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
7131 							// with an Authority Section SOA record for d.com, then this is a hint that the authority
7132 							// is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
7133 							// To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
7134 							if (q.qtype == kDNSType_SOA)
7135 								{
7136 								int qcount = CountLabels(&q.qname);
7137 								int scount = CountLabels(m->rec.r.resrec.name);
7138 								if (qcount - 1 > scount)
7139 									if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
7140 										repeat = qcount - 1 - scount;
7141 								}
7142 							}
7143 						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7144 						}
7145 
7146 					// If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
7147 					// the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
7148 					// and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
7149 					// of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
7150 					// With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
7151 					// so that we back off our polling rate and don't keep hitting the server continually.
7152 					if (neg)
7153 						{
7154 						if (negttl < neg->resrec.rroriginalttl * 2)
7155 							negttl = neg->resrec.rroriginalttl * 2;
7156 						if (negttl > 3600)
7157 							negttl = 3600;
7158 						}
7159 
7160 					negttl = GetEffectiveTTL(LLQType, negttl);	// Add 25% grace period if necessary
7161 
7162 					// If we already had a negative cache entry just update it, else make one or more new negative cache entries
7163 					if (neg)
7164 						{
7165 						debugf("Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
7166 						RefreshCacheRecord(m, neg, negttl);
7167 						}
7168 					else while (1)
7169 						{
7170 						debugf("mDNSCoreReceiveResponse making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
7171 						MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
7172 						CreateNewCacheEntry(m, slot, cg, 0);	// We never need any delivery delay for these generated negative cache records
7173 						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7174 						if (!repeat) break;
7175 						repeat--;
7176 						name = (const domainname *)(name->c + 1 + name->c[0]);
7177 						hash = DomainNameHashValue(name);
7178 						slot = HashSlot(name);
7179 						cg   = CacheGroupForName(m, slot, hash, name);
7180 						}
7181 					}
7182 				}
7183 			}
7184 		}
7185 	}
7186 
7187 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
7188 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
7189 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
7190 // that warrants waking the sleeping host.
7191 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
7192 
7193 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
7194 	{
7195 	// We don't need to use the m->CurrentRecord mechanism here because the target HMAC is nonzero,
7196 	// so all we're doing is marking the record to generate a few wakeup packets
7197 	AuthRecord *rr;
7198 	if (!e->l[0]) { LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero"); return; }
7199 	for (rr = thelist; rr; rr = rr->next)
7200 		if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
7201 			{
7202 			LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
7203 			mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7204 			}
7205 	}
7206 
7207 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
7208 	{
7209 	if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
7210 	ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
7211 	ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
7212 	}
7213 
7214 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
7215 	{
7216 	if (result && result != mStatus_MemFree)
7217 		LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
7218 
7219 	if (result == mStatus_NameConflict)
7220 		{
7221 		mDNS_Lock(m);
7222 		LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
7223 		if (ar->WakeUp.HMAC.l[0])
7224 			{
7225 			SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password);	// Send one wakeup magic packet
7226 			ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC);					// Schedule all other records with the same owner to be woken
7227 			}
7228 		mDNS_Unlock(m);
7229 		}
7230 
7231 	if (result == mStatus_NameConflict || result == mStatus_MemFree)
7232 		{
7233 		m->ProxyRecords--;
7234 		mDNSPlatformMemFree(ar);
7235 		mDNS_UpdateAllowSleep(m);
7236 		}
7237 	}
7238 
7239 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
7240 	const DNSMessage *const msg, const mDNSu8 *end,
7241 	const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
7242 	const mDNSInterfaceID InterfaceID)
7243 	{
7244 	int i;
7245 	AuthRecord opt;
7246 	mDNSu8 *p = m->omsg.data;
7247 	OwnerOptData owner = zeroOwner;		// Need to zero this, so we'll know if this Update packet was missing its Owner option
7248 	mDNSu32 updatelease = 0;
7249 	const mDNSu8 *ptr;
7250 
7251 	LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7252 		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
7253 		srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7254 		msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
7255 		msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
7256 		msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
7257 		msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
7258 
7259 	if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
7260 
7261 	if (mDNS_PacketLoggingEnabled)
7262 		DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
7263 
7264 	ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
7265 	if (ptr)
7266 		{
7267 		ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
7268 		if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7269 			{
7270 			const rdataOPT *o;
7271 			const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7272 			for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
7273 				{
7274 				if      (o->opt == kDNSOpt_Lease)                         updatelease = o->u.updatelease;
7275 				else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner       = o->u.owner;
7276 				}
7277 			}
7278 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7279 		}
7280 
7281 	InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
7282 
7283 	if (!updatelease || !owner.HMAC.l[0])
7284 		{
7285 		static int msgs = 0;
7286 		if (msgs < 100)
7287 			{
7288 			msgs++;
7289 			LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
7290 				!updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
7291 			}
7292 		m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
7293 		}
7294 	else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
7295 		{
7296 		static int msgs = 0;
7297 		if (msgs < 100)
7298 			{
7299 			msgs++;
7300 			LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
7301 				m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
7302 			}
7303 		m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
7304 		}
7305 	else
7306 		{
7307 		LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
7308 
7309 		if (updatelease > 24 * 60 * 60)
7310 			updatelease = 24 * 60 * 60;
7311 
7312 		if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
7313 			updatelease = 0x40000000UL / mDNSPlatformOneSecond;
7314 
7315 		ptr = LocateAuthorities(msg, end);
7316 		for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
7317 			{
7318 			ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7319 			if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7320 				{
7321 				mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
7322 				AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
7323 				if (!ar) { m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; break; }
7324 				else
7325 					{
7326 					mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
7327 					m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
7328 					ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords);	// Make sure we don't have any old stale duplicates of this record
7329 					ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
7330 					mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
7331 					AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
7332 					ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
7333 					ar->resrec.rdata->MaxRDLength = RDLengthMem;
7334 					mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
7335 					ar->ForceMCast = mDNStrue;
7336 					ar->WakeUp     = owner;
7337 					if (m->rec.r.resrec.rrtype == kDNSType_PTR)
7338 						{
7339 						mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
7340 						if      (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
7341 						else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
7342 						debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
7343 						if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
7344 						}
7345 					ar->TimeRcvd   = m->timenow;
7346 					ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
7347 					if (m->NextScheduledSPS - ar->TimeExpire > 0)
7348 						m->NextScheduledSPS = ar->TimeExpire;
7349 					mDNS_Register_internal(m, ar);
7350 					// Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
7351 					// but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
7352 					// Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
7353 					// Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
7354 					// new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
7355 					if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
7356 						if (ar->resrec.rrtype == kDNSType_AAAA) ar->resrec.rroriginalttl = 0;
7357 					m->ProxyRecords++;
7358 					mDNS_UpdateAllowSleep(m);
7359 					LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
7360 					}
7361 				}
7362 			m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7363 			}
7364 
7365 		if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
7366 			{
7367 			LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
7368 			ClearProxyRecords(m, &owner, m->DuplicateRecords);
7369 			ClearProxyRecords(m, &owner, m->ResourceRecords);
7370 			}
7371 		else
7372 			{
7373 			mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
7374 			opt.resrec.rrclass    = NormalMaxDNSMessageData;
7375 			opt.resrec.rdlength   = sizeof(rdataOPT);	// One option in this OPT record
7376 			opt.resrec.rdestimate = sizeof(rdataOPT);
7377 			opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
7378 			opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
7379 			p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
7380 			}
7381 		}
7382 
7383 	if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
7384 	}
7385 
7386 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSInterfaceID InterfaceID)
7387 	{
7388 	if (InterfaceID)
7389 		{
7390 		mDNSu32 updatelease = 60 * 60;		// If SPS fails to indicate lease time, assume one hour
7391 		const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
7392 		if (ptr)
7393 			{
7394 			ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
7395 			if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7396 				{
7397 				const rdataOPT *o;
7398 				const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7399 				for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
7400 					if (o->opt == kDNSOpt_Lease)
7401 						{
7402 						updatelease = o->u.updatelease;
7403 						LogSPS("Sleep Proxy granted lease time %4d seconds", updatelease);
7404 						}
7405 				}
7406 			m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7407 			}
7408 
7409 		if (m->CurrentRecord)
7410 			LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7411 		m->CurrentRecord = m->ResourceRecords;
7412 		while (m->CurrentRecord)
7413 			{
7414 			AuthRecord *const rr = m->CurrentRecord;
7415 			if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
7416 				if (mDNSSameOpaque16(rr->updateid, msg->h.id))
7417 					{
7418 					rr->updateid = zeroID;
7419 					rr->expire   = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
7420 					LogSPS("Sleep Proxy %s record %5d %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", updatelease, ARDisplayString(m,rr));
7421 					if (rr->WakeUp.HMAC.l[0])
7422 						{
7423 						rr->WakeUp.HMAC = zeroEthAddr;	// Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7424 						rr->RequireGoodbye = mDNSfalse;	// and we don't want to send goodbye for it
7425 						mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7426 						}
7427 					}
7428 			// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7429 			// new records could have been added to the end of the list as a result of that call.
7430 			if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7431 				m->CurrentRecord = rr->next;
7432 			}
7433 		}
7434 	// If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
7435 	// may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
7436 	if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
7437 	}
7438 
7439 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
7440 	const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
7441 	{
7442 	if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
7443 		{
7444 		LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
7445 #if ForceAlerts
7446 		*(long*)0 = 0;
7447 #endif
7448 		}
7449 
7450 	// Create empty resource record
7451 	cr->resrec.RecordType    = kDNSRecordTypePacketNegative;
7452 	cr->resrec.InterfaceID   = InterfaceID;
7453 	cr->resrec.rDNSServer	 = dnsserver;
7454 	cr->resrec.name          = name;	// Will be updated to point to cg->name when we call CreateNewCacheEntry
7455 	cr->resrec.rrtype        = rrtype;
7456 	cr->resrec.rrclass       = rrclass;
7457 	cr->resrec.rroriginalttl = ttl_seconds;
7458 	cr->resrec.rdlength      = 0;
7459 	cr->resrec.rdestimate    = 0;
7460 	cr->resrec.namehash      = namehash;
7461 	cr->resrec.rdatahash     = 0;
7462 	cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
7463 	cr->resrec.rdata->MaxRDLength = 0;
7464 
7465 	cr->NextInKAList       = mDNSNULL;
7466 	cr->TimeRcvd           = m->timenow;
7467 	cr->DelayDelivery      = 0;
7468 	cr->NextRequiredQuery  = m->timenow;
7469 	cr->LastUsed           = m->timenow;
7470 	cr->CRActiveQuestion   = mDNSNULL;
7471 	cr->UnansweredQueries  = 0;
7472 	cr->LastUnansweredTime = 0;
7473 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7474 	cr->MPUnansweredQ      = 0;
7475 	cr->MPLastUnansweredQT = 0;
7476 	cr->MPUnansweredKA     = 0;
7477 	cr->MPExpectingKA      = mDNSfalse;
7478 #endif
7479 	cr->NextInCFList       = mDNSNULL;
7480 	}
7481 
7482 mDNSexport void mDNSCoreReceive(mDNS *const m, void *const pkt, const mDNSu8 *const end,
7483 	const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
7484 	const mDNSInterfaceID InterfaceID)
7485 	{
7486 	mDNSInterfaceID ifid = InterfaceID;
7487 	DNSMessage  *msg  = (DNSMessage *)pkt;
7488 	const mDNSu8 StdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_StdQuery;
7489 	const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
7490 	const mDNSu8 UpdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_Update;
7491 	const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
7492 	mDNSu8 QR_OP;
7493 	mDNSu8 *ptr = mDNSNULL;
7494 	mDNSBool TLS = (dstaddr == (mDNSAddr *)1);	// For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
7495 	if (TLS) dstaddr = mDNSNULL;
7496 
7497 #ifndef UNICAST_DISABLED
7498 	if (mDNSSameAddress(srcaddr, &m->Router))
7499 		{
7500 #ifdef _LEGACY_NAT_TRAVERSAL_
7501 		if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
7502 			{
7503 			mDNS_Lock(m);
7504 			LNT_ConfigureRouterInfo(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
7505 			mDNS_Unlock(m);
7506 			return;
7507 			}
7508 #endif
7509 		if (mDNSSameIPPort(srcport, NATPMPPort))
7510 			{
7511 			mDNS_Lock(m);
7512 			uDNS_ReceiveNATPMPPacket(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
7513 			mDNS_Unlock(m);
7514 			return;
7515 			}
7516 		}
7517 #ifdef _LEGACY_NAT_TRAVERSAL_
7518 	else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
7519 #endif
7520 
7521 #endif
7522 	if ((unsigned)(end - (mDNSu8 *)pkt) < sizeof(DNSMessageHeader))
7523 		{
7524 		LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt);
7525 		return;
7526 		}
7527 	QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
7528 	// Read the integer parts which are in IETF byte-order (MSB first, LSB second)
7529 	ptr = (mDNSu8 *)&msg->h.numQuestions;
7530 	msg->h.numQuestions   = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
7531 	msg->h.numAnswers     = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
7532 	msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
7533 	msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
7534 
7535 	if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
7536 
7537 	// We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
7538 	// If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
7539 	if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
7540 
7541 	mDNS_Lock(m);
7542 	m->PktNum++;
7543 #ifndef UNICAST_DISABLED
7544 	if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
7545 		if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
7546 			{
7547 			ifid = mDNSInterface_Any;
7548 			if (mDNS_PacketLoggingEnabled)
7549 				DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
7550 			uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
7551 			// Note: mDNSCore also needs to get access to received unicast responses
7552 			}
7553 #endif
7554 	if      (QR_OP == StdQ) mDNSCoreReceiveQuery   (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
7555 	else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
7556 	else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate  (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
7557 	else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end,                                     InterfaceID);
7558 	else
7559 		{
7560 		LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
7561 			msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt, InterfaceID);
7562 		if (mDNS_LoggingEnabled)
7563 			{
7564 			int i = 0;
7565 			while (i<end - (mDNSu8 *)pkt)
7566 				{
7567 				char buffer[128];
7568 				char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
7569 				do if (i<end - (mDNSu8 *)pkt) p += mDNS_snprintf(p, sizeof(buffer), " %02X", ((mDNSu8 *)pkt)[i]); while (++i & 15);
7570 				LogInfo("%s", buffer);
7571 				}
7572 			}
7573 		}
7574 	// Packet reception often causes a change to the task list:
7575 	// 1. Inbound queries can cause us to need to send responses
7576 	// 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
7577 	// 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
7578 	// 4. Response packets that answer questions may cause our client to issue new questions
7579 	mDNS_Unlock(m);
7580 	}
7581 
7582 // ***************************************************************************
7583 #if COMPILER_LIKES_PRAGMA_MARK
7584 #pragma mark -
7585 #pragma mark - Searcher Functions
7586 #endif
7587 
7588 // Targets are considered the same if both queries are untargeted, or
7589 // if both are targeted to the same address+port
7590 // (If Target address is zero, TargetPort is undefined)
7591 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
7592 	(mDNSSameAddress(&(A)->Target, &(B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
7593 
7594 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
7595 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
7596 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
7597 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
7598 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
7599 //
7600 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
7601 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
7602 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
7603 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
7604 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
7605 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
7606 // breaks this design principle.
7607 
7608 // If IsLLQ(Q) is true, it means the question is both:
7609 // (a) long-lived and
7610 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
7611 // for multicast questions, we don't want to treat LongLived as anything special
7612 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
7613 
7614 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
7615 	{
7616 	DNSQuestion *q;
7617 	// Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
7618 	// This prevents circular references, where two questions are each marked as a duplicate of the other.
7619 	// Accordingly, we break out of the loop when we get to 'question', because there's no point searching
7620 	// further in the list.
7621 	for (q = m->Questions; q && q != question; q=q->next)		// Scan our list for another question
7622 		if (q->InterfaceID == question->InterfaceID &&			// with the same InterfaceID,
7623 			SameQTarget(q, question)                &&			// and same unicast/multicast target settings
7624 			q->qtype      == question->qtype        &&			// type,
7625 			q->qclass     == question->qclass       &&			// class,
7626 			IsLLQ(q)      == IsLLQ(question)        &&			// and long-lived status matches
7627 			(!q->AuthInfo || question->AuthInfo)    &&			// to avoid deadlock, don't make public query dup of a private one
7628 			(q->SuppressQuery == question->SuppressQuery) &&	// Questions that are suppressed/not suppressed
7629 			q->qnamehash  == question->qnamehash    &&
7630 			SameDomainName(&q->qname, &question->qname))		// and name
7631 			return(q);
7632 	return(mDNSNULL);
7633 	}
7634 
7635 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
7636 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
7637 	{
7638 	DNSQuestion *q;
7639 	DNSQuestion *first = mDNSNULL;
7640 
7641 	// This is referring to some other question as duplicate. No other question can refer to this
7642 	// question as a duplicate.
7643 	if (question->DuplicateOf)
7644 		{
7645 		LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
7646 			question, question->qname.c, DNSTypeName(question->qtype),
7647 			question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
7648 		return;
7649 		}
7650 
7651 	for (q = m->Questions; q; q=q->next)		// Scan our list of questions
7652 		if (q->DuplicateOf == question)			// To see if any questions were referencing this as their duplicate
7653 			{
7654 			q->DuplicateOf = first;
7655 			if (!first)
7656 				{
7657 				first = q;
7658 				// If q used to be a duplicate, but now is not,
7659 				// then inherit the state from the question that's going away
7660 				q->LastQTime         = question->LastQTime;
7661 				q->ThisQInterval     = question->ThisQInterval;
7662 				q->ExpectUnicastResp = question->ExpectUnicastResp;
7663 				q->LastAnswerPktNum  = question->LastAnswerPktNum;
7664 				q->RecentAnswerPkts  = question->RecentAnswerPkts;
7665 				q->RequestUnicast    = question->RequestUnicast;
7666 				q->LastQTxTime       = question->LastQTxTime;
7667 				q->CNAMEReferrals    = question->CNAMEReferrals;
7668 				q->nta               = question->nta;
7669 				q->servAddr          = question->servAddr;
7670 				q->servPort          = question->servPort;
7671 				q->qDNSServer        = question->qDNSServer;
7672 				q->validDNSServers   = question->validDNSServers;
7673 				q->unansweredQueries = question->unansweredQueries;
7674 				q->noServerResponse  = question->noServerResponse;
7675 				q->triedAllServersOnce = question->triedAllServersOnce;
7676 
7677 				q->TargetQID         = question->TargetQID;
7678 				q->LocalSocket       = question->LocalSocket;
7679 
7680 				q->state             = question->state;
7681 			//	q->tcp               = question->tcp;
7682 				q->ReqLease          = question->ReqLease;
7683 				q->expire            = question->expire;
7684 				q->ntries            = question->ntries;
7685 				q->id                = question->id;
7686 
7687 				question->LocalSocket = mDNSNULL;
7688 				question->nta        = mDNSNULL;	// If we've got a GetZoneData in progress, transfer it to the newly active question
7689 			//	question->tcp        = mDNSNULL;
7690 
7691 				if (q->LocalSocket)
7692 					debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7693 
7694 				if (q->nta)
7695 					{
7696 					LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7697 					q->nta->ZoneDataContext = q;
7698 					}
7699 
7700 				// Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
7701 				if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
7702 
7703 				if (question->state == LLQ_Established)
7704 					{
7705 					LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7706 					question->state = 0;	// Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
7707 					}
7708 
7709 				SetNextQueryTime(m,q);
7710 				}
7711 			}
7712 	}
7713 
7714 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
7715 	{
7716 	McastResolver **p = &m->McastResolvers;
7717 	McastResolver *tmp = mDNSNULL;
7718 
7719 	if (!d) d = (const domainname *)"";
7720 
7721 	LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
7722 
7723 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
7724 		LogMsg("mDNS_AddMcastResolver: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
7725 
7726 	while (*p)	// Check if we already have this {interface, domain} tuple registered
7727 		{
7728 		if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
7729 			{
7730 			if (!((*p)->flags & DNSServer_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
7731 			(*p)->flags &= ~DNSServer_FlagDelete;
7732 			tmp = *p;
7733 			*p = tmp->next;
7734 			tmp->next = mDNSNULL;
7735 			}
7736 		else
7737 			p=&(*p)->next;
7738 		}
7739 
7740 	if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
7741 	else
7742 		{
7743 		// allocate, add to list
7744 		*p = mDNSPlatformMemAllocate(sizeof(**p));
7745 		if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
7746 		else
7747 			{
7748 			(*p)->interface = interface;
7749 			(*p)->flags     = DNSServer_FlagNew;
7750 			(*p)->timeout   = timeout;
7751 			AssignDomainName(&(*p)->domain, d);
7752 			(*p)->next = mDNSNULL;
7753 			}
7754 		}
7755 	return(*p);
7756 	}
7757 
7758 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
7759 	{
7760 	mDNSs32 ptime = 0;
7761 	if (server->penaltyTime != 0)
7762 		{
7763 		ptime = server->penaltyTime - m->timenow;
7764 		if (ptime < 0)
7765 			{
7766 			// This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
7767 			// If it does not get reset in ResetDNSServerPenalties for some reason, we do it
7768 			// here
7769 			LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
7770 				ptime, server->penaltyTime, m->timenow);
7771 			server->penaltyTime = 0;
7772 			ptime = 0;
7773 			}
7774 		}
7775 	return ptime;
7776 	}
7777 
7778 //Checks to see whether the newname is a better match for the name, given the best one we have
7779 //seen so far (given in bestcount).
7780 //Returns -1 if the newname is not a better match
7781 //Returns 0 if the newname is the same as the old match
7782 //Returns 1 if the newname is a better match
7783 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
7784 	int bestcount)
7785 	{
7786 	// If the name contains fewer labels than the new server's domain or the new name
7787 	// contains fewer labels than the current best, then it can't possibly be a better match
7788 	if (namecount < newcount || newcount < bestcount) return -1;
7789 
7790 	// If there is no match, return -1 and the caller will skip this newname for
7791 	// selection
7792 	//
7793 	// If we find a match and the number of labels is the same as bestcount, then
7794 	// we return 0 so that the caller can do additional logic to pick one of
7795 	// the best based on some other factors e.g., penaltyTime
7796 	//
7797 	// If we find a match and the number of labels is more than bestcount, then we
7798 	// return 1 so that the caller can pick this over the old one.
7799 	//
7800 	// Note: newcount can either be equal or greater than bestcount beause of the
7801 	// check above.
7802 
7803 	if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
7804 		return bestcount == newcount ? 0 : 1;
7805 	else
7806 		return -1;
7807 	}
7808 
7809 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
7810 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
7811 // names. In that case, we give a default timeout of 5 seconds
7812 #define DEFAULT_MCAST_TIMEOUT	5
7813 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
7814 	{
7815 	McastResolver *curmatch = mDNSNULL;
7816 	int bestmatchlen = -1, namecount = CountLabels(&question->qname);
7817 	McastResolver *curr;
7818 	int bettermatch, currcount;
7819 	for (curr = m->McastResolvers; curr; curr = curr->next)
7820 		{
7821 		currcount = CountLabels(&curr->domain);
7822 		bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
7823 		// Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
7824 		// the timeout value from the first one
7825 		if (bettermatch == 1)
7826 			{
7827 			curmatch = curr;
7828 			bestmatchlen = currcount;
7829 			}
7830 		}
7831 	LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
7832 		curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
7833 	return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
7834 	}
7835 
7836 // Sets all the Valid DNS servers for a question
7837 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
7838 	{
7839 	DNSServer *curmatch = mDNSNULL;
7840 	int bestmatchlen = -1, namecount = CountLabels(&question->qname);
7841 	DNSServer *curr;
7842 	int bettermatch, currcount;
7843 	int index = 0;
7844 	mDNSu32 timeout = 0;
7845 
7846 	question->validDNSServers = zeroOpaque64;
7847 	for (curr = m->DNSServers; curr; curr = curr->next)
7848 		{
7849 		debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
7850 		// skip servers that will soon be deleted
7851 		if (curr->flags & DNSServer_FlagDelete)
7852 			{ debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
7853 
7854 		// This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
7855 		// the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
7856 		// But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
7857 		// (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
7858 		// match the scoped entries by mistake.
7859 		//
7860 		// Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
7861 
7862 		if (curr->scoped && curr->interface == mDNSInterface_Any)
7863 			{ debugf("SetValidDNSServers: Scoped DNS server %#a (Domain %##s) with Interface Any", &curr->addr, curr->domain.c); continue; }
7864 
7865 		currcount = CountLabels(&curr->domain);
7866 		if ((!curr->scoped && (!question->InterfaceID || (question->InterfaceID == mDNSInterface_Unicast))) || (curr->interface == question->InterfaceID))
7867 			{
7868 			bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
7869 
7870 			// If we found a better match (bettermatch == 1) then clear all the bits
7871 			// corresponding to the old DNSServers that we have may set before and start fresh.
7872 			// If we find an equal match, then include that DNSServer also by setting the corresponding
7873 			// bit
7874 			if ((bettermatch == 1) || (bettermatch == 0))
7875 				{
7876 				curmatch = curr;
7877 				bestmatchlen = currcount;
7878 				if (bettermatch) { debugf("SetValidDNSServers: Resetting all the bits"); question->validDNSServers = zeroOpaque64; timeout = 0; }
7879 				debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
7880 					" Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
7881 					curr->interface);
7882 				timeout += curr->timeout;
7883 				bit_set_opaque64(question->validDNSServers, index);
7884 				}
7885 			}
7886 		index++;
7887 		}
7888 	question->noServerResponse = 0;
7889 
7890 	debugf("SetValidDNSServers: ValidDNSServer bits  0x%x%x for question %p %##s (%s)",
7891 		question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
7892 	// If there are no matching resolvers, then use the default value to timeout
7893 	return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
7894 	}
7895 
7896 // Get the Best server that matches a name. If you find penalized servers, look for the one
7897 // that will come out of the penalty box soon
7898 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSOpaque64 validBits, int *selected, mDNSBool nameMatch)
7899 	{
7900 	DNSServer *curmatch = mDNSNULL;
7901 	int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
7902 	DNSServer *curr;
7903 	mDNSs32 bestPenaltyTime, currPenaltyTime;
7904 	int bettermatch, currcount;
7905 	int index = 0;
7906 	int currindex = -1;
7907 
7908 	debugf("GetBestServer: ValidDNSServer bits  0x%x%x", validBits.l[1], validBits.l[0]);
7909 	bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
7910 	for (curr = m->DNSServers; curr; curr = curr->next)
7911 		{
7912 		// skip servers that will soon be deleted
7913 		if (curr->flags & DNSServer_FlagDelete)
7914 			{ debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
7915 
7916 		// Check if this is a valid DNSServer
7917 		if (!bit_get_opaque64(validBits, index)) { debugf("GetBestServer: continuing for index %d", index); index++; continue; }
7918 
7919 		currcount = CountLabels(&curr->domain);
7920 		currPenaltyTime = PenaltyTimeForServer(m, curr);
7921 
7922 		debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
7923 			&curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
7924 
7925 		// If there are multiple best servers for a given question, we will pick the first one
7926 		// if none of them are penalized. If some of them are penalized in that list, we pick
7927 		// the least penalized one. BetterMatchForName walks through all best matches and
7928 		// "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
7929 		// in the list when there are no penalized servers and least one among them
7930 		// when there are some penalized servers
7931 		//
7932 		// Notes on InterfaceID matching:
7933 		//
7934 		// 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
7935 		// is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
7936 		// entries by "scoped" being false. These are like any other unscoped entries except that
7937 		// if it is picked e.g., domain match, when the packet is sent out later, the packet will
7938 		// be sent out on that interface. Theese entries can be matched by either specifying a
7939 		// zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
7940 		// the question will cause an extra check on matching the InterfaceID on the question
7941 		// against the DNSServer.
7942 		//
7943 		// 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
7944 		// is the new way of specifying an InterfaceID option for DNSServer. These will be considered
7945 		// only when the question has non-zero interfaceID.
7946 
7947 		if ((!curr->scoped && !InterfaceID) || (curr->interface == InterfaceID))
7948 			{
7949 
7950 			// If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
7951 			// This happens when we initially walk all the DNS servers and set the validity bit on the question.
7952 			// Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
7953 			// part and still do some redundant steps e.g., InterfaceID match
7954 
7955 			if (nameMatch) bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
7956 			else bettermatch = 0;
7957 
7958 			// If we found a better match (bettermatch == 1) then we don't need to
7959 			// compare penalty times. But if we found an equal match, then we compare
7960 			// the penalty times to pick a better match
7961 
7962 			if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
7963 				{ currindex = index; curmatch = curr; bestmatchlen = currcount; bestPenaltyTime = currPenaltyTime; }
7964 			}
7965 		index++;
7966 		}
7967 	if (selected) *selected = currindex;
7968 	return curmatch;
7969 	}
7970 
7971 // Look up a DNS Server, matching by name and InterfaceID
7972 mDNSexport DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID)
7973     {
7974 	DNSServer *curmatch = mDNSNULL;
7975 	char *ifname = mDNSNULL;	// for logging purposes only
7976 	mDNSOpaque64 allValid;
7977 
7978 	if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
7979 		InterfaceID = mDNSNULL;
7980 
7981 	if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
7982 
7983 	// By passing in all ones, we make sure that every DNS server is considered
7984 	allValid.l[0] = allValid.l[1] = 0xFFFFFFFF;
7985 
7986 	curmatch = GetBestServer(m, name, InterfaceID, allValid, mDNSNULL, mDNStrue);
7987 
7988 	if (curmatch != mDNSNULL)
7989 		LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
7990 		    mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
7991 		InterfaceID, name);
7992 	else
7993 		LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
7994 
7995 	return(curmatch);
7996 	}
7997 
7998 // Look up a DNS Server for a question within its valid DNSServer bits
7999 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
8000     {
8001 	DNSServer *curmatch = mDNSNULL;
8002 	char *ifname = mDNSNULL;	// for logging purposes only
8003 	mDNSInterfaceID InterfaceID = question->InterfaceID;
8004 	const domainname *name = &question->qname;
8005 	int currindex;
8006 
8007 	if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
8008 		InterfaceID = mDNSNULL;
8009 
8010 	if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
8011 
8012 	if (!mDNSOpaque64IsZero(&question->validDNSServers))
8013 		{
8014 		curmatch = GetBestServer(m, name, InterfaceID, question->validDNSServers, &currindex, mDNSfalse);
8015 		if (currindex != -1) bit_clr_opaque64(question->validDNSServers, currindex);
8016 		}
8017 
8018 	if (curmatch != mDNSNULL)
8019 		LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question, &curmatch->addr,
8020 		    mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
8021 		InterfaceID, name, DNSTypeName(question->qtype));
8022 	else
8023 		LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question, ifname ? ifname : "None", InterfaceID, name, DNSTypeName(question->qtype));
8024 
8025 	return(curmatch);
8026 	}
8027 
8028 
8029 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
8030 	(mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
8031 
8032 // Called in normal client context (lock not held)
8033 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
8034 	{
8035 	DNSQuestion *q;
8036 	(void)n;    // Unused
8037 	mDNS_Lock(m);
8038 	LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
8039 	for (q = m->Questions; q; q=q->next)
8040 		if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
8041 			startLLQHandshake(m, q);	// If ExternalPort is zero, will do StartLLQPolling instead
8042 #if APPLE_OSX_mDNSResponder
8043 	UpdateAutoTunnelDomainStatuses(m);
8044 #endif
8045 	mDNS_Unlock(m);
8046 	}
8047 
8048 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, domainname *qname, mDNSu16 qtype, mDNSInterfaceID InterfaceID)
8049 	{
8050 	NetworkInterfaceInfo *i;
8051 	mDNSs32 iptype;
8052 	DomainAuthInfo *AuthInfo;
8053 
8054 	if (qtype == kDNSType_A) iptype = mDNSAddrType_IPv4;
8055 	else if (qtype == kDNSType_AAAA) iptype = mDNSAddrType_IPv6;
8056 	else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname, DNSTypeName(qtype)); return mDNSfalse; }
8057 
8058 	// We still want the ability to be able to listen to the local services and hence
8059 	// don't fail .local requests. We always have a loopback interface which we don't
8060 	// check here.
8061 	if (InterfaceID != mDNSInterface_Unicast && IsLocalDomain(qname)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname, DNSTypeName(qtype)); return mDNSfalse; }
8062 
8063 	// Skip Private domains as we have special addresses to get the hosts in the Private domain
8064 	AuthInfo = GetAuthInfoForName_internal(m, qname);
8065 	if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
8066 		{ LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname, DNSTypeName(qtype)); return mDNSfalse; }
8067 
8068 	// Match on Type, Address and InterfaceID
8069 	//
8070 	// Check whether we are looking for a name that ends in .local, then presence of a link-local
8071 	// address on the interface is sufficient.
8072 	for (i = m->HostInterfaces; i; i = i->next)
8073 		{
8074 		if (i->ip.type != iptype) continue;
8075 
8076 		if (!InterfaceID || (InterfaceID == mDNSInterface_LocalOnly) || (InterfaceID == mDNSInterface_P2P) ||
8077 			(InterfaceID == mDNSInterface_Unicast) || (i->InterfaceID == InterfaceID))
8078 			{
8079 			if (iptype == mDNSAddrType_IPv4 && !mDNSv4AddressIsLoopback(&i->ip.ip.v4) && !mDNSv4AddressIsLinkLocal(&i->ip.ip.v4))
8080 				{
8081 				LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname, DNSTypeName(qtype),
8082 					&i->ip.ip.v4);
8083 				if (m->SleepState == SleepState_Sleeping)
8084 					LogInfo("ShouldSuppressQuery: Would have returned true earlier");
8085 				return mDNSfalse;
8086 				}
8087 			else if (iptype == mDNSAddrType_IPv6 &&
8088 				!mDNSv6AddressIsLoopback(&i->ip.ip.v6) &&
8089 				!mDNSv6AddressIsLinkLocal(&i->ip.ip.v6) &&
8090 				!mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelHostAddr) &&
8091 				!mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelRelayAddrOut))
8092 				{
8093 				LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname, DNSTypeName(qtype),
8094 					&i->ip.ip.v6);
8095 				if (m->SleepState == SleepState_Sleeping)
8096 					LogInfo("ShouldSuppressQuery: Would have returned true earlier");
8097 				return mDNSfalse;
8098 				}
8099 			}
8100 		}
8101 	LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname, DNSTypeName(qtype));
8102 	return mDNStrue;
8103 	}
8104 
8105 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
8106 	{
8107 	CacheRecord *rr;
8108 	mDNSu32 slot;
8109 	CacheGroup *cg;
8110 
8111 	slot = HashSlot(&q->qname);
8112 	cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
8113 	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8114 		{
8115 		// Don't deliver RMV events for negative records
8116 		if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
8117 			{
8118  			LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
8119 				CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
8120 			continue;
8121 			}
8122 
8123 		if (SameNameRecordAnswersQuestion(&rr->resrec, q))
8124 			{
8125  			LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
8126 				q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
8127 
8128 			q->CurrentAnswers--;
8129 			if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
8130 			if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
8131 
8132 			if (rr->CRActiveQuestion == q)
8133 				{
8134 				DNSQuestion *qptr;
8135 				// If this was the active question for this cache entry, it was the one that was
8136 				// responsible for keeping the cache entry fresh when the cache entry was reaching
8137 				// its expiry. We need to handover the responsibility to someone else. Otherwise,
8138 				// when the cache entry is about to expire, we won't find an active question
8139 				// (pointed by CRActiveQuestion) to refresh the cache.
8140 				for (qptr = m->Questions; qptr; qptr=qptr->next)
8141  					if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
8142 						break;
8143 
8144 				if (qptr)
8145 					LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
8146 						"Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
8147 						qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
8148 
8149 				rr->CRActiveQuestion = qptr;		// Question used to be active; new value may or may not be null
8150 				if (!qptr) m->rrcache_active--;	// If no longer active, decrement rrcache_active count
8151 				}
8152 			AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
8153 			if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
8154 			}
8155 		}
8156 	}
8157 
8158 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
8159 	{
8160 	DNSQuestion *q;
8161 	for (q = m->NewQuestions; q; q = q->next)
8162 		if (q == question) return mDNStrue;
8163 	return mDNSfalse;
8164 	}
8165 
8166 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
8167 	{
8168 	AuthRecord *rr;
8169 	mDNSu32 slot;
8170 	AuthGroup *ag;
8171 
8172 	if (m->CurrentQuestion)
8173 		LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
8174 			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
8175 
8176 	if (IsQuestionNew(m, q))
8177 		{
8178 		LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
8179 		return mDNStrue;
8180 		}
8181 	m->CurrentQuestion = q;
8182 	slot = AuthHashSlot(&q->qname);
8183 	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
8184 	if (ag)
8185 		{
8186 		for (rr = ag->members; rr; rr=rr->next)
8187 			// Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
8188 			if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
8189 				{
8190 				LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
8191 					ARDisplayString(m, rr));
8192 				if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
8193 					{
8194 					LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
8195 						" (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
8196 						q->CurrentAnswers, q->LOAddressAnswers);
8197 					continue;
8198 					}
8199 				AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv);		// MUST NOT dereference q again
8200 				if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
8201 				}
8202 		}
8203 	m->CurrentQuestion = mDNSNULL;
8204 	return mDNStrue;
8205 	}
8206 
8207 // Returns false if the question got deleted while delivering the RMV events
8208 // The caller should handle the case
8209 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
8210 	{
8211 	if (m->CurrentQuestion)
8212 		LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
8213 			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
8214 
8215 	// If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
8216 	// If this question was answered using local auth records, then you can't deliver RMVs using cache
8217 	if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
8218 		{
8219 		m->CurrentQuestion = q;
8220 		CacheRecordRmvEventsForCurrentQuestion(m, q);
8221 		if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
8222 		m->CurrentQuestion = mDNSNULL;
8223 		}
8224 	else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
8225 	return mDNStrue;
8226 	}
8227 
8228 // The caller should hold the lock
8229 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
8230 	{
8231 	DNSQuestion *q;
8232 	DNSQuestion *restart = mDNSNULL;
8233 
8234 	// We look through all questions including new questions. During network change events,
8235 	// we potentially restart questions here in this function that ends up as new questions,
8236 	// which may be suppressed at this instance. Before it is handled we get another network
8237 	// event that changes the status e.g., address becomes available. If we did not process
8238 	// new questions, we would never change its SuppressQuery status.
8239 	//
8240 	// CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
8241 	// application callback can potentially stop the current question (detected by CurrentQuestion) or
8242 	// *any* other question which could be the next one that we may process here. RestartQuestion
8243 	// points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
8244 	// if the "next" question is stopped while the CurrentQuestion is stopped
8245 	if (m->RestartQuestion)
8246 		LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
8247 			m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
8248 	m->RestartQuestion = m->Questions;
8249 	while (m->RestartQuestion)
8250 		{
8251 		q = m->RestartQuestion;
8252 		m->RestartQuestion = q->next;
8253 		if (!mDNSOpaque16IsZero(q->TargetQID) && q->SuppressUnusable)
8254 			{
8255 			mDNSBool old = q->SuppressQuery;
8256 			q->SuppressQuery = ShouldSuppressQuery(m, &q->qname, q->qtype, q->InterfaceID);
8257 			if (q->SuppressQuery != old)
8258 				{
8259 				// NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
8260 				// LOddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
8261 				// LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
8262 
8263   				if (q->SuppressQuery)
8264   					{
8265   					// Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
8266  					// followed by a negative cache response. Temporarily turn off suppression so that
8267  					// AnswerCurrentQuestionWithResourceRecord can answer the question
8268  					q->SuppressQuery = mDNSfalse;
8269  					if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
8270  					q->SuppressQuery = mDNStrue;
8271   					}
8272 
8273 				// SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
8274 				// and SuppressQuery status does not mean anything for these questions. As we are going to stop the
8275 				// question below, we need to deliver the RMV events so that the ADDs that will be delivered during
8276 				// the restart will not be a duplicate ADD
8277  				if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
8278 
8279 				// There are two cases here.
8280 				//
8281 				// 1. Previously it was suppressed and now it is not suppressed, restart the question so
8282 				// that it will start as a new question. Note that we can't just call ActivateUnicastQuery
8283 				// because when we get the response, if we had entries in the cache already, it will not answer
8284 				// this question if the cache entry did not change. Hence, we need to restart
8285 				// the query so that it can be answered from the cache.
8286 				//
8287 				// 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
8288 				// so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
8289 				// is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
8290 				// A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
8291 				// (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
8292 				// immediate response and not want to be blocked behind a question that is querying DNS servers. When
8293 				// the question is not suppressed, we don't want two active questions sending packets on the wire.
8294 				// This affects both efficiency and also the current design where there is only one active question
8295 				// pointed to from a cache entry.
8296 				//
8297 				// We restart queries in a two step process by first calling stop and build a temporary list which we
8298 				// will restart at the end. The main reason for the two step process is to handle duplicate questions.
8299 				// If there are duplicate questions, calling stop inherits the values from another question on the list (which
8300 				// will soon become the real question) including q->ThisQInterval which might be zero if it was
8301 				// suppressed before. At the end when we have restarted all questions, none of them is active as each
8302 				// inherits from one another and we need to reactivate one of the questions here which is a little hacky.
8303 				//
8304 				// It is much cleaner and less error prone to build a list of questions and restart at the end.
8305 
8306 				LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8307 				mDNS_StopQuery_internal(m, q);
8308 				q->next = restart;
8309 				restart = q;
8310 				}
8311 			}
8312 		}
8313 	while (restart)
8314 		{
8315 		q = restart;
8316 		restart = restart->next;
8317 		q->next = mDNSNULL;
8318 		LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8319 		mDNS_StartQuery_internal(m, q);
8320 		}
8321 	}
8322 
8323 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
8324 	{
8325 	if (question->Target.type && !ValidQuestionTarget(question))
8326 		{
8327 		LogMsg("mDNS_StartQuery_internal: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
8328 			question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
8329 		question->Target.type = mDNSAddrType_None;
8330 		}
8331 
8332 	if (!question->Target.type) question->TargetPort = zeroIPPort;	// If no question->Target specified clear TargetPort
8333 
8334 	question->TargetQID =
8335 #ifndef UNICAST_DISABLED
8336 		(question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
8337 #endif // UNICAST_DISABLED
8338 		zeroID;
8339 
8340 	debugf("mDNS_StartQuery: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8341 
8342 	if (m->rrcache_size == 0)	// Can't do queries if we have no cache space allocated
8343 		return(mStatus_NoCache);
8344 	else
8345 		{
8346 		int i;
8347 		DNSQuestion **q;
8348 
8349 		if (!ValidateDomainName(&question->qname))
8350 			{
8351 			LogMsg("Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8352 			return(mStatus_Invalid);
8353 			}
8354 
8355 		// Note: It important that new questions are appended at the *end* of the list, not prepended at the start
8356 		q = &m->Questions;
8357 		if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) q = &m->LocalOnlyQuestions;
8358 		while (*q && *q != question) q=&(*q)->next;
8359 
8360 		if (*q)
8361 			{
8362 			LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
8363 				question->qname.c, DNSTypeName(question->qtype), question);
8364 			return(mStatus_AlreadyRegistered);
8365 			}
8366 
8367 		*q = question;
8368 
8369 		// If this question is referencing a specific interface, verify it exists
8370 		if (question->InterfaceID && question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_Unicast && question->InterfaceID != mDNSInterface_P2P)
8371 			{
8372 			NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
8373 			if (!intf)
8374 				LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
8375 					question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
8376 			}
8377 
8378 		// Note: In the case where we already have the answer to this question in our cache, that may be all the client
8379 		// wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
8380 		// be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
8381 		// If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
8382 		// that to go out immediately.
8383 		question->next              = mDNSNULL;
8384 		question->qnamehash         = DomainNameHashValue(&question->qname);	// MUST do this before FindDuplicateQuestion()
8385 		question->DelayAnswering    = CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash, HashSlot(&question->qname));
8386 		question->LastQTime         = m->timenow;
8387 		question->ThisQInterval     = InitialQuestionInterval;					// MUST be > zero for an active question
8388 		question->ExpectUnicastResp = 0;
8389 		question->LastAnswerPktNum  = m->PktNum;
8390 		question->RecentAnswerPkts  = 0;
8391 		question->CurrentAnswers    = 0;
8392 		question->LargeAnswers      = 0;
8393 		question->UniqueAnswers     = 0;
8394 		question->LOAddressAnswers  = 0;
8395 		question->FlappingInterface1 = mDNSNULL;
8396 		question->FlappingInterface2 = mDNSNULL;
8397 		// Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
8398 		question->AuthInfo          = GetAuthInfoForQuestion(m, question);
8399 		if (question->SuppressUnusable)
8400 			question->SuppressQuery = ShouldSuppressQuery(m, &question->qname, question->qtype, question->InterfaceID);
8401 		else
8402 			question->SuppressQuery = 0;
8403 		question->DuplicateOf       = FindDuplicateQuestion(m, question);
8404 		question->NextInDQList      = mDNSNULL;
8405 		question->SendQNow          = mDNSNULL;
8406 		question->SendOnAll         = mDNSfalse;
8407 		question->RequestUnicast    = 0;
8408 		question->LastQTxTime       = m->timenow;
8409 		question->CNAMEReferrals    = 0;
8410 
8411 		// We'll create our question->LocalSocket on demand, if needed.
8412 		// We won't need one for duplicate questions, or from questions answered immediately out of the cache.
8413 		// We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
8414 		// NAT mapping for receiving inbound add/remove events.
8415 		question->LocalSocket       = mDNSNULL;
8416 		question->deliverAddEvents  = mDNSfalse;
8417 		question->qDNSServer        = mDNSNULL;
8418 		question->unansweredQueries = 0;
8419 		question->nta               = mDNSNULL;
8420 		question->servAddr          = zeroAddr;
8421 		question->servPort          = zeroIPPort;
8422 		question->tcp               = mDNSNULL;
8423 		question->NoAnswer          = NoAnswer_Normal;
8424 
8425 		question->state             = LLQ_InitialRequest;
8426 		question->ReqLease          = 0;
8427 		question->expire            = 0;
8428 		question->ntries            = 0;
8429 		question->id                = zeroOpaque64;
8430 		question->validDNSServers   = zeroOpaque64;
8431 		question->triedAllServersOnce = 0;
8432 		question->noServerResponse  = 0;
8433 		question->StopTime = 0;
8434 		if (question->WakeOnResolve)
8435 			{
8436 			question->WakeOnResolveCount = InitialWakeOnResolveCount;
8437 			mDNS_PurgeBeforeResolve(m, question);
8438 			}
8439 		else
8440 			question->WakeOnResolveCount = 0;
8441 
8442 		if (question->DuplicateOf) question->AuthInfo = question->DuplicateOf->AuthInfo;
8443 
8444 		for (i=0; i<DupSuppressInfoSize; i++)
8445 			question->DupSuppress[i].InterfaceID = mDNSNULL;
8446 
8447 		debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
8448 			question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
8449 			NextQSendTime(question) - m->timenow,
8450 			question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
8451 			question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
8452 
8453 		if (question->DelayAnswering)
8454 			LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
8455 				question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
8456 
8457 		if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
8458 			{
8459 			if (!m->NewLocalOnlyQuestions) m->NewLocalOnlyQuestions = question;
8460 			}
8461 		else
8462 			{
8463 			if (!m->NewQuestions) m->NewQuestions = question;
8464 
8465 			// If the question's id is non-zero, then it's Wide Area
8466 			// MUST NOT do this Wide Area setup until near the end of
8467 			// mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
8468 			// NS, etc.) and if we haven't finished setting up our own question and setting
8469 			// m->NewQuestions if necessary then we could end up recursively re-entering
8470 			// this routine with the question list data structures in an inconsistent state.
8471 			if (!mDNSOpaque16IsZero(question->TargetQID))
8472 				{
8473 				// Duplicate questions should have the same DNSServers so that when we find
8474 				// a matching resource record, all of them get the answers. Calling GetServerForQuestion
8475 				// for the duplicate question may get a different DNS server from the original question
8476 				mDNSu32 timeout = SetValidDNSServers(m, question);
8477 				// We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
8478 				// a networking change/search domain change that calls this function again we keep
8479 				// reinitializing the timeout value which means it may never timeout. If this becomes
8480 				// a common case in the future, we can easily fix this by adding extra state that
8481 				// indicates that we have already set the StopTime.
8482 				if (question->TimeoutQuestion)
8483 					question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
8484 				if (question->DuplicateOf)
8485 					{
8486 					question->validDNSServers = question->DuplicateOf->validDNSServers;
8487 					question->qDNSServer = question->DuplicateOf->qDNSServer;
8488 					LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), Timeout %d, DNS Server %#a:%d",
8489 						question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype), timeout,
8490 						question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
8491 					    mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
8492 					}
8493 				else
8494 					{
8495 					question->qDNSServer = GetServerForQuestion(m, question);
8496 					LogInfo("mDNS_StartQuery_internal: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
8497 						question, question->qname.c, DNSTypeName(question->qtype), timeout,
8498 						question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
8499 					    mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
8500 					}
8501 				ActivateUnicastQuery(m, question, mDNSfalse);
8502 
8503 				// If long-lived query, and we don't have our NAT mapping active, start it now
8504 				if (question->LongLived && !m->LLQNAT.clientContext)
8505 					{
8506 					m->LLQNAT.Protocol       = NATOp_MapUDP;
8507 					m->LLQNAT.IntPort        = m->UnicastPort4;
8508 					m->LLQNAT.RequestedPort  = m->UnicastPort4;
8509 					m->LLQNAT.clientCallback = LLQNATCallback;
8510 					m->LLQNAT.clientContext  = (void*)1; // Means LLQ NAT Traversal is active
8511 					mDNS_StartNATOperation_internal(m, &m->LLQNAT);
8512 					}
8513 
8514 #if APPLE_OSX_mDNSResponder
8515 				if (question->LongLived)
8516 					UpdateAutoTunnelDomainStatuses(m);
8517 #endif
8518 
8519 				}
8520 			else
8521 				{
8522 				if (question->TimeoutQuestion)
8523 					question->StopTime = NonZeroTime(m->timenow + GetTimeoutForMcastQuestion(m, question) * mDNSPlatformOneSecond);
8524 				}
8525 			if (question->StopTime) SetNextQueryStopTime(m, question);
8526 			SetNextQueryTime(m,question);
8527 			}
8528 
8529 		return(mStatus_NoError);
8530 		}
8531 	}
8532 
8533 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
8534 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
8535 	{
8536 	debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
8537 	// This function may be called anytime to free the zone information.The question may or may not have stopped.
8538 	// If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
8539 	// call it again
8540 	if (nta->question.ThisQInterval != -1)
8541 		{
8542 		mDNS_StopQuery_internal(m, &nta->question);
8543 		if (nta->question.ThisQInterval != -1)
8544 			LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
8545 		}
8546 	mDNSPlatformMemFree(nta);
8547 	}
8548 
8549 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
8550 	{
8551 	const mDNSu32 slot = HashSlot(&question->qname);
8552 	CacheGroup *cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
8553 	CacheRecord *rr;
8554 	DNSQuestion **qp = &m->Questions;
8555 
8556 	//LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8557 
8558 	if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) qp = &m->LocalOnlyQuestions;
8559 	while (*qp && *qp != question) qp=&(*qp)->next;
8560 	if (*qp) *qp = (*qp)->next;
8561 	else
8562 		{
8563 #if !ForceAlerts
8564 		if (question->ThisQInterval >= 0)	// Only log error message if the query was supposed to be active
8565 #endif
8566 			LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
8567 				question->qname.c, DNSTypeName(question->qtype));
8568 #if ForceAlerts
8569 		*(long*)0 = 0;
8570 #endif
8571 		return(mStatus_BadReferenceErr);
8572 		}
8573 
8574 	// Take care to cut question from list *before* calling UpdateQuestionDuplicates
8575 	UpdateQuestionDuplicates(m, question);
8576 	// But don't trash ThisQInterval until afterwards.
8577 	question->ThisQInterval = -1;
8578 
8579 	// If there are any cache records referencing this as their active question, then see if there is any
8580 	// other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
8581 	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8582 		{
8583 		if (rr->CRActiveQuestion == question)
8584 			{
8585 			DNSQuestion *q;
8586 			// Checking for ActiveQuestion filters questions that are suppressed also
8587 			// as suppressed questions are not active
8588 			for (q = m->Questions; q; q=q->next)		// Scan our list of questions
8589 				if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
8590 					break;
8591 			if (q)
8592 				debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
8593 					"CurrentAnswers %d, SuppressQuery %d", q, CRDisplayString(m,rr), question->CurrentAnswers, q->CurrentAnswers, q->SuppressQuery);
8594 			rr->CRActiveQuestion = q;		// Question used to be active; new value may or may not be null
8595 			if (!q) m->rrcache_active--;	// If no longer active, decrement rrcache_active count
8596 			}
8597 		}
8598 
8599 	// If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
8600 	// bump its pointer forward one question.
8601 	if (m->CurrentQuestion == question)
8602 		{
8603 		debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
8604 			question->qname.c, DNSTypeName(question->qtype));
8605 		m->CurrentQuestion = question->next;
8606 		}
8607 
8608 	if (m->NewQuestions == question)
8609 		{
8610 		debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
8611 			question->qname.c, DNSTypeName(question->qtype));
8612 		m->NewQuestions = question->next;
8613 		}
8614 
8615 	if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
8616 
8617 	if (m->RestartQuestion == question)
8618 		{
8619 		LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
8620 			question->qname.c, DNSTypeName(question->qtype));
8621 		m->RestartQuestion = question->next;
8622 		}
8623 
8624 	// Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
8625 	question->next = mDNSNULL;
8626 
8627 	// LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
8628 
8629 	// And finally, cancel any associated GetZoneData operation that's still running.
8630 	// Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
8631 	// so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
8632 	// invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
8633 	// *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
8634 	if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
8635 	if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
8636 	if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
8637 		{
8638 		// Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
8639 		DNSQuestion *q;
8640 		for (q = m->Questions; q; q=q->next)
8641 			if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
8642 		if (!q)
8643 			{
8644 			if (!m->LLQNAT.clientContext)		// Should never happen, but just in case...
8645 				LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
8646 			else
8647 				{
8648 				LogInfo("Stopping LLQNAT");
8649 				mDNS_StopNATOperation_internal(m, &m->LLQNAT);
8650 				m->LLQNAT.clientContext = mDNSNULL; // Means LLQ NAT Traversal not running
8651 				}
8652 			}
8653 
8654 		// If necessary, tell server it can delete this LLQ state
8655 		if (question->state == LLQ_Established)
8656 			{
8657 			question->ReqLease = 0;
8658 			sendLLQRefresh(m, question);
8659 			// If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
8660 			// We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
8661 			// crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
8662 			// we let that run out its natural course and complete asynchronously.
8663 			if (question->tcp)
8664 				{
8665 				question->tcp->question = mDNSNULL;
8666 				question->tcp           = mDNSNULL;
8667 				}
8668 			}
8669 #if APPLE_OSX_mDNSResponder
8670 		UpdateAutoTunnelDomainStatuses(m);
8671 #endif
8672 		}
8673 	// wait until we send the refresh above which needs the nta
8674 	if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
8675 
8676 	return(mStatus_NoError);
8677 	}
8678 
8679 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
8680 	{
8681 	mStatus status;
8682 	mDNS_Lock(m);
8683 	status = mDNS_StartQuery_internal(m, question);
8684 	mDNS_Unlock(m);
8685 	return(status);
8686 	}
8687 
8688 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
8689 	{
8690 	mStatus status;
8691 	mDNS_Lock(m);
8692 	status = mDNS_StopQuery_internal(m, question);
8693 	mDNS_Unlock(m);
8694 	return(status);
8695 	}
8696 
8697 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
8698 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
8699 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
8700 // specifically to catch and report if the client callback does try to make API calls
8701 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
8702 	{
8703 	mStatus status;
8704 	DNSQuestion *qq;
8705 	mDNS_Lock(m);
8706 
8707 	// Check if question is new -- don't want to give remove events for a question we haven't even answered yet
8708 	for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
8709 
8710 	status = mDNS_StopQuery_internal(m, question);
8711 	if (status == mStatus_NoError && !qq)
8712 		{
8713 		const CacheRecord *rr;
8714 		const mDNSu32 slot = HashSlot(&question->qname);
8715 		CacheGroup *const cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
8716 		LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8717 		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8718 			if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
8719 				{
8720 				// Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
8721 				if (question->QuestionCallback)
8722 					question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
8723 				}
8724 		}
8725 	mDNS_Unlock(m);
8726 	return(status);
8727 	}
8728 
8729 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
8730 	{
8731 	mStatus status;
8732 	mDNS_Lock(m);
8733 	status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8734 	if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
8735 	mDNS_Unlock(m);
8736 	return(status);
8737 	}
8738 
8739 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
8740 	{
8741 	mStatus status = mStatus_BadReferenceErr;
8742 	CacheRecord *cr;
8743 	mDNS_Lock(m);
8744 	cr = FindIdenticalRecordInCache(m, rr);
8745 	debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
8746 	if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8747 	if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
8748 	mDNS_Unlock(m);
8749 	return(status);
8750 	}
8751 
8752 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
8753 	const domainname *const srv, const domainname *const domain,
8754 	const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
8755 	{
8756 	question->InterfaceID      = InterfaceID;
8757 	question->Target           = zeroAddr;
8758 	question->qtype            = kDNSType_PTR;
8759 	question->qclass           = kDNSClass_IN;
8760 	question->LongLived        = mDNStrue;
8761 	question->ExpectUnique     = mDNSfalse;
8762 	question->ForceMCast       = ForceMCast;
8763 	question->ReturnIntermed   = mDNSfalse;
8764 	question->SuppressUnusable = mDNSfalse;
8765 	question->SearchListIndex  = 0;
8766 	question->AppendSearchDomains = 0;
8767 	question->RetryWithSearchDomains = mDNSfalse;
8768 	question->TimeoutQuestion  = 0;
8769 	question->WakeOnResolve    = 0;
8770 	question->qnameOrig        = mDNSNULL;
8771 	question->QuestionCallback = Callback;
8772 	question->QuestionContext  = Context;
8773 	if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) return(mStatus_BadParamErr);
8774 
8775 	return(mDNS_StartQuery_internal(m, question));
8776 	}
8777 
8778 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
8779 	const domainname *const srv, const domainname *const domain,
8780 	const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
8781 	{
8782 	mStatus status;
8783 	mDNS_Lock(m);
8784 	status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, ForceMCast, Callback, Context);
8785 	mDNS_Unlock(m);
8786 	return(status);
8787 	}
8788 
8789 mDNSlocal mDNSBool MachineHasActiveIPv6(mDNS *const m)
8790 	{
8791 	NetworkInterfaceInfo *intf;
8792 	for (intf = m->HostInterfaces; intf; intf = intf->next)
8793 	if (intf->ip.type == mDNSAddrType_IPv6) return(mDNStrue);
8794 	return(mDNSfalse);
8795 	}
8796 
8797 mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8798 	{
8799 	ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8800 	mDNSBool PortChanged = !mDNSSameIPPort(query->info->port, answer->rdata->u.srv.port);
8801 	if (!AddRecord) return;
8802 	if (answer->rrtype != kDNSType_SRV) return;
8803 
8804 	query->info->port = answer->rdata->u.srv.port;
8805 
8806 	// If this is our first answer, then set the GotSRV flag and start the address query
8807 	if (!query->GotSRV)
8808 		{
8809 		query->GotSRV             = mDNStrue;
8810 		query->qAv4.InterfaceID   = answer->InterfaceID;
8811 		AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
8812 		query->qAv6.InterfaceID   = answer->InterfaceID;
8813 		AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
8814 		mDNS_StartQuery(m, &query->qAv4);
8815 		// Only do the AAAA query if this machine actually has IPv6 active
8816 		if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
8817 		}
8818 	// If this is not our first answer, only re-issue the address query if the target host name has changed
8819 	else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
8820 		!SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
8821 		{
8822 		mDNS_StopQuery(m, &query->qAv4);
8823 		if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery(m, &query->qAv6);
8824 		if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
8825 			{
8826 			// If we get here, it means:
8827 			// 1. This is not our first SRV answer
8828 			// 2. The interface ID is different, but the target host and port are the same
8829 			// This implies that we're seeing the exact same SRV record on more than one interface, so we should
8830 			// make our address queries at least as broad as the original SRV query so that we catch all the answers.
8831 			query->qAv4.InterfaceID = query->qSRV.InterfaceID;	// Will be mDNSInterface_Any, or a specific interface
8832 			query->qAv6.InterfaceID = query->qSRV.InterfaceID;
8833 			}
8834 		else
8835 			{
8836 			query->qAv4.InterfaceID   = answer->InterfaceID;
8837 			AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
8838 			query->qAv6.InterfaceID   = answer->InterfaceID;
8839 			AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
8840 			}
8841 		debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query->qAv4.qname.c, DNSTypeName(query->qAv4.qtype));
8842 		mDNS_StartQuery(m, &query->qAv4);
8843 		// Only do the AAAA query if this machine actually has IPv6 active
8844 		if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
8845 		}
8846 	else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
8847 		{
8848 		if (++query->Answers >= 100)
8849 			debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
8850 				query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
8851 				mDNSVal16(answer->rdata->u.srv.port));
8852 		query->ServiceInfoQueryCallback(m, query);
8853 		}
8854 	// CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8855 	// callback function is allowed to do anything, including deleting this query and freeing its memory.
8856 	}
8857 
8858 mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8859 	{
8860 	ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8861 	if (!AddRecord) return;
8862 	if (answer->rrtype != kDNSType_TXT) return;
8863 	if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
8864 
8865 	query->GotTXT       = mDNStrue;
8866 	query->info->TXTlen = answer->rdlength;
8867 	query->info->TXTinfo[0] = 0;		// In case answer->rdlength is zero
8868 	mDNSPlatformMemCopy(query->info->TXTinfo, answer->rdata->u.txt.c, answer->rdlength);
8869 
8870 	verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
8871 
8872 	// CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8873 	// callback function is allowed to do anything, including deleting this query and freeing its memory.
8874 	if (query->ServiceInfoQueryCallback && query->GotADD)
8875 		{
8876 		if (++query->Answers >= 100)
8877 			debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
8878 				query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
8879 		query->ServiceInfoQueryCallback(m, query);
8880 		}
8881 	}
8882 
8883 mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8884 	{
8885 	ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8886 	//LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
8887 	if (!AddRecord) return;
8888 
8889 	if (answer->rrtype == kDNSType_A)
8890 		{
8891 		query->info->ip.type = mDNSAddrType_IPv4;
8892 		query->info->ip.ip.v4 = answer->rdata->u.ipv4;
8893 		}
8894 	else if (answer->rrtype == kDNSType_AAAA)
8895 		{
8896 		query->info->ip.type = mDNSAddrType_IPv6;
8897 		query->info->ip.ip.v6 = answer->rdata->u.ipv6;
8898 		}
8899 	else
8900 		{
8901 		debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name->c, answer->rrtype, DNSTypeName(answer->rrtype));
8902 		return;
8903 		}
8904 
8905 	query->GotADD = mDNStrue;
8906 	query->info->InterfaceID = answer->InterfaceID;
8907 
8908 	verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
8909 
8910 	// CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8911 	// callback function is allowed to do anything, including deleting this query and freeing its memory.
8912 	if (query->ServiceInfoQueryCallback && query->GotTXT)
8913 		{
8914 		if (++query->Answers >= 100)
8915 			debugf(answer->rrtype == kDNSType_A ?
8916 				"**** WARNING **** have given %lu answers for %##s (A) %.4a" :
8917 				"**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
8918 				query->Answers, query->qSRV.qname.c, &answer->rdata->u.data);
8919 		query->ServiceInfoQueryCallback(m, query);
8920 		}
8921 	}
8922 
8923 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
8924 // If the query is not interface-specific, then InterfaceID may be zero
8925 // Each time the Callback is invoked, the remainder of the fields will have been filled in
8926 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
8927 mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
8928 	ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
8929 	{
8930 	mStatus status;
8931 	mDNS_Lock(m);
8932 
8933 	query->qSRV.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8934 	query->qSRV.InterfaceID         = info->InterfaceID;
8935 	query->qSRV.Target              = zeroAddr;
8936 	AssignDomainName(&query->qSRV.qname, &info->name);
8937 	query->qSRV.qtype               = kDNSType_SRV;
8938 	query->qSRV.qclass              = kDNSClass_IN;
8939 	query->qSRV.LongLived           = mDNSfalse;
8940 	query->qSRV.ExpectUnique        = mDNStrue;
8941 	query->qSRV.ForceMCast          = mDNSfalse;
8942 	query->qSRV.ReturnIntermed      = mDNSfalse;
8943 	query->qSRV.SuppressUnusable    = mDNSfalse;
8944 	query->qSRV.SearchListIndex     = 0;
8945 	query->qSRV.AppendSearchDomains = 0;
8946 	query->qSRV.RetryWithSearchDomains = mDNSfalse;
8947 	query->qSRV.TimeoutQuestion     = 0;
8948 	query->qSRV.WakeOnResolve       = 0;
8949 	query->qSRV.qnameOrig           = mDNSNULL;
8950 	query->qSRV.QuestionCallback    = FoundServiceInfoSRV;
8951 	query->qSRV.QuestionContext     = query;
8952 
8953 	query->qTXT.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8954 	query->qTXT.InterfaceID         = info->InterfaceID;
8955 	query->qTXT.Target              = zeroAddr;
8956 	AssignDomainName(&query->qTXT.qname, &info->name);
8957 	query->qTXT.qtype               = kDNSType_TXT;
8958 	query->qTXT.qclass              = kDNSClass_IN;
8959 	query->qTXT.LongLived           = mDNSfalse;
8960 	query->qTXT.ExpectUnique        = mDNStrue;
8961 	query->qTXT.ForceMCast          = mDNSfalse;
8962 	query->qTXT.ReturnIntermed      = mDNSfalse;
8963 	query->qTXT.SuppressUnusable    = mDNSfalse;
8964 	query->qTXT.SearchListIndex     = 0;
8965 	query->qTXT.AppendSearchDomains = 0;
8966 	query->qTXT.RetryWithSearchDomains = mDNSfalse;
8967 	query->qTXT.TimeoutQuestion     = 0;
8968 	query->qTXT.WakeOnResolve       = 0;
8969 	query->qTXT.qnameOrig           = mDNSNULL;
8970 	query->qTXT.QuestionCallback    = FoundServiceInfoTXT;
8971 	query->qTXT.QuestionContext     = query;
8972 
8973 	query->qAv4.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8974 	query->qAv4.InterfaceID         = info->InterfaceID;
8975 	query->qAv4.Target              = zeroAddr;
8976 	query->qAv4.qname.c[0]          = 0;
8977 	query->qAv4.qtype               = kDNSType_A;
8978 	query->qAv4.qclass              = kDNSClass_IN;
8979 	query->qAv4.LongLived           = mDNSfalse;
8980 	query->qAv4.ExpectUnique        = mDNStrue;
8981 	query->qAv4.ForceMCast          = mDNSfalse;
8982 	query->qAv4.ReturnIntermed      = mDNSfalse;
8983 	query->qAv4.SuppressUnusable    = mDNSfalse;
8984 	query->qAv4.SearchListIndex     = 0;
8985 	query->qAv4.AppendSearchDomains = 0;
8986 	query->qAv4.RetryWithSearchDomains = mDNSfalse;
8987 	query->qAv4.TimeoutQuestion     = 0;
8988 	query->qAv4.WakeOnResolve       = 0;
8989 	query->qAv4.qnameOrig           = mDNSNULL;
8990 	query->qAv4.QuestionCallback    = FoundServiceInfo;
8991 	query->qAv4.QuestionContext     = query;
8992 
8993 	query->qAv6.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8994 	query->qAv6.InterfaceID         = info->InterfaceID;
8995 	query->qAv6.Target              = zeroAddr;
8996 	query->qAv6.qname.c[0]          = 0;
8997 	query->qAv6.qtype               = kDNSType_AAAA;
8998 	query->qAv6.qclass              = kDNSClass_IN;
8999 	query->qAv6.LongLived           = mDNSfalse;
9000 	query->qAv6.ExpectUnique        = mDNStrue;
9001 	query->qAv6.ForceMCast          = mDNSfalse;
9002 	query->qAv6.ReturnIntermed      = mDNSfalse;
9003 	query->qAv6.SuppressUnusable    = mDNSfalse;
9004 	query->qAv6.SearchListIndex     = 0;
9005 	query->qAv6.AppendSearchDomains = 0;
9006 	query->qAv6.RetryWithSearchDomains = mDNSfalse;
9007 	query->qAv6.TimeoutQuestion     = 0;
9008 	query->qAv6.WakeOnResolve       = 0;
9009 	query->qAv6.qnameOrig           = mDNSNULL;
9010 	query->qAv6.QuestionCallback    = FoundServiceInfo;
9011 	query->qAv6.QuestionContext     = query;
9012 
9013 	query->GotSRV                   = mDNSfalse;
9014 	query->GotTXT                   = mDNSfalse;
9015 	query->GotADD                   = mDNSfalse;
9016 	query->Answers                  = 0;
9017 
9018 	query->info                     = info;
9019 	query->ServiceInfoQueryCallback = Callback;
9020 	query->ServiceInfoQueryContext  = Context;
9021 
9022 //	info->name      = Must already be set up by client
9023 //	info->interface = Must already be set up by client
9024 	info->ip        = zeroAddr;
9025 	info->port      = zeroIPPort;
9026 	info->TXTlen    = 0;
9027 
9028 	// We use mDNS_StartQuery_internal here because we're already holding the lock
9029 	status = mDNS_StartQuery_internal(m, &query->qSRV);
9030 	if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
9031 	if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
9032 
9033 	mDNS_Unlock(m);
9034 	return(status);
9035 	}
9036 
9037 mDNSexport void    mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *q)
9038 	{
9039 	mDNS_Lock(m);
9040 	// We use mDNS_StopQuery_internal here because we're already holding the lock
9041 	if (q->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qSRV);
9042 	if (q->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qTXT);
9043 	if (q->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv4);
9044 	if (q->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv6);
9045 	mDNS_Unlock(m);
9046 	}
9047 
9048 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
9049 	const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
9050 	{
9051 	question->InterfaceID      = InterfaceID;
9052 	question->Target           = zeroAddr;
9053 	question->qtype            = kDNSType_PTR;
9054 	question->qclass           = kDNSClass_IN;
9055 	question->LongLived        = mDNSfalse;
9056 	question->ExpectUnique     = mDNSfalse;
9057 	question->ForceMCast       = mDNSfalse;
9058 	question->ReturnIntermed   = mDNSfalse;
9059 	question->SuppressUnusable = mDNSfalse;
9060 	question->SearchListIndex  = 0;
9061 	question->AppendSearchDomains = 0;
9062 	question->RetryWithSearchDomains = mDNSfalse;
9063 	question->TimeoutQuestion  = 0;
9064 	question->WakeOnResolve    = 0;
9065 	question->qnameOrig        = mDNSNULL;
9066 	question->QuestionCallback = Callback;
9067 	question->QuestionContext  = Context;
9068 	if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
9069 	if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
9070 	if (!dom) dom = &localdomain;
9071 	if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
9072 	return(mDNS_StartQuery(m, question));
9073 	}
9074 
9075 // ***************************************************************************
9076 #if COMPILER_LIKES_PRAGMA_MARK
9077 #pragma mark -
9078 #pragma mark - Responder Functions
9079 #endif
9080 
9081 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
9082 	{
9083 	mStatus status;
9084 	mDNS_Lock(m);
9085 	status = mDNS_Register_internal(m, rr);
9086 	mDNS_Unlock(m);
9087 	return(status);
9088 	}
9089 
9090 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
9091 	const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
9092 	{
9093 	if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
9094 		{
9095 		LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
9096 		return(mStatus_Invalid);
9097 		}
9098 
9099 	mDNS_Lock(m);
9100 
9101 	// If TTL is unspecified, leave TTL unchanged
9102 	if (newttl == 0) newttl = rr->resrec.rroriginalttl;
9103 
9104 	// If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
9105 	if (rr->NewRData)
9106 		{
9107 		RData *n = rr->NewRData;
9108 		rr->NewRData = mDNSNULL;							// Clear the NewRData pointer ...
9109 		if (rr->UpdateCallback)
9110 			rr->UpdateCallback(m, rr, n, rr->newrdlength);	// ...and let the client free this memory, if necessary
9111 		}
9112 
9113 	rr->NewRData             = newrdata;
9114 	rr->newrdlength          = newrdlength;
9115 	rr->UpdateCallback       = Callback;
9116 
9117 #ifndef UNICAST_DISABLED
9118 	if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
9119 		{
9120 		mStatus status = uDNS_UpdateRecord(m, rr);
9121 		// The caller frees the memory on error, don't retain stale pointers
9122 		if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
9123 		mDNS_Unlock(m);
9124 		return(status);
9125 		}
9126 #endif
9127 
9128 	if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
9129 		rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
9130 		CompleteRDataUpdate(m, rr);
9131 	else
9132 		{
9133 		rr->AnnounceCount = InitialAnnounceCount;
9134 		InitializeLastAPTime(m, rr);
9135 		while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
9136 		if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
9137 		if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
9138 		if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
9139 		if (rr->UpdateCredits <= 5)
9140 			{
9141 			mDNSu32 delay = 6 - rr->UpdateCredits;		// Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
9142 			if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
9143 			rr->ThisAPInterval *= 4;
9144 			rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
9145 			LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
9146 				rr->resrec.name->c, delay, delay > 1 ? "s" : "");
9147 			}
9148 		rr->resrec.rroriginalttl = newttl;
9149 		}
9150 
9151 	mDNS_Unlock(m);
9152 	return(mStatus_NoError);
9153 	}
9154 
9155 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
9156 // the record list and/or question list.
9157 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9158 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
9159 	{
9160 	mStatus status;
9161 	mDNS_Lock(m);
9162 	status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9163 	mDNS_Unlock(m);
9164 	return(status);
9165 	}
9166 
9167 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
9168 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
9169 
9170 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
9171 	{
9172 	NetworkInterfaceInfo *intf;
9173 	for (intf = m->HostInterfaces; intf; intf = intf->next)
9174 		if (intf->Advertise) break;
9175 	return(intf);
9176 	}
9177 
9178 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
9179 	{
9180 	char buffer[MAX_REVERSE_MAPPING_NAME];
9181 	NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
9182 	if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
9183 
9184 	// Send dynamic update for non-linklocal IPv4 Addresses
9185 	mDNS_SetupResourceRecord(&set->RR_A,     mDNSNULL, set->InterfaceID, kDNSType_A,     kHostNameTTL, kDNSRecordTypeUnique,      AuthRecordAny, mDNS_HostNameCallback, set);
9186 	mDNS_SetupResourceRecord(&set->RR_PTR,   mDNSNULL, set->InterfaceID, kDNSType_PTR,   kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
9187 	mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique,      AuthRecordAny, mDNSNULL, mDNSNULL);
9188 
9189 #if ANSWER_REMOTE_HOSTNAME_QUERIES
9190 	set->RR_A    .AllowRemoteQuery  = mDNStrue;
9191 	set->RR_PTR  .AllowRemoteQuery  = mDNStrue;
9192 	set->RR_HINFO.AllowRemoteQuery  = mDNStrue;
9193 #endif
9194 	// 1. Set up Address record to map from host name ("foo.local.") to IP address
9195 	// 2. Set up reverse-lookup PTR record to map from our address back to our host name
9196 	AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
9197 	if (set->ip.type == mDNSAddrType_IPv4)
9198 		{
9199 		set->RR_A.resrec.rrtype = kDNSType_A;
9200 		set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
9201 		// Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
9202 		mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
9203 			set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
9204 		}
9205 	else if (set->ip.type == mDNSAddrType_IPv6)
9206 		{
9207 		int i;
9208 		set->RR_A.resrec.rrtype = kDNSType_AAAA;
9209 		set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
9210 		for (i = 0; i < 16; i++)
9211 			{
9212 			static const char hexValues[] = "0123456789ABCDEF";
9213 			buffer[i * 4    ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
9214 			buffer[i * 4 + 1] = '.';
9215 			buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
9216 			buffer[i * 4 + 3] = '.';
9217 			}
9218 		mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
9219 		}
9220 
9221 	MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
9222 	set->RR_PTR.AutoTarget = Target_AutoHost;	// Tell mDNS that the target of this PTR is to be kept in sync with our host name
9223 	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
9224 
9225 	set->RR_A.RRSet = &primary->RR_A;			// May refer to self
9226 
9227 	mDNS_Register_internal(m, &set->RR_A);
9228 	mDNS_Register_internal(m, &set->RR_PTR);
9229 
9230 	if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
9231 		{
9232 		mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
9233 		AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
9234 		set->RR_HINFO.DependentOn = &set->RR_A;
9235 		mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
9236 		p += 1 + (int)p[0];
9237 		mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
9238 		mDNS_Register_internal(m, &set->RR_HINFO);
9239 		}
9240 	else
9241 		{
9242 		debugf("Not creating HINFO record: platform support layer provided no information");
9243 		set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
9244 		}
9245 	}
9246 
9247 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
9248 	{
9249 	NetworkInterfaceInfo *intf;
9250 
9251     // If we still have address records referring to this one, update them
9252 	NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
9253 	AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
9254 	for (intf = m->HostInterfaces; intf; intf = intf->next)
9255 		if (intf->RR_A.RRSet == &set->RR_A)
9256 			intf->RR_A.RRSet = A;
9257 
9258 	// Unregister these records.
9259 	// When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
9260 	// support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
9261 	// Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
9262 	// To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
9263 	if (set->RR_A.    resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A,     mDNS_Dereg_normal);
9264 	if (set->RR_PTR.  resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR,   mDNS_Dereg_normal);
9265 	if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
9266 	}
9267 
9268 mDNSexport void mDNS_SetFQDN(mDNS *const m)
9269 	{
9270 	domainname newmname;
9271 	NetworkInterfaceInfo *intf;
9272 	AuthRecord *rr;
9273 	newmname.c[0] = 0;
9274 
9275 	if (!AppendDomainLabel(&newmname, &m->hostlabel))  { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
9276 	if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
9277 
9278 	mDNS_Lock(m);
9279 
9280 	if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
9281 	else
9282 		{
9283 		AssignDomainName(&m->MulticastHostname, &newmname);
9284 
9285 		// 1. Stop advertising our address records on all interfaces
9286 		for (intf = m->HostInterfaces; intf; intf = intf->next)
9287 			if (intf->Advertise) DeadvertiseInterface(m, intf);
9288 
9289 		// 2. Start advertising our address records using the new name
9290 		for (intf = m->HostInterfaces; intf; intf = intf->next)
9291 			if (intf->Advertise) AdvertiseInterface(m, intf);
9292 		}
9293 
9294 	// 3. Make sure that any AutoTarget SRV records (and the like) get updated
9295 	for (rr = m->ResourceRecords;  rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
9296 	for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
9297 
9298 	mDNS_Unlock(m);
9299 	}
9300 
9301 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9302 	{
9303 	(void)rr;	// Unused parameter
9304 
9305 	#if MDNS_DEBUGMSGS
9306 		{
9307 		char *msg = "Unknown result";
9308 		if      (result == mStatus_NoError)      msg = "Name registered";
9309 		else if (result == mStatus_NameConflict) msg = "Name conflict";
9310 		debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
9311 		}
9312 	#endif
9313 
9314 	if (result == mStatus_NoError)
9315 		{
9316 		// Notify the client that the host name is successfully registered
9317 		if (m->MainCallback)
9318 			m->MainCallback(m, mStatus_NoError);
9319 		}
9320 	else if (result == mStatus_NameConflict)
9321 		{
9322 		domainlabel oldlabel = m->hostlabel;
9323 
9324 		// 1. First give the client callback a chance to pick a new name
9325 		if (m->MainCallback)
9326 			m->MainCallback(m, mStatus_NameConflict);
9327 
9328 		// 2. If the client callback didn't do it, add (or increment) an index ourselves
9329 		// This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
9330 		// remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
9331 		if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
9332 			IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
9333 
9334 		// 3. Generate the FQDNs from the hostlabel,
9335 		// and make sure all SRV records, etc., are updated to reference our new hostname
9336 		mDNS_SetFQDN(m);
9337 		LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
9338 		}
9339 	else if (result == mStatus_MemFree)
9340 		{
9341 		// .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
9342 		// mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
9343 		debugf("mDNS_HostNameCallback: MemFree (ignored)");
9344 		}
9345 	else
9346 		LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result,  rr->resrec.name->c);
9347 	}
9348 
9349 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
9350 	{
9351 	NetworkInterfaceInfo *intf;
9352 	active->IPv4Available = mDNSfalse;
9353 	active->IPv6Available = mDNSfalse;
9354 	for (intf = m->HostInterfaces; intf; intf = intf->next)
9355 		if (intf->InterfaceID == active->InterfaceID)
9356 			{
9357 			if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
9358 			if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
9359 			}
9360 	}
9361 
9362 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
9363 	{
9364 	AuthRecord *rr;
9365 	LogInfo("RestartRecordGetZoneData: ResourceRecords");
9366 	for (rr = m->ResourceRecords; rr; rr=rr->next)
9367 		if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
9368 			{
9369 			debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
9370 			// Zero out the updateid so that if we have a pending response from the server, it won't
9371 			// be accepted as a valid response. If we accept the response, we might free the new "nta"
9372 			if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
9373 			rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
9374 			}
9375 	}
9376 
9377 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
9378 	{
9379 	int i;
9380 	set->NetWakeBrowse.ThisQInterval = -1;
9381 	for (i=0; i<3; i++)
9382 		{
9383 		set->NetWakeResolve[i].ThisQInterval = -1;
9384 		set->SPSAddr[i].type = mDNSAddrType_None;
9385 		}
9386 	set->NextSPSAttempt     = -1;
9387 	set->NextSPSAttemptTime = m->timenow;
9388 	}
9389 
9390 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
9391 	{
9392 	NetworkInterfaceInfo *p = m->HostInterfaces;
9393 	while (p && p != set) p=p->next;
9394 	if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
9395 
9396 	if (set->InterfaceActive)
9397 		{
9398 		LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
9399 		mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, mDNSfalse, m->SPSBrowseCallback, set);
9400 		}
9401 	}
9402 
9403 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
9404 	{
9405 	NetworkInterfaceInfo *p = m->HostInterfaces;
9406 	while (p && p != set) p=p->next;
9407 	if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
9408 
9409 	if (set->NetWakeBrowse.ThisQInterval >= 0)
9410 		{
9411 		int i;
9412 		LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
9413 
9414 		// Stop our browse and resolve operations
9415 		mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
9416 		for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
9417 
9418 		// Make special call to the browse callback to let it know it can to remove all records for this interface
9419 		if (m->SPSBrowseCallback)
9420 			{
9421 			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
9422 			m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
9423 			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
9424 			}
9425 
9426 		// Reset our variables back to initial state, so we're ready for when NetWake is turned back on
9427 		// (includes resetting NetWakeBrowse.ThisQInterval back to -1)
9428 		InitializeNetWakeState(m, set);
9429 		}
9430 	}
9431 
9432 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
9433 	{
9434 	AuthRecord *rr;
9435 	mDNSBool FirstOfType = mDNStrue;
9436 	NetworkInterfaceInfo **p = &m->HostInterfaces;
9437 
9438 	if (!set->InterfaceID)
9439 		{ LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
9440 
9441 	if (!mDNSAddressIsValidNonZero(&set->mask))
9442 		{ LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
9443 
9444 	mDNS_Lock(m);
9445 
9446 	// Assume this interface will be active now, unless we find a duplicate already in the list
9447 	set->InterfaceActive = mDNStrue;
9448 	set->IPv4Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
9449 	set->IPv6Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
9450 
9451 	InitializeNetWakeState(m, set);
9452 
9453 	// Scan list to see if this InterfaceID is already represented
9454 	while (*p)
9455 		{
9456 		if (*p == set)
9457 			{
9458 			LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
9459 			mDNS_Unlock(m);
9460 			return(mStatus_AlreadyRegistered);
9461 			}
9462 
9463 		if ((*p)->InterfaceID == set->InterfaceID)
9464 			{
9465 			// This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
9466 			set->InterfaceActive = mDNSfalse;
9467 			if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
9468 			if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
9469 			if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
9470 			}
9471 
9472 		p=&(*p)->next;
9473 		}
9474 
9475 	set->next = mDNSNULL;
9476 	*p = set;
9477 
9478 	if (set->Advertise)
9479 		AdvertiseInterface(m, set);
9480 
9481 	LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set->InterfaceID, set->ifname, &set->ip,
9482 		set->InterfaceActive ?
9483 			"not represented in list; marking active and retriggering queries" :
9484 			"already represented in list; marking inactive for now");
9485 
9486 	if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
9487 
9488 	// In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
9489 	// giving the false impression that there's an active representative of this interface when there really isn't.
9490 	// Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
9491 	// even if we believe that we previously had an active representative of this interface.
9492 	if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
9493 		{
9494 		DNSQuestion *q;
9495 		// Normally, after an interface comes up, we pause half a second before beginning probing.
9496 		// This is to guard against cases where there's rapid interface changes, where we could be confused by
9497 		// seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
9498 		// which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
9499 		// We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
9500 		// and think it's a conflicting answer to our probe.
9501 		// In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
9502 		const mDNSs32 probedelay  = flapping ? mDNSPlatformOneSecond * 5 : mDNSPlatformOneSecond / 2;
9503 		const mDNSu8  numannounce = flapping ? (mDNSu8)1                 : InitialAnnounceCount;
9504 
9505 		// Use a small amount of randomness:
9506 		// In the case of a network administrator turning on an Ethernet hub so that all the
9507 		// connected machines establish link at exactly the same time, we don't want them all
9508 		// to go and hit the network with identical queries at exactly the same moment.
9509 		// We set a random delay of up to InitialQuestionInterval (1/3 second).
9510 		// We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
9511 		// that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
9512 		// suppressing packet sending for more than about 1/3 second can cause protocol correctness
9513 		// to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
9514 		// See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
9515 		if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
9516 
9517 		if (flapping) LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
9518 
9519 		LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
9520 		if (m->SuppressProbes == 0 ||
9521 			m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
9522 			m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
9523 
9524 		// Include OWNER option in packets for 60 seconds after connecting to the network. Setting
9525 		// it here also handles the wake up case as the network link comes UP after waking causing
9526 		// us to reconnect to the network. If we do this as part of the wake up code, it is possible
9527 		// that the network link comes UP after 60 seconds and we never set the OWNER option
9528 		m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
9529 		LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
9530 
9531 		for (q = m->Questions; q; q=q->next)								// Scan our list of questions
9532 			if (mDNSOpaque16IsZero(q->TargetQID))
9533 				if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)		// If non-specific Q, or Q on this specific interface,
9534 					{															// then reactivate this question
9535 					// If flapping, delay between first and second queries is nine seconds instead of one second
9536 					mDNSBool dodelay = flapping && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
9537 					mDNSs32 initial  = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
9538 					mDNSs32 qdelay   = dodelay ? mDNSPlatformOneSecond * 5 : 0;
9539 					if (dodelay) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q->qname.c, DNSTypeName(q->qtype));
9540 
9541 					if (!q->ThisQInterval || q->ThisQInterval > initial)
9542 						{
9543 						q->ThisQInterval = initial;
9544 						q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
9545 						}
9546 					q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
9547 					q->RecentAnswerPkts = 0;
9548 					SetNextQueryTime(m,q);
9549 					}
9550 
9551 		// For all our non-specific authoritative resource records (and any dormant records specific to this interface)
9552 		// we now need them to re-probe if necessary, and then re-announce.
9553 		for (rr = m->ResourceRecords; rr; rr=rr->next)
9554 			if (!AuthRecord_uDNS(rr))
9555 				if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
9556 					{
9557 					if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
9558 					rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
9559 					if (rr->AnnounceCount < numannounce) rr->AnnounceCount  = numannounce;
9560 					rr->SendNSECNow    = mDNSNULL;
9561 					InitializeLastAPTime(m, rr);
9562 					}
9563 		}
9564 
9565 	RestartRecordGetZoneData(m);
9566 
9567 	CheckSuppressUnusableQuestions(m);
9568 
9569 	mDNS_UpdateAllowSleep(m);
9570 
9571 	mDNS_Unlock(m);
9572 	return(mStatus_NoError);
9573 	}
9574 
9575 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
9576 // the record list and/or question list.
9577 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9578 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
9579 	{
9580 	NetworkInterfaceInfo **p = &m->HostInterfaces;
9581 	mDNSBool revalidate = mDNSfalse;
9582 
9583 	mDNS_Lock(m);
9584 
9585 	// Find this record in our list
9586 	while (*p && *p != set) p=&(*p)->next;
9587 	if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
9588 
9589 	mDNS_DeactivateNetWake_internal(m, set);
9590 
9591 	// Unlink this record from our list
9592 	*p = (*p)->next;
9593 	set->next = mDNSNULL;
9594 
9595 	if (!set->InterfaceActive)
9596 		{
9597 		// If this interface not the active member of its set, update the v4/v6Available flags for the active member
9598 		NetworkInterfaceInfo *intf;
9599 		for (intf = m->HostInterfaces; intf; intf = intf->next)
9600 			if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
9601 				UpdateInterfaceProtocols(m, intf);
9602 		}
9603 	else
9604 		{
9605 		NetworkInterfaceInfo *intf = FirstInterfaceForID(m, set->InterfaceID);
9606 		if (intf)
9607 			{
9608 			LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
9609 				" making it active", set->InterfaceID, set->ifname, &set->ip);
9610 			if (intf->InterfaceActive)
9611 				LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
9612 			intf->InterfaceActive = mDNStrue;
9613 			UpdateInterfaceProtocols(m, intf);
9614 
9615 			if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
9616 
9617 			// See if another representative *of the same type* exists. If not, we mave have gone from
9618 			// dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
9619 			for (intf = m->HostInterfaces; intf; intf = intf->next)
9620 				if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
9621 					break;
9622 			if (!intf) revalidate = mDNStrue;
9623 			}
9624 		else
9625 			{
9626 			mDNSu32 slot;
9627 			CacheGroup *cg;
9628 			CacheRecord *rr;
9629 			DNSQuestion *q;
9630 			DNSServer *s;
9631 
9632 			LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
9633 				" marking questions etc. dormant", set->InterfaceID, set->ifname, &set->ip);
9634 
9635 			if (set->McastTxRx && flapping)
9636 				LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
9637 
9638 			// 1. Deactivate any questions specific to this interface, and tag appropriate questions
9639 			// so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
9640 			for (q = m->Questions; q; q=q->next)
9641 				{
9642 				if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
9643 				if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
9644 					{
9645 					q->FlappingInterface2 = q->FlappingInterface1;
9646 					q->FlappingInterface1 = set->InterfaceID;		// Keep history of the last two interfaces to go away
9647 					}
9648 				}
9649 
9650 			// 2. Flush any cache records received on this interface
9651 			revalidate = mDNSfalse;		// Don't revalidate if we're flushing the records
9652 			FORALL_CACHERECORDS(slot, cg, rr)
9653 				if (rr->resrec.InterfaceID == set->InterfaceID)
9654 					{
9655 					// If this interface is deemed flapping,
9656 					// postpone deleting the cache records in case the interface comes back again
9657 					if (set->McastTxRx && flapping)
9658 						{
9659 						// For a flapping interface we want these record to go away after 30 seconds
9660 						mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
9661 						// We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
9662 						// if the interface does come back, any relevant questions will be reactivated anyway
9663 						rr->UnansweredQueries = MaxUnansweredQueries;
9664 						}
9665 					else
9666 						mDNS_PurgeCacheResourceRecord(m, rr);
9667 					}
9668 
9669 			// 3. Any DNS servers specific to this interface are now unusable
9670 			for (s = m->DNSServers; s; s = s->next)
9671 				if (s->interface == set->InterfaceID)
9672 					{
9673 					s->interface = mDNSInterface_Any;
9674 					s->teststate = DNSServer_Disabled;
9675 					}
9676 			}
9677 		}
9678 
9679 	// If we were advertising on this interface, deregister those address and reverse-lookup records now
9680 	if (set->Advertise) DeadvertiseInterface(m, set);
9681 
9682 	// If we have any cache records received on this interface that went away, then re-verify them.
9683 	// In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
9684 	// giving the false impression that there's an active representative of this interface when there really isn't.
9685 	// Don't need to do this when shutting down, because *all* interfaces are about to go away
9686 	if (revalidate && !m->ShutdownTime)
9687 		{
9688 		mDNSu32 slot;
9689 		CacheGroup *cg;
9690 		CacheRecord *rr;
9691 		FORALL_CACHERECORDS(slot, cg, rr)
9692 			if (rr->resrec.InterfaceID == set->InterfaceID)
9693 				mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
9694 		}
9695 
9696 	CheckSuppressUnusableQuestions(m);
9697 
9698 	mDNS_UpdateAllowSleep(m);
9699 
9700 	mDNS_Unlock(m);
9701 	}
9702 
9703 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9704 	{
9705 	ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
9706 	(void)m;	// Unused parameter
9707 
9708 	#if MDNS_DEBUGMSGS
9709 		{
9710 		char *msg = "Unknown result";
9711 		if      (result == mStatus_NoError)      msg = "Name Registered";
9712 		else if (result == mStatus_NameConflict) msg = "Name Conflict";
9713 		else if (result == mStatus_MemFree)      msg = "Memory Free";
9714 		debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
9715 		}
9716 	#endif
9717 
9718 	// Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
9719 	if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
9720 
9721 	// If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
9722 	if (result == mStatus_NameConflict)
9723 		{
9724 		sr->Conflict = mDNStrue;				// Record that this service set had a conflict
9725 		mDNS_DeregisterService(m, sr);			// Unlink the records from our list
9726 		return;
9727 		}
9728 
9729 	if (result == mStatus_MemFree)
9730 		{
9731 		// If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
9732 		// are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
9733 		// every record is finished cleaning up.
9734 		mDNSu32 i;
9735 		ExtraResourceRecord *e = sr->Extras;
9736 
9737 		if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9738 		if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9739 		if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9740 		if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9741 		for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
9742 
9743 		while (e)
9744 			{
9745 			if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9746 			e = e->next;
9747 			}
9748 
9749 		// If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
9750 		// then we can now report the NameConflict to the client
9751 		if (sr->Conflict) result = mStatus_NameConflict;
9752 
9753 		}
9754 
9755 	LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered": "Registered"), sr->RR_PTR.resrec.name->c);
9756 	// CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
9757 	// function is allowed to do anything, including deregistering this service and freeing its memory.
9758 	if (sr->ServiceCallback)
9759 		sr->ServiceCallback(m, sr, result);
9760 	}
9761 
9762 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9763 	{
9764 	ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
9765 	if (sr->ServiceCallback)
9766 		sr->ServiceCallback(m, sr, result);
9767 	}
9768 
9769 // Note:
9770 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
9771 // Type is service type (e.g. "_ipp._tcp.")
9772 // Domain is fully qualified domain name (i.e. ending with a null label)
9773 // We always register a TXT, even if it is empty (so that clients are not
9774 // left waiting forever looking for a nonexistent record.)
9775 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
9776 // then the default host name (m->MulticastHostname) is automatically used
9777 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
9778 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
9779 	const domainlabel *const name, const domainname *const type, const domainname *const domain,
9780 	const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
9781 	AuthRecord *SubTypes, mDNSu32 NumSubTypes,
9782 	mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
9783 	{
9784 	mStatus err;
9785 	mDNSu32 i;
9786 	mDNSu32 hostTTL;
9787 	AuthRecType artype;
9788 	mDNSu8 recordType = (flags & regFlagKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
9789 
9790 	sr->ServiceCallback = Callback;
9791 	sr->ServiceContext  = Context;
9792 	sr->Conflict        = mDNSfalse;
9793 
9794 	sr->Extras          = mDNSNULL;
9795 	sr->NumSubTypes     = NumSubTypes;
9796 	sr->SubTypes        = SubTypes;
9797 
9798 	if (InterfaceID == mDNSInterface_LocalOnly)
9799 		artype = AuthRecordLocalOnly;
9800 	else if (InterfaceID == mDNSInterface_P2P)
9801 		artype = AuthRecordP2P;
9802 	else if ((InterfaceID == mDNSInterface_Any) && (flags & regFlagIncludeP2P))
9803 		artype = AuthRecordAnyIncludeP2P;
9804 	else
9805 		artype = AuthRecordAny;
9806 
9807 	// Initialize the AuthRecord objects to sane values
9808 	// Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
9809 	mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
9810 	mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared,   artype, ServiceCallback, sr);
9811 
9812 	if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
9813 		hostTTL = kHostNameSmallTTL;
9814 	else
9815 		hostTTL = kHostNameTTL;
9816 
9817 	mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
9818 	mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
9819 
9820 	// If port number is zero, that means the client is really trying to do a RegisterNoSuchService
9821 	if (mDNSIPPortIsZero(port))
9822 		return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, (flags & regFlagIncludeP2P)));
9823 
9824 	// If the client is registering an oversized TXT record,
9825 	// it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
9826 	if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
9827 		sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
9828 
9829 	// Set up the record names
9830 	// For now we only create an advisory record for the main type, not for subtypes
9831 	// We need to gain some operational experience before we decide if there's a need to create them for subtypes too
9832 	if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
9833 		return(mStatus_BadParamErr);
9834 	if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
9835 	if (ConstructServiceName(&sr->RR_SRV.namestorage, name,     type, domain) == mDNSNULL) return(mStatus_BadParamErr);
9836 	AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
9837 
9838 	// 1. Set up the ADV record rdata to advertise our service type
9839 	AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
9840 
9841 	// 2. Set up the PTR record rdata to point to our service name
9842 	// We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
9843 	// Note: uDNS registration code assumes that Additional1 points to the SRV record
9844 	AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
9845 	sr->RR_PTR.Additional1 = &sr->RR_SRV;
9846 	sr->RR_PTR.Additional2 = &sr->RR_TXT;
9847 
9848 	// 2a. Set up any subtype PTRs to point to our service name
9849 	// If the client is using subtypes, it is the client's responsibility to have
9850 	// already set the first label of the record name to the subtype being registered
9851 	for (i=0; i<NumSubTypes; i++)
9852 		{
9853 		domainname st;
9854 		AssignDomainName(&st, sr->SubTypes[i].resrec.name);
9855 		st.c[1+st.c[0]] = 0;			// Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
9856 		AppendDomainName(&st, type);
9857 		mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
9858 		if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
9859 		AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
9860 		sr->SubTypes[i].Additional1 = &sr->RR_SRV;
9861 		sr->SubTypes[i].Additional2 = &sr->RR_TXT;
9862 		}
9863 
9864 	// 3. Set up the SRV record rdata.
9865 	sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
9866 	sr->RR_SRV.resrec.rdata->u.srv.weight   = 0;
9867 	sr->RR_SRV.resrec.rdata->u.srv.port     = port;
9868 
9869 	// Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
9870 	if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
9871 	else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
9872 
9873 	// 4. Set up the TXT record rdata,
9874 	// and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
9875 	// Note: uDNS registration code assumes that DependentOn points to the SRV record
9876 	if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
9877 	else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
9878 		{
9879 		sr->RR_TXT.resrec.rdlength = txtlen;
9880 		if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
9881 		mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
9882 		}
9883 	sr->RR_TXT.DependentOn = &sr->RR_SRV;
9884 
9885 	mDNS_Lock(m);
9886 	// It is important that we register SRV first. uDNS assumes that SRV is registered first so
9887 	// that if the SRV cannot find a target, rest of the records that belong to this service
9888 	// will not be activated.
9889 	err = mDNS_Register_internal(m, &sr->RR_SRV);
9890 	// If we can't register the SRV record due to errors, bail out. It has not been inserted in
9891 	// any list and hence no need to deregister. We could probably do similar checks for other
9892 	// records below and bail out. For now, this seems to be sufficient to address rdar://9304275
9893 	if (err)
9894 		{
9895 		mDNS_Unlock(m);
9896 		return err;
9897 		}
9898 	if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
9899 	// We register the RR_PTR last, because we want to be sure that in the event of a forced call to
9900 	// mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
9901 	// the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
9902 	// the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
9903 	// make sure we've deregistered all our records and done any other necessary cleanup before that happens.
9904 	if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
9905 	for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
9906 	if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
9907 
9908 	mDNS_Unlock(m);
9909 
9910 	if (err) mDNS_DeregisterService(m, sr);
9911 	return(err);
9912 	}
9913 
9914 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
9915 	ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl,  mDNSu32 includeP2P)
9916 	{
9917 	ExtraResourceRecord **e;
9918 	mStatus status;
9919 	AuthRecType artype;
9920 	mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
9921 
9922 	if (InterfaceID == mDNSInterface_LocalOnly)
9923 		artype = AuthRecordLocalOnly;
9924 	if (InterfaceID == mDNSInterface_P2P)
9925 		artype = AuthRecordP2P;
9926 	else if ((InterfaceID == mDNSInterface_Any) && includeP2P)
9927 		artype = AuthRecordAnyIncludeP2P;
9928 	else
9929 		artype = AuthRecordAny;
9930 
9931 	extra->next = mDNSNULL;
9932 	mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
9933 		extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
9934 	AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
9935 
9936 	mDNS_Lock(m);
9937 	e = &sr->Extras;
9938 	while (*e) e = &(*e)->next;
9939 
9940 	if (ttl == 0) ttl = kStandardTTL;
9941 
9942 	extra->r.DependentOn = &sr->RR_SRV;
9943 
9944 	debugf("mDNS_AddRecordToService adding record to %##s %s %d",
9945 		extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
9946 
9947 	status = mDNS_Register_internal(m, &extra->r);
9948 	if (status == mStatus_NoError) *e = extra;
9949 
9950 	mDNS_Unlock(m);
9951 	return(status);
9952 	}
9953 
9954 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
9955 	mDNSRecordCallback MemFreeCallback, void *Context)
9956 	{
9957 	ExtraResourceRecord **e;
9958 	mStatus status;
9959 
9960 	mDNS_Lock(m);
9961 	e = &sr->Extras;
9962 	while (*e && *e != extra) e = &(*e)->next;
9963 	if (!*e)
9964 		{
9965 		debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
9966 		status = mStatus_BadReferenceErr;
9967 		}
9968 	else
9969 		{
9970 		debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
9971 		extra->r.RecordCallback = MemFreeCallback;
9972 		extra->r.RecordContext  = Context;
9973 		*e = (*e)->next;
9974 		status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
9975 		}
9976 	mDNS_Unlock(m);
9977 	return(status);
9978 	}
9979 
9980 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
9981 	{
9982 	// Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
9983 	// mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
9984 	domainlabel name1, name2;
9985 	domainname type, domain;
9986 	const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
9987 	ExtraResourceRecord *extras = sr->Extras;
9988 	mStatus err;
9989 
9990 	DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
9991 	if (!newname)
9992 		{
9993 		name2 = name1;
9994 		IncrementLabelSuffix(&name2, mDNStrue);
9995 		newname = &name2;
9996 		}
9997 
9998 	if (SameDomainName(&domain, &localdomain))
9999 		debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
10000 	else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
10001 
10002 	err = mDNS_RegisterService(m, sr, newname, &type, &domain,
10003 		host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
10004 		sr->SubTypes, sr->NumSubTypes,
10005 		sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, 0);
10006 
10007 	// mDNS_RegisterService() just reset sr->Extras to NULL.
10008 	// Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
10009 	// through the old list of extra records, and re-add them to our freshly created service registration
10010 	while (!err && extras)
10011 		{
10012 		ExtraResourceRecord *e = extras;
10013 		extras = extras->next;
10014 		err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
10015 		}
10016 
10017 	return(err);
10018 	}
10019 
10020 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
10021 // which may change the record list and/or question list.
10022 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
10023 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
10024 	{
10025 	// If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
10026 	if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
10027 
10028 	if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
10029 		{
10030 		debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
10031 		return(mStatus_BadReferenceErr);
10032 		}
10033 	else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
10034 		{
10035 		LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
10036 		// Avoid race condition:
10037 		// If a service gets a conflict, then we set the Conflict flag to tell us to generate
10038 		// an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
10039 		// If the client happens to deregister the service in the middle of that process, then
10040 		// we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
10041 		// instead of incorrectly promoting it to mStatus_NameConflict.
10042 		// This race condition is exposed particularly when the conformance test generates
10043 		// a whole batch of simultaneous conflicts across a range of services all advertised
10044 		// using the same system default name, and if we don't take this precaution then
10045 		// we end up incrementing m->nicelabel multiple times instead of just once.
10046 		// <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
10047 		sr->Conflict = mDNSfalse;
10048 		return(mStatus_NoError);
10049 		}
10050 	else
10051 		{
10052 		mDNSu32 i;
10053 		mStatus status;
10054 		ExtraResourceRecord *e;
10055 		mDNS_Lock(m);
10056 		e = sr->Extras;
10057 
10058 		// We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
10059 		// SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
10060 		mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
10061 		mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
10062 
10063 		mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
10064 
10065 		// We deregister all of the extra records, but we leave the sr->Extras list intact
10066 		// in case the client wants to do a RenameAndReregister and reinstate the registration
10067 		while (e)
10068 			{
10069 			mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
10070 			e = e->next;
10071 			}
10072 
10073 		for (i=0; i<sr->NumSubTypes; i++)
10074 			mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
10075 
10076 		status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
10077 		mDNS_Unlock(m);
10078 		return(status);
10079 		}
10080 	}
10081 
10082 // Create a registration that asserts that no such service exists with this name.
10083 // This can be useful where there is a given function is available through several protocols.
10084 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
10085 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
10086 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
10087 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
10088 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
10089 	const domainlabel *const name, const domainname *const type, const domainname *const domain,
10090 	const domainname *const host,
10091 	const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSBool includeP2P)
10092 	{
10093 	AuthRecType artype;
10094 
10095 	if (InterfaceID == mDNSInterface_LocalOnly)
10096 		artype = AuthRecordLocalOnly;
10097 	else if (InterfaceID == mDNSInterface_P2P)
10098 		artype = AuthRecordP2P;
10099 	else if ((InterfaceID == mDNSInterface_Any) && includeP2P)
10100 		artype = AuthRecordAnyIncludeP2P;
10101 	else
10102 		artype = AuthRecordAny;
10103 
10104 	mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
10105 	if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
10106 	rr->resrec.rdata->u.srv.priority    = 0;
10107 	rr->resrec.rdata->u.srv.weight      = 0;
10108 	rr->resrec.rdata->u.srv.port        = zeroIPPort;
10109 	if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
10110 	else rr->AutoTarget = Target_AutoHost;
10111 	return(mDNS_Register(m, rr));
10112 	}
10113 
10114 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
10115 	mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
10116 	{
10117 	AuthRecType artype;
10118 
10119 	if (InterfaceID == mDNSInterface_LocalOnly)
10120 		artype = AuthRecordLocalOnly;
10121 	else if (InterfaceID == mDNSInterface_P2P)
10122 		artype = AuthRecordP2P;
10123 	else
10124 		artype = AuthRecordAny;
10125 	mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
10126 	if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
10127 	if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname))                 return(mStatus_BadParamErr);
10128 	return(mDNS_Register(m, rr));
10129 	}
10130 
10131 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
10132 	{
10133 	AuthRecord *r;
10134 	for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
10135 	return mDNSfalse;
10136 	}
10137 
10138 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
10139 	{
10140 	DNSQuestion *q;
10141 	for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
10142 	return mDNSfalse;
10143 	}
10144 
10145 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
10146 	{
10147 	mDNSOpaque16 id;
10148 	int i;
10149 
10150 	for (i=0; i<10; i++)
10151 		{
10152 		id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
10153 		if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
10154 		}
10155 
10156 	debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
10157 
10158 	return id;
10159 	}
10160 
10161 // ***************************************************************************
10162 #if COMPILER_LIKES_PRAGMA_MARK
10163 #pragma mark -
10164 #pragma mark - Sleep Proxy Server
10165 #endif
10166 
10167 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
10168 	{
10169 	// If we see an ARP from a machine we think is sleeping, then either
10170 	// (i) the machine has woken, or
10171 	// (ii) it's just a stray old packet from before the machine slept
10172 	// To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
10173 	// generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
10174 	// If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
10175 	// 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*
10176 	// need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
10177 	// re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
10178 
10179 	rr->resrec.RecordType = kDNSRecordTypeUnique;
10180 	rr->ProbeCount        = DefaultProbeCountForTypeUnique;
10181 
10182 	// If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
10183 	// still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
10184 	// If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
10185 	// we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
10186 	// sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
10187 	// didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
10188 	if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
10189 		InitializeLastAPTime(m, rr);
10190 	else
10191 		{
10192 		rr->AnnounceCount  = InitialAnnounceCount;
10193 		rr->ThisAPInterval = mDNSPlatformOneSecond;
10194 		rr->LastAPTime     = m->timenow + mDNSPlatformOneSecond * 9;	// Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
10195 		SetNextAnnounceProbeTime(m, rr);
10196 		}
10197 	}
10198 
10199 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
10200 	{
10201 	static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
10202 	AuthRecord *rr;
10203 	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
10204 	if (!intf) return;
10205 
10206 	mDNS_Lock(m);
10207 
10208 	// Pass 1:
10209 	// Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
10210 	// We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
10211 	// We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
10212 	// The times we might need to react to an ARP Announcement are:
10213 	// (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
10214 	// (ii) if it's a conflicting Announcement from another host
10215 	// -- and we check for these in Pass 2 below.
10216 	if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
10217 		{
10218 		for (rr = m->ResourceRecords; rr; rr=rr->next)
10219 			if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10220 				rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
10221 				{
10222 				static const char msg1[] = "ARP Req from owner -- re-probing";
10223 				static const char msg2[] = "Ignoring  ARP Request from      ";
10224 				static const char msg3[] = "Creating Local ARP Cache entry  ";
10225 				static const char msg4[] = "Answering ARP Request from      ";
10226 				const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
10227 										(rr->AnnounceCount == InitialAnnounceCount)     ? msg2 :
10228 										mDNSSameEthAddress(&arp->sha, &intf->MAC)       ? msg3 : msg4;
10229 				LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
10230 					intf->ifname, msg, &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10231 				if      (msg == msg1) RestartARPProbing(m, rr);
10232 				else if (msg == msg3) mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
10233 				else if (msg == msg4) SendARP(m, 2, rr, &arp->tpa, &arp->sha, &arp->spa, &arp->sha);
10234 				}
10235 		}
10236 
10237 	// Pass 2:
10238 	// 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.
10239 	// (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
10240 	// so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
10241 	// 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.
10242 	// If we see an apparently conflicting ARP, we check the sender hardware address:
10243 	//   If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
10244 	//   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.
10245 	if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
10246 		debugf("ARP from self for %.4a", &arp->tpa);
10247 	else
10248 		{
10249 		if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
10250 			for (rr = m->ResourceRecords; rr; rr=rr->next)
10251 				if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10252 					rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa))
10253 					{
10254 					RestartARPProbing(m, rr);
10255 					if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
10256 						LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
10257 							mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request      " : "Response     ",
10258 							&arp->sha, &arp->spa, &arp->tpa, ARDisplayString(m, rr));
10259 					else
10260 						{
10261 						LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
10262 							&arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10263 						ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10264 						}
10265 					}
10266 		}
10267 
10268 	mDNS_Unlock(m);
10269 	}
10270 
10271 /*
10272 // Option 1 is Source Link Layer Address Option
10273 // Option 2 is Target Link Layer Address Option
10274 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
10275 	{
10276 	const mDNSu8 *options = (mDNSu8 *)(ndp+1);
10277 	while (options < end)
10278 		{
10279 		debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
10280 		if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
10281 		options += options[1] * 8;
10282 		}
10283 	return mDNSNULL;
10284 	}
10285 */
10286 
10287 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
10288 	const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
10289 	{
10290 	AuthRecord *rr;
10291 	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
10292 	if (!intf) return;
10293 
10294 	mDNS_Lock(m);
10295 
10296 	// Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
10297 	if (ndp->type == NDP_Sol)
10298 		{
10299 		//const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
10300 		(void)end;
10301 		for (rr = m->ResourceRecords; rr; rr=rr->next)
10302 			if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10303 				rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
10304 				{
10305 				static const char msg1[] = "NDP Req from owner -- re-probing";
10306 				static const char msg2[] = "Ignoring  NDP Request from      ";
10307 				static const char msg3[] = "Creating Local NDP Cache entry  ";
10308 				static const char msg4[] = "Answering NDP Request from      ";
10309 				static const char msg5[] = "Answering NDP Probe   from      ";
10310 				const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
10311 										(rr->AnnounceCount == InitialAnnounceCount)      ? msg2 :
10312 										sha && mDNSSameEthAddress(sha, &intf->MAC)       ? msg3 :
10313 										spa && mDNSIPv6AddressIsZero(*spa)               ? msg4 : msg5;
10314 				LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
10315 					intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10316 				if      (msg == msg1) RestartARPProbing(m, rr);
10317 				else if (msg == msg3)
10318 					{
10319 					if (!(m->KnownBugs & mDNS_KnownBug_LimitedIPv6))
10320 						mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
10321 					}
10322 				else if (msg == msg4) SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa,          sha             );
10323 				else if (msg == msg5) SendNDP(m, NDP_Adv, 0,             rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
10324 				}
10325 		}
10326 
10327 	// 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.
10328 	if (mDNSSameEthAddress(sha, &intf->MAC))
10329 		debugf("NDP from self for %.16a", &ndp->target);
10330 	else
10331 		{
10332 		// For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
10333 		// When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
10334 		// about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
10335 		// Hence it is the NDP target address we care about, not the actual packet source address.
10336 		if (ndp->type == NDP_Adv) spa = &ndp->target;
10337 		if (!mDNSSameIPv6Address(*spa, zerov6Addr))
10338 			for (rr = m->ResourceRecords; rr; rr=rr->next)
10339 				if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10340 					rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa))
10341 					{
10342 					RestartARPProbing(m, rr);
10343 					if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
10344 						LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
10345 							ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
10346 					else
10347 						{
10348 						LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
10349 							sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10350 						ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10351 						}
10352 					}
10353 		}
10354 
10355 	mDNS_Unlock(m);
10356 	}
10357 
10358 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
10359 	const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
10360 	{
10361 	const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
10362 	mDNSBool wake = mDNSfalse;
10363 
10364 	switch (protocol)
10365 		{
10366 		#define XX wake ? "Received" : "Ignoring", end-p
10367 		case 0x01:	LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
10368 					break;
10369 
10370 		case 0x06:	{
10371 					#define SSH_AsNumber 22
10372 					static const mDNSIPPort SSH = { { SSH_AsNumber >> 8, SSH_AsNumber & 0xFF } };
10373 
10374 					// Plan to wake if
10375 					// (a) RST is not set, AND
10376 					// (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
10377 					wake = (!(t->tcp.flags & 4) && (t->tcp.flags & 3) != 1);
10378 
10379 					// For now, to reduce spurious wakeups, we wake only for TCP SYN,
10380 					// except for ssh connections, where we'll wake for plain data packets too
10381 					if (!mDNSSameIPPort(port, SSH) && !(t->tcp.flags & 2)) wake = mDNSfalse;
10382 
10383 					LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
10384 						src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
10385 						(t->tcp.flags & 2) ? " SYN" : "",
10386 						(t->tcp.flags & 1) ? " FIN" : "",
10387 						(t->tcp.flags & 4) ? " RST" : "");
10388 					}
10389 					break;
10390 
10391 		case 0x11:	{
10392 					#define ARD_AsNumber 3283
10393 					static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
10394 					const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]);		// Length *including* 8-byte UDP header
10395 					if (udplen >= sizeof(UDPHeader))
10396 						{
10397 						const mDNSu16 datalen = udplen - sizeof(UDPHeader);
10398 						wake = mDNStrue;
10399 
10400 						// For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
10401 						if (mDNSSameIPPort(port, IPSECPort))
10402 							{
10403 							// Specifically ignore NAT keepalive packets
10404 							if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
10405 							else
10406 								{
10407 								// Skip over the Non-ESP Marker if present
10408 								const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
10409 								const IKEHeader *const ike    = (IKEHeader *)(t + (NonESP ? 12 : 8));
10410 								const mDNSu16          ikelen = datalen - (NonESP ? 4 : 0);
10411 								if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
10412 									if ((ike->Version & 0x10) == 0x10)
10413 										{
10414 										// ExchangeType ==  5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
10415 										// ExchangeType == 34 means 'IKE_SA_INIT'   <http://www.iana.org/assignments/ikev2-parameters>
10416 										if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
10417 										LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
10418 										}
10419 								}
10420 							}
10421 
10422 						// For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
10423 						// Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
10424 						// except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
10425 						// UDP header (8 bytes)
10426 						// Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
10427 						if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
10428 
10429 						LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
10430 						}
10431 					}
10432 					break;
10433 
10434 		case 0x3A:	if (&t->bytes[len] <= end)
10435 						{
10436 						mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
10437 						if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
10438 						else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
10439 						}
10440 					break;
10441 
10442 		default:	LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
10443 					break;
10444 		}
10445 
10446 	if (wake)
10447 		{
10448 		AuthRecord *rr, *r2;
10449 
10450 		mDNS_Lock(m);
10451 		for (rr = m->ResourceRecords; rr; rr=rr->next)
10452 			if (rr->resrec.InterfaceID == InterfaceID &&
10453 				rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10454 				rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
10455 				{
10456 				const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
10457 				for (r2 = m->ResourceRecords; r2; r2=r2->next)
10458 					if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
10459 						r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
10460 						r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
10461 						SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
10462 						break;
10463 				if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr;	// So that we wake for BTMM IPSEC packets, even without a matching SRV record
10464 				if (r2)
10465 					{
10466 					LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
10467 						InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
10468 					ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10469 					}
10470 				else
10471 					LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
10472 						InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
10473 				}
10474 		mDNS_Unlock(m);
10475 		}
10476 	}
10477 
10478 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
10479 	{
10480 	static const mDNSOpaque16 Ethertype_ARP  = { { 0x08, 0x06 } };	// Ethertype 0x0806 = ARP
10481 	static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } };	// Ethertype 0x0800 = IPv4
10482 	static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } };	// Ethertype 0x86DD = IPv6
10483 	static const mDNSOpaque16 ARP_hrd_eth    = { { 0x00, 0x01 } };	// Hardware address space (Ethernet = 1)
10484 	static const mDNSOpaque16 ARP_pro_ip     = { { 0x08, 0x00 } };	// Protocol address space (IP = 0x0800)
10485 
10486 	// Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
10487 	// In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
10488 	// but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
10489 	// since it points to a an address 14 bytes before pkt.
10490 	const EthernetHeader     *const eth = (const EthernetHeader *)p;
10491 	const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
10492 	mDNSAddr src, dst;
10493 	#define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
10494 
10495 	// Is ARP? Length must be at least 14 + 28 = 42 bytes
10496 	if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
10497 		mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
10498 	// Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
10499 	else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
10500 		{
10501 		const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
10502 		debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
10503 		src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
10504 		dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
10505 		if (end >= trans + RequiredCapLen(pkt->v4.protocol))
10506 			mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, end, InterfaceID, 0);
10507 		}
10508 	// Is IPv6? Length must be at least 14 + 28 = 42 bytes
10509 	else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
10510 		{
10511 		const mDNSu8 *const trans = p + 54;
10512 		debugf("Got IPv6  %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
10513 		src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
10514 		dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
10515 		if (end >= trans + RequiredCapLen(pkt->v6.pro))
10516 			mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
10517 				(mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
10518 		}
10519 	}
10520 
10521 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
10522 	{
10523 	name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d %#s",
10524 		m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, &m->nicelabel);
10525 	}
10526 
10527 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
10528 	{
10529 	if (result == mStatus_NameConflict)
10530 		mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
10531 	else if (result == mStatus_MemFree)
10532 		{
10533 		if (m->SleepState)
10534 			m->SPSState = 3;
10535 		else
10536 			{
10537 			m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
10538 			if (m->SPSState)
10539 				{
10540 				domainlabel name;
10541 				ConstructSleepProxyServerName(m, &name);
10542 				mDNS_RegisterService(m, srs,
10543 					&name, &SleepProxyServiceType, &localdomain,
10544 					mDNSNULL, m->SPSSocket->port,				// Host, port
10545 					(mDNSu8 *)"", 1,							// TXT data, length
10546 					mDNSNULL, 0,								// Subtypes (none)
10547 					mDNSInterface_Any,							// Interface ID
10548 					SleepProxyServerCallback, mDNSNULL, 0);		// Callback, context, flags
10549 				}
10550 			LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
10551 			}
10552 		}
10553 	}
10554 
10555 // Called with lock held
10556 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower)
10557 	{
10558 	// This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
10559 	mDNS_DropLockBeforeCallback();
10560 
10561 	// If turning off SPS, close our socket
10562 	// (Do this first, BEFORE calling mDNS_DeregisterService below)
10563 	if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
10564 
10565 	// If turning off, or changing type, deregister old name
10566 	if (m->SPSState == 1 && sps != m->SPSType)
10567 		{ m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
10568 
10569 	// Record our new SPS parameters
10570 	m->SPSType          = sps;
10571 	m->SPSPortability   = port;
10572 	m->SPSMarginalPower = marginalpower;
10573 	m->SPSTotalPower    = totpower;
10574 
10575 	// If turning on, open socket and advertise service
10576 	if (sps)
10577 		{
10578 		if (!m->SPSSocket)
10579 			{
10580 			m->SPSSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
10581 			if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
10582 			}
10583 		if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
10584 		}
10585 	else if (m->SPSState)
10586 		{
10587 		LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
10588 		m->NextScheduledSPS = m->timenow;
10589 		}
10590 fail:
10591 	mDNS_ReclaimLockAfterCallback();
10592 	}
10593 
10594 // ***************************************************************************
10595 #if COMPILER_LIKES_PRAGMA_MARK
10596 #pragma mark -
10597 #pragma mark - Startup and Shutdown
10598 #endif
10599 
10600 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
10601 	{
10602 	if (storage && numrecords)
10603 		{
10604 		mDNSu32 i;
10605 		debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
10606 		for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
10607 		storage[numrecords-1].next = m->rrcache_free;
10608 		m->rrcache_free = storage;
10609 		m->rrcache_size += numrecords;
10610 		}
10611 	}
10612 
10613 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
10614 	{
10615 	mDNS_Lock(m);
10616 	mDNS_GrowCache_internal(m, storage, numrecords);
10617 	mDNS_Unlock(m);
10618 	}
10619 
10620 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
10621 	CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
10622 	mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
10623 	{
10624 	mDNSu32 slot;
10625 	mDNSs32 timenow;
10626 	mStatus result;
10627 
10628 	if (!rrcachestorage) rrcachesize = 0;
10629 
10630 	m->p                             = p;
10631 	m->KnownBugs                     = 0;
10632 	m->CanReceiveUnicastOn5353       = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
10633 	m->AdvertiseLocalAddresses       = AdvertiseLocalAddresses;
10634 	m->DivertMulticastAdvertisements = mDNSfalse;
10635 	m->mDNSPlatformStatus            = mStatus_Waiting;
10636 	m->UnicastPort4                  = zeroIPPort;
10637 	m->UnicastPort6                  = zeroIPPort;
10638 	m->PrimaryMAC                    = zeroEthAddr;
10639 	m->MainCallback                  = Callback;
10640 	m->MainContext                   = Context;
10641 	m->rec.r.resrec.RecordType       = 0;
10642 
10643 	// For debugging: To catch and report locking failures
10644 	m->mDNS_busy               = 0;
10645 	m->mDNS_reentrancy         = 0;
10646 	m->ShutdownTime            = 0;
10647 	m->lock_rrcache            = 0;
10648 	m->lock_Questions          = 0;
10649 	m->lock_Records            = 0;
10650 
10651 	// Task Scheduling variables
10652 	result = mDNSPlatformTimeInit();
10653 	if (result != mStatus_NoError) return(result);
10654 	m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
10655 	timenow = mDNS_TimeNow_NoLock(m);
10656 
10657 	m->timenow                 = 0;		// MUST only be set within mDNS_Lock/mDNS_Unlock section
10658 	m->timenow_last            = timenow;
10659 	m->NextScheduledEvent      = timenow;
10660 	m->SuppressSending         = timenow;
10661 	m->NextCacheCheck          = timenow + 0x78000000;
10662 	m->NextScheduledQuery      = timenow + 0x78000000;
10663 	m->NextScheduledProbe      = timenow + 0x78000000;
10664 	m->NextScheduledResponse   = timenow + 0x78000000;
10665 	m->NextScheduledNATOp      = timenow + 0x78000000;
10666 	m->NextScheduledSPS        = timenow + 0x78000000;
10667 	m->NextScheduledStopTime   = timenow + 0x78000000;
10668 	m->RandomQueryDelay        = 0;
10669 	m->RandomReconfirmDelay    = 0;
10670 	m->PktNum                  = 0;
10671 	m->LocalRemoveEvents       = mDNSfalse;
10672 	m->SleepState              = SleepState_Awake;
10673 	m->SleepSeqNum             = 0;
10674 	m->SystemWakeOnLANEnabled  = mDNSfalse;
10675 	m->AnnounceOwner           = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
10676 	m->DelaySleep              = 0;
10677 	m->SleepLimit              = 0;
10678 
10679 	// These fields only required for mDNS Searcher...
10680 	m->Questions               = mDNSNULL;
10681 	m->NewQuestions            = mDNSNULL;
10682 	m->CurrentQuestion         = mDNSNULL;
10683 	m->LocalOnlyQuestions      = mDNSNULL;
10684 	m->NewLocalOnlyQuestions   = mDNSNULL;
10685 	m->RestartQuestion	       = mDNSNULL;
10686 	m->rrcache_size            = 0;
10687 	m->rrcache_totalused       = 0;
10688 	m->rrcache_active          = 0;
10689 	m->rrcache_report          = 10;
10690 	m->rrcache_free            = mDNSNULL;
10691 
10692 	for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
10693 		{
10694 		m->rrcache_hash[slot]      = mDNSNULL;
10695 		m->rrcache_nextcheck[slot] = timenow + 0x78000000;;
10696 		}
10697 
10698 	mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
10699 	m->rrauth.rrauth_free            = mDNSNULL;
10700 
10701 	for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
10702 		m->rrauth.rrauth_hash[slot] = mDNSNULL;
10703 
10704 	// Fields below only required for mDNS Responder...
10705 	m->hostlabel.c[0]          = 0;
10706 	m->nicelabel.c[0]          = 0;
10707 	m->MulticastHostname.c[0]  = 0;
10708 	m->HIHardware.c[0]         = 0;
10709 	m->HISoftware.c[0]         = 0;
10710 	m->ResourceRecords         = mDNSNULL;
10711 	m->DuplicateRecords        = mDNSNULL;
10712 	m->NewLocalRecords         = mDNSNULL;
10713 	m->NewLocalOnlyRecords     = mDNSfalse;
10714 	m->CurrentRecord           = mDNSNULL;
10715 	m->HostInterfaces          = mDNSNULL;
10716 	m->ProbeFailTime           = 0;
10717 	m->NumFailedProbes         = 0;
10718 	m->SuppressProbes          = 0;
10719 
10720 #ifndef UNICAST_DISABLED
10721 	m->NextuDNSEvent            = timenow + 0x78000000;
10722 	m->NextSRVUpdate            = timenow + 0x78000000;
10723 
10724 	m->DNSServers               = mDNSNULL;
10725 
10726 	m->Router                   = zeroAddr;
10727 	m->AdvertisedV4             = zeroAddr;
10728 	m->AdvertisedV6             = zeroAddr;
10729 
10730 	m->AuthInfoList             = mDNSNULL;
10731 
10732 	m->ReverseMap.ThisQInterval = -1;
10733 	m->StaticHostname.c[0]      = 0;
10734 	m->FQDN.c[0]                = 0;
10735 	m->Hostnames                = mDNSNULL;
10736 	m->AutoTunnelHostAddr.b[0]  = 0;
10737 	m->AutoTunnelHostAddrActive = mDNSfalse;
10738 	m->AutoTunnelLabel.c[0]     = 0;
10739 
10740 	m->StartWABQueries          = mDNSfalse;
10741 	m->RegisterAutoTunnel6      = mDNStrue;
10742 
10743 	// NAT traversal fields
10744 	m->NATTraversals            = mDNSNULL;
10745 	m->CurrentNATTraversal      = mDNSNULL;
10746 	m->retryIntervalGetAddr     = 0;	// delta between time sent and retry
10747 	m->retryGetAddr             = timenow + 0x78000000;	// absolute time when we retry
10748 	m->ExternalAddress          = zerov4Addr;
10749 
10750 	m->NATMcastRecvskt          = mDNSNULL;
10751 	m->LastNATupseconds         = 0;
10752 	m->LastNATReplyLocalTime    = timenow;
10753 	m->LastNATMapResultCode     = NATErr_None;
10754 
10755 	m->UPnPInterfaceID          = 0;
10756 	m->SSDPSocket               = mDNSNULL;
10757 	m->SSDPWANPPPConnection     = mDNSfalse;
10758 	m->UPnPRouterPort           = zeroIPPort;
10759 	m->UPnPSOAPPort             = zeroIPPort;
10760 	m->UPnPRouterURL            = mDNSNULL;
10761 	m->UPnPWANPPPConnection     = mDNSfalse;
10762 	m->UPnPSOAPURL              = mDNSNULL;
10763 	m->UPnPRouterAddressString  = mDNSNULL;
10764 	m->UPnPSOAPAddressString    = mDNSNULL;
10765 	m->SPSType                  = 0;
10766 	m->SPSPortability           = 0;
10767 	m->SPSMarginalPower         = 0;
10768 	m->SPSTotalPower            = 0;
10769 	m->SPSState                 = 0;
10770 	m->SPSProxyListChanged      = mDNSNULL;
10771 	m->SPSSocket                = mDNSNULL;
10772 	m->SPSBrowseCallback        = mDNSNULL;
10773 	m->ProxyRecords             = 0;
10774 
10775 #endif
10776 
10777 #if APPLE_OSX_mDNSResponder
10778 	m->TunnelClients            = mDNSNULL;
10779 
10780 #if ! NO_WCF
10781 	CHECK_WCF_FUNCTION(WCFConnectionNew)
10782 		{
10783 		m->WCF = WCFConnectionNew();
10784 		if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
10785 		}
10786 #endif
10787 
10788 #endif
10789 
10790 	result = mDNSPlatformInit(m);
10791 
10792 #ifndef UNICAST_DISABLED
10793 	// It's better to do this *after* the platform layer has set up the
10794 	// interface list and security credentials
10795 	uDNS_SetupDNSConfig(m);						// Get initial DNS configuration
10796 #endif
10797 
10798 	return(result);
10799 	}
10800 
10801 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
10802 	{
10803 	if (m->SPSState == 1)
10804 		{
10805 		domainlabel name, newname;
10806 		domainname type, domain;
10807 		DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
10808 		ConstructSleepProxyServerName(m, &newname);
10809 		if (!SameDomainLabelCS(name.c, newname.c))
10810 			{
10811 			LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
10812 			// When SleepProxyServerCallback gets the mStatus_MemFree message,
10813 			// it will reregister the service under the new name
10814 			m->SPSState = 2;
10815 			mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
10816 			}
10817 		}
10818 
10819 	if (m->MainCallback)
10820 		m->MainCallback(m, mStatus_ConfigChanged);
10821 	}
10822 
10823 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
10824 	{
10825 	(void)m;	// unused
10826 	debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
10827 	mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
10828 	}
10829 
10830 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
10831 	{
10832 	mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
10833 					 cr->resrec.rrtype     == kDNSType_A ||
10834 					 cr->resrec.rrtype     == kDNSType_AAAA ||
10835 					 cr->resrec.rrtype     == kDNSType_SRV;
10836 
10837 	(void) lameduck;
10838 	(void) ptr;
10839 	debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
10840 		purge    ? "purging"   : "reconfirming",
10841 		lameduck ? "lame duck" : "new",
10842 		ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
10843 
10844 	if (purge)
10845 		{
10846 		LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
10847 		mDNS_PurgeCacheResourceRecord(m, cr);
10848 		}
10849 	else
10850 		{
10851 		LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
10852 		mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
10853 		}
10854 	}
10855 
10856 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
10857 	{
10858 	const mDNSu32 slot = HashSlot(&q->qname);
10859 	CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
10860 	CacheRecord *rp;
10861 
10862 	for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10863 		{
10864 		if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10865 			{
10866 			LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
10867 			mDNS_PurgeCacheResourceRecord(m, rp);
10868 			}
10869 		}
10870 	}
10871 
10872 // Check for a positive unicast response to the question but with qtype
10873 mDNSexport mDNSBool mDNS_CheckForCacheRecord(mDNS *const m, DNSQuestion *q, mDNSu16 qtype)
10874 	{
10875 	DNSQuestion question;
10876 	const mDNSu32 slot = HashSlot(&q->qname);
10877 	CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
10878 	CacheRecord *rp;
10879 
10880 	// Create an identical question but with qtype
10881 	mDNS_SetupQuestion(&question, q->InterfaceID, &q->qname, qtype, mDNSNULL, mDNSNULL);
10882 	question.qDNSServer = q->qDNSServer;
10883 
10884 	for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10885 		{
10886 		if (!rp->resrec.InterfaceID && rp->resrec.RecordType != kDNSRecordTypePacketNegative &&
10887 			SameNameRecordAnswersQuestion(&rp->resrec, &question))
10888 			{
10889 			LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m, rp));
10890 			return mDNStrue;
10891 			}
10892 		}
10893 	return mDNSfalse;
10894 	}
10895 
10896 mDNSlocal void CacheRecordResetDNSServer(mDNS *const m, DNSQuestion *q, DNSServer *new)
10897 	{
10898 	const mDNSu32 slot = HashSlot(&q->qname);
10899 	CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
10900 	CacheRecord *rp;
10901 	mDNSBool found = mDNSfalse;
10902 	mDNSBool foundNew = mDNSfalse;
10903 	DNSServer *old = q->qDNSServer;
10904 	mDNSBool newQuestion = IsQuestionNew(m, q);
10905 	DNSQuestion *qptr;
10906 
10907 	// This function is called when the DNSServer is updated to the new question. There may already be
10908 	// some cache entries matching the old DNSServer and/or new DNSServer. There are four cases. In the
10909 	// following table, "Yes" denotes that a cache entry was found for old/new DNSServer.
10910 	//
10911 	// 					old DNSServer		new DNSServer
10912 	//
10913 	//	Case 1				Yes					Yes
10914 	//  Case 2				No					Yes
10915 	//  Case 3				Yes					No
10916 	//  Case 4				No					No
10917 	//
10918 	// Case 1: There are cache entries for both old and new DNSServer. We handle this case by simply
10919 	//		   expiring the old Cache entries, deliver a RMV event (if an ADD event was delivered before)
10920 	//		   followed by the ADD event of the cache entries corresponding to the new server. This
10921 	//		   case happens when we pick a DNSServer, issue a query and get a valid response and create
10922 	//		   cache entries after which it stops responding. Another query (non-duplicate) picks a different
10923 	//	       DNSServer and creates identical cache entries (perhaps through records in Additional records).
10924 	//		   Now if the first one expires and tries to pick the new DNSServer (the original DNSServer
10925 	//		   is not responding) we will find cache entries corresponding to both DNSServers.
10926 	//
10927 	// Case 2: There are no cache entries for the old DNSServer but there are some for the new DNSServer.
10928 	//		   This means we should deliver an ADD event. Normally ADD events are delivered by
10929 	//		   AnswerNewQuestion if it is a new question. So, we check to see if it is a new question
10930 	//		   and if so, leave it to AnswerNewQuestion to deliver it. Otherwise, we use
10931 	//		   AnswerQuestionsForDNSServerChanges to deliver the ADD event. This case happens when a
10932 	//		   question picks a DNS server for which AnswerNewQuestion could not deliver an answer even
10933 	//         though there were potential cache entries but DNSServer did not match. Now when we
10934 	//         pick a new DNSServer, those cache entries may answer this question.
10935 	//
10936 	// Case 3: There are the cache entries for the old DNSServer but none for the new. We just move
10937 	//		   the old cache entries to point to the new DNSServer and the caller is expected to
10938 	//		   do a purge or reconfirm to delete or validate the RDATA. We don't need to do anything
10939 	//		   special for delivering ADD events, as it should have been done/will be done by
10940 	//		   AnswerNewQuestion. This case happens when we picked a DNSServer, sent the query and
10941 	//		   got a response and the cache is expired now and we are reissuing the question but the
10942 	//		   original DNSServer does not respond.
10943 	//
10944 	// Case 4: There are no cache entries either for the old or for the new DNSServer. There is nothing
10945 	//		   much we can do here.
10946 	//
10947 	// Case 2 and 3 are the most common while case 4 is possible when no DNSServers are working. Case 1
10948 	// is relatively less likely to happen in practice
10949 
10950 	// Temporarily set the DNSServer to look for the matching records for the new DNSServer.
10951 	q->qDNSServer = new;
10952 	for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10953 		{
10954 		if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10955 			{
10956 			LogInfo("CacheRecordResetDNSServer: Found cache record %##s for new DNSServer address: %#a", rp->resrec.name->c,
10957 				(rp->resrec.rDNSServer != mDNSNULL ?  &rp->resrec.rDNSServer->addr : mDNSNULL));
10958 			foundNew = mDNStrue;
10959 			break;
10960 			}
10961 		}
10962 	q->qDNSServer = old;
10963 
10964 	for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10965 		{
10966 		if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10967 			{
10968 			// Case1
10969 			found = mDNStrue;
10970 			if (foundNew)
10971 				{
10972 				LogInfo("CacheRecordResetDNSServer: Flushing Resourcerecord %##s, before:%#a, after:%#a", rp->resrec.name->c,
10973 					(rp->resrec.rDNSServer != mDNSNULL ?  &rp->resrec.rDNSServer->addr : mDNSNULL),
10974 					(new != mDNSNULL ?  &new->addr : mDNSNULL));
10975 				mDNS_PurgeCacheResourceRecord(m, rp);
10976 				if (newQuestion)
10977 					{
10978 					// "q" is not a duplicate question. If it is a newQuestion, then the CRActiveQuestion can't be
10979 					// possibly set as it is set only when we deliver the ADD event to the question.
10980 					if (rp->CRActiveQuestion != mDNSNULL)
10981 						{
10982 						LogMsg("CacheRecordResetDNSServer: ERROR!!: CRActiveQuestion %p set, current question %p, name %##s", rp->CRActiveQuestion, q, q->qname.c);
10983 						rp->CRActiveQuestion = mDNSNULL;
10984 						}
10985 					// if this is a new question, then we never delivered an ADD yet, so don't deliver the RMV.
10986 					continue;
10987 					}
10988 				}
10989 			LogInfo("CacheRecordResetDNSServer: resetting cache record %##s DNSServer address before:%#a,"
10990 				" after:%#a, CRActiveQuestion %p", rp->resrec.name->c, (rp->resrec.rDNSServer != mDNSNULL ?
10991 				&rp->resrec.rDNSServer->addr : mDNSNULL), (new != mDNSNULL ?  &new->addr : mDNSNULL),
10992 				rp->CRActiveQuestion);
10993 			// Though we set it to the new DNS server, the caller is *assumed* to do either a purge
10994 			// or reconfirm or send out questions to the "new" server to verify whether the cached
10995 			// RDATA is valid
10996 			rp->resrec.rDNSServer = new;
10997 			}
10998 		}
10999 
11000 	// Case 1 and Case 2
11001 	if ((found && foundNew) || (!found && foundNew))
11002 		{
11003 		if (newQuestion)
11004 			LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11005 		else if (QuerySuppressed(q))
11006 			LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for suppressed question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11007 		else
11008 			{
11009 			LogInfo("CacheRecordResetDNSServer: deliverAddEvents set for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11010 			q->deliverAddEvents = mDNStrue;
11011 			for (qptr = q->next; qptr; qptr = qptr->next)
11012 				if (qptr->DuplicateOf == q) qptr->deliverAddEvents = mDNStrue;
11013 			}
11014 		return;
11015 		}
11016 
11017 	// Case 3 and Case 4
11018 	return;
11019 	}
11020 
11021 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
11022 	{
11023 	DNSQuestion *qptr;
11024 
11025 	// 1. Whenever we change the DNS server, we change the message identifier also so that response
11026 	// from the old server is not accepted as a response from the new server but only messages
11027 	// from the new server are accepted as valid responses. We do it irrespective of whether "new"
11028 	// is NULL or not. It is possible that we send two queries, no responses, pick a new DNS server
11029 	// which is NULL and now the response comes back and will try to penalize the DNS server which
11030 	// is NULL. By setting the messageID here, we will not accept that as a valid response.
11031 
11032 	q->TargetQID = mDNS_NewMessageID(m);
11033 
11034 	// 2. Move the old cache records to point them at the new DNSServer so that we can deliver the ADD/RMV events
11035 	// appropriately. At any point in time, we want all the cache records point only to one DNSServer for a given
11036 	// question. "DNSServer" here is the DNSServer object and not the DNS server itself. It is possible to
11037 	// have the same DNS server address in two objects, one scoped and another not scoped. But, the cache is per
11038 	// DNSServer object. By maintaining the question and the cache entries point to the same DNSServer
11039 	// always, the cache maintenance and delivery of ADD/RMV events becomes simpler.
11040 	//
11041 	// CacheRecordResetDNSServer should be called only once for the non-duplicate question as once the cache
11042 	// entries are moved to point to the new DNSServer, we don't need to call it for the duplicate question
11043 	// and it is wrong to call for the duplicate question as it's decision to mark deliverAddevents will be
11044 	// incorrect.
11045 
11046 	if (q->DuplicateOf)
11047 		LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
11048 	else
11049 		CacheRecordResetDNSServer(m, q, new);
11050 
11051 	// 3. Make sure all the duplicate questions point to the same DNSServer so that delivery
11052 	// of events for all of them are consistent. Duplicates for a question are always inserted
11053 	// after in the list.
11054 	q->qDNSServer = new;
11055 	for (qptr = q->next ; qptr; qptr = qptr->next)
11056 		{
11057 		if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
11058 		}
11059 	}
11060 
11061 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
11062 	{
11063 	mDNSu32 slot;
11064 	CacheGroup *cg;
11065 	CacheRecord *cr;
11066 
11067 	mDNSAddr     v4, v6, r;
11068 	domainname   fqdn;
11069 	DNSServer   *ptr, **p = &m->DNSServers;
11070 	const DNSServer *oldServers = m->DNSServers;
11071 	DNSQuestion *q;
11072 	McastResolver *mr, **mres = &m->McastResolvers;
11073 
11074 	debugf("uDNS_SetupDNSConfig: entry");
11075 
11076 	// Let the platform layer get the current DNS information
11077 	// The m->StartWABQueries is set when we get the first domain enumeration query (no need to hit the network
11078 	// with domain enumeration queries until we actually need that information). Even if it is not set, we still
11079 	// need to setup the search domains so that we can append them to queries that need them.
11080 
11081 	uDNS_SetupSearchDomains(m, m->StartWABQueries ? UDNS_START_WAB_QUERY : 0);
11082 
11083 	mDNS_Lock(m);
11084 
11085 	for (ptr = m->DNSServers; ptr; ptr = ptr->next)
11086 		{
11087 		ptr->penaltyTime = 0;
11088 		ptr->flags |= DNSServer_FlagDelete;
11089 		}
11090 
11091 	// We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
11092 	// mcast resolvers. Today we get both mcast and ucast configuration using the same
11093 	// API
11094 	for (mr = m->McastResolvers; mr; mr = mr->next)
11095 		mr->flags |= McastResolver_FlagDelete;
11096 
11097 	mDNSPlatformSetDNSConfig(m, mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL);
11098 
11099 	// For now, we just delete the mcast resolvers. We don't deal with cache or
11100 	// questions here. Neither question nor cache point to mcast resolvers. Questions
11101 	// do inherit the timeout values from mcast resolvers. But we don't bother
11102 	// affecting them as they never change.
11103 	while (*mres)
11104 		{
11105 		if (((*mres)->flags & DNSServer_FlagDelete) != 0)
11106 			{
11107 			mr = *mres;
11108 			*mres = (*mres)->next;
11109 			debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
11110 			mDNSPlatformMemFree(mr);
11111 			}
11112 		else
11113 			{
11114 			(*mres)->flags &= ~McastResolver_FlagNew;
11115 			mres = &(*mres)->next;
11116 			}
11117 		}
11118 
11119 	// Mark the records to be flushed that match a new resolver. We need to do this before
11120 	// we walk the questions below where we change the DNSServer pointer of the cache
11121 	// record
11122 	FORALL_CACHERECORDS(slot, cg, cr)
11123 		{
11124 		if (cr->resrec.InterfaceID) continue;
11125 
11126 		// We just mark them for purge or reconfirm. We can't affect the DNSServer pointer
11127 		// here as the code below that calls CacheRecordResetDNSServer relies on this
11128 		//
11129 		// The new DNSServer may be a scoped or non-scoped one. We use the active question's
11130 		// InterfaceID for looking up the right DNS server
11131 		ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL);
11132 
11133 		// Purge or Reconfirm if this cache entry would use the new DNS server
11134 		if (ptr && (ptr != cr->resrec.rDNSServer))
11135 			{
11136 			// As the DNSServers for this cache record is not the same anymore, we don't
11137 			// want any new questions to pick this old value
11138 			if (cr->CRActiveQuestion == mDNSNULL)
11139 				{
11140 				LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s", CRDisplayString(m, cr));
11141 				mDNS_PurgeCacheResourceRecord(m, cr);
11142 				}
11143 			else
11144 				{
11145 				LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s", CRDisplayString(m, cr));
11146 				PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
11147 				}
11148 			}
11149 		}
11150 	// Update our qDNSServer pointers before we go and free the DNSServer object memory
11151 	for (q = m->Questions; q; q=q->next)
11152 		if (!mDNSOpaque16IsZero(q->TargetQID))
11153 			{
11154 			DNSServer *s, *t;
11155 			DNSQuestion *qptr;
11156 			if (q->DuplicateOf) continue;
11157 			SetValidDNSServers(m, q);
11158 			q->triedAllServersOnce = 0;
11159 			s = GetServerForQuestion(m, q);
11160 			t = q->qDNSServer;
11161 			if (t != s)
11162 				{
11163 				// If DNS Server for this question has changed, reactivate it
11164 				debugf("uDNS_SetupDNSConfig: Updating DNS Server from %p %#a:%d (%##s) to %p %#a:%d (%##s) for %##s (%s)",
11165 					t, t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
11166 					s, s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
11167 					q->qname.c, DNSTypeName(q->qtype));
11168 
11169 				// After we reset the DNSServer pointer on the cache records here, three things could happen:
11170 				//
11171 				// 1) The query gets sent out and when the actual response comes back later it is possible
11172 				// that the response has the same RDATA, in which case we update our cache entry.
11173 				// If the response is different, then the entry will expire and a new entry gets added.
11174 				// For the latter case to generate a RMV followed by ADD events, we need to reset the DNS
11175 				// server here to match the question and the cache record.
11176 				//
11177 				// 2) We might have marked the cache entries for purge above and for us to be able to generate the RMV
11178 				// events for the questions, the DNSServer on the question should match the Cache Record
11179 				//
11180 				// 3) We might have marked the cache entries for reconfirm above, for which we send the query out which is
11181 				// the same as the first case above.
11182 
11183 				DNSServerChangeForQuestion(m, q, s);
11184 				q->unansweredQueries = 0;
11185 				// We still need to pick a new DNSServer for the questions that have been
11186 				// suppressed, but it is wrong to activate the query as DNS server change
11187 				// could not possibly change the status of SuppressUnusable questions
11188 				if (!QuerySuppressed(q))
11189 					{
11190 					debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11191 					ActivateUnicastQuery(m, q, mDNStrue);
11192 					// ActivateUnicastQuery is called for duplicate questions also as it does something
11193 					// special for AutoTunnel questions
11194 					for (qptr = q->next ; qptr; qptr = qptr->next)
11195 						{
11196 						if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
11197 						}
11198 					}
11199 				}
11200 			else
11201 				{
11202 				debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
11203 					q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
11204 				for (qptr = q->next ; qptr; qptr = qptr->next)
11205 					if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
11206 				}
11207 			}
11208 
11209 	while (*p)
11210 		{
11211 		if (((*p)->flags & DNSServer_FlagDelete) != 0)
11212 			{
11213 			// Scan our cache, looking for uDNS records that we would have queried this server for.
11214 			// We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
11215 			// different DNS servers can give different answers to the same question.
11216 			ptr = *p;
11217 			FORALL_CACHERECORDS(slot, cg, cr)
11218 				{
11219 				if (cr->resrec.InterfaceID) continue;
11220 				if (cr->resrec.rDNSServer == ptr)
11221 					{
11222 					// If we don't have an active question for this cache record, neither Purge can
11223 					// generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
11224 					// pointer on the record NULL so that we don't point to freed memory (We might dereference
11225 					// DNSServer pointers from resource record for logging purposes).
11226 					//
11227 					// If there is an active question, point to its DNSServer as long as it does not point to the
11228 					// freed one. We already went through the questions above and made them point at either the
11229 					// new server or NULL if there is no server and also affected the cache entries that match
11230 					// this question. Hence, whenever we hit a resource record with a DNSServer that is just
11231 					// about to be deleted, we should never have an active question. The code below just tries to
11232 					// be careful logging messages if we ever hit this case.
11233 
11234 					if (cr->CRActiveQuestion)
11235 						{
11236 						DNSQuestion *qptr = cr->CRActiveQuestion;
11237 						if (qptr->qDNSServer == mDNSNULL)
11238 							LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) with DNSServer Address NULL, Server to be deleted %#a",
11239 								CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), &ptr->addr);
11240 						else
11241 							LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) DNSServer Address %#a, Server to be deleted %#a",
11242 								CRDisplayString(m, cr),  qptr->qname.c, DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr, &ptr->addr);
11243 
11244 						if (qptr->qDNSServer == ptr)
11245 							{
11246 							qptr->validDNSServers = zeroOpaque64;
11247 							qptr->qDNSServer = mDNSNULL;
11248 							cr->resrec.rDNSServer = mDNSNULL;
11249 							}
11250 						else
11251 							{
11252 							cr->resrec.rDNSServer = qptr->qDNSServer;
11253 							}
11254 						}
11255 					else
11256 						{
11257 						LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
11258 							cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
11259 						cr->resrec.rDNSServer = mDNSNULL;
11260 						}
11261 
11262 					PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
11263 					}
11264 				}
11265 			*p = (*p)->next;
11266 			debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
11267 			mDNSPlatformMemFree(ptr);
11268 			NumUnicastDNSServers--;
11269 			}
11270 		else
11271 			{
11272 			(*p)->flags &= ~DNSServer_FlagNew;
11273 			p = &(*p)->next;
11274 			}
11275 		}
11276 
11277 	// 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).
11278 	// This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
11279 	// Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
11280 	// 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.
11281 	if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
11282 		{
11283 		int count = 0;
11284 		FORALL_CACHERECORDS(slot, cg, cr) if (!cr->resrec.InterfaceID) { mDNS_PurgeCacheResourceRecord(m, cr); count++; }
11285 		LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
11286 			m->DNSServers ? "DNS server became" : "No DNS servers", count);
11287 
11288 		// Force anything that needs to get zone data to get that information again
11289 		RestartRecordGetZoneData(m);
11290 		}
11291 
11292 	// Did our FQDN change?
11293 	if (!SameDomainName(&fqdn, &m->FQDN))
11294 		{
11295 		if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
11296 
11297 		AssignDomainName(&m->FQDN, &fqdn);
11298 
11299 		if (m->FQDN.c[0])
11300 			{
11301 			mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
11302 			mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
11303 			}
11304 		}
11305 
11306 	mDNS_Unlock(m);
11307 
11308 	// handle router and primary interface changes
11309 	v4 = v6 = r = zeroAddr;
11310 	v4.type = r.type = mDNSAddrType_IPv4;
11311 
11312 	if (mDNSPlatformGetPrimaryInterface(m, &v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
11313 		{
11314 		mDNS_SetPrimaryInterfaceInfo(m,
11315 			!mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
11316 			!mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
11317 			!mDNSIPv4AddressIsZero(r .ip.v4) ? &r  : mDNSNULL);
11318 		}
11319 	else
11320 		{
11321 		mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
11322 		if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);	// Set status to 1 to indicate temporary failure
11323 		}
11324 
11325 	debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
11326 	return mStatus_NoError;
11327 	}
11328 
11329 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
11330 	{
11331 	m->mDNSPlatformStatus = result;
11332 	if (m->MainCallback)
11333 		{
11334 		mDNS_Lock(m);
11335 		mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
11336 		m->MainCallback(m, mStatus_NoError);
11337 		mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
11338 		mDNS_Unlock(m);
11339 		}
11340 	}
11341 
11342 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
11343 	{
11344 	m->CurrentRecord = start;
11345 	while (m->CurrentRecord)
11346 		{
11347 		AuthRecord *rr = m->CurrentRecord;
11348 		LogInfo("DeregLoop: %s deregistration for %p %02X %s",
11349 			(rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating  " : "Accelerating",
11350 			rr, rr->resrec.RecordType, ARDisplayString(m, rr));
11351 		if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
11352 			mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
11353 		else if (rr->AnnounceCount > 1)
11354 			{
11355 			rr->AnnounceCount = 1;
11356 			rr->LastAPTime = m->timenow - rr->ThisAPInterval;
11357 			}
11358 		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
11359 		// new records could have been added to the end of the list as a result of that call.
11360 		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
11361 			m->CurrentRecord = rr->next;
11362 		}
11363 	}
11364 
11365 mDNSexport void mDNS_StartExit(mDNS *const m)
11366 	{
11367 	NetworkInterfaceInfo *intf;
11368 	AuthRecord *rr;
11369 
11370 	mDNS_Lock(m);
11371 
11372 	LogInfo("mDNS_StartExit");
11373 	m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
11374 
11375 	mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0);
11376 
11377 #if APPLE_OSX_mDNSResponder
11378 #if ! NO_WCF
11379 	CHECK_WCF_FUNCTION(WCFConnectionDealloc)
11380 		{
11381 		if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
11382 		}
11383 #endif
11384 #endif
11385 
11386 #ifndef UNICAST_DISABLED
11387 	{
11388 	SearchListElem *s;
11389 	SuspendLLQs(m);
11390 	// Don't need to do SleepRecordRegistrations() here
11391 	// because we deregister all records and services later in this routine
11392 	while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
11393 
11394 	// For each member of our SearchList, deregister any records it may have created, and cut them from the list.
11395 	// Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
11396 	// and we may crash because the list still contains dangling pointers.
11397 	for (s = SearchList; s; s = s->next)
11398 		while (s->AuthRecs)
11399 			{
11400 			ARListElem *dereg = s->AuthRecs;
11401 			s->AuthRecs = s->AuthRecs->next;
11402 			mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal);	// Memory will be freed in the FreeARElemCallback
11403 			}
11404 	}
11405 #endif
11406 
11407 	for (intf = m->HostInterfaces; intf; intf = intf->next)
11408 		if (intf->Advertise)
11409 			DeadvertiseInterface(m, intf);
11410 
11411 	// Shut down all our active NAT Traversals
11412 	while (m->NATTraversals)
11413 		{
11414 		NATTraversalInfo *t = m->NATTraversals;
11415 		mDNS_StopNATOperation_internal(m, t);		// This will cut 't' from the list, thereby advancing m->NATTraversals in the process
11416 
11417 		// After stopping the NAT Traversal, we zero out the fields.
11418 		// This has particularly important implications for our AutoTunnel records --
11419 		// when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
11420 		// handlers to just turn around and attempt to re-register those same records.
11421 		// Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
11422 		// to not do this.
11423 		t->ExternalAddress = zerov4Addr;
11424 		t->ExternalPort    = zeroIPPort;
11425 		t->RequestedPort   = zeroIPPort;
11426 		t->Lifetime        = 0;
11427 		t->Result          = mStatus_NoError;
11428 		}
11429 
11430 	// Make sure there are nothing but deregistering records remaining in the list
11431 	if (m->CurrentRecord)
11432 		LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
11433 
11434 	// We're in the process of shutting down, so queries, etc. are no longer available.
11435 	// Consequently, determining certain information, e.g. the uDNS update server's IP
11436 	// address, will not be possible.  The records on the main list are more likely to
11437 	// already contain such information, so we deregister the duplicate records first.
11438 	LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
11439 	DeregLoop(m, m->DuplicateRecords);
11440 	LogInfo("mDNS_StartExit: Deregistering resource records");
11441 	DeregLoop(m, m->ResourceRecords);
11442 
11443 	// If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
11444 	// we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
11445 	if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
11446 		{
11447 		m->NextScheduledResponse = m->timenow;
11448 		m->SuppressSending = 0;
11449 		}
11450 
11451 	if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
11452 	else                    LogInfo("mDNS_StartExit: No deregistering records remain");
11453 
11454 	for (rr = m->DuplicateRecords; rr; rr = rr->next)
11455 		LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
11456 
11457 	// If any deregistering records remain, send their deregistration announcements before we exit
11458 	if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
11459 
11460 	mDNS_Unlock(m);
11461 
11462 	LogInfo("mDNS_StartExit: done");
11463 	}
11464 
11465 mDNSexport void mDNS_FinalExit(mDNS *const m)
11466 	{
11467 	mDNSu32 rrcache_active = 0;
11468 	mDNSu32 rrcache_totalused = 0;
11469 	mDNSu32 slot;
11470 	AuthRecord *rr;
11471 
11472 	LogInfo("mDNS_FinalExit: mDNSPlatformClose");
11473 	mDNSPlatformClose(m);
11474 
11475 	rrcache_totalused = m->rrcache_totalused;
11476 	for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
11477 		{
11478 		while (m->rrcache_hash[slot])
11479 			{
11480 			CacheGroup *cg = m->rrcache_hash[slot];
11481 			while (cg->members)
11482 				{
11483 				CacheRecord *cr = cg->members;
11484 				cg->members = cg->members->next;
11485 				if (cr->CRActiveQuestion) rrcache_active++;
11486 				ReleaseCacheRecord(m, cr);
11487 				}
11488 			cg->rrcache_tail = &cg->members;
11489 			ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
11490 			}
11491 		}
11492 	debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
11493 	if (rrcache_active != m->rrcache_active)
11494 		LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
11495 
11496 	for (rr = m->ResourceRecords; rr; rr = rr->next)
11497 		LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
11498 
11499 	LogInfo("mDNS_FinalExit: done");
11500 	}
11501