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
62WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
63void 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
75mDNSlocal void BeginSleepProcessing(mDNS *const m);
76mDNSlocal void RetrySPSRegistrations(mDNS *const m);
77mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password);
78mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
79mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
80mDNSlocal 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
96mDNSexport 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
126mDNSlocal 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
139mDNSexport 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
159mDNSlocal 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
170mDNSlocal 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
182mDNSlocal 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
238mDNSexport 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
247mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
248	{
249	return(AuthGroupForName(r, slot, rr->namehash, rr->name));
250	}
251
252mDNSlocal 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
280mDNSexport 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
295mDNSexport 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
322mDNSexport 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
331mDNSlocal 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
336mDNSexport 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
365mDNSlocal 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
372mDNSexport 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
379mDNSlocal 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
393mDNSlocal 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
442mDNSlocal 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
491mDNSlocal 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
524mDNSlocal 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
615mDNSlocal 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
636mDNSlocal 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.
658mDNSlocal 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
675mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
676	{
677	if (rr->resrec.RecordType == kDNSRecordTypeUnique)
678		{
679		if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
680			{
681			LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
682			LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
683			}
684		if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
685			m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
686		// Some defensive code:
687		// If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
688		// NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
689		// See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
690		if (m->NextScheduledProbe - m->timenow < 0)
691			m->NextScheduledProbe = m->timenow;
692		}
693	else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
694		{
695		if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
696			m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
697		}
698	}
699
700mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
701	{
702	// For reverse-mapping Sleep Proxy PTR records, probe interval is one second
703	rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
704
705	// * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
706	// * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
707	//   records that are going to probe, then we delay its first announcement so that it will
708	//   go out synchronized with the first announcement for the other records that *are* probing.
709	//   This is a minor performance tweak that helps keep groups of related records synchronized together.
710	//   The addition of "interval / 2" is to make sure that, in the event that any of the probes are
711	//   delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
712	//   When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
713	//   because they will meet the criterion of being at least half-way to their scheduled announcement time.
714	// * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
715
716	if (rr->ProbeCount)
717		{
718		// If we have no probe suppression time set, or it is in the past, set it now
719		if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
720			{
721			// To allow us to aggregate probes when a group of services are registered together,
722			// the first probe is delayed 1/4 second. This means the common-case behaviour is:
723			// 1/4 second wait; probe
724			// 1/4 second wait; probe
725			// 1/4 second wait; probe
726			// 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
727			m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
728
729			// If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
730			if (m->SuppressProbes - m->NextScheduledProbe >= 0)
731				m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
732			if (m->SuppressProbes - m->timenow < 0)		// Make sure we don't set m->SuppressProbes excessively in the past
733				m->SuppressProbes = m->timenow;
734
735			// If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
736			if (m->SuppressProbes - m->NextScheduledQuery >= 0)
737				m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
738			if (m->SuppressProbes - m->timenow < 0)		// Make sure we don't set m->SuppressProbes excessively in the past
739				m->SuppressProbes = m->timenow;
740
741			// except... don't expect to be able to send before the m->SuppressSending timer fires
742			if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
743				m->SuppressProbes = NonZeroTime(m->SuppressSending);
744
745			if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
746				{
747				LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
748					m->SuppressProbes     - m->timenow,
749					m->NextScheduledProbe - m->timenow,
750					m->NextScheduledQuery - m->timenow,
751					m->SuppressSending,
752					m->SuppressSending    - m->timenow);
753				m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
754				}
755			}
756		rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
757		}
758	else if (m->SuppressProbes && m->SuppressProbes - m->timenow >= 0)
759		rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
760	else
761		rr->LastAPTime = m->timenow - rr->ThisAPInterval;
762
763	// For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
764	// wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
765	// After three probes one second apart with no answer, we conclude the client is now sleeping
766	// and we can begin broadcasting our announcements to take over ownership of that IP address.
767	// If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
768	// (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
769	if (rr->AddressProxy.type) rr->LastAPTime = m->timenow;
770
771	// Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
772	// but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
773	// Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
774	// Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
775	// new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
776	if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
777		if (rr->WakeUp.HMAC.l[0] && rr->resrec.rrtype == kDNSType_AAAA)
778			rr->LastAPTime = m->timenow - rr->ThisAPInterval + mDNSPlatformOneSecond * 10;
779
780	// Set LastMCTime to now, to inhibit multicast responses
781	// (no need to send additional multicast responses when we're announcing anyway)
782	rr->LastMCTime      = m->timenow;
783	rr->LastMCInterface = mDNSInterfaceMark;
784
785	SetNextAnnounceProbeTime(m, rr);
786	}
787
788mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
789	{
790	const domainname *target;
791	if (rr->AutoTarget)
792		{
793		// For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
794		// advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
795		// with the port number in our advertised SRV record automatically tracking the external mapped port.
796		DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
797		if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
798		}
799
800	target = GetServiceTarget(m, rr);
801	if (!target || target->c[0] == 0)
802		{
803		// defer registration until we've got a target
804		LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
805		rr->state = regState_NoTarget;
806		return mDNSNULL;
807		}
808	else
809		{
810		LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
811		return target;
812		}
813	}
814
815// Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
816// Eventually we should unify this with GetServiceTarget() in uDNS.c
817mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
818	{
819	domainname *const target = GetRRDomainNameTarget(&rr->resrec);
820	const domainname *newname = &m->MulticastHostname;
821
822	if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
823
824	if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
825		{
826		const domainname *const n = SetUnicastTargetToHostName(m, rr);
827		if (n) newname = n;
828		else { target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
829		}
830
831	if (target && SameDomainName(target, newname))
832		debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
833
834	if (target && !SameDomainName(target, newname))
835		{
836		AssignDomainName(target, newname);
837		SetNewRData(&rr->resrec, mDNSNULL, 0);		// Update rdlength, rdestimate, rdatahash
838
839		// If we're in the middle of probing this record, we need to start again,
840		// because changing its rdata may change the outcome of the tie-breaker.
841		// (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
842		rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
843
844		// If we've announced this record, we really should send a goodbye packet for the old rdata before
845		// changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
846		// so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
847		if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
848			debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
849				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
850
851		rr->AnnounceCount  = InitialAnnounceCount;
852		rr->RequireGoodbye = mDNSfalse;
853		InitializeLastAPTime(m, rr);
854		}
855	}
856
857mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
858	{
859	if (rr->RecordCallback)
860		{
861		// CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
862		// is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
863		rr->Acknowledged = mDNStrue;
864		mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
865		rr->RecordCallback(m, rr, mStatus_NoError);
866		mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
867		}
868	}
869
870mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
871	{
872	// Make sure that we don't activate the SRV record and associated service records, if it is in
873	// NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
874	// We should not activate any of the other reords (PTR, TXT) that are part of the service. When
875	// the target becomes available, the records will be reregistered.
876	if (rr->resrec.rrtype != kDNSType_SRV)
877		{
878		AuthRecord *srvRR = mDNSNULL;
879		if (rr->resrec.rrtype == kDNSType_PTR)
880			srvRR = rr->Additional1;
881		else if (rr->resrec.rrtype == kDNSType_TXT)
882			srvRR = rr->DependentOn;
883		if (srvRR)
884			{
885			if (srvRR->resrec.rrtype != kDNSType_SRV)
886				{
887				LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
888				}
889			else
890				{
891				LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
892					ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
893				rr->state = srvRR->state;
894				}
895			}
896		}
897
898	if (rr->state == regState_NoTarget)
899		{
900		LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
901		return;
902		}
903	// When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
904	// the service/record was being deregistered. In that case, we should not try to register again. For the cases where
905	// the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
906	// was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
907	// to sleep, then it is okay to start in Pending state as we will go back to NoTarget state if we don't have a target.
908	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
909		{
910		LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
911		rr->state = regState_DeregPending;
912		}
913	else
914		{
915		LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
916		rr->state = regState_Pending;
917		}
918	rr->ProbeCount     = 0;
919	rr->AnnounceCount  = 0;
920	rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
921	rr->LastAPTime     = m->timenow - rr->ThisAPInterval;
922	rr->expire         = 0;	// Forget about all the leases, start fresh
923	rr->uselease       = mDNStrue;
924	rr->updateid       = zeroID;
925	rr->SRVChanged     = mDNSfalse;
926	rr->updateError    = mStatus_NoError;
927	// RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
928	// The records might already be registered with the server and hence could have NAT state.
929	if (rr->NATinfo.clientContext)
930		{
931		mDNS_StopNATOperation_internal(m, &rr->NATinfo);
932		rr->NATinfo.clientContext = mDNSNULL;
933		}
934	if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
935	if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
936	if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
937		m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
938	}
939
940// Two records qualify to be local duplicates if:
941// (a) the RecordTypes are the same, or
942// (b) one is Unique and the other Verified
943// (c) either is in the process of deregistering
944#define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
945	((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
946	((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
947
948#define RecordIsLocalDuplicate(A,B) \
949	((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
950
951mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
952	{
953	AuthGroup *a;
954	AuthGroup **ag = &a;
955	AuthRecord **rp;
956	const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
957
958	a = AuthGroupForRecord(r, slot, &rr->resrec);
959	if (!a) return mDNSNULL;
960	rp = &(*ag)->members;
961	while (*rp)
962		{
963		if (!RecordIsLocalDuplicate(*rp, rr))
964			rp=&(*rp)->next;
965		else
966			{
967			if ((*rp)->resrec.RecordType == kDNSRecordTypeDeregistering)
968				{
969				(*rp)->AnnounceCount = 0;
970				rp=&(*rp)->next;
971				}
972			else return *rp;
973			}
974		}
975	return (mDNSNULL);
976	}
977
978mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
979	{
980	AuthGroup *a;
981	AuthGroup **ag = &a;
982	AuthRecord **rp;
983	const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
984
985	a = AuthGroupForRecord(r, slot, &rr->resrec);
986	if (!a) return mDNSfalse;
987	rp = &(*ag)->members;
988	while (*rp)
989		{
990		const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
991		const AuthRecord *s2 = (*rp)->RRSet ? (*rp)->RRSet : *rp;
992		if (s1 != s2 && SameResourceRecordSignature((*rp), rr) && !IdenticalSameNameRecord(&(*rp)->resrec, &rr->resrec))
993			return mDNStrue;
994		else
995			rp=&(*rp)->next;
996		}
997	return (mDNSfalse);
998	}
999
1000// checks to see if "rr" is already present
1001mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1002	{
1003	AuthGroup *a;
1004	AuthGroup **ag = &a;
1005	AuthRecord **rp;
1006	const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1007
1008	a = AuthGroupForRecord(r, slot, &rr->resrec);
1009	if (!a) return mDNSNULL;
1010	rp = &(*ag)->members;
1011	while (*rp)
1012		{
1013		if (*rp != rr)
1014			rp=&(*rp)->next;
1015		else
1016			{
1017			return *rp;
1018			}
1019		}
1020	return (mDNSNULL);
1021	}
1022
1023// Exported so uDNS.c can call this
1024mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1025	{
1026	domainname *target = GetRRDomainNameTarget(&rr->resrec);
1027	AuthRecord *r;
1028	AuthRecord **p = &m->ResourceRecords;
1029	AuthRecord **d = &m->DuplicateRecords;
1030
1031	if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1032		{ LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1033
1034	if (!rr->resrec.RecordType)
1035		{ LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1036
1037	if (m->ShutdownTime)
1038		{ LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1039
1040	if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1041		{
1042		mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1043		if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1044			{
1045			rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1046			rr->ARType = AuthRecordLocalOnly;
1047			}
1048		if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1049			{
1050			NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1051			if (intf && !intf->Advertise){ rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1052			}
1053		if (rr->resrec.InterfaceID != previousID)
1054			LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1055		}
1056
1057	if (RRLocalOnly(rr))
1058		{
1059		if (CheckAuthSameRecord(&m->rrauth, rr))
1060			{
1061			LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1062				rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1063			return(mStatus_AlreadyRegistered);
1064			}
1065		}
1066	else
1067		{
1068		while (*p && *p != rr) p=&(*p)->next;
1069		if (*p)
1070			{
1071			LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1072				rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1073			return(mStatus_AlreadyRegistered);
1074			}
1075		}
1076
1077	while (*d && *d != rr) d=&(*d)->next;
1078	if (*d)
1079		{
1080		LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1081				rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1082		return(mStatus_AlreadyRegistered);
1083		}
1084
1085	if (rr->DependentOn)
1086		{
1087		if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1088			rr->resrec.RecordType =  kDNSRecordTypeVerified;
1089		else
1090			{
1091			LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1092				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1093			return(mStatus_Invalid);
1094			}
1095		if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1096			{
1097			LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1098				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1099			return(mStatus_Invalid);
1100			}
1101		}
1102
1103	// If this resource record is referencing a specific interface, make sure it exists.
1104	// Skip checks for LocalOnly and P2P as they are not valid InterfaceIDs. Also, for scoped
1105	// entries in /etc/hosts skip that check as that interface may not be valid at this time.
1106	if (rr->resrec.InterfaceID && rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
1107		{
1108		NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1109		if (!intf)
1110			{
1111			debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr->resrec.InterfaceID);
1112			return(mStatus_BadReferenceErr);
1113			}
1114		}
1115
1116	rr->next = mDNSNULL;
1117
1118	// Field Group 1: The actual information pertaining to this resource record
1119	// Set up by client prior to call
1120
1121	// Field Group 2: Persistent metadata for Authoritative Records
1122//	rr->Additional1       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1123//	rr->Additional2       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1124//	rr->DependentOn       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1125//	rr->RRSet             = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1126//	rr->Callback          = already set      in mDNS_SetupResourceRecord
1127//	rr->Context           = already set      in mDNS_SetupResourceRecord
1128//	rr->RecordType        = already set      in mDNS_SetupResourceRecord
1129//	rr->HostTarget        = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1130//	rr->AllowRemoteQuery  = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1131	// Make sure target is not uninitialized data, or we may crash writing debugging log messages
1132	if (rr->AutoTarget && target) target->c[0] = 0;
1133
1134	// Field Group 3: Transient state for Authoritative Records
1135	rr->Acknowledged      = mDNSfalse;
1136	rr->ProbeCount        = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1137	rr->AnnounceCount     = InitialAnnounceCount;
1138	rr->RequireGoodbye    = mDNSfalse;
1139	rr->AnsweredLocalQ    = mDNSfalse;
1140	rr->IncludeInProbe    = mDNSfalse;
1141	rr->ImmedUnicast      = mDNSfalse;
1142	rr->SendNSECNow       = mDNSNULL;
1143	rr->ImmedAnswer       = mDNSNULL;
1144	rr->ImmedAdditional   = mDNSNULL;
1145	rr->SendRNow          = mDNSNULL;
1146	rr->v4Requester       = zerov4Addr;
1147	rr->v6Requester       = zerov6Addr;
1148	rr->NextResponse      = mDNSNULL;
1149	rr->NR_AnswerTo       = mDNSNULL;
1150	rr->NR_AdditionalTo   = mDNSNULL;
1151	if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1152//	rr->LastAPTime        = Set for us in InitializeLastAPTime()
1153//	rr->LastMCTime        = Set for us in InitializeLastAPTime()
1154//	rr->LastMCInterface   = Set for us in InitializeLastAPTime()
1155	rr->NewRData          = mDNSNULL;
1156	rr->newrdlength       = 0;
1157	rr->UpdateCallback    = mDNSNULL;
1158	rr->UpdateCredits     = kMaxUpdateCredits;
1159	rr->NextUpdateCredit  = 0;
1160	rr->UpdateBlocked     = 0;
1161
1162	// For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1163	if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1164
1165	// Field Group 4: Transient uDNS state for Authoritative Records
1166	rr->state             = regState_Zero;
1167	rr->uselease          = 0;
1168	rr->expire            = 0;
1169	rr->Private           = 0;
1170	rr->updateid          = zeroID;
1171	rr->zone              = rr->resrec.name;
1172	rr->nta               = mDNSNULL;
1173	rr->tcp               = mDNSNULL;
1174	rr->OrigRData         = 0;
1175	rr->OrigRDLen         = 0;
1176	rr->InFlightRData     = 0;
1177	rr->InFlightRDLen     = 0;
1178	rr->QueuedRData       = 0;
1179	rr->QueuedRDLen       = 0;
1180	//mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1181	// We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1182	// request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1183	// times with different values if the external NAT port changes during the lifetime of the service registration.
1184	//if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1185
1186//	rr->resrec.interface         = already set in mDNS_SetupResourceRecord
1187//	rr->resrec.name->c           = MUST be set by client
1188//	rr->resrec.rrtype            = already set in mDNS_SetupResourceRecord
1189//	rr->resrec.rrclass           = already set in mDNS_SetupResourceRecord
1190//	rr->resrec.rroriginalttl     = already set in mDNS_SetupResourceRecord
1191//	rr->resrec.rdata             = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1192
1193	// BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1194	// since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1195	// Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1196	if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1197
1198	if (rr->AutoTarget)
1199		{
1200		SetTargetToHostName(m, rr);	// Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1201#ifndef UNICAST_DISABLED
1202		// If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1203		// In this case we leave the record half-formed in the list, and later we'll remove it from the list and re-add it properly.
1204		if (rr->state == regState_NoTarget)
1205			{
1206			// Initialize the target so that we don't crash while logging etc.
1207			domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1208			if (tar) tar->c[0] = 0;
1209			LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1210			}
1211#endif
1212		}
1213	else
1214		{
1215		rr->resrec.rdlength   = GetRDLength(&rr->resrec, mDNSfalse);
1216		rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1217		}
1218
1219	if (!ValidateDomainName(rr->resrec.name))
1220		{ LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1221
1222	// Don't do this until *after* we've set rr->resrec.rdlength
1223	if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1224		{ LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1225
1226	rr->resrec.namehash   = DomainNameHashValue(rr->resrec.name);
1227	rr->resrec.rdatahash  = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1228
1229	if (RRLocalOnly(rr))
1230		{
1231		// If this is supposed to be unique, make sure we don't have any name conflicts.
1232		// If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1233		// (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1234		// complications and not clear whether there are any benefits. See rdar:9304275 for details.
1235		// Hence, just bail out.
1236		if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1237			{
1238			if (CheckAuthRecordConflict(&m->rrauth, rr))
1239				{
1240				LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1241				return mStatus_NameConflict;
1242				}
1243			}
1244		}
1245
1246	// For uDNS records, we don't support duplicate checks at this time.
1247#ifndef UNICAST_DISABLED
1248	if (AuthRecord_uDNS(rr))
1249		{
1250		if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1251		// When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1252		// records to the list, so we now need to update p to advance to the new end to the list before appending our new record.
1253		// Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1254		while (*p) p=&(*p)->next;
1255		*p = rr;
1256		if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1257		rr->ProbeCount    = 0;
1258		rr->AnnounceCount = 0;
1259		if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1260		return(mStatus_NoError);			// <--- Note: For unicast records, code currently bails out at this point
1261		}
1262#endif
1263
1264	// Now that we've finished building our new record, make sure it's not identical to one we already have
1265	if (RRLocalOnly(rr))
1266		{
1267		rr->ProbeCount    = 0;
1268		rr->AnnounceCount = 0;
1269		r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1270		}
1271	else
1272		{
1273		for (r = m->ResourceRecords; r; r=r->next)
1274			if (RecordIsLocalDuplicate(r, rr))
1275				{
1276				if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1277				else break;
1278				}
1279		}
1280
1281	if (r)
1282		{
1283		debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m,rr));
1284		*d = rr;
1285		// If the previous copy of this record is already verified unique,
1286		// then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1287		// Setting ProbeCount to zero will cause SendQueries() to advance this record to
1288		// kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1289		if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1290			rr->ProbeCount = 0;
1291		}
1292	else
1293		{
1294		debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1295		if (RRLocalOnly(rr))
1296			{
1297			AuthGroup *ag;
1298			ag = InsertAuthRecord(m, &m->rrauth, rr);
1299			if (ag && !ag->NewLocalOnlyRecords) {
1300				m->NewLocalOnlyRecords = mDNStrue;
1301				ag->NewLocalOnlyRecords = rr;
1302			}
1303			// No probing for LocalOnly records, Acknowledge them right away
1304			if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1305			AcknowledgeRecord(m, rr);
1306			return(mStatus_NoError);
1307			}
1308		else
1309			{
1310			if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1311			*p = rr;
1312			}
1313		}
1314
1315	if (!AuthRecord_uDNS(rr))	// This check is superfluous, given that for unicast records we (currently) bail out above
1316		{
1317		// For records that are not going to probe, acknowledge them right away
1318		if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1319			AcknowledgeRecord(m, rr);
1320
1321		// Adding a record may affect whether or not we should sleep
1322		mDNS_UpdateAllowSleep(m);
1323		}
1324
1325	return(mStatus_NoError);
1326	}
1327
1328mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1329	{
1330	m->ProbeFailTime = m->timenow;
1331	m->NumFailedProbes++;
1332	// If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1333	// If a bunch of hosts have all been configured with the same name, then they'll all
1334	// conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1335	// up to name-10. After that they'll start adding random increments in the range 1-100,
1336	// so they're more likely to branch out in the available namespace and settle on a set of
1337	// unique names quickly. If after five more tries the host is still conflicting, then we
1338	// may have a serious problem, so we start rate-limiting so we don't melt down the network.
1339	if (m->NumFailedProbes >= 15)
1340		{
1341		m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1342		LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1343			m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1344		}
1345	}
1346
1347mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1348	{
1349	RData *OldRData = rr->resrec.rdata;
1350	mDNSu16 OldRDLen = rr->resrec.rdlength;
1351	SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);	// Update our rdata
1352	rr->NewRData = mDNSNULL;									// Clear the NewRData pointer ...
1353	if (rr->UpdateCallback)
1354		rr->UpdateCallback(m, rr, OldRData, OldRDLen);			// ... and let the client know
1355	}
1356
1357// Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1358// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1359// Exported so uDNS.c can call this
1360mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1361	{
1362	AuthRecord *r2;
1363	mDNSu8 RecordType = rr->resrec.RecordType;
1364	AuthRecord **p = &m->ResourceRecords;	// Find this record in our list of active records
1365	mDNSBool dupList = mDNSfalse;
1366
1367	if (RRLocalOnly(rr))
1368		{
1369		AuthGroup *a;
1370		AuthGroup **ag = &a;
1371		AuthRecord **rp;
1372		const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1373
1374		a = AuthGroupForRecord(&m->rrauth, slot, &rr->resrec);
1375		if (!a) return mDNSfalse;
1376		rp = &(*ag)->members;
1377		while (*rp && *rp != rr) rp=&(*rp)->next;
1378		p = rp;
1379		}
1380	else
1381		{
1382		while (*p && *p != rr) p=&(*p)->next;
1383		}
1384
1385	if (*p)
1386		{
1387		// We found our record on the main list. See if there are any duplicates that need special handling.
1388		if (drt == mDNS_Dereg_conflict)		// If this was a conflict, see that all duplicates get the same treatment
1389			{
1390			// Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1391			// deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1392			for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1393			}
1394		else
1395			{
1396			// Before we delete the record (and potentially send a goodbye packet)
1397			// first see if we have a record on the duplicate list ready to take over from it.
1398			AuthRecord **d = &m->DuplicateRecords;
1399			while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1400			if (*d)
1401				{
1402				AuthRecord *dup = *d;
1403				debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1404					dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1405				*d        = dup->next;		// Cut replacement record from DuplicateRecords list
1406				if (RRLocalOnly(rr))
1407					{
1408					dup->next = mDNSNULL;
1409					if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1410					}
1411				else
1412					{
1413					dup->next = rr->next;		// And then...
1414					rr->next  = dup;			// ... splice it in right after the record we're about to delete
1415					}
1416				dup->resrec.RecordType        = rr->resrec.RecordType;
1417				dup->ProbeCount      = rr->ProbeCount;
1418				dup->AnnounceCount   = rr->AnnounceCount;
1419				dup->RequireGoodbye  = rr->RequireGoodbye;
1420				dup->AnsweredLocalQ  = rr->AnsweredLocalQ;
1421				dup->ImmedAnswer     = rr->ImmedAnswer;
1422				dup->ImmedUnicast    = rr->ImmedUnicast;
1423				dup->ImmedAdditional = rr->ImmedAdditional;
1424				dup->v4Requester     = rr->v4Requester;
1425				dup->v6Requester     = rr->v6Requester;
1426				dup->ThisAPInterval  = rr->ThisAPInterval;
1427				dup->LastAPTime      = rr->LastAPTime;
1428				dup->LastMCTime      = rr->LastMCTime;
1429				dup->LastMCInterface = rr->LastMCInterface;
1430				dup->Private         = rr->Private;
1431				dup->state           = rr->state;
1432				rr->RequireGoodbye = mDNSfalse;
1433				rr->AnsweredLocalQ = mDNSfalse;
1434				}
1435			}
1436		}
1437	else
1438		{
1439		// We didn't find our record on the main list; try the DuplicateRecords list instead.
1440		p = &m->DuplicateRecords;
1441		while (*p && *p != rr) p=&(*p)->next;
1442		// If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1443		if (*p) { rr->RequireGoodbye = mDNSfalse; dupList = mDNStrue; }
1444		if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1445			rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1446		}
1447
1448	if (!*p)
1449		{
1450		// No need to log an error message if we already know this is a potentially repeated deregistration
1451		if (drt != mDNS_Dereg_repeat)
1452			LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1453		return(mStatus_BadReferenceErr);
1454		}
1455
1456	// If this is a shared record and we've announced it at least once,
1457	// we need to retract that announcement before we delete the record
1458
1459	// If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1460	// it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1461	// The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1462	// mechanism to cope with the client callback modifying the question list while that's happening.
1463	// However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1464	// which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1465	// More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1466	// records, thereby invoking yet more callbacks, without limit.
1467	// The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1468	// actual goodbye packets.
1469
1470#ifndef UNICAST_DISABLED
1471	if (AuthRecord_uDNS(rr))
1472		{
1473		if (rr->RequireGoodbye)
1474			{
1475			if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1476			rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
1477			m->LocalRemoveEvents     = mDNStrue;
1478			uDNS_DeregisterRecord(m, rr);
1479			// At this point unconditionally we bail out
1480			// Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1481			// which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1482			// process and will complete asynchronously. Either way we don't need to do anything more here.
1483			return(mStatus_NoError);
1484			}
1485		// Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1486		// from the server. In that case, if the records have been part of a group update, clear the
1487		// state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1488		rr->updateid = zeroID;
1489
1490		// We defer cleaning up NAT state only after sending goodbyes. This is important because
1491		// RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1492		// This happens today when we turn on/off interface where we get multiple network transitions
1493		// and RestartRecordGetZoneData triggers re-registration of the resource records even though
1494		// they may be in Registered state which causes NAT information to be setup multiple times. Defering
1495		// the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1496		// NAT state here takes care of the case where we did not send goodbyes at all.
1497		if (rr->NATinfo.clientContext)
1498			{
1499			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1500			rr->NATinfo.clientContext = mDNSNULL;
1501			}
1502		if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1503		if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
1504		}
1505#endif // UNICAST_DISABLED
1506
1507	if      (RecordType == kDNSRecordTypeUnregistered)
1508		LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1509	else if (RecordType == kDNSRecordTypeDeregistering)
1510		{
1511		LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1512		return(mStatus_BadReferenceErr);
1513		}
1514
1515	// <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1516	// We may want to consider changing this code so that we generate local-only question "rmv"
1517	// events (and maybe goodbye packets too) for unique records as well as for shared records
1518	// Note: If we change the logic for this "if" statement, need to ensure that the code in
1519	// CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1520	// clause will execute here and the record will be cut from the list.
1521	if (rr->WakeUp.HMAC.l[0] ||
1522		(RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1523		{
1524		verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1525		rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
1526		rr->resrec.rroriginalttl = 0;
1527		rr->AnnounceCount        = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1528		rr->ThisAPInterval       = mDNSPlatformOneSecond * 2;
1529		rr->LastAPTime           = m->timenow - rr->ThisAPInterval;
1530		m->LocalRemoveEvents     = mDNStrue;
1531		if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1532			m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1533		}
1534	else
1535		{
1536		if (!dupList && RRLocalOnly(rr))
1537			{
1538			AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1539			if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1540			}
1541		else
1542			{
1543			*p = rr->next;					// Cut this record from the list
1544			if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1545			}
1546		// If someone is about to look at this, bump the pointer forward
1547		if (m->CurrentRecord   == rr) m->CurrentRecord   = rr->next;
1548		rr->next = mDNSNULL;
1549
1550		// Should we generate local remove events here?
1551		// i.e. something like:
1552		// if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1553
1554		verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1555		rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1556
1557		if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1558			debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1559				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1560
1561		// If we have an update queued up which never executed, give the client a chance to free that memory
1562		if (rr->NewRData) CompleteRDataUpdate(m, rr);	// Update our rdata, clear the NewRData pointer, and return memory to the client
1563
1564
1565		// CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1566		// is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1567		// In this case the likely client action to the mStatus_MemFree message is to free the memory,
1568		// so any attempt to touch rr after this is likely to lead to a crash.
1569		if (drt != mDNS_Dereg_conflict)
1570			{
1571			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
1572			LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m, rr));
1573			if (rr->RecordCallback)
1574				rr->RecordCallback(m, rr, mStatus_MemFree);			// MUST NOT touch rr after this
1575			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
1576			}
1577		else
1578			{
1579			RecordProbeFailure(m, rr);
1580			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
1581			if (rr->RecordCallback)
1582				rr->RecordCallback(m, rr, mStatus_NameConflict);	// MUST NOT touch rr after this
1583			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
1584			// Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1585			// Note that with all the client callbacks going on, by the time we get here all the
1586			// records we marked may have been explicitly deregistered by the client anyway.
1587			r2 = m->DuplicateRecords;
1588			while (r2)
1589				{
1590				if (r2->ProbeCount != 0xFF) r2 = r2->next;
1591				else { mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict); r2 = m->DuplicateRecords; }
1592				}
1593			}
1594		}
1595	mDNS_UpdateAllowSleep(m);
1596	return(mStatus_NoError);
1597	}
1598
1599// ***************************************************************************
1600#if COMPILER_LIKES_PRAGMA_MARK
1601#pragma mark -
1602#pragma mark - Packet Sending Functions
1603#endif
1604
1605mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1606	{
1607	if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1608		{
1609		**nrpp = rr;
1610		// NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1611		// If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1612		// The referenced record will definitely be acceptable (by recursive application of this rule)
1613		if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1614		rr->NR_AdditionalTo = add;
1615		*nrpp = &rr->NextResponse;
1616		}
1617	debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1618	}
1619
1620mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1621	{
1622	AuthRecord  *rr, *rr2;
1623	for (rr=ResponseRecords; rr; rr=rr->NextResponse)			// For each record we plan to put
1624		{
1625		// (Note: This is an "if", not a "while". If we add a record, we'll find it again
1626		// later in the "for" loop, and we will follow further "additional" links then.)
1627		if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1628			AddRecordToResponseList(nrpp, rr->Additional1, rr);
1629
1630		if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
1631			AddRecordToResponseList(nrpp, rr->Additional2, rr);
1632
1633		// For SRV records, automatically add the Address record(s) for the target host
1634		if (rr->resrec.rrtype == kDNSType_SRV)
1635			{
1636			for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)					// Scan list of resource records
1637				if (RRTypeIsAddressType(rr2->resrec.rrtype) &&					// For all address records (A/AAAA) ...
1638					ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&	// ... which are valid for answer ...
1639					rr->resrec.rdatahash == rr2->resrec.namehash &&			// ... whose name is the name of the SRV target
1640					SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
1641					AddRecordToResponseList(nrpp, rr2, rr);
1642			}
1643		else if (RRTypeIsAddressType(rr->resrec.rrtype))	// For A or AAAA, put counterpart as additional
1644			{
1645			for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)					// Scan list of resource records
1646				if (RRTypeIsAddressType(rr2->resrec.rrtype) &&					// For all address records (A/AAAA) ...
1647					ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&	// ... which are valid for answer ...
1648					rr->resrec.namehash == rr2->resrec.namehash &&				// ... and have the same name
1649					SameDomainName(rr->resrec.name, rr2->resrec.name))
1650					AddRecordToResponseList(nrpp, rr2, rr);
1651			}
1652		else if (rr->resrec.rrtype == kDNSType_PTR)			// For service PTR, see if we want to add DeviceInfo record
1653			{
1654			if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
1655				SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1656				AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
1657			}
1658		}
1659	}
1660
1661mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
1662	{
1663	AuthRecord *rr;
1664	AuthRecord  *ResponseRecords = mDNSNULL;
1665	AuthRecord **nrp             = &ResponseRecords;
1666	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
1667
1668	// Make a list of all our records that need to be unicast to this destination
1669	for (rr = m->ResourceRecords; rr; rr=rr->next)
1670		{
1671		// If we find we can no longer unicast this answer, clear ImmedUnicast
1672		if (rr->ImmedAnswer == mDNSInterfaceMark               ||
1673			mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
1674			mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr)  )
1675			rr->ImmedUnicast = mDNSfalse;
1676
1677		if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
1678			{
1679			if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
1680				(dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
1681				{
1682				rr->ImmedAnswer  = mDNSNULL;				// Clear the state fields
1683				rr->ImmedUnicast = mDNSfalse;
1684				rr->v4Requester  = zerov4Addr;
1685				rr->v6Requester  = zerov6Addr;
1686
1687				// Only sent records registered for P2P over P2P interfaces
1688				if (intf && !mDNSPlatformValidRecordForInterface(rr, intf))
1689					{
1690					LogInfo("SendDelayedUnicastResponse: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, InterfaceID));
1691					continue;
1692					}
1693
1694				if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse)	// rr->NR_AnswerTo
1695					{ rr->NR_AnswerTo = (mDNSu8*)~0; *nrp = rr; nrp = &rr->NextResponse; }
1696				}
1697			}
1698		}
1699
1700	AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
1701
1702	while (ResponseRecords)
1703		{
1704		mDNSu8 *responseptr = m->omsg.data;
1705		mDNSu8 *newptr;
1706		InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1707
1708		// Put answers in the packet
1709		while (ResponseRecords && ResponseRecords->NR_AnswerTo)
1710			{
1711			rr = ResponseRecords;
1712			if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1713				rr->resrec.rrclass |= kDNSClass_UniqueRRSet;		// Temporarily set the cache flush bit so PutResourceRecord will set it
1714			newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
1715			rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;			// Make sure to clear cache flush bit back to normal state
1716			if (!newptr && m->omsg.h.numAnswers) break;	// If packet full, send it now
1717			if (newptr) responseptr = newptr;
1718			ResponseRecords = rr->NextResponse;
1719			rr->NextResponse    = mDNSNULL;
1720			rr->NR_AnswerTo     = mDNSNULL;
1721			rr->NR_AdditionalTo = mDNSNULL;
1722			rr->RequireGoodbye  = mDNStrue;
1723			}
1724
1725		// Add additionals, if there's space
1726		while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
1727			{
1728			rr = ResponseRecords;
1729			if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1730				rr->resrec.rrclass |= kDNSClass_UniqueRRSet;		// Temporarily set the cache flush bit so PutResourceRecord will set it
1731			newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
1732			rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;			// Make sure to clear cache flush bit back to normal state
1733
1734			if (newptr) responseptr = newptr;
1735			if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
1736			else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
1737			ResponseRecords = rr->NextResponse;
1738			rr->NextResponse    = mDNSNULL;
1739			rr->NR_AnswerTo     = mDNSNULL;
1740			rr->NR_AdditionalTo = mDNSNULL;
1741			}
1742
1743		if (m->omsg.h.numAnswers)
1744			mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL);
1745		}
1746	}
1747
1748// CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1749// and the client's mStatus_MemFree callback will have been invoked
1750mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
1751	{
1752	LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
1753	// Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
1754	// it should go ahead and immediately dispose of this registration
1755	rr->resrec.RecordType = kDNSRecordTypeShared;
1756	rr->RequireGoodbye    = mDNSfalse;
1757	rr->WakeUp.HMAC       = zeroEthAddr;
1758	if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1759	mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);		// Don't touch rr after this
1760	}
1761
1762// DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
1763// any deregistering records that remain in the m->ResourceRecords list.
1764// DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
1765// which may change the record list and/or question list.
1766// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1767mDNSlocal void DiscardDeregistrations(mDNS *const m)
1768	{
1769	if (m->CurrentRecord)
1770		LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
1771	m->CurrentRecord = m->ResourceRecords;
1772
1773	while (m->CurrentRecord)
1774		{
1775		AuthRecord *rr = m->CurrentRecord;
1776		if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1777			CompleteDeregistration(m, rr);		// Don't touch rr after this
1778		else
1779			m->CurrentRecord = rr->next;
1780		}
1781	}
1782
1783mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
1784	{
1785	int i, val = 0;
1786	if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
1787	for (i=1; i<=src[0]; i++)
1788		{
1789		if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
1790		val = val * 10 + src[i] - '0';
1791		}
1792	if (val > 255) return(mStatus_Invalid);
1793	*dst = (mDNSu8)val;
1794	return(mStatus_NoError);
1795	}
1796
1797mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
1798	{
1799	int skip = CountLabels(name) - 6;
1800	if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
1801	if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
1802		GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
1803		GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
1804		GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
1805	a->type = mDNSAddrType_IPv4;
1806	return(mStatus_NoError);
1807	}
1808
1809#define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :   \
1810					((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :   \
1811					((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
1812
1813mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
1814	{
1815	int i, h, l;
1816	const domainname *n;
1817
1818	int skip = CountLabels(name) - 34;
1819	if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
1820
1821	n = SkipLeadingLabels(name, skip);
1822	for (i=0; i<16; i++)
1823		{
1824		if (n->c[0] != 1) return mStatus_Invalid;
1825		l = HexVal(n->c[1]);
1826		n = (const domainname *)(n->c + 2);
1827
1828		if (n->c[0] != 1) return mStatus_Invalid;
1829		h = HexVal(n->c[1]);
1830		n = (const domainname *)(n->c + 2);
1831
1832		if (l<0 || h<0) return mStatus_Invalid;
1833		a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
1834		}
1835
1836	a->type = mDNSAddrType_IPv6;
1837	return(mStatus_NoError);
1838	}
1839
1840mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
1841	{
1842	int skip = CountLabels(name) - 2;
1843	if (skip >= 0)
1844		{
1845		const domainname *suffix = SkipLeadingLabels(name, skip);
1846		if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
1847		if (SameDomainName(suffix, (const domainname*)"\x3" "ip6"     "\x4" "arpa")) return mDNSAddrType_IPv6;
1848		}
1849	return(mDNSAddrType_None);
1850	}
1851
1852mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
1853	const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
1854	{
1855	int i;
1856	mDNSu8 *ptr = m->omsg.data;
1857	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1858	if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1859
1860	// 0x00 Destination address
1861	for (i=0; i<6; i++) *ptr++ = dst->b[i];
1862
1863	// 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1864	for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
1865
1866	// 0x0C ARP Ethertype (0x0806)
1867	*ptr++ = 0x08; *ptr++ = 0x06;
1868
1869	// 0x0E ARP header
1870	*ptr++ = 0x00; *ptr++ = 0x01;	// Hardware address space; Ethernet = 1
1871	*ptr++ = 0x08; *ptr++ = 0x00;	// Protocol address space; IP = 0x0800
1872	*ptr++ = 6;						// Hardware address length
1873	*ptr++ = 4;						// Protocol address length
1874	*ptr++ = 0x00; *ptr++ = op;		// opcode; Request = 1, Response = 2
1875
1876	// 0x16 Sender hardware address (our MAC address)
1877	for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
1878
1879	// 0x1C Sender protocol address
1880	for (i=0; i<4; i++) *ptr++ = spa->b[i];
1881
1882	// 0x20 Target hardware address
1883	for (i=0; i<6; i++) *ptr++ = tha->b[i];
1884
1885	// 0x26 Target protocol address
1886	for (i=0; i<4; i++) *ptr++ = tpa->b[i];
1887
1888	// 0x2A Total ARP Packet length 42 bytes
1889	mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
1890	}
1891
1892mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
1893	{
1894	const mDNSu16 *ptr = data;
1895	while (length > 0) { length -= 2; sum += *ptr++; }
1896	sum = (sum & 0xFFFF) + (sum >> 16);
1897	sum = (sum & 0xFFFF) + (sum >> 16);
1898	return(sum != 0xFFFF ? sum : 0);
1899	}
1900
1901mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
1902	{
1903	IPv6PseudoHeader ph;
1904	ph.src = *src;
1905	ph.dst = *dst;
1906	ph.len.b[0] = length >> 24;
1907	ph.len.b[1] = length >> 16;
1908	ph.len.b[2] = length >> 8;
1909	ph.len.b[3] = length;
1910	ph.pro.b[0] = 0;
1911	ph.pro.b[1] = 0;
1912	ph.pro.b[2] = 0;
1913	ph.pro.b[3] = protocol;
1914	return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
1915	}
1916
1917mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
1918	const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
1919	{
1920	int i;
1921	mDNSOpaque16 checksum;
1922	mDNSu8 *ptr = m->omsg.data;
1923	// Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
1924	// appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
1925	// at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
1926	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] } };
1927	const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
1928	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1929	if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1930
1931	// 0x00 Destination address
1932	for (i=0; i<6; i++) *ptr++ = dst->b[i];
1933	// Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
1934	// Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
1935	// link with a pointless link-layer multicast.
1936	// Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
1937	// Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
1938	// *ptr++ = 0x33;
1939	// *ptr++ = 0x33;
1940	// *ptr++ = 0xFF;
1941	// *ptr++ = tpa->b[0xD];
1942	// *ptr++ = tpa->b[0xE];
1943	// *ptr++ = tpa->b[0xF];
1944
1945	// 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1946	for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1947
1948	// 0x0C IPv6 Ethertype (0x86DD)
1949	*ptr++ = 0x86; *ptr++ = 0xDD;
1950
1951	// 0x0E IPv6 header
1952	*ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;		// Version, Traffic Class, Flow Label
1953	*ptr++ = 0x00; *ptr++ = 0x20;									// Length
1954	*ptr++ = 0x3A;													// Protocol == ICMPv6
1955	*ptr++ = 0xFF;													// Hop Limit
1956
1957	// 0x16 Sender IPv6 address
1958	for (i=0; i<16; i++) *ptr++ = spa->b[i];
1959
1960	// 0x26 Destination IPv6 address
1961	for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
1962
1963	// 0x36 NDP header
1964	*ptr++ = op;					// 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
1965	*ptr++ = 0x00;					// Code
1966	*ptr++ = 0x00; *ptr++ = 0x00;	// Checksum placeholder (0x38, 0x39)
1967	*ptr++ = flags;
1968	*ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
1969
1970	if (op == NDP_Sol)	// Neighbor Solicitation. The NDP "target" is the address we seek.
1971		{
1972		// 0x3E NDP target.
1973		for (i=0; i<16; i++) *ptr++ = tpa->b[i];
1974		// 0x4E Source Link-layer Address
1975		// <http://www.ietf.org/rfc/rfc2461.txt>
1976		// MUST NOT be included when the source IP address is the unspecified address.
1977		// Otherwise, on link layers that have addresses this option MUST be included
1978		// in multicast solicitations and SHOULD be included in unicast solicitations.
1979		if (!mDNSIPv6AddressIsZero(*spa))
1980			{
1981			*ptr++ = NDP_SrcLL;	// Option Type 1 == Source Link-layer Address
1982			*ptr++ = 0x01;		// Option length 1 (in units of 8 octets)
1983			for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1984			}
1985		}
1986	else			// Neighbor Advertisement. The NDP "target" is the address we're giving information about.
1987		{
1988		// 0x3E NDP target.
1989		for (i=0; i<16; i++) *ptr++ = spa->b[i];
1990		// 0x4E Target Link-layer Address
1991		*ptr++ = NDP_TgtLL;	// Option Type 2 == Target Link-layer Address
1992		*ptr++ = 0x01;		// Option length 1 (in units of 8 octets)
1993		for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1994		}
1995
1996	// 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
1997	m->omsg.data[0x13] = ptr - &m->omsg.data[0x36];		// Compute actual length
1998	checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
1999	m->omsg.data[0x38] = checksum.b[0];
2000	m->omsg.data[0x39] = checksum.b[1];
2001
2002	mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2003	}
2004
2005mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2006	{
2007	owner->u.owner.vers     = 0;
2008	owner->u.owner.seq      = m->SleepSeqNum;
2009	owner->u.owner.HMAC     = m->PrimaryMAC;
2010	owner->u.owner.IMAC     = intf->MAC;
2011	owner->u.owner.password = zeroEthAddr;
2012
2013	// Don't try to compute the optlen until *after* we've set up the data fields
2014	// 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
2015	owner->opt              = kDNSOpt_Owner;
2016	owner->optlen           = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2017	}
2018
2019mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2020	{
2021	if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2022	else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2023	}
2024
2025// Note about acceleration of announcements to facilitate automatic coalescing of
2026// multiple independent threads of announcements into a single synchronized thread:
2027// The announcements in the packet may be at different stages of maturity;
2028// One-second interval, two-second interval, four-second interval, and so on.
2029// After we've put in all the announcements that are due, we then consider
2030// whether there are other nearly-due announcements that are worth accelerating.
2031// To be eligible for acceleration, a record MUST NOT be older (further along
2032// its timeline) than the most mature record we've already put in the packet.
2033// In other words, younger records can have their timelines accelerated to catch up
2034// with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2035// Older records cannot have their timelines accelerated; this would just widen
2036// the gap between them and their younger bretheren and get them even more out of sync.
2037
2038// Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2039// the record list and/or question list.
2040// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2041mDNSlocal void SendResponses(mDNS *const m)
2042	{
2043	int pktcount = 0;
2044	AuthRecord *rr, *r2;
2045	mDNSs32 maxExistingAnnounceInterval = 0;
2046	const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2047
2048	m->NextScheduledResponse = m->timenow + 0x78000000;
2049
2050	if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2051
2052	for (rr = m->ResourceRecords; rr; rr=rr->next)
2053		if (rr->ImmedUnicast)
2054			{
2055			mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2056			mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2057			v4.ip.v4 = rr->v4Requester;
2058			v6.ip.v6 = rr->v6Requester;
2059			if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2060			if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2061			if (rr->ImmedUnicast)
2062				{
2063				LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2064				rr->ImmedUnicast = mDNSfalse;
2065				}
2066			}
2067
2068	// ***
2069	// *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2070	// ***
2071
2072	// Run through our list of records, and decide which ones we're going to announce on all interfaces
2073	for (rr = m->ResourceRecords; rr; rr=rr->next)
2074		{
2075		while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2076		if (TimeToAnnounceThisRecord(rr, m->timenow))
2077			{
2078			if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2079				{
2080				if (!rr->WakeUp.HMAC.l[0])
2081					{
2082					if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark;		// Send goodbye packet on all interfaces
2083					}
2084				else
2085					{
2086					LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2087					SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
2088					for (r2 = rr; r2; r2=r2->next)
2089						if (r2->AnnounceCount && r2->resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC))
2090							{
2091							// For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2092							// owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2093							if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2094								{
2095								LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2096									r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2097								SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2098								}
2099							r2->LastAPTime = m->timenow;
2100							// After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2101							if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2102							}
2103					}
2104				}
2105			else if (ResourceRecordIsValidAnswer(rr))
2106				{
2107				if (rr->AddressProxy.type)
2108					{
2109					rr->AnnounceCount--;
2110					rr->ThisAPInterval *= 2;
2111					rr->LastAPTime = m->timenow;
2112					if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2113						{
2114						LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2115							rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2116						SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2117						}
2118					else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2119						{
2120						LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2121							rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2122						SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2123						}
2124					}
2125				else
2126					{
2127					rr->ImmedAnswer = mDNSInterfaceMark;		// Send on all interfaces
2128					if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2129						maxExistingAnnounceInterval = rr->ThisAPInterval;
2130					if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2131					}
2132				}
2133			}
2134		}
2135
2136	// Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2137	// Eligible records that are more than half-way to their announcement time are accelerated
2138	for (rr = m->ResourceRecords; rr; rr=rr->next)
2139		if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2140			(rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2141			TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2142			!rr->AddressProxy.type && 					// Don't include ARP Annoucements when considering which records to accelerate
2143			ResourceRecordIsValidAnswer(rr)))
2144			rr->ImmedAnswer = mDNSInterfaceMark;		// Send on all interfaces
2145
2146	// When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2147	// Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2148	// which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2149	// then all that means is that it won't get sent -- which would not be the end of the world.
2150	for (rr = m->ResourceRecords; rr; rr=rr->next)
2151		{
2152		if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2153			for (r2=m->ResourceRecords; r2; r2=r2->next)				// Scan list of resource records
2154				if (RRTypeIsAddressType(r2->resrec.rrtype) &&			// For all address records (A/AAAA) ...
2155					ResourceRecordIsValidAnswer(r2) &&					// ... which are valid for answer ...
2156					rr->LastMCTime - r2->LastMCTime >= 0 &&				// ... which we have not sent recently ...
2157					rr->resrec.rdatahash == r2->resrec.namehash &&		// ... whose name is the name of the SRV target
2158					SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2159					(rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2160					r2->ImmedAdditional = r2->resrec.InterfaceID;		// ... then mark this address record for sending too
2161		// We also make sure we send the DeviceInfo TXT record too, if necessary
2162		// We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2163		// DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2164		if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2165			if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2166				{
2167				if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2168				else                            m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2169				}
2170		}
2171
2172	// If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2173	// the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2174	// then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2175	// record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2176	// -- 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
2177	// -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2178	for (rr = m->ResourceRecords; rr; rr=rr->next)
2179		if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2180			{
2181			if (rr->ImmedAnswer)			// If we're sending this as answer, see that its whole RRSet is similarly marked
2182				{
2183				for (r2 = m->ResourceRecords; r2; r2=r2->next)
2184					if (ResourceRecordIsValidAnswer(r2))
2185						if (r2->ImmedAnswer != mDNSInterfaceMark &&
2186							r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(r2, rr))
2187							r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2188				}
2189			else if (rr->ImmedAdditional)	// If we're sending this as additional, see that its whole RRSet is similarly marked
2190				{
2191				for (r2 = m->ResourceRecords; r2; r2=r2->next)
2192					if (ResourceRecordIsValidAnswer(r2))
2193						if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(r2, rr))
2194							r2->ImmedAdditional = rr->ImmedAdditional;
2195				}
2196			}
2197
2198	// Now set SendRNow state appropriately
2199	for (rr = m->ResourceRecords; rr; rr=rr->next)
2200		{
2201		if (rr->ImmedAnswer == mDNSInterfaceMark)		// Sending this record on all appropriate interfaces
2202			{
2203			rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2204			rr->ImmedAdditional = mDNSNULL;				// No need to send as additional if sending as answer
2205			rr->LastMCTime      = m->timenow;
2206			rr->LastMCInterface = rr->ImmedAnswer;
2207			// If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2208			if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2209				{
2210				rr->AnnounceCount--;
2211				if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2212					rr->ThisAPInterval *= 2;
2213				rr->LastAPTime = m->timenow;
2214				debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2215				}
2216			}
2217		else if (rr->ImmedAnswer)						// Else, just respond to a single query on single interface:
2218			{
2219			rr->SendRNow        = rr->ImmedAnswer;		// Just respond on that interface
2220			rr->ImmedAdditional = mDNSNULL;				// No need to send as additional too
2221			rr->LastMCTime      = m->timenow;
2222			rr->LastMCInterface = rr->ImmedAnswer;
2223			}
2224		SetNextAnnounceProbeTime(m, rr);
2225		//if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2226		}
2227
2228	// ***
2229	// *** 2. Loop through interface list, sending records as appropriate
2230	// ***
2231
2232	while (intf)
2233		{
2234		const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2235		int numDereg    = 0;
2236		int numAnnounce = 0;
2237		int numAnswer   = 0;
2238		mDNSu8 *responseptr = m->omsg.data;
2239		mDNSu8 *newptr;
2240		InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2241
2242		// First Pass. Look for:
2243		// 1. Deregistering records that need to send their goodbye packet
2244		// 2. Updated records that need to retract their old data
2245		// 3. Answers and announcements we need to send
2246		for (rr = m->ResourceRecords; rr; rr=rr->next)
2247			{
2248
2249			// Skip this interface if the record InterfaceID is *Any and the record is not
2250			// appropriate for the interface type.
2251			if ((rr->SendRNow == intf->InterfaceID) &&
2252				((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf)))
2253				{
2254					LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
2255					rr->SendRNow = GetNextActiveInterfaceID(intf);
2256				}
2257			else if (rr->SendRNow == intf->InterfaceID)
2258				{
2259				RData  *OldRData    = rr->resrec.rdata;
2260				mDNSu16 oldrdlength = rr->resrec.rdlength;
2261				mDNSu8 active = (mDNSu8)
2262					(rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
2263					(m->SleepState != SleepState_Sleeping || intf->SPSAddr[0].type || intf->SPSAddr[1].type || intf->SPSAddr[2].type));
2264				newptr = mDNSNULL;
2265				if (rr->NewRData && active)
2266					{
2267					// See if we should send a courtesy "goodbye" for the old data before we replace it.
2268					if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2269						{
2270						newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2271						if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2272						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
2273						}
2274					SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2275					}
2276
2277				if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2278					rr->resrec.rrclass |= kDNSClass_UniqueRRSet;		// Temporarily set the cache flush bit so PutResourceRecord will set it
2279				newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2280				rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;			// Make sure to clear cache flush bit back to normal state
2281				if (newptr)
2282					{
2283					responseptr = newptr;
2284					rr->RequireGoodbye = active;
2285					if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2286					else if (rr->LastAPTime == m->timenow) numAnnounce++; else numAnswer++;
2287					}
2288
2289				if (rr->NewRData && active)
2290					SetNewRData(&rr->resrec, OldRData, oldrdlength);
2291
2292				// The first time through (pktcount==0), if this record is verified unique
2293				// (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2294				if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2295					rr->SendNSECNow = mDNSInterfaceMark;
2296
2297				if (newptr)		// If succeeded in sending, advance to next interface
2298					{
2299					// If sending on all interfaces, go to next interface; else we're finished now
2300					if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2301						rr->SendRNow = GetNextActiveInterfaceID(intf);
2302					else
2303						rr->SendRNow = mDNSNULL;
2304					}
2305				}
2306			}
2307
2308		// Second Pass. Add additional records, if there's space.
2309		newptr = responseptr;
2310		for (rr = m->ResourceRecords; rr; rr=rr->next)
2311			if (rr->ImmedAdditional == intf->InterfaceID)
2312				if (ResourceRecordIsValidAnswer(rr))
2313					{
2314					// If we have at least one answer already in the packet, then plan to add additionals too
2315					mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2316
2317					// If we're not planning to send any additionals, but this record is a unique one, then
2318					// make sure we haven't already sent any other members of its RRSet -- if we have, then they
2319					// will have had the cache flush bit set, so now we need to finish the job and send the rest.
2320					if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2321						{
2322						const AuthRecord *a;
2323						for (a = m->ResourceRecords; a; a=a->next)
2324							if (a->LastMCTime      == m->timenow &&
2325								a->LastMCInterface == intf->InterfaceID &&
2326								SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2327						}
2328					if (!SendAdditional)					// If we don't want to send this after all,
2329						rr->ImmedAdditional = mDNSNULL;		// then cancel its ImmedAdditional field
2330					else if (newptr)						// Else, try to add it if we can
2331						{
2332						// The first time through (pktcount==0), if this record is verified unique
2333						// (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2334						if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2335							rr->SendNSECNow = mDNSInterfaceMark;
2336
2337						if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2338							rr->resrec.rrclass |= kDNSClass_UniqueRRSet;	// Temporarily set the cache flush bit so PutResourceRecord will set it
2339						newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2340						rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;		// Make sure to clear cache flush bit back to normal state
2341						if (newptr)
2342							{
2343							responseptr = newptr;
2344							rr->ImmedAdditional = mDNSNULL;
2345							rr->RequireGoodbye = mDNStrue;
2346							// If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2347							// This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2348							// when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2349							// all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2350							rr->LastMCTime      = m->timenow;
2351							rr->LastMCInterface = intf->InterfaceID;
2352							}
2353						}
2354					}
2355
2356		// Third Pass. Add NSEC records, if there's space.
2357		// When we're generating an NSEC record in response to a specify query for that type
2358		// (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2359		// not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2360		for (rr = m->ResourceRecords; rr; rr=rr->next)
2361			if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2362				{
2363				AuthRecord nsec;
2364				mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2365				nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2366				AssignDomainName(&nsec.namestorage, rr->resrec.name);
2367				mDNSPlatformMemZero(nsec.rdatastorage.u.nsec.bitmap, sizeof(nsec.rdatastorage.u.nsec.bitmap));
2368				for (r2 = m->ResourceRecords; r2; r2=r2->next)
2369					if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2370						{
2371						if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2372						else nsec.rdatastorage.u.nsec.bitmap[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2373						}
2374				newptr = responseptr;
2375				if (!r2)	// If we successfully built our NSEC record, add it to the packet now
2376					{
2377					newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2378					if (newptr) responseptr = newptr;
2379					}
2380
2381				// If we successfully put the NSEC record, clear the SendNSECNow flag
2382				// If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2383				if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2384					{
2385					rr->SendNSECNow = mDNSNULL;
2386					// Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2387					for (r2 = rr->next; r2; r2=r2->next)
2388						if (SameResourceRecordNameClassInterface(r2, rr))
2389							if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2390								r2->SendNSECNow = mDNSNULL;
2391					}
2392				}
2393
2394		if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2395			{
2396			// If we have data to send, add OWNER option if necessary, then send packet
2397
2398			if (OwnerRecordSpace)
2399				{
2400				AuthRecord opt;
2401				mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2402				opt.resrec.rrclass    = NormalMaxDNSMessageData;
2403				opt.resrec.rdlength   = sizeof(rdataOPT);	// One option in this OPT record
2404				opt.resrec.rdestimate = sizeof(rdataOPT);
2405				SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2406				newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2407				if (newptr) { responseptr = newptr; LogSPS("SendResponses put   %s", ARDisplayString(m, &opt)); }
2408				else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2409					LogSPS("SendResponses: No space in packet for Owner OPT record (%d/%d/%d/%d) %s",
2410						m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2411				else
2412					LogMsg("SendResponses: How did we fail to have space for Owner OPT record (%d/%d/%d/%d) %s",
2413						m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2414				}
2415
2416			debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2417				numDereg,                 numDereg                 == 1 ? "" : "s",
2418				numAnnounce,              numAnnounce              == 1 ? "" : "s",
2419				numAnswer,                numAnswer                == 1 ? "" : "s",
2420				m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2421
2422			if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
2423			if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
2424			if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2425			if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
2426			// There might be more things to send on this interface, so go around one more time and try again.
2427			}
2428		else	// Nothing more to send on this interface; go to next
2429			{
2430			const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
2431			#if MDNS_DEBUGMSGS && 0
2432			const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2433			debugf(msg, intf, next);
2434			#endif
2435			intf = next;
2436			pktcount = 0;		// When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2437			}
2438		}
2439
2440	// ***
2441	// *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2442	// ***
2443
2444	if (m->CurrentRecord)
2445		LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2446	m->CurrentRecord = m->ResourceRecords;
2447	while (m->CurrentRecord)
2448		{
2449		rr = m->CurrentRecord;
2450		m->CurrentRecord = rr->next;
2451
2452		if (rr->SendRNow)
2453			{
2454			if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
2455				LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr->SendRNow, rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
2456			rr->SendRNow = mDNSNULL;
2457			}
2458
2459		if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2460			{
2461			if (rr->NewRData) CompleteRDataUpdate(m, rr);	// Update our rdata, clear the NewRData pointer, and return memory to the client
2462
2463			if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
2464				{
2465				// For Unicast, when we get the response from the server, we will call CompleteDeregistration
2466				if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr);		// Don't touch rr after this
2467				}
2468			else
2469				{
2470				rr->ImmedAnswer  = mDNSNULL;
2471				rr->ImmedUnicast = mDNSfalse;
2472				rr->v4Requester  = zerov4Addr;
2473				rr->v6Requester  = zerov6Addr;
2474				}
2475			}
2476		}
2477	verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
2478	}
2479
2480// Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2481// so we want to be lazy about how frequently we do it.
2482// 1. If a cache record is currently referenced by *no* active questions,
2483//    then we don't mind expiring it up to a minute late (who will know?)
2484// 2. Else, if a cache record is due for some of its final expiration queries,
2485//    we'll allow them to be late by up to 2% of the TTL
2486// 3. Else, if a cache record has completed all its final expiration queries without success,
2487//    and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2488// 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2489//    so allow at most 1/10 second lateness
2490// 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2491//    (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2492#define CacheCheckGracePeriod(RR) (                                                   \
2493	((RR)->CRActiveQuestion == mDNSNULL            ) ? (60 * mDNSPlatformOneSecond) : \
2494	((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50)            : \
2495	((RR)->resrec.rroriginalttl > 10               ) ? (mDNSPlatformOneSecond)      : \
2496	((RR)->resrec.rroriginalttl > 0                ) ? (mDNSPlatformOneSecond/10)   : 0)
2497
2498#define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2499
2500mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
2501	{
2502	if (m->rrcache_nextcheck[slot] - event > 0)
2503		m->rrcache_nextcheck[slot] = event;
2504	if (m->NextCacheCheck          - event > 0)
2505		m->NextCacheCheck          = event;
2506	}
2507
2508// Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2509// rr->TimeRcvd
2510// rr->resrec.rroriginalttl
2511// rr->UnansweredQueries
2512// rr->CRActiveQuestion
2513mDNSlocal void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
2514	{
2515	rr->NextRequiredQuery = RRExpireTime(rr);
2516
2517	// If we have an active question, then see if we want to schedule a refresher query for this record.
2518	// Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2519	if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
2520		{
2521		rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
2522		rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
2523		verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2524			(rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
2525		}
2526
2527	ScheduleNextCacheCheckTime(m, HashSlot(rr->resrec.name), NextCacheCheckEvent(rr));
2528	}
2529
2530#define kMinimumReconfirmTime                     ((mDNSu32)mDNSPlatformOneSecond *  5)
2531#define kDefaultReconfirmTimeForWake              ((mDNSu32)mDNSPlatformOneSecond *  5)
2532#define kDefaultReconfirmTimeForNoAnswer          ((mDNSu32)mDNSPlatformOneSecond *  5)
2533#define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 30)
2534
2535mDNSlocal mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
2536	{
2537	if (interval < kMinimumReconfirmTime)
2538		interval = kMinimumReconfirmTime;
2539	if (interval > 0x10000000)	// Make sure interval doesn't overflow when we multiply by four below
2540		interval = 0x10000000;
2541
2542	// If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2543	if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
2544		{
2545		// Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2546		// For all the reconfirmations in a given batch, we want to use the same random value
2547		// so that the reconfirmation questions can be grouped into a single query packet
2548		if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(0x3FFFFFFF);
2549		interval += m->RandomReconfirmDelay % ((interval/3) + 1);
2550		rr->TimeRcvd          = m->timenow - (mDNSs32)interval * 3;
2551		rr->resrec.rroriginalttl     = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
2552		SetNextCacheCheckTimeForRecord(m, rr);
2553		}
2554	debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2555		RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
2556	return(mStatus_NoError);
2557	}
2558
2559#define MaxQuestionInterval         (3600 * mDNSPlatformOneSecond)
2560
2561// BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2562// It also appends to the list of known answer records that need to be included,
2563// and updates the forcast for the size of the known answer section.
2564mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
2565	CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
2566	{
2567	mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353;
2568	mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2569	const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
2570	mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
2571	if (!newptr)
2572		{
2573		debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2574		return(mDNSfalse);
2575		}
2576	else
2577		{
2578		mDNSu32 forecast = *answerforecast;
2579		const mDNSu32 slot = HashSlot(&q->qname);
2580		const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2581		CacheRecord *rr;
2582		CacheRecord **ka = *kalistptrptr;	// Make a working copy of the pointer we're going to update
2583
2584		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)				// If we have a resource record in our cache,
2585			if (rr->resrec.InterfaceID == q->SendQNow &&					// received on this interface
2586				!(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) &&		// which is a shared (i.e. not unique) record type
2587				rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList &&	// which is not already in the known answer list
2588				rr->resrec.rdlength <= SmallRecordLimit &&					// which is small enough to sensibly fit in the packet
2589				SameNameRecordAnswersQuestion(&rr->resrec, q) &&			// which answers our question
2590				rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >				// and its half-way-to-expiry time is at least 1 second away
2591												mDNSPlatformOneSecond)		// (also ensures we never include goodbye records with TTL=1)
2592				{
2593				// We don't want to include unique records in the Known Answer section. The Known Answer section
2594				// is intended to suppress floods of shared-record replies from many other devices on the network.
2595				// That concept really does not apply to unique records, and indeed if we do send a query for
2596				// which we have a unique record already in our cache, then including that unique record as a
2597				// Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2598
2599				*ka = rr;	// Link this record into our known answer chain
2600				ka = &rr->NextInKAList;
2601				// We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2602				forecast += 12 + rr->resrec.rdestimate;
2603				// If we're trying to put more than one question in this packet, and it doesn't fit
2604				// then undo that last question and try again next time
2605				if (query->h.numQuestions > 1 && newptr + forecast >= limit)
2606					{
2607					debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
2608						q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data);
2609					query->h.numQuestions--;
2610					ka = *kalistptrptr;		// Go back to where we started and retract these answer records
2611					while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
2612					return(mDNSfalse);		// Return false, so we'll try again in the next packet
2613					}
2614				}
2615
2616		// Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2617		*queryptr        = newptr;				// Update the packet pointer
2618		*answerforecast  = forecast;			// Update the forecast
2619		*kalistptrptr    = ka;					// Update the known answer list pointer
2620		if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
2621
2622		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)				// For every resource record in our cache,
2623			if (rr->resrec.InterfaceID == q->SendQNow &&					// received on this interface
2624				rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList &&	// which is not in the known answer list
2625				SameNameRecordAnswersQuestion(&rr->resrec, q))				// which answers our question
2626					{
2627					rr->UnansweredQueries++;								// indicate that we're expecting a response
2628					rr->LastUnansweredTime = m->timenow;
2629					SetNextCacheCheckTimeForRecord(m, rr);
2630					}
2631
2632		return(mDNStrue);
2633		}
2634	}
2635
2636// When we have a query looking for a specified name, but there appear to be no answers with
2637// that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
2638// for any records in our cache that reference the given name (e.g. PTR and SRV records).
2639// For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
2640// We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
2641// A typical reconfirmation scenario might go like this:
2642// Depth 0: Name "myhost.local" has no address records
2643// Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
2644// Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
2645// Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
2646// Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
2647// found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
2648mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
2649	{
2650	mDNSu32 slot;
2651	CacheGroup *cg;
2652	CacheRecord *cr;
2653	debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
2654	FORALL_CACHERECORDS(slot, cg, cr)
2655		{
2656		domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
2657		if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
2658			{
2659			LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
2660			mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
2661			if (depth < 5) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
2662			}
2663		}
2664	}
2665
2666// If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
2667// we check if we have an address record for the same name. If we do have an IPv4 address for a given
2668// name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
2669// to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
2670mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
2671	{
2672	CacheGroup *const cg = CacheGroupForName(m, HashSlot(name), namehash, name);
2673	const CacheRecord *cr = cg ? cg->members : mDNSNULL;
2674	while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
2675	return(cr);
2676	}
2677
2678mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
2679	{
2680	CacheGroup *const cg = CacheGroupForName(m, HashSlot(&q->qname), q->qnamehash, &q->qname);
2681	const CacheRecord *cr, *bestcr = mDNSNULL;
2682	mDNSu32 bestmetric = 1000000;
2683	for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
2684		if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6)						// If record is PTR type, with long enough name,
2685			if (cr != c0 && cr != c1)															// that's not one we've seen before,
2686				if (SameNameRecordAnswersQuestion(&cr->resrec, q))								// and answers our browse query,
2687					if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec))	// and is not our own advertised service...
2688						{
2689						mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
2690						if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
2691						}
2692	return(bestcr);
2693	}
2694
2695// Finds the three best Sleep Proxies we currently have in our cache
2696mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
2697	{
2698	sps[0] =                      FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
2699	sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   mDNSNULL);
2700	sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   sps[1]);
2701	}
2702
2703// Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
2704mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
2705	{
2706	int i;
2707	for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2708	}
2709
2710mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
2711	{
2712	int i;
2713	for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2714	}
2715
2716mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
2717	{
2718	int i;
2719	mDNSBool v4 = !intf->IPv4Available;		// If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
2720	mDNSBool v6 = !intf->IPv6Available;		// If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
2721	for (i=0; i<DupSuppressInfoSize; i++)
2722		if (ds[i].InterfaceID == intf->InterfaceID)
2723			{
2724			if      (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
2725			else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
2726			if (v4 && v6) return(mDNStrue);
2727			}
2728	return(mDNSfalse);
2729	}
2730
2731mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
2732	{
2733	int i, j;
2734
2735	// See if we have this one in our list somewhere already
2736	for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
2737
2738	// If not, find a slot we can re-use
2739	if (i >= DupSuppressInfoSize)
2740		{
2741		i = 0;
2742		for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
2743			if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
2744				i = j;
2745		}
2746
2747	// Record the info about this query we saw
2748	ds[i].Time        = Time;
2749	ds[i].InterfaceID = InterfaceID;
2750	ds[i].Type        = Type;
2751
2752	return(i);
2753	}
2754
2755mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
2756	{
2757	int len, i, cnt;
2758	mDNSInterfaceID InterfaceID = q->InterfaceID;
2759	domainname *d = &q->qname;
2760
2761	// We can't send magic packets without knowing which interface to send it on.
2762	if (InterfaceID == mDNSInterface_Any || InterfaceID == mDNSInterface_LocalOnly || InterfaceID == mDNSInterface_P2P)
2763		{
2764		LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
2765		return;
2766		}
2767
2768	// Split MAC@IPAddress and pass them separately
2769	len = d->c[0];
2770	i = 1;
2771	cnt = 0;
2772	for (i = 1; i < len; i++)
2773		{
2774		if (d->c[i] == '@')
2775			{
2776			char EthAddr[18];	// ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
2777			char IPAddr[47];    // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
2778			if (cnt != 5)
2779				{
2780				LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
2781				return;
2782				}
2783			if ((i - 1) > (int) (sizeof(EthAddr) - 1))
2784				{
2785				LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
2786				return;
2787				}
2788			if ((len - i) > (int)(sizeof(IPAddr) - 1))
2789				{
2790				LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
2791				return;
2792				}
2793			mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
2794			EthAddr[i - 1] = 0;
2795			mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
2796			IPAddr[len - i] = 0;
2797			mDNSPlatformSendWakeupPacket(m, InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
2798			return;
2799			}
2800		else if (d->c[i] == ':')
2801			cnt++;
2802		}
2803	LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
2804	}
2805
2806
2807mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
2808	{
2809	// If more than 90% of the way to the query time, we should unconditionally accelerate it
2810	if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
2811		return(mDNStrue);
2812
2813	// If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
2814	if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
2815		{
2816		// We forecast: qname (n) type (2) class (2)
2817		mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
2818		const mDNSu32 slot = HashSlot(&q->qname);
2819		const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2820		const CacheRecord *rr;
2821		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)				// If we have a resource record in our cache,
2822			if (rr->resrec.rdlength <= SmallRecordLimit &&					// which is small enough to sensibly fit in the packet
2823				SameNameRecordAnswersQuestion(&rr->resrec, q) &&			// which answers our question
2824				rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 &&			// and it is less than half-way to expiry
2825				rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0)// and we'll ask at least once again before NextRequiredQuery
2826				{
2827				// We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2828				forecast += 12 + rr->resrec.rdestimate;
2829				if (forecast >= 512) return(mDNSfalse);	// If this would add 512 bytes or more to the packet, don't accelerate
2830				}
2831		return(mDNStrue);
2832		}
2833
2834	return(mDNSfalse);
2835	}
2836
2837// How Standard Queries are generated:
2838// 1. The Question Section contains the question
2839// 2. The Additional Section contains answers we already know, to suppress duplicate responses
2840
2841// How Probe Queries are generated:
2842// 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
2843// if some other host is already using *any* records with this name, we want to know about it.
2844// 2. The Authority Section contains the proposed values we intend to use for one or more
2845// of our records with that name (analogous to the Update section of DNS Update packets)
2846// because if some other host is probing at the same time, we each want to know what the other is
2847// planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
2848
2849mDNSlocal void SendQueries(mDNS *const m)
2850	{
2851	mDNSu32 slot;
2852	CacheGroup *cg;
2853	CacheRecord *cr;
2854	AuthRecord *ar;
2855	int pktcount = 0;
2856	DNSQuestion *q;
2857	// For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
2858	mDNSs32 maxExistingQuestionInterval = 0;
2859	const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2860	CacheRecord *KnownAnswerList = mDNSNULL;
2861
2862	// 1. If time for a query, work out what we need to do
2863
2864	// We're expecting to send a query anyway, so see if any expiring cache records are close enough
2865	// to their NextRequiredQuery to be worth batching them together with this one
2866	FORALL_CACHERECORDS(slot, cg, cr)
2867		if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
2868			if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
2869				{
2870				debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
2871				q = cr->CRActiveQuestion;
2872				ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
2873				// For uDNS queries (TargetQID non-zero) we adjust LastQTime,
2874				// and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
2875				if      (q->Target.type)                        q->SendQNow = mDNSInterfaceMark;	// If targeted query, mark it
2876				else if (!mDNSOpaque16IsZero(q->TargetQID))     { q->LastQTime = m->timenow - q->ThisQInterval; cr->UnansweredQueries++; }
2877				else if (q->SendQNow == mDNSNULL)               q->SendQNow = cr->resrec.InterfaceID;
2878				else if (q->SendQNow != cr->resrec.InterfaceID) q->SendQNow = mDNSInterfaceMark;
2879				}
2880
2881	// Scan our list of questions to see which:
2882	//     *WideArea*  queries need to be sent
2883	//     *unicast*   queries need to be sent
2884	//     *multicast* queries we're definitely going to send
2885	if (m->CurrentQuestion)
2886		LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2887	m->CurrentQuestion = m->Questions;
2888	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
2889		{
2890		q = m->CurrentQuestion;
2891		if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
2892			{
2893			mDNSu8       *qptr        = m->omsg.data;
2894			const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
2895
2896			// 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
2897			if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
2898			if (q->LocalSocket)
2899				{
2900				InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
2901				qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
2902				mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL);
2903				q->ThisQInterval    *= QuestionIntervalStep;
2904				}
2905			if (q->ThisQInterval > MaxQuestionInterval)
2906				q->ThisQInterval = MaxQuestionInterval;
2907			q->LastQTime         = m->timenow;
2908			q->LastQTxTime       = m->timenow;
2909			q->RecentAnswerPkts  = 0;
2910			q->SendQNow          = mDNSNULL;
2911			q->ExpectUnicastResp = NonZeroTime(m->timenow);
2912			}
2913		else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
2914			{
2915			//LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2916			q->SendQNow = mDNSInterfaceMark;		// Mark this question for sending on all interfaces
2917			if (maxExistingQuestionInterval < q->ThisQInterval)
2918				maxExistingQuestionInterval = q->ThisQInterval;
2919			}
2920		// If m->CurrentQuestion wasn't modified out from under us, advance it now
2921		// We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
2922		// m->CurrentQuestion point to the right question
2923		if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
2924		}
2925	while (m->CurrentQuestion)
2926		{
2927		LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2928		m->CurrentQuestion = m->CurrentQuestion->next;
2929		}
2930	m->CurrentQuestion = mDNSNULL;
2931
2932	// Scan our list of questions
2933	// (a) to see if there are any more that are worth accelerating, and
2934	// (b) to update the state variables for *all* the questions we're going to send
2935	// Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
2936	// which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
2937	// 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.
2938	m->NextScheduledQuery = m->timenow + 0x78000000;
2939	for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
2940		{
2941		if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow ||
2942			(!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
2943			{
2944			// If at least halfway to next query time, advance to next interval
2945			// If less than halfway to next query time, then
2946			// treat this as logically a repeat of the last transmission, without advancing the interval
2947			if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
2948				{
2949				//LogInfo("Accelerating %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2950				q->SendQNow = mDNSInterfaceMark;	// Mark this question for sending on all interfaces
2951				debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
2952					q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
2953				q->ThisQInterval *= QuestionIntervalStep;
2954				if (q->ThisQInterval > MaxQuestionInterval)
2955					q->ThisQInterval = MaxQuestionInterval;
2956				else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
2957						!(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
2958					{
2959					// Generally don't need to log this.
2960					// It's not especially noteworthy if a query finds no results -- this usually happens for domain
2961					// enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
2962					// and when there simply happen to be no instances of the service the client is looking
2963					// for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
2964					debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
2965						q->qname.c, DNSTypeName(q->qtype));
2966					// Sending third query, and no answers yet; time to begin doubting the source
2967					ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
2968					}
2969				}
2970
2971			// Mark for sending. (If no active interfaces, then don't even try.)
2972			q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
2973			if (q->SendOnAll)
2974				{
2975				q->SendQNow  = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
2976				q->LastQTime = m->timenow;
2977				}
2978
2979			// If we recorded a duplicate suppression for this question less than half an interval ago,
2980			// then we consider it recent enough that we don't need to do an identical query ourselves.
2981			ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
2982
2983			q->LastQTxTime      = m->timenow;
2984			q->RecentAnswerPkts = 0;
2985			if (q->RequestUnicast) q->RequestUnicast--;
2986			}
2987		// For all questions (not just the ones we're sending) check what the next scheduled event will be
2988		// We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
2989		SetNextQueryTime(m,q);
2990		}
2991
2992	// 2. Scan our authoritative RR list to see what probes we might need to send
2993
2994	m->NextScheduledProbe = m->timenow + 0x78000000;
2995
2996	if (m->CurrentRecord)
2997		LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2998	m->CurrentRecord = m->ResourceRecords;
2999	while (m->CurrentRecord)
3000		{
3001		ar = m->CurrentRecord;
3002		m->CurrentRecord = ar->next;
3003		if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique)	// For all records that are still probing...
3004			{
3005			// 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3006			if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3007				{
3008				SetNextAnnounceProbeTime(m, ar);
3009				}
3010			// 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3011			else if (ar->ProbeCount)
3012				{
3013				if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3014					{
3015					LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3016					SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3017					}
3018				else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3019					{
3020					LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3021					// IPv6 source = zero
3022					// No target hardware address
3023					// IPv6 target address is address we're probing
3024					// Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3025					SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3026					}
3027				// Mark for sending. (If no active interfaces, then don't even try.)
3028				ar->SendRNow   = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3029				ar->LastAPTime = m->timenow;
3030				// When we have a late conflict that resets a record to probing state we use a special marker value greater
3031				// than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3032				if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3033					ar->ProbeCount = DefaultProbeCountForTypeUnique;
3034				ar->ProbeCount--;
3035				SetNextAnnounceProbeTime(m, ar);
3036				if (ar->ProbeCount == 0)
3037					{
3038					// If this is the last probe for this record, then see if we have any matching records
3039					// on our duplicate list which should similarly have their ProbeCount cleared to zero...
3040					AuthRecord *r2;
3041					for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3042						if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3043							r2->ProbeCount = 0;
3044					// ... then acknowledge this record to the client.
3045					// We do this optimistically, just as we're about to send the third probe.
3046					// This helps clients that both advertise and browse, and want to filter themselves
3047					// from the browse results list, because it helps ensure that the registration
3048					// confirmation will be delivered 1/4 second *before* the browse "add" event.
3049					// A potential downside is that we could deliver a registration confirmation and then find out
3050					// moments later that there's a name conflict, but applications have to be prepared to handle
3051					// late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3052					if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3053					}
3054				}
3055			// else, if it has now finished probing, move it to state Verified,
3056			// and update m->NextScheduledResponse so it will be announced
3057			else
3058				{
3059				if (!ar->Acknowledged) AcknowledgeRecord(m, ar);	// Defensive, just in case it got missed somehow
3060				ar->resrec.RecordType     = kDNSRecordTypeVerified;
3061				ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3062				ar->LastAPTime     = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3063				SetNextAnnounceProbeTime(m, ar);
3064				}
3065			}
3066		}
3067	m->CurrentRecord = m->DuplicateRecords;
3068	while (m->CurrentRecord)
3069		{
3070		ar = m->CurrentRecord;
3071		m->CurrentRecord = ar->next;
3072		if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3073			AcknowledgeRecord(m, ar);
3074		}
3075
3076	// 3. Now we know which queries and probes we're sending,
3077	// go through our interface list sending the appropriate queries on each interface
3078	while (intf)
3079		{
3080		const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3081		mDNSu8 *queryptr = m->omsg.data;
3082		InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3083		if (KnownAnswerList) verbosedebugf("SendQueries:   KnownAnswerList set... Will continue from previous packet");
3084		if (!KnownAnswerList)
3085			{
3086			// Start a new known-answer list
3087			CacheRecord **kalistptr = &KnownAnswerList;
3088			mDNSu32 answerforecast = OwnerRecordSpace;		// We start by assuming we'll need at least enough space to put the Owner Option
3089
3090			// Put query questions in this packet
3091			for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3092				{
3093				if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3094					{
3095					debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3096						SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting    ",
3097						q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3098
3099					// If we're suppressing this question, or we successfully put it, update its SendQNow state
3100					if (SuppressOnThisInterface(q->DupSuppress, intf) ||
3101						BuildQuestion(m, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3102						{
3103						q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3104						if (q->WakeOnResolveCount)
3105							{
3106							mDNSSendWakeOnResolve(m, q);
3107							q->WakeOnResolveCount--;
3108							}
3109						}
3110					}
3111				}
3112
3113			// Put probe questions in this packet
3114			for (ar = m->ResourceRecords; ar; ar=ar->next)
3115				if (ar->SendRNow == intf->InterfaceID)
3116					{
3117					mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353;
3118					mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3119					const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3120					// We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3121					mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3122					mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, (mDNSu16)(ar->resrec.rrclass | ucbit));
3123					if (newptr)
3124						{
3125						queryptr       = newptr;
3126						answerforecast = forecast;
3127						ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3128						ar->IncludeInProbe = mDNStrue;
3129						verbosedebugf("SendQueries:   Put Question %##s (%s) probecount %d",
3130							ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount);
3131						}
3132					}
3133			}
3134
3135		// Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3136		while (KnownAnswerList)
3137			{
3138			CacheRecord *ka = KnownAnswerList;
3139			mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3140			mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers,
3141				&ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd, m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace);
3142			if (newptr)
3143				{
3144				verbosedebugf("SendQueries:   Put %##s (%s) at %d - %d",
3145					ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3146				queryptr = newptr;
3147				KnownAnswerList = ka->NextInKAList;
3148				ka->NextInKAList = mDNSNULL;
3149				}
3150			else
3151				{
3152				// If we ran out of space and we have more than one question in the packet, that's an error --
3153				// we shouldn't have put more than one question if there was a risk of us running out of space.
3154				if (m->omsg.h.numQuestions > 1)
3155					LogMsg("SendQueries:   Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3156				m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3157				break;
3158				}
3159			}
3160
3161		for (ar = m->ResourceRecords; ar; ar=ar->next)
3162			if (ar->IncludeInProbe)
3163				{
3164				mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3165				ar->IncludeInProbe = mDNSfalse;
3166				if (newptr) queryptr = newptr;
3167				else LogMsg("SendQueries:   How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3168				}
3169
3170		if (queryptr > m->omsg.data)
3171			{
3172			if (OwnerRecordSpace)
3173				{
3174				AuthRecord opt;
3175				mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3176				opt.resrec.rrclass    = NormalMaxDNSMessageData;
3177				opt.resrec.rdlength   = sizeof(rdataOPT);	// One option in this OPT record
3178				opt.resrec.rdestimate = sizeof(rdataOPT);
3179				SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3180				LogSPS("SendQueries putting %s", ARDisplayString(m, &opt));
3181				queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3182					&opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3183				if (!queryptr)
3184					LogMsg("SendQueries: How did we fail to have space for the OPT record (%d/%d/%d/%d) %s",
3185						m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3186				if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3187					if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3188						LogMsg("SendQueries: Why did we generate oversized packet with OPT record %p %p %p (%d/%d/%d/%d) %s",
3189							m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr,
3190							m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3191				}
3192
3193			if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3194				LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3195			debugf("SendQueries:   Sending %d Question%s %d Answer%s %d Update%s on %p",
3196				m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
3197				m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
3198				m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3199			if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
3200			if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
3201			if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3202			if (++pktcount >= 1000)
3203				{ LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3204			// There might be more records left in the known answer list, or more questions to send
3205			// on this interface, so go around one more time and try again.
3206			}
3207		else	// Nothing more to send on this interface; go to next
3208			{
3209			const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3210			#if MDNS_DEBUGMSGS && 0
3211			const char *const msg = next ? "SendQueries:   Nothing more on %p; moving to %p" : "SendQueries:   Nothing more on %p";
3212			debugf(msg, intf, next);
3213			#endif
3214			intf = next;
3215			}
3216		}
3217
3218	// 4. Final housekeeping
3219
3220	// 4a. Debugging check: Make sure we announced all our records
3221	for (ar = m->ResourceRecords; ar; ar=ar->next)
3222		if (ar->SendRNow)
3223			{
3224			if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
3225				LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar->SendRNow, ar->resrec.InterfaceID, ARDisplayString(m, ar));
3226			ar->SendRNow = mDNSNULL;
3227			}
3228
3229	// 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3230	// that their interface which went away might come back again, the logic will want to send queries
3231	// for those records, but we can't because their interface isn't here any more, so to keep the
3232	// state machine ticking over we just pretend we did so.
3233	// If the interface does not come back in time, the cache record will expire naturally
3234	FORALL_CACHERECORDS(slot, cg, cr)
3235		if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3236			if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3237				{
3238				cr->UnansweredQueries++;
3239				cr->CRActiveQuestion->SendQNow = mDNSNULL;
3240				SetNextCacheCheckTimeForRecord(m, cr);
3241				}
3242
3243	// 4c. Debugging check: Make sure we sent all our planned questions
3244	// Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3245	// we legitimately couldn't send because the interface is no longer available
3246	for (q = m->Questions; q; q=q->next)
3247		if (q->SendQNow)
3248			{
3249			DNSQuestion *x;
3250			for (x = m->NewQuestions; x; x=x->next) if (x == q) break;	// Check if this question is a NewQuestion
3251			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));
3252			q->SendQNow = mDNSNULL;
3253			}
3254	}
3255
3256mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password)
3257	{
3258	int i, j;
3259	mDNSu8 *ptr = m->omsg.data;
3260	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
3261	if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
3262
3263	// 0x00 Destination address
3264	for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3265
3266	// 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
3267	for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
3268
3269	// 0x0C Ethertype (0x0842)
3270	*ptr++ = 0x08;
3271	*ptr++ = 0x42;
3272
3273	// 0x0E Wakeup sync sequence
3274	for (i=0; i<6; i++) *ptr++ = 0xFF;
3275
3276	// 0x14 Wakeup data
3277	for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3278
3279	// 0x74 Password
3280	for (i=0; i<6; i++) *ptr++ = password->b[i];
3281
3282	mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3283
3284	// For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
3285	// broadcast is the only reliable way to get a wakeup packet to the intended target machine.
3286	// For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
3287	// key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
3288	// So, we send one of each, unicast first, then broadcast second.
3289	for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
3290	mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3291	}
3292
3293// ***************************************************************************
3294#if COMPILER_LIKES_PRAGMA_MARK
3295#pragma mark -
3296#pragma mark - RR List Management & Task Management
3297#endif
3298
3299// Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
3300// Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
3301// In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
3302// which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
3303mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
3304	{
3305	DNSQuestion *const q = m->CurrentQuestion;
3306	mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
3307
3308	verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
3309		q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
3310
3311	// Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
3312	// But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
3313	// send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
3314	// we check to see if that query already has a unique local answer.
3315	if (q->LOAddressAnswers)
3316		{
3317		LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
3318			"LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
3319			q->LOAddressAnswers);
3320		return;
3321		}
3322
3323	if (QuerySuppressed(q))
3324		{
3325		// If the query is suppressed, then we don't want to answer from the cache. But if this query is
3326		// supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
3327		// that are timing out, which we know are answered with Negative cache record when timing out.
3328		if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
3329			return;
3330		}
3331
3332	// Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
3333	// may be called twice, once when the record is received, and again when it's time to notify local clients.
3334	// If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
3335
3336	rr->LastUsed = m->timenow;
3337	if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
3338		{
3339		if (!rr->CRActiveQuestion) m->rrcache_active++;	// If not previously active, increment rrcache_active count
3340		debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
3341			rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
3342		rr->CRActiveQuestion = q;						// We know q is non-null
3343		SetNextCacheCheckTimeForRecord(m, rr);
3344		}
3345
3346	// If this is:
3347	// (a) a no-cache add, where we've already done at least one 'QM' query, or
3348	// (b) a normal add, where we have at least one unique-type answer,
3349	// then there's no need to keep polling the network.
3350	// (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
3351	// We do this for mDNS questions and uDNS one-shot questions, but not for
3352	// uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
3353	if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
3354		(AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
3355		if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
3356			{
3357			q->LastQTime        = m->timenow;
3358			q->LastQTxTime      = m->timenow;
3359			q->RecentAnswerPkts = 0;
3360			q->ThisQInterval    = MaxQuestionInterval;
3361			q->RequestUnicast   = mDNSfalse;
3362			debugf("AnswerCurrentQuestionWithResourceRecord: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3363			}
3364
3365	if (rr->DelayDelivery) return;		// We'll come back later when CacheRecordDeferredAdd() calls us
3366
3367	// Only deliver negative answers if client has explicitly requested them
3368	if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
3369		if (!AddRecord || !q->ReturnIntermed) return;
3370
3371	// For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
3372	if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
3373		{
3374		mDNS_DropLockBeforeCallback();		// Allow client (and us) to legally make mDNS API calls
3375		if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
3376			{
3377			CacheRecord neg;
3378			MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
3379			q->QuestionCallback(m, q, &neg.resrec, AddRecord);
3380			}
3381		else
3382			q->QuestionCallback(m, q, &rr->resrec, AddRecord);
3383		mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
3384		}
3385	// Note: Proceed with caution here because client callback function is allowed to do anything,
3386	// including starting/stopping queries, registering/deregistering records, etc.
3387
3388	if (followcname && m->CurrentQuestion == q)
3389		AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
3390	}
3391
3392// New Questions are answered through AnswerNewQuestion. But there may not have been any
3393// matching cache records for the questions when it is called. There are two possibilities.
3394//
3395// 1) There are no cache records
3396// 2) There are cache records but the DNSServers between question and cache record don't match.
3397//
3398// In the case of (1), where there are no cache records and later we add them when we get a response,
3399// CacheRecordAdd/CacheRecordDeferredAdd will take care of adding the cache and delivering the ADD
3400// events to the application. If we already have a cache entry, then no ADD events are delivered
3401// unless the RDATA has changed
3402//
3403// In the case of (2) where we had the cache records and did not answer because of the DNSServer mismatch,
3404// we need to answer them whenever we change the DNSServer.  But we can't do it at the instant the DNSServer
3405// changes because when we do the callback, the question can get deleted and the calling function would not
3406// know how to handle it. So, we run this function from mDNS_Execute to handle DNSServer changes on the
3407// question
3408
3409mDNSlocal void AnswerQuestionsForDNSServerChanges(mDNS *const m)
3410	{
3411	DNSQuestion *q;
3412	DNSQuestion *qnext;
3413	CacheRecord *rr;
3414	mDNSu32 slot;
3415	CacheGroup *cg;
3416
3417	if (m->CurrentQuestion)
3418		LogMsg("AnswerQuestionsForDNSServerChanges: ERROR m->CurrentQuestion already set: %##s (%s)",
3419				m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3420
3421	for (q = m->Questions; q && q != m->NewQuestions; q = qnext)
3422		{
3423		qnext = q->next;
3424
3425		// multicast or DNSServers did not change.
3426		if (mDNSOpaque16IsZero(q->TargetQID)) continue;
3427		if (!q->deliverAddEvents) continue;
3428
3429		// We are going to look through the cache for this question since it changed
3430		// its DNSserver last time. Reset it so that we don't call them again. Calling
3431		// them again will deliver duplicate events to the application
3432		q->deliverAddEvents = mDNSfalse;
3433		if (QuerySuppressed(q)) continue;
3434		m->CurrentQuestion = q;
3435		slot = HashSlot(&q->qname);
3436		cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3437		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3438			{
3439			if (SameNameRecordAnswersQuestion(&rr->resrec, q))
3440				{
3441				LogInfo("AnswerQuestionsForDNSServerChanges: Calling AnswerCurrentQuestionWithResourceRecord for question %p %##s using resource record %s",
3442					q, q->qname.c, CRDisplayString(m, rr));
3443				// When this question penalizes a DNS server and has no more DNS servers to pick, we normally
3444				// deliver a negative cache response and suspend the question for 60 seconds (see uDNS_CheckCurrentQuestion).
3445				// But sometimes we may already find the negative cache entry and deliver that here as the process
3446				// of changing DNS servers. When the cache entry is about to expire, we will resend the question and
3447				// that time, we need to make sure that we have a valid DNS server. Otherwise, we will deliver
3448				// a negative cache response without trying the server.
3449				if (!q->qDNSServer && !q->DuplicateOf && rr->resrec.RecordType == kDNSRecordTypePacketNegative)
3450					{
3451					DNSQuestion *qptr;
3452					SetValidDNSServers(m, q);
3453					q->qDNSServer = GetServerForQuestion(m, q);
3454					for (qptr = q->next ; qptr; qptr = qptr->next)
3455						if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
3456					}
3457				q->CurrentAnswers++;
3458				if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3459				if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3460				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3461				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
3462				}
3463			}
3464		}
3465		m->CurrentQuestion = mDNSNULL;
3466	}
3467
3468mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
3469	{
3470	rr->DelayDelivery = 0;
3471	if (m->CurrentQuestion)
3472		LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
3473			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3474	m->CurrentQuestion = m->Questions;
3475	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3476		{
3477		DNSQuestion *q = m->CurrentQuestion;
3478		if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3479			AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3480		if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3481			m->CurrentQuestion = q->next;
3482		}
3483	m->CurrentQuestion = mDNSNULL;
3484	}
3485
3486mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSu32 slot)
3487	{
3488	const mDNSs32 threshhold = m->timenow + mDNSPlatformOneSecond;	// See if there are any records expiring within one second
3489	const mDNSs32 start      = m->timenow - 0x10000000;
3490	mDNSs32 delay = start;
3491	CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
3492	const CacheRecord *rr;
3493	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3494		if (threshhold - RRExpireTime(rr) >= 0)		// If we have records about to expire within a second
3495			if (delay - RRExpireTime(rr) < 0)		// then delay until after they've been deleted
3496				delay = RRExpireTime(rr);
3497	if (delay - start > 0) return(NonZeroTime(delay));
3498	else return(0);
3499	}
3500
3501// CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
3502// If new questions are created as a result of invoking client callbacks, they will be added to
3503// the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3504// rr is a new CacheRecord just received into our cache
3505// (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3506// Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3507// which may change the record list and/or question list.
3508// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3509mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
3510	{
3511	DNSQuestion *q;
3512
3513	// We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
3514	// counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
3515	for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3516		{
3517		if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3518			{
3519			// If this question is one that's actively sending queries, and it's received ten answers within one
3520			// second of sending the last query packet, then that indicates some radical network topology change,
3521			// so reset its exponential backoff back to the start. We must be at least at the eight-second interval
3522			// to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3523			// because we will anyway send another query within a few seconds. The first reset query is sent out
3524			// randomized over the next four seconds to reduce possible synchronization between machines.
3525			if (q->LastAnswerPktNum != m->PktNum)
3526				{
3527				q->LastAnswerPktNum = m->PktNum;
3528				if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
3529					q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
3530					{
3531					LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3532						q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
3533					q->LastQTime      = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
3534					q->ThisQInterval  = InitialQuestionInterval;
3535					SetNextQueryTime(m,q);
3536					}
3537				}
3538			verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
3539				DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
3540				&rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
3541				rr->resrec.rDNSServer->port : zeroIPPort), q);
3542			q->CurrentAnswers++;
3543			q->unansweredQueries = 0;
3544			if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3545			if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3546			if (q->CurrentAnswers > 4000)
3547				{
3548				static int msgcount = 0;
3549				if (msgcount++ < 10)
3550					LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3551						q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
3552				rr->resrec.rroriginalttl = 0;
3553				rr->UnansweredQueries = MaxUnansweredQueries;
3554				}
3555			}
3556		}
3557
3558	if (!rr->DelayDelivery)
3559		{
3560		if (m->CurrentQuestion)
3561			LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3562		m->CurrentQuestion = m->Questions;
3563		while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3564			{
3565			q = m->CurrentQuestion;
3566			if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3567				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3568			if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3569				m->CurrentQuestion = q->next;
3570			}
3571		m->CurrentQuestion = mDNSNULL;
3572		}
3573
3574	SetNextCacheCheckTimeForRecord(m, rr);
3575	}
3576
3577// NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3578// If new questions are created as a result of invoking client callbacks, they will be added to
3579// the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3580// rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3581// but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3582// way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3583// so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3584// Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3585// which may change the record list and/or question list.
3586// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3587mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
3588	{
3589	LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
3590	if (m->CurrentQuestion)
3591		LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3592	m->CurrentQuestion = m->Questions;
3593	// We do this for *all* questions, not stopping when we get to m->NewQuestions,
3594	// since we're not caching the record and we'll get no opportunity to do this later
3595	while (m->CurrentQuestion)
3596		{
3597		DNSQuestion *q = m->CurrentQuestion;
3598		if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3599			AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache);	// QC_addnocache means "don't expect remove events for this"
3600		if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3601			m->CurrentQuestion = q->next;
3602		}
3603	m->CurrentQuestion = mDNSNULL;
3604	}
3605
3606// CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3607// Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3608// If new questions are created as a result of invoking client callbacks, they will be added to
3609// the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3610// rr is an existing cache CacheRecord that just expired and is being deleted
3611// (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3612// Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3613// which may change the record list and/or question list.
3614// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3615mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
3616	{
3617	if (m->CurrentQuestion)
3618		LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3619			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3620	m->CurrentQuestion = m->Questions;
3621
3622	// We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3623	// will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3624	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3625		{
3626		DNSQuestion *q = m->CurrentQuestion;
3627		// When a question enters suppressed state, we generate RMV events and generate a negative
3628		// response. A cache may be present that answers this question e.g., cache entry generated
3629		// before the question became suppressed. We need to skip the suppressed questions here as
3630		// the RMV event has already been generated.
3631		if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
3632			{
3633			verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
3634			q->FlappingInterface1 = mDNSNULL;
3635			q->FlappingInterface2 = mDNSNULL;
3636
3637			// When a question changes DNS server, it is marked with deliverAddEvents if we find any
3638			// cache entry corresponding to the new DNS server. Before we deliver the ADD event, the
3639			// cache entry may be removed in which case CurrentAnswers can be zero.
3640			if (q->deliverAddEvents && !q->CurrentAnswers)
3641				{
3642				LogInfo("CacheRecordRmv: Question %p %##s (%s) deliverAddEvents set, DNSServer %#a:%d",
3643					q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3644					mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3645				m->CurrentQuestion = q->next;
3646				continue;
3647				}
3648			if (q->CurrentAnswers == 0)
3649				LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3650					q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3651					mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3652			else
3653				{
3654				q->CurrentAnswers--;
3655				if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
3656				if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
3657				}
3658			if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
3659				{
3660				if (q->CurrentAnswers == 0)
3661					{
3662					LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3663						q->qname.c, DNSTypeName(q->qtype));
3664					ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3665					}
3666				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
3667				}
3668			}
3669		if (m->CurrentQuestion == q)	// If m->CurrentQuestion was not auto-advanced, do it ourselves now
3670			m->CurrentQuestion = q->next;
3671		}
3672	m->CurrentQuestion = mDNSNULL;
3673	}
3674
3675mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
3676	{
3677#if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3678	unsigned int i;
3679	for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
3680#endif
3681	e->next = m->rrcache_free;
3682	m->rrcache_free = e;
3683	m->rrcache_totalused--;
3684	}
3685
3686mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
3687	{
3688	CacheEntity *e = (CacheEntity *)(*cp);
3689	//LogMsg("ReleaseCacheGroup:  Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3690	if ((*cp)->rrcache_tail != &(*cp)->members)
3691		LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3692	//if ((*cp)->name != (domainname*)((*cp)->namestorage))
3693	//	LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3694	if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
3695	(*cp)->name = mDNSNULL;
3696	*cp = (*cp)->next;			// Cut record from list
3697	ReleaseCacheEntity(m, e);
3698	}
3699
3700mDNSlocal void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
3701	{
3702	//LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3703	if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
3704	r->resrec.rdata = mDNSNULL;
3705	ReleaseCacheEntity(m, (CacheEntity *)r);
3706	}
3707
3708// Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3709// CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3710// callbacks for old records are delivered before callbacks for newer records.
3711mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
3712	{
3713	CacheRecord **rp = &cg->members;
3714
3715	if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3716	m->lock_rrcache = 1;
3717
3718	while (*rp)
3719		{
3720		CacheRecord *const rr = *rp;
3721		mDNSs32 event = RRExpireTime(rr);
3722		if (m->timenow - event >= 0)	// If expired, delete it
3723			{
3724			*rp = rr->next;				// Cut it from the list
3725			verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3726				m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
3727			if (rr->CRActiveQuestion)	// If this record has one or more active questions, tell them it's going away
3728				{
3729				DNSQuestion *q = rr->CRActiveQuestion;
3730				// When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3731				// then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3732				// before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3733				// not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3734				// a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3735				// MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3736				// don't ressurect them as they will deliver duplicate "No such Record" ADD events
3737				if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
3738					{
3739					q->ThisQInterval = InitialQuestionInterval;
3740					q->LastQTime     = m->timenow - q->ThisQInterval;
3741					SetNextQueryTime(m, q);
3742					}
3743				CacheRecordRmv(m, rr);
3744				m->rrcache_active--;
3745				}
3746			ReleaseCacheRecord(m, rr);
3747			}
3748		else							// else, not expired; see if we need to query
3749			{
3750			// If waiting to delay delivery, do nothing until then
3751			if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
3752				event = rr->DelayDelivery;
3753			else
3754				{
3755				if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
3756				if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3757					{
3758					if (m->timenow - rr->NextRequiredQuery < 0)		// If not yet time for next query
3759						event = NextCacheCheckEvent(rr);			// then just record when we want the next query
3760					else											// else trigger our question to go out now
3761						{
3762						// Set NextScheduledQuery to timenow so that SendQueries() will run.
3763						// SendQueries() will see that we have records close to expiration, and send FEQs for them.
3764						m->NextScheduledQuery = m->timenow;
3765						// After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3766						// which will correctly update m->NextCacheCheck for us.
3767						event = m->timenow + 0x3FFFFFFF;
3768						}
3769					}
3770				}
3771			verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3772				(event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
3773			if (m->rrcache_nextcheck[slot] - event > 0)
3774				m->rrcache_nextcheck[slot] = event;
3775			rp = &rr->next;
3776			}
3777		}
3778	if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
3779	cg->rrcache_tail = rp;
3780	m->lock_rrcache = 0;
3781	}
3782
3783mDNSlocal void AnswerNewQuestion(mDNS *const m)
3784	{
3785	mDNSBool ShouldQueryImmediately = mDNStrue;
3786	DNSQuestion *const q = m->NewQuestions;		// Grab the question we're going to answer
3787	mDNSu32 slot = HashSlot(&q->qname);
3788	CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3789	AuthRecord *lr;
3790	AuthGroup *ag;
3791	mDNSBool AnsweredFromCache = mDNSfalse;
3792
3793	verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3794
3795	if (cg) CheckCacheExpiration(m, slot, cg);
3796	if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
3797	m->NewQuestions = q->next;
3798	// Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3799	// then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3800	//
3801	// Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3802	// client callbacks, which may delete their own or any other question. Our mechanism for detecting
3803	// whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3804	// value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3805	// that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3806	// advanced it), that means the question was deleted, so we no longer need to worry about answering
3807	// it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3808	// values we computed for slot and cg are now stale and relate to a question that no longer exists).
3809	//
3810	// We can't use the usual m->CurrentQuestion mechanism for this because  CacheRecordDeferredAdd() and
3811	// CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3812	// Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3813	// deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3814
3815	if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3816	// This should be safe, because calling the client's question callback may cause the
3817	// question list to be modified, but should not ever cause the rrcache list to be modified.
3818	// If the client's question callback deletes the question, then m->CurrentQuestion will
3819	// be advanced, and we'll exit out of the loop
3820	m->lock_rrcache = 1;
3821	if (m->CurrentQuestion)
3822		LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3823			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3824	m->CurrentQuestion = q;		// Indicate which question we're answering, so we'll know if it gets deleted
3825
3826	if (q->NoAnswer == NoAnswer_Fail)
3827		{
3828		LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3829		MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
3830		q->NoAnswer = NoAnswer_Normal;		// Temporarily turn off answer suppression
3831		AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
3832		// Don't touch the question if it has been stopped already
3833		if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail;		// Restore NoAnswer state
3834		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
3835		}
3836	if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit; }
3837
3838	// See if we want to tell it about LocalOnly records
3839	if (m->CurrentRecord)
3840		LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3841	slot = AuthHashSlot(&q->qname);
3842	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
3843	if (ag)
3844		{
3845		m->CurrentRecord = ag->members;
3846		while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
3847			{
3848			AuthRecord *rr = m->CurrentRecord;
3849			m->CurrentRecord = rr->next;
3850			//
3851			// If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
3852			// to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
3853			//
3854			// We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
3855			// details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
3856			// we handle both mDNSInterface_Any and scoped questions.
3857
3858			if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && q->InterfaceID == mDNSInterface_Any))
3859				if (LocalOnlyRecordAnswersQuestion(rr, q))
3860					{
3861					AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
3862					if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
3863					}
3864			}
3865		}
3866	m->CurrentRecord = mDNSNULL;
3867
3868	if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit; }
3869
3870	if (q->LOAddressAnswers)
3871		{
3872		LogInfo("AnswerNewQuestion: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
3873			q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
3874		goto exit;
3875		}
3876
3877	// Before we go check the cache and ship this query on the wire, we have to be sure that there are
3878	// no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
3879	// need to just peek at them to see whether it will answer this question. If it would answer, pretend
3880	// that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
3881	// when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
3882	if (ag)
3883		{
3884		lr = ag->NewLocalOnlyRecords;
3885		while (lr)
3886			{
3887			if (LORecordAnswersAddressType(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
3888				{
3889				LogInfo("AnswerNewQuestion: Question %p %##s (%s) will be answered using new local auth records "
3890					" LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
3891				goto exit;
3892				}
3893			lr = lr->next;
3894			}
3895		}
3896
3897
3898	// If we are not supposed to answer this question, generate a negative response.
3899	// Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
3900	if (QuerySuppressed(q)) { q->SuppressQuery = mDNSfalse; GenerateNegativeResponse(m); q->SuppressQuery = mDNStrue; }
3901	else
3902		{
3903		CacheRecord *rr;
3904		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3905			if (SameNameRecordAnswersQuestion(&rr->resrec, q))
3906				{
3907				// SecsSinceRcvd is whole number of elapsed seconds, rounded down
3908				mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
3909				if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
3910					{
3911					LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
3912						rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
3913					continue;	// Go to next one in loop
3914					}
3915
3916				// If this record set is marked unique, then that means we can reasonably assume we have the whole set
3917				// -- we don't need to rush out on the network and query immediately to see if there are more answers out there
3918				if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
3919					ShouldQueryImmediately = mDNSfalse;
3920				q->CurrentAnswers++;
3921				if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3922				if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3923				AnsweredFromCache = mDNStrue;
3924				AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3925				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
3926				}
3927			else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
3928				ShouldQueryImmediately = mDNSfalse;
3929		}
3930	// We don't use LogInfo for this "Question deleted" message because it happens so routinely that
3931	// it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
3932	if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
3933
3934	// Neither a local record nor a cache entry could answer this question. If this question need to be retried
3935	// with search domains, generate a negative response which will now retry after appending search domains.
3936	// If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
3937	// we will retry with search domains.
3938	if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
3939		{
3940		LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3941		GenerateNegativeResponse(m);
3942		}
3943
3944	if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
3945
3946	// Note: When a query gets suppressed or retried with search domains, we de-activate the question.
3947	// Hence we don't execute the following block of code for those cases.
3948	if (ShouldQueryImmediately && ActiveQuestion(q))
3949		{
3950		debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3951		q->ThisQInterval  = InitialQuestionInterval;
3952		q->LastQTime      = m->timenow - q->ThisQInterval;
3953		if (mDNSOpaque16IsZero(q->TargetQID))		// For mDNS, spread packets to avoid a burst of simultaneous queries
3954			{
3955			// Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
3956			if (!m->RandomQueryDelay)
3957				m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
3958			q->LastQTime += m->RandomQueryDelay;
3959			}
3960		}
3961
3962	// IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
3963	// In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
3964	// answers for this question until *after* its scheduled transmission time, in which case
3965	// m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
3966	// ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
3967	SetNextQueryTime(m,q);
3968
3969exit:
3970	m->CurrentQuestion = mDNSNULL;
3971	m->lock_rrcache = 0;
3972	}
3973
3974// When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
3975// appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
3976mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
3977	{
3978	mDNSu32 slot;
3979	AuthGroup *ag;
3980	DNSQuestion *q = m->NewLocalOnlyQuestions;		// Grab the question we're going to answer
3981	m->NewLocalOnlyQuestions = q->next;				// Advance NewLocalOnlyQuestions to the next (if any)
3982
3983	debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3984
3985	if (m->CurrentQuestion)
3986		LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3987			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3988	m->CurrentQuestion = q;		// Indicate which question we're answering, so we'll know if it gets deleted
3989
3990	if (m->CurrentRecord)
3991		LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3992
3993	// 1. First walk the LocalOnly records answering the LocalOnly question
3994	// 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
3995	//    walk the ResourceRecords list delivering the answers
3996	slot = AuthHashSlot(&q->qname);
3997	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
3998	if (ag)
3999		{
4000		m->CurrentRecord = ag->members;
4001		while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4002			{
4003			AuthRecord *rr = m->CurrentRecord;
4004			m->CurrentRecord = rr->next;
4005			if (LocalOnlyRecordAnswersQuestion(rr, q))
4006				{
4007				AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4008				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
4009				}
4010			}
4011		}
4012
4013	if (m->CurrentQuestion == q)
4014		{
4015		m->CurrentRecord = m->ResourceRecords;
4016
4017		while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
4018			{
4019			AuthRecord *rr = m->CurrentRecord;
4020			m->CurrentRecord = rr->next;
4021			if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4022				{
4023				AnswerLocalQuestionWithLocalAuthRecord(m, rr, mDNStrue);
4024				if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
4025				}
4026			}
4027		}
4028
4029	m->CurrentQuestion = mDNSNULL;
4030	m->CurrentRecord   = mDNSNULL;
4031	}
4032
4033mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
4034	{
4035	CacheEntity *e = mDNSNULL;
4036
4037	if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
4038	m->lock_rrcache = 1;
4039
4040	// If we have no free records, ask the client layer to give us some more memory
4041	if (!m->rrcache_free && m->MainCallback)
4042		{
4043		if (m->rrcache_totalused != m->rrcache_size)
4044			LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4045				m->rrcache_totalused, m->rrcache_size);
4046
4047		// We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4048		// number of bogus records so that we keep growing our cache until the machine runs out of memory.
4049		// To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
4050		// and we're actively using less than 1/32 of that cache, then we purge all the unused records
4051		// and recycle them, instead of allocating more memory.
4052		if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
4053			LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4054				m->rrcache_size, m->rrcache_active);
4055		else
4056			{
4057			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
4058			m->MainCallback(m, mStatus_GrowCache);
4059			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
4060			}
4061		}
4062
4063	// If we still have no free records, recycle all the records we can.
4064	// Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4065	if (!m->rrcache_free)
4066		{
4067		mDNSu32 oldtotalused = m->rrcache_totalused;
4068		mDNSu32 slot;
4069		for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4070			{
4071			CacheGroup **cp = &m->rrcache_hash[slot];
4072			while (*cp)
4073				{
4074				CacheRecord **rp = &(*cp)->members;
4075				while (*rp)
4076					{
4077					// Records that answer still-active questions are not candidates for recycling
4078					// Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
4079					if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
4080						rp=&(*rp)->next;
4081					else
4082						{
4083						CacheRecord *rr = *rp;
4084						*rp = (*rp)->next;			// Cut record from list
4085						ReleaseCacheRecord(m, rr);
4086						}
4087					}
4088				if ((*cp)->rrcache_tail != rp)
4089					verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
4090				(*cp)->rrcache_tail = rp;
4091				if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
4092				else ReleaseCacheGroup(m, cp);
4093				}
4094			}
4095		LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
4096			oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
4097		}
4098
4099	if (m->rrcache_free)	// If there are records in the free list, take one
4100		{
4101		e = m->rrcache_free;
4102		m->rrcache_free = e->next;
4103		if (++m->rrcache_totalused >= m->rrcache_report)
4104			{
4105			LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
4106			if      (m->rrcache_report <  100) m->rrcache_report += 10;
4107			else if (m->rrcache_report < 1000) m->rrcache_report += 100;
4108			else                               m->rrcache_report += 1000;
4109			}
4110		mDNSPlatformMemZero(e, sizeof(*e));
4111		}
4112
4113	m->lock_rrcache = 0;
4114
4115	return(e);
4116	}
4117
4118mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
4119	{
4120	CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
4121	if (r)
4122		{
4123		r->resrec.rdata = (RData*)&r->smallrdatastorage;	// By default, assume we're usually going to be using local storage
4124		if (RDLength > InlineCacheRDSize)			// If RDLength is too big, allocate extra storage
4125			{
4126			r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
4127			if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
4128			else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
4129			}
4130		}
4131	return(r);
4132	}
4133
4134mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
4135	{
4136	mDNSu16 namelen = DomainNameLength(rr->name);
4137	CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
4138	if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
4139	cg->next         = m->rrcache_hash[slot];
4140	cg->namehash     = rr->namehash;
4141	cg->members      = mDNSNULL;
4142	cg->rrcache_tail = &cg->members;
4143	cg->name         = (domainname*)cg->namestorage;
4144	//LogMsg("GetCacheGroup: %-10s %d-byte cache name %##s",
4145	//	(namelen > InlineCacheGroupNameSize) ? "Allocating" : "Inline", namelen, rr->name->c);
4146	if (namelen > InlineCacheGroupNameSize) cg->name = mDNSPlatformMemAllocate(namelen);
4147	if (!cg->name)
4148		{
4149		LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
4150		ReleaseCacheEntity(m, (CacheEntity*)cg);
4151		return(mDNSNULL);
4152		}
4153	AssignDomainName(cg->name, rr->name);
4154
4155	if (CacheGroupForRecord(m, slot, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
4156	m->rrcache_hash[slot] = cg;
4157	if (CacheGroupForRecord(m, slot, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
4158
4159	return(cg);
4160	}
4161
4162mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
4163	{
4164	if (m->mDNS_busy != m->mDNS_reentrancy+1)
4165		LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
4166	// Make sure we mark this record as thoroughly expired -- we don't ever want to give
4167	// a positive answer using an expired record (e.g. from an interface that has gone away).
4168	// We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4169	// summary deletion without giving the proper callback to any questions that are monitoring it.
4170	// By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4171	rr->TimeRcvd          = m->timenow - mDNSPlatformOneSecond * 60;
4172	rr->UnansweredQueries = MaxUnansweredQueries;
4173	rr->resrec.rroriginalttl     = 0;
4174	SetNextCacheCheckTimeForRecord(m, rr);
4175	}
4176
4177mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
4178	{
4179	mDNSs32 time;
4180	mDNSPlatformLock(m);
4181	if (m->mDNS_busy)
4182		{
4183		LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
4184		if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
4185		}
4186
4187	if (m->timenow) time = m->timenow;
4188	else            time = mDNS_TimeNow_NoLock(m);
4189	mDNSPlatformUnlock(m);
4190	return(time);
4191	}
4192
4193// To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
4194// had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
4195// (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
4196#define SetSPSProxyListChanged(X) do { \
4197	if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
4198	m->SPSProxyListChanged = (X); } while(0)
4199
4200// Called from mDNS_Execute() to expire stale proxy records
4201mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
4202	{
4203	m->CurrentRecord = list;
4204	while (m->CurrentRecord)
4205		{
4206		AuthRecord *rr = m->CurrentRecord;
4207		if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
4208			{
4209			// If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
4210			// so we need to cease proxying for *all* records we may have, expired or not.
4211			if (m->SPSSocket && m->timenow - rr->TimeExpire < 0)	// If proxy record not expired yet, update m->NextScheduledSPS
4212				{
4213				if (m->NextScheduledSPS - rr->TimeExpire > 0)
4214					m->NextScheduledSPS = rr->TimeExpire;
4215				}
4216			else													// else proxy record expired, so remove it
4217				{
4218				LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
4219					m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
4220				SetSPSProxyListChanged(rr->resrec.InterfaceID);
4221				mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4222				// Don't touch rr after this -- memory may have been free'd
4223				}
4224			}
4225		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4226		// new records could have been added to the end of the list as a result of that call.
4227		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
4228			m->CurrentRecord = rr->next;
4229		}
4230	}
4231
4232mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
4233	{
4234	while (m->CurrentRecord)
4235		{
4236		AuthRecord *rr = m->CurrentRecord;
4237		if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
4238			{
4239			debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
4240			rr->resrec.RecordType = kDNSRecordTypeShared;
4241			AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
4242			if (m->CurrentRecord == rr)	// If rr still exists in list, restore its state now
4243				{
4244				rr->resrec.RecordType = kDNSRecordTypeDeregistering;
4245				rr->AnsweredLocalQ = mDNSfalse;
4246				// SendResponses normally calls CompleteDeregistration after sending goodbyes.
4247				// For LocalOnly records, we don't do that and hence we need to do that here.
4248				if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
4249				}
4250			}
4251		if (m->CurrentRecord == rr)		// If m->CurrentRecord was not auto-advanced, do it ourselves now
4252			m->CurrentRecord = rr->next;
4253		}
4254	}
4255
4256mDNSlocal void TimeoutQuestions(mDNS *const m)
4257	{
4258	m->NextScheduledStopTime = m->timenow + 0x3FFFFFFF;
4259	if (m->CurrentQuestion)
4260		LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
4261			DNSTypeName(m->CurrentQuestion->qtype));
4262	m->CurrentQuestion = m->Questions;
4263	while (m->CurrentQuestion)
4264		{
4265		DNSQuestion *const q = m->CurrentQuestion;
4266		if (q->StopTime)
4267			{
4268			if (m->timenow - q->StopTime >= 0)
4269				{
4270				LogInfo("TimeoutQuestions: question %##s timed out, time %d", q->qname.c, m->timenow - q->StopTime);
4271				GenerateNegativeResponse(m);
4272				if (m->CurrentQuestion == q) q->StopTime = 0;
4273				}
4274			else
4275				{
4276				if (m->NextScheduledStopTime - q->StopTime > 0)
4277					m->NextScheduledStopTime = q->StopTime;
4278				}
4279			}
4280		// If m->CurrentQuestion wasn't modified out from under us, advance it now
4281		// We can't do this at the start of the loop because GenerateNegativeResponse
4282		// depends on having m->CurrentQuestion point to the right question
4283		if (m->CurrentQuestion == q)
4284			m->CurrentQuestion = q->next;
4285		}
4286	m->CurrentQuestion = mDNSNULL;
4287	}
4288
4289mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
4290	{
4291	mDNS_Lock(m);	// Must grab lock before trying to read m->timenow
4292
4293	if (m->timenow - m->NextScheduledEvent >= 0)
4294		{
4295		int i;
4296		AuthRecord *head, *tail;
4297		mDNSu32 slot;
4298		AuthGroup *ag;
4299
4300		verbosedebugf("mDNS_Execute");
4301
4302		if (m->CurrentQuestion)
4303			LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
4304				m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4305
4306		if (m->CurrentRecord)
4307			LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
4308
4309		// 1. If we're past the probe suppression time, we can clear it
4310		if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
4311
4312		// 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4313		if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
4314
4315		// 3. Purge our cache of stale old records
4316		if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
4317			{
4318			mDNSu32 numchecked = 0;
4319			m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
4320			for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4321				{
4322				if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
4323					{
4324					CacheGroup **cp = &m->rrcache_hash[slot];
4325					m->rrcache_nextcheck[slot] = m->timenow + 0x3FFFFFFF;
4326					while (*cp)
4327						{
4328						debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
4329						numchecked++;
4330						CheckCacheExpiration(m, slot, *cp);
4331						if ((*cp)->members) cp=&(*cp)->next;
4332						else ReleaseCacheGroup(m, cp);
4333						}
4334					}
4335				// Even if we didn't need to actually check this slot yet, still need to
4336				// factor its nextcheck time into our overall NextCacheCheck value
4337				if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
4338					m->NextCacheCheck = m->rrcache_nextcheck[slot];
4339				}
4340			debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
4341			}
4342
4343		if (m->timenow - m->NextScheduledSPS >= 0)
4344			{
4345			m->NextScheduledSPS = m->timenow + 0x3FFFFFFF;
4346			CheckProxyRecords(m, m->DuplicateRecords);	// Clear m->DuplicateRecords first, then m->ResourceRecords
4347			CheckProxyRecords(m, m->ResourceRecords);
4348			}
4349
4350		SetSPSProxyListChanged(mDNSNULL);		// Perform any deferred BPF reconfiguration now
4351
4352		// Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
4353		if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0) m->AnnounceOwner = 0;
4354
4355		if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
4356			{
4357			m->DelaySleep = 0;
4358			if (m->SleepState == SleepState_Transferring)
4359				{
4360				LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
4361				BeginSleepProcessing(m);
4362				}
4363			}
4364
4365		// 4. See if we can answer any of our new local questions from the cache
4366		for (i=0; m->NewQuestions && i<1000; i++)
4367			{
4368			if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
4369			AnswerNewQuestion(m);
4370			}
4371		if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4372
4373		// Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
4374		// we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
4375		for (i=0; i<1000 && m->LocalRemoveEvents; i++)
4376			{
4377			m->LocalRemoveEvents = mDNSfalse;
4378			m->CurrentRecord = m->ResourceRecords;
4379			CheckRmvEventsForLocalRecords(m);
4380			// Walk the LocalOnly records and deliver the RMV events
4381			for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4382				for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4383					{
4384					m->CurrentRecord = ag->members;
4385					if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
4386					}
4387			}
4388
4389		if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
4390
4391		for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
4392		if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4393
4394		head = tail = mDNSNULL;
4395		for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
4396			{
4397			AuthRecord *rr = m->NewLocalRecords;
4398			m->NewLocalRecords = m->NewLocalRecords->next;
4399			if (LocalRecordReady(rr))
4400				{
4401				debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4402				AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4403				}
4404			else if (!rr->next)
4405				{
4406				// If we have just one record that is not ready, we don't have to unlink and
4407				// reinsert. As the NewLocalRecords will be NULL for this case, the loop will
4408				// terminate and set the NewLocalRecords to rr.
4409				debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
4410				if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
4411					LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
4412
4413				head = rr;
4414				}
4415			else
4416				{
4417				AuthRecord **p = &m->ResourceRecords;	// Find this record in our list of active records
4418				debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
4419				// if this is the first record we are skipping, move to the end of the list.
4420				// if we have already skipped records before, append it at the end.
4421				while (*p && *p != rr) p=&(*p)->next;
4422				if (*p) *p = rr->next;					// Cut this record from the list
4423				else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
4424				if (!head)
4425					{
4426					while (*p) p=&(*p)->next;
4427					*p = rr;
4428					head = tail = rr;
4429					}
4430				else
4431					{
4432					tail->next = rr;
4433					tail = rr;
4434					}
4435				rr->next = mDNSNULL;
4436				}
4437			}
4438		m->NewLocalRecords = head;
4439		debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
4440
4441		if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
4442
4443		// Check to see if we have any new LocalOnly/P2P records to examine for delivering
4444		// to our local questions
4445		if (m->NewLocalOnlyRecords)
4446			{
4447			m->NewLocalOnlyRecords = mDNSfalse;
4448			for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4449				for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4450					{
4451					for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
4452						{
4453						AuthRecord *rr = ag->NewLocalOnlyRecords;
4454						ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
4455						// LocalOnly records should always be ready as they never probe
4456						if (LocalRecordReady(rr))
4457							{
4458							debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
4459							AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
4460							}
4461						else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
4462						}
4463					// We limit about 100 per AuthGroup that can be serviced at a time
4464					if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
4465					}
4466			}
4467
4468		// 5. Some questions may have picked a new DNS server and the cache may answer these questions now.
4469		AnswerQuestionsForDNSServerChanges(m);
4470
4471		// 6. See what packets we need to send
4472		if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
4473			DiscardDeregistrations(m);
4474		if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
4475			{
4476			// If the platform code is ready, and we're not suppressing packet generation right now
4477			// then send our responses, probes, and questions.
4478			// We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
4479			// We send queries next, because there might be final-stage probes that complete their probing here, causing
4480			// them to advance to announcing state, and we want those to be included in any announcements we send out.
4481			// Finally, we send responses, including the previously mentioned records that just completed probing.
4482			m->SuppressSending = 0;
4483
4484			// 7. Send Query packets. This may cause some probing records to advance to announcing state
4485			if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
4486			if (m->timenow - m->NextScheduledQuery >= 0)
4487				{
4488				DNSQuestion *q;
4489				LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
4490					m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
4491				m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
4492				for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4493					if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
4494						LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4495				}
4496			if (m->timenow - m->NextScheduledProbe >= 0)
4497				{
4498				LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
4499					m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
4500				m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
4501				}
4502
4503			// 8. Send Response packets, including probing records just advanced to announcing state
4504			if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
4505			if (m->timenow - m->NextScheduledResponse >= 0)
4506				{
4507				LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4508				m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
4509				}
4510			}
4511
4512		// Clear RandomDelay values, ready to pick a new different value next time
4513		m->RandomQueryDelay     = 0;
4514		m->RandomReconfirmDelay = 0;
4515
4516		if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
4517#ifndef UNICAST_DISABLED
4518		if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
4519		if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
4520		if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
4521#endif
4522		}
4523
4524	// Note about multi-threaded systems:
4525	// On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4526	// performing mDNS API operations that change our next scheduled event time.
4527	//
4528	// On multi-threaded systems (like the current Windows implementation) that have a single main thread
4529	// calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4530	// of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4531	// signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4532	// more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4533	// in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4534	// does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4535	// without blocking. This avoids the race condition between the signal from the other thread arriving
4536	// just *before* or just *after* the main thread enters the blocking primitive.
4537	//
4538	// On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4539	// with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4540	// set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4541	// callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4542	// by the time it gets to the timer callback function).
4543
4544	mDNS_Unlock(m);		// Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4545	return(m->NextScheduledEvent);
4546	}
4547
4548mDNSlocal void SuspendLLQs(mDNS *m)
4549	{
4550	DNSQuestion *q;
4551	for (q = m->Questions; q; q = q->next)
4552		if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
4553			{ q->ReqLease = 0; sendLLQRefresh(m, q); }
4554	}
4555
4556mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
4557	{
4558	AuthRecord *rr;
4559	mDNSu32 slot;
4560	AuthGroup *ag;
4561
4562	slot = AuthHashSlot(&q->qname);
4563	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4564	if (ag)
4565		{
4566		for (rr = ag->members; rr; rr=rr->next)
4567			// Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
4568			if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
4569				{
4570				LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
4571				return mDNStrue;
4572				}
4573		}
4574	return mDNSfalse;
4575	}
4576
4577// ActivateUnicastQuery() is called from three places:
4578// 1. When a new question is created
4579// 2. On wake from sleep
4580// 3. When the DNS configuration changes
4581// In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
4582// In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
4583mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
4584	{
4585	// For now this AutoTunnel stuff is specific to Mac OS X.
4586	// In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
4587#if APPLE_OSX_mDNSResponder
4588	// Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
4589	// Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
4590	// caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
4591	// To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
4592	// returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
4593	// as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
4594
4595	if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
4596		!SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
4597		{
4598		question->NoAnswer = NoAnswer_Suspended;
4599		AddNewClientTunnel(m, question);
4600		return;
4601		}
4602#endif // APPLE_OSX_mDNSResponder
4603
4604	if (!question->DuplicateOf)
4605		{
4606		debugf("ActivateUnicastQuery: %##s %s%s%s",
4607			question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
4608		question->CNAMEReferrals = 0;
4609		if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
4610		if (question->LongLived)
4611			{
4612			question->state = LLQ_InitialRequest;
4613			question->id = zeroOpaque64;
4614			question->servPort = zeroIPPort;
4615			if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
4616			}
4617		// If the question has local answers, then we don't want answers from outside
4618		if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
4619			{
4620			question->ThisQInterval = InitialQuestionInterval;
4621			question->LastQTime     = m->timenow - question->ThisQInterval;
4622			SetNextQueryTime(m, question);
4623			}
4624		}
4625	}
4626
4627// Caller should hold the lock
4628mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
4629	CallbackBeforeStartQuery BeforeStartCallback, void *context)
4630	{
4631	DNSQuestion *q;
4632	DNSQuestion *restart = mDNSNULL;
4633
4634	if (!m->mDNS_busy) LogMsg("mDNSCoreRestartAddressQueries: ERROR!! Lock not held");
4635
4636	// 1. Flush the cache records
4637	if (flushCacheRecords) flushCacheRecords(m);
4638
4639	// 2. Even though we may have purged the cache records above, before it can generate RMV event
4640	// we are going to stop the question. Hence we need to deliver the RMV event before we
4641	// stop the question.
4642	//
4643	// CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
4644	// application callback can potentially stop the current question (detected by CurrentQuestion) or
4645	// *any* other question which could be the next one that we may process here. RestartQuestion
4646	// points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
4647	// if the "next" question is stopped while the CurrentQuestion is stopped
4648
4649	if (m->RestartQuestion)
4650		LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
4651			m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
4652
4653	m->RestartQuestion = m->Questions;
4654	while (m->RestartQuestion)
4655		{
4656		q = m->RestartQuestion;
4657		m->RestartQuestion = q->next;
4658		// GetZoneData questions are referenced by other questions (original query that started the GetZoneData
4659		// question)  through their "nta" pointer. Normally when the original query stops, it stops the
4660		// GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
4661		// question followed by the original query that refers to this GetZoneData question, we will end up
4662		// freeing the GetZoneData question and then start the "freed" question at the end.
4663
4664		if (IsGetZoneDataQuestion(q))
4665			{
4666			DNSQuestion *refq = q->next;
4667			LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4668			// debug stuff, we just try to find the referencing question and don't do much with it
4669			while (refq)
4670				{
4671				if (q == &refq->nta->question)
4672					{
4673					LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
4674					}
4675				refq = refq->next;
4676				}
4677			continue;
4678			}
4679
4680		// This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
4681		if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
4682
4683		// If the search domains did not change, then we restart all the queries. Otherwise, only
4684		// for queries for which we "might" have appended search domains ("might" because we may
4685		// find results before we apply search domains even though AppendSearchDomains is set to 1)
4686		if (!SearchDomainsChanged || q->AppendSearchDomains)
4687			{
4688			// NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
4689			// LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
4690			// LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
4691			// /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
4692			// But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
4693			// it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
4694			// for the original query using these cache entries as ADDs were never delivered using these cache
4695			// entries and hence this order is needed.
4696
4697			// If the query is suppressed, the RMV events won't be delivered
4698			if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
4699
4700			// SuppressQuery status does not affect questions that are answered using local records
4701			if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
4702
4703			LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
4704				q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
4705			mDNS_StopQuery_internal(m, q);
4706			// Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
4707			// and then search domains should be appended. At the beginning, qnameOrig was NULL.
4708			if (q->qnameOrig)
4709				{
4710				LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
4711				AssignDomainName(&q->qname, q->qnameOrig);
4712				mDNSPlatformMemFree(q->qnameOrig);
4713				q->qnameOrig = mDNSNULL;
4714				q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
4715				}
4716			q->SearchListIndex = 0;
4717			q->next = restart;
4718			restart = q;
4719			}
4720		}
4721
4722	// 3. Callback before we start the query
4723	if (BeforeStartCallback) BeforeStartCallback(m, context);
4724
4725	// 4. Restart all the stopped queries
4726	while (restart)
4727		{
4728		q = restart;
4729		restart = restart->next;
4730		q->next = mDNSNULL;
4731		LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
4732		mDNS_StartQuery_internal(m, q);
4733		}
4734	}
4735
4736mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
4737	{
4738	DNSQuestion *q;
4739
4740#ifndef UNICAST_DISABLED
4741	// Retrigger all our uDNS questions
4742	if (m->CurrentQuestion)
4743		LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
4744			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4745	m->CurrentQuestion = m->Questions;
4746	while (m->CurrentQuestion)
4747		{
4748		q = m->CurrentQuestion;
4749		m->CurrentQuestion = m->CurrentQuestion->next;
4750		if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
4751		}
4752#endif
4753
4754	// Retrigger all our mDNS questions
4755	for (q = m->Questions; q; q=q->next)				// Scan our list of questions
4756		if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
4757			{
4758			q->ThisQInterval    = InitialQuestionInterval;	// MUST be > zero for an active question
4759			q->RequestUnicast   = 2;						// Set to 2 because is decremented once *before* we check it
4760			q->LastQTime        = m->timenow - q->ThisQInterval;
4761			q->RecentAnswerPkts = 0;
4762			ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
4763			m->NextScheduledQuery = m->timenow;
4764			}
4765	}
4766
4767// ***************************************************************************
4768#if COMPILER_LIKES_PRAGMA_MARK
4769#pragma mark -
4770#pragma mark - Power Management (Sleep/Wake)
4771#endif
4772
4773mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
4774	{
4775#ifndef IDLESLEEPCONTROL_DISABLED
4776	mDNSBool allowSleep = mDNStrue;
4777	char     reason[128];
4778
4779	reason[0] = 0;
4780
4781	if (m->SystemSleepOnlyIfWakeOnLAN)
4782		{
4783		// Don't sleep if we are a proxy for any services
4784		if (m->ProxyRecords)
4785			{
4786			allowSleep = mDNSfalse;
4787			mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
4788			LogInfo("Sleep disabled because we are proxying %d records", m->ProxyRecords);
4789			}
4790
4791		if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
4792			{
4793			// Scan the list of active interfaces
4794			NetworkInterfaceInfo *intf;
4795			for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4796				{
4797				if (intf->McastTxRx && !intf->Loopback)
4798					{
4799					// Disallow sleep if this interface doesn't support NetWake
4800					if (!intf->NetWake)
4801						{
4802						allowSleep = mDNSfalse;
4803						mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
4804						LogInfo("Sleep disabled because %s does not support NetWake", intf->ifname);
4805						break;
4806						}
4807
4808					// Disallow sleep if there is no sleep proxy server
4809					if (FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL) == mDNSNULL)
4810						{
4811						allowSleep = mDNSfalse;
4812						mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
4813						LogInfo("Sleep disabled because %s has no sleep proxy", intf->ifname);
4814						break;
4815						}
4816					}
4817				}
4818			}
4819		}
4820
4821	// Call the platform code to enable/disable sleep
4822	mDNSPlatformSetAllowSleep(m, allowSleep, reason);
4823#endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
4824	}
4825
4826mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
4827	{
4828	const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
4829	const int sps = intf->NextSPSAttempt / 3;
4830	AuthRecord *rr;
4831
4832	if (!intf->SPSAddr[sps].type)
4833		{
4834		intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
4835		if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
4836			m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
4837		LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
4838		goto exit;
4839		}
4840
4841	// Mark our mDNS records (not unicast records) for transfer to SPS
4842	if (mDNSOpaque16IsZero(id))
4843		for (rr = m->ResourceRecords; rr; rr=rr->next)
4844			if (rr->resrec.RecordType > kDNSRecordTypeDeregistering)
4845				if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
4846					if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
4847						rr->SendRNow = mDNSInterfaceMark;	// mark it now
4848
4849	while (1)
4850		{
4851		mDNSu8 *p = m->omsg.data;
4852		// To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
4853		// For now we follow that same logic for SPS registrations too.
4854		// If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
4855		// initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
4856		InitializeDNSMessage(&m->omsg.h, mDNSOpaque16IsZero(id) ? mDNS_NewMessageID(m) : id, UpdateReqFlags);
4857
4858		for (rr = m->ResourceRecords; rr; rr=rr->next)
4859			if (rr->SendRNow || (!mDNSOpaque16IsZero(id) && !AuthRecord_uDNS(rr) && mDNSSameOpaque16(rr->updateid, id) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0))
4860				if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
4861					{
4862					mDNSu8 *newptr;
4863					const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
4864					if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
4865						rr->resrec.rrclass |= kDNSClass_UniqueRRSet;	// Temporarily set the 'unique' bit so PutResourceRecord will set it
4866					newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
4867					rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;		// Make sure to clear 'unique' bit back to normal state
4868					if (!newptr)
4869						LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
4870					else
4871						{
4872						LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, rr));
4873						rr->SendRNow       = mDNSNULL;
4874						rr->ThisAPInterval = mDNSPlatformOneSecond;
4875						rr->LastAPTime     = m->timenow;
4876						rr->updateid       = m->omsg.h.id;
4877						if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4878							m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
4879						p = newptr;
4880						}
4881					}
4882
4883		if (!m->omsg.h.mDNS_numUpdates) break;
4884		else
4885			{
4886			AuthRecord opt;
4887			mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
4888			opt.resrec.rrclass    = NormalMaxDNSMessageData;
4889			opt.resrec.rdlength   = sizeof(rdataOPT) * 2;	// Two options in this OPT record
4890			opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
4891			opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
4892			opt.resrec.rdata->u.opt[0].optlen        = DNSOpt_LeaseData_Space - 4;
4893			opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
4894			if (!owner->HMAC.l[0])											// If no owner data,
4895				SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]);		// use our own interface information
4896			else															// otherwise, use the owner data we were given
4897				{
4898				opt.resrec.rdata->u.opt[1].u.owner = *owner;
4899				opt.resrec.rdata->u.opt[1].opt     = kDNSOpt_Owner;
4900				opt.resrec.rdata->u.opt[1].optlen  = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
4901				}
4902			LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
4903			p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4904			if (!p)
4905				LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
4906			else
4907				{
4908				mStatus err;
4909
4910				LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
4911					mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
4912				// if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID;	// For simulating packet loss
4913				err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL);
4914				if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
4915				if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv6 && intf->NetWakeResolve[sps].ThisQInterval == -1)
4916					{
4917					LogSPS("SendSPSRegistration %d %##s failed to send to IPv6 address; will try IPv4 instead", sps, intf->NetWakeResolve[sps].qname.c);
4918					intf->NetWakeResolve[sps].qtype = kDNSType_A;
4919					mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
4920					return;
4921					}
4922				}
4923			}
4924		}
4925
4926	intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10;		// If successful, update NextSPSAttemptTime
4927
4928exit:
4929	if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
4930	}
4931
4932mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
4933	{
4934	AuthRecord *ar;
4935	for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
4936		if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
4937	return mDNStrue;
4938	}
4939
4940mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
4941	{
4942	AuthRecord *ar;
4943	OwnerOptData owner = zeroOwner;
4944
4945	SendSPSRegistrationForOwner(m, intf, id, &owner);
4946
4947	for (ar = m->ResourceRecords; ar; ar=ar->next)
4948		{
4949		if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
4950			{
4951			owner = ar->WakeUp;
4952			SendSPSRegistrationForOwner(m, intf, id, &owner);
4953			}
4954		}
4955	}
4956
4957// RetrySPSRegistrations is called from SendResponses, with the lock held
4958mDNSlocal void RetrySPSRegistrations(mDNS *const m)
4959	{
4960	AuthRecord *rr;
4961	NetworkInterfaceInfo *intf;
4962
4963	// First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
4964	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4965		if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
4966			intf->NextSPSAttemptTime++;
4967
4968	// Retry any record registrations that are due
4969	for (rr = m->ResourceRecords; rr; rr=rr->next)
4970		if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4971			for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4972				if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID)
4973					{
4974					LogSPS("RetrySPSRegistrations: %s", ARDisplayString(m, rr));
4975					SendSPSRegistration(m, intf, rr->updateid);
4976					}
4977
4978	// For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
4979	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4980		if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
4981			intf->NextSPSAttempt++;
4982	}
4983
4984mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
4985	{
4986	NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
4987	int sps = (int)(question - intf->NetWakeResolve);
4988	(void)m;			// Unused
4989	LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
4990
4991	if (!AddRecord) return;												// Don't care about REMOVE events
4992	if (answer->rrtype != question->qtype) return;						// Don't care about CNAMEs
4993
4994	// if (answer->rrtype == kDNSType_AAAA && sps == 0) return;	// To test failing to resolve sleep proxy's address
4995
4996	if (answer->rrtype == kDNSType_SRV)
4997		{
4998		// 1. Got the SRV record; now look up the target host's IPv6 link-local address
4999		mDNS_StopQuery(m, question);
5000		intf->SPSPort[sps] = answer->rdata->u.srv.port;
5001		AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
5002		question->qtype = kDNSType_AAAA;
5003		mDNS_StartQuery(m, question);
5004		}
5005	else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
5006		{
5007		// 2. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
5008		mDNS_StopQuery(m, question);
5009		question->ThisQInterval = -1;
5010		intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
5011		intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
5012		mDNS_Lock(m);
5013		if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);	// If we're ready for this result, use it now
5014		mDNS_Unlock(m);
5015		}
5016	else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == 0)
5017		{
5018		// 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
5019		mDNS_StopQuery(m, question);
5020		LogSPS("NetWakeResolve: SPS %d %##s has no IPv6 address, will try IPv4 instead", sps, question->qname.c);
5021		question->qtype = kDNSType_A;
5022		mDNS_StartQuery(m, question);
5023		}
5024	else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
5025		{
5026		// 4. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
5027		mDNS_StopQuery(m, question);
5028		question->ThisQInterval = -1;
5029		intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
5030		intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
5031		mDNS_Lock(m);
5032		if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);	// If we're ready for this result, use it now
5033		mDNS_Unlock(m);
5034		}
5035	}
5036
5037mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
5038	{
5039	AuthRecord *rr;
5040	for (rr = m->ResourceRecords; rr; rr=rr->next)
5041		if (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort))
5042			return mDNStrue;
5043	return mDNSfalse;
5044	}
5045
5046mDNSlocal void SendSleepGoodbyes(mDNS *const m)
5047	{
5048	AuthRecord *rr;
5049	m->SleepState = SleepState_Sleeping;
5050
5051#ifndef UNICAST_DISABLED
5052	SleepRecordRegistrations(m);	// If we have no SPS, need to deregister our uDNS records
5053#endif /* UNICAST_DISABLED */
5054
5055	// Mark all the records we need to deregister and send them
5056	for (rr = m->ResourceRecords; rr; rr=rr->next)
5057		if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
5058			rr->ImmedAnswer = mDNSInterfaceMark;
5059	SendResponses(m);
5060	}
5061
5062// BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
5063mDNSlocal void BeginSleepProcessing(mDNS *const m)
5064	{
5065	mDNSBool SendGoodbyes = mDNStrue;
5066	const CacheRecord *sps[3] = { mDNSNULL };
5067
5068	m->NextScheduledSPRetry = m->timenow;
5069
5070	if      (!m->SystemWakeOnLANEnabled)                  LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
5071	else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
5072	else	// If we have at least one advertised service
5073		{
5074		NetworkInterfaceInfo *intf;
5075		for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5076			{
5077			if (!intf->NetWake) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
5078#if APPLE_OSX_mDNSResponder
5079			else if (ActivateLocalProxy(m, intf->ifname) == mStatus_NoError)
5080				{
5081				SendGoodbyes = mDNSfalse;
5082				LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
5083				// This will leave m->SleepState set to SleepState_Transferring,
5084				// which is okay because with no outstanding resolves, or updates in flight,
5085				// mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
5086				}
5087#endif // APPLE_OSX_mDNSResponder
5088			else
5089				{
5090				FindSPSInCache(m, &intf->NetWakeBrowse, sps);
5091				if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
5092					intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
5093				else
5094					{
5095					int i;
5096					SendGoodbyes = mDNSfalse;
5097					intf->NextSPSAttempt = 0;
5098					intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
5099					// Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
5100					for (i=0; i<3; i++)
5101						{
5102#if ForceAlerts
5103						if (intf->SPSAddr[i].type)
5104							{ LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); *(long*)0 = 0; }
5105						if (intf->NetWakeResolve[i].ThisQInterval >= 0)
5106							{ LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); *(long*)0 = 0; }
5107#endif
5108						intf->SPSAddr[i].type = mDNSAddrType_None;
5109						if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
5110						intf->NetWakeResolve[i].ThisQInterval = -1;
5111						if (sps[i])
5112							{
5113							LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
5114							mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
5115							intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
5116							mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
5117							}
5118						}
5119					}
5120				}
5121			}
5122		}
5123
5124	if (SendGoodbyes)	// If we didn't find even one Sleep Proxy
5125		{
5126		LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
5127		SendSleepGoodbyes(m);
5128		}
5129	}
5130
5131// Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
5132// Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
5133// Normally, the platform support layer below mDNSCore should call this, not the client layer above.
5134mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
5135	{
5136	AuthRecord *rr;
5137
5138	LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
5139
5140	if (sleep && !m->SleepState)		// Going to sleep
5141		{
5142		mDNS_Lock(m);
5143		// If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
5144		if (m->SPSSocket)
5145			{
5146			mDNSu8 oldstate = m->SPSState;
5147			mDNS_DropLockBeforeCallback();		// mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
5148			m->SPSState = 2;
5149			if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
5150			mDNS_ReclaimLockAfterCallback();
5151			}
5152
5153		m->SleepState = SleepState_Transferring;
5154		if (m->SystemWakeOnLANEnabled && m->DelaySleep)
5155			{
5156			// If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
5157			LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
5158			m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
5159			}
5160		else
5161			{
5162			m->DelaySleep = 0;
5163			m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
5164			BeginSleepProcessing(m);
5165			}
5166
5167#ifndef UNICAST_DISABLED
5168		SuspendLLQs(m);
5169#endif
5170		mDNS_Unlock(m);
5171		// RemoveAutoTunnel6Record needs to be called outside the lock, as it grabs the lock also.
5172#if APPLE_OSX_mDNSResponder
5173		RemoveAutoTunnel6Record(m);
5174#endif
5175		LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
5176			m->SleepState == SleepState_Transferring ? "Transferring" :
5177			m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?", m->SleepSeqNum);
5178		}
5179	else if (!sleep)		// Waking up
5180		{
5181		mDNSu32 slot;
5182		CacheGroup *cg;
5183		CacheRecord *cr;
5184		NetworkInterfaceInfo *intf;
5185
5186		mDNS_Lock(m);
5187		// Reset SleepLimit back to 0 now that we're awake again.
5188		m->SleepLimit = 0;
5189
5190		// If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
5191		if (m->SleepState != SleepState_Awake)
5192			{
5193			m->SleepState = SleepState_Awake;
5194			m->SleepSeqNum++;
5195			// If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
5196			// then we enforce a minimum delay of 16 seconds before we begin sleep processing.
5197			// This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
5198			// before we make our determination of whether there's a Sleep Proxy out there we should register with.
5199			m->DelaySleep = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 16);
5200			}
5201
5202		if (m->SPSState == 3)
5203			{
5204			m->SPSState = 0;
5205			mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower);
5206			}
5207
5208		// In case we gave up waiting and went to sleep before we got an ack from the Sleep Proxy,
5209		// on wake we go through our record list and clear updateid back to zero
5210		for (rr = m->ResourceRecords; rr; rr=rr->next) rr->updateid = zeroID;
5211
5212		// ... and the same for NextSPSAttempt
5213		for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
5214
5215		// Restart unicast and multicast queries
5216		mDNSCoreRestartQueries(m);
5217
5218		// and reactivtate service registrations
5219		m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
5220		LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
5221
5222		// 2. Re-validate our cache records
5223		FORALL_CACHERECORDS(slot, cg, cr)
5224			mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
5225
5226		// 3. Retrigger probing and announcing for all our authoritative records
5227		for (rr = m->ResourceRecords; rr; rr=rr->next)
5228			if (AuthRecord_uDNS(rr))
5229				{
5230				ActivateUnicastRegistration(m, rr);
5231				}
5232			else
5233				{
5234				if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5235				rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5236				rr->AnnounceCount  = InitialAnnounceCount;
5237				rr->SendNSECNow    = mDNSNULL;
5238				InitializeLastAPTime(m, rr);
5239				}
5240
5241		// 4. Refresh NAT mappings
5242		// We don't want to have to assume that all hardware can necessarily keep accurate
5243		// track of passage of time while asleep, so on wake we refresh our NAT mappings
5244		// We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
5245		// When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
5246		// mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
5247		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
5248		m->retryGetAddr         = m->timenow + mDNSPlatformOneSecond * 5;
5249		LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m->retryGetAddr - m->timenow, m->timenow);
5250		RecreateNATMappings(m);
5251		mDNS_Unlock(m);
5252		}
5253	}
5254
5255mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
5256	{
5257	DNSQuestion *q;
5258	AuthRecord *rr;
5259	NetworkInterfaceInfo *intf;
5260
5261	mDNS_Lock(m);
5262
5263	if (m->DelaySleep) goto notready;
5264
5265	// If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
5266	if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
5267
5268	m->NextScheduledSPRetry = now + 0x40000000UL;
5269
5270	// See if we might need to retransmit any lost Sleep Proxy Registrations
5271	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5272		if (intf->NextSPSAttempt >= 0)
5273			{
5274			if (now - intf->NextSPSAttemptTime >= 0)
5275				{
5276				LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
5277					intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
5278				SendSPSRegistration(m, intf, zeroID);
5279				// Don't need to "goto notready" here, because if we do still have record registrations
5280				// that have not been acknowledged yet, we'll catch that in the record list scan below.
5281				}
5282			else
5283				if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
5284					m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
5285			}
5286
5287	// Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
5288	for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5289		{
5290		int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
5291		if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
5292			{
5293			LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
5294				intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
5295			goto spsnotready;
5296			}
5297		}
5298
5299	// Scan list of registered records
5300	for (rr = m->ResourceRecords; rr; rr = rr->next)
5301		if (!AuthRecord_uDNS(rr))
5302			if (!mDNSOpaque16IsZero(rr->updateid))
5303				{ LogSPS("mDNSCoreReadyForSleep: waiting for SPS Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto spsnotready; }
5304
5305	// Scan list of private LLQs, and make sure they've all completed their handshake with the server
5306	for (q = m->Questions; q; q = q->next)
5307		if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
5308			{
5309			LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5310			goto notready;
5311			}
5312
5313	// Scan list of registered records
5314	for (rr = m->ResourceRecords; rr; rr = rr->next)
5315		if (AuthRecord_uDNS(rr))
5316			{
5317			if (rr->state == regState_Refresh && rr->tcp)
5318				{ LogSPS("mDNSCoreReadyForSleep: waiting for Record Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto notready; }
5319			#if APPLE_OSX_mDNSResponder
5320			if (!RecordReadyForSleep(m, rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
5321			#endif
5322			}
5323
5324	mDNS_Unlock(m);
5325	return mDNStrue;
5326
5327spsnotready:
5328
5329	// If we failed to complete sleep proxy registration within ten seconds, we give up on that
5330	// and allow up to ten seconds more to complete wide-area deregistration instead
5331	if (now - m->SleepLimit >= 0)
5332		{
5333		LogMsg("Failed to register with SPS, now sending goodbyes");
5334
5335		for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5336			if (intf->NetWakeBrowse.ThisQInterval >= 0)
5337				{
5338				LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
5339					intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
5340				mDNS_DeactivateNetWake_internal(m, intf);
5341				}
5342
5343		for (rr = m->ResourceRecords; rr; rr = rr->next)
5344			if (!AuthRecord_uDNS(rr))
5345				if (!mDNSOpaque16IsZero(rr->updateid))
5346					{
5347					LogSPS("ReadyForSleep clearing updateid for %s", ARDisplayString(m, rr));
5348					rr->updateid = zeroID;
5349					}
5350
5351		// We'd really like to allow up to ten seconds more here,
5352		// but if we don't respond to the sleep notification within 30 seconds
5353		// we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
5354		// Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
5355		// more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
5356		// If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
5357		m->SleepLimit = now + mDNSPlatformOneSecond * 1;
5358
5359		SendSleepGoodbyes(m);
5360		}
5361
5362notready:
5363	mDNS_Unlock(m);
5364	return mDNSfalse;
5365	}
5366
5367mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
5368	{
5369	AuthRecord *ar;
5370
5371	// Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
5372	// failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
5373	// E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
5374	// and if that happens we don't want to just give up and go back to sleep and never try again.
5375	mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond);		// Sleep for at most 120 minutes
5376
5377	NATTraversalInfo *nat;
5378	for (nat = m->NATTraversals; nat; nat=nat->next)
5379		if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
5380			{
5381			mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10;		// Wake up when 90% of the way to the expiry time
5382			if (e - t > 0) e = t;
5383			LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
5384				nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
5385				mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
5386				nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5387				nat->retryInterval / mDNSPlatformOneSecond,
5388				nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5389				(t - now) / mDNSPlatformOneSecond);
5390			}
5391
5392	// This loop checks both the time we need to renew wide-area registrations,
5393	// and the time we need to renew Sleep Proxy registrations
5394	for (ar = m->ResourceRecords; ar; ar = ar->next)
5395		if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
5396			{
5397			mDNSs32 t = ar->expire - (ar->expire - now) / 10;		// Wake up when 90% of the way to the expiry time
5398			if (e - t > 0) e = t;
5399			LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
5400				ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
5401				(ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5402				ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5403				(t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
5404			}
5405
5406	return(e - now);
5407	}
5408
5409// ***************************************************************************
5410#if COMPILER_LIKES_PRAGMA_MARK
5411#pragma mark -
5412#pragma mark - Packet Reception Functions
5413#endif
5414
5415#define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
5416
5417mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
5418	const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
5419	{
5420	mDNSu8          *responseptr     = response->data;
5421	const mDNSu8    *const limit     = response->data + sizeof(response->data);
5422	const mDNSu8    *ptr             = query->data;
5423	AuthRecord  *rr;
5424	mDNSu32          maxttl = 0x70000000;
5425	int i;
5426
5427	// Initialize the response fields so we can answer the questions
5428	InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
5429
5430	// ***
5431	// *** 1. Write out the list of questions we are actually going to answer with this packet
5432	// ***
5433	if (LegacyQuery)
5434		{
5435		maxttl = kStaticCacheTTL;
5436		for (i=0; i<query->h.numQuestions; i++)						// For each question...
5437			{
5438			DNSQuestion q;
5439			ptr = getQuestion(query, ptr, end, InterfaceID, &q);	// get the question...
5440			if (!ptr) return(mDNSNULL);
5441
5442			for (rr=ResponseRecords; rr; rr=rr->NextResponse)		// and search our list of proposed answers
5443				{
5444				if (rr->NR_AnswerTo == ptr)							// If we're going to generate a record answering this question
5445					{												// then put the question in the question section
5446					responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
5447					if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
5448					break;		// break out of the ResponseRecords loop, and go on to the next question
5449					}
5450				}
5451			}
5452
5453		if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
5454		}
5455
5456	// ***
5457	// *** 2. Write Answers
5458	// ***
5459	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5460		if (rr->NR_AnswerTo)
5461			{
5462			mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
5463				maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5464			if (p) responseptr = p;
5465			else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
5466			}
5467
5468	// ***
5469	// *** 3. Write Additionals
5470	// ***
5471	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5472		if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
5473			{
5474			mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
5475				maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
5476			if (p) responseptr = p;
5477			else debugf("GenerateUnicastResponse: No more space for additionals");
5478			}
5479
5480	return(responseptr);
5481	}
5482
5483// AuthRecord *our is our Resource Record
5484// CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
5485// Returns 0 if there is no conflict
5486// Returns +1 if there was a conflict and we won
5487// Returns -1 if there was a conflict and we lost and have to rename
5488mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
5489	{
5490	mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
5491	mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
5492	if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
5493	if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
5494
5495	ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
5496	pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
5497	while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
5498	if (ourptr >= ourend && pktptr >= pktend) return(0);			// If data identical, not a conflict
5499
5500	if (ourptr >= ourend) return(-1);								// Our data ran out first; We lost
5501	if (pktptr >= pktend) return(+1);								// Packet data ran out first; We won
5502	if (*pktptr > *ourptr) return(-1);								// Our data is numerically lower; We lost
5503	if (*pktptr < *ourptr) return(+1);								// Packet data is numerically lower; We won
5504
5505	LogMsg("CompareRData ERROR: Invalid state");
5506	return(-1);
5507	}
5508
5509// See if we have an authoritative record that's identical to this packet record,
5510// whose canonical DependentOn record is the specified master record.
5511// The DependentOn pointer is typically used for the TXT record of service registrations
5512// It indicates that there is no inherent conflict detection for the TXT record
5513// -- it depends on the SRV record to resolve name conflicts
5514// If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
5515// pointer chain (if any) to make sure we reach the canonical DependentOn record
5516// If the record has no DependentOn, then just return that record's pointer
5517// Returns NULL if we don't have any local RRs that are identical to the one from the packet
5518mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
5519	{
5520	const AuthRecord *r1;
5521	for (r1 = m->ResourceRecords; r1; r1=r1->next)
5522		{
5523		if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
5524			{
5525			const AuthRecord *r2 = r1;
5526			while (r2->DependentOn) r2 = r2->DependentOn;
5527			if (r2 == master) return(mDNStrue);
5528			}
5529		}
5530	for (r1 = m->DuplicateRecords; r1; r1=r1->next)
5531		{
5532		if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
5533			{
5534			const AuthRecord *r2 = r1;
5535			while (r2->DependentOn) r2 = r2->DependentOn;
5536			if (r2 == master) return(mDNStrue);
5537			}
5538		}
5539	return(mDNSfalse);
5540	}
5541
5542// Find the canonical RRSet pointer for this RR received in a packet.
5543// If we find any identical AuthRecord in our authoritative list, then follow its RRSet
5544// pointers (if any) to make sure we return the canonical member of this name/type/class
5545// Returns NULL if we don't have any local RRs that are identical to the one from the packet
5546mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
5547	{
5548	const AuthRecord *rr;
5549	for (rr = m->ResourceRecords; rr; rr=rr->next)
5550		{
5551		if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
5552			{
5553			while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
5554			return(rr);
5555			}
5556		}
5557	return(mDNSNULL);
5558	}
5559
5560// PacketRRConflict is called when we've received an RR (pktrr) which has the same name
5561// as one of our records (our) but different rdata.
5562// 1. If our record is not a type that's supposed to be unique, we don't care.
5563// 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
5564// 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
5565//     points to our record, ignore this conflict (e.g. the packet record matches one of our
5566//     TXT records, and that record is marked as dependent on 'our', its SRV record).
5567// 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
5568//    are members of the same RRSet, then this is not a conflict.
5569mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
5570	{
5571	// If not supposed to be unique, not a conflict
5572	if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
5573
5574	// If a dependent record, not a conflict
5575	if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
5576	else
5577		{
5578		// If the pktrr matches a member of ourset, not a conflict
5579		const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
5580		const AuthRecord *pktset = FindRRSet(m, pktrr);
5581		if (pktset == ourset) return(mDNSfalse);
5582
5583		// For records we're proxying, where we don't know the full
5584		// relationship between the records, having any matching record
5585		// in our AuthRecords list is sufficient evidence of non-conflict
5586		if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
5587		}
5588
5589	// Okay, this is a conflict
5590	return(mDNStrue);
5591	}
5592
5593// Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
5594// the record list and/or question list.
5595// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5596mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
5597	DNSQuestion *q, AuthRecord *our)
5598	{
5599	int i;
5600	const mDNSu8 *ptr = LocateAuthorities(query, end);
5601	mDNSBool FoundUpdate = mDNSfalse;
5602
5603	for (i = 0; i < query->h.numAuthorities; i++)
5604		{
5605		ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
5606		if (!ptr) break;
5607		if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
5608			{
5609			FoundUpdate = mDNStrue;
5610			if (PacketRRConflict(m, our, &m->rec.r))
5611				{
5612				int result          = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
5613				if (!result) result = (int)our->resrec.rrtype  - (int)m->rec.r.resrec.rrtype;
5614				if (!result) result = CompareRData(our, &m->rec.r);
5615				if (result)
5616					{
5617					const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
5618					LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
5619					LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
5620					}
5621				// 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.
5622				// Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
5623				// If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
5624				if (result < 0)
5625					{
5626					m->SuppressProbes   = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
5627					our->ProbeCount     = DefaultProbeCountForTypeUnique;
5628					our->AnnounceCount  = InitialAnnounceCount;
5629					InitializeLastAPTime(m, our);
5630					goto exit;
5631					}
5632				}
5633#if 0
5634			else
5635				{
5636				LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
5637				LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign:  %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
5638				}
5639#endif
5640			}
5641		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
5642		}
5643	if (!FoundUpdate)
5644		LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
5645exit:
5646	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
5647	}
5648
5649mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
5650	{
5651	mDNSu32 slot = HashSlot(pktrr->name);
5652	CacheGroup *cg = CacheGroupForRecord(m, slot, pktrr);
5653	CacheRecord *rr;
5654	mDNSBool match;
5655	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
5656		{
5657		match = !pktrr->InterfaceID ? pktrr->rDNSServer == rr->resrec.rDNSServer : pktrr->InterfaceID == rr->resrec.InterfaceID;
5658		if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
5659		}
5660	return(rr);
5661	}
5662
5663// Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
5664// to check our lists and discard any stale duplicates of this record we already have
5665mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
5666	{
5667	if (m->CurrentRecord)
5668		LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5669	m->CurrentRecord = thelist;
5670	while (m->CurrentRecord)
5671		{
5672		AuthRecord *const rr = m->CurrentRecord;
5673		if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
5674			if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
5675				{
5676				LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
5677					m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
5678				rr->WakeUp.HMAC = zeroEthAddr;	// Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
5679				rr->RequireGoodbye = mDNSfalse;	// and we don't want to send goodbye for it
5680				mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5681				SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
5682				}
5683		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5684		// new records could have been added to the end of the list as a result of that call.
5685		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5686			m->CurrentRecord = rr->next;
5687		}
5688	}
5689
5690// Called from ProcessQuery when we get an mDNS packet with an owner record in it
5691mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
5692	{
5693	if (m->CurrentRecord)
5694		LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5695	m->CurrentRecord = thelist;
5696	while (m->CurrentRecord)
5697		{
5698		AuthRecord *const rr = m->CurrentRecord;
5699		if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
5700			if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
5701				{
5702				if (rr->AddressProxy.type == mDNSAddrType_IPv6)
5703					{
5704					// We don't do this here because we know that the host is waking up at this point, so we don't send
5705					// Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
5706					// saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
5707					#if MDNS_USE_Unsolicited_Neighbor_Advertisements
5708					LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
5709						&rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
5710					SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
5711					#endif
5712					}
5713				LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
5714					m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
5715					&rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
5716				if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
5717				rr->WakeUp.HMAC = zeroEthAddr;	// Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
5718				rr->RequireGoodbye = mDNSfalse;	// and we don't want to send goodbye for it, since real host is now back and functional
5719				mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5720				SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
5721				}
5722		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5723		// new records could have been added to the end of the list as a result of that call.
5724		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5725			m->CurrentRecord = rr->next;
5726		}
5727	}
5728
5729// ProcessQuery examines a received query to see if we have any answers to give
5730mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
5731	const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
5732	mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
5733	{
5734	mDNSBool      FromLocalSubnet    = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
5735	AuthRecord   *ResponseRecords    = mDNSNULL;
5736	AuthRecord  **nrp                = &ResponseRecords;
5737	CacheRecord  *ExpectedAnswers    = mDNSNULL;			// Records in our cache we expect to see updated
5738	CacheRecord **eap                = &ExpectedAnswers;
5739	DNSQuestion  *DupQuestions       = mDNSNULL;			// Our questions that are identical to questions in this packet
5740	DNSQuestion **dqp                = &DupQuestions;
5741	mDNSs32       delayresponse      = 0;
5742	mDNSBool      SendLegacyResponse = mDNSfalse;
5743	const mDNSu8 *ptr;
5744	mDNSu8       *responseptr        = mDNSNULL;
5745	AuthRecord   *rr;
5746	int i;
5747
5748	// ***
5749	// *** 1. Look in Additional Section for an OPT record
5750	// ***
5751	ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
5752	if (ptr)
5753		{
5754		ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
5755		if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
5756			{
5757			const rdataOPT *opt;
5758			const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
5759			// Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
5760			// delete all our own AuthRecords (which are identified by having zero MAC tags on them).
5761			for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
5762				if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
5763					{
5764					ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
5765					ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
5766					}
5767			}
5768		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
5769		}
5770
5771	// ***
5772	// *** 2. Parse Question Section and mark potential answers
5773	// ***
5774	ptr = query->data;
5775	for (i=0; i<query->h.numQuestions; i++)						// For each question...
5776		{
5777		mDNSBool QuestionNeedsMulticastResponse;
5778		int NumAnswersForThisQuestion = 0;
5779		AuthRecord *NSECAnswer = mDNSNULL;
5780		DNSQuestion pktq, *q;
5781		ptr = getQuestion(query, ptr, end, InterfaceID, &pktq);	// get the question...
5782		if (!ptr) goto exit;
5783
5784		// The only queries that *need* a multicast response are:
5785		// * Queries sent via multicast
5786		// * from port 5353
5787		// * that don't have the kDNSQClass_UnicastResponse bit set
5788		// These queries need multicast responses because other clients will:
5789		// * suppress their own identical questions when they see these questions, and
5790		// * expire their cache records if they don't see the expected responses
5791		// For other queries, we may still choose to send the occasional multicast response anyway,
5792		// to keep our neighbours caches warm, and for ongoing conflict detection.
5793		QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
5794		// Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
5795		pktq.qclass &= ~kDNSQClass_UnicastResponse;
5796
5797		// Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
5798		// can result in user callbacks which may change the record list and/or question list.
5799		// Also note: we just mark potential answer records here, without trying to build the
5800		// "ResponseRecords" list, because we don't want to risk user callbacks deleting records
5801		// from that list while we're in the middle of trying to build it.
5802		if (m->CurrentRecord)
5803			LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5804		m->CurrentRecord = m->ResourceRecords;
5805		while (m->CurrentRecord)
5806			{
5807			rr = m->CurrentRecord;
5808			m->CurrentRecord = rr->next;
5809			if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
5810				{
5811				if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
5812					{
5813					if (rr->resrec.RecordType == kDNSRecordTypeUnique)
5814						ResolveSimultaneousProbe(m, query, end, &pktq, rr);
5815					else if (ResourceRecordIsValidAnswer(rr))
5816						{
5817						NumAnswersForThisQuestion++;
5818						// Note: We should check here if this is a probe-type query, and if so, generate an immediate
5819						// unicast answer back to the source, because timeliness in answering probes is important.
5820
5821						// Notes:
5822						// NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
5823						// NR_AnswerTo == (mDNSu8*)~1             means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
5824						// NR_AnswerTo == (mDNSu8*)~0             means "definitely answer via multicast" (can't downgrade to unicast later)
5825						// If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
5826						// but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
5827						// then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
5828						if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
5829							{
5830							// We only mark this question for sending if it is at least one second since the last time we multicast it
5831							// on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
5832							// This is to guard against the case where someone blasts us with queries as fast as they can.
5833							if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
5834								(rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
5835								rr->NR_AnswerTo = (mDNSu8*)~0;
5836							}
5837						else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : (mDNSu8*)~1;
5838						}
5839					}
5840				else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
5841					{
5842					// If we don't have any answers for this question, but we do own another record with the same name,
5843					// then we'll want to mark it to generate an NSEC record on this interface
5844					if (!NSECAnswer) NSECAnswer = rr;
5845					}
5846				}
5847			}
5848
5849		if (NumAnswersForThisQuestion == 0 && NSECAnswer)
5850			{
5851			NumAnswersForThisQuestion++;
5852			NSECAnswer->SendNSECNow = InterfaceID;
5853			m->NextScheduledResponse = m->timenow;
5854			}
5855
5856		// If we couldn't answer this question, someone else might be able to,
5857		// so use random delay on response to reduce collisions
5858		if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond;	// Divided by 50 = 20ms
5859
5860#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5861		if (QuestionNeedsMulticastResponse)
5862#else
5863		// We only do the following accelerated cache expiration and duplicate question suppression processing
5864		// for non-truncated multicast queries with multicast responses.
5865		// For any query generating a unicast response we don't do this because we can't assume we will see the response.
5866		// For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
5867		// known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
5868		if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
5869#endif
5870			{
5871			const mDNSu32 slot = HashSlot(&pktq.qname);
5872			CacheGroup *cg = CacheGroupForName(m, slot, pktq.qnamehash, &pktq.qname);
5873			CacheRecord *cr;
5874
5875			// Make a list indicating which of our own cache records we expect to see updated as a result of this query
5876			// Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5877#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5878			if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5879#endif
5880				for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5881					if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
5882						if (!cr->NextInKAList && eap != &cr->NextInKAList)
5883							{
5884							*eap = cr;
5885							eap = &cr->NextInKAList;
5886#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5887							if (cr->MPUnansweredQ == 0 || m->timenow - cr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
5888								{
5889								// Although MPUnansweredQ is only really used for multi-packet query processing,
5890								// we increment it for both single-packet and multi-packet queries, so that it stays in sync
5891								// with the MPUnansweredKA value, which by necessity is incremented for both query types.
5892								cr->MPUnansweredQ++;
5893								cr->MPLastUnansweredQT = m->timenow;
5894								cr->MPExpectingKA = mDNStrue;
5895								}
5896#endif
5897							}
5898
5899			// Check if this question is the same as any of mine.
5900			// We only do this for non-truncated queries. Right now it would be too complicated to try
5901			// to keep track of duplicate suppression state between multiple packets, especially when we
5902			// can't guarantee to receive all of the Known Answer packets that go with a particular query.
5903#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5904			if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5905#endif
5906				for (q = m->Questions; q; q=q->next)
5907					if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
5908						if (!q->InterfaceID || q->InterfaceID == InterfaceID)
5909							if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
5910								if (q->qtype == pktq.qtype &&
5911									q->qclass == pktq.qclass &&
5912									q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
5913									{ *dqp = q; dqp = &q->NextInDQList; }
5914			}
5915		}
5916
5917	// ***
5918	// *** 3. Now we can safely build the list of marked answers
5919	// ***
5920	for (rr = m->ResourceRecords; rr; rr=rr->next)				// Now build our list of potential answers
5921		if (rr->NR_AnswerTo)									// If we marked the record...
5922			AddRecordToResponseList(&nrp, rr, mDNSNULL);		// ... add it to the list
5923
5924	// ***
5925	// *** 4. Add additional records
5926	// ***
5927	AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
5928
5929	// ***
5930	// *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
5931	// ***
5932	for (i=0; i<query->h.numAnswers; i++)						// For each record in the query's answer section...
5933		{
5934		// Get the record...
5935		CacheRecord *ourcacherr;
5936		ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
5937		if (!ptr) goto exit;
5938		if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
5939			{
5940			// See if this Known-Answer suppresses any of our currently planned answers
5941			for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5942				if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5943					{ rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
5944
5945			// See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5946			for (rr=m->ResourceRecords; rr; rr=rr->next)
5947				{
5948				// If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5949				if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5950					{
5951					if (srcaddr->type == mDNSAddrType_IPv4)
5952						{
5953						if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
5954						}
5955					else if (srcaddr->type == mDNSAddrType_IPv6)
5956						{
5957						if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
5958						}
5959					if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
5960						{
5961						rr->ImmedAnswer  = mDNSNULL;
5962						rr->ImmedUnicast = mDNSfalse;
5963	#if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5964						LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
5965	#endif
5966						}
5967					}
5968				}
5969
5970			ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
5971
5972	#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5973			// See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5974			// 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).
5975			if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
5976				{
5977				ourcacherr->MPUnansweredKA++;
5978				ourcacherr->MPExpectingKA = mDNSfalse;
5979				}
5980	#endif
5981
5982			// Having built our ExpectedAnswers list from the questions in this packet, we then remove
5983			// any records that are suppressed by the Known Answer list in this packet.
5984			eap = &ExpectedAnswers;
5985			while (*eap)
5986				{
5987				CacheRecord *cr = *eap;
5988				if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
5989					{ *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
5990				else eap = &cr->NextInKAList;
5991				}
5992
5993			// See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5994			if (!ourcacherr)
5995				{
5996				dqp = &DupQuestions;
5997				while (*dqp)
5998					{
5999					DNSQuestion *q = *dqp;
6000					if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
6001						{ *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
6002					else dqp = &q->NextInDQList;
6003					}
6004				}
6005			}
6006		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6007		}
6008
6009	// ***
6010	// *** 6. Cancel any additionals that were added because of now-deleted records
6011	// ***
6012	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6013		if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
6014			{ rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
6015
6016	// ***
6017	// *** 7. Mark the send flags on the records we plan to send
6018	// ***
6019	for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6020		{
6021		if (rr->NR_AnswerTo)
6022			{
6023			mDNSBool SendMulticastResponse = mDNSfalse;		// Send modern multicast response
6024			mDNSBool SendUnicastResponse   = mDNSfalse;		// Send modern unicast response (not legacy unicast response)
6025
6026			// If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
6027			if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0)
6028				{
6029				SendMulticastResponse = mDNStrue;
6030				// If this record was marked for modern (delayed) unicast response, then mark it as promoted to
6031				// multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
6032				// If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
6033				if (rr->NR_AnswerTo == (mDNSu8*)~1) rr->NR_AnswerTo = (mDNSu8*)~0;
6034				}
6035
6036			// If the client insists on a multicast response, then we'd better send one
6037			if      (rr->NR_AnswerTo == (mDNSu8*)~0) SendMulticastResponse = mDNStrue;
6038			else if (rr->NR_AnswerTo == (mDNSu8*)~1) SendUnicastResponse   = mDNStrue;
6039			else if (rr->NR_AnswerTo)                SendLegacyResponse    = mDNStrue;
6040
6041			if (SendMulticastResponse || SendUnicastResponse)
6042				{
6043#if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6044				rr->ImmedAnswerMarkTime = m->timenow;
6045#endif
6046				m->NextScheduledResponse = m->timenow;
6047				// If we're already planning to send this on another interface, just send it on all interfaces
6048				if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
6049					rr->ImmedAnswer = mDNSInterfaceMark;
6050				else
6051					{
6052					rr->ImmedAnswer = InterfaceID;			// Record interface to send it on
6053					if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
6054					if (srcaddr->type == mDNSAddrType_IPv4)
6055						{
6056						if      (mDNSIPv4AddressIsZero(rr->v4Requester))                rr->v4Requester = srcaddr->ip.v4;
6057						else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
6058						}
6059					else if (srcaddr->type == mDNSAddrType_IPv6)
6060						{
6061						if      (mDNSIPv6AddressIsZero(rr->v6Requester))                rr->v6Requester = srcaddr->ip.v6;
6062						else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
6063						}
6064					}
6065				}
6066			// If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
6067			// so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
6068			// else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
6069			// else, for a simple unique record reply, we can reply immediately; no need for delay
6070			if      (query->h.flags.b[0] & kDNSFlag0_TC)            delayresponse = mDNSPlatformOneSecond * 20;	// Divided by 50 = 400ms
6071			else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond;		// Divided by 50 = 20ms
6072			}
6073		else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == (mDNSu8*)~0)
6074			{
6075			// Since additional records are an optimization anyway, we only ever send them on one interface at a time
6076			// If two clients on different interfaces do queries that invoke the same optional additional answer,
6077			// then the earlier client is out of luck
6078			rr->ImmedAdditional = InterfaceID;
6079			// No need to set m->NextScheduledResponse here
6080			// We'll send these additional records when we send them, or not, as the case may be
6081			}
6082		}
6083
6084	// ***
6085	// *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
6086	// ***
6087	if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
6088		{
6089#if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6090		mDNSs32 oldss = m->SuppressSending;
6091		if (oldss && delayresponse)
6092			LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
6093#endif
6094		// Pick a random delay:
6095		// We start with the base delay chosen above (typically either 1 second or 20 seconds),
6096		// and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
6097		// This is an integer value, with resolution determined by the platform clock rate.
6098		// We then divide that by 50 to get the delay value in ticks. We defer the division until last
6099		// to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
6100		// The +49 before dividing is to ensure we round up, not down, to ensure that even
6101		// on platforms where the native clock rate is less than fifty ticks per second,
6102		// we still guarantee that the final calculated delay is at least one platform tick.
6103		// We want to make sure we don't ever allow the delay to be zero ticks,
6104		// because if that happens we'll fail the Bonjour Conformance Test.
6105		// Our final computed delay is 20-120ms for normal delayed replies,
6106		// or 400-500ms in the case of multi-packet known-answer lists.
6107		m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
6108		if (m->SuppressSending == 0) m->SuppressSending = 1;
6109#if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6110		if (oldss && delayresponse)
6111			LogMsg("Set     SuppressSending to   %5ld", m->SuppressSending - m->timenow);
6112#endif
6113		}
6114
6115	// ***
6116	// *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
6117	// ***
6118	if (SendLegacyResponse)
6119		responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
6120
6121exit:
6122	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6123
6124	// ***
6125	// *** 10. Finally, clear our link chains ready for use next time
6126	// ***
6127	while (ResponseRecords)
6128		{
6129		rr = ResponseRecords;
6130		ResponseRecords = rr->NextResponse;
6131		rr->NextResponse    = mDNSNULL;
6132		rr->NR_AnswerTo     = mDNSNULL;
6133		rr->NR_AdditionalTo = mDNSNULL;
6134		}
6135
6136	while (ExpectedAnswers)
6137		{
6138		CacheRecord *cr = ExpectedAnswers;
6139		ExpectedAnswers = cr->NextInKAList;
6140		cr->NextInKAList = mDNSNULL;
6141
6142		// For non-truncated queries, we can definitively say that we should expect
6143		// to be seeing a response for any records still left in the ExpectedAnswers list
6144		if (!(query->h.flags.b[0] & kDNSFlag0_TC))
6145			if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond)
6146				{
6147				cr->UnansweredQueries++;
6148				cr->LastUnansweredTime = m->timenow;
6149#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6150				if (cr->UnansweredQueries > 1)
6151					debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
6152						cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6153#endif
6154				SetNextCacheCheckTimeForRecord(m, cr);
6155				}
6156
6157		// If we've seen multiple unanswered queries for this record,
6158		// then mark it to expire in five seconds if we don't get a response by then.
6159		if (cr->UnansweredQueries >= MaxUnansweredQueries)
6160			{
6161#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6162			// Only show debugging message if this record was not about to expire anyway
6163			if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6164				debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6165					cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6166#endif
6167			mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
6168			}
6169#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6170		// Make a guess, based on the multi-packet query / known answer counts, whether we think we
6171		// should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
6172		// possible packet loss of up to 20% of the additional KA packets.)
6173		else if (cr->MPUnansweredQ * 4 > cr->MPUnansweredKA * 5 + 8)
6174			{
6175			// We want to do this conservatively.
6176			// If there are so many machines on the network that they have to use multi-packet known-answer lists,
6177			// then we don't want them to all hit the network simultaneously with their final expiration queries.
6178			// By setting the record to expire in four minutes, we achieve two things:
6179			// (a) the 90-95% final expiration queries will be less bunched together
6180			// (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
6181			mDNSu32 remain = (mDNSu32)(RRExpireTime(cr) - m->timenow) / 4;
6182			if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
6183				remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
6184
6185			// Only show debugging message if this record was not about to expire anyway
6186			if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
6187				debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6188					cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
6189
6190			if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
6191				cr->UnansweredQueries++;	// Treat this as equivalent to one definite unanswered query
6192			cr->MPUnansweredQ  = 0;			// Clear MPQ/MPKA statistics
6193			cr->MPUnansweredKA = 0;
6194			cr->MPExpectingKA  = mDNSfalse;
6195
6196			if (remain < kDefaultReconfirmTimeForNoAnswer)
6197				remain = kDefaultReconfirmTimeForNoAnswer;
6198			mDNS_Reconfirm_internal(m, cr, remain);
6199			}
6200#endif
6201		}
6202
6203	while (DupQuestions)
6204		{
6205		DNSQuestion *q = DupQuestions;
6206		DupQuestions = q->NextInDQList;
6207		q->NextInDQList = mDNSNULL;
6208		i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
6209		debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
6210			srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
6211		}
6212
6213	return(responseptr);
6214	}
6215
6216mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
6217	const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6218	const mDNSInterfaceID InterfaceID)
6219	{
6220	mDNSu8    *responseend = mDNSNULL;
6221	mDNSBool   QueryWasLocalUnicast = srcaddr && dstaddr &&
6222		!mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6223
6224	if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
6225		{
6226		LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6227			"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
6228			srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6229			msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
6230			msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
6231			msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
6232			msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
6233		return;
6234		}
6235
6236	verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6237		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6238		srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6239		msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
6240		msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
6241		msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
6242		msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
6243
6244	responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
6245		!mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
6246
6247	if (responseend)	// If responseend is non-null, that means we built a unicast response packet
6248		{
6249		debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
6250			m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
6251			m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
6252			m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
6253			srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
6254		mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL);
6255		}
6256	}
6257
6258#if 0
6259mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
6260	{
6261	DNSServer *s;
6262	(void)m; // Unused
6263	(void)srcaddr; // Unused
6264	for (s = m->DNSServers; s; s = s->next)
6265		if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
6266	return(mDNSfalse);
6267	}
6268#endif
6269
6270struct UDPSocket_struct
6271	{
6272	mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
6273	};
6274
6275mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
6276	{
6277	DNSQuestion *q;
6278	for (q = m->Questions; q; q=q->next)
6279		{
6280		if (!tcp && !q->LocalSocket) continue;
6281		if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port)     &&
6282			mDNSSameOpaque16(q->TargetQID,         id)       &&
6283			q->qtype                  == question->qtype     &&
6284			q->qclass                 == question->qclass    &&
6285			q->qnamehash              == question->qnamehash &&
6286			SameDomainName(&q->qname, &question->qname))
6287			return(q);
6288		}
6289	return(mDNSNULL);
6290	}
6291
6292// This function is called when we receive a unicast response. This could be the case of a unicast response from the
6293// DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
6294mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
6295	const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
6296	{
6297	DNSQuestion *q;
6298	(void)id;
6299	(void)srcaddr;
6300
6301	for (q = m->Questions; q; q=q->next)
6302		{
6303		if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
6304			{
6305			if (!mDNSOpaque16IsZero(q->TargetQID))
6306				{
6307				debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
6308
6309				if (mDNSSameOpaque16(q->TargetQID, id))
6310					{
6311					mDNSIPPort srcp;
6312					if (!tcp)
6313						{
6314						srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
6315						}
6316					else
6317						{
6318						srcp = q->tcpSrcPort;
6319						}
6320					if (mDNSSameIPPort(srcp, port)) return(q);
6321
6322				//	if (mDNSSameAddress(srcaddr, &q->Target))                   return(mDNStrue);
6323				//	if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
6324				//	if (TrustedSource(m, srcaddr))                              return(mDNStrue);
6325					LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
6326						q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
6327					return(mDNSNULL);
6328					}
6329				}
6330			else
6331				{
6332				if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
6333					return(q);
6334				}
6335			}
6336		}
6337	return(mDNSNULL);
6338	}
6339
6340// Certain data types need more space for in-memory storage than their in-packet rdlength would imply
6341// Currently this applies only to rdata types containing more than one domainname,
6342// or types where the domainname is not the last item in the structure.
6343// In addition, NSEC currently requires less space for in-memory storage than its in-packet representation.
6344mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
6345	{
6346	switch (rr->rrtype)
6347		{
6348		case kDNSType_SOA: return sizeof(rdataSOA);
6349		case kDNSType_RP:  return sizeof(rdataRP);
6350		case kDNSType_PX:  return sizeof(rdataPX);
6351		case kDNSType_NSEC:return sizeof(rdataNSEC);
6352		default:           return rr->rdlength;
6353		}
6354	}
6355
6356mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay)
6357	{
6358	CacheRecord *rr = mDNSNULL;
6359	mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
6360
6361	if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
6362
6363	//if (RDLength > InlineCacheRDSize)
6364	//	LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
6365
6366	if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec);	// If we don't have a CacheGroup for this name, make one now
6367	if (cg)  rr = GetCacheRecord(m, cg, RDLength);	// Make a cache record, being careful not to recycle cg
6368	if (!rr) NoCacheAnswer(m, &m->rec.r);
6369	else
6370		{
6371		RData *saveptr = rr->resrec.rdata;		// Save the rr->resrec.rdata pointer
6372		*rr = m->rec.r;							// Block copy the CacheRecord object
6373		rr->resrec.rdata  = saveptr;				// Restore rr->resrec.rdata after the structure assignment
6374		rr->resrec.name   = cg->name;			// And set rr->resrec.name to point into our CacheGroup header
6375		rr->DelayDelivery = delay;
6376
6377		// If this is an oversized record with external storage allocated, copy rdata to external storage
6378		if      (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
6379			LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
6380		else 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		if (RDLength > InlineCacheRDSize)
6383			mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
6384
6385		rr->next = mDNSNULL;					// Clear 'next' pointer
6386		*(cg->rrcache_tail) = rr;				// Append this record to tail of cache slot list
6387		cg->rrcache_tail = &(rr->next);			// Advance tail pointer
6388
6389		CacheRecordAdd(m, rr);	// CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
6390		}
6391	return(rr);
6392	}
6393
6394mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
6395	{
6396	rr->TimeRcvd             = m->timenow;
6397	rr->resrec.rroriginalttl = ttl;
6398	rr->UnansweredQueries = 0;
6399#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6400	rr->MPUnansweredQ     = 0;
6401	rr->MPUnansweredKA    = 0;
6402	rr->MPExpectingKA     = mDNSfalse;
6403#endif
6404	SetNextCacheCheckTimeForRecord(m, rr);
6405	}
6406
6407mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
6408	{
6409	CacheRecord *rr;
6410	const mDNSu32 slot = HashSlot(&q->qname);
6411	CacheGroup *cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
6412	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6413		if (rr->CRActiveQuestion == q)
6414			{
6415			//LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
6416			RefreshCacheRecord(m, rr, lease);
6417			}
6418	}
6419
6420mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl)		// TTL in seconds
6421	{
6422	if      (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
6423	else if (LLQType == uDNS_LLQ_Events)
6424		{
6425		// If the TTL is -1 for uDNS LLQ event packet, that means "remove"
6426		if (ttl == 0xFFFFFFFF) ttl = 0;
6427		else                   ttl = kLLQ_DefLease;
6428		}
6429	else	// else not LLQ (standard uDNS response)
6430		{
6431		// The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
6432		// also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
6433		if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
6434
6435		// Adjustment factor to avoid race condition:
6436		// 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.
6437		// If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
6438		// 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
6439		// To avoid this, we extend the record's effective TTL to give it a little extra grace period.
6440		// We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
6441		// the cached copy at our local caching server will already have expired, so the server will be forced
6442		// to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
6443		ttl += ttl/4 + 2;
6444
6445		// For mDNS, TTL zero means "delete this record"
6446		// For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
6447		// For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
6448		// This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
6449		// respectively, and then if we get no response, delete the record from the cache at 15 seconds.
6450		// This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
6451		// and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
6452		// (with the current code) result in the server having even less than three seconds to respond
6453		// before we deleted the record and reported a "remove" event to any active questions.
6454		// Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
6455		// then things really break (e.g. we end up making a negative cache entry).
6456		// In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
6457		if (ttl < 15) ttl = 15;
6458		}
6459
6460	return ttl;
6461	}
6462
6463// Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
6464// the record list and/or question list.
6465// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6466// InterfaceID non-NULL tells us the interface this multicast response was received on
6467// InterfaceID NULL tells us this was a unicast response
6468// dstaddr NULL tells us we received this over an outgoing TCP connection we made
6469mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
6470	const DNSMessage *const response, const mDNSu8 *end,
6471	const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6472	const mDNSInterfaceID InterfaceID)
6473	{
6474	int i;
6475	mDNSBool ResponseMCast    = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
6476	mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
6477	DNSQuestion *llqMatch = mDNSNULL;
6478	uDNS_LLQType LLQType      = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
6479
6480	// "(CacheRecord*)1" is a special (non-zero) end-of-list marker
6481	// We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
6482	// set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
6483	CacheRecord *CacheFlushRecords = (CacheRecord*)1;
6484	CacheRecord **cfp = &CacheFlushRecords;
6485
6486	// All records in a DNS response packet are treated as equally valid statements of truth. If we want
6487	// to guard against spoof responses, then the only credible protection against that is cryptographic
6488	// security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
6489	int firstauthority  =                   response->h.numAnswers;
6490	int firstadditional = firstauthority  + response->h.numAuthorities;
6491	int totalrecords    = firstadditional + response->h.numAdditionals;
6492	const mDNSu8 *ptr   = response->data;
6493	DNSServer *uDNSServer = mDNSNULL;
6494
6495	debugf("Received Response from %#-15a addressed to %#-15a on %p with "
6496		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
6497		srcaddr, dstaddr, InterfaceID,
6498		response->h.numQuestions,   response->h.numQuestions   == 1 ? ", "   : "s,",
6499		response->h.numAnswers,     response->h.numAnswers     == 1 ? ", "   : "s,",
6500		response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
6501		response->h.numAdditionals, response->h.numAdditionals == 1 ? " "    : "s", end - response->data, LLQType);
6502
6503	// According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
6504	//    When a DNS client receives a reply with TC
6505	//    set, it should ignore that response, and query again, using a
6506	//    mechanism, such as a TCP connection, that will permit larger replies.
6507	// It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
6508	// delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
6509	// failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
6510	// <rdar://problem/6690034> Can't bind to Active Directory
6511	// In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
6512	// abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
6513	// Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
6514	// and not even do the TCP query.
6515	// Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
6516	if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC)) return;
6517
6518	if (LLQType == uDNS_LLQ_Ignore) return;
6519
6520	// 1. We ignore questions (if any) in mDNS response packets
6521	// 2. If this is an LLQ response, we handle it much the same
6522	// 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
6523	//    answer as being the authoritative complete RRSet, and respond by deleting all other
6524	//    matching cache records that don't appear in this packet.
6525	// Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
6526	if (ResponseMCast || LLQType == uDNS_LLQ_Events || (response->h.flags.b[0] & kDNSFlag0_TC))
6527		ptr = LocateAnswers(response, end);
6528	// Otherwise, for one-shot queries, any answers in our cache that are not also contained
6529	// in this response packet are immediately deemed to be invalid.
6530	else
6531		{
6532		mDNSu8 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
6533		mDNSBool failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
6534		mDNSBool returnEarly = mDNSfalse;
6535		// We could possibly combine this with the similar loop at the end of this function --
6536		// instead of tagging cache records here and then rescuing them if we find them in the answer section,
6537		// we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
6538		// which it was received (or refreshed), and then at the end if we find any cache records which
6539		// answer questions in this packet's question section, but which aren't tagged with this packet's
6540		// packet number, then we deduce they are old and delete them
6541		for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
6542			{
6543			DNSQuestion q, *qptr = mDNSNULL;
6544			ptr = getQuestion(response, ptr, end, InterfaceID, &q);
6545			if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
6546				{
6547				if (!failure)
6548					{
6549					CacheRecord *rr;
6550					const mDNSu32 slot = HashSlot(&q.qname);
6551					CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
6552					for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6553						if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
6554							{
6555							debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
6556								rr->resrec.InterfaceID, CRDisplayString(m, rr));
6557							// Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
6558							rr->TimeRcvd          = m->timenow - TicksTTL(rr) - 1;
6559							rr->UnansweredQueries = MaxUnansweredQueries;
6560							}
6561					}
6562				else
6563					{
6564					if (qptr)
6565						{
6566						LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
6567						PenalizeDNSServer(m, qptr);
6568						}
6569					returnEarly = mDNStrue;
6570					}
6571				}
6572			}
6573		if (returnEarly)
6574			{
6575			LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
6576				response->h.numAnswers,     response->h.numAnswers     == 1 ? ", " : "s,",
6577				response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
6578				response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
6579			// not goto exit because we won't have any CacheFlushRecords and we do not want to
6580			// generate negative cache entries (we want to query the next server)
6581			return;
6582			}
6583		}
6584
6585	for (i = 0; i < totalrecords && ptr && ptr < end; i++)
6586		{
6587		// All responses sent via LL multicast are acceptable for caching
6588		// All responses received over our outbound TCP connections are acceptable for caching
6589		mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType;
6590		// (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
6591		// to any specific question -- any code reading records from the cache needs to make that determination for itself.)
6592
6593		const mDNSu8 RecordType =
6594			(i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns  :
6595			(i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
6596		ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
6597		if (!ptr) goto exit;		// Break out of the loop and clean up our CacheFlushRecords list before exiting
6598		if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) { m->rec.r.resrec.RecordType = 0; continue; }
6599
6600		// Don't want to cache OPT or TSIG pseudo-RRs
6601		if (m->rec.r.resrec.rrtype == kDNSType_TSIG) { m->rec.r.resrec.RecordType = 0; continue; }
6602		if (m->rec.r.resrec.rrtype == kDNSType_OPT)
6603			{
6604			const rdataOPT *opt;
6605			const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
6606			// Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
6607			// delete all our own AuthRecords (which are identified by having zero MAC tags on them).
6608			for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
6609				if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
6610					{
6611					ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
6612					ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
6613					}
6614			m->rec.r.resrec.RecordType = 0;
6615			continue;
6616			}
6617
6618		// if a CNAME record points to itself, then don't add it to the cache
6619		if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
6620			{
6621			LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
6622			m->rec.r.resrec.RecordType = 0;
6623			continue;
6624			}
6625
6626		// When we receive uDNS LLQ responses, we assume a long cache lifetime --
6627		// In the case of active LLQs, we'll get remove events when the records actually do go away
6628		// In the case of polling LLQs, we assume the record remains valid until the next poll
6629		if (!mDNSOpaque16IsZero(response->h.id))
6630			m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
6631
6632		// If response was not sent via LL multicast,
6633		// then see if it answers a recent query of ours, which would also make it acceptable for caching.
6634		if (!ResponseMCast)
6635			{
6636			if (LLQType)
6637				{
6638				// For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
6639				// Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
6640				// queries to get ADD/RMV events. To lookup the question, we can't use
6641				// ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
6642				// has already matched the question using the 64 bit Id in the packet and we use that here.
6643
6644				if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
6645				}
6646			else if (!AcceptableResponse || !dstaddr)
6647				{
6648				// For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
6649				// that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
6650				// Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
6651				// we create.
6652
6653				DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
6654
6655				// Intialize the DNS server on the resource record which will now filter what questions we answer with
6656				// this record.
6657				//
6658				// We could potentially lookup the DNS server based on the source address, but that may not work always
6659				// and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
6660				// from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
6661				// on the "id" and "source port", then this response answers the question and assume the response
6662				// came from the same DNS server that we sent the query to.
6663
6664				if (q != mDNSNULL)
6665					{
6666					AcceptableResponse = mDNStrue;
6667					if (!InterfaceID)
6668						{
6669						debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
6670						m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
6671						}
6672					}
6673				else
6674					{
6675					// If we can't find a matching question, we need to see whether we have seen records earlier that matched
6676					// the question. The code below does that. So, make this record unacceptable for now
6677					if (!InterfaceID)
6678						{
6679						debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
6680						AcceptableResponse = mDNSfalse;
6681						}
6682					}
6683				}
6684			}
6685
6686		// 1. Check that this packet resource record does not conflict with any of ours
6687		if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
6688			{
6689			if (m->CurrentRecord)
6690				LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
6691			m->CurrentRecord = m->ResourceRecords;
6692			while (m->CurrentRecord)
6693				{
6694				AuthRecord *rr = m->CurrentRecord;
6695				m->CurrentRecord = rr->next;
6696				// We accept all multicast responses, and unicast responses resulting from queries we issued
6697				// For other unicast responses, this code accepts them only for responses with an
6698				// (apparently) local source address that pertain to a record of our own that's in probing state
6699				if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
6700
6701				if (PacketRRMatchesSignature(&m->rec.r, rr))		// If interface, name, type (if shared record) and class match...
6702					{
6703					// ... check to see if type and rdata are identical
6704					if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
6705						{
6706						// If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
6707						if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
6708							{
6709							// If we were planning to send on this -- and only this -- interface, then we don't need to any more
6710							if      (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
6711							}
6712						else
6713							{
6714							if      (rr->ImmedAnswer == mDNSNULL)    { rr->ImmedAnswer = InterfaceID;       m->NextScheduledResponse = m->timenow; }
6715							else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
6716							}
6717						}
6718					// else, the packet RR has different type or different rdata -- check to see if this is a conflict
6719					else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
6720						{
6721						LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
6722						LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->     resrec.rdatahash, ARDisplayString(m, rr));
6723
6724						// If this record is marked DependentOn another record for conflict detection purposes,
6725						// then *that* record has to be bumped back to probing state to resolve the conflict
6726						if (rr->DependentOn)
6727							{
6728							while (rr->DependentOn) rr = rr->DependentOn;
6729							LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->     resrec.rdatahash, ARDisplayString(m, rr));
6730							}
6731
6732						// If we've just whacked this record's ProbeCount, don't need to do it again
6733						if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
6734							LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
6735						else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
6736							LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
6737						else
6738							{
6739							LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
6740							// If we'd previously verified this record, put it back to probing state and try again
6741							if (rr->resrec.RecordType == kDNSRecordTypeVerified)
6742								{
6743								LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
6744								rr->resrec.RecordType     = kDNSRecordTypeUnique;
6745								// We set ProbeCount to one more than the usual value so we know we've already touched this record.
6746								// This is because our single probe for "example-name.local" could yield a response with (say) two A records and
6747								// three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
6748								// This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
6749								rr->ProbeCount     = DefaultProbeCountForTypeUnique + 1;
6750								rr->AnnounceCount  = InitialAnnounceCount;
6751								InitializeLastAPTime(m, rr);
6752								RecordProbeFailure(m, rr);	// Repeated late conflicts also cause us to back off to the slower probing rate
6753								}
6754							// If we're probing for this record, we just failed
6755							else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
6756								{
6757								LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
6758								mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6759								}
6760							// We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
6761							// same machine giving different answers for the reverse mapping record, or there are two machines on the
6762							// network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
6763							// to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
6764							// record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
6765							else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
6766								{
6767								LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
6768								mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6769								}
6770							else
6771								LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
6772							}
6773						}
6774					// Else, matching signature, different type or rdata, but not a considered a conflict.
6775					// If the packet record has the cache-flush bit set, then we check to see if we
6776					// have any record(s) of the same type that we should re-assert to rescue them
6777					// (see note about "multi-homing and bridged networks" at the end of this function).
6778					else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
6779						if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
6780							{ rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
6781					}
6782				}
6783			}
6784
6785		if (!AcceptableResponse)
6786			{
6787			const CacheRecord *cr;
6788			for (cr = CacheFlushRecords; cr != (CacheRecord*)1; cr = cr->NextInCFList)
6789				{
6790				domainname *target = GetRRDomainNameTarget(&cr->resrec);
6791				// When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
6792				// match the question and we already created a cache entry in the previous pass of this loop. Now when we process
6793				// the A record, it does not match the question because the record name here is the CNAME. Hence we try to
6794				// match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
6795				// DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
6796
6797				if (target && cr->resrec.rdatahash == m->rec.r.resrec.namehash && SameDomainName(target, m->rec.r.resrec.name))
6798					{
6799					debugf("mDNSCoreReceiveResponse: Found a matching entry for %##s in the CacheFlushRecords", m->rec.r.resrec.name->c);
6800					AcceptableResponse = mDNStrue;
6801					m->rec.r.resrec.rDNSServer = uDNSServer;
6802					break;
6803					}
6804				}
6805			}
6806
6807		// 2. See if we want to add this packet resource record to our cache
6808		// We only try to cache answers if we have a cache to put them in
6809		// Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
6810		if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
6811		if (m->rrcache_size && AcceptableResponse)
6812			{
6813			const mDNSu32 slot = HashSlot(m->rec.r.resrec.name);
6814			CacheGroup *cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
6815			CacheRecord *rr;
6816
6817			// 2a. Check if this packet resource record is already in our cache
6818			for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6819				{
6820				mDNSBool match = !InterfaceID ? m->rec.r.resrec.rDNSServer == rr->resrec.rDNSServer : rr->resrec.InterfaceID == InterfaceID;
6821				// If we found this exact resource record, refresh its TTL
6822				if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
6823					{
6824					if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
6825						verbosedebugf("Found record size %5d interface %p already in cache: %s",
6826							m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
6827
6828					if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6829						{
6830						// If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
6831						if (rr->NextInCFList == mDNSNULL && cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
6832							{ *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6833
6834						// If this packet record is marked unique, and our previous cached copy was not, then fix it
6835						if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
6836							{
6837							DNSQuestion *q;
6838							for (q = m->Questions; q; q=q->next) if (ResourceRecordAnswersQuestion(&rr->resrec, q)) q->UniqueAnswers++;
6839							rr->resrec.RecordType = m->rec.r.resrec.RecordType;
6840							}
6841						}
6842
6843					if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
6844						{
6845						// If the rdata of the packet record differs in name capitalization from the record in our cache
6846						// then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
6847						// a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
6848						// <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
6849						rr->resrec.rroriginalttl = 0;
6850						rr->TimeRcvd = m->timenow;
6851						rr->UnansweredQueries = MaxUnansweredQueries;
6852						SetNextCacheCheckTimeForRecord(m, rr);
6853						LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m,rr));
6854						LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m,&m->rec.r));
6855						LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
6856							NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
6857						// DO NOT break out here -- we want to continue as if we never found it
6858						}
6859					else if (m->rec.r.resrec.rroriginalttl > 0)
6860						{
6861						DNSQuestion *q;
6862						//if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
6863						RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
6864
6865						// We have to reset the question interval to MaxQuestionInterval so that we don't keep
6866						// polling the network once we get a valid response back. For the first time when a new
6867						// cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
6868						// Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
6869						// configuration changed, without flushing the cache, we reset the question interval here.
6870						// Currently, we do this for for both multicast and unicast questions as long as the record
6871						// type is unique. For unicast, resource record is always unique and for multicast it is
6872						// true for records like A etc. but not for PTR.
6873						if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6874							{
6875							for (q = m->Questions; q; q=q->next)
6876								{
6877								if (!q->DuplicateOf && !q->LongLived &&
6878									ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
6879									{
6880									q->LastQTime        = m->timenow;
6881									q->LastQTxTime      = m->timenow;
6882									q->RecentAnswerPkts = 0;
6883									q->ThisQInterval    = MaxQuestionInterval;
6884									q->RequestUnicast   = mDNSfalse;
6885									q->unansweredQueries = 0;
6886									debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
6887									break;		// Why break here? Aren't there other questions we might want to look at?-- SC July 2010
6888									}
6889								}
6890							}
6891						break;
6892						}
6893					else
6894						{
6895						// If the packet TTL is zero, that means we're deleting this record.
6896						// To give other hosts on the network a chance to protest, we push the deletion
6897						// out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
6898						// Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
6899						// lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
6900						// If record's current expiry time is more than a second from now, we set it to expire in one second.
6901						// If the record is already going to expire in less than one second anyway, we leave it alone --
6902						// we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
6903						debugf("DE for %s", CRDisplayString(m, rr));
6904						if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
6905							{
6906							rr->resrec.rroriginalttl = 1;
6907							rr->TimeRcvd = m->timenow;
6908							rr->UnansweredQueries = MaxUnansweredQueries;
6909							SetNextCacheCheckTimeForRecord(m, rr);
6910							}
6911						break;
6912						}
6913					}
6914				}
6915
6916			// If packet resource record not in our cache, add it now
6917			// (unless it is just a deletion of a record we never had, in which case we don't care)
6918			if (!rr && m->rec.r.resrec.rroriginalttl > 0)
6919				{
6920				const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
6921				const mDNSs32 delay = AddToCFList ? NonZeroTime(m->timenow + mDNSPlatformOneSecond) :
6922					CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash, slot);
6923				// If unique, assume we may have to delay delivery of this 'add' event.
6924				// Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
6925				// to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
6926				// to schedule an mDNS_Execute task at the appropriate time.
6927				rr = CreateNewCacheEntry(m, slot, cg, delay);
6928				if (rr)
6929					{
6930					if (AddToCFList) { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6931					else if (rr->DelayDelivery) ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
6932					}
6933				}
6934			}
6935		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6936		}
6937
6938exit:
6939	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
6940
6941	// If we've just received one or more records with their cache flush bits set,
6942	// then scan that cache slot to see if there are any old stale records we need to flush
6943	while (CacheFlushRecords != (CacheRecord*)1)
6944		{
6945		CacheRecord *r1 = CacheFlushRecords, *r2;
6946		const mDNSu32 slot = HashSlot(r1->resrec.name);
6947		const CacheGroup *cg = CacheGroupForRecord(m, slot, &r1->resrec);
6948		CacheFlushRecords = CacheFlushRecords->NextInCFList;
6949		r1->NextInCFList = mDNSNULL;
6950
6951		// Look for records in the cache with the same signature as this new one with the cache flush
6952		// bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
6953		// (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
6954		// We make these TTL adjustments *only* for records that still have *more* than one second
6955		// remaining to live. Otherwise, a record that we tagged for deletion half a second ago
6956		// (and now has half a second remaining) could inadvertently get its life extended, by either
6957		// (a) if we got an explicit goodbye packet half a second ago, the record would be considered
6958		// "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
6959		// or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
6960		// in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
6961		// If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
6962		// To avoid this, we need to ensure that the cache flushing operation will only act to
6963		// *decrease* a record's remaining lifetime, never *increase* it.
6964		for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
6965			// For Unicast (null InterfaceID) the DNSservers should also match
6966			if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
6967				(r1->resrec.InterfaceID || (r1->resrec.rDNSServer == r2->resrec.rDNSServer)) &&
6968				r1->resrec.rrtype      == r2->resrec.rrtype &&
6969				r1->resrec.rrclass     == r2->resrec.rrclass)
6970				{
6971				// If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
6972				// else, if record is old, mark it to be flushed
6973				if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
6974					{
6975					// If we find mismatched TTLs in an RRSet, correct them.
6976					// We only do this for records with a TTL of 2 or higher. It's possible to have a
6977					// goodbye announcement with the cache flush bit set (or a case-change on record rdata,
6978					// which we treat as a goodbye followed by an addition) and in that case it would be
6979					// inappropriate to synchronize all the other records to a TTL of 0 (or 1).
6980					// We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
6981					// because certain early Bonjour devices are known to have this specific mismatch, and
6982					// there's no point filling syslog with messages about something we already know about.
6983					// We also don't log this for uDNS responses, since a caching name server is obliged
6984					// to give us an aged TTL to correct for how long it has held the record,
6985					// so our received TTLs are expected to vary in that case
6986					if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
6987						{
6988						if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
6989							mDNSOpaque16IsZero(response->h.id))
6990							LogInfo("Correcting TTL from %4d to %4d for %s",
6991								r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
6992						r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
6993						}
6994					r2->TimeRcvd = m->timenow;
6995					}
6996				else				// else, if record is old, mark it to be flushed
6997					{
6998					verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
6999					verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
7000					// We set stale records to expire in one second.
7001					// This gives the owner a chance to rescue it if necessary.
7002					// This is important in the case of multi-homing and bridged networks:
7003					//   Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
7004					//   bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
7005					//   set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
7006					//   will promptly delete their cached copies of the (still valid) Ethernet IP address record.
7007					//   By delaying the deletion by one second, we give X a change to notice that this bridging has
7008					//   happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
7009
7010					// We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
7011					// final expiration queries for this record.
7012
7013					// If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
7014					// flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
7015					// one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
7016					// <rdar://problem/5636422> Updating TXT records is too slow
7017					// We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
7018					// which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
7019					if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
7020						{
7021						LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
7022						r2->resrec.rroriginalttl = 0;
7023						}
7024					else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
7025						{
7026						// We only set a record to expire in one second if it currently has *more* than a second to live
7027						// If it's already due to expire in a second or less, we just leave it alone
7028						r2->resrec.rroriginalttl = 1;
7029						r2->UnansweredQueries = MaxUnansweredQueries;
7030						r2->TimeRcvd = m->timenow - 1;
7031						// We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
7032						// that we marked for deletion via an explicit DE record
7033						}
7034					}
7035				SetNextCacheCheckTimeForRecord(m, r2);
7036				}
7037
7038		if (r1->DelayDelivery)	// If we were planning to delay delivery of this record, see if we still need to
7039			{
7040			r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash, slot);
7041			// If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
7042			if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
7043			else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
7044			}
7045		}
7046
7047	// See if we need to generate negative cache entries for unanswered unicast questions
7048	ptr = response->data;
7049	for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
7050		{
7051		DNSQuestion q;
7052		DNSQuestion *qptr = mDNSNULL;
7053		ptr = getQuestion(response, ptr, end, InterfaceID, &q);
7054		if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
7055			{
7056			CacheRecord *rr, *neg = mDNSNULL;
7057			mDNSu32 slot = HashSlot(&q.qname);
7058			CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
7059			for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7060				if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
7061					{
7062					// 1. If we got a fresh answer to this query, then don't need to generate a negative entry
7063					if (RRExpireTime(rr) - m->timenow > 0) break;
7064					// 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
7065					if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
7066					}
7067			// When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
7068			// Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
7069			// Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
7070			// (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
7071			// This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
7072			// suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
7073			// The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
7074			// *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
7075			// in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
7076			// negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
7077			if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
7078				{
7079				// If we did not find a positive answer and we can append search domains to this question,
7080				// generate a negative response (without creating a cache entry) to append search domains.
7081				if (qptr->AppendSearchDomains && !rr)
7082					{
7083					LogInfo("mDNSCoreReceiveResponse: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
7084					m->CurrentQuestion = qptr;
7085					GenerateNegativeResponse(m);
7086					m->CurrentQuestion = mDNSNULL;
7087					}
7088				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));
7089				}
7090			else
7091				{
7092				if (!rr)
7093					{
7094					// We start off assuming a negative caching TTL of 60 seconds
7095					// but then look to see if we can find an SOA authority record to tell us a better value we should be using
7096					mDNSu32 negttl = 60;
7097					int repeat = 0;
7098					const domainname *name = &q.qname;
7099					mDNSu32           hash = q.qnamehash;
7100
7101					// Special case for our special Microsoft Active Directory "local SOA" check.
7102					// Some cheap home gateways don't include an SOA record in the authority section when
7103					// they send negative responses, so we don't know how long to cache the negative result.
7104					// Because we don't want to keep hitting the root name servers with our query to find
7105					// if we're on a network using Microsoft Active Directory using "local" as a private
7106					// internal top-level domain, we make sure to cache the negative result for at least one day.
7107					if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
7108
7109					// If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
7110					if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
7111						{
7112						ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7113						if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
7114							{
7115							const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
7116							mDNSu32 ttl_s = soa->min;
7117							// We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
7118							// for the SOA record for ".", where the record is reported as non-cacheable
7119							// (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
7120							if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
7121								ttl_s = m->rec.r.resrec.rroriginalttl;
7122							if (negttl < ttl_s) negttl = ttl_s;
7123
7124							// Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
7125							// with an Authority Section SOA record for d.com, then this is a hint that the authority
7126							// is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
7127							// To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
7128							if (q.qtype == kDNSType_SOA)
7129								{
7130								int qcount = CountLabels(&q.qname);
7131								int scount = CountLabels(m->rec.r.resrec.name);
7132								if (qcount - 1 > scount)
7133									if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
7134										repeat = qcount - 1 - scount;
7135								}
7136							}
7137						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7138						}
7139
7140					// If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
7141					// the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
7142					// and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
7143					// of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
7144					// With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
7145					// so that we back off our polling rate and don't keep hitting the server continually.
7146					if (neg)
7147						{
7148						if (negttl < neg->resrec.rroriginalttl * 2)
7149							negttl = neg->resrec.rroriginalttl * 2;
7150						if (negttl > 3600)
7151							negttl = 3600;
7152						}
7153
7154					negttl = GetEffectiveTTL(LLQType, negttl);	// Add 25% grace period if necessary
7155
7156					// If we already had a negative cache entry just update it, else make one or more new negative cache entries
7157					if (neg)
7158						{
7159						debugf("Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
7160						RefreshCacheRecord(m, neg, negttl);
7161						}
7162					else while (1)
7163						{
7164						debugf("mDNSCoreReceiveResponse making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
7165						MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
7166						CreateNewCacheEntry(m, slot, cg, 0);	// We never need any delivery delay for these generated negative cache records
7167						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7168						if (!repeat) break;
7169						repeat--;
7170						name = (const domainname *)(name->c + 1 + name->c[0]);
7171						hash = DomainNameHashValue(name);
7172						slot = HashSlot(name);
7173						cg   = CacheGroupForName(m, slot, hash, name);
7174						}
7175					}
7176				}
7177			}
7178		}
7179	}
7180
7181// ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
7182// multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
7183// ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
7184// that warrants waking the sleeping host.
7185// ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
7186
7187mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
7188	{
7189	// We don't need to use the m->CurrentRecord mechanism here because the target HMAC is nonzero,
7190	// so all we're doing is marking the record to generate a few wakeup packets
7191	AuthRecord *rr;
7192	if (!e->l[0]) { LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero"); return; }
7193	for (rr = thelist; rr; rr = rr->next)
7194		if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
7195			{
7196			LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
7197			mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7198			}
7199	}
7200
7201mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
7202	{
7203	if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
7204	ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
7205	ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
7206	}
7207
7208mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
7209	{
7210	if (result && result != mStatus_MemFree)
7211		LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
7212
7213	if (result == mStatus_NameConflict)
7214		{
7215		mDNS_Lock(m);
7216		LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
7217		if (ar->WakeUp.HMAC.l[0])
7218			{
7219			SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password);	// Send one wakeup magic packet
7220			ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC);					// Schedule all other records with the same owner to be woken
7221			}
7222		mDNS_Unlock(m);
7223		}
7224
7225	if (result == mStatus_NameConflict || result == mStatus_MemFree)
7226		{
7227		m->ProxyRecords--;
7228		mDNSPlatformMemFree(ar);
7229		mDNS_UpdateAllowSleep(m);
7230		}
7231	}
7232
7233mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
7234	const DNSMessage *const msg, const mDNSu8 *end,
7235	const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
7236	const mDNSInterfaceID InterfaceID)
7237	{
7238	int i;
7239	AuthRecord opt;
7240	mDNSu8 *p = m->omsg.data;
7241	OwnerOptData owner = zeroOwner;		// Need to zero this, so we'll know if this Update packet was missing its Owner option
7242	mDNSu32 updatelease = 0;
7243	const mDNSu8 *ptr;
7244
7245	LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7246		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
7247		srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7248		msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
7249		msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
7250		msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
7251		msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
7252
7253	if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
7254
7255	if (mDNS_PacketLoggingEnabled)
7256		DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
7257
7258	ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
7259	if (ptr)
7260		{
7261		ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
7262		if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7263			{
7264			const rdataOPT *o;
7265			const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7266			for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
7267				{
7268				if      (o->opt == kDNSOpt_Lease)                         updatelease = o->u.updatelease;
7269				else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner       = o->u.owner;
7270				}
7271			}
7272		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7273		}
7274
7275	InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
7276
7277	if (!updatelease || !owner.HMAC.l[0])
7278		{
7279		static int msgs = 0;
7280		if (msgs < 100)
7281			{
7282			msgs++;
7283			LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
7284				!updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
7285			}
7286		m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
7287		}
7288	else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
7289		{
7290		static int msgs = 0;
7291		if (msgs < 100)
7292			{
7293			msgs++;
7294			LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
7295				m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
7296			}
7297		m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
7298		}
7299	else
7300		{
7301		LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
7302
7303		if (updatelease > 24 * 60 * 60)
7304			updatelease = 24 * 60 * 60;
7305
7306		if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
7307			updatelease = 0x40000000UL / mDNSPlatformOneSecond;
7308
7309		ptr = LocateAuthorities(msg, end);
7310		for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
7311			{
7312			ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7313			if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7314				{
7315				mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
7316				AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
7317				if (!ar) { m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; break; }
7318				else
7319					{
7320					mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
7321					m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
7322					ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords);	// Make sure we don't have any old stale duplicates of this record
7323					ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
7324					mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
7325					AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
7326					ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
7327					ar->resrec.rdata->MaxRDLength = RDLengthMem;
7328					mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
7329					ar->ForceMCast = mDNStrue;
7330					ar->WakeUp     = owner;
7331					if (m->rec.r.resrec.rrtype == kDNSType_PTR)
7332						{
7333						mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
7334						if      (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
7335						else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
7336						debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
7337						if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
7338						}
7339					ar->TimeRcvd   = m->timenow;
7340					ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
7341					if (m->NextScheduledSPS - ar->TimeExpire > 0)
7342						m->NextScheduledSPS = ar->TimeExpire;
7343					mDNS_Register_internal(m, ar);
7344					// Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
7345					// but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
7346					// Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
7347					// Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
7348					// new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
7349					if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
7350						if (ar->resrec.rrtype == kDNSType_AAAA) ar->resrec.rroriginalttl = 0;
7351					m->ProxyRecords++;
7352					mDNS_UpdateAllowSleep(m);
7353					LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
7354					}
7355				}
7356			m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7357			}
7358
7359		if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
7360			{
7361			LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
7362			ClearProxyRecords(m, &owner, m->DuplicateRecords);
7363			ClearProxyRecords(m, &owner, m->ResourceRecords);
7364			}
7365		else
7366			{
7367			mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
7368			opt.resrec.rrclass    = NormalMaxDNSMessageData;
7369			opt.resrec.rdlength   = sizeof(rdataOPT);	// One option in this OPT record
7370			opt.resrec.rdestimate = sizeof(rdataOPT);
7371			opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
7372			opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
7373			p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
7374			}
7375		}
7376
7377	if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
7378	}
7379
7380mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSInterfaceID InterfaceID)
7381	{
7382	if (InterfaceID)
7383		{
7384		mDNSu32 updatelease = 60 * 60;		// If SPS fails to indicate lease time, assume one hour
7385		const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
7386		if (ptr)
7387			{
7388			ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
7389			if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7390				{
7391				const rdataOPT *o;
7392				const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7393				for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
7394					if (o->opt == kDNSOpt_Lease)
7395						{
7396						updatelease = o->u.updatelease;
7397						LogSPS("Sleep Proxy granted lease time %4d seconds", updatelease);
7398						}
7399				}
7400			m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
7401			}
7402
7403		if (m->CurrentRecord)
7404			LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7405		m->CurrentRecord = m->ResourceRecords;
7406		while (m->CurrentRecord)
7407			{
7408			AuthRecord *const rr = m->CurrentRecord;
7409			if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
7410				if (mDNSSameOpaque16(rr->updateid, msg->h.id))
7411					{
7412					rr->updateid = zeroID;
7413					rr->expire   = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
7414					LogSPS("Sleep Proxy %s record %5d %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", updatelease, ARDisplayString(m,rr));
7415					if (rr->WakeUp.HMAC.l[0])
7416						{
7417						rr->WakeUp.HMAC = zeroEthAddr;	// Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7418						rr->RequireGoodbye = mDNSfalse;	// and we don't want to send goodbye for it
7419						mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7420						}
7421					}
7422			// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7423			// new records could have been added to the end of the list as a result of that call.
7424			if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7425				m->CurrentRecord = rr->next;
7426			}
7427		}
7428	// If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
7429	// may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
7430	if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
7431	}
7432
7433mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
7434	const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
7435	{
7436	if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
7437		{
7438		LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
7439#if ForceAlerts
7440		*(long*)0 = 0;
7441#endif
7442		}
7443
7444	// Create empty resource record
7445	cr->resrec.RecordType    = kDNSRecordTypePacketNegative;
7446	cr->resrec.InterfaceID   = InterfaceID;
7447	cr->resrec.rDNSServer	 = dnsserver;
7448	cr->resrec.name          = name;	// Will be updated to point to cg->name when we call CreateNewCacheEntry
7449	cr->resrec.rrtype        = rrtype;
7450	cr->resrec.rrclass       = rrclass;
7451	cr->resrec.rroriginalttl = ttl_seconds;
7452	cr->resrec.rdlength      = 0;
7453	cr->resrec.rdestimate    = 0;
7454	cr->resrec.namehash      = namehash;
7455	cr->resrec.rdatahash     = 0;
7456	cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
7457	cr->resrec.rdata->MaxRDLength = 0;
7458
7459	cr->NextInKAList       = mDNSNULL;
7460	cr->TimeRcvd           = m->timenow;
7461	cr->DelayDelivery      = 0;
7462	cr->NextRequiredQuery  = m->timenow;
7463	cr->LastUsed           = m->timenow;
7464	cr->CRActiveQuestion   = mDNSNULL;
7465	cr->UnansweredQueries  = 0;
7466	cr->LastUnansweredTime = 0;
7467#if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7468	cr->MPUnansweredQ      = 0;
7469	cr->MPLastUnansweredQT = 0;
7470	cr->MPUnansweredKA     = 0;
7471	cr->MPExpectingKA      = mDNSfalse;
7472#endif
7473	cr->NextInCFList       = mDNSNULL;
7474	}
7475
7476mDNSexport void mDNSCoreReceive(mDNS *const m, void *const pkt, const mDNSu8 *const end,
7477	const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
7478	const mDNSInterfaceID InterfaceID)
7479	{
7480	mDNSInterfaceID ifid = InterfaceID;
7481	DNSMessage  *msg  = (DNSMessage *)pkt;
7482	const mDNSu8 StdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_StdQuery;
7483	const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
7484	const mDNSu8 UpdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_Update;
7485	const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
7486	mDNSu8 QR_OP;
7487	mDNSu8 *ptr = mDNSNULL;
7488	mDNSBool TLS = (dstaddr == (mDNSAddr *)1);	// For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
7489	if (TLS) dstaddr = mDNSNULL;
7490
7491#ifndef UNICAST_DISABLED
7492	if (mDNSSameAddress(srcaddr, &m->Router))
7493		{
7494#ifdef _LEGACY_NAT_TRAVERSAL_
7495		if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
7496			{
7497			mDNS_Lock(m);
7498			LNT_ConfigureRouterInfo(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
7499			mDNS_Unlock(m);
7500			return;
7501			}
7502#endif
7503		if (mDNSSameIPPort(srcport, NATPMPPort))
7504			{
7505			mDNS_Lock(m);
7506			uDNS_ReceiveNATPMPPacket(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
7507			mDNS_Unlock(m);
7508			return;
7509			}
7510		}
7511#ifdef _LEGACY_NAT_TRAVERSAL_
7512	else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
7513#endif
7514
7515#endif
7516	if ((unsigned)(end - (mDNSu8 *)pkt) < sizeof(DNSMessageHeader))
7517		{
7518		LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt);
7519		return;
7520		}
7521	QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
7522	// Read the integer parts which are in IETF byte-order (MSB first, LSB second)
7523	ptr = (mDNSu8 *)&msg->h.numQuestions;
7524	msg->h.numQuestions   = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
7525	msg->h.numAnswers     = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
7526	msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
7527	msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
7528
7529	if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
7530
7531	// We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
7532	// If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
7533	if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
7534
7535	mDNS_Lock(m);
7536	m->PktNum++;
7537#ifndef UNICAST_DISABLED
7538	if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
7539		if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
7540			{
7541			ifid = mDNSInterface_Any;
7542			if (mDNS_PacketLoggingEnabled)
7543				DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
7544			uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
7545			// Note: mDNSCore also needs to get access to received unicast responses
7546			}
7547#endif
7548	if      (QR_OP == StdQ) mDNSCoreReceiveQuery   (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
7549	else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
7550	else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate  (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
7551	else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end,                                     InterfaceID);
7552	else
7553		{
7554		LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
7555			msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt, InterfaceID);
7556		if (mDNS_LoggingEnabled)
7557			{
7558			int i = 0;
7559			while (i<end - (mDNSu8 *)pkt)
7560				{
7561				char buffer[128];
7562				char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
7563				do if (i<end - (mDNSu8 *)pkt) p += mDNS_snprintf(p, sizeof(buffer), " %02X", ((mDNSu8 *)pkt)[i]); while (++i & 15);
7564				LogInfo("%s", buffer);
7565				}
7566			}
7567		}
7568	// Packet reception often causes a change to the task list:
7569	// 1. Inbound queries can cause us to need to send responses
7570	// 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
7571	// 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
7572	// 4. Response packets that answer questions may cause our client to issue new questions
7573	mDNS_Unlock(m);
7574	}
7575
7576// ***************************************************************************
7577#if COMPILER_LIKES_PRAGMA_MARK
7578#pragma mark -
7579#pragma mark - Searcher Functions
7580#endif
7581
7582// Targets are considered the same if both queries are untargeted, or
7583// if both are targeted to the same address+port
7584// (If Target address is zero, TargetPort is undefined)
7585#define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
7586	(mDNSSameAddress(&(A)->Target, &(B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
7587
7588// Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
7589// circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
7590// and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
7591// doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
7592// a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
7593//
7594// We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
7595// the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
7596// non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
7597// is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
7598// The main reason for this design is that cache entries point to a *single* question and that question is responsible
7599// for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
7600// breaks this design principle.
7601
7602// If IsLLQ(Q) is true, it means the question is both:
7603// (a) long-lived and
7604// (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
7605// for multicast questions, we don't want to treat LongLived as anything special
7606#define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
7607
7608mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
7609	{
7610	DNSQuestion *q;
7611	// Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
7612	// This prevents circular references, where two questions are each marked as a duplicate of the other.
7613	// Accordingly, we break out of the loop when we get to 'question', because there's no point searching
7614	// further in the list.
7615	for (q = m->Questions; q && q != question; q=q->next)		// Scan our list for another question
7616		if (q->InterfaceID == question->InterfaceID &&			// with the same InterfaceID,
7617			SameQTarget(q, question)                &&			// and same unicast/multicast target settings
7618			q->qtype      == question->qtype        &&			// type,
7619			q->qclass     == question->qclass       &&			// class,
7620			IsLLQ(q)      == IsLLQ(question)        &&			// and long-lived status matches
7621			(!q->AuthInfo || question->AuthInfo)    &&			// to avoid deadlock, don't make public query dup of a private one
7622			(q->SuppressQuery == question->SuppressQuery) &&	// Questions that are suppressed/not suppressed
7623			q->qnamehash  == question->qnamehash    &&
7624			SameDomainName(&q->qname, &question->qname))		// and name
7625			return(q);
7626	return(mDNSNULL);
7627	}
7628
7629// This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
7630mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
7631	{
7632	DNSQuestion *q;
7633	DNSQuestion *first = mDNSNULL;
7634
7635	// This is referring to some other question as duplicate. No other question can refer to this
7636	// question as a duplicate.
7637	if (question->DuplicateOf)
7638		{
7639		LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
7640			question, question->qname.c, DNSTypeName(question->qtype),
7641			question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
7642		return;
7643		}
7644
7645	for (q = m->Questions; q; q=q->next)		// Scan our list of questions
7646		if (q->DuplicateOf == question)			// To see if any questions were referencing this as their duplicate
7647			{
7648			q->DuplicateOf = first;
7649			if (!first)
7650				{
7651				first = q;
7652				// If q used to be a duplicate, but now is not,
7653				// then inherit the state from the question that's going away
7654				q->LastQTime         = question->LastQTime;
7655				q->ThisQInterval     = question->ThisQInterval;
7656				q->ExpectUnicastResp = question->ExpectUnicastResp;
7657				q->LastAnswerPktNum  = question->LastAnswerPktNum;
7658				q->RecentAnswerPkts  = question->RecentAnswerPkts;
7659				q->RequestUnicast    = question->RequestUnicast;
7660				q->LastQTxTime       = question->LastQTxTime;
7661				q->CNAMEReferrals    = question->CNAMEReferrals;
7662				q->nta               = question->nta;
7663				q->servAddr          = question->servAddr;
7664				q->servPort          = question->servPort;
7665				q->qDNSServer        = question->qDNSServer;
7666				q->validDNSServers   = question->validDNSServers;
7667				q->unansweredQueries = question->unansweredQueries;
7668				q->noServerResponse  = question->noServerResponse;
7669				q->triedAllServersOnce = question->triedAllServersOnce;
7670
7671				q->TargetQID         = question->TargetQID;
7672				q->LocalSocket       = question->LocalSocket;
7673
7674				q->state             = question->state;
7675			//	q->tcp               = question->tcp;
7676				q->ReqLease          = question->ReqLease;
7677				q->expire            = question->expire;
7678				q->ntries            = question->ntries;
7679				q->id                = question->id;
7680
7681				question->LocalSocket = mDNSNULL;
7682				question->nta        = mDNSNULL;	// If we've got a GetZoneData in progress, transfer it to the newly active question
7683			//	question->tcp        = mDNSNULL;
7684
7685				if (q->LocalSocket)
7686					debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7687
7688				if (q->nta)
7689					{
7690					LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7691					q->nta->ZoneDataContext = q;
7692					}
7693
7694				// Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
7695				if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
7696
7697				if (question->state == LLQ_Established)
7698					{
7699					LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7700					question->state = 0;	// Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
7701					}
7702
7703				SetNextQueryTime(m,q);
7704				}
7705			}
7706	}
7707
7708mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
7709	{
7710	McastResolver **p = &m->McastResolvers;
7711	McastResolver *tmp = mDNSNULL;
7712
7713	if (!d) d = (const domainname *)"";
7714
7715	LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
7716
7717	if (m->mDNS_busy != m->mDNS_reentrancy+1)
7718		LogMsg("mDNS_AddMcastResolver: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
7719
7720	while (*p)	// Check if we already have this {interface, domain} tuple registered
7721		{
7722		if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
7723			{
7724			if (!((*p)->flags & DNSServer_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
7725			(*p)->flags &= ~DNSServer_FlagDelete;
7726			tmp = *p;
7727			*p = tmp->next;
7728			tmp->next = mDNSNULL;
7729			}
7730		else
7731			p=&(*p)->next;
7732		}
7733
7734	if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
7735	else
7736		{
7737		// allocate, add to list
7738		*p = mDNSPlatformMemAllocate(sizeof(**p));
7739		if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
7740		else
7741			{
7742			(*p)->interface = interface;
7743			(*p)->flags     = DNSServer_FlagNew;
7744			(*p)->timeout   = timeout;
7745			AssignDomainName(&(*p)->domain, d);
7746			(*p)->next = mDNSNULL;
7747			}
7748		}
7749	return(*p);
7750	}
7751
7752mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
7753	{
7754	mDNSs32 ptime = 0;
7755	if (server->penaltyTime != 0)
7756		{
7757		ptime = server->penaltyTime - m->timenow;
7758		if (ptime < 0)
7759			{
7760			// This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
7761			// If it does not get reset in ResetDNSServerPenalties for some reason, we do it
7762			// here
7763			LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
7764				ptime, server->penaltyTime, m->timenow);
7765			server->penaltyTime = 0;
7766			ptime = 0;
7767			}
7768		}
7769	return ptime;
7770	}
7771
7772//Checks to see whether the newname is a better match for the name, given the best one we have
7773//seen so far (given in bestcount).
7774//Returns -1 if the newname is not a better match
7775//Returns 0 if the newname is the same as the old match
7776//Returns 1 if the newname is a better match
7777mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
7778	int bestcount)
7779	{
7780	// If the name contains fewer labels than the new server's domain or the new name
7781	// contains fewer labels than the current best, then it can't possibly be a better match
7782	if (namecount < newcount || newcount < bestcount) return -1;
7783
7784	// If there is no match, return -1 and the caller will skip this newname for
7785	// selection
7786	//
7787	// If we find a match and the number of labels is the same as bestcount, then
7788	// we return 0 so that the caller can do additional logic to pick one of
7789	// the best based on some other factors e.g., penaltyTime
7790	//
7791	// If we find a match and the number of labels is more than bestcount, then we
7792	// return 1 so that the caller can pick this over the old one.
7793	//
7794	// Note: newcount can either be equal or greater than bestcount beause of the
7795	// check above.
7796
7797	if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
7798		return bestcount == newcount ? 0 : 1;
7799	else
7800		return -1;
7801	}
7802
7803// Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
7804// can be queries that can forced to multicast (ForceMCast) even though they don't end in these
7805// names. In that case, we give a default timeout of 5 seconds
7806#define DEFAULT_MCAST_TIMEOUT	5
7807mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
7808	{
7809	McastResolver *curmatch = mDNSNULL;
7810	int bestmatchlen = -1, namecount = CountLabels(&question->qname);
7811	McastResolver *curr;
7812	int bettermatch, currcount;
7813	for (curr = m->McastResolvers; curr; curr = curr->next)
7814		{
7815		currcount = CountLabels(&curr->domain);
7816		bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
7817		// Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
7818		// the timeout value from the first one
7819		if (bettermatch == 1)
7820			{
7821			curmatch = curr;
7822			bestmatchlen = currcount;
7823			}
7824		}
7825	LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
7826		curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
7827	return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
7828	}
7829
7830// Sets all the Valid DNS servers for a question
7831mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
7832	{
7833	DNSServer *curmatch = mDNSNULL;
7834	int bestmatchlen = -1, namecount = CountLabels(&question->qname);
7835	DNSServer *curr;
7836	int bettermatch, currcount;
7837	int index = 0;
7838	mDNSu32 timeout = 0;
7839
7840	question->validDNSServers = zeroOpaque64;
7841	for (curr = m->DNSServers; curr; curr = curr->next)
7842		{
7843		debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
7844		// skip servers that will soon be deleted
7845		if (curr->flags & DNSServer_FlagDelete)
7846			{ debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
7847
7848		// This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
7849		// the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
7850		// But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
7851		// (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
7852		// match the scoped entries by mistake.
7853		//
7854		// Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
7855
7856		if (curr->scoped && curr->interface == mDNSInterface_Any)
7857			{ debugf("SetValidDNSServers: Scoped DNS server %#a (Domain %##s) with Interface Any", &curr->addr, curr->domain.c); continue; }
7858
7859		currcount = CountLabels(&curr->domain);
7860		if ((!curr->scoped && (!question->InterfaceID || (question->InterfaceID == mDNSInterface_Unicast))) || (curr->interface == question->InterfaceID))
7861			{
7862			bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
7863
7864			// If we found a better match (bettermatch == 1) then clear all the bits
7865			// corresponding to the old DNSServers that we have may set before and start fresh.
7866			// If we find an equal match, then include that DNSServer also by setting the corresponding
7867			// bit
7868			if ((bettermatch == 1) || (bettermatch == 0))
7869				{
7870				curmatch = curr;
7871				bestmatchlen = currcount;
7872				if (bettermatch) { debugf("SetValidDNSServers: Resetting all the bits"); question->validDNSServers = zeroOpaque64; timeout = 0; }
7873				debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
7874					" Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
7875					curr->interface);
7876				timeout += curr->timeout;
7877				bit_set_opaque64(question->validDNSServers, index);
7878				}
7879			}
7880		index++;
7881		}
7882	question->noServerResponse = 0;
7883
7884	debugf("SetValidDNSServers: ValidDNSServer bits  0x%x%x for question %p %##s (%s)",
7885		question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
7886	// If there are no matching resolvers, then use the default value to timeout
7887	return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
7888	}
7889
7890// Get the Best server that matches a name. If you find penalized servers, look for the one
7891// that will come out of the penalty box soon
7892mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSOpaque64 validBits, int *selected, mDNSBool nameMatch)
7893	{
7894	DNSServer *curmatch = mDNSNULL;
7895	int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
7896	DNSServer *curr;
7897	mDNSs32 bestPenaltyTime, currPenaltyTime;
7898	int bettermatch, currcount;
7899	int index = 0;
7900	int currindex = -1;
7901
7902	debugf("GetBestServer: ValidDNSServer bits  0x%x%x", validBits.l[1], validBits.l[0]);
7903	bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
7904	for (curr = m->DNSServers; curr; curr = curr->next)
7905		{
7906		// skip servers that will soon be deleted
7907		if (curr->flags & DNSServer_FlagDelete)
7908			{ debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
7909
7910		// Check if this is a valid DNSServer
7911		if (!bit_get_opaque64(validBits, index)) { debugf("GetBestServer: continuing for index %d", index); index++; continue; }
7912
7913		currcount = CountLabels(&curr->domain);
7914		currPenaltyTime = PenaltyTimeForServer(m, curr);
7915
7916		debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
7917			&curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
7918
7919		// If there are multiple best servers for a given question, we will pick the first one
7920		// if none of them are penalized. If some of them are penalized in that list, we pick
7921		// the least penalized one. BetterMatchForName walks through all best matches and
7922		// "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
7923		// in the list when there are no penalized servers and least one among them
7924		// when there are some penalized servers
7925		//
7926		// Notes on InterfaceID matching:
7927		//
7928		// 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
7929		// is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
7930		// entries by "scoped" being false. These are like any other unscoped entries except that
7931		// if it is picked e.g., domain match, when the packet is sent out later, the packet will
7932		// be sent out on that interface. Theese entries can be matched by either specifying a
7933		// zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
7934		// the question will cause an extra check on matching the InterfaceID on the question
7935		// against the DNSServer.
7936		//
7937		// 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
7938		// is the new way of specifying an InterfaceID option for DNSServer. These will be considered
7939		// only when the question has non-zero interfaceID.
7940
7941		if ((!curr->scoped && !InterfaceID) || (curr->interface == InterfaceID))
7942			{
7943
7944			// If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
7945			// This happens when we initially walk all the DNS servers and set the validity bit on the question.
7946			// Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
7947			// part and still do some redundant steps e.g., InterfaceID match
7948
7949			if (nameMatch) bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
7950			else bettermatch = 0;
7951
7952			// If we found a better match (bettermatch == 1) then we don't need to
7953			// compare penalty times. But if we found an equal match, then we compare
7954			// the penalty times to pick a better match
7955
7956			if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
7957				{ currindex = index; curmatch = curr; bestmatchlen = currcount; bestPenaltyTime = currPenaltyTime; }
7958			}
7959		index++;
7960		}
7961	if (selected) *selected = currindex;
7962	return curmatch;
7963	}
7964
7965// Look up a DNS Server, matching by name and InterfaceID
7966mDNSexport DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID)
7967    {
7968	DNSServer *curmatch = mDNSNULL;
7969	char *ifname = mDNSNULL;	// for logging purposes only
7970	mDNSOpaque64 allValid;
7971
7972	if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
7973		InterfaceID = mDNSNULL;
7974
7975	if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
7976
7977	// By passing in all ones, we make sure that every DNS server is considered
7978	allValid.l[0] = allValid.l[1] = 0xFFFFFFFF;
7979
7980	curmatch = GetBestServer(m, name, InterfaceID, allValid, mDNSNULL, mDNStrue);
7981
7982	if (curmatch != mDNSNULL)
7983		LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
7984		    mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
7985		InterfaceID, name);
7986	else
7987		LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
7988
7989	return(curmatch);
7990	}
7991
7992// Look up a DNS Server for a question within its valid DNSServer bits
7993mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
7994    {
7995	DNSServer *curmatch = mDNSNULL;
7996	char *ifname = mDNSNULL;	// for logging purposes only
7997	mDNSInterfaceID InterfaceID = question->InterfaceID;
7998	const domainname *name = &question->qname;
7999	int currindex;
8000
8001	if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
8002		InterfaceID = mDNSNULL;
8003
8004	if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
8005
8006	if (!mDNSOpaque64IsZero(&question->validDNSServers))
8007		{
8008		curmatch = GetBestServer(m, name, InterfaceID, question->validDNSServers, &currindex, mDNSfalse);
8009		if (currindex != -1) bit_clr_opaque64(question->validDNSServers, currindex);
8010		}
8011
8012	if (curmatch != mDNSNULL)
8013		LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question, &curmatch->addr,
8014		    mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
8015		InterfaceID, name, DNSTypeName(question->qtype));
8016	else
8017		LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question, ifname ? ifname : "None", InterfaceID, name, DNSTypeName(question->qtype));
8018
8019	return(curmatch);
8020	}
8021
8022
8023#define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
8024	(mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
8025
8026// Called in normal client context (lock not held)
8027mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
8028	{
8029	DNSQuestion *q;
8030	(void)n;    // Unused
8031	mDNS_Lock(m);
8032	LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
8033	for (q = m->Questions; q; q=q->next)
8034		if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
8035			startLLQHandshake(m, q);	// If ExternalPort is zero, will do StartLLQPolling instead
8036#if APPLE_OSX_mDNSResponder
8037	UpdateAutoTunnelDomainStatuses(m);
8038#endif
8039	mDNS_Unlock(m);
8040	}
8041
8042mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, domainname *qname, mDNSu16 qtype, mDNSInterfaceID InterfaceID)
8043	{
8044	NetworkInterfaceInfo *i;
8045	mDNSs32 iptype;
8046	DomainAuthInfo *AuthInfo;
8047
8048	if (qtype == kDNSType_A) iptype = mDNSAddrType_IPv4;
8049	else if (qtype == kDNSType_AAAA) iptype = mDNSAddrType_IPv6;
8050	else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname, DNSTypeName(qtype)); return mDNSfalse; }
8051
8052	// We still want the ability to be able to listen to the local services and hence
8053	// don't fail .local requests. We always have a loopback interface which we don't
8054	// check here.
8055	if (InterfaceID != mDNSInterface_Unicast && IsLocalDomain(qname)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname, DNSTypeName(qtype)); return mDNSfalse; }
8056
8057	// Skip Private domains as we have special addresses to get the hosts in the Private domain
8058	AuthInfo = GetAuthInfoForName_internal(m, qname);
8059	if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
8060		{ LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname, DNSTypeName(qtype)); return mDNSfalse; }
8061
8062	// Match on Type, Address and InterfaceID
8063	//
8064	// Check whether we are looking for a name that ends in .local, then presence of a link-local
8065	// address on the interface is sufficient.
8066	for (i = m->HostInterfaces; i; i = i->next)
8067		{
8068		if (i->ip.type != iptype) continue;
8069
8070		if (!InterfaceID || (InterfaceID == mDNSInterface_LocalOnly) || (InterfaceID == mDNSInterface_P2P) ||
8071			(InterfaceID == mDNSInterface_Unicast) || (i->InterfaceID == InterfaceID))
8072			{
8073			if (iptype == mDNSAddrType_IPv4 && !mDNSv4AddressIsLoopback(&i->ip.ip.v4) && !mDNSv4AddressIsLinkLocal(&i->ip.ip.v4))
8074				{
8075				LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname, DNSTypeName(qtype),
8076					&i->ip.ip.v4);
8077				return mDNSfalse;
8078				}
8079			else if (iptype == mDNSAddrType_IPv6 &&
8080				!mDNSv6AddressIsLoopback(&i->ip.ip.v6) &&
8081				!mDNSv6AddressIsLinkLocal(&i->ip.ip.v6) &&
8082				!mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelHostAddr) &&
8083				!mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelRelayAddrOut))
8084				{
8085				LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname, DNSTypeName(qtype),
8086					&i->ip.ip.v6);
8087				return mDNSfalse;
8088				}
8089			}
8090		}
8091	LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname, DNSTypeName(qtype));
8092	return mDNStrue;
8093	}
8094
8095mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
8096	{
8097	CacheRecord *rr;
8098	mDNSu32 slot;
8099	CacheGroup *cg;
8100
8101	slot = HashSlot(&q->qname);
8102	cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
8103	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8104		{
8105		// Don't deliver RMV events for negative records
8106		if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
8107			{
8108 			LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
8109				CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
8110			continue;
8111			}
8112
8113		if (SameNameRecordAnswersQuestion(&rr->resrec, q))
8114			{
8115 			LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
8116				q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
8117
8118			q->CurrentAnswers--;
8119			if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
8120			if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
8121
8122			if (rr->CRActiveQuestion == q)
8123				{
8124				DNSQuestion *qptr;
8125				// If this was the active question for this cache entry, it was the one that was
8126				// responsible for keeping the cache entry fresh when the cache entry was reaching
8127				// its expiry. We need to handover the responsibility to someone else. Otherwise,
8128				// when the cache entry is about to expire, we won't find an active question
8129				// (pointed by CRActiveQuestion) to refresh the cache.
8130				for (qptr = m->Questions; qptr; qptr=qptr->next)
8131 					if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
8132						break;
8133
8134				if (qptr)
8135					LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
8136						"Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
8137						qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
8138
8139				rr->CRActiveQuestion = qptr;		// Question used to be active; new value may or may not be null
8140				if (!qptr) m->rrcache_active--;	// If no longer active, decrement rrcache_active count
8141				}
8142			AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
8143			if (m->CurrentQuestion != q) break;		// If callback deleted q, then we're finished here
8144			}
8145		}
8146	}
8147
8148mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
8149	{
8150	DNSQuestion *q;
8151	for (q = m->NewQuestions; q; q = q->next)
8152		if (q == question) return mDNStrue;
8153	return mDNSfalse;
8154	}
8155
8156mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
8157	{
8158	AuthRecord *rr;
8159	mDNSu32 slot;
8160	AuthGroup *ag;
8161
8162	if (m->CurrentQuestion)
8163		LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
8164			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
8165
8166	if (IsQuestionNew(m, q))
8167		{
8168		LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
8169		return mDNStrue;
8170		}
8171	m->CurrentQuestion = q;
8172	slot = AuthHashSlot(&q->qname);
8173	ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
8174	if (ag)
8175		{
8176		for (rr = ag->members; rr; rr=rr->next)
8177			// Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
8178			if (LORecordAnswersAddressType(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
8179				{
8180				LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
8181					ARDisplayString(m, rr));
8182				if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
8183					{
8184					LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
8185						" (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
8186						q->CurrentAnswers, q->LOAddressAnswers);
8187					continue;
8188					}
8189				AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv);		// MUST NOT dereference q again
8190				if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
8191				}
8192		}
8193	m->CurrentQuestion = mDNSNULL;
8194	return mDNStrue;
8195	}
8196
8197// Returns false if the question got deleted while delivering the RMV events
8198// The caller should handle the case
8199mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
8200	{
8201	if (m->CurrentQuestion)
8202		LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
8203			m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
8204
8205	// If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
8206	// If this question was answered using local auth records, then you can't deliver RMVs using cache
8207	if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
8208		{
8209		m->CurrentQuestion = q;
8210		CacheRecordRmvEventsForCurrentQuestion(m, q);
8211		if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
8212		m->CurrentQuestion = mDNSNULL;
8213		}
8214	else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
8215	return mDNStrue;
8216	}
8217
8218// The caller should hold the lock
8219mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
8220	{
8221	DNSQuestion *q;
8222	DNSQuestion *restart = mDNSNULL;
8223
8224	// We look through all questions including new questions. During network change events,
8225	// we potentially restart questions here in this function that ends up as new questions,
8226	// which may be suppressed at this instance. Before it is handled we get another network
8227	// event that changes the status e.g., address becomes available. If we did not process
8228	// new questions, we would never change its SuppressQuery status.
8229	//
8230	// CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
8231	// application callback can potentially stop the current question (detected by CurrentQuestion) or
8232	// *any* other question which could be the next one that we may process here. RestartQuestion
8233	// points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
8234	// if the "next" question is stopped while the CurrentQuestion is stopped
8235	if (m->RestartQuestion)
8236		LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
8237			m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
8238	m->RestartQuestion = m->Questions;
8239	while (m->RestartQuestion)
8240		{
8241		q = m->RestartQuestion;
8242		m->RestartQuestion = q->next;
8243		if (!mDNSOpaque16IsZero(q->TargetQID) && q->SuppressUnusable)
8244			{
8245			mDNSBool old = q->SuppressQuery;
8246			q->SuppressQuery = ShouldSuppressQuery(m, &q->qname, q->qtype, q->InterfaceID);
8247			if (q->SuppressQuery != old)
8248				{
8249				// NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
8250				// LOddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
8251				// LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
8252
8253  				if (q->SuppressQuery)
8254  					{
8255  					// Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
8256 					// followed by a negative cache response. Temporarily turn off suppression so that
8257 					// AnswerCurrentQuestionWithResourceRecord can answer the question
8258 					q->SuppressQuery = mDNSfalse;
8259 					if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
8260 					q->SuppressQuery = mDNStrue;
8261  					}
8262
8263				// SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
8264				// and SuppressQuery status does not mean anything for these questions. As we are going to stop the
8265				// question below, we need to deliver the RMV events so that the ADDs that will be delivered during
8266				// the restart will not be a duplicate ADD
8267 				if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
8268
8269				// There are two cases here.
8270				//
8271				// 1. Previously it was suppressed and now it is not suppressed, restart the question so
8272				// that it will start as a new question. Note that we can't just call ActivateUnicastQuery
8273				// because when we get the response, if we had entries in the cache already, it will not answer
8274				// this question if the cache entry did not change. Hence, we need to restart
8275				// the query so that it can be answered from the cache.
8276				//
8277				// 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
8278				// so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
8279				// is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
8280				// A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
8281				// (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
8282				// immediate response and not want to be blocked behind a question that is querying DNS servers. When
8283				// the question is not suppressed, we don't want two active questions sending packets on the wire.
8284				// This affects both efficiency and also the current design where there is only one active question
8285				// pointed to from a cache entry.
8286				//
8287				// We restart queries in a two step process by first calling stop and build a temporary list which we
8288				// will restart at the end. The main reason for the two step process is to handle duplicate questions.
8289				// If there are duplicate questions, calling stop inherits the values from another question on the list (which
8290				// will soon become the real question) including q->ThisQInterval which might be zero if it was
8291				// suppressed before. At the end when we have restarted all questions, none of them is active as each
8292				// inherits from one another and we need to reactivate one of the questions here which is a little hacky.
8293				//
8294				// It is much cleaner and less error prone to build a list of questions and restart at the end.
8295
8296				LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8297				mDNS_StopQuery_internal(m, q);
8298				q->next = restart;
8299				restart = q;
8300				}
8301			}
8302		}
8303	while (restart)
8304		{
8305		q = restart;
8306		restart = restart->next;
8307		q->next = mDNSNULL;
8308		LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8309		mDNS_StartQuery_internal(m, q);
8310		}
8311	}
8312
8313mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
8314	{
8315	if (question->Target.type && !ValidQuestionTarget(question))
8316		{
8317		LogMsg("mDNS_StartQuery_internal: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
8318			question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
8319		question->Target.type = mDNSAddrType_None;
8320		}
8321
8322	if (!question->Target.type) question->TargetPort = zeroIPPort;	// If no question->Target specified clear TargetPort
8323
8324	question->TargetQID =
8325#ifndef UNICAST_DISABLED
8326		(question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
8327#endif // UNICAST_DISABLED
8328		zeroID;
8329
8330	debugf("mDNS_StartQuery: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8331
8332	if (m->rrcache_size == 0)	// Can't do queries if we have no cache space allocated
8333		return(mStatus_NoCache);
8334	else
8335		{
8336		int i;
8337		DNSQuestion **q;
8338
8339		if (!ValidateDomainName(&question->qname))
8340			{
8341			LogMsg("Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8342			return(mStatus_Invalid);
8343			}
8344
8345		// Note: It important that new questions are appended at the *end* of the list, not prepended at the start
8346		q = &m->Questions;
8347		if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) q = &m->LocalOnlyQuestions;
8348		while (*q && *q != question) q=&(*q)->next;
8349
8350		if (*q)
8351			{
8352			LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
8353				question->qname.c, DNSTypeName(question->qtype), question);
8354			return(mStatus_AlreadyRegistered);
8355			}
8356
8357		*q = question;
8358
8359		// If this question is referencing a specific interface, verify it exists
8360		if (question->InterfaceID && question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_Unicast && question->InterfaceID != mDNSInterface_P2P)
8361			{
8362			NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
8363			if (!intf)
8364				LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
8365					question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
8366			}
8367
8368		// Note: In the case where we already have the answer to this question in our cache, that may be all the client
8369		// wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
8370		// be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
8371		// If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
8372		// that to go out immediately.
8373		question->next              = mDNSNULL;
8374		question->qnamehash         = DomainNameHashValue(&question->qname);	// MUST do this before FindDuplicateQuestion()
8375		question->DelayAnswering    = CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash, HashSlot(&question->qname));
8376		question->LastQTime         = m->timenow;
8377		question->ThisQInterval     = InitialQuestionInterval;					// MUST be > zero for an active question
8378		question->ExpectUnicastResp = 0;
8379		question->LastAnswerPktNum  = m->PktNum;
8380		question->RecentAnswerPkts  = 0;
8381		question->CurrentAnswers    = 0;
8382		question->LargeAnswers      = 0;
8383		question->UniqueAnswers     = 0;
8384		question->LOAddressAnswers  = 0;
8385		question->FlappingInterface1 = mDNSNULL;
8386		question->FlappingInterface2 = mDNSNULL;
8387		// Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
8388		question->AuthInfo          = GetAuthInfoForQuestion(m, question);
8389		if (question->SuppressUnusable)
8390			question->SuppressQuery = ShouldSuppressQuery(m, &question->qname, question->qtype, question->InterfaceID);
8391		else
8392			question->SuppressQuery = 0;
8393		question->DuplicateOf       = FindDuplicateQuestion(m, question);
8394		question->NextInDQList      = mDNSNULL;
8395		question->SendQNow          = mDNSNULL;
8396		question->SendOnAll         = mDNSfalse;
8397		question->RequestUnicast    = 0;
8398		question->LastQTxTime       = m->timenow;
8399		question->CNAMEReferrals    = 0;
8400
8401		// We'll create our question->LocalSocket on demand, if needed.
8402		// We won't need one for duplicate questions, or from questions answered immediately out of the cache.
8403		// We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
8404		// NAT mapping for receiving inbound add/remove events.
8405		question->LocalSocket       = mDNSNULL;
8406		question->deliverAddEvents  = mDNSfalse;
8407		question->qDNSServer        = mDNSNULL;
8408		question->unansweredQueries = 0;
8409		question->nta               = mDNSNULL;
8410		question->servAddr          = zeroAddr;
8411		question->servPort          = zeroIPPort;
8412		question->tcp               = mDNSNULL;
8413		question->NoAnswer          = NoAnswer_Normal;
8414
8415		question->state             = LLQ_InitialRequest;
8416		question->ReqLease          = 0;
8417		question->expire            = 0;
8418		question->ntries            = 0;
8419		question->id                = zeroOpaque64;
8420		question->validDNSServers   = zeroOpaque64;
8421		question->triedAllServersOnce = 0;
8422		question->noServerResponse  = 0;
8423		question->StopTime = 0;
8424		if (question->WakeOnResolve)
8425			{
8426			question->WakeOnResolveCount = InitialWakeOnResolveCount;
8427			mDNS_PurgeBeforeResolve(m, question);
8428			}
8429		else
8430			question->WakeOnResolveCount = 0;
8431
8432		if (question->DuplicateOf) question->AuthInfo = question->DuplicateOf->AuthInfo;
8433
8434		for (i=0; i<DupSuppressInfoSize; i++)
8435			question->DupSuppress[i].InterfaceID = mDNSNULL;
8436
8437		debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
8438			question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
8439			NextQSendTime(question) - m->timenow,
8440			question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
8441			question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
8442
8443		if (question->DelayAnswering)
8444			LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
8445				question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
8446
8447		if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
8448			{
8449			if (!m->NewLocalOnlyQuestions) m->NewLocalOnlyQuestions = question;
8450			}
8451		else
8452			{
8453			if (!m->NewQuestions) m->NewQuestions = question;
8454
8455			// If the question's id is non-zero, then it's Wide Area
8456			// MUST NOT do this Wide Area setup until near the end of
8457			// mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
8458			// NS, etc.) and if we haven't finished setting up our own question and setting
8459			// m->NewQuestions if necessary then we could end up recursively re-entering
8460			// this routine with the question list data structures in an inconsistent state.
8461			if (!mDNSOpaque16IsZero(question->TargetQID))
8462				{
8463				// Duplicate questions should have the same DNSServers so that when we find
8464				// a matching resource record, all of them get the answers. Calling GetServerForQuestion
8465				// for the duplicate question may get a different DNS server from the original question
8466				mDNSu32 timeout = SetValidDNSServers(m, question);
8467				// We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
8468				// a networking change/search domain change that calls this function again we keep
8469				// reinitializing the timeout value which means it may never timeout. If this becomes
8470				// a common case in the future, we can easily fix this by adding extra state that
8471				// indicates that we have already set the StopTime.
8472				if (question->TimeoutQuestion)
8473					question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
8474				if (question->DuplicateOf)
8475					{
8476					question->validDNSServers = question->DuplicateOf->validDNSServers;
8477					question->qDNSServer = question->DuplicateOf->qDNSServer;
8478					LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), Timeout %d, DNS Server %#a:%d",
8479						question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype), timeout,
8480						question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
8481					    mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
8482					}
8483				else
8484					{
8485					question->qDNSServer = GetServerForQuestion(m, question);
8486					LogInfo("mDNS_StartQuery_internal: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
8487						question, question->qname.c, DNSTypeName(question->qtype), timeout,
8488						question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
8489					    mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
8490					}
8491				ActivateUnicastQuery(m, question, mDNSfalse);
8492
8493				// If long-lived query, and we don't have our NAT mapping active, start it now
8494				if (question->LongLived && !m->LLQNAT.clientContext)
8495					{
8496					m->LLQNAT.Protocol       = NATOp_MapUDP;
8497					m->LLQNAT.IntPort        = m->UnicastPort4;
8498					m->LLQNAT.RequestedPort  = m->UnicastPort4;
8499					m->LLQNAT.clientCallback = LLQNATCallback;
8500					m->LLQNAT.clientContext  = (void*)1; // Means LLQ NAT Traversal is active
8501					mDNS_StartNATOperation_internal(m, &m->LLQNAT);
8502					}
8503
8504#if APPLE_OSX_mDNSResponder
8505				if (question->LongLived)
8506					UpdateAutoTunnelDomainStatuses(m);
8507#endif
8508
8509				}
8510			else
8511				{
8512				if (question->TimeoutQuestion)
8513					question->StopTime = NonZeroTime(m->timenow + GetTimeoutForMcastQuestion(m, question) * mDNSPlatformOneSecond);
8514				}
8515			if (question->StopTime) SetNextQueryStopTime(m, question);
8516			SetNextQueryTime(m,question);
8517			}
8518
8519		return(mStatus_NoError);
8520		}
8521	}
8522
8523// CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
8524mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
8525	{
8526	debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
8527	// This function may be called anytime to free the zone information.The question may or may not have stopped.
8528	// If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
8529	// call it again
8530	if (nta->question.ThisQInterval != -1)
8531		{
8532		mDNS_StopQuery_internal(m, &nta->question);
8533		if (nta->question.ThisQInterval != -1)
8534			LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
8535		}
8536	mDNSPlatformMemFree(nta);
8537	}
8538
8539mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
8540	{
8541	const mDNSu32 slot = HashSlot(&question->qname);
8542	CacheGroup *cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
8543	CacheRecord *rr;
8544	DNSQuestion **qp = &m->Questions;
8545
8546	//LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8547
8548	if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) qp = &m->LocalOnlyQuestions;
8549	while (*qp && *qp != question) qp=&(*qp)->next;
8550	if (*qp) *qp = (*qp)->next;
8551	else
8552		{
8553#if !ForceAlerts
8554		if (question->ThisQInterval >= 0)	// Only log error message if the query was supposed to be active
8555#endif
8556			LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
8557				question->qname.c, DNSTypeName(question->qtype));
8558#if ForceAlerts
8559		*(long*)0 = 0;
8560#endif
8561		return(mStatus_BadReferenceErr);
8562		}
8563
8564	// Take care to cut question from list *before* calling UpdateQuestionDuplicates
8565	UpdateQuestionDuplicates(m, question);
8566	// But don't trash ThisQInterval until afterwards.
8567	question->ThisQInterval = -1;
8568
8569	// If there are any cache records referencing this as their active question, then see if there is any
8570	// other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
8571	for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8572		{
8573		if (rr->CRActiveQuestion == question)
8574			{
8575			DNSQuestion *q;
8576			// Checking for ActiveQuestion filters questions that are suppressed also
8577			// as suppressed questions are not active
8578			for (q = m->Questions; q; q=q->next)		// Scan our list of questions
8579				if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
8580					break;
8581			if (q)
8582				debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
8583					"CurrentAnswers %d, SuppressQuery %d", q, CRDisplayString(m,rr), question->CurrentAnswers, q->CurrentAnswers, q->SuppressQuery);
8584			rr->CRActiveQuestion = q;		// Question used to be active; new value may or may not be null
8585			if (!q) m->rrcache_active--;	// If no longer active, decrement rrcache_active count
8586			}
8587		}
8588
8589	// If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
8590	// bump its pointer forward one question.
8591	if (m->CurrentQuestion == question)
8592		{
8593		debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
8594			question->qname.c, DNSTypeName(question->qtype));
8595		m->CurrentQuestion = question->next;
8596		}
8597
8598	if (m->NewQuestions == question)
8599		{
8600		debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
8601			question->qname.c, DNSTypeName(question->qtype));
8602		m->NewQuestions = question->next;
8603		}
8604
8605	if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
8606
8607	if (m->RestartQuestion == question)
8608		{
8609		LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
8610			question->qname.c, DNSTypeName(question->qtype));
8611		m->RestartQuestion = question->next;
8612		}
8613
8614	// Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
8615	question->next = mDNSNULL;
8616
8617	// LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
8618
8619	// And finally, cancel any associated GetZoneData operation that's still running.
8620	// Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
8621	// so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
8622	// invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
8623	// *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
8624	if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
8625	if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
8626	if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
8627		{
8628		// Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
8629		DNSQuestion *q;
8630		for (q = m->Questions; q; q=q->next)
8631			if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
8632		if (!q)
8633			{
8634			if (!m->LLQNAT.clientContext)		// Should never happen, but just in case...
8635				LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
8636			else
8637				{
8638				LogInfo("Stopping LLQNAT");
8639				mDNS_StopNATOperation_internal(m, &m->LLQNAT);
8640				m->LLQNAT.clientContext = mDNSNULL; // Means LLQ NAT Traversal not running
8641				}
8642			}
8643
8644		// If necessary, tell server it can delete this LLQ state
8645		if (question->state == LLQ_Established)
8646			{
8647			question->ReqLease = 0;
8648			sendLLQRefresh(m, question);
8649			// If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
8650			// We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
8651			// crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
8652			// we let that run out its natural course and complete asynchronously.
8653			if (question->tcp)
8654				{
8655				question->tcp->question = mDNSNULL;
8656				question->tcp           = mDNSNULL;
8657				}
8658			}
8659#if APPLE_OSX_mDNSResponder
8660		UpdateAutoTunnelDomainStatuses(m);
8661#endif
8662		}
8663	// wait until we send the refresh above which needs the nta
8664	if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
8665
8666	return(mStatus_NoError);
8667	}
8668
8669mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
8670	{
8671	mStatus status;
8672	mDNS_Lock(m);
8673	status = mDNS_StartQuery_internal(m, question);
8674	mDNS_Unlock(m);
8675	return(status);
8676	}
8677
8678mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
8679	{
8680	mStatus status;
8681	mDNS_Lock(m);
8682	status = mDNS_StopQuery_internal(m, question);
8683	mDNS_Unlock(m);
8684	return(status);
8685	}
8686
8687// Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
8688// Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
8689// We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
8690// specifically to catch and report if the client callback does try to make API calls
8691mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
8692	{
8693	mStatus status;
8694	DNSQuestion *qq;
8695	mDNS_Lock(m);
8696
8697	// Check if question is new -- don't want to give remove events for a question we haven't even answered yet
8698	for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
8699
8700	status = mDNS_StopQuery_internal(m, question);
8701	if (status == mStatus_NoError && !qq)
8702		{
8703		const CacheRecord *rr;
8704		const mDNSu32 slot = HashSlot(&question->qname);
8705		CacheGroup *const cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
8706		LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
8707		for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8708			if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
8709				{
8710				// Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
8711				if (question->QuestionCallback)
8712					question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
8713				}
8714		}
8715	mDNS_Unlock(m);
8716	return(status);
8717	}
8718
8719mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
8720	{
8721	mStatus status;
8722	mDNS_Lock(m);
8723	status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8724	if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
8725	mDNS_Unlock(m);
8726	return(status);
8727	}
8728
8729mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
8730	{
8731	mStatus status = mStatus_BadReferenceErr;
8732	CacheRecord *cr;
8733	mDNS_Lock(m);
8734	cr = FindIdenticalRecordInCache(m, rr);
8735	debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
8736	if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8737	if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
8738	mDNS_Unlock(m);
8739	return(status);
8740	}
8741
8742mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
8743	const domainname *const srv, const domainname *const domain,
8744	const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
8745	{
8746	question->InterfaceID      = InterfaceID;
8747	question->Target           = zeroAddr;
8748	question->qtype            = kDNSType_PTR;
8749	question->qclass           = kDNSClass_IN;
8750	question->LongLived        = mDNStrue;
8751	question->ExpectUnique     = mDNSfalse;
8752	question->ForceMCast       = ForceMCast;
8753	question->ReturnIntermed   = mDNSfalse;
8754	question->SuppressUnusable = mDNSfalse;
8755	question->SearchListIndex  = 0;
8756	question->AppendSearchDomains = 0;
8757	question->RetryWithSearchDomains = mDNSfalse;
8758	question->TimeoutQuestion  = 0;
8759	question->WakeOnResolve    = 0;
8760	question->qnameOrig        = mDNSNULL;
8761	question->QuestionCallback = Callback;
8762	question->QuestionContext  = Context;
8763	if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) return(mStatus_BadParamErr);
8764
8765	return(mDNS_StartQuery_internal(m, question));
8766	}
8767
8768mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
8769	const domainname *const srv, const domainname *const domain,
8770	const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
8771	{
8772	mStatus status;
8773	mDNS_Lock(m);
8774	status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, ForceMCast, Callback, Context);
8775	mDNS_Unlock(m);
8776	return(status);
8777	}
8778
8779mDNSlocal mDNSBool MachineHasActiveIPv6(mDNS *const m)
8780	{
8781	NetworkInterfaceInfo *intf;
8782	for (intf = m->HostInterfaces; intf; intf = intf->next)
8783	if (intf->ip.type == mDNSAddrType_IPv6) return(mDNStrue);
8784	return(mDNSfalse);
8785	}
8786
8787mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8788	{
8789	ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8790	mDNSBool PortChanged = !mDNSSameIPPort(query->info->port, answer->rdata->u.srv.port);
8791	if (!AddRecord) return;
8792	if (answer->rrtype != kDNSType_SRV) return;
8793
8794	query->info->port = answer->rdata->u.srv.port;
8795
8796	// If this is our first answer, then set the GotSRV flag and start the address query
8797	if (!query->GotSRV)
8798		{
8799		query->GotSRV             = mDNStrue;
8800		query->qAv4.InterfaceID   = answer->InterfaceID;
8801		AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
8802		query->qAv6.InterfaceID   = answer->InterfaceID;
8803		AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
8804		mDNS_StartQuery(m, &query->qAv4);
8805		// Only do the AAAA query if this machine actually has IPv6 active
8806		if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
8807		}
8808	// If this is not our first answer, only re-issue the address query if the target host name has changed
8809	else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
8810		!SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
8811		{
8812		mDNS_StopQuery(m, &query->qAv4);
8813		if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery(m, &query->qAv6);
8814		if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
8815			{
8816			// If we get here, it means:
8817			// 1. This is not our first SRV answer
8818			// 2. The interface ID is different, but the target host and port are the same
8819			// This implies that we're seeing the exact same SRV record on more than one interface, so we should
8820			// make our address queries at least as broad as the original SRV query so that we catch all the answers.
8821			query->qAv4.InterfaceID = query->qSRV.InterfaceID;	// Will be mDNSInterface_Any, or a specific interface
8822			query->qAv6.InterfaceID = query->qSRV.InterfaceID;
8823			}
8824		else
8825			{
8826			query->qAv4.InterfaceID   = answer->InterfaceID;
8827			AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
8828			query->qAv6.InterfaceID   = answer->InterfaceID;
8829			AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
8830			}
8831		debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query->qAv4.qname.c, DNSTypeName(query->qAv4.qtype));
8832		mDNS_StartQuery(m, &query->qAv4);
8833		// Only do the AAAA query if this machine actually has IPv6 active
8834		if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
8835		}
8836	else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
8837		{
8838		if (++query->Answers >= 100)
8839			debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
8840				query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
8841				mDNSVal16(answer->rdata->u.srv.port));
8842		query->ServiceInfoQueryCallback(m, query);
8843		}
8844	// CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8845	// callback function is allowed to do anything, including deleting this query and freeing its memory.
8846	}
8847
8848mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8849	{
8850	ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8851	if (!AddRecord) return;
8852	if (answer->rrtype != kDNSType_TXT) return;
8853	if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
8854
8855	query->GotTXT       = mDNStrue;
8856	query->info->TXTlen = answer->rdlength;
8857	query->info->TXTinfo[0] = 0;		// In case answer->rdlength is zero
8858	mDNSPlatformMemCopy(query->info->TXTinfo, answer->rdata->u.txt.c, answer->rdlength);
8859
8860	verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
8861
8862	// CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8863	// callback function is allowed to do anything, including deleting this query and freeing its memory.
8864	if (query->ServiceInfoQueryCallback && query->GotADD)
8865		{
8866		if (++query->Answers >= 100)
8867			debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
8868				query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
8869		query->ServiceInfoQueryCallback(m, query);
8870		}
8871	}
8872
8873mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
8874	{
8875	ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
8876	//LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
8877	if (!AddRecord) return;
8878
8879	if (answer->rrtype == kDNSType_A)
8880		{
8881		query->info->ip.type = mDNSAddrType_IPv4;
8882		query->info->ip.ip.v4 = answer->rdata->u.ipv4;
8883		}
8884	else if (answer->rrtype == kDNSType_AAAA)
8885		{
8886		query->info->ip.type = mDNSAddrType_IPv6;
8887		query->info->ip.ip.v6 = answer->rdata->u.ipv6;
8888		}
8889	else
8890		{
8891		debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name->c, answer->rrtype, DNSTypeName(answer->rrtype));
8892		return;
8893		}
8894
8895	query->GotADD = mDNStrue;
8896	query->info->InterfaceID = answer->InterfaceID;
8897
8898	verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
8899
8900	// CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
8901	// callback function is allowed to do anything, including deleting this query and freeing its memory.
8902	if (query->ServiceInfoQueryCallback && query->GotTXT)
8903		{
8904		if (++query->Answers >= 100)
8905			debugf(answer->rrtype == kDNSType_A ?
8906				"**** WARNING **** have given %lu answers for %##s (A) %.4a" :
8907				"**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
8908				query->Answers, query->qSRV.qname.c, &answer->rdata->u.data);
8909		query->ServiceInfoQueryCallback(m, query);
8910		}
8911	}
8912
8913// On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
8914// If the query is not interface-specific, then InterfaceID may be zero
8915// Each time the Callback is invoked, the remainder of the fields will have been filled in
8916// In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
8917mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
8918	ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
8919	{
8920	mStatus status;
8921	mDNS_Lock(m);
8922
8923	query->qSRV.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8924	query->qSRV.InterfaceID         = info->InterfaceID;
8925	query->qSRV.Target              = zeroAddr;
8926	AssignDomainName(&query->qSRV.qname, &info->name);
8927	query->qSRV.qtype               = kDNSType_SRV;
8928	query->qSRV.qclass              = kDNSClass_IN;
8929	query->qSRV.LongLived           = mDNSfalse;
8930	query->qSRV.ExpectUnique        = mDNStrue;
8931	query->qSRV.ForceMCast          = mDNSfalse;
8932	query->qSRV.ReturnIntermed      = mDNSfalse;
8933	query->qSRV.SuppressUnusable    = mDNSfalse;
8934	query->qSRV.SearchListIndex     = 0;
8935	query->qSRV.AppendSearchDomains = 0;
8936	query->qSRV.RetryWithSearchDomains = mDNSfalse;
8937	query->qSRV.TimeoutQuestion     = 0;
8938	query->qSRV.WakeOnResolve       = 0;
8939	query->qSRV.qnameOrig           = mDNSNULL;
8940	query->qSRV.QuestionCallback    = FoundServiceInfoSRV;
8941	query->qSRV.QuestionContext     = query;
8942
8943	query->qTXT.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8944	query->qTXT.InterfaceID         = info->InterfaceID;
8945	query->qTXT.Target              = zeroAddr;
8946	AssignDomainName(&query->qTXT.qname, &info->name);
8947	query->qTXT.qtype               = kDNSType_TXT;
8948	query->qTXT.qclass              = kDNSClass_IN;
8949	query->qTXT.LongLived           = mDNSfalse;
8950	query->qTXT.ExpectUnique        = mDNStrue;
8951	query->qTXT.ForceMCast          = mDNSfalse;
8952	query->qTXT.ReturnIntermed      = mDNSfalse;
8953	query->qTXT.SuppressUnusable    = mDNSfalse;
8954	query->qTXT.SearchListIndex     = 0;
8955	query->qTXT.AppendSearchDomains = 0;
8956	query->qTXT.RetryWithSearchDomains = mDNSfalse;
8957	query->qTXT.TimeoutQuestion     = 0;
8958	query->qTXT.WakeOnResolve       = 0;
8959	query->qTXT.qnameOrig           = mDNSNULL;
8960	query->qTXT.QuestionCallback    = FoundServiceInfoTXT;
8961	query->qTXT.QuestionContext     = query;
8962
8963	query->qAv4.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8964	query->qAv4.InterfaceID         = info->InterfaceID;
8965	query->qAv4.Target              = zeroAddr;
8966	query->qAv4.qname.c[0]          = 0;
8967	query->qAv4.qtype               = kDNSType_A;
8968	query->qAv4.qclass              = kDNSClass_IN;
8969	query->qAv4.LongLived           = mDNSfalse;
8970	query->qAv4.ExpectUnique        = mDNStrue;
8971	query->qAv4.ForceMCast          = mDNSfalse;
8972	query->qAv4.ReturnIntermed      = mDNSfalse;
8973	query->qAv4.SuppressUnusable    = mDNSfalse;
8974	query->qAv4.SearchListIndex     = 0;
8975	query->qAv4.AppendSearchDomains = 0;
8976	query->qAv4.RetryWithSearchDomains = mDNSfalse;
8977	query->qAv4.TimeoutQuestion     = 0;
8978	query->qAv4.WakeOnResolve       = 0;
8979	query->qAv4.qnameOrig           = mDNSNULL;
8980	query->qAv4.QuestionCallback    = FoundServiceInfo;
8981	query->qAv4.QuestionContext     = query;
8982
8983	query->qAv6.ThisQInterval       = -1;		// So that mDNS_StopResolveService() knows whether to cancel this question
8984	query->qAv6.InterfaceID         = info->InterfaceID;
8985	query->qAv6.Target              = zeroAddr;
8986	query->qAv6.qname.c[0]          = 0;
8987	query->qAv6.qtype               = kDNSType_AAAA;
8988	query->qAv6.qclass              = kDNSClass_IN;
8989	query->qAv6.LongLived           = mDNSfalse;
8990	query->qAv6.ExpectUnique        = mDNStrue;
8991	query->qAv6.ForceMCast          = mDNSfalse;
8992	query->qAv6.ReturnIntermed      = mDNSfalse;
8993	query->qAv6.SuppressUnusable    = mDNSfalse;
8994	query->qAv6.SearchListIndex     = 0;
8995	query->qAv6.AppendSearchDomains = 0;
8996	query->qAv6.RetryWithSearchDomains = mDNSfalse;
8997	query->qAv6.TimeoutQuestion     = 0;
8998	query->qAv6.WakeOnResolve       = 0;
8999	query->qAv6.qnameOrig           = mDNSNULL;
9000	query->qAv6.QuestionCallback    = FoundServiceInfo;
9001	query->qAv6.QuestionContext     = query;
9002
9003	query->GotSRV                   = mDNSfalse;
9004	query->GotTXT                   = mDNSfalse;
9005	query->GotADD                   = mDNSfalse;
9006	query->Answers                  = 0;
9007
9008	query->info                     = info;
9009	query->ServiceInfoQueryCallback = Callback;
9010	query->ServiceInfoQueryContext  = Context;
9011
9012//	info->name      = Must already be set up by client
9013//	info->interface = Must already be set up by client
9014	info->ip        = zeroAddr;
9015	info->port      = zeroIPPort;
9016	info->TXTlen    = 0;
9017
9018	// We use mDNS_StartQuery_internal here because we're already holding the lock
9019	status = mDNS_StartQuery_internal(m, &query->qSRV);
9020	if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
9021	if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
9022
9023	mDNS_Unlock(m);
9024	return(status);
9025	}
9026
9027mDNSexport void    mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *q)
9028	{
9029	mDNS_Lock(m);
9030	// We use mDNS_StopQuery_internal here because we're already holding the lock
9031	if (q->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qSRV);
9032	if (q->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qTXT);
9033	if (q->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv4);
9034	if (q->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv6);
9035	mDNS_Unlock(m);
9036	}
9037
9038mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
9039	const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
9040	{
9041	question->InterfaceID      = InterfaceID;
9042	question->Target           = zeroAddr;
9043	question->qtype            = kDNSType_PTR;
9044	question->qclass           = kDNSClass_IN;
9045	question->LongLived        = mDNSfalse;
9046	question->ExpectUnique     = mDNSfalse;
9047	question->ForceMCast       = mDNSfalse;
9048	question->ReturnIntermed   = mDNSfalse;
9049	question->SuppressUnusable = mDNSfalse;
9050	question->SearchListIndex  = 0;
9051	question->AppendSearchDomains = 0;
9052	question->RetryWithSearchDomains = mDNSfalse;
9053	question->TimeoutQuestion  = 0;
9054	question->WakeOnResolve    = 0;
9055	question->qnameOrig        = mDNSNULL;
9056	question->QuestionCallback = Callback;
9057	question->QuestionContext  = Context;
9058	if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
9059	if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
9060	if (!dom) dom = &localdomain;
9061	if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
9062	return(mDNS_StartQuery(m, question));
9063	}
9064
9065// ***************************************************************************
9066#if COMPILER_LIKES_PRAGMA_MARK
9067#pragma mark -
9068#pragma mark - Responder Functions
9069#endif
9070
9071mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
9072	{
9073	mStatus status;
9074	mDNS_Lock(m);
9075	status = mDNS_Register_internal(m, rr);
9076	mDNS_Unlock(m);
9077	return(status);
9078	}
9079
9080mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
9081	const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
9082	{
9083	if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
9084		{
9085		LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
9086		return(mStatus_Invalid);
9087		}
9088
9089	mDNS_Lock(m);
9090
9091	// If TTL is unspecified, leave TTL unchanged
9092	if (newttl == 0) newttl = rr->resrec.rroriginalttl;
9093
9094	// If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
9095	if (rr->NewRData)
9096		{
9097		RData *n = rr->NewRData;
9098		rr->NewRData = mDNSNULL;							// Clear the NewRData pointer ...
9099		if (rr->UpdateCallback)
9100			rr->UpdateCallback(m, rr, n, rr->newrdlength);	// ...and let the client free this memory, if necessary
9101		}
9102
9103	rr->NewRData             = newrdata;
9104	rr->newrdlength          = newrdlength;
9105	rr->UpdateCallback       = Callback;
9106
9107#ifndef UNICAST_DISABLED
9108	if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
9109		{
9110		mStatus status = uDNS_UpdateRecord(m, rr);
9111		// The caller frees the memory on error, don't retain stale pointers
9112		if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
9113		mDNS_Unlock(m);
9114		return(status);
9115		}
9116#endif
9117
9118	if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
9119		rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
9120		CompleteRDataUpdate(m, rr);
9121	else
9122		{
9123		rr->AnnounceCount = InitialAnnounceCount;
9124		InitializeLastAPTime(m, rr);
9125		while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
9126		if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
9127		if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
9128		if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
9129		if (rr->UpdateCredits <= 5)
9130			{
9131			mDNSu32 delay = 6 - rr->UpdateCredits;		// Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
9132			if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
9133			rr->ThisAPInterval *= 4;
9134			rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
9135			LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
9136				rr->resrec.name->c, delay, delay > 1 ? "s" : "");
9137			}
9138		rr->resrec.rroriginalttl = newttl;
9139		}
9140
9141	mDNS_Unlock(m);
9142	return(mStatus_NoError);
9143	}
9144
9145// Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
9146// the record list and/or question list.
9147// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9148mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
9149	{
9150	mStatus status;
9151	mDNS_Lock(m);
9152	status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9153	mDNS_Unlock(m);
9154	return(status);
9155	}
9156
9157// Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
9158mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
9159
9160mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
9161	{
9162	NetworkInterfaceInfo *intf;
9163	for (intf = m->HostInterfaces; intf; intf = intf->next)
9164		if (intf->Advertise) break;
9165	return(intf);
9166	}
9167
9168mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
9169	{
9170	char buffer[MAX_REVERSE_MAPPING_NAME];
9171	NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
9172	if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
9173
9174	// Send dynamic update for non-linklocal IPv4 Addresses
9175	mDNS_SetupResourceRecord(&set->RR_A,     mDNSNULL, set->InterfaceID, kDNSType_A,     kHostNameTTL, kDNSRecordTypeUnique,      AuthRecordAny, mDNS_HostNameCallback, set);
9176	mDNS_SetupResourceRecord(&set->RR_PTR,   mDNSNULL, set->InterfaceID, kDNSType_PTR,   kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
9177	mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique,      AuthRecordAny, mDNSNULL, mDNSNULL);
9178
9179#if ANSWER_REMOTE_HOSTNAME_QUERIES
9180	set->RR_A    .AllowRemoteQuery  = mDNStrue;
9181	set->RR_PTR  .AllowRemoteQuery  = mDNStrue;
9182	set->RR_HINFO.AllowRemoteQuery  = mDNStrue;
9183#endif
9184	// 1. Set up Address record to map from host name ("foo.local.") to IP address
9185	// 2. Set up reverse-lookup PTR record to map from our address back to our host name
9186	AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
9187	if (set->ip.type == mDNSAddrType_IPv4)
9188		{
9189		set->RR_A.resrec.rrtype = kDNSType_A;
9190		set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
9191		// Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
9192		mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
9193			set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
9194		}
9195	else if (set->ip.type == mDNSAddrType_IPv6)
9196		{
9197		int i;
9198		set->RR_A.resrec.rrtype = kDNSType_AAAA;
9199		set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
9200		for (i = 0; i < 16; i++)
9201			{
9202			static const char hexValues[] = "0123456789ABCDEF";
9203			buffer[i * 4    ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
9204			buffer[i * 4 + 1] = '.';
9205			buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
9206			buffer[i * 4 + 3] = '.';
9207			}
9208		mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
9209		}
9210
9211	MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
9212	set->RR_PTR.AutoTarget = Target_AutoHost;	// Tell mDNS that the target of this PTR is to be kept in sync with our host name
9213	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
9214
9215	set->RR_A.RRSet = &primary->RR_A;			// May refer to self
9216
9217	mDNS_Register_internal(m, &set->RR_A);
9218	mDNS_Register_internal(m, &set->RR_PTR);
9219
9220	if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
9221		{
9222		mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
9223		AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
9224		set->RR_HINFO.DependentOn = &set->RR_A;
9225		mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
9226		p += 1 + (int)p[0];
9227		mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
9228		mDNS_Register_internal(m, &set->RR_HINFO);
9229		}
9230	else
9231		{
9232		debugf("Not creating HINFO record: platform support layer provided no information");
9233		set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
9234		}
9235	}
9236
9237mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
9238	{
9239	NetworkInterfaceInfo *intf;
9240
9241    // If we still have address records referring to this one, update them
9242	NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
9243	AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
9244	for (intf = m->HostInterfaces; intf; intf = intf->next)
9245		if (intf->RR_A.RRSet == &set->RR_A)
9246			intf->RR_A.RRSet = A;
9247
9248	// Unregister these records.
9249	// When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
9250	// support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
9251	// Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
9252	// To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
9253	if (set->RR_A.    resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A,     mDNS_Dereg_normal);
9254	if (set->RR_PTR.  resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR,   mDNS_Dereg_normal);
9255	if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
9256	}
9257
9258mDNSexport void mDNS_SetFQDN(mDNS *const m)
9259	{
9260	domainname newmname;
9261	NetworkInterfaceInfo *intf;
9262	AuthRecord *rr;
9263	newmname.c[0] = 0;
9264
9265	if (!AppendDomainLabel(&newmname, &m->hostlabel))  { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
9266	if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
9267
9268	mDNS_Lock(m);
9269
9270	if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
9271	else
9272		{
9273		AssignDomainName(&m->MulticastHostname, &newmname);
9274
9275		// 1. Stop advertising our address records on all interfaces
9276		for (intf = m->HostInterfaces; intf; intf = intf->next)
9277			if (intf->Advertise) DeadvertiseInterface(m, intf);
9278
9279		// 2. Start advertising our address records using the new name
9280		for (intf = m->HostInterfaces; intf; intf = intf->next)
9281			if (intf->Advertise) AdvertiseInterface(m, intf);
9282		}
9283
9284	// 3. Make sure that any AutoTarget SRV records (and the like) get updated
9285	for (rr = m->ResourceRecords;  rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
9286	for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
9287
9288	mDNS_Unlock(m);
9289	}
9290
9291mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9292	{
9293	(void)rr;	// Unused parameter
9294
9295	#if MDNS_DEBUGMSGS
9296		{
9297		char *msg = "Unknown result";
9298		if      (result == mStatus_NoError)      msg = "Name registered";
9299		else if (result == mStatus_NameConflict) msg = "Name conflict";
9300		debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
9301		}
9302	#endif
9303
9304	if (result == mStatus_NoError)
9305		{
9306		// Notify the client that the host name is successfully registered
9307		if (m->MainCallback)
9308			m->MainCallback(m, mStatus_NoError);
9309		}
9310	else if (result == mStatus_NameConflict)
9311		{
9312		domainlabel oldlabel = m->hostlabel;
9313
9314		// 1. First give the client callback a chance to pick a new name
9315		if (m->MainCallback)
9316			m->MainCallback(m, mStatus_NameConflict);
9317
9318		// 2. If the client callback didn't do it, add (or increment) an index ourselves
9319		// This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
9320		// remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
9321		if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
9322			IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
9323
9324		// 3. Generate the FQDNs from the hostlabel,
9325		// and make sure all SRV records, etc., are updated to reference our new hostname
9326		mDNS_SetFQDN(m);
9327		LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
9328		}
9329	else if (result == mStatus_MemFree)
9330		{
9331		// .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
9332		// mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
9333		debugf("mDNS_HostNameCallback: MemFree (ignored)");
9334		}
9335	else
9336		LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result,  rr->resrec.name->c);
9337	}
9338
9339mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
9340	{
9341	NetworkInterfaceInfo *intf;
9342	active->IPv4Available = mDNSfalse;
9343	active->IPv6Available = mDNSfalse;
9344	for (intf = m->HostInterfaces; intf; intf = intf->next)
9345		if (intf->InterfaceID == active->InterfaceID)
9346			{
9347			if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
9348			if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
9349			}
9350	}
9351
9352mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
9353	{
9354	AuthRecord *rr;
9355	LogInfo("RestartRecordGetZoneData: ResourceRecords");
9356	for (rr = m->ResourceRecords; rr; rr=rr->next)
9357		if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
9358			{
9359			debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
9360			// Zero out the updateid so that if we have a pending response from the server, it won't
9361			// be accepted as a valid response. If we accept the response, we might free the new "nta"
9362			if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
9363			rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
9364			}
9365	}
9366
9367mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
9368	{
9369	int i;
9370	set->NetWakeBrowse.ThisQInterval = -1;
9371	for (i=0; i<3; i++)
9372		{
9373		set->NetWakeResolve[i].ThisQInterval = -1;
9374		set->SPSAddr[i].type = mDNSAddrType_None;
9375		}
9376	set->NextSPSAttempt     = -1;
9377	set->NextSPSAttemptTime = m->timenow;
9378	}
9379
9380mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
9381	{
9382	NetworkInterfaceInfo *p = m->HostInterfaces;
9383	while (p && p != set) p=p->next;
9384	if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
9385
9386	if (set->InterfaceActive)
9387		{
9388		LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
9389		mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, mDNSfalse, m->SPSBrowseCallback, set);
9390		}
9391	}
9392
9393mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
9394	{
9395	NetworkInterfaceInfo *p = m->HostInterfaces;
9396	while (p && p != set) p=p->next;
9397	if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
9398
9399	if (set->NetWakeBrowse.ThisQInterval >= 0)
9400		{
9401		int i;
9402		LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
9403
9404		// Stop our browse and resolve operations
9405		mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
9406		for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
9407
9408		// Make special call to the browse callback to let it know it can to remove all records for this interface
9409		if (m->SPSBrowseCallback)
9410			{
9411			mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
9412			m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
9413			mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
9414			}
9415
9416		// Reset our variables back to initial state, so we're ready for when NetWake is turned back on
9417		// (includes resetting NetWakeBrowse.ThisQInterval back to -1)
9418		InitializeNetWakeState(m, set);
9419		}
9420	}
9421
9422mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
9423	{
9424	AuthRecord *rr;
9425	mDNSBool FirstOfType = mDNStrue;
9426	NetworkInterfaceInfo **p = &m->HostInterfaces;
9427
9428	if (!set->InterfaceID)
9429		{ LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
9430
9431	if (!mDNSAddressIsValidNonZero(&set->mask))
9432		{ LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
9433
9434	mDNS_Lock(m);
9435
9436	// Assume this interface will be active now, unless we find a duplicate already in the list
9437	set->InterfaceActive = mDNStrue;
9438	set->IPv4Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
9439	set->IPv6Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
9440
9441	InitializeNetWakeState(m, set);
9442
9443	// Scan list to see if this InterfaceID is already represented
9444	while (*p)
9445		{
9446		if (*p == set)
9447			{
9448			LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
9449			mDNS_Unlock(m);
9450			return(mStatus_AlreadyRegistered);
9451			}
9452
9453		if ((*p)->InterfaceID == set->InterfaceID)
9454			{
9455			// This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
9456			set->InterfaceActive = mDNSfalse;
9457			if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
9458			if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
9459			if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
9460			}
9461
9462		p=&(*p)->next;
9463		}
9464
9465	set->next = mDNSNULL;
9466	*p = set;
9467
9468	if (set->Advertise)
9469		AdvertiseInterface(m, set);
9470
9471	LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set->InterfaceID, set->ifname, &set->ip,
9472		set->InterfaceActive ?
9473			"not represented in list; marking active and retriggering queries" :
9474			"already represented in list; marking inactive for now");
9475
9476	if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
9477
9478	// In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
9479	// giving the false impression that there's an active representative of this interface when there really isn't.
9480	// Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
9481	// even if we believe that we previously had an active representative of this interface.
9482	if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
9483		{
9484		DNSQuestion *q;
9485		// Normally, after an interface comes up, we pause half a second before beginning probing.
9486		// This is to guard against cases where there's rapid interface changes, where we could be confused by
9487		// seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
9488		// which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
9489		// We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
9490		// and think it's a conflicting answer to our probe.
9491		// In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
9492		const mDNSs32 probedelay  = flapping ? mDNSPlatformOneSecond * 5 : mDNSPlatformOneSecond / 2;
9493		const mDNSu8  numannounce = flapping ? (mDNSu8)1                 : InitialAnnounceCount;
9494
9495		// Use a small amount of randomness:
9496		// In the case of a network administrator turning on an Ethernet hub so that all the
9497		// connected machines establish link at exactly the same time, we don't want them all
9498		// to go and hit the network with identical queries at exactly the same moment.
9499		// We set a random delay of up to InitialQuestionInterval (1/3 second).
9500		// We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
9501		// that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
9502		// suppressing packet sending for more than about 1/3 second can cause protocol correctness
9503		// to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
9504		// See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
9505		if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
9506
9507		if (flapping) LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
9508
9509		LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
9510		if (m->SuppressProbes == 0 ||
9511			m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
9512			m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
9513
9514		// Include OWNER option in packets for 60 seconds after connecting to the network. Setting
9515		// it here also handles the wake up case as the network link comes UP after waking causing
9516		// us to reconnect to the network. If we do this as part of the wake up code, it is possible
9517		// that the network link comes UP after 60 seconds and we never set the OWNER option
9518		m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
9519		LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
9520
9521		for (q = m->Questions; q; q=q->next)								// Scan our list of questions
9522			if (mDNSOpaque16IsZero(q->TargetQID))
9523				if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)		// If non-specific Q, or Q on this specific interface,
9524					{															// then reactivate this question
9525					// If flapping, delay between first and second queries is nine seconds instead of one second
9526					mDNSBool dodelay = flapping && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
9527					mDNSs32 initial  = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
9528					mDNSs32 qdelay   = dodelay ? mDNSPlatformOneSecond * 5 : 0;
9529					if (dodelay) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q->qname.c, DNSTypeName(q->qtype));
9530
9531					if (!q->ThisQInterval || q->ThisQInterval > initial)
9532						{
9533						q->ThisQInterval = initial;
9534						q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
9535						}
9536					q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
9537					q->RecentAnswerPkts = 0;
9538					SetNextQueryTime(m,q);
9539					}
9540
9541		// For all our non-specific authoritative resource records (and any dormant records specific to this interface)
9542		// we now need them to re-probe if necessary, and then re-announce.
9543		for (rr = m->ResourceRecords; rr; rr=rr->next)
9544			if (!AuthRecord_uDNS(rr))
9545				if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
9546					{
9547					if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
9548					rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
9549					if (rr->AnnounceCount < numannounce) rr->AnnounceCount  = numannounce;
9550					rr->SendNSECNow    = mDNSNULL;
9551					InitializeLastAPTime(m, rr);
9552					}
9553		}
9554
9555	RestartRecordGetZoneData(m);
9556
9557	CheckSuppressUnusableQuestions(m);
9558
9559	mDNS_UpdateAllowSleep(m);
9560
9561	mDNS_Unlock(m);
9562	return(mStatus_NoError);
9563	}
9564
9565// Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
9566// the record list and/or question list.
9567// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9568mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
9569	{
9570	NetworkInterfaceInfo **p = &m->HostInterfaces;
9571	mDNSBool revalidate = mDNSfalse;
9572
9573	mDNS_Lock(m);
9574
9575	// Find this record in our list
9576	while (*p && *p != set) p=&(*p)->next;
9577	if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
9578
9579	mDNS_DeactivateNetWake_internal(m, set);
9580
9581	// Unlink this record from our list
9582	*p = (*p)->next;
9583	set->next = mDNSNULL;
9584
9585	if (!set->InterfaceActive)
9586		{
9587		// If this interface not the active member of its set, update the v4/v6Available flags for the active member
9588		NetworkInterfaceInfo *intf;
9589		for (intf = m->HostInterfaces; intf; intf = intf->next)
9590			if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
9591				UpdateInterfaceProtocols(m, intf);
9592		}
9593	else
9594		{
9595		NetworkInterfaceInfo *intf = FirstInterfaceForID(m, set->InterfaceID);
9596		if (intf)
9597			{
9598			LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
9599				" making it active", set->InterfaceID, set->ifname, &set->ip);
9600			if (intf->InterfaceActive)
9601				LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
9602			intf->InterfaceActive = mDNStrue;
9603			UpdateInterfaceProtocols(m, intf);
9604
9605			if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
9606
9607			// See if another representative *of the same type* exists. If not, we mave have gone from
9608			// dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
9609			for (intf = m->HostInterfaces; intf; intf = intf->next)
9610				if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
9611					break;
9612			if (!intf) revalidate = mDNStrue;
9613			}
9614		else
9615			{
9616			mDNSu32 slot;
9617			CacheGroup *cg;
9618			CacheRecord *rr;
9619			DNSQuestion *q;
9620			DNSServer *s;
9621
9622			LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
9623				" marking questions etc. dormant", set->InterfaceID, set->ifname, &set->ip);
9624
9625			if (set->McastTxRx && flapping)
9626				LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
9627
9628			// 1. Deactivate any questions specific to this interface, and tag appropriate questions
9629			// so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
9630			for (q = m->Questions; q; q=q->next)
9631				{
9632				if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
9633				if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
9634					{
9635					q->FlappingInterface2 = q->FlappingInterface1;
9636					q->FlappingInterface1 = set->InterfaceID;		// Keep history of the last two interfaces to go away
9637					}
9638				}
9639
9640			// 2. Flush any cache records received on this interface
9641			revalidate = mDNSfalse;		// Don't revalidate if we're flushing the records
9642			FORALL_CACHERECORDS(slot, cg, rr)
9643				if (rr->resrec.InterfaceID == set->InterfaceID)
9644					{
9645					// If this interface is deemed flapping,
9646					// postpone deleting the cache records in case the interface comes back again
9647					if (set->McastTxRx && flapping)
9648						{
9649						// For a flapping interface we want these record to go away after 30 seconds
9650						mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
9651						// We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
9652						// if the interface does come back, any relevant questions will be reactivated anyway
9653						rr->UnansweredQueries = MaxUnansweredQueries;
9654						}
9655					else
9656						mDNS_PurgeCacheResourceRecord(m, rr);
9657					}
9658
9659			// 3. Any DNS servers specific to this interface are now unusable
9660			for (s = m->DNSServers; s; s = s->next)
9661				if (s->interface == set->InterfaceID)
9662					{
9663					s->interface = mDNSInterface_Any;
9664					s->teststate = DNSServer_Disabled;
9665					}
9666			}
9667		}
9668
9669	// If we were advertising on this interface, deregister those address and reverse-lookup records now
9670	if (set->Advertise) DeadvertiseInterface(m, set);
9671
9672	// If we have any cache records received on this interface that went away, then re-verify them.
9673	// In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
9674	// giving the false impression that there's an active representative of this interface when there really isn't.
9675	// Don't need to do this when shutting down, because *all* interfaces are about to go away
9676	if (revalidate && !m->ShutdownTime)
9677		{
9678		mDNSu32 slot;
9679		CacheGroup *cg;
9680		CacheRecord *rr;
9681		FORALL_CACHERECORDS(slot, cg, rr)
9682			if (rr->resrec.InterfaceID == set->InterfaceID)
9683				mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
9684		}
9685
9686	CheckSuppressUnusableQuestions(m);
9687
9688	mDNS_UpdateAllowSleep(m);
9689
9690	mDNS_Unlock(m);
9691	}
9692
9693mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9694	{
9695	ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
9696	(void)m;	// Unused parameter
9697
9698	#if MDNS_DEBUGMSGS
9699		{
9700		char *msg = "Unknown result";
9701		if      (result == mStatus_NoError)      msg = "Name Registered";
9702		else if (result == mStatus_NameConflict) msg = "Name Conflict";
9703		else if (result == mStatus_MemFree)      msg = "Memory Free";
9704		debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
9705		}
9706	#endif
9707
9708	// Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
9709	if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
9710
9711	// If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
9712	if (result == mStatus_NameConflict)
9713		{
9714		sr->Conflict = mDNStrue;				// Record that this service set had a conflict
9715		mDNS_DeregisterService(m, sr);			// Unlink the records from our list
9716		return;
9717		}
9718
9719	if (result == mStatus_MemFree)
9720		{
9721		// If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
9722		// are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
9723		// every record is finished cleaning up.
9724		mDNSu32 i;
9725		ExtraResourceRecord *e = sr->Extras;
9726
9727		if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9728		if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9729		if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9730		if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9731		for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
9732
9733		while (e)
9734			{
9735			if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
9736			e = e->next;
9737			}
9738
9739		// If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
9740		// then we can now report the NameConflict to the client
9741		if (sr->Conflict) result = mStatus_NameConflict;
9742
9743		}
9744
9745	LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered": "Registered"), sr->RR_PTR.resrec.name->c);
9746	// CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
9747	// function is allowed to do anything, including deregistering this service and freeing its memory.
9748	if (sr->ServiceCallback)
9749		sr->ServiceCallback(m, sr, result);
9750	}
9751
9752mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9753	{
9754	ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
9755	if (sr->ServiceCallback)
9756		sr->ServiceCallback(m, sr, result);
9757	}
9758
9759// Note:
9760// Name is first label of domain name (any dots in the name are actual dots, not label separators)
9761// Type is service type (e.g. "_ipp._tcp.")
9762// Domain is fully qualified domain name (i.e. ending with a null label)
9763// We always register a TXT, even if it is empty (so that clients are not
9764// left waiting forever looking for a nonexistent record.)
9765// If the host parameter is mDNSNULL or the root domain (ASCII NUL),
9766// then the default host name (m->MulticastHostname) is automatically used
9767// If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
9768mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
9769	const domainlabel *const name, const domainname *const type, const domainname *const domain,
9770	const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
9771	AuthRecord *SubTypes, mDNSu32 NumSubTypes,
9772	mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
9773	{
9774	mStatus err;
9775	mDNSu32 i;
9776	mDNSu32 hostTTL;
9777	AuthRecType artype;
9778	mDNSu8 recordType = (flags & regFlagKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
9779
9780	sr->ServiceCallback = Callback;
9781	sr->ServiceContext  = Context;
9782	sr->Conflict        = mDNSfalse;
9783
9784	sr->Extras          = mDNSNULL;
9785	sr->NumSubTypes     = NumSubTypes;
9786	sr->SubTypes        = SubTypes;
9787
9788	if (InterfaceID == mDNSInterface_LocalOnly)
9789		artype = AuthRecordLocalOnly;
9790	else if (InterfaceID == mDNSInterface_P2P)
9791		artype = AuthRecordP2P;
9792	else if ((InterfaceID == mDNSInterface_Any) && (flags & regFlagIncludeP2P))
9793		artype = AuthRecordAnyIncludeP2P;
9794	else
9795		artype = AuthRecordAny;
9796
9797	// Initialize the AuthRecord objects to sane values
9798	// Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
9799	mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
9800	mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared,   artype, ServiceCallback, sr);
9801
9802	if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
9803		hostTTL = kHostNameSmallTTL;
9804	else
9805		hostTTL = kHostNameTTL;
9806
9807	mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
9808	mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
9809
9810	// If port number is zero, that means the client is really trying to do a RegisterNoSuchService
9811	if (mDNSIPPortIsZero(port))
9812		return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, (flags & regFlagIncludeP2P)));
9813
9814	// If the client is registering an oversized TXT record,
9815	// it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
9816	if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
9817		sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
9818
9819	// Set up the record names
9820	// For now we only create an advisory record for the main type, not for subtypes
9821	// We need to gain some operational experience before we decide if there's a need to create them for subtypes too
9822	if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
9823		return(mStatus_BadParamErr);
9824	if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
9825	if (ConstructServiceName(&sr->RR_SRV.namestorage, name,     type, domain) == mDNSNULL) return(mStatus_BadParamErr);
9826	AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
9827
9828	// 1. Set up the ADV record rdata to advertise our service type
9829	AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
9830
9831	// 2. Set up the PTR record rdata to point to our service name
9832	// We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
9833	// Note: uDNS registration code assumes that Additional1 points to the SRV record
9834	AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
9835	sr->RR_PTR.Additional1 = &sr->RR_SRV;
9836	sr->RR_PTR.Additional2 = &sr->RR_TXT;
9837
9838	// 2a. Set up any subtype PTRs to point to our service name
9839	// If the client is using subtypes, it is the client's responsibility to have
9840	// already set the first label of the record name to the subtype being registered
9841	for (i=0; i<NumSubTypes; i++)
9842		{
9843		domainname st;
9844		AssignDomainName(&st, sr->SubTypes[i].resrec.name);
9845		st.c[1+st.c[0]] = 0;			// Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
9846		AppendDomainName(&st, type);
9847		mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
9848		if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
9849		AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
9850		sr->SubTypes[i].Additional1 = &sr->RR_SRV;
9851		sr->SubTypes[i].Additional2 = &sr->RR_TXT;
9852		}
9853
9854	// 3. Set up the SRV record rdata.
9855	sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
9856	sr->RR_SRV.resrec.rdata->u.srv.weight   = 0;
9857	sr->RR_SRV.resrec.rdata->u.srv.port     = port;
9858
9859	// Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
9860	if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
9861	else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
9862
9863	// 4. Set up the TXT record rdata,
9864	// and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
9865	// Note: uDNS registration code assumes that DependentOn points to the SRV record
9866	if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
9867	else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
9868		{
9869		sr->RR_TXT.resrec.rdlength = txtlen;
9870		if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
9871		mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
9872		}
9873	sr->RR_TXT.DependentOn = &sr->RR_SRV;
9874
9875	mDNS_Lock(m);
9876	// It is important that we register SRV first. uDNS assumes that SRV is registered first so
9877	// that if the SRV cannot find a target, rest of the records that belong to this service
9878	// will not be activated.
9879	err = mDNS_Register_internal(m, &sr->RR_SRV);
9880	// If we can't register the SRV record due to errors, bail out. It has not been inserted in
9881	// any list and hence no need to deregister. We could probably do similar checks for other
9882	// records below and bail out. For now, this seems to be sufficient to address rdar://9304275
9883	if (err)
9884		{
9885		mDNS_Unlock(m);
9886		return err;
9887		}
9888	if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
9889	// We register the RR_PTR last, because we want to be sure that in the event of a forced call to
9890	// mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
9891	// the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
9892	// the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
9893	// make sure we've deregistered all our records and done any other necessary cleanup before that happens.
9894	if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
9895	for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
9896	if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
9897
9898	mDNS_Unlock(m);
9899
9900	if (err) mDNS_DeregisterService(m, sr);
9901	return(err);
9902	}
9903
9904mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
9905	ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl,  mDNSu32 includeP2P)
9906	{
9907	ExtraResourceRecord **e;
9908	mStatus status;
9909	AuthRecType artype;
9910	mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
9911
9912	if (InterfaceID == mDNSInterface_LocalOnly)
9913		artype = AuthRecordLocalOnly;
9914	if (InterfaceID == mDNSInterface_P2P)
9915		artype = AuthRecordP2P;
9916	else if ((InterfaceID == mDNSInterface_Any) && includeP2P)
9917		artype = AuthRecordAnyIncludeP2P;
9918	else
9919		artype = AuthRecordAny;
9920
9921	extra->next = mDNSNULL;
9922	mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
9923		extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
9924	AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
9925
9926	mDNS_Lock(m);
9927	e = &sr->Extras;
9928	while (*e) e = &(*e)->next;
9929
9930	if (ttl == 0) ttl = kStandardTTL;
9931
9932	extra->r.DependentOn = &sr->RR_SRV;
9933
9934	debugf("mDNS_AddRecordToService adding record to %##s %s %d",
9935		extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
9936
9937	status = mDNS_Register_internal(m, &extra->r);
9938	if (status == mStatus_NoError) *e = extra;
9939
9940	mDNS_Unlock(m);
9941	return(status);
9942	}
9943
9944mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
9945	mDNSRecordCallback MemFreeCallback, void *Context)
9946	{
9947	ExtraResourceRecord **e;
9948	mStatus status;
9949
9950	mDNS_Lock(m);
9951	e = &sr->Extras;
9952	while (*e && *e != extra) e = &(*e)->next;
9953	if (!*e)
9954		{
9955		debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
9956		status = mStatus_BadReferenceErr;
9957		}
9958	else
9959		{
9960		debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
9961		extra->r.RecordCallback = MemFreeCallback;
9962		extra->r.RecordContext  = Context;
9963		*e = (*e)->next;
9964		status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
9965		}
9966	mDNS_Unlock(m);
9967	return(status);
9968	}
9969
9970mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
9971	{
9972	// Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
9973	// mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
9974	domainlabel name1, name2;
9975	domainname type, domain;
9976	const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
9977	ExtraResourceRecord *extras = sr->Extras;
9978	mStatus err;
9979
9980	DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
9981	if (!newname)
9982		{
9983		name2 = name1;
9984		IncrementLabelSuffix(&name2, mDNStrue);
9985		newname = &name2;
9986		}
9987
9988	if (SameDomainName(&domain, &localdomain))
9989		debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
9990	else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
9991
9992	err = mDNS_RegisterService(m, sr, newname, &type, &domain,
9993		host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
9994		sr->SubTypes, sr->NumSubTypes,
9995		sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, 0);
9996
9997	// mDNS_RegisterService() just reset sr->Extras to NULL.
9998	// Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
9999	// through the old list of extra records, and re-add them to our freshly created service registration
10000	while (!err && extras)
10001		{
10002		ExtraResourceRecord *e = extras;
10003		extras = extras->next;
10004		err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
10005		}
10006
10007	return(err);
10008	}
10009
10010// Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
10011// which may change the record list and/or question list.
10012// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
10013mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
10014	{
10015	// If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
10016	if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
10017
10018	if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
10019		{
10020		debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
10021		return(mStatus_BadReferenceErr);
10022		}
10023	else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
10024		{
10025		LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
10026		// Avoid race condition:
10027		// If a service gets a conflict, then we set the Conflict flag to tell us to generate
10028		// an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
10029		// If the client happens to deregister the service in the middle of that process, then
10030		// we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
10031		// instead of incorrectly promoting it to mStatus_NameConflict.
10032		// This race condition is exposed particularly when the conformance test generates
10033		// a whole batch of simultaneous conflicts across a range of services all advertised
10034		// using the same system default name, and if we don't take this precaution then
10035		// we end up incrementing m->nicelabel multiple times instead of just once.
10036		// <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
10037		sr->Conflict = mDNSfalse;
10038		return(mStatus_NoError);
10039		}
10040	else
10041		{
10042		mDNSu32 i;
10043		mStatus status;
10044		ExtraResourceRecord *e;
10045		mDNS_Lock(m);
10046		e = sr->Extras;
10047
10048		// We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
10049		// SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
10050		mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
10051		mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
10052
10053		mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
10054
10055		// We deregister all of the extra records, but we leave the sr->Extras list intact
10056		// in case the client wants to do a RenameAndReregister and reinstate the registration
10057		while (e)
10058			{
10059			mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
10060			e = e->next;
10061			}
10062
10063		for (i=0; i<sr->NumSubTypes; i++)
10064			mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
10065
10066		status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
10067		mDNS_Unlock(m);
10068		return(status);
10069		}
10070	}
10071
10072// Create a registration that asserts that no such service exists with this name.
10073// This can be useful where there is a given function is available through several protocols.
10074// For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
10075// protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
10076// "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
10077// could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
10078mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
10079	const domainlabel *const name, const domainname *const type, const domainname *const domain,
10080	const domainname *const host,
10081	const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSBool includeP2P)
10082	{
10083	AuthRecType artype;
10084
10085	if (InterfaceID == mDNSInterface_LocalOnly)
10086		artype = AuthRecordLocalOnly;
10087	else if (InterfaceID == mDNSInterface_P2P)
10088		artype = AuthRecordP2P;
10089	else if ((InterfaceID == mDNSInterface_Any) && includeP2P)
10090		artype = AuthRecordAnyIncludeP2P;
10091	else
10092		artype = AuthRecordAny;
10093
10094	mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
10095	if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
10096	rr->resrec.rdata->u.srv.priority    = 0;
10097	rr->resrec.rdata->u.srv.weight      = 0;
10098	rr->resrec.rdata->u.srv.port        = zeroIPPort;
10099	if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
10100	else rr->AutoTarget = Target_AutoHost;
10101	return(mDNS_Register(m, rr));
10102	}
10103
10104mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
10105	mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
10106	{
10107	AuthRecType artype;
10108
10109	if (InterfaceID == mDNSInterface_LocalOnly)
10110		artype = AuthRecordLocalOnly;
10111	else if (InterfaceID == mDNSInterface_P2P)
10112		artype = AuthRecordP2P;
10113	else
10114		artype = AuthRecordAny;
10115	mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
10116	if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
10117	if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname))                 return(mStatus_BadParamErr);
10118	return(mDNS_Register(m, rr));
10119	}
10120
10121mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
10122	{
10123	AuthRecord *r;
10124	for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
10125	return mDNSfalse;
10126	}
10127
10128mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
10129	{
10130	DNSQuestion *q;
10131	for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
10132	return mDNSfalse;
10133	}
10134
10135mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
10136	{
10137	mDNSOpaque16 id;
10138	int i;
10139
10140	for (i=0; i<10; i++)
10141		{
10142		id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
10143		if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
10144		}
10145
10146	debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
10147
10148	return id;
10149	}
10150
10151// ***************************************************************************
10152#if COMPILER_LIKES_PRAGMA_MARK
10153#pragma mark -
10154#pragma mark - Sleep Proxy Server
10155#endif
10156
10157mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
10158	{
10159	// If we see an ARP from a machine we think is sleeping, then either
10160	// (i) the machine has woken, or
10161	// (ii) it's just a stray old packet from before the machine slept
10162	// To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
10163	// generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
10164	// If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
10165	// 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*
10166	// need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
10167	// re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
10168
10169	rr->resrec.RecordType = kDNSRecordTypeUnique;
10170	rr->ProbeCount        = DefaultProbeCountForTypeUnique;
10171
10172	// If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
10173	// still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
10174	// If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
10175	// we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
10176	// sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
10177	// didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
10178	if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
10179		InitializeLastAPTime(m, rr);
10180	else
10181		{
10182		rr->AnnounceCount  = InitialAnnounceCount;
10183		rr->ThisAPInterval = mDNSPlatformOneSecond;
10184		rr->LastAPTime     = m->timenow + mDNSPlatformOneSecond * 9;	// Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
10185		SetNextAnnounceProbeTime(m, rr);
10186		}
10187	}
10188
10189mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
10190	{
10191	static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
10192	AuthRecord *rr;
10193	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
10194	if (!intf) return;
10195
10196	mDNS_Lock(m);
10197
10198	// Pass 1:
10199	// Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
10200	// We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
10201	// We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
10202	// The times we might need to react to an ARP Announcement are:
10203	// (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
10204	// (ii) if it's a conflicting Announcement from another host
10205	// -- and we check for these in Pass 2 below.
10206	if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
10207		{
10208		for (rr = m->ResourceRecords; rr; rr=rr->next)
10209			if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10210				rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
10211				{
10212				static const char msg1[] = "ARP Req from owner -- re-probing";
10213				static const char msg2[] = "Ignoring  ARP Request from      ";
10214				static const char msg3[] = "Creating Local ARP Cache entry  ";
10215				static const char msg4[] = "Answering ARP Request from      ";
10216				const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
10217										(rr->AnnounceCount == InitialAnnounceCount)     ? msg2 :
10218										mDNSSameEthAddress(&arp->sha, &intf->MAC)       ? msg3 : msg4;
10219				LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
10220					intf->ifname, msg, &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10221				if      (msg == msg1) RestartARPProbing(m, rr);
10222				else if (msg == msg3) mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
10223				else if (msg == msg4) SendARP(m, 2, rr, &arp->tpa, &arp->sha, &arp->spa, &arp->sha);
10224				}
10225		}
10226
10227	// Pass 2:
10228	// 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.
10229	// (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
10230	// so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
10231	// 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.
10232	// If we see an apparently conflicting ARP, we check the sender hardware address:
10233	//   If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
10234	//   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.
10235	if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
10236		debugf("ARP from self for %.4a", &arp->tpa);
10237	else
10238		{
10239		if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
10240			for (rr = m->ResourceRecords; rr; rr=rr->next)
10241				if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10242					rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa))
10243					{
10244					RestartARPProbing(m, rr);
10245					if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
10246						LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
10247							mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request      " : "Response     ",
10248							&arp->sha, &arp->spa, &arp->tpa, ARDisplayString(m, rr));
10249					else
10250						{
10251						LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
10252							&arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10253						ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10254						}
10255					}
10256		}
10257
10258	mDNS_Unlock(m);
10259	}
10260
10261/*
10262// Option 1 is Source Link Layer Address Option
10263// Option 2 is Target Link Layer Address Option
10264mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
10265	{
10266	const mDNSu8 *options = (mDNSu8 *)(ndp+1);
10267	while (options < end)
10268		{
10269		debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
10270		if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
10271		options += options[1] * 8;
10272		}
10273	return mDNSNULL;
10274	}
10275*/
10276
10277mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
10278	const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
10279	{
10280	AuthRecord *rr;
10281	NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
10282	if (!intf) return;
10283
10284	mDNS_Lock(m);
10285
10286	// Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
10287	if (ndp->type == NDP_Sol)
10288		{
10289		//const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
10290		(void)end;
10291		for (rr = m->ResourceRecords; rr; rr=rr->next)
10292			if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10293				rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
10294				{
10295				static const char msg1[] = "NDP Req from owner -- re-probing";
10296				static const char msg2[] = "Ignoring  NDP Request from      ";
10297				static const char msg3[] = "Creating Local NDP Cache entry  ";
10298				static const char msg4[] = "Answering NDP Request from      ";
10299				static const char msg5[] = "Answering NDP Probe   from      ";
10300				const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
10301										(rr->AnnounceCount == InitialAnnounceCount)      ? msg2 :
10302										sha && mDNSSameEthAddress(sha, &intf->MAC)       ? msg3 :
10303										spa && mDNSIPv6AddressIsZero(*spa)               ? msg4 : msg5;
10304				LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
10305					intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10306				if      (msg == msg1) RestartARPProbing(m, rr);
10307				else if (msg == msg3)
10308					{
10309					if (!(m->KnownBugs & mDNS_KnownBug_LimitedIPv6))
10310						mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
10311					}
10312				else if (msg == msg4) SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa,          sha             );
10313				else if (msg == msg5) SendNDP(m, NDP_Adv, 0,             rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
10314				}
10315		}
10316
10317	// 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.
10318	if (mDNSSameEthAddress(sha, &intf->MAC))
10319		debugf("NDP from self for %.16a", &ndp->target);
10320	else
10321		{
10322		// For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
10323		// When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
10324		// about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
10325		// Hence it is the NDP target address we care about, not the actual packet source address.
10326		if (ndp->type == NDP_Adv) spa = &ndp->target;
10327		if (!mDNSSameIPv6Address(*spa, zerov6Addr))
10328			for (rr = m->ResourceRecords; rr; rr=rr->next)
10329				if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10330					rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa))
10331					{
10332					RestartARPProbing(m, rr);
10333					if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
10334						LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
10335							ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
10336					else
10337						{
10338						LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
10339							sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
10340						ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10341						}
10342					}
10343		}
10344
10345	mDNS_Unlock(m);
10346	}
10347
10348mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
10349	const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
10350	{
10351	const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
10352	mDNSBool wake = mDNSfalse;
10353
10354	switch (protocol)
10355		{
10356		#define XX wake ? "Received" : "Ignoring", end-p
10357		case 0x01:	LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
10358					break;
10359
10360		case 0x06:	{
10361					#define SSH_AsNumber 22
10362					static const mDNSIPPort SSH = { { SSH_AsNumber >> 8, SSH_AsNumber & 0xFF } };
10363
10364					// Plan to wake if
10365					// (a) RST is not set, AND
10366					// (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
10367					wake = (!(t->tcp.flags & 4) && (t->tcp.flags & 3) != 1);
10368
10369					// For now, to reduce spurious wakeups, we wake only for TCP SYN,
10370					// except for ssh connections, where we'll wake for plain data packets too
10371					if (!mDNSSameIPPort(port, SSH) && !(t->tcp.flags & 2)) wake = mDNSfalse;
10372
10373					LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
10374						src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
10375						(t->tcp.flags & 2) ? " SYN" : "",
10376						(t->tcp.flags & 1) ? " FIN" : "",
10377						(t->tcp.flags & 4) ? " RST" : "");
10378					}
10379					break;
10380
10381		case 0x11:	{
10382					#define ARD_AsNumber 3283
10383					static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
10384					const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]);		// Length *including* 8-byte UDP header
10385					if (udplen >= sizeof(UDPHeader))
10386						{
10387						const mDNSu16 datalen = udplen - sizeof(UDPHeader);
10388						wake = mDNStrue;
10389
10390						// For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
10391						if (mDNSSameIPPort(port, IPSECPort))
10392							{
10393							// Specifically ignore NAT keepalive packets
10394							if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
10395							else
10396								{
10397								// Skip over the Non-ESP Marker if present
10398								const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
10399								const IKEHeader *const ike    = (IKEHeader *)(t + (NonESP ? 12 : 8));
10400								const mDNSu16          ikelen = datalen - (NonESP ? 4 : 0);
10401								if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
10402									if ((ike->Version & 0x10) == 0x10)
10403										{
10404										// ExchangeType ==  5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
10405										// ExchangeType == 34 means 'IKE_SA_INIT'   <http://www.iana.org/assignments/ikev2-parameters>
10406										if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
10407										LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
10408										}
10409								}
10410							}
10411
10412						// For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
10413						// Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
10414						// except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
10415						// UDP header (8 bytes)
10416						// Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
10417						if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
10418
10419						LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
10420						}
10421					}
10422					break;
10423
10424		case 0x3A:	if (&t->bytes[len] <= end)
10425						{
10426						mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
10427						if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
10428						else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
10429						}
10430					break;
10431
10432		default:	LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
10433					break;
10434		}
10435
10436	if (wake)
10437		{
10438		AuthRecord *rr, *r2;
10439
10440		mDNS_Lock(m);
10441		for (rr = m->ResourceRecords; rr; rr=rr->next)
10442			if (rr->resrec.InterfaceID == InterfaceID &&
10443				rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
10444				rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
10445				{
10446				const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
10447				for (r2 = m->ResourceRecords; r2; r2=r2->next)
10448					if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
10449						r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
10450						r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
10451						SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
10452						break;
10453				if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr;	// So that we wake for BTMM IPSEC packets, even without a matching SRV record
10454				if (r2)
10455					{
10456					LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
10457						InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
10458					ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
10459					}
10460				else
10461					LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
10462						InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
10463				}
10464		mDNS_Unlock(m);
10465		}
10466	}
10467
10468mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
10469	{
10470	static const mDNSOpaque16 Ethertype_ARP  = { { 0x08, 0x06 } };	// Ethertype 0x0806 = ARP
10471	static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } };	// Ethertype 0x0800 = IPv4
10472	static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } };	// Ethertype 0x86DD = IPv6
10473	static const mDNSOpaque16 ARP_hrd_eth    = { { 0x00, 0x01 } };	// Hardware address space (Ethernet = 1)
10474	static const mDNSOpaque16 ARP_pro_ip     = { { 0x08, 0x00 } };	// Protocol address space (IP = 0x0800)
10475
10476	// Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
10477	// In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
10478	// but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
10479	// since it points to a an address 14 bytes before pkt.
10480	const EthernetHeader     *const eth = (const EthernetHeader *)p;
10481	const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
10482	mDNSAddr src, dst;
10483	#define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
10484
10485	// Is ARP? Length must be at least 14 + 28 = 42 bytes
10486	if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
10487		mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
10488	// Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
10489	else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
10490		{
10491		const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
10492		debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
10493		src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
10494		dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
10495		if (end >= trans + RequiredCapLen(pkt->v4.protocol))
10496			mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, end, InterfaceID, 0);
10497		}
10498	// Is IPv6? Length must be at least 14 + 28 = 42 bytes
10499	else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
10500		{
10501		const mDNSu8 *const trans = p + 54;
10502		debugf("Got IPv6  %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
10503		src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
10504		dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
10505		if (end >= trans + RequiredCapLen(pkt->v6.pro))
10506			mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
10507				(mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
10508		}
10509	}
10510
10511mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
10512	{
10513	name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d %#s",
10514		m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, &m->nicelabel);
10515	}
10516
10517mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
10518	{
10519	if (result == mStatus_NameConflict)
10520		mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
10521	else if (result == mStatus_MemFree)
10522		{
10523		if (m->SleepState)
10524			m->SPSState = 3;
10525		else
10526			{
10527			m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
10528			if (m->SPSState)
10529				{
10530				domainlabel name;
10531				ConstructSleepProxyServerName(m, &name);
10532				mDNS_RegisterService(m, srs,
10533					&name, &SleepProxyServiceType, &localdomain,
10534					mDNSNULL, m->SPSSocket->port,				// Host, port
10535					(mDNSu8 *)"", 1,							// TXT data, length
10536					mDNSNULL, 0,								// Subtypes (none)
10537					mDNSInterface_Any,							// Interface ID
10538					SleepProxyServerCallback, mDNSNULL, 0);		// Callback, context, flags
10539				}
10540			LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
10541			}
10542		}
10543	}
10544
10545// Called with lock held
10546mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower)
10547	{
10548	// This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
10549	mDNS_DropLockBeforeCallback();
10550
10551	// If turning off SPS, close our socket
10552	// (Do this first, BEFORE calling mDNS_DeregisterService below)
10553	if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
10554
10555	// If turning off, or changing type, deregister old name
10556	if (m->SPSState == 1 && sps != m->SPSType)
10557		{ m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
10558
10559	// Record our new SPS parameters
10560	m->SPSType          = sps;
10561	m->SPSPortability   = port;
10562	m->SPSMarginalPower = marginalpower;
10563	m->SPSTotalPower    = totpower;
10564
10565	// If turning on, open socket and advertise service
10566	if (sps)
10567		{
10568		if (!m->SPSSocket)
10569			{
10570			m->SPSSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
10571			if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
10572			}
10573		if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
10574		}
10575	else if (m->SPSState)
10576		{
10577		LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
10578		m->NextScheduledSPS = m->timenow;
10579		}
10580fail:
10581	mDNS_ReclaimLockAfterCallback();
10582	}
10583
10584// ***************************************************************************
10585#if COMPILER_LIKES_PRAGMA_MARK
10586#pragma mark -
10587#pragma mark - Startup and Shutdown
10588#endif
10589
10590mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
10591	{
10592	if (storage && numrecords)
10593		{
10594		mDNSu32 i;
10595		debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
10596		for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
10597		storage[numrecords-1].next = m->rrcache_free;
10598		m->rrcache_free = storage;
10599		m->rrcache_size += numrecords;
10600		}
10601	}
10602
10603mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
10604	{
10605	mDNS_Lock(m);
10606	mDNS_GrowCache_internal(m, storage, numrecords);
10607	mDNS_Unlock(m);
10608	}
10609
10610mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
10611	CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
10612	mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
10613	{
10614	mDNSu32 slot;
10615	mDNSs32 timenow;
10616	mStatus result;
10617
10618	if (!rrcachestorage) rrcachesize = 0;
10619
10620	m->p                             = p;
10621	m->KnownBugs                     = 0;
10622	m->CanReceiveUnicastOn5353       = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
10623	m->AdvertiseLocalAddresses       = AdvertiseLocalAddresses;
10624	m->DivertMulticastAdvertisements = mDNSfalse;
10625	m->mDNSPlatformStatus            = mStatus_Waiting;
10626	m->UnicastPort4                  = zeroIPPort;
10627	m->UnicastPort6                  = zeroIPPort;
10628	m->PrimaryMAC                    = zeroEthAddr;
10629	m->MainCallback                  = Callback;
10630	m->MainContext                   = Context;
10631	m->rec.r.resrec.RecordType       = 0;
10632
10633	// For debugging: To catch and report locking failures
10634	m->mDNS_busy               = 0;
10635	m->mDNS_reentrancy         = 0;
10636	m->ShutdownTime            = 0;
10637	m->lock_rrcache            = 0;
10638	m->lock_Questions          = 0;
10639	m->lock_Records            = 0;
10640
10641	// Task Scheduling variables
10642	result = mDNSPlatformTimeInit();
10643	if (result != mStatus_NoError) return(result);
10644	m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
10645	timenow = mDNS_TimeNow_NoLock(m);
10646
10647	m->timenow                 = 0;		// MUST only be set within mDNS_Lock/mDNS_Unlock section
10648	m->timenow_last            = timenow;
10649	m->NextScheduledEvent      = timenow;
10650	m->SuppressSending         = timenow;
10651	m->NextCacheCheck          = timenow + 0x78000000;
10652	m->NextScheduledQuery      = timenow + 0x78000000;
10653	m->NextScheduledProbe      = timenow + 0x78000000;
10654	m->NextScheduledResponse   = timenow + 0x78000000;
10655	m->NextScheduledNATOp      = timenow + 0x78000000;
10656	m->NextScheduledSPS        = timenow + 0x78000000;
10657	m->NextScheduledStopTime   = timenow + 0x78000000;
10658	m->RandomQueryDelay        = 0;
10659	m->RandomReconfirmDelay    = 0;
10660	m->PktNum                  = 0;
10661	m->LocalRemoveEvents       = mDNSfalse;
10662	m->SleepState              = SleepState_Awake;
10663	m->SleepSeqNum             = 0;
10664	m->SystemWakeOnLANEnabled  = mDNSfalse;
10665	m->AnnounceOwner           = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
10666	m->DelaySleep              = 0;
10667	m->SleepLimit              = 0;
10668
10669	// These fields only required for mDNS Searcher...
10670	m->Questions               = mDNSNULL;
10671	m->NewQuestions            = mDNSNULL;
10672	m->CurrentQuestion         = mDNSNULL;
10673	m->LocalOnlyQuestions      = mDNSNULL;
10674	m->NewLocalOnlyQuestions   = mDNSNULL;
10675	m->RestartQuestion	       = mDNSNULL;
10676	m->rrcache_size            = 0;
10677	m->rrcache_totalused       = 0;
10678	m->rrcache_active          = 0;
10679	m->rrcache_report          = 10;
10680	m->rrcache_free            = mDNSNULL;
10681
10682	for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
10683		{
10684		m->rrcache_hash[slot]      = mDNSNULL;
10685		m->rrcache_nextcheck[slot] = timenow + 0x78000000;;
10686		}
10687
10688	mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
10689	m->rrauth.rrauth_free            = mDNSNULL;
10690
10691	for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
10692		m->rrauth.rrauth_hash[slot] = mDNSNULL;
10693
10694	// Fields below only required for mDNS Responder...
10695	m->hostlabel.c[0]          = 0;
10696	m->nicelabel.c[0]          = 0;
10697	m->MulticastHostname.c[0]  = 0;
10698	m->HIHardware.c[0]         = 0;
10699	m->HISoftware.c[0]         = 0;
10700	m->ResourceRecords         = mDNSNULL;
10701	m->DuplicateRecords        = mDNSNULL;
10702	m->NewLocalRecords         = mDNSNULL;
10703	m->NewLocalOnlyRecords     = mDNSfalse;
10704	m->CurrentRecord           = mDNSNULL;
10705	m->HostInterfaces          = mDNSNULL;
10706	m->ProbeFailTime           = 0;
10707	m->NumFailedProbes         = 0;
10708	m->SuppressProbes          = 0;
10709
10710#ifndef UNICAST_DISABLED
10711	m->NextuDNSEvent            = timenow + 0x78000000;
10712	m->NextSRVUpdate            = timenow + 0x78000000;
10713
10714	m->DNSServers               = mDNSNULL;
10715
10716	m->Router                   = zeroAddr;
10717	m->AdvertisedV4             = zeroAddr;
10718	m->AdvertisedV6             = zeroAddr;
10719
10720	m->AuthInfoList             = mDNSNULL;
10721
10722	m->ReverseMap.ThisQInterval = -1;
10723	m->StaticHostname.c[0]      = 0;
10724	m->FQDN.c[0]                = 0;
10725	m->Hostnames                = mDNSNULL;
10726	m->AutoTunnelHostAddr.b[0]  = 0;
10727	m->AutoTunnelHostAddrActive = mDNSfalse;
10728	m->AutoTunnelLabel.c[0]     = 0;
10729
10730	m->StartWABQueries          = mDNSfalse;
10731	m->RegisterAutoTunnel6      = mDNStrue;
10732
10733	// NAT traversal fields
10734	m->NATTraversals            = mDNSNULL;
10735	m->CurrentNATTraversal      = mDNSNULL;
10736	m->retryIntervalGetAddr     = 0;	// delta between time sent and retry
10737	m->retryGetAddr             = timenow + 0x78000000;	// absolute time when we retry
10738	m->ExternalAddress          = zerov4Addr;
10739
10740	m->NATMcastRecvskt          = mDNSNULL;
10741	m->LastNATupseconds         = 0;
10742	m->LastNATReplyLocalTime    = timenow;
10743	m->LastNATMapResultCode     = NATErr_None;
10744
10745	m->UPnPInterfaceID          = 0;
10746	m->SSDPSocket               = mDNSNULL;
10747	m->SSDPWANPPPConnection     = mDNSfalse;
10748	m->UPnPRouterPort           = zeroIPPort;
10749	m->UPnPSOAPPort             = zeroIPPort;
10750	m->UPnPRouterURL            = mDNSNULL;
10751	m->UPnPWANPPPConnection     = mDNSfalse;
10752	m->UPnPSOAPURL              = mDNSNULL;
10753	m->UPnPRouterAddressString  = mDNSNULL;
10754	m->UPnPSOAPAddressString    = mDNSNULL;
10755	m->SPSType                  = 0;
10756	m->SPSPortability           = 0;
10757	m->SPSMarginalPower         = 0;
10758	m->SPSTotalPower            = 0;
10759	m->SPSState                 = 0;
10760	m->SPSProxyListChanged      = mDNSNULL;
10761	m->SPSSocket                = mDNSNULL;
10762	m->SPSBrowseCallback        = mDNSNULL;
10763	m->ProxyRecords             = 0;
10764
10765#endif
10766
10767#if APPLE_OSX_mDNSResponder
10768	m->TunnelClients            = mDNSNULL;
10769
10770#if ! NO_WCF
10771	CHECK_WCF_FUNCTION(WCFConnectionNew)
10772		{
10773		m->WCF = WCFConnectionNew();
10774		if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
10775		}
10776#endif
10777
10778#endif
10779
10780	result = mDNSPlatformInit(m);
10781
10782#ifndef UNICAST_DISABLED
10783	// It's better to do this *after* the platform layer has set up the
10784	// interface list and security credentials
10785	uDNS_SetupDNSConfig(m);						// Get initial DNS configuration
10786#endif
10787
10788	return(result);
10789	}
10790
10791mDNSexport void mDNS_ConfigChanged(mDNS *const m)
10792	{
10793	if (m->SPSState == 1)
10794		{
10795		domainlabel name, newname;
10796		domainname type, domain;
10797		DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
10798		ConstructSleepProxyServerName(m, &newname);
10799		if (!SameDomainLabelCS(name.c, newname.c))
10800			{
10801			LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
10802			// When SleepProxyServerCallback gets the mStatus_MemFree message,
10803			// it will reregister the service under the new name
10804			m->SPSState = 2;
10805			mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
10806			}
10807		}
10808
10809	if (m->MainCallback)
10810		m->MainCallback(m, mStatus_ConfigChanged);
10811	}
10812
10813mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
10814	{
10815	(void)m;	// unused
10816	debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
10817	mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
10818	}
10819
10820mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
10821	{
10822	mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
10823					 cr->resrec.rrtype     == kDNSType_A ||
10824					 cr->resrec.rrtype     == kDNSType_AAAA ||
10825					 cr->resrec.rrtype     == kDNSType_SRV;
10826
10827	(void) lameduck;
10828	(void) ptr;
10829	debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
10830		purge    ? "purging"   : "reconfirming",
10831		lameduck ? "lame duck" : "new",
10832		ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
10833
10834	if (purge)
10835		{
10836		LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
10837		mDNS_PurgeCacheResourceRecord(m, cr);
10838		}
10839	else
10840		{
10841		LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
10842		mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
10843		}
10844	}
10845
10846mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
10847	{
10848	const mDNSu32 slot = HashSlot(&q->qname);
10849	CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
10850	CacheRecord *rp;
10851
10852	for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10853		{
10854		if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10855			{
10856			LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
10857			mDNS_PurgeCacheResourceRecord(m, rp);
10858			}
10859		}
10860	}
10861
10862mDNSlocal void CacheRecordResetDNSServer(mDNS *const m, DNSQuestion *q, DNSServer *new)
10863	{
10864	const mDNSu32 slot = HashSlot(&q->qname);
10865	CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
10866	CacheRecord *rp;
10867	mDNSBool found = mDNSfalse;
10868	mDNSBool foundNew = mDNSfalse;
10869	DNSServer *old = q->qDNSServer;
10870	mDNSBool newQuestion = IsQuestionNew(m, q);
10871	DNSQuestion *qptr;
10872
10873	// This function is called when the DNSServer is updated to the new question. There may already be
10874	// some cache entries matching the old DNSServer and/or new DNSServer. There are four cases. In the
10875	// following table, "Yes" denotes that a cache entry was found for old/new DNSServer.
10876	//
10877	// 					old DNSServer		new DNSServer
10878	//
10879	//	Case 1				Yes					Yes
10880	//  Case 2				No					Yes
10881	//  Case 3				Yes					No
10882	//  Case 4				No					No
10883	//
10884	// Case 1: There are cache entries for both old and new DNSServer. We handle this case by simply
10885	//		   expiring the old Cache entries, deliver a RMV event (if an ADD event was delivered before)
10886	//		   followed by the ADD event of the cache entries corresponding to the new server. This
10887	//		   case happens when we pick a DNSServer, issue a query and get a valid response and create
10888	//		   cache entries after which it stops responding. Another query (non-duplicate) picks a different
10889	//	       DNSServer and creates identical cache entries (perhaps through records in Additional records).
10890	//		   Now if the first one expires and tries to pick the new DNSServer (the original DNSServer
10891	//		   is not responding) we will find cache entries corresponding to both DNSServers.
10892	//
10893	// Case 2: There are no cache entries for the old DNSServer but there are some for the new DNSServer.
10894	//		   This means we should deliver an ADD event. Normally ADD events are delivered by
10895	//		   AnswerNewQuestion if it is a new question. So, we check to see if it is a new question
10896	//		   and if so, leave it to AnswerNewQuestion to deliver it. Otherwise, we use
10897	//		   AnswerQuestionsForDNSServerChanges to deliver the ADD event. This case happens when a
10898	//		   question picks a DNS server for which AnswerNewQuestion could not deliver an answer even
10899	//         though there were potential cache entries but DNSServer did not match. Now when we
10900	//         pick a new DNSServer, those cache entries may answer this question.
10901	//
10902	// Case 3: There are the cache entries for the old DNSServer but none for the new. We just move
10903	//		   the old cache entries to point to the new DNSServer and the caller is expected to
10904	//		   do a purge or reconfirm to delete or validate the RDATA. We don't need to do anything
10905	//		   special for delivering ADD events, as it should have been done/will be done by
10906	//		   AnswerNewQuestion. This case happens when we picked a DNSServer, sent the query and
10907	//		   got a response and the cache is expired now and we are reissuing the question but the
10908	//		   original DNSServer does not respond.
10909	//
10910	// Case 4: There are no cache entries either for the old or for the new DNSServer. There is nothing
10911	//		   much we can do here.
10912	//
10913	// Case 2 and 3 are the most common while case 4 is possible when no DNSServers are working. Case 1
10914	// is relatively less likely to happen in practice
10915
10916	// Temporarily set the DNSServer to look for the matching records for the new DNSServer.
10917	q->qDNSServer = new;
10918	for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10919		{
10920		if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10921			{
10922			LogInfo("CacheRecordResetDNSServer: Found cache record %##s for new DNSServer address: %#a", rp->resrec.name->c,
10923				(rp->resrec.rDNSServer != mDNSNULL ?  &rp->resrec.rDNSServer->addr : mDNSNULL));
10924			foundNew = mDNStrue;
10925			break;
10926			}
10927		}
10928	q->qDNSServer = old;
10929
10930	for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
10931		{
10932		if (SameNameRecordAnswersQuestion(&rp->resrec, q))
10933			{
10934			// Case1
10935			found = mDNStrue;
10936			if (foundNew)
10937				{
10938				LogInfo("CacheRecordResetDNSServer: Flushing Resourcerecord %##s, before:%#a, after:%#a", rp->resrec.name->c,
10939					(rp->resrec.rDNSServer != mDNSNULL ?  &rp->resrec.rDNSServer->addr : mDNSNULL),
10940					(new != mDNSNULL ?  &new->addr : mDNSNULL));
10941				mDNS_PurgeCacheResourceRecord(m, rp);
10942				if (newQuestion)
10943					{
10944					// "q" is not a duplicate question. If it is a newQuestion, then the CRActiveQuestion can't be
10945					// possibly set as it is set only when we deliver the ADD event to the question.
10946					if (rp->CRActiveQuestion != mDNSNULL)
10947						{
10948						LogMsg("CacheRecordResetDNSServer: ERROR!!: CRActiveQuestion %p set, current question %p, name %##s", rp->CRActiveQuestion, q, q->qname.c);
10949						rp->CRActiveQuestion = mDNSNULL;
10950						}
10951					// if this is a new question, then we never delivered an ADD yet, so don't deliver the RMV.
10952					continue;
10953					}
10954				}
10955			LogInfo("CacheRecordResetDNSServer: resetting cache record %##s DNSServer address before:%#a,"
10956				" after:%#a, CRActiveQuestion %p", rp->resrec.name->c, (rp->resrec.rDNSServer != mDNSNULL ?
10957				&rp->resrec.rDNSServer->addr : mDNSNULL), (new != mDNSNULL ?  &new->addr : mDNSNULL),
10958				rp->CRActiveQuestion);
10959			// Though we set it to the new DNS server, the caller is *assumed* to do either a purge
10960			// or reconfirm or send out questions to the "new" server to verify whether the cached
10961			// RDATA is valid
10962			rp->resrec.rDNSServer = new;
10963			}
10964		}
10965
10966	// Case 1 and Case 2
10967	if ((found && foundNew) || (!found && foundNew))
10968		{
10969		if (newQuestion)
10970			LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
10971		else if (QuerySuppressed(q))
10972			LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for suppressed question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
10973		else
10974			{
10975			LogInfo("CacheRecordResetDNSServer: deliverAddEvents set for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
10976			q->deliverAddEvents = mDNStrue;
10977			for (qptr = q->next; qptr; qptr = qptr->next)
10978				if (qptr->DuplicateOf == q) qptr->deliverAddEvents = mDNStrue;
10979			}
10980		return;
10981		}
10982
10983	// Case 3 and Case 4
10984	return;
10985	}
10986
10987mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
10988	{
10989	DNSQuestion *qptr;
10990
10991	// 1. Whenever we change the DNS server, we change the message identifier also so that response
10992	// from the old server is not accepted as a response from the new server but only messages
10993	// from the new server are accepted as valid responses. We do it irrespective of whether "new"
10994	// is NULL or not. It is possible that we send two queries, no responses, pick a new DNS server
10995	// which is NULL and now the response comes back and will try to penalize the DNS server which
10996	// is NULL. By setting the messageID here, we will not accept that as a valid response.
10997
10998	q->TargetQID = mDNS_NewMessageID(m);
10999
11000	// 2. Move the old cache records to point them at the new DNSServer so that we can deliver the ADD/RMV events
11001	// appropriately. At any point in time, we want all the cache records point only to one DNSServer for a given
11002	// question. "DNSServer" here is the DNSServer object and not the DNS server itself. It is possible to
11003	// have the same DNS server address in two objects, one scoped and another not scoped. But, the cache is per
11004	// DNSServer object. By maintaining the question and the cache entries point to the same DNSServer
11005	// always, the cache maintenance and delivery of ADD/RMV events becomes simpler.
11006	//
11007	// CacheRecordResetDNSServer should be called only once for the non-duplicate question as once the cache
11008	// entries are moved to point to the new DNSServer, we don't need to call it for the duplicate question
11009	// and it is wrong to call for the duplicate question as it's decision to mark deliverAddevents will be
11010	// incorrect.
11011
11012	if (q->DuplicateOf)
11013		LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
11014	else
11015		CacheRecordResetDNSServer(m, q, new);
11016
11017	// 3. Make sure all the duplicate questions point to the same DNSServer so that delivery
11018	// of events for all of them are consistent. Duplicates for a question are always inserted
11019	// after in the list.
11020	q->qDNSServer = new;
11021	for (qptr = q->next ; qptr; qptr = qptr->next)
11022		{
11023		if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
11024		}
11025	}
11026
11027mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
11028	{
11029	mDNSu32 slot;
11030	CacheGroup *cg;
11031	CacheRecord *cr;
11032
11033	mDNSAddr     v4, v6, r;
11034	domainname   fqdn;
11035	DNSServer   *ptr, **p = &m->DNSServers;
11036	const DNSServer *oldServers = m->DNSServers;
11037	DNSQuestion *q;
11038	McastResolver *mr, **mres = &m->McastResolvers;
11039
11040	debugf("uDNS_SetupDNSConfig: entry");
11041
11042	// Let the platform layer get the current DNS information
11043	// The m->StartWABQueries is set when we get the first domain enumeration query (no need to hit the network
11044	// with domain enumeration queries until we actually need that information). Even if it is not set, we still
11045	// need to setup the search domains so that we can append them to queries that need them.
11046
11047	uDNS_SetupSearchDomains(m, m->StartWABQueries ? UDNS_START_WAB_QUERY : 0);
11048
11049	mDNS_Lock(m);
11050
11051	for (ptr = m->DNSServers; ptr; ptr = ptr->next)
11052		{
11053		ptr->penaltyTime = 0;
11054		ptr->flags |= DNSServer_FlagDelete;
11055		}
11056
11057	// We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
11058	// mcast resolvers. Today we get both mcast and ucast configuration using the same
11059	// API
11060	for (mr = m->McastResolvers; mr; mr = mr->next)
11061		mr->flags |= McastResolver_FlagDelete;
11062
11063	mDNSPlatformSetDNSConfig(m, mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL);
11064
11065	// For now, we just delete the mcast resolvers. We don't deal with cache or
11066	// questions here. Neither question nor cache point to mcast resolvers. Questions
11067	// do inherit the timeout values from mcast resolvers. But we don't bother
11068	// affecting them as they never change.
11069	while (*mres)
11070		{
11071		if (((*mres)->flags & DNSServer_FlagDelete) != 0)
11072			{
11073			mr = *mres;
11074			*mres = (*mres)->next;
11075			debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
11076			mDNSPlatformMemFree(mr);
11077			}
11078		else
11079			{
11080			(*mres)->flags &= ~McastResolver_FlagNew;
11081			mres = &(*mres)->next;
11082			}
11083		}
11084
11085	// Mark the records to be flushed that match a new resolver. We need to do this before
11086	// we walk the questions below where we change the DNSServer pointer of the cache
11087	// record
11088	FORALL_CACHERECORDS(slot, cg, cr)
11089		{
11090		if (cr->resrec.InterfaceID) continue;
11091
11092		// We just mark them for purge or reconfirm. We can't affect the DNSServer pointer
11093		// here as the code below that calls CacheRecordResetDNSServer relies on this
11094		//
11095		// The new DNSServer may be a scoped or non-scoped one. We use the active question's
11096		// InterfaceID for looking up the right DNS server
11097		ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL);
11098
11099		// Purge or Reconfirm if this cache entry would use the new DNS server
11100		if (ptr && (ptr != cr->resrec.rDNSServer))
11101			{
11102			// As the DNSServers for this cache record is not the same anymore, we don't
11103			// want any new questions to pick this old value
11104			if (cr->CRActiveQuestion == mDNSNULL)
11105				{
11106				LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s", CRDisplayString(m, cr));
11107				mDNS_PurgeCacheResourceRecord(m, cr);
11108				}
11109			else
11110				{
11111				LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s", CRDisplayString(m, cr));
11112				PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
11113				}
11114			}
11115		}
11116	// Update our qDNSServer pointers before we go and free the DNSServer object memory
11117	for (q = m->Questions; q; q=q->next)
11118		if (!mDNSOpaque16IsZero(q->TargetQID))
11119			{
11120			DNSServer *s, *t;
11121			DNSQuestion *qptr;
11122			if (q->DuplicateOf) continue;
11123			SetValidDNSServers(m, q);
11124			q->triedAllServersOnce = 0;
11125			s = GetServerForQuestion(m, q);
11126			t = q->qDNSServer;
11127			if (t != s)
11128				{
11129				// If DNS Server for this question has changed, reactivate it
11130				debugf("uDNS_SetupDNSConfig: Updating DNS Server from %p %#a:%d (%##s) to %p %#a:%d (%##s) for %##s (%s)",
11131					t, t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
11132					s, s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
11133					q->qname.c, DNSTypeName(q->qtype));
11134
11135				// After we reset the DNSServer pointer on the cache records here, three things could happen:
11136				//
11137				// 1) The query gets sent out and when the actual response comes back later it is possible
11138				// that the response has the same RDATA, in which case we update our cache entry.
11139				// If the response is different, then the entry will expire and a new entry gets added.
11140				// For the latter case to generate a RMV followed by ADD events, we need to reset the DNS
11141				// server here to match the question and the cache record.
11142				//
11143				// 2) We might have marked the cache entries for purge above and for us to be able to generate the RMV
11144				// events for the questions, the DNSServer on the question should match the Cache Record
11145				//
11146				// 3) We might have marked the cache entries for reconfirm above, for which we send the query out which is
11147				// the same as the first case above.
11148
11149				DNSServerChangeForQuestion(m, q, s);
11150				q->unansweredQueries = 0;
11151				// We still need to pick a new DNSServer for the questions that have been
11152				// suppressed, but it is wrong to activate the query as DNS server change
11153				// could not possibly change the status of SuppressUnusable questions
11154				if (!QuerySuppressed(q))
11155					{
11156					debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11157					ActivateUnicastQuery(m, q, mDNStrue);
11158					// ActivateUnicastQuery is called for duplicate questions also as it does something
11159					// special for AutoTunnel questions
11160					for (qptr = q->next ; qptr; qptr = qptr->next)
11161						{
11162						if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
11163						}
11164					}
11165				}
11166			else
11167				{
11168				debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
11169					q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
11170				for (qptr = q->next ; qptr; qptr = qptr->next)
11171					if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
11172				}
11173			}
11174
11175	while (*p)
11176		{
11177		if (((*p)->flags & DNSServer_FlagDelete) != 0)
11178			{
11179			// Scan our cache, looking for uDNS records that we would have queried this server for.
11180			// We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
11181			// different DNS servers can give different answers to the same question.
11182			ptr = *p;
11183			FORALL_CACHERECORDS(slot, cg, cr)
11184				{
11185				if (cr->resrec.InterfaceID) continue;
11186				if (cr->resrec.rDNSServer == ptr)
11187					{
11188					// If we don't have an active question for this cache record, neither Purge can
11189					// generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
11190					// pointer on the record NULL so that we don't point to freed memory (We might dereference
11191					// DNSServer pointers from resource record for logging purposes).
11192					//
11193					// If there is an active question, point to its DNSServer as long as it does not point to the
11194					// freed one. We already went through the questions above and made them point at either the
11195					// new server or NULL if there is no server and also affected the cache entries that match
11196					// this question. Hence, whenever we hit a resource record with a DNSServer that is just
11197					// about to be deleted, we should never have an active question. The code below just tries to
11198					// be careful logging messages if we ever hit this case.
11199
11200					if (cr->CRActiveQuestion)
11201						{
11202						DNSQuestion *qptr = cr->CRActiveQuestion;
11203						if (qptr->qDNSServer == mDNSNULL)
11204							LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) with DNSServer Address NULL, Server to be deleted %#a",
11205								CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), &ptr->addr);
11206						else
11207							LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) DNSServer Address %#a, Server to be deleted %#a",
11208								CRDisplayString(m, cr),  qptr->qname.c, DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr, &ptr->addr);
11209
11210						if (qptr->qDNSServer == ptr)
11211							{
11212							qptr->validDNSServers = zeroOpaque64;
11213							qptr->qDNSServer = mDNSNULL;
11214							cr->resrec.rDNSServer = mDNSNULL;
11215							}
11216						else
11217							{
11218							cr->resrec.rDNSServer = qptr->qDNSServer;
11219							}
11220						}
11221					else
11222						{
11223						LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
11224							cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
11225						cr->resrec.rDNSServer = mDNSNULL;
11226						}
11227
11228					PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
11229					}
11230				}
11231			*p = (*p)->next;
11232			debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
11233			mDNSPlatformMemFree(ptr);
11234			NumUnicastDNSServers--;
11235			}
11236		else
11237			{
11238			(*p)->flags &= ~DNSServer_FlagNew;
11239			p = &(*p)->next;
11240			}
11241		}
11242
11243	// 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).
11244	// This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
11245	// Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
11246	// 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.
11247	if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
11248		{
11249		int count = 0;
11250		FORALL_CACHERECORDS(slot, cg, cr) if (!cr->resrec.InterfaceID) { mDNS_PurgeCacheResourceRecord(m, cr); count++; }
11251		LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
11252			m->DNSServers ? "DNS server became" : "No DNS servers", count);
11253
11254		// Force anything that needs to get zone data to get that information again
11255		RestartRecordGetZoneData(m);
11256		}
11257
11258	// Did our FQDN change?
11259	if (!SameDomainName(&fqdn, &m->FQDN))
11260		{
11261		if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
11262
11263		AssignDomainName(&m->FQDN, &fqdn);
11264
11265		if (m->FQDN.c[0])
11266			{
11267			mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
11268			mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
11269			}
11270		}
11271
11272	mDNS_Unlock(m);
11273
11274	// handle router and primary interface changes
11275	v4 = v6 = r = zeroAddr;
11276	v4.type = r.type = mDNSAddrType_IPv4;
11277
11278	if (mDNSPlatformGetPrimaryInterface(m, &v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
11279		{
11280		mDNS_SetPrimaryInterfaceInfo(m,
11281			!mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
11282			!mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
11283			!mDNSIPv4AddressIsZero(r .ip.v4) ? &r  : mDNSNULL);
11284		}
11285	else
11286		{
11287		mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
11288		if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);	// Set status to 1 to indicate temporary failure
11289		}
11290
11291	debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
11292	return mStatus_NoError;
11293	}
11294
11295mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
11296	{
11297	m->mDNSPlatformStatus = result;
11298	if (m->MainCallback)
11299		{
11300		mDNS_Lock(m);
11301		mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
11302		m->MainCallback(m, mStatus_NoError);
11303		mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
11304		mDNS_Unlock(m);
11305		}
11306	}
11307
11308mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
11309	{
11310	m->CurrentRecord = start;
11311	while (m->CurrentRecord)
11312		{
11313		AuthRecord *rr = m->CurrentRecord;
11314		LogInfo("DeregLoop: %s deregistration for %p %02X %s",
11315			(rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating  " : "Accelerating",
11316			rr, rr->resrec.RecordType, ARDisplayString(m, rr));
11317		if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
11318			mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
11319		else if (rr->AnnounceCount > 1)
11320			{
11321			rr->AnnounceCount = 1;
11322			rr->LastAPTime = m->timenow - rr->ThisAPInterval;
11323			}
11324		// Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
11325		// new records could have been added to the end of the list as a result of that call.
11326		if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
11327			m->CurrentRecord = rr->next;
11328		}
11329	}
11330
11331mDNSexport void mDNS_StartExit(mDNS *const m)
11332	{
11333	NetworkInterfaceInfo *intf;
11334	AuthRecord *rr;
11335
11336	mDNS_Lock(m);
11337
11338	LogInfo("mDNS_StartExit");
11339	m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
11340
11341	mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0);
11342
11343#if APPLE_OSX_mDNSResponder
11344#if ! NO_WCF
11345	CHECK_WCF_FUNCTION(WCFConnectionDealloc)
11346		{
11347		if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
11348		}
11349#endif
11350#endif
11351
11352#ifndef UNICAST_DISABLED
11353	{
11354	SearchListElem *s;
11355	SuspendLLQs(m);
11356	// Don't need to do SleepRecordRegistrations() here
11357	// because we deregister all records and services later in this routine
11358	while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
11359
11360	// For each member of our SearchList, deregister any records it may have created, and cut them from the list.
11361	// Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
11362	// and we may crash because the list still contains dangling pointers.
11363	for (s = SearchList; s; s = s->next)
11364		while (s->AuthRecs)
11365			{
11366			ARListElem *dereg = s->AuthRecs;
11367			s->AuthRecs = s->AuthRecs->next;
11368			mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal);	// Memory will be freed in the FreeARElemCallback
11369			}
11370	}
11371#endif
11372
11373	for (intf = m->HostInterfaces; intf; intf = intf->next)
11374		if (intf->Advertise)
11375			DeadvertiseInterface(m, intf);
11376
11377	// Shut down all our active NAT Traversals
11378	while (m->NATTraversals)
11379		{
11380		NATTraversalInfo *t = m->NATTraversals;
11381		mDNS_StopNATOperation_internal(m, t);		// This will cut 't' from the list, thereby advancing m->NATTraversals in the process
11382
11383		// After stopping the NAT Traversal, we zero out the fields.
11384		// This has particularly important implications for our AutoTunnel records --
11385		// when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
11386		// handlers to just turn around and attempt to re-register those same records.
11387		// Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
11388		// to not do this.
11389		t->ExternalAddress = zerov4Addr;
11390		t->ExternalPort    = zeroIPPort;
11391		t->RequestedPort   = zeroIPPort;
11392		t->Lifetime        = 0;
11393		t->Result          = mStatus_NoError;
11394		}
11395
11396	// Make sure there are nothing but deregistering records remaining in the list
11397	if (m->CurrentRecord)
11398		LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
11399
11400	// We're in the process of shutting down, so queries, etc. are no longer available.
11401	// Consequently, determining certain information, e.g. the uDNS update server's IP
11402	// address, will not be possible.  The records on the main list are more likely to
11403	// already contain such information, so we deregister the duplicate records first.
11404	LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
11405	DeregLoop(m, m->DuplicateRecords);
11406	LogInfo("mDNS_StartExit: Deregistering resource records");
11407	DeregLoop(m, m->ResourceRecords);
11408
11409	// If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
11410	// we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
11411	if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
11412		{
11413		m->NextScheduledResponse = m->timenow;
11414		m->SuppressSending = 0;
11415		}
11416
11417	if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
11418	else                    LogInfo("mDNS_StartExit: No deregistering records remain");
11419
11420	for (rr = m->DuplicateRecords; rr; rr = rr->next)
11421		LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
11422
11423	// If any deregistering records remain, send their deregistration announcements before we exit
11424	if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
11425
11426	mDNS_Unlock(m);
11427
11428	LogInfo("mDNS_StartExit: done");
11429	}
11430
11431mDNSexport void mDNS_FinalExit(mDNS *const m)
11432	{
11433	mDNSu32 rrcache_active = 0;
11434	mDNSu32 rrcache_totalused = 0;
11435	mDNSu32 slot;
11436	AuthRecord *rr;
11437
11438	LogInfo("mDNS_FinalExit: mDNSPlatformClose");
11439	mDNSPlatformClose(m);
11440
11441	rrcache_totalused = m->rrcache_totalused;
11442	for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
11443		{
11444		while (m->rrcache_hash[slot])
11445			{
11446			CacheGroup *cg = m->rrcache_hash[slot];
11447			while (cg->members)
11448				{
11449				CacheRecord *cr = cg->members;
11450				cg->members = cg->members->next;
11451				if (cr->CRActiveQuestion) rrcache_active++;
11452				ReleaseCacheRecord(m, cr);
11453				}
11454			cg->rrcache_tail = &cg->members;
11455			ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
11456			}
11457		}
11458	debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
11459	if (rrcache_active != m->rrcache_active)
11460		LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
11461
11462	for (rr = m->ResourceRecords; rr; rr = rr->next)
11463		LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
11464
11465	LogInfo("mDNS_FinalExit: done");
11466	}
11467