xref: /netbsd-src/external/apache2/mDNSResponder/dist/mDNSCore/uDNS.c (revision fa28c6faa16e0b00edee7acdcaf4899797043def)
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  * To Do:
18  * Elimate all mDNSPlatformMemAllocate/mDNSPlatformMemFree from this code -- the core code
19  * is supposed to be malloc-free so that it runs in constant memory determined at compile-time.
20  * Any dynamic run-time requirements should be handled by the platform layer below or client layer above
21  */
22 
23 #if APPLE_OSX_mDNSResponder
24 #include <TargetConditionals.h>
25 #endif
26 #include "uDNS.h"
27 
28 #if(defined(_MSC_VER))
29 	// Disable "assignment within conditional expression".
30 	// Other compilers understand the convention that if you place the assignment expression within an extra pair
31 	// of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
32 	// The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
33 	// to the compiler that the assignment is intentional, we have to just turn this warning off completely.
34 	#pragma warning(disable:4706)
35 #endif
36 
37 // For domain enumeration and automatic browsing
38 // This is the user's DNS search list.
39 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
40 // to discover recommended domains for domain enumeration (browse, default browse, registration,
41 // default registration) and possibly one or more recommended automatic browsing domains.
42 mDNSexport SearchListElem *SearchList = mDNSNULL;
43 
44 // The value can be set to true by the Platform code e.g., MacOSX uses the plist mechanism
45 mDNSBool StrictUnicastOrdering = mDNSfalse;
46 
47 // We keep track of the number of unicast DNS servers and log a message when we exceed 64.
48 // Currently the unicast queries maintain a 64 bit map to track the valid DNS servers for that
49 // question. Bit position is the index into the DNS server list. This is done so to try all
50 // the servers exactly once before giving up. If we could allocate memory in the core, then
51 // arbitrary limitation of 64 DNSServers can be removed.
52 mDNSu8 NumUnicastDNSServers = 0;
53 #define MAX_UNICAST_DNS_SERVERS	64
54 
55 // ***************************************************************************
56 #if COMPILER_LIKES_PRAGMA_MARK
57 #pragma mark - General Utility Functions
58 #endif
59 
60 // set retry timestamp for record with exponential backoff
61 mDNSlocal void SetRecordRetry(mDNS *const m, AuthRecord *rr, mDNSu32 random)
62 	{
63 	rr->LastAPTime = m->timenow;
64 
65 	if (rr->expire && rr->refreshCount < MAX_UPDATE_REFRESH_COUNT)
66 		{
67 		mDNSs32 remaining = rr->expire - m->timenow;
68 		rr->refreshCount++;
69 		if (remaining > MIN_UPDATE_REFRESH_TIME)
70 			{
71 			// Refresh at 70% + random (currently it is 0 to 10%)
72 			rr->ThisAPInterval =  7 * (remaining/10) + (random ? random : mDNSRandom(remaining/10));
73 			// Don't update more often than 5 minutes
74 			if (rr->ThisAPInterval < MIN_UPDATE_REFRESH_TIME)
75 				rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
76 			LogInfo("SetRecordRetry refresh in %d of %d for %s",
77 				rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
78 			}
79 		else
80 			{
81 			rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
82 			LogInfo("SetRecordRetry clamping to min refresh in %d of %d for %s",
83 				rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
84 			}
85 		return;
86 		}
87 
88 	rr->expire = 0;
89 
90 	rr->ThisAPInterval = rr->ThisAPInterval * QuestionIntervalStep;	// Same Retry logic as Unicast Queries
91 	if (rr->ThisAPInterval < INIT_RECORD_REG_INTERVAL)
92 		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
93 	if (rr->ThisAPInterval > MAX_RECORD_REG_INTERVAL)
94 		rr->ThisAPInterval = MAX_RECORD_REG_INTERVAL;
95 
96 	LogInfo("SetRecordRetry retry in %d ms for %s", rr->ThisAPInterval, ARDisplayString(m, rr));
97 	}
98 
99 // ***************************************************************************
100 #if COMPILER_LIKES_PRAGMA_MARK
101 #pragma mark - Name Server List Management
102 #endif
103 
104 mDNSexport DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, const mDNSAddr *addr, const mDNSIPPort port, mDNSBool scoped, mDNSu32 timeout)
105 	{
106 	DNSServer **p = &m->DNSServers;
107 	DNSServer *tmp = mDNSNULL;
108 
109 	if ((NumUnicastDNSServers + 1) > MAX_UNICAST_DNS_SERVERS)
110 		{
111 		LogMsg("mDNS_AddDNSServer: DNS server limit of %d reached, not adding this server", MAX_UNICAST_DNS_SERVERS);
112 		return mDNSNULL;
113 		}
114 
115 	if (!d) d = (const domainname *)"";
116 
117 	LogInfo("mDNS_AddDNSServer: Adding %#a for %##s, InterfaceID %p, scoped %d", addr, d->c, interface, scoped);
118 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
119 		LogMsg("mDNS_AddDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
120 
121 	while (*p)	// Check if we already have this {interface,address,port,domain} tuple registered
122 		{
123 		if ((*p)->scoped == scoped && (*p)->interface == interface && (*p)->teststate != DNSServer_Disabled &&
124 			mDNSSameAddress(&(*p)->addr, addr) && mDNSSameIPPort((*p)->port, port) && SameDomainName(&(*p)->domain, d))
125 			{
126 			if (!((*p)->flags & DNSServer_FlagDelete)) debugf("Note: DNS Server %#a:%d for domain %##s (%p) registered more than once", addr, mDNSVal16(port), d->c, interface);
127 			(*p)->flags &= ~DNSServer_FlagDelete;
128 			tmp = *p;
129 			*p = tmp->next;
130 			tmp->next = mDNSNULL;
131 			}
132 		else
133 			p=&(*p)->next;
134 		}
135 
136 	if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
137 	else
138 		{
139 		// allocate, add to list
140 		*p = mDNSPlatformMemAllocate(sizeof(**p));
141 		if (!*p) LogMsg("Error: mDNS_AddDNSServer - malloc");
142 		else
143 			{
144 			NumUnicastDNSServers++;
145 			(*p)->scoped	= scoped;
146 			(*p)->interface = interface;
147 			(*p)->addr      = *addr;
148 			(*p)->port      = port;
149 			(*p)->flags     = DNSServer_FlagNew;
150 			(*p)->teststate = /* DNSServer_Untested */ DNSServer_Passed;
151 			(*p)->lasttest  = m->timenow - INIT_UCAST_POLL_INTERVAL;
152 			(*p)->timeout   = timeout;
153 			AssignDomainName(&(*p)->domain, d);
154 			(*p)->next = mDNSNULL;
155 			}
156 		}
157 	(*p)->penaltyTime = 0;
158 	return(*p);
159 	}
160 
161 // PenalizeDNSServer is called when the number of queries to the unicast
162 // DNS server exceeds MAX_UCAST_UNANSWERED_QUERIES or when we receive an
163 // error e.g., SERV_FAIL from DNS server.
164 mDNSexport void PenalizeDNSServer(mDNS *const m, DNSQuestion *q)
165 	{
166 	DNSServer *new;
167 	DNSServer *orig = q->qDNSServer;
168 
169 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
170 		LogMsg("PenalizeDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
171 
172 	// This should never happen. Whenever we change DNS server, we change the ID on the question and hence
173 	// we should never accept a response after we penalize a DNS server e.g., send two queries, no response,
174 	// penalize DNS server and no new servers to pick for the question and hence qDNSServer is NULL. If we
175 	// receive a response now, the DNS server can be NULL. But we won't because the ID already has been
176 	// changed.
177 	if (!q->qDNSServer)
178 		{
179 		LogMsg("PenalizeDNSServer: ERROR!! Null DNS server for %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), q->unansweredQueries);
180 		goto end;
181 		}
182 
183 	LogInfo("PenalizeDNSServer: Penalizing DNS server %#a:%d question (%##s) for question %p %##s (%s) SuppressUnusable %d",
184 		&q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c, q, q->qname.c, DNSTypeName(q->qtype),
185 		q->SuppressUnusable);
186 
187 	// If strict ordering of unicast servers needs to be preserved, we just lookup
188 	// the next best match server below
189 	//
190 	// If strict ordering is not required which is the default behavior, we penalize the server
191 	// for DNSSERVER_PENALTY_TIME. We may also use additional logic e.g., don't penalize for PTR
192 	// in the future.
193 
194 	if (!StrictUnicastOrdering)
195 		{
196 		LogInfo("PenalizeDNSServer: Strict Unicast Ordering is FALSE");
197 		// We penalize the server so that new queries don't pick this server for DNSSERVER_PENALTY_TIME
198 		// XXX Include other logic here to see if this server should really be penalized
199 		//
200 		if (q->qtype == kDNSType_PTR)
201 			{
202 			LogInfo("PenalizeDNSServer: Not Penalizing PTR question");
203 			}
204 		else
205 			{
206 			LogInfo("PenalizeDNSServer: Penalizing question type %d", q->qtype);
207 			q->qDNSServer->penaltyTime = NonZeroTime(m->timenow + DNSSERVER_PENALTY_TIME);
208 			}
209 		}
210 	else
211 		{
212 		LogInfo("PenalizeDNSServer: Strict Unicast Ordering is TRUE");
213 		}
214 
215 end:
216 	new = GetServerForQuestion(m, q);
217 
218 
219 	if (new == orig)
220 		{
221 		if (new)
222 			LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server %#a:%d", &new->addr,
223 		    	mDNSVal16(new->port));
224 		else
225 			LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server NULL");
226 		q->ThisQInterval = 0;	// Inactivate this question so that we dont bombard the network
227 		}
228 	else
229 		{
230 		// The new DNSServer is set in DNSServerChangeForQuestion
231 		DNSServerChangeForQuestion(m, q, new);
232 
233 		if (new)
234 			{
235 			LogInfo("PenalizeDNSServer: Server for %##s (%s) changed to %#a:%d (%##s)",
236 				q->qname.c, DNSTypeName(q->qtype), &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c);
237 			// We want to try the next server immediately. As the question may already have backed off, reset
238 			// the interval. We do this only the first time when we try all the DNS servers. Once we reached the end of
239 			// list and retrying all the servers again e.g., at least one server failed to respond in the previous try, we
240 			// use the normal backoff which is done in uDNS_CheckCurrentQuestion when we send the packet out.
241 			if (!q->triedAllServersOnce)
242 				{
243 				q->ThisQInterval = InitialQuestionInterval;
244 				q->LastQTime  = m->timenow - q->ThisQInterval;
245 				SetNextQueryTime(m, q);
246 				}
247 			}
248 		else
249 			{
250 			// We don't have any more DNS servers for this question. If some server in the list did not return
251 			// any response, we need to keep retrying till we get a response. uDNS_CheckCurrentQuestion handles
252 			// this case.
253 			//
254 			// If all servers responded with a negative response, We need to do two things. First, generate a
255 			// negative response so that applications get a reply. We also need to reinitialize the DNS servers
256 			// so that when the cache expires, we can restart the query.
257 			//
258 			// Negative response may be generated in two ways.
259 			//
260 			// 1. AnswerQuestionForDNSServerChanges (called from DNSServerChangedForQuestion) might find some
261 			//    cache entries and answer this question.
262 			// 2. uDNS_CheckCurrentQuestion will create a new cache entry and answer this question
263 			//
264 			// For (1), it might be okay to reinitialize the DNS servers here. But for (2), we can't do it here
265 			// because uDNS_CheckCurrentQuestion will try resending the queries. Hence, to be consistent, we
266 			// defer reintializing the DNS servers up until generating a negative cache response.
267 			//
268 			// Be careful not to touch the ThisQInterval here. For a normal question, when we answer the question
269 			// in AnswerCurrentQuestionWithResourceRecord will set ThisQInterval to MaxQuestionInterval and hence
270 			// the next query will not happen until cache expiry. If it is a long lived question,
271 			// AnswerCurrentQuestionWithResourceRecord will not set it to MaxQuestionInterval. In that case,
272 			// we want the normal backoff to work.
273 			LogInfo("PenalizeDNSServer: Server for %p, %##s (%s) changed to NULL, Interval %d", q, q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
274 			}
275 		q->unansweredQueries = 0;
276 
277 		}
278 	}
279 
280 // ***************************************************************************
281 #if COMPILER_LIKES_PRAGMA_MARK
282 #pragma mark - authorization management
283 #endif
284 
285 mDNSlocal DomainAuthInfo *GetAuthInfoForName_direct(mDNS *m, const domainname *const name)
286 	{
287 	const domainname *n = name;
288 	while (n->c[0])
289 		{
290 		DomainAuthInfo *ptr;
291 		for (ptr = m->AuthInfoList; ptr; ptr = ptr->next)
292 			if (SameDomainName(&ptr->domain, n))
293 				{
294 				debugf("GetAuthInfoForName %##s Matched %##s Key name %##s", name->c, ptr->domain.c, ptr->keyname.c);
295 				return(ptr);
296 				}
297 		n = (const domainname *)(n->c + 1 + n->c[0]);
298 		}
299 	//LogInfo("GetAuthInfoForName none found for %##s", name->c);
300 	return mDNSNULL;
301 	}
302 
303 // MUST be called with lock held
304 mDNSexport DomainAuthInfo *GetAuthInfoForName_internal(mDNS *m, const domainname *const name)
305 	{
306 	DomainAuthInfo **p = &m->AuthInfoList;
307 
308 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
309 		LogMsg("GetAuthInfoForName_internal: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
310 
311 	// First purge any dead keys from the list
312 	while (*p)
313 		{
314 		if ((*p)->deltime && m->timenow - (*p)->deltime >= 0 && AutoTunnelUnregistered(*p))
315 			{
316 			DNSQuestion *q;
317 			DomainAuthInfo *info = *p;
318 			LogInfo("GetAuthInfoForName_internal deleting expired key %##s %##s", info->domain.c, info->keyname.c);
319 			*p = info->next;	// Cut DomainAuthInfo from list *before* scanning our question list updating AuthInfo pointers
320 			for (q = m->Questions; q; q=q->next)
321 				if (q->AuthInfo == info)
322 					{
323 					q->AuthInfo = GetAuthInfoForName_direct(m, &q->qname);
324 					debugf("GetAuthInfoForName_internal updated q->AuthInfo from %##s to %##s for %##s (%s)",
325 						info->domain.c, q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
326 					}
327 
328 			// Probably not essential, but just to be safe, zero out the secret key data
329 			// so we don't leave it hanging around in memory
330 			// (where it could potentially get exposed via some other bug)
331 			mDNSPlatformMemZero(info, sizeof(*info));
332 			mDNSPlatformMemFree(info);
333 			}
334 		else
335 			p = &(*p)->next;
336 		}
337 
338 	return(GetAuthInfoForName_direct(m, name));
339 	}
340 
341 mDNSexport DomainAuthInfo *GetAuthInfoForName(mDNS *m, const domainname *const name)
342 	{
343 	DomainAuthInfo *d;
344 	mDNS_Lock(m);
345 	d = GetAuthInfoForName_internal(m, name);
346 	mDNS_Unlock(m);
347 	return(d);
348 	}
349 
350 // MUST be called with the lock held
351 mDNSexport mStatus mDNS_SetSecretForDomain(mDNS *m, DomainAuthInfo *info,
352 	const domainname *domain, const domainname *keyname, const char *b64keydata, const domainname *hostname, mDNSIPPort *port, const char *autoTunnelPrefix)
353 	{
354 	DNSQuestion *q;
355 	DomainAuthInfo **p = &m->AuthInfoList;
356 	if (!info || !b64keydata) { LogMsg("mDNS_SetSecretForDomain: ERROR: info %p b64keydata %p", info, b64keydata); return(mStatus_BadParamErr); }
357 
358 	LogInfo("mDNS_SetSecretForDomain: domain %##s key %##s%s%s", domain->c, keyname->c, autoTunnelPrefix ? " prefix " : "", autoTunnelPrefix ? autoTunnelPrefix : "");
359 
360 	info->AutoTunnel = autoTunnelPrefix;
361 	AssignDomainName(&info->domain,  domain);
362 	AssignDomainName(&info->keyname, keyname);
363 	if (hostname)
364 		AssignDomainName(&info->hostname, hostname);
365 	else
366 		info->hostname.c[0] = 0;
367 	if (port)
368 		info->port = *port;
369 	else
370 		info->port = zeroIPPort;
371 	mDNS_snprintf(info->b64keydata, sizeof(info->b64keydata), "%s", b64keydata);
372 
373 	if (DNSDigest_ConstructHMACKeyfromBase64(info, b64keydata) < 0)
374 		{
375 		LogMsg("mDNS_SetSecretForDomain: ERROR: Could not convert shared secret from base64: domain %##s key %##s %s", domain->c, keyname->c, mDNS_LoggingEnabled ? b64keydata : "");
376 		return(mStatus_BadParamErr);
377 		}
378 
379 	// Don't clear deltime until after we've ascertained that b64keydata is valid
380 	info->deltime = 0;
381 
382 	while (*p && (*p) != info) p=&(*p)->next;
383 	if (*p) {LogInfo("mDNS_SetSecretForDomain: Domain %##s Already in list", (*p)->domain.c); return(mStatus_AlreadyRegistered);}
384 
385 	// Caution: Only zero AutoTunnelHostRecord.namestorage and AutoTunnelNAT.clientContext AFTER we've determined that this is a NEW DomainAuthInfo
386 	// being added to the list. Otherwise we risk smashing our AutoTunnel host records and NATOperation that are already active and in use.
387 	info->AutoTunnelHostRecord .resrec.RecordType = kDNSRecordTypeUnregistered;
388 	info->AutoTunnelHostRecord .namestorage.c[0] = 0;
389 	info->AutoTunnelTarget     .resrec.RecordType = kDNSRecordTypeUnregistered;
390 	info->AutoTunnelDeviceInfo .resrec.RecordType = kDNSRecordTypeUnregistered;
391 	info->AutoTunnelService    .resrec.RecordType = kDNSRecordTypeUnregistered;
392 	info->AutoTunnel6Record    .resrec.RecordType = kDNSRecordTypeUnregistered;
393 	info->AutoTunnel6MetaRecord.resrec.RecordType = kDNSRecordTypeUnregistered;
394 	info->AutoTunnelNAT.clientContext = mDNSNULL;
395 	info->next = mDNSNULL;
396 	*p = info;
397 
398 	// Check to see if adding this new DomainAuthInfo has changed the credentials for any of our questions
399 	for (q = m->Questions; q; q=q->next)
400 		{
401 		DomainAuthInfo *newinfo = GetAuthInfoForQuestion(m, q);
402 		if (q->AuthInfo != newinfo)
403 			{
404 			debugf("mDNS_SetSecretForDomain updating q->AuthInfo from %##s to %##s for %##s (%s)",
405 				q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL,
406 				newinfo     ? newinfo    ->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
407 			q->AuthInfo = newinfo;
408 			}
409 		}
410 
411 	return(mStatus_NoError);
412 	}
413 
414 // ***************************************************************************
415 #if COMPILER_LIKES_PRAGMA_MARK
416 #pragma mark -
417 #pragma mark - NAT Traversal
418 #endif
419 
420 mDNSlocal mStatus uDNS_SendNATMsg(mDNS *m, NATTraversalInfo *info)
421 	{
422 	mStatus err = mStatus_NoError;
423 
424 	// send msg if we have a router and it is a private address
425 	if (!mDNSIPv4AddressIsZero(m->Router.ip.v4) && mDNSv4AddrIsRFC1918(&m->Router.ip.v4))
426 		{
427 		union { NATAddrRequest NATAddrReq; NATPortMapRequest NATPortReq; } u = { { NATMAP_VERS, NATOp_AddrRequest } } ;
428 		const mDNSu8 *end = (mDNSu8 *)&u + sizeof(NATAddrRequest);
429 
430 		if (info)			// For NATOp_MapUDP and NATOp_MapTCP, fill in additional fields
431 			{
432 			mDNSu8 *p = (mDNSu8 *)&u.NATPortReq.NATReq_lease;
433 			u.NATPortReq.opcode  = info->Protocol;
434 			u.NATPortReq.unused  = zeroID;
435 			u.NATPortReq.intport = info->IntPort;
436 			u.NATPortReq.extport = info->RequestedPort;
437 			p[0] = (mDNSu8)((info->NATLease >> 24) &  0xFF);
438 			p[1] = (mDNSu8)((info->NATLease >> 16) &  0xFF);
439 			p[2] = (mDNSu8)((info->NATLease >>  8) &  0xFF);
440 			p[3] = (mDNSu8)( info->NATLease        &  0xFF);
441 			end = (mDNSu8 *)&u + sizeof(NATPortMapRequest);
442 			}
443 
444 		err = mDNSPlatformSendUDP(m, (mDNSu8 *)&u, end, 0, mDNSNULL, &m->Router, NATPMPPort);
445 
446 #ifdef _LEGACY_NAT_TRAVERSAL_
447 		if (mDNSIPPortIsZero(m->UPnPRouterPort) || mDNSIPPortIsZero(m->UPnPSOAPPort)) LNT_SendDiscoveryMsg(m);
448 		else if (info) err = LNT_MapPort(m, info);
449 		else err = LNT_GetExternalAddress(m);
450 #endif // _LEGACY_NAT_TRAVERSAL_
451 		}
452 	return(err);
453 	}
454 
455 mDNSexport void RecreateNATMappings(mDNS *const m)
456 	{
457 	NATTraversalInfo *n;
458 	for (n = m->NATTraversals; n; n=n->next)
459 		{
460 		n->ExpiryTime    = 0;		// Mark this mapping as expired
461 		n->retryInterval = NATMAP_INIT_RETRY;
462 		n->retryPortMap  = m->timenow;
463 #ifdef _LEGACY_NAT_TRAVERSAL_
464 		if (n->tcpInfo.sock) { mDNSPlatformTCPCloseConnection(n->tcpInfo.sock); n->tcpInfo.sock = mDNSNULL; }
465 #endif // _LEGACY_NAT_TRAVERSAL_
466 		}
467 
468 	m->NextScheduledNATOp = m->timenow;		// Need to send packets immediately
469 	}
470 
471 mDNSexport void natTraversalHandleAddressReply(mDNS *const m, mDNSu16 err, mDNSv4Addr ExtAddr)
472 	{
473 	static mDNSu16 last_err = 0;
474 
475 	if (err)
476 		{
477 		if (err != last_err) LogMsg("Error getting external address %d", err);
478 		ExtAddr = zerov4Addr;
479 		}
480 	else
481 		{
482 		LogInfo("Received external IP address %.4a from NAT", &ExtAddr);
483 		if (mDNSv4AddrIsRFC1918(&ExtAddr))
484 			LogMsg("Double NAT (external NAT gateway address %.4a is also a private RFC 1918 address)", &ExtAddr);
485 		if (mDNSIPv4AddressIsZero(ExtAddr))
486 			err = NATErr_NetFail; // fake error to handle routers that pathologically report success with the zero address
487 		}
488 
489 	if (!mDNSSameIPv4Address(m->ExternalAddress, ExtAddr))
490 		{
491 		m->ExternalAddress = ExtAddr;
492 		RecreateNATMappings(m);		// Also sets NextScheduledNATOp for us
493 		}
494 
495 	if (!err) // Success, back-off to maximum interval
496 		m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
497 	else if (!last_err) // Failure after success, retry quickly (then back-off exponentially)
498 		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
499 	// else back-off normally in case of pathological failures
500 
501 	m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
502 	if (m->NextScheduledNATOp - m->retryIntervalGetAddr > 0)
503 		m->NextScheduledNATOp = m->retryIntervalGetAddr;
504 
505 	last_err = err;
506 	}
507 
508 // Both places that call NATSetNextRenewalTime() update m->NextScheduledNATOp correctly afterwards
509 mDNSlocal void NATSetNextRenewalTime(mDNS *const m, NATTraversalInfo *n)
510 	{
511 	n->retryInterval = (n->ExpiryTime - m->timenow)/2;
512 	if (n->retryInterval < NATMAP_MIN_RETRY_INTERVAL)	// Min retry interval is 2 seconds
513 		n->retryInterval = NATMAP_MIN_RETRY_INTERVAL;
514 	n->retryPortMap = m->timenow + n->retryInterval;
515 	}
516 
517 // Note: When called from handleLNTPortMappingResponse() only pkt->err, pkt->extport and pkt->NATRep_lease fields are filled in
518 mDNSexport void natTraversalHandlePortMapReply(mDNS *const m, NATTraversalInfo *n, const mDNSInterfaceID InterfaceID, mDNSu16 err, mDNSIPPort extport, mDNSu32 lease)
519 	{
520 	const char *prot = n->Protocol == NATOp_MapUDP ? "UDP" : n->Protocol == NATOp_MapTCP ? "TCP" : "?";
521 	(void)prot;
522 	n->NewResult = err;
523 	if (err || lease == 0 || mDNSIPPortIsZero(extport))
524 		{
525 		LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d error %d",
526 			n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease, err);
527 		n->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
528 		n->retryPortMap = m->timenow + NATMAP_MAX_RETRY_INTERVAL;
529 		// No need to set m->NextScheduledNATOp here, since we're only ever extending the m->retryPortMap time
530 		if      (err == NATErr_Refused)                     n->NewResult = mStatus_NATPortMappingDisabled;
531 		else if (err > NATErr_None && err <= NATErr_Opcode) n->NewResult = mStatus_NATPortMappingUnsupported;
532 		}
533 	else
534 		{
535 		if (lease > 999999999UL / mDNSPlatformOneSecond)
536 			lease = 999999999UL / mDNSPlatformOneSecond;
537 		n->ExpiryTime = NonZeroTime(m->timenow + lease * mDNSPlatformOneSecond);
538 
539 		if (!mDNSSameIPPort(n->RequestedPort, extport))
540 			LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d changed to %5d",
541 				n, prot, mDNSVal16(n->IntPort), mDNSVal16(n->RequestedPort), mDNSVal16(extport));
542 
543 		n->InterfaceID   = InterfaceID;
544 		n->RequestedPort = extport;
545 
546 		LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d",
547 			n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease);
548 
549 		NATSetNextRenewalTime(m, n);			// Got our port mapping; now set timer to renew it at halfway point
550 		m->NextScheduledNATOp = m->timenow;		// May need to invoke client callback immediately
551 		}
552 	}
553 
554 // Must be called with the mDNS_Lock held
555 mDNSexport mStatus mDNS_StartNATOperation_internal(mDNS *const m, NATTraversalInfo *traversal)
556 	{
557 	NATTraversalInfo **n;
558 
559 	LogInfo("mDNS_StartNATOperation_internal %p Protocol %d IntPort %d RequestedPort %d NATLease %d", traversal,
560 		traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
561 
562 	// Note: It important that new traversal requests are appended at the *end* of the list, not prepended at the start
563 	for (n = &m->NATTraversals; *n; n=&(*n)->next)
564 		{
565 		if (traversal == *n)
566 			{
567 			LogMsg("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
568 				traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease);
569 			#if ForceAlerts
570 				*(long*)0 = 0;
571 			#endif
572 			return(mStatus_AlreadyRegistered);
573 			}
574 		if (traversal->Protocol && traversal->Protocol == (*n)->Protocol && mDNSSameIPPort(traversal->IntPort, (*n)->IntPort) &&
575 			!mDNSSameIPPort(traversal->IntPort, SSHPort))
576 			LogMsg("Warning: Created port mapping request %p Prot %d Int %d TTL %d "
577 				"duplicates existing port mapping request %p Prot %d Int %d TTL %d",
578 				traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
579 				*n,        (*n)     ->Protocol, mDNSVal16((*n)     ->IntPort), (*n)     ->NATLease);
580 		}
581 
582 	// Initialize necessary fields
583 	traversal->next            = mDNSNULL;
584 	traversal->ExpiryTime      = 0;
585 	traversal->retryInterval   = NATMAP_INIT_RETRY;
586 	traversal->retryPortMap    = m->timenow;
587 	traversal->NewResult       = mStatus_NoError;
588 	traversal->ExternalAddress = onesIPv4Addr;
589 	traversal->ExternalPort    = zeroIPPort;
590 	traversal->Lifetime        = 0;
591 	traversal->Result          = mStatus_NoError;
592 
593 	// set default lease if necessary
594 	if (!traversal->NATLease) traversal->NATLease = NATMAP_DEFAULT_LEASE;
595 
596 #ifdef _LEGACY_NAT_TRAVERSAL_
597 	mDNSPlatformMemZero(&traversal->tcpInfo, sizeof(traversal->tcpInfo));
598 #endif // _LEGACY_NAT_TRAVERSAL_
599 
600 	if (!m->NATTraversals)		// If this is our first NAT request, kick off an address request too
601 		{
602 		m->retryGetAddr         = m->timenow;
603 		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
604 		}
605 
606 	m->NextScheduledNATOp = m->timenow;	// This will always trigger sending the packet ASAP, and generate client callback if necessary
607 
608 	*n = traversal;		// Append new NATTraversalInfo to the end of our list
609 
610 	return(mStatus_NoError);
611 	}
612 
613 // Must be called with the mDNS_Lock held
614 mDNSexport mStatus mDNS_StopNATOperation_internal(mDNS *m, NATTraversalInfo *traversal)
615 	{
616 	mDNSBool unmap = mDNStrue;
617 	NATTraversalInfo *p;
618 	NATTraversalInfo **ptr = &m->NATTraversals;
619 
620 	while (*ptr && *ptr != traversal) ptr=&(*ptr)->next;
621 	if (*ptr) *ptr = (*ptr)->next;		// If we found it, cut this NATTraversalInfo struct from our list
622 	else
623 		{
624 		LogMsg("mDNS_StopNATOperation_internal: NATTraversalInfo %p not found in list", traversal);
625 		return(mStatus_BadReferenceErr);
626 		}
627 
628 	LogInfo("mDNS_StopNATOperation_internal %p %d %d %d %d", traversal,
629 		traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
630 
631 	if (m->CurrentNATTraversal == traversal)
632 		m->CurrentNATTraversal = m->CurrentNATTraversal->next;
633 
634 	if (traversal->Protocol)
635 		for (p = m->NATTraversals; p; p=p->next)
636 			if (traversal->Protocol == p->Protocol && mDNSSameIPPort(traversal->IntPort, p->IntPort))
637 				{
638 				if (!mDNSSameIPPort(traversal->IntPort, SSHPort))
639 					LogMsg("Warning: Removed port mapping request %p Prot %d Int %d TTL %d "
640 						"duplicates existing port mapping request %p Prot %d Int %d TTL %d",
641 						traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
642 						p,         p        ->Protocol, mDNSVal16(p        ->IntPort), p        ->NATLease);
643 				unmap = mDNSfalse;
644 				}
645 
646 	if (traversal->ExpiryTime && unmap)
647 		{
648 		traversal->NATLease = 0;
649 		traversal->retryInterval = 0;
650 		uDNS_SendNATMsg(m, traversal);
651 		}
652 
653 	// Even if we DIDN'T make a successful UPnP mapping yet, we might still have a partially-open TCP connection we need to clean up
654 	#ifdef _LEGACY_NAT_TRAVERSAL_
655 		{
656 		mStatus err = LNT_UnmapPort(m, traversal);
657 		if (err) LogMsg("Legacy NAT Traversal - unmap request failed with error %d", err);
658 		}
659 	#endif // _LEGACY_NAT_TRAVERSAL_
660 
661 	return(mStatus_NoError);
662 	}
663 
664 mDNSexport mStatus mDNS_StartNATOperation(mDNS *const m, NATTraversalInfo *traversal)
665 	{
666 	mStatus status;
667 	mDNS_Lock(m);
668 	status = mDNS_StartNATOperation_internal(m, traversal);
669 	mDNS_Unlock(m);
670 	return(status);
671 	}
672 
673 mDNSexport mStatus mDNS_StopNATOperation(mDNS *const m, NATTraversalInfo *traversal)
674 	{
675 	mStatus status;
676 	mDNS_Lock(m);
677 	status = mDNS_StopNATOperation_internal(m, traversal);
678 	mDNS_Unlock(m);
679 	return(status);
680 	}
681 
682 // ***************************************************************************
683 #if COMPILER_LIKES_PRAGMA_MARK
684 #pragma mark -
685 #pragma mark - Long-Lived Queries
686 #endif
687 
688 // Lock must be held -- otherwise m->timenow is undefined
689 mDNSlocal void StartLLQPolling(mDNS *const m, DNSQuestion *q)
690 	{
691 	debugf("StartLLQPolling: %##s", q->qname.c);
692 	q->state = LLQ_Poll;
693 	q->ThisQInterval = INIT_UCAST_POLL_INTERVAL;
694 	// We want to send our poll query ASAP, but the "+ 1" is because if we set the time to now,
695 	// we risk causing spurious "SendQueries didn't send all its queries" log messages
696 	q->LastQTime     = m->timenow - q->ThisQInterval + 1;
697 	SetNextQueryTime(m, q);
698 #if APPLE_OSX_mDNSResponder
699 	UpdateAutoTunnelDomainStatuses(m);
700 #endif
701 	}
702 
703 mDNSlocal mDNSu8 *putLLQ(DNSMessage *const msg, mDNSu8 *ptr, const DNSQuestion *const question, const LLQOptData *const data)
704 	{
705 	AuthRecord rr;
706 	ResourceRecord *opt = &rr.resrec;
707 	rdataOPT *optRD;
708 
709 	//!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
710 	ptr = putQuestion(msg, ptr, msg->data + AbsoluteMaxDNSMessageData, &question->qname, question->qtype, question->qclass);
711 	if (!ptr) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL; }
712 
713 	// locate OptRR if it exists, set pointer to end
714 	// !!!KRS implement me
715 
716 	// format opt rr (fields not specified are zero-valued)
717 	mDNS_SetupResourceRecord(&rr, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
718 	opt->rrclass    = NormalMaxDNSMessageData;
719 	opt->rdlength   = sizeof(rdataOPT);	// One option in this OPT record
720 	opt->rdestimate = sizeof(rdataOPT);
721 
722 	optRD = &rr.resrec.rdata->u.opt[0];
723 	optRD->opt = kDNSOpt_LLQ;
724 	optRD->u.llq = *data;
725 	ptr = PutResourceRecordTTLJumbo(msg, ptr, &msg->h.numAdditionals, opt, 0);
726 	if (!ptr) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL; }
727 
728 	return ptr;
729 	}
730 
731 // Normally we'd just request event packets be sent directly to m->LLQNAT.ExternalPort, except...
732 // with LLQs over TLS/TCP we're doing a weird thing where instead of requesting packets be sent to ExternalAddress:ExternalPort
733 // we're requesting that packets be sent to ExternalPort, but at the source address of our outgoing TCP connection.
734 // Normally, after going through the NAT gateway, the source address of our outgoing TCP connection is the same as ExternalAddress,
735 // so this is fine, except when the TCP connection ends up going over a VPN tunnel instead.
736 // To work around this, if we find that the source address for our TCP connection is not a private address, we tell the Dot Mac
737 // LLQ server to send events to us directly at port 5353 on that address, instead of at our mapped external NAT port.
738 
739 mDNSlocal mDNSu16 GetLLQEventPort(const mDNS *const m, const mDNSAddr *const dst)
740 	{
741 	mDNSAddr src;
742 	mDNSPlatformSourceAddrForDest(&src, dst);
743 	//LogMsg("GetLLQEventPort: src %#a for dst %#a (%d)", &src, dst, mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : 0);
744 	return(mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : mDNSVal16(MulticastDNSPort));
745 	}
746 
747 // Normally called with llq set.
748 // May be called with llq NULL, when retransmitting a lost Challenge Response
749 mDNSlocal void sendChallengeResponse(mDNS *const m, DNSQuestion *const q, const LLQOptData *llq)
750 	{
751 	mDNSu8 *responsePtr = m->omsg.data;
752 	LLQOptData llqBuf;
753 
754 	if (q->tcp) { LogMsg("sendChallengeResponse: ERROR!!: question %##s (%s) tcp non-NULL", q->qname.c, DNSTypeName(q->qtype)); return; }
755 
756 	if (PrivateQuery(q)) { LogMsg("sendChallengeResponse: ERROR!!: Private Query %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
757 
758 	if (q->ntries++ == kLLQ_MAX_TRIES)
759 		{
760 		LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s", kLLQ_MAX_TRIES, q->qname.c);
761 		StartLLQPolling(m,q);
762 		return;
763 		}
764 
765 	if (!llq)		// Retransmission: need to make a new LLQOptData
766 		{
767 		llqBuf.vers     = kLLQ_Vers;
768 		llqBuf.llqOp    = kLLQOp_Setup;
769 		llqBuf.err      = LLQErr_NoError;	// Don't need to tell server UDP notification port when sending over UDP
770 		llqBuf.id       = q->id;
771 		llqBuf.llqlease = q->ReqLease;
772 		llq = &llqBuf;
773 		}
774 
775 	q->LastQTime     = m->timenow;
776 	q->ThisQInterval = q->tcp ? 0 : (kLLQ_INIT_RESEND * q->ntries * mDNSPlatformOneSecond);		// If using TCP, don't need to retransmit
777 	SetNextQueryTime(m, q);
778 
779 	// To simulate loss of challenge response packet, uncomment line below
780 	//if (q->ntries == 1) return;
781 
782 	InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
783 	responsePtr = putLLQ(&m->omsg, responsePtr, q, llq);
784 	if (responsePtr)
785 		{
786 		mStatus err = mDNSSendDNSMessage(m, &m->omsg, responsePtr, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
787 		if (err) { LogMsg("sendChallengeResponse: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err); }
788 		}
789 	else StartLLQPolling(m,q);
790 	}
791 
792 mDNSlocal void SetLLQTimer(mDNS *const m, DNSQuestion *const q, const LLQOptData *const llq)
793 	{
794 	mDNSs32 lease = (mDNSs32)llq->llqlease * mDNSPlatformOneSecond;
795 	q->ReqLease      = llq->llqlease;
796 	q->LastQTime     = m->timenow;
797 	q->expire        = m->timenow + lease;
798 	q->ThisQInterval = lease/2 + mDNSRandom(lease/10);
799 	debugf("SetLLQTimer setting %##s (%s) to %d %d", q->qname.c, DNSTypeName(q->qtype), lease/mDNSPlatformOneSecond, q->ThisQInterval/mDNSPlatformOneSecond);
800 	SetNextQueryTime(m, q);
801 	}
802 
803 mDNSlocal void recvSetupResponse(mDNS *const m, mDNSu8 rcode, DNSQuestion *const q, const LLQOptData *const llq)
804 	{
805 	if (rcode && rcode != kDNSFlag1_RC_NXDomain)
806 		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - rcode && rcode != kDNSFlag1_RC_NXDomain", q->qname.c, DNSTypeName(q->qtype)); return; }
807 
808 	if (llq->llqOp != kLLQOp_Setup)
809 		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - bad op %d", q->qname.c, DNSTypeName(q->qtype), llq->llqOp); return; }
810 
811 	if (llq->vers != kLLQ_Vers)
812 		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - bad vers %d", q->qname.c, DNSTypeName(q->qtype), llq->vers); return; }
813 
814 	if (q->state == LLQ_InitialRequest)
815 		{
816 		//LogInfo("Got LLQ_InitialRequest");
817 
818 		if (llq->err) { LogMsg("recvSetupResponse - received llq->err %d from server", llq->err); StartLLQPolling(m,q); return; }
819 
820 		if (q->ReqLease != llq->llqlease)
821 			debugf("recvSetupResponse: requested lease %lu, granted lease %lu", q->ReqLease, llq->llqlease);
822 
823 		// cache expiration in case we go to sleep before finishing setup
824 		q->ReqLease = llq->llqlease;
825 		q->expire = m->timenow + ((mDNSs32)llq->llqlease * mDNSPlatformOneSecond);
826 
827 		// update state
828 		q->state  = LLQ_SecondaryRequest;
829 		q->id     = llq->id;
830 		q->ntries = 0; // first attempt to send response
831 		sendChallengeResponse(m, q, llq);
832 		}
833 	else if (q->state == LLQ_SecondaryRequest)
834 		{
835 		//LogInfo("Got LLQ_SecondaryRequest");
836 
837 		// Fix this immediately if not sooner.  Copy the id from the LLQOptData into our DNSQuestion struct.  This is only
838 		// an issue for private LLQs, because we skip parts 2 and 3 of the handshake.  This is related to a bigger
839 		// problem of the current implementation of TCP LLQ setup: we're not handling state transitions correctly
840 		// if the server sends back SERVFULL or STATIC.
841 		if (PrivateQuery(q))
842 			{
843 			LogInfo("Private LLQ_SecondaryRequest; copying id %08X%08X", llq->id.l[0], llq->id.l[1]);
844 			q->id = llq->id;
845 			}
846 
847 		if (llq->err) { LogMsg("ERROR: recvSetupResponse %##s (%s) code %d from server", q->qname.c, DNSTypeName(q->qtype), llq->err); StartLLQPolling(m,q); return; }
848 		if (!mDNSSameOpaque64(&q->id, &llq->id))
849 			{ LogMsg("recvSetupResponse - ID changed.  discarding"); return; } // this can happen rarely (on packet loss + reordering)
850 		q->state         = LLQ_Established;
851 		q->ntries        = 0;
852 		SetLLQTimer(m, q, llq);
853 #if APPLE_OSX_mDNSResponder
854 		UpdateAutoTunnelDomainStatuses(m);
855 #endif
856 		}
857 	}
858 
859 mDNSexport uDNS_LLQType uDNS_recvLLQResponse(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
860 	const mDNSAddr *const srcaddr, const mDNSIPPort srcport, DNSQuestion **matchQuestion)
861 	{
862 	DNSQuestion pktQ, *q;
863 	if (msg->h.numQuestions && getQuestion(msg, msg->data, end, 0, &pktQ))
864 		{
865 		const rdataOPT *opt = GetLLQOptData(m, msg, end);
866 
867 		for (q = m->Questions; q; q = q->next)
868 			{
869 			if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->qtype == pktQ.qtype && q->qnamehash == pktQ.qnamehash && SameDomainName(&q->qname, &pktQ.qname))
870 				{
871 				debugf("uDNS_recvLLQResponse found %##s (%s) %d %#a %#a %X %X %X %X %d",
872 					q->qname.c, DNSTypeName(q->qtype), q->state, srcaddr, &q->servAddr,
873 					opt ? opt->u.llq.id.l[0] : 0, opt ? opt->u.llq.id.l[1] : 0, q->id.l[0], q->id.l[1], opt ? opt->u.llq.llqOp : 0);
874 				if (q->state == LLQ_Poll) debugf("uDNS_LLQ_Events: q->state == LLQ_Poll msg->h.id %d q->TargetQID %d", mDNSVal16(msg->h.id), mDNSVal16(q->TargetQID));
875 				if (q->state == LLQ_Poll && mDNSSameOpaque16(msg->h.id, q->TargetQID))
876 					{
877 					m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
878 
879 					// Don't reset the state to IntialRequest as we may write that to the dynamic store
880 					// and PrefPane might wrongly think that we are "Starting" instead of "Polling". If
881 					// we are in polling state because of NAT-PMP disabled or DoubleNAT, next LLQNATCallback
882 					// would kick us back to LLQInitialRequest. So, resetting the state here may not be useful.
883 					//
884 					// If we have a good NAT (neither NAT-PMP disabled nor Double-NAT), then we should not be
885 					// possibly in polling state. To be safe, we want to retry from the start in that case
886 					// as there may not be another LLQNATCallback
887 					//
888 					// NOTE: We can be in polling state if we cannot resolve the SOA record i.e, servAddr is set to
889 					// all ones. In that case, we would set it in LLQ_InitialRequest as it overrides the NAT-PMP or
890 					// Double-NAT state.
891 					if (!mDNSAddressIsOnes(&q->servAddr) && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) &&
892 						!m->LLQNAT.Result)
893 						{
894 						debugf("uDNS_recvLLQResponse got poll response; moving to LLQ_InitialRequest for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
895 						q->state         = LLQ_InitialRequest;
896 						}
897 					q->servPort      = zeroIPPort;		// Clear servPort so that startLLQHandshake will retry the GetZoneData processing
898 					q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry LLQ setup in approx 15 minutes
899 					q->LastQTime     = m->timenow;
900 					SetNextQueryTime(m, q);
901 					*matchQuestion = q;
902 					return uDNS_LLQ_Entire;		// uDNS_LLQ_Entire means flush stale records; assume a large effective TTL
903 					}
904 				// Note: In LLQ Event packets, the msg->h.id does not match our q->TargetQID, because in that case the msg->h.id nonce is selected by the server
905 				else if (opt && q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Event && mDNSSameOpaque64(&opt->u.llq.id, &q->id))
906 					{
907 					mDNSu8 *ackEnd;
908 					//debugf("Sending LLQ ack for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
909 					InitializeDNSMessage(&m->omsg.h, msg->h.id, ResponseFlags);
910 					ackEnd = putLLQ(&m->omsg, m->omsg.data, q, &opt->u.llq);
911 					if (ackEnd) mDNSSendDNSMessage(m, &m->omsg, ackEnd, mDNSInterface_Any, q->LocalSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
912 					m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
913 					debugf("uDNS_LLQ_Events: q->state == LLQ_Established msg->h.id %d q->TargetQID %d", mDNSVal16(msg->h.id), mDNSVal16(q->TargetQID));
914 					*matchQuestion = q;
915 					return uDNS_LLQ_Events;
916 					}
917 				if (opt && mDNSSameOpaque16(msg->h.id, q->TargetQID))
918 					{
919 					if (q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Refresh && mDNSSameOpaque64(&opt->u.llq.id, &q->id) && msg->h.numAdditionals && !msg->h.numAnswers)
920 						{
921 						if (opt->u.llq.err != LLQErr_NoError) LogMsg("recvRefreshReply: received error %d from server", opt->u.llq.err);
922 						else
923 							{
924 							//LogInfo("Received refresh confirmation ntries %d for %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
925 							// If we're waiting to go to sleep, then this LLQ deletion may have been the thing
926 							// we were waiting for, so schedule another check to see if we can sleep now.
927 							if (opt->u.llq.llqlease == 0 && m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
928 							GrantCacheExtensions(m, q, opt->u.llq.llqlease);
929 							SetLLQTimer(m, q, &opt->u.llq);
930 							q->ntries = 0;
931 							}
932 						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
933 						*matchQuestion = q;
934 						return uDNS_LLQ_Ignore;
935 						}
936 					if (q->state < LLQ_Established && mDNSSameAddress(srcaddr, &q->servAddr))
937 						{
938 						LLQ_State oldstate = q->state;
939 						recvSetupResponse(m, msg->h.flags.b[1] & kDNSFlag1_RC_Mask, q, &opt->u.llq);
940 						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
941 						// We have a protocol anomaly here in the LLQ definition.
942 						// Both the challenge packet from the server and the ack+answers packet have opt->u.llq.llqOp == kLLQOp_Setup.
943 						// However, we need to treat them differently:
944 						// The challenge packet has no answers in it, and tells us nothing about whether our cache entries
945 						// are still valid, so this packet should not cause us to do anything that messes with our cache.
946 						// The ack+answers packet gives us the whole truth, so we should handle it by updating our cache
947 						// to match the answers in the packet, and only the answers in the packet.
948 						*matchQuestion = q;
949 						return (oldstate == LLQ_SecondaryRequest ? uDNS_LLQ_Entire : uDNS_LLQ_Ignore);
950 						}
951 					}
952 				}
953 			}
954 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
955 		}
956 	*matchQuestion = mDNSNULL;
957 	return uDNS_LLQ_Not;
958 	}
959 
960 // Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
961 struct TCPSocket_struct { TCPSocketFlags flags; /* ... */ };
962 
963 // tcpCallback is called to handle events (e.g. connection opening and data reception) on TCP connections for
964 // Private DNS operations -- private queries, private LLQs, private record updates and private service updates
965 mDNSlocal void tcpCallback(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err)
966 	{
967 	tcpInfo_t *tcpInfo = (tcpInfo_t *)context;
968 	mDNSBool   closed  = mDNSfalse;
969 	mDNS      *m       = tcpInfo->m;
970 	DNSQuestion *const q = tcpInfo->question;
971 	tcpInfo_t **backpointer =
972 		q                 ? &q           ->tcp :
973 		tcpInfo->rr       ? &tcpInfo->rr ->tcp : mDNSNULL;
974 	if (backpointer && *backpointer != tcpInfo)
975 		LogMsg("tcpCallback: %d backpointer %p incorrect tcpInfo %p question %p rr %p",
976 			mDNSPlatformTCPGetFD(tcpInfo->sock), *backpointer, tcpInfo, q, tcpInfo->rr);
977 
978 	if (err) goto exit;
979 
980 	if (ConnectionEstablished)
981 		{
982 		mDNSu8    *end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
983 		DomainAuthInfo *AuthInfo;
984 
985 		// Defensive coding for <rdar://problem/5546824> Crash in mDNSResponder at GetAuthInfoForName_internal + 366
986 		// Don't know yet what's causing this, but at least we can be cautious and try to avoid crashing if we find our pointers in an unexpected state
987 		if (tcpInfo->rr && tcpInfo->rr->resrec.name != &tcpInfo->rr->namestorage)
988 			LogMsg("tcpCallback: ERROR: tcpInfo->rr->resrec.name %p != &tcpInfo->rr->namestorage %p",
989 				tcpInfo->rr->resrec.name, &tcpInfo->rr->namestorage);
990 		if (tcpInfo->rr  && tcpInfo->rr->        resrec.name != &tcpInfo->rr->        namestorage) return;
991 
992 		AuthInfo =  tcpInfo->rr  ? GetAuthInfoForName(m, tcpInfo->rr->resrec.name)         : mDNSNULL;
993 
994 		// connection is established - send the message
995 		if (q && q->LongLived && q->state == LLQ_Established)
996 			{
997 			// Lease renewal over TCP, resulting from opening a TCP connection in sendLLQRefresh
998 			end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
999 			}
1000 		else if (q && q->LongLived && q->state != LLQ_Poll && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) && !mDNSIPPortIsZero(q->servPort))
1001 			{
1002 			// Notes:
1003 			// If we have a NAT port mapping, ExternalPort is the external port
1004 			// If we have a routable address so we don't need a port mapping, ExternalPort is the same as our own internal port
1005 			// If we need a NAT port mapping but can't get one, then ExternalPort is zero
1006 			LLQOptData llqData;			// set llq rdata
1007 			llqData.vers  = kLLQ_Vers;
1008 			llqData.llqOp = kLLQOp_Setup;
1009 			llqData.err   = GetLLQEventPort(m, &tcpInfo->Addr);	// We're using TCP; tell server what UDP port to send notifications to
1010 			LogInfo("tcpCallback: eventPort %d", llqData.err);
1011 			llqData.id    = zeroOpaque64;
1012 			llqData.llqlease = kLLQ_DefLease;
1013 			InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
1014 			end = putLLQ(&tcpInfo->request, tcpInfo->request.data, q, &llqData);
1015 			if (!end) { LogMsg("ERROR: tcpCallback - putLLQ"); err = mStatus_UnknownErr; goto exit; }
1016 			AuthInfo = q->AuthInfo;		// Need to add TSIG to this message
1017 			q->ntries = 0; // Reset ntries so that tcp/tls connection failures don't affect sendChallengeResponse failures
1018 			}
1019 		else if (q)
1020 			{
1021 			// LLQ Polling mode or non-LLQ uDNS over TCP
1022 			InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
1023 			end = putQuestion(&tcpInfo->request, tcpInfo->request.data, tcpInfo->request.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
1024 			AuthInfo = q->AuthInfo;		// Need to add TSIG to this message
1025 			}
1026 
1027 		err = mDNSSendDNSMessage(m, &tcpInfo->request, end, mDNSInterface_Any, mDNSNULL, &tcpInfo->Addr, tcpInfo->Port, sock, AuthInfo);
1028 		if (err) { debugf("ERROR: tcpCallback: mDNSSendDNSMessage - %d", err); err = mStatus_UnknownErr; goto exit; }
1029 
1030 		// Record time we sent this question
1031 		if (q)
1032 			{
1033 			mDNS_Lock(m);
1034 			q->LastQTime = m->timenow;
1035 			if (q->ThisQInterval < (256 * mDNSPlatformOneSecond))	// Now we have a TCP connection open, make sure we wait at least 256 seconds before retrying
1036 				q->ThisQInterval = (256 * mDNSPlatformOneSecond);
1037 			SetNextQueryTime(m, q);
1038 			mDNS_Unlock(m);
1039 			}
1040 		}
1041 	else
1042 		{
1043 		long n;
1044 		if (tcpInfo->nread < 2)			// First read the two-byte length preceeding the DNS message
1045 			{
1046 			mDNSu8 *lenptr = (mDNSu8 *)&tcpInfo->replylen;
1047 			n = mDNSPlatformReadTCP(sock, lenptr + tcpInfo->nread, 2 - tcpInfo->nread, &closed);
1048 			if (n < 0)
1049 				{
1050 				LogMsg("ERROR: tcpCallback - attempt to read message length failed (%d)", n);
1051 				err = mStatus_ConnFailed;
1052 				goto exit;
1053 				}
1054 			else if (closed)
1055 				{
1056 				// It's perfectly fine for this socket to close after the first reply. The server might
1057 				// be sending gratuitous replies using UDP and doesn't have a need to leave the TCP socket open.
1058 				// We'll only log this event if we've never received a reply before.
1059 				// BIND 9 appears to close an idle connection after 30 seconds.
1060 				if (tcpInfo->numReplies == 0)
1061 					{
1062 					LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
1063 					err = mStatus_ConnFailed;
1064 					goto exit;
1065 					}
1066 				else
1067 					{
1068 					// Note that we may not be doing the best thing if an error occurs after we've sent a second request
1069 					// over this tcp connection.  That is, we only track whether we've received at least one response
1070 					// which may have been to a previous request sent over this tcp connection.
1071 					if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1072 					DisposeTCPConn(tcpInfo);
1073 					return;
1074 					}
1075 				}
1076 
1077 			tcpInfo->nread += n;
1078 			if (tcpInfo->nread < 2) goto exit;
1079 
1080 			tcpInfo->replylen = (mDNSu16)((mDNSu16)lenptr[0] << 8 | lenptr[1]);
1081 			if (tcpInfo->replylen < sizeof(DNSMessageHeader))
1082 				{ LogMsg("ERROR: tcpCallback - length too short (%d bytes)", tcpInfo->replylen); err = mStatus_UnknownErr; goto exit; }
1083 
1084 			tcpInfo->reply = mDNSPlatformMemAllocate(tcpInfo->replylen);
1085 			if (!tcpInfo->reply) { LogMsg("ERROR: tcpCallback - malloc failed"); err = mStatus_NoMemoryErr; goto exit; }
1086 			}
1087 
1088 		n = mDNSPlatformReadTCP(sock, ((char *)tcpInfo->reply) + (tcpInfo->nread - 2), tcpInfo->replylen - (tcpInfo->nread - 2), &closed);
1089 
1090 		if (n < 0)
1091 			{
1092 			LogMsg("ERROR: tcpCallback - read returned %d", n);
1093 			err = mStatus_ConnFailed;
1094 			goto exit;
1095 			}
1096 		else if (closed)
1097 			{
1098 			if (tcpInfo->numReplies == 0)
1099 				{
1100 				LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
1101 				err = mStatus_ConnFailed;
1102 				goto exit;
1103 				}
1104 			else
1105 				{
1106 				// Note that we may not be doing the best thing if an error occurs after we've sent a second request
1107 				// over this tcp connection.  That is, we only track whether we've received at least one response
1108 				// which may have been to a previous request sent over this tcp connection.
1109 				if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1110 				DisposeTCPConn(tcpInfo);
1111 				return;
1112 				}
1113 			}
1114 
1115 		tcpInfo->nread += n;
1116 
1117 		if ((tcpInfo->nread - 2) == tcpInfo->replylen)
1118 			{
1119 			mDNSBool tls;
1120 			DNSMessage *reply = tcpInfo->reply;
1121 			mDNSu8     *end   = (mDNSu8 *)tcpInfo->reply + tcpInfo->replylen;
1122 			mDNSAddr    Addr  = tcpInfo->Addr;
1123 			mDNSIPPort  Port  = tcpInfo->Port;
1124 			mDNSIPPort srcPort = zeroIPPort;
1125 			tcpInfo->numReplies++;
1126 			tcpInfo->reply    = mDNSNULL;	// Detach reply buffer from tcpInfo_t, to make sure client callback can't cause it to be disposed
1127 			tcpInfo->nread    = 0;
1128 			tcpInfo->replylen = 0;
1129 
1130 			// If we're going to dispose this connection, do it FIRST, before calling client callback
1131 			// Note: Sleep code depends on us clearing *backpointer here -- it uses the clearing of rr->tcp
1132 			// as the signal that the DNS deregistration operation with the server has completed, and the machine may now sleep
1133 			// If we clear the tcp pointer in the question, mDNSCoreReceiveResponse cannot find a matching question. Hence
1134 			// we store the minimal information i.e., the source port of the connection in the question itself.
1135 			// Dereference sock before it is disposed in DisposeTCPConn below.
1136 
1137 			if (sock->flags & kTCPSocketFlags_UseTLS) tls = mDNStrue;
1138 			else tls = mDNSfalse;
1139 
1140 			if (q && q->tcp) {srcPort = q->tcp->SrcPort; q->tcpSrcPort = srcPort;}
1141 
1142 			if (backpointer)
1143 				if (!q || !q->LongLived || m->SleepState)
1144 					{ *backpointer = mDNSNULL; DisposeTCPConn(tcpInfo); }
1145 
1146 			mDNSCoreReceive(m, reply, end, &Addr, Port, tls ? (mDNSAddr *)1 : mDNSNULL, srcPort, 0);
1147 			// USE CAUTION HERE: Invoking mDNSCoreReceive may have caused the environment to change, including canceling this operation itself
1148 
1149 			mDNSPlatformMemFree(reply);
1150 			return;
1151 			}
1152 		}
1153 
1154 exit:
1155 
1156 	if (err)
1157 		{
1158 		// Clear client backpointer FIRST -- that way if one of the callbacks cancels its operation
1159 		// we won't end up double-disposing our tcpInfo_t
1160 		if (backpointer) *backpointer = mDNSNULL;
1161 
1162 		mDNS_Lock(m);		// Need to grab the lock to get m->timenow
1163 
1164 		if (q)
1165 			{
1166 			if (q->ThisQInterval == 0)
1167 				{
1168 				// We get here when we fail to establish a new TCP/TLS connection that would have been used for a new LLQ request or an LLQ renewal.
1169 				// Note that ThisQInterval is also zero when sendChallengeResponse resends the LLQ request on an extant TCP/TLS connection.
1170 				q->LastQTime = m->timenow;
1171 				if (q->LongLived)
1172 					{
1173 					// We didn't get the chance to send our request packet before the TCP/TLS connection failed.
1174 					// We want to retry quickly, but want to back off exponentially in case the server is having issues.
1175 					// Since ThisQInterval was 0, we can't just multiply by QuestionIntervalStep, we must track the number
1176 					// of TCP/TLS connection failures using ntries.
1177 					mDNSu32 count = q->ntries + 1; // want to wait at least 1 second before retrying
1178 
1179 					q->ThisQInterval = InitialQuestionInterval;
1180 
1181 					for (;count;count--)
1182 						q->ThisQInterval *= QuestionIntervalStep;
1183 
1184 					if (q->ThisQInterval > LLQ_POLL_INTERVAL)
1185 						q->ThisQInterval = LLQ_POLL_INTERVAL;
1186 					else
1187 						q->ntries++;
1188 
1189 					LogMsg("tcpCallback: stream connection for LLQ %##s (%s) failed %d times, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ntries, q->ThisQInterval);
1190 					}
1191 				else
1192 					{
1193 					q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
1194 					LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
1195 					}
1196 				SetNextQueryTime(m, q);
1197 				}
1198 			else if (NextQSendTime(q) - m->timenow > (q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL))
1199 				{
1200 				// If we get an error and our next scheduled query for this question is more than the max interval from now,
1201 				// reset the next query to ensure we wait no longer the maximum interval from now before trying again.
1202 				q->LastQTime     = m->timenow;
1203 				q->ThisQInterval = q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL;
1204 				SetNextQueryTime(m, q);
1205 				LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
1206 				}
1207 
1208 			// We're about to dispose of the TCP connection, so we must reset the state to retry over TCP/TLS
1209 			// because sendChallengeResponse will send the query via UDP if we don't have a tcp pointer.
1210 			// Resetting to LLQ_InitialRequest will cause uDNS_CheckCurrentQuestion to call startLLQHandshake, which
1211 			// will attempt to establish a new tcp connection.
1212 			if (q->LongLived && q->state == LLQ_SecondaryRequest)
1213 				q->state = LLQ_InitialRequest;
1214 
1215 			// ConnFailed may happen if the server sends a TCP reset or TLS fails, in which case we want to retry establishing the LLQ
1216 			// quickly rather than switching to polling mode.  This case is handled by the above code to set q->ThisQInterval just above.
1217 			// If the error isn't ConnFailed, then the LLQ is in bad shape, so we switch to polling mode.
1218 			if (err != mStatus_ConnFailed)
1219 				{
1220 				if (q->LongLived && q->state != LLQ_Poll) StartLLQPolling(m, q);
1221 				}
1222 			}
1223 
1224 		mDNS_Unlock(m);
1225 
1226 		DisposeTCPConn(tcpInfo);
1227 		}
1228 	}
1229 
1230 mDNSlocal tcpInfo_t *MakeTCPConn(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
1231 	TCPSocketFlags flags, const mDNSAddr *const Addr, const mDNSIPPort Port, domainname *hostname,
1232 	DNSQuestion *const question, AuthRecord *const rr)
1233 	{
1234 	mStatus err;
1235 	mDNSIPPort srcport = zeroIPPort;
1236 	tcpInfo_t *info;
1237 
1238 	if ((flags & kTCPSocketFlags_UseTLS) && (!hostname || !hostname->c[0]))
1239 		{ LogMsg("MakeTCPConn: TLS connection being setup with NULL hostname"); return mDNSNULL; }
1240 
1241 	info = (tcpInfo_t *)mDNSPlatformMemAllocate(sizeof(tcpInfo_t));
1242 	if (!info) { LogMsg("ERROR: MakeTCP - memallocate failed"); return(mDNSNULL); }
1243 	mDNSPlatformMemZero(info, sizeof(tcpInfo_t));
1244 
1245 	info->m          = m;
1246 	info->sock       = mDNSPlatformTCPSocket(m, flags, &srcport);
1247 	info->requestLen = 0;
1248 	info->question   = question;
1249 	info->rr         = rr;
1250 	info->Addr       = *Addr;
1251 	info->Port       = Port;
1252 	info->reply      = mDNSNULL;
1253 	info->replylen   = 0;
1254 	info->nread      = 0;
1255 	info->numReplies = 0;
1256 	info->SrcPort = srcport;
1257 
1258 	if (msg)
1259 		{
1260 		info->requestLen = (int) (end - ((mDNSu8*)msg));
1261 		mDNSPlatformMemCopy(&info->request, msg, info->requestLen);
1262 		}
1263 
1264 	if (!info->sock) { LogMsg("MakeTCPConn: unable to create TCP socket"); mDNSPlatformMemFree(info); return(mDNSNULL); }
1265 	err = mDNSPlatformTCPConnect(info->sock, Addr, Port, hostname, (question ? question->InterfaceID : mDNSNULL), tcpCallback, info);
1266 
1267 	// Probably suboptimal here.
1268 	// Instead of returning mDNSNULL here on failure, we should probably invoke the callback with an error code.
1269 	// That way clients can put all the error handling and retry/recovery code in one place,
1270 	// instead of having to handle immediate errors in one place and async errors in another.
1271 	// Also: "err == mStatus_ConnEstablished" probably never happens.
1272 
1273 	// Don't need to log "connection failed" in customer builds -- it happens quite often during sleep, wake, configuration changes, etc.
1274 	if      (err == mStatus_ConnEstablished) { tcpCallback(info->sock, info, mDNStrue, mStatus_NoError); }
1275 	else if (err != mStatus_ConnPending    ) { LogInfo("MakeTCPConn: connection failed"); DisposeTCPConn(info); return(mDNSNULL); }
1276 	return(info);
1277 	}
1278 
1279 mDNSexport void DisposeTCPConn(struct tcpInfo_t *tcp)
1280 	{
1281 	mDNSPlatformTCPCloseConnection(tcp->sock);
1282 	if (tcp->reply) mDNSPlatformMemFree(tcp->reply);
1283 	mDNSPlatformMemFree(tcp);
1284 	}
1285 
1286 // Lock must be held
1287 mDNSexport void startLLQHandshake(mDNS *m, DNSQuestion *q)
1288 	{
1289 	if (mDNSIPv4AddressIsOnes(m->LLQNAT.ExternalAddress))
1290 		{
1291 		LogInfo("startLLQHandshake: waiting for NAT status for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1292 		q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry in approx 15 minutes
1293 		q->LastQTime = m->timenow;
1294 		SetNextQueryTime(m, q);
1295 		return;
1296 		}
1297 
1298 	// Either we don't have NAT-PMP support (ExternalPort is zero) or behind a Double NAT that may or
1299 	// may not have NAT-PMP support (NATResult is non-zero)
1300 	if (mDNSIPPortIsZero(m->LLQNAT.ExternalPort) || m->LLQNAT.Result)
1301 		{
1302 		LogInfo("startLLQHandshake: Cannot receive inbound packets; will poll for %##s (%s) External Port %d, NAT Result %d",
1303 			q->qname.c, DNSTypeName(q->qtype), mDNSVal16(m->LLQNAT.ExternalPort), m->LLQNAT.Result);
1304 		StartLLQPolling(m, q);
1305 		return;
1306 		}
1307 
1308 	if (mDNSIPPortIsZero(q->servPort))
1309 		{
1310 		debugf("startLLQHandshake: StartGetZoneData for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1311 		q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry in approx 15 minutes
1312 		q->LastQTime     = m->timenow;
1313 		SetNextQueryTime(m, q);
1314 		q->servAddr = zeroAddr;
1315 		// We know q->servPort is zero because of check above
1316 		if (q->nta) CancelGetZoneData(m, q->nta);
1317 		q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
1318 		return;
1319 		}
1320 
1321 	if (PrivateQuery(q))
1322 		{
1323 		if (q->tcp) LogInfo("startLLQHandshake: Disposing existing TCP connection for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1324 		if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
1325 		if (!q->nta)
1326 			{
1327 			// Normally we lookup the zone data and then call this function. And we never free the zone data
1328 			// for "PrivateQuery". But sometimes this can happen due to some race conditions. When we
1329 			// switch networks, we might end up "Polling" the network e.g., we are behind a Double NAT.
1330 			// When we poll, we free the zone information as we send the query to the server (See
1331 			// PrivateQueryGotZoneData). The NAT callback (LLQNATCallback) may happen soon after that. If we
1332 			// are still behind Double NAT, we would have returned early in this function. But we could
1333 			// have switched to a network with no NATs and we should get the zone data again.
1334 			LogInfo("startLLQHandshake: nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1335 			q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
1336 			return;
1337 			}
1338 		else if (!q->nta->Host.c[0])
1339 			{
1340 			// This should not happen. If it happens, we print a log and MakeTCPConn will fail if it can't find a hostname
1341 			LogMsg("startLLQHandshake: ERROR!!: nta non NULL for %##s (%s) but HostName %d NULL, LongLived %d", q->qname.c, DNSTypeName(q->qtype), q->nta->Host.c[0], q->LongLived);
1342 			}
1343 		q->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
1344 		if (!q->tcp)
1345 			q->ThisQInterval = mDNSPlatformOneSecond * 5;	// If TCP failed (transient networking glitch) try again in five seconds
1346 		else
1347 			{
1348 			q->state         = LLQ_SecondaryRequest;		// Right now, for private DNS, we skip the four-way LLQ handshake
1349 			q->ReqLease      = kLLQ_DefLease;
1350 			q->ThisQInterval = 0;
1351 			}
1352 		q->LastQTime     = m->timenow;
1353 		SetNextQueryTime(m, q);
1354 		}
1355 	else
1356 		{
1357 		debugf("startLLQHandshake: m->AdvertisedV4 %#a%s Server %#a:%d%s %##s (%s)",
1358 			&m->AdvertisedV4,                     mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) ? " (RFC 1918)" : "",
1359 			&q->servAddr, mDNSVal16(q->servPort), mDNSAddrIsRFC1918(&q->servAddr)             ? " (RFC 1918)" : "",
1360 			q->qname.c, DNSTypeName(q->qtype));
1361 
1362 		if (q->ntries++ >= kLLQ_MAX_TRIES)
1363 			{
1364 			LogMsg("startLLQHandshake: %d failed attempts for LLQ %##s Polling.", kLLQ_MAX_TRIES, q->qname.c);
1365 			StartLLQPolling(m, q);
1366 			}
1367 		else
1368 			{
1369 			mDNSu8 *end;
1370 			LLQOptData llqData;
1371 
1372 			// set llq rdata
1373 			llqData.vers  = kLLQ_Vers;
1374 			llqData.llqOp = kLLQOp_Setup;
1375 			llqData.err   = LLQErr_NoError;	// Don't need to tell server UDP notification port when sending over UDP
1376 			llqData.id    = zeroOpaque64;
1377 			llqData.llqlease = kLLQ_DefLease;
1378 
1379 			InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
1380 			end = putLLQ(&m->omsg, m->omsg.data, q, &llqData);
1381 			if (!end) { LogMsg("ERROR: startLLQHandshake - putLLQ"); StartLLQPolling(m,q); return; }
1382 
1383 			mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
1384 
1385 			// update question state
1386 			q->state         = LLQ_InitialRequest;
1387 			q->ReqLease      = kLLQ_DefLease;
1388 			q->ThisQInterval = (kLLQ_INIT_RESEND * mDNSPlatformOneSecond);
1389 			q->LastQTime     = m->timenow;
1390 			SetNextQueryTime(m, q);
1391 			}
1392 		}
1393 	}
1394 
1395 // forward declaration so GetServiceTarget can do reverse lookup if needed
1396 mDNSlocal void GetStaticHostname(mDNS *m);
1397 
1398 mDNSexport const domainname *GetServiceTarget(mDNS *m, AuthRecord *const rr)
1399 	{
1400 	debugf("GetServiceTarget %##s", rr->resrec.name->c);
1401 
1402 	if (!rr->AutoTarget)		// If not automatically tracking this host's current name, just return the existing target
1403 		return(&rr->resrec.rdata->u.srv.target);
1404 	else
1405 		{
1406 #if APPLE_OSX_mDNSResponder
1407 		DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
1408 		if (AuthInfo && AuthInfo->AutoTunnel)
1409 			{
1410 			// If this AutoTunnel is not yet active, start it now (which entails activating its NAT Traversal request,
1411 			// which will subsequently advertise the appropriate records when the NAT Traversal returns a result)
1412 			if (!AuthInfo->AutoTunnelNAT.clientContext && m->AutoTunnelHostAddr.b[0])
1413 				{
1414 				LogInfo("GetServiceTarget: Calling SetupLocalAutoTunnelInterface_internal");
1415 				SetupLocalAutoTunnelInterface_internal(m, mDNStrue);
1416 				}
1417 			if (AuthInfo->AutoTunnelHostRecord.namestorage.c[0] == 0) return(mDNSNULL);
1418 			debugf("GetServiceTarget: Returning %##s", AuthInfo->AutoTunnelHostRecord.namestorage.c);
1419 			return(&AuthInfo->AutoTunnelHostRecord.namestorage);
1420 			}
1421 		else
1422 #endif // APPLE_OSX_mDNSResponder
1423 			{
1424 			const int srvcount = CountLabels(rr->resrec.name);
1425 			HostnameInfo *besthi = mDNSNULL, *hi;
1426 			int best = 0;
1427 			for (hi = m->Hostnames; hi; hi = hi->next)
1428 				if (hi->arv4.state == regState_Registered || hi->arv4.state == regState_Refresh ||
1429 					hi->arv6.state == regState_Registered || hi->arv6.state == regState_Refresh)
1430 					{
1431 					int x, hostcount = CountLabels(&hi->fqdn);
1432 					for (x = hostcount < srvcount ? hostcount : srvcount; x > 0 && x > best; x--)
1433 						if (SameDomainName(SkipLeadingLabels(rr->resrec.name, srvcount - x), SkipLeadingLabels(&hi->fqdn, hostcount - x)))
1434 							{ best = x; besthi = hi; }
1435 					}
1436 
1437 			if (besthi) return(&besthi->fqdn);
1438 			}
1439 		if (m->StaticHostname.c[0]) return(&m->StaticHostname);
1440 		else GetStaticHostname(m); // asynchronously do reverse lookup for primary IPv4 address
1441 		LogInfo("GetServiceTarget: Returning NULL for %s", ARDisplayString(m, rr));
1442 		return(mDNSNULL);
1443 		}
1444 	}
1445 
1446 mDNSlocal const domainname *PUBLIC_UPDATE_SERVICE_TYPE  = (const domainname*)"\x0B_dns-update"     "\x04_udp";
1447 mDNSlocal const domainname *PUBLIC_LLQ_SERVICE_TYPE     = (const domainname*)"\x08_dns-llq"        "\x04_udp";
1448 
1449 mDNSlocal const domainname *PRIVATE_UPDATE_SERVICE_TYPE = (const domainname*)"\x0F_dns-update-tls" "\x04_tcp";
1450 mDNSlocal const domainname *PRIVATE_QUERY_SERVICE_TYPE  = (const domainname*)"\x0E_dns-query-tls"  "\x04_tcp";
1451 mDNSlocal const domainname *PRIVATE_LLQ_SERVICE_TYPE    = (const domainname*)"\x0C_dns-llq-tls"    "\x04_tcp";
1452 
1453 #define ZoneDataSRV(X) (\
1454 	(X)->ZoneService == ZoneServiceUpdate ? ((X)->ZonePrivate ? PRIVATE_UPDATE_SERVICE_TYPE : PUBLIC_UPDATE_SERVICE_TYPE) : \
1455 	(X)->ZoneService == ZoneServiceQuery  ? ((X)->ZonePrivate ? PRIVATE_QUERY_SERVICE_TYPE  : (const domainname*)""     ) : \
1456 	(X)->ZoneService == ZoneServiceLLQ    ? ((X)->ZonePrivate ? PRIVATE_LLQ_SERVICE_TYPE    : PUBLIC_LLQ_SERVICE_TYPE   ) : (const domainname*)"")
1457 
1458 // Forward reference: GetZoneData_StartQuery references GetZoneData_QuestionCallback, and
1459 // GetZoneData_QuestionCallback calls GetZoneData_StartQuery
1460 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype);
1461 
1462 // GetZoneData_QuestionCallback is called from normal client callback context (core API calls allowed)
1463 mDNSlocal void GetZoneData_QuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
1464 	{
1465 	ZoneData *zd = (ZoneData*)question->QuestionContext;
1466 
1467 	debugf("GetZoneData_QuestionCallback: %s %s", AddRecord ? "Add" : "Rmv", RRDisplayString(m, answer));
1468 
1469 	if (!AddRecord) return;												// Don't care about REMOVE events
1470 	if (AddRecord == QC_addnocache && answer->rdlength == 0) return;	// Don't care about transient failure indications
1471 	if (answer->rrtype != question->qtype) return;						// Don't care about CNAMEs
1472 
1473 	if (answer->rrtype == kDNSType_SOA)
1474 		{
1475 		debugf("GetZoneData GOT SOA %s", RRDisplayString(m, answer));
1476 		mDNS_StopQuery(m, question);
1477 		if (question->ThisQInterval != -1)
1478 			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1479 		if (answer->rdlength)
1480 			{
1481 			AssignDomainName(&zd->ZoneName, answer->name);
1482 			zd->ZoneClass = answer->rrclass;
1483 			AssignDomainName(&zd->question.qname, &zd->ZoneName);
1484 			GetZoneData_StartQuery(m, zd, kDNSType_SRV);
1485 			}
1486 		else if (zd->CurrentSOA->c[0])
1487 			{
1488 			DomainAuthInfo *AuthInfo = GetAuthInfoForName(m, zd->CurrentSOA);
1489 			if (AuthInfo && AuthInfo->AutoTunnel)
1490 				{
1491 				// To keep the load on the server down, we don't chop down on
1492 				// SOA lookups for AutoTunnels
1493 				LogInfo("GetZoneData_QuestionCallback: not chopping labels for %##s", zd->CurrentSOA->c);
1494 				zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
1495 				}
1496 			else
1497 				{
1498 				zd->CurrentSOA = (domainname *)(zd->CurrentSOA->c + zd->CurrentSOA->c[0]+1);
1499 				AssignDomainName(&zd->question.qname, zd->CurrentSOA);
1500 				GetZoneData_StartQuery(m, zd, kDNSType_SOA);
1501 				}
1502 			}
1503 		else
1504 			{
1505 			LogInfo("GetZoneData recursed to root label of %##s without finding SOA", zd->ChildName.c);
1506 			zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
1507 			}
1508 		}
1509 	else if (answer->rrtype == kDNSType_SRV)
1510 		{
1511 		debugf("GetZoneData GOT SRV %s", RRDisplayString(m, answer));
1512 		mDNS_StopQuery(m, question);
1513 		if (question->ThisQInterval != -1)
1514 			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1515 // Right now we don't want to fail back to non-encrypted operations
1516 // If the AuthInfo has the AutoTunnel field set, then we want private or nothing
1517 // <rdar://problem/5687667> BTMM: Don't fallback to unencrypted operations when SRV lookup fails
1518 #if 0
1519 		if (!answer->rdlength && zd->ZonePrivate && zd->ZoneService != ZoneServiceQuery)
1520 			{
1521 			zd->ZonePrivate = mDNSfalse;	// Causes ZoneDataSRV() to yield a different SRV name when building the query
1522 			GetZoneData_StartQuery(m, zd, kDNSType_SRV);		// Try again, non-private this time
1523 			}
1524 		else
1525 #endif
1526 			{
1527 			if (answer->rdlength)
1528 				{
1529 				AssignDomainName(&zd->Host, &answer->rdata->u.srv.target);
1530 				zd->Port = answer->rdata->u.srv.port;
1531 				AssignDomainName(&zd->question.qname, &zd->Host);
1532 				GetZoneData_StartQuery(m, zd, kDNSType_A);
1533 				}
1534 			else
1535 				{
1536 				zd->ZonePrivate = mDNSfalse;
1537 				zd->Host.c[0] = 0;
1538 				zd->Port = zeroIPPort;
1539 				zd->Addr = zeroAddr;
1540 				zd->ZoneDataCallback(m, mStatus_NoError, zd);
1541 				}
1542 			}
1543 		}
1544 	else if (answer->rrtype == kDNSType_A)
1545 		{
1546 		debugf("GetZoneData GOT A %s", RRDisplayString(m, answer));
1547 		mDNS_StopQuery(m, question);
1548 		if (question->ThisQInterval != -1)
1549 			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1550 		zd->Addr.type  = mDNSAddrType_IPv4;
1551 		zd->Addr.ip.v4 = (answer->rdlength == 4) ? answer->rdata->u.ipv4 : zerov4Addr;
1552 		// In order to simulate firewalls blocking our outgoing TCP connections, returning immediate ICMP errors or TCP resets,
1553 		// the code below will make us try to connect to loopback, resulting in an immediate "port unreachable" failure.
1554 		// This helps us test to make sure we handle this case gracefully
1555 		// <rdar://problem/5607082> BTMM: mDNSResponder taking 100 percent CPU after upgrading to 10.5.1
1556 #if 0
1557 		zd->Addr.ip.v4.b[0] = 127;
1558 		zd->Addr.ip.v4.b[1] = 0;
1559 		zd->Addr.ip.v4.b[2] = 0;
1560 		zd->Addr.ip.v4.b[3] = 1;
1561 #endif
1562 		// The caller needs to free the memory when done with zone data
1563 		zd->ZoneDataCallback(m, mStatus_NoError, zd);
1564 		}
1565 	}
1566 
1567 // GetZoneData_StartQuery is called from normal client context (lock not held, or client callback)
1568 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype)
1569 	{
1570 	if (qtype == kDNSType_SRV)
1571 		{
1572 		AssignDomainName(&zd->question.qname, ZoneDataSRV(zd));
1573 		AppendDomainName(&zd->question.qname, &zd->ZoneName);
1574 		debugf("lookupDNSPort %##s", zd->question.qname.c);
1575 		}
1576 
1577 	// CancelGetZoneData can get called at any time. We should stop the question if it has not been
1578 	// stopped already. A value of -1 for ThisQInterval indicates that the question is not active
1579 	// yet.
1580 	zd->question.ThisQInterval       = -1;
1581 	zd->question.InterfaceID         = mDNSInterface_Any;
1582 	zd->question.Target              = zeroAddr;
1583 	//zd->question.qname.c[0]        = 0;			// Already set
1584 	zd->question.qtype               = qtype;
1585 	zd->question.qclass              = kDNSClass_IN;
1586 	zd->question.LongLived           = mDNSfalse;
1587 	zd->question.ExpectUnique        = mDNStrue;
1588 	zd->question.ForceMCast          = mDNSfalse;
1589 	zd->question.ReturnIntermed      = mDNStrue;
1590 	zd->question.SuppressUnusable    = mDNSfalse;
1591 	zd->question.SearchListIndex     = 0;
1592 	zd->question.AppendSearchDomains = 0;
1593 	zd->question.RetryWithSearchDomains = mDNSfalse;
1594 	zd->question.TimeoutQuestion     = 0;
1595 	zd->question.WakeOnResolve       = 0;
1596 	zd->question.qnameOrig           = mDNSNULL;
1597 	zd->question.QuestionCallback    = GetZoneData_QuestionCallback;
1598 	zd->question.QuestionContext     = zd;
1599 
1600 	//LogMsg("GetZoneData_StartQuery %##s (%s) %p", zd->question.qname.c, DNSTypeName(zd->question.qtype), zd->question.Private);
1601 	return(mDNS_StartQuery(m, &zd->question));
1602 	}
1603 
1604 // StartGetZoneData is an internal routine (i.e. must be called with the lock already held)
1605 mDNSexport ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *ZoneDataContext)
1606 	{
1607 	DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, name);
1608 	int initialskip = (AuthInfo && AuthInfo->AutoTunnel) ? DomainNameLength(name) - DomainNameLength(&AuthInfo->domain) : 0;
1609 	ZoneData *zd = (ZoneData*)mDNSPlatformMemAllocate(sizeof(ZoneData));
1610 	if (!zd) { LogMsg("ERROR: StartGetZoneData - mDNSPlatformMemAllocate failed"); return mDNSNULL; }
1611 	mDNSPlatformMemZero(zd, sizeof(ZoneData));
1612 	AssignDomainName(&zd->ChildName, name);
1613 	zd->ZoneService      = target;
1614 	zd->CurrentSOA       = (domainname *)(&zd->ChildName.c[initialskip]);
1615 	zd->ZoneName.c[0]    = 0;
1616 	zd->ZoneClass        = 0;
1617 	zd->Host.c[0]        = 0;
1618 	zd->Port             = zeroIPPort;
1619 	zd->Addr             = zeroAddr;
1620 	zd->ZonePrivate      = AuthInfo && AuthInfo->AutoTunnel ? mDNStrue : mDNSfalse;
1621 	zd->ZoneDataCallback = callback;
1622 	zd->ZoneDataContext  = ZoneDataContext;
1623 
1624 	zd->question.QuestionContext = zd;
1625 
1626 	mDNS_DropLockBeforeCallback();		// GetZoneData_StartQuery expects to be called from a normal callback, so we emulate that here
1627 	if (AuthInfo && AuthInfo->AutoTunnel && !mDNSIPPortIsZero(AuthInfo->port))
1628 		{
1629 		LogInfo("StartGetZoneData: Bypassing SOA, SRV query for %##s", AuthInfo->domain.c);
1630 		// We bypass SOA and SRV queries if we know the hostname and port already from the configuration.
1631 		// Today this is only true for AutoTunnel. As we bypass, we need to infer a few things:
1632 		//
1633 		// 1. Zone name is the same as the AuthInfo domain
1634 		// 2. ZoneClass is kDNSClass_IN which should be a safe assumption
1635 		//
1636 		// If we want to make this bypass mechanism work for non-AutoTunnels also, (1) has to hold
1637 		// good. Otherwise, it has to be configured also.
1638 
1639 		AssignDomainName(&zd->ZoneName, &AuthInfo->domain);
1640 		zd->ZoneClass = kDNSClass_IN;
1641 		AssignDomainName(&zd->Host, &AuthInfo->hostname);
1642 		zd->Port = AuthInfo->port;
1643 		AssignDomainName(&zd->question.qname, &zd->Host);
1644 		GetZoneData_StartQuery(m, zd, kDNSType_A);
1645 		}
1646 	else
1647 		{
1648 		if (AuthInfo && AuthInfo->AutoTunnel) LogInfo("StartGetZoneData: Not Bypassing SOA, SRV query for %##s", AuthInfo->domain.c);
1649 		AssignDomainName(&zd->question.qname, zd->CurrentSOA);
1650 		GetZoneData_StartQuery(m, zd, kDNSType_SOA);
1651 		}
1652 	mDNS_ReclaimLockAfterCallback();
1653 
1654 	return zd;
1655 	}
1656 
1657 // Returns if the question is a GetZoneData question. These questions are special in
1658 // that they are created internally while resolving a private query or LLQs.
1659 mDNSexport mDNSBool IsGetZoneDataQuestion(DNSQuestion *q)
1660 	{
1661 	if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNStrue);
1662 	else return(mDNSfalse);
1663 	}
1664 
1665 // GetZoneData queries are a special case -- even if we have a key for them, we don't do them privately,
1666 // because that would result in an infinite loop (i.e. to do a private query we first need to get
1667 // the _dns-query-tls SRV record for the zone, and we can't do *that* privately because to do so
1668 // we'd need to already know the _dns-query-tls SRV record.
1669 // Also, as a general rule, we never do SOA queries privately
1670 mDNSexport DomainAuthInfo *GetAuthInfoForQuestion(mDNS *m, const DNSQuestion *const q)	// Must be called with lock held
1671 	{
1672 	if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNSNULL);
1673 	if (q->qtype            == kDNSType_SOA                ) return(mDNSNULL);
1674 	return(GetAuthInfoForName_internal(m, &q->qname));
1675 	}
1676 
1677 // ***************************************************************************
1678 #if COMPILER_LIKES_PRAGMA_MARK
1679 #pragma mark - host name and interface management
1680 #endif
1681 
1682 mDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr);
1683 mDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr);
1684 mDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time);
1685 
1686 // When this function is called, service record is already deregistered. We just
1687 // have to deregister the PTR and TXT records.
1688 mDNSlocal void UpdateAllServiceRecords(mDNS *const m, AuthRecord *rr, mDNSBool reg)
1689 	{
1690 	AuthRecord *r, *srvRR;
1691 
1692 	if (rr->resrec.rrtype != kDNSType_SRV) { LogMsg("UpdateAllServiceRecords:ERROR!! ResourceRecord not a service record %s", ARDisplayString(m, rr)); return; }
1693 
1694 	if (reg && rr->state == regState_NoTarget) { LogMsg("UpdateAllServiceRecords:ERROR!! SRV record %s in noTarget state during registration", ARDisplayString(m, rr)); return; }
1695 
1696 	LogInfo("UpdateAllServiceRecords: ResourceRecord %s", ARDisplayString(m, rr));
1697 
1698 	for (r = m->ResourceRecords; r; r=r->next)
1699 		{
1700 		if (!AuthRecord_uDNS(r)) continue;
1701 		srvRR = mDNSNULL;
1702 		if (r->resrec.rrtype == kDNSType_PTR)
1703 			srvRR = r->Additional1;
1704 		else if (r->resrec.rrtype == kDNSType_TXT)
1705 			srvRR = r->DependentOn;
1706 		if (srvRR && srvRR->resrec.rrtype != kDNSType_SRV)
1707 			LogMsg("UpdateAllServiceRecords: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1708 		if (srvRR == rr)
1709 			{
1710 			if (!reg)
1711 				{
1712 				LogInfo("UpdateAllServiceRecords: deregistering %s", ARDisplayString(m, r));
1713 				r->SRVChanged = mDNStrue;
1714 				r->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1715 				r->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1716 				r->state = regState_DeregPending;
1717 				}
1718 			else
1719 				{
1720 				// Clearing SRVchanged is a safety measure. If our pevious dereg never
1721 				// came back and we had a target change, we are starting fresh
1722 				r->SRVChanged = mDNSfalse;
1723 				// if it is already registered or in the process of registering, then don't
1724 				// bother re-registering. This happens today for non-BTMM domains where the
1725 				// TXT and PTR get registered before SRV records because of the delay in
1726 				// getting the port mapping. There is no point in re-registering the TXT
1727 				// and PTR records.
1728 				if ((r->state == regState_Registered) ||
1729 				    (r->state == regState_Pending && r->nta && !mDNSIPv4AddressIsZero(r->nta->Addr.ip.v4)))
1730 					LogInfo("UpdateAllServiceRecords: not registering %s, state %d", ARDisplayString(m, r), r->state);
1731 				else
1732 					{
1733 					LogInfo("UpdateAllServiceRecords: registering %s, state %d", ARDisplayString(m, r), r->state);
1734 					ActivateUnicastRegistration(m, r);
1735 					}
1736 				}
1737 			}
1738 		}
1739 	}
1740 
1741 // Called in normal client context (lock not held)
1742 // Currently only supports SRV records for nat mapping
1743 mDNSlocal void CompleteRecordNatMap(mDNS *m, NATTraversalInfo *n)
1744 	{
1745 	const domainname *target;
1746 	domainname *srvt;
1747 	AuthRecord *rr = (AuthRecord *)n->clientContext;
1748 	debugf("SRVNatMap complete %.4a IntPort %u ExternalPort %u NATLease %u", &n->ExternalAddress, mDNSVal16(n->IntPort), mDNSVal16(n->ExternalPort), n->NATLease);
1749 
1750 	if (!rr) { LogMsg("CompleteRecordNatMap called with unknown AuthRecord object"); return; }
1751 	if (!n->NATLease) { LogMsg("CompleteRecordNatMap No NATLease for %s", ARDisplayString(m, rr)); return; }
1752 
1753 	if (rr->resrec.rrtype != kDNSType_SRV) {LogMsg("CompleteRecordNatMap: Not a service record %s", ARDisplayString(m, rr)); return; }
1754 
1755 	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) { LogInfo("CompleteRecordNatMap called for %s, Service deregistering", ARDisplayString(m, rr)); return; }
1756 
1757 	if (rr->state == regState_DeregPending) { LogInfo("CompleteRecordNatMap called for %s, record in DeregPending", ARDisplayString(m, rr)); return; }
1758 
1759 	// As we free the zone info after registering/deregistering with the server (See hndlRecordUpdateReply),
1760 	// we need to restart the get zone data and nat mapping request to get the latest mapping result as we can't handle it
1761 	// at this moment. Restart from the beginning.
1762 	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
1763 		{
1764 		LogInfo("CompleteRecordNatMap called for %s but no zone information!", ARDisplayString(m, rr));
1765 		// We need to clear out the NATinfo state so that it will result in re-acquiring the mapping
1766 		// and hence this callback called again.
1767 		if (rr->NATinfo.clientContext)
1768 			{
1769 			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1770 			rr->NATinfo.clientContext = mDNSNULL;
1771 			}
1772 		rr->state = regState_Pending;
1773 		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1774 		rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1775 		return;
1776 		}
1777 
1778 	mDNS_Lock(m);
1779 	// Reevaluate the target always as Target could have changed while
1780 	// we were getting the port mapping (See UpdateOneSRVRecord)
1781 	target = GetServiceTarget(m, rr);
1782 	srvt = GetRRDomainNameTarget(&rr->resrec);
1783 	if (!target || target->c[0] == 0 || mDNSIPPortIsZero(n->ExternalPort))
1784 		{
1785 		if (target && target->c[0])
1786 			LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
1787 		else
1788 			LogInfo("CompleteRecordNatMap - no target for %##s, ExternalPort %d", rr->resrec.name->c, mDNSVal16(n->ExternalPort));
1789 		if (srvt) srvt->c[0] = 0;
1790 		rr->state = regState_NoTarget;
1791 		rr->resrec.rdlength = rr->resrec.rdestimate = 0;
1792 		mDNS_Unlock(m);
1793 		UpdateAllServiceRecords(m, rr, mDNSfalse);
1794 		return;
1795 		}
1796 	LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
1797 	// This function might get called multiple times during a network transition event. Previosuly, we could
1798 	// have put the SRV record in NoTarget state above and deregistered all the other records. When this
1799 	// function gets called again with a non-zero ExternalPort, we need to set the target and register the
1800 	// other records again.
1801 	if (srvt && !SameDomainName(srvt, target))
1802 		{
1803 		AssignDomainName(srvt, target);
1804 		SetNewRData(&rr->resrec, mDNSNULL, 0);		// Update rdlength, rdestimate, rdatahash
1805 		}
1806 
1807 	// SRVChanged is set when when the target of the SRV record changes (See UpdateOneSRVRecord).
1808 	// As a result of the target change, we might register just that SRV Record if it was
1809 	// previously registered and we have a new target OR deregister SRV (and the associated
1810 	// PTR/TXT records) if we don't have a target anymore. When we get a response from the server,
1811 	// SRVChanged state tells that we registered/deregistered because of a target change
1812 	// and hence handle accordingly e.g., if we deregistered, put the records in NoTarget state OR
1813 	// if we registered then put it in Registered state.
1814 	//
1815 	// Here, we are registering all the records again from the beginning. Treat this as first time
1816 	// registration rather than a temporary target change.
1817 	rr->SRVChanged = mDNSfalse;
1818 
1819 	// We want IsRecordMergeable to check whether it is a record whose update can be
1820 	// sent with others. We set the time before we call IsRecordMergeable, so that
1821 	// it does not fail this record based on time. We are interested in other checks
1822 	// at this time
1823 	rr->state = regState_Pending;
1824 	rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1825 	rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1826 	if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
1827 		// Delay the record registration by MERGE_DELAY_TIME so that we can merge them
1828 		// into one update
1829 		rr->LastAPTime += MERGE_DELAY_TIME;
1830 	mDNS_Unlock(m);
1831 	// We call this always even though it may not be necessary always e.g., normal registration
1832 	// process where TXT and PTR gets registered followed by the SRV record after it gets
1833 	// the port mapping. In that case, UpdateAllServiceRecords handles the optimization. The
1834 	// update of TXT and PTR record is required if we entered noTargetState before as explained
1835 	// above.
1836 	UpdateAllServiceRecords(m, rr, mDNStrue);
1837 	}
1838 
1839 mDNSlocal void StartRecordNatMap(mDNS *m, AuthRecord *rr)
1840 	{
1841 	const mDNSu8 *p;
1842 	mDNSu8 protocol;
1843 
1844 	if (rr->resrec.rrtype != kDNSType_SRV)
1845 		{
1846 		LogInfo("StartRecordNatMap: Resource Record %##s type %d, not supported", rr->resrec.name->c, rr->resrec.rrtype);
1847 		return;
1848 		}
1849 	p = rr->resrec.name->c;
1850 	//Assume <Service Instance>.<App Protocol>.<Transport protocol>.<Name>
1851 	// Skip the first two labels to get to the transport protocol
1852 	if (p[0]) p += 1 + p[0];
1853 	if (p[0]) p += 1 + p[0];
1854 	if      (SameDomainLabel(p, (mDNSu8 *)"\x4" "_tcp")) protocol = NATOp_MapTCP;
1855 	else if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_udp")) protocol = NATOp_MapUDP;
1856 	else { LogMsg("StartRecordNatMap: could not determine transport protocol of service %##s", rr->resrec.name->c); return; }
1857 
1858 	//LogMsg("StartRecordNatMap: clientContext %p IntPort %d srv.port %d %s",
1859 	//	rr->NATinfo.clientContext, mDNSVal16(rr->NATinfo.IntPort), mDNSVal16(rr->resrec.rdata->u.srv.port), ARDisplayString(m, rr));
1860 	if (rr->NATinfo.clientContext) mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1861 	rr->NATinfo.Protocol       = protocol;
1862 
1863 	// Shouldn't be trying to set IntPort here --
1864 	// BuildUpdateMessage overwrites srs->RR_SRV.resrec.rdata->u.srv.port with external (mapped) port number
1865 	rr->NATinfo.IntPort        = rr->resrec.rdata->u.srv.port;
1866 	rr->NATinfo.RequestedPort  = rr->resrec.rdata->u.srv.port;
1867 	rr->NATinfo.NATLease       = 0;		// Request default lease
1868 	rr->NATinfo.clientCallback = CompleteRecordNatMap;
1869 	rr->NATinfo.clientContext  = rr;
1870 	mDNS_StartNATOperation_internal(m, &rr->NATinfo);
1871 	}
1872 
1873 // Unlink an Auth Record from the m->ResourceRecords list.
1874 // When a resource record enters regState_NoTarget initially, mDNS_Register_internal
1875 // does not initialize completely e.g., it cannot check for duplicates etc. The resource
1876 // record is temporarily left in the ResourceRecords list so that we can initialize later
1877 // when the target is resolvable. Similarly, when host name changes, we enter regState_NoTarget
1878 // and we do the same.
1879 
1880 // This UnlinkResourceRecord routine is very worrying. It bypasses all the normal cleanup performed
1881 // by mDNS_Deregister_internal and just unceremoniously cuts the record from the active list.
1882 // This is why re-regsitering this record was producing syslog messages like this:
1883 // "Error! Tried to add a NAT traversal that's already in the active list"
1884 // Right now UnlinkResourceRecord is fortunately only called by RegisterAllServiceRecords,
1885 // which then immediately calls mDNS_Register_internal to re-register the record, which probably
1886 // masked more serious problems. Any other use of UnlinkResourceRecord is likely to lead to crashes.
1887 // For now we'll workaround that specific problem by explicitly calling mDNS_StopNATOperation_internal,
1888 // but long-term we should either stop cancelling the record registration and then re-registering it,
1889 // or if we really do need to do this for some reason it should be done via the usual
1890 // mDNS_Deregister_internal path instead of just cutting the record from the list.
1891 
1892 mDNSlocal mStatus UnlinkResourceRecord(mDNS *const m, AuthRecord *const rr)
1893 	{
1894 	AuthRecord **list = &m->ResourceRecords;
1895 	while (*list && *list != rr) list = &(*list)->next;
1896 	if (*list)
1897 		{
1898 		*list = rr->next;
1899 		rr->next = mDNSNULL;
1900 
1901 		// Temporary workaround to cancel any active NAT mapping operation
1902 		if (rr->NATinfo.clientContext)
1903 			{
1904 			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1905 			rr->NATinfo.clientContext = mDNSNULL;
1906 			if (rr->resrec.rrtype == kDNSType_SRV) rr->resrec.rdata->u.srv.port = rr->NATinfo.IntPort;
1907 			}
1908 
1909 		return(mStatus_NoError);
1910 		}
1911 	LogMsg("UnlinkResourceRecord:ERROR!! - no such active record %##s", rr->resrec.name->c);
1912 	return(mStatus_NoSuchRecord);
1913 	}
1914 
1915 // We need to go through mDNS_Register again as we did not complete the
1916 // full initialization last time e.g., duplicate checks.
1917 // After we register, we will be in regState_GetZoneData.
1918 mDNSlocal void RegisterAllServiceRecords(mDNS *const m, AuthRecord *rr)
1919 	{
1920 	LogInfo("RegisterAllServiceRecords: Service Record %##s", rr->resrec.name->c);
1921 	// First Register the service record, we do this differently from other records because
1922 	// when it entered NoTarget state, it did not go through complete initialization
1923 	rr->SRVChanged = mDNSfalse;
1924 	UnlinkResourceRecord(m, rr);
1925 	mDNS_Register_internal(m, rr);
1926 	// Register the other records
1927 	UpdateAllServiceRecords(m, rr, mDNStrue);
1928 	}
1929 
1930 // Called with lock held
1931 mDNSlocal void UpdateOneSRVRecord(mDNS *m, AuthRecord *rr)
1932 	{
1933 	// Target change if:
1934 	// We have a target and were previously waiting for one, or
1935 	// We had a target and no longer do, or
1936 	// The target has changed
1937 
1938 	domainname *curtarget = &rr->resrec.rdata->u.srv.target;
1939 	const domainname *const nt = GetServiceTarget(m, rr);
1940 	const domainname *const newtarget = nt ? nt : (domainname*)"";
1941 	mDNSBool TargetChanged = (newtarget->c[0] && rr->state == regState_NoTarget) || !SameDomainName(curtarget, newtarget);
1942 	mDNSBool HaveZoneData  = rr->nta && !mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4);
1943 
1944 	// Nat state change if:
1945 	// We were behind a NAT, and now we are behind a new NAT, or
1946 	// We're not behind a NAT but our port was previously mapped to a different external port
1947 	// We were not behind a NAT and now we are
1948 
1949 	mDNSIPPort port        = rr->resrec.rdata->u.srv.port;
1950 	mDNSBool NowNeedNATMAP = (rr->AutoTarget == Target_AutoHostAndNATMAP && !mDNSIPPortIsZero(port) && mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && rr->nta && !mDNSAddrIsRFC1918(&rr->nta->Addr));
1951 	mDNSBool WereBehindNAT = (rr->NATinfo.clientContext != mDNSNULL);
1952 	mDNSBool PortWasMapped = (rr->NATinfo.clientContext && !mDNSSameIPPort(rr->NATinfo.RequestedPort, port));		// I think this is always false -- SC Sept 07
1953 	mDNSBool NATChanged    = (!WereBehindNAT && NowNeedNATMAP) || (!NowNeedNATMAP && PortWasMapped);
1954 
1955 	(void)HaveZoneData; //unused
1956 
1957 	LogInfo("UpdateOneSRVRecord: Resource Record %s TargetChanged %d, NewTarget %##s", ARDisplayString(m, rr), TargetChanged, nt->c);
1958 
1959 	debugf("UpdateOneSRVRecord: %##s newtarget %##s TargetChanged %d HaveZoneData %d port %d NowNeedNATMAP %d WereBehindNAT %d PortWasMapped %d NATChanged %d",
1960 		rr->resrec.name->c, newtarget,
1961 		TargetChanged, HaveZoneData, mDNSVal16(port), NowNeedNATMAP, WereBehindNAT, PortWasMapped, NATChanged);
1962 
1963 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
1964 		LogMsg("UpdateOneSRVRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
1965 
1966 	if (!TargetChanged && !NATChanged) return;
1967 
1968 	// If we are deregistering the record, then ignore any NAT/Target change.
1969 	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1970 		{
1971 		LogInfo("UpdateOneSRVRecord: Deregistering record, Ignoring TargetChanged %d, NATChanged %d for %##s, state %d", TargetChanged, NATChanged,
1972 			rr->resrec.name->c, rr->state);
1973 		return;
1974 		}
1975 
1976 	if (newtarget)
1977 		LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, newtarget %##s", TargetChanged, NATChanged, rr->resrec.name->c, rr->state, newtarget->c);
1978 	else
1979 		LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, null newtarget", TargetChanged, NATChanged, rr->resrec.name->c, rr->state);
1980 	switch(rr->state)
1981 		{
1982 		case regState_NATMap:
1983 			// In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
1984 			// or is in the process of, or has already been, deregistered. This assumes that whenever we transition out
1985 			// of this state, we need to look at the target again.
1986 			return;
1987 
1988 		case regState_UpdatePending:
1989 			// We are getting a Target change/NAT change while the SRV record is being updated ?
1990 			// let us not do anything for now.
1991 			return;
1992 
1993 		case regState_NATError:
1994 			if (!NATChanged) return;
1995 			// if nat changed, register if we have a target (below)
1996 
1997 		case regState_NoTarget:
1998 			if (!newtarget->c[0])
1999 				{
2000 				LogInfo("UpdateOneSRVRecord: No target yet for Resource Record %s", ARDisplayString(m, rr));
2001 				return;
2002 				}
2003 			RegisterAllServiceRecords(m , rr);
2004 			return;
2005 		case regState_DeregPending:
2006 			// We are in DeregPending either because the service was deregistered from above or we handled
2007 			// a NAT/Target change before and sent the deregistration below. There are a few race conditions
2008 			// possible
2009 			//
2010 			// 1. We are handling a second NAT/Target change while the first dereg is in progress. It is possible
2011 			//    that first dereg never made it through because there was no network connectivity e.g., disconnecting
2012 			//    from network triggers this function due to a target change and later connecting to the network
2013 			//    retriggers this function but the deregistration never made it through yet. Just fall through.
2014 			//    If there is a target register otherwise deregister.
2015 			//
2016 			// 2. While we sent the dereg during a previous NAT/Target change, uDNS_DeregisterRecord gets
2017 			//    called as part of service deregistration. When the response comes back, we call
2018 			//    CompleteDeregistration rather than handle NAT/Target change because the record is in
2019 			//    kDNSRecordTypeDeregistering state.
2020 			//
2021 			// 3. If the upper layer deregisters the service, we check for kDNSRecordTypeDeregistering both
2022 			//    here in this function to avoid handling NAT/Target change and in hndlRecordUpdateReply to call
2023 			//    CompleteDeregistration instead of handling NAT/Target change. Hence, we are not concerned
2024 			//    about that case here.
2025 			//
2026 			// We just handle case (1) by falling through
2027 		case regState_Pending:
2028 		case regState_Refresh:
2029 		case regState_Registered:
2030 			// target or nat changed.  deregister service.  upon completion, we'll look for a new target
2031 			rr->SRVChanged = mDNStrue;
2032 			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
2033 			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
2034 			if (newtarget->c[0])
2035 				{
2036 				LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s, registering with new target %##s",
2037 					rr->resrec.name->c, newtarget->c);
2038 				rr->state = regState_Pending;
2039 				}
2040 			else
2041 				{
2042 				LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s de-registering", rr->resrec.name->c);
2043 				rr->state = regState_DeregPending;
2044 				UpdateAllServiceRecords(m, rr, mDNSfalse);
2045 				}
2046 			return;
2047 		case regState_Unregistered:
2048 		default: LogMsg("UpdateOneSRVRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
2049 		}
2050 	}
2051 
2052 mDNSexport void UpdateAllSRVRecords(mDNS *m)
2053 	{
2054 	m->NextSRVUpdate = 0;
2055 	LogInfo("UpdateAllSRVRecords %d", m->SleepState);
2056 
2057 	if (m->CurrentRecord)
2058 		LogMsg("UpdateAllSRVRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2059 	m->CurrentRecord = m->ResourceRecords;
2060 	while (m->CurrentRecord)
2061 		{
2062 		AuthRecord *rptr = m->CurrentRecord;
2063 		m->CurrentRecord = m->CurrentRecord->next;
2064 		if (AuthRecord_uDNS(rptr) && rptr->resrec.rrtype == kDNSType_SRV)
2065 			UpdateOneSRVRecord(m, rptr);
2066 		}
2067 	}
2068 
2069 // Forward reference: AdvertiseHostname references HostnameCallback, and HostnameCallback calls AdvertiseHostname
2070 mDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
2071 
2072 // Called in normal client context (lock not held)
2073 mDNSlocal void hostnameGetPublicAddressCallback(mDNS *m, NATTraversalInfo *n)
2074 	{
2075 	HostnameInfo *h = (HostnameInfo *)n->clientContext;
2076 
2077 	if (!h) { LogMsg("RegisterHostnameRecord: registration cancelled"); return; }
2078 
2079 	if (!n->Result)
2080 		{
2081 		if (mDNSIPv4AddressIsZero(n->ExternalAddress) || mDNSv4AddrIsRFC1918(&n->ExternalAddress)) return;
2082 
2083 		if (h->arv4.resrec.RecordType)
2084 			{
2085 			if (mDNSSameIPv4Address(h->arv4.resrec.rdata->u.ipv4, n->ExternalAddress)) return;	// If address unchanged, do nothing
2086 			LogInfo("Updating hostname %p %##s IPv4 from %.4a to %.4a (NAT gateway's external address)",n,
2087 				h->arv4.resrec.name->c, &h->arv4.resrec.rdata->u.ipv4, &n->ExternalAddress);
2088 			mDNS_Deregister(m, &h->arv4);	// mStatus_MemFree callback will re-register with new address
2089 			}
2090 		else
2091 			{
2092 			LogInfo("Advertising hostname %##s IPv4 %.4a (NAT gateway's external address)", h->arv4.resrec.name->c, &n->ExternalAddress);
2093 			h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
2094 			h->arv4.resrec.rdata->u.ipv4 = n->ExternalAddress;
2095 			mDNS_Register(m, &h->arv4);
2096 			}
2097 		}
2098 	}
2099 
2100 // register record or begin NAT traversal
2101 mDNSlocal void AdvertiseHostname(mDNS *m, HostnameInfo *h)
2102 	{
2103 	if (!mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4) && h->arv4.resrec.RecordType == kDNSRecordTypeUnregistered)
2104 		{
2105 		mDNS_SetupResourceRecord(&h->arv4, mDNSNULL, mDNSInterface_Any, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnregistered, AuthRecordAny, HostnameCallback, h);
2106 		AssignDomainName(&h->arv4.namestorage, &h->fqdn);
2107 		h->arv4.resrec.rdata->u.ipv4 = m->AdvertisedV4.ip.v4;
2108 		h->arv4.state = regState_Unregistered;
2109 		if (mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4))
2110 			{
2111 			// If we already have a NAT query active, stop it and restart it to make sure we get another callback
2112 			if (h->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &h->natinfo);
2113 			h->natinfo.Protocol         = 0;
2114 			h->natinfo.IntPort          = zeroIPPort;
2115 			h->natinfo.RequestedPort    = zeroIPPort;
2116 			h->natinfo.NATLease         = 0;
2117 			h->natinfo.clientCallback   = hostnameGetPublicAddressCallback;
2118 			h->natinfo.clientContext    = h;
2119 			mDNS_StartNATOperation_internal(m, &h->natinfo);
2120 			}
2121 		else
2122 			{
2123 			LogInfo("Advertising hostname %##s IPv4 %.4a", h->arv4.resrec.name->c, &m->AdvertisedV4.ip.v4);
2124 			h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
2125 			mDNS_Register_internal(m, &h->arv4);
2126 			}
2127 		}
2128 
2129 	if (!mDNSIPv6AddressIsZero(m->AdvertisedV6.ip.v6) && h->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
2130 		{
2131 		mDNS_SetupResourceRecord(&h->arv6, mDNSNULL, mDNSInterface_Any, kDNSType_AAAA, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, HostnameCallback, h);
2132 		AssignDomainName(&h->arv6.namestorage, &h->fqdn);
2133 		h->arv6.resrec.rdata->u.ipv6 = m->AdvertisedV6.ip.v6;
2134 		h->arv6.state = regState_Unregistered;
2135 		LogInfo("Advertising hostname %##s IPv6 %.16a", h->arv6.resrec.name->c, &m->AdvertisedV6.ip.v6);
2136 		mDNS_Register_internal(m, &h->arv6);
2137 		}
2138 	}
2139 
2140 mDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
2141 	{
2142 	HostnameInfo *hi = (HostnameInfo *)rr->RecordContext;
2143 
2144 	if (result == mStatus_MemFree)
2145 		{
2146 		if (hi)
2147 			{
2148 			// If we're still in the Hostnames list, update to new address
2149 			HostnameInfo *i;
2150 			LogInfo("HostnameCallback: Got mStatus_MemFree for %p %p %s", hi, rr, ARDisplayString(m, rr));
2151 			for (i = m->Hostnames; i; i = i->next)
2152 				if (rr == &i->arv4 || rr == &i->arv6)
2153 					{ mDNS_Lock(m); AdvertiseHostname(m, i); mDNS_Unlock(m); return; }
2154 
2155 			// Else, we're not still in the Hostnames list, so free the memory
2156 			if (hi->arv4.resrec.RecordType == kDNSRecordTypeUnregistered &&
2157 				hi->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
2158 				{
2159 				if (hi->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &hi->natinfo);
2160 				hi->natinfo.clientContext = mDNSNULL;
2161 				mDNSPlatformMemFree(hi);	// free hi when both v4 and v6 AuthRecs deallocated
2162 				}
2163 			}
2164 		return;
2165 		}
2166 
2167 	if (result)
2168 		{
2169 		// don't unlink or free - we can retry when we get a new address/router
2170 		if (rr->resrec.rrtype == kDNSType_A)
2171 			LogMsg("HostnameCallback: Error %d for registration of %##s IP %.4a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
2172 		else
2173 			LogMsg("HostnameCallback: Error %d for registration of %##s IP %.16a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
2174 		if (!hi) { mDNSPlatformMemFree(rr); return; }
2175 		if (rr->state != regState_Unregistered) LogMsg("Error: HostnameCallback invoked with error code for record not in regState_Unregistered!");
2176 
2177 		if (hi->arv4.state == regState_Unregistered &&
2178 			hi->arv6.state == regState_Unregistered)
2179 			{
2180 			// only deliver status if both v4 and v6 fail
2181 			rr->RecordContext = (void *)hi->StatusContext;
2182 			if (hi->StatusCallback)
2183 				hi->StatusCallback(m, rr, result); // client may NOT make API calls here
2184 			rr->RecordContext = (void *)hi;
2185 			}
2186 		return;
2187 		}
2188 
2189 	// register any pending services that require a target
2190 	mDNS_Lock(m);
2191 	m->NextSRVUpdate = NonZeroTime(m->timenow);
2192 	mDNS_Unlock(m);
2193 
2194 	// Deliver success to client
2195 	if (!hi) { LogMsg("HostnameCallback invoked with orphaned address record"); return; }
2196 	if (rr->resrec.rrtype == kDNSType_A)
2197 		LogInfo("Registered hostname %##s IP %.4a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
2198 	else
2199 		LogInfo("Registered hostname %##s IP %.16a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
2200 
2201 	rr->RecordContext = (void *)hi->StatusContext;
2202 	if (hi->StatusCallback)
2203 		hi->StatusCallback(m, rr, result); // client may NOT make API calls here
2204 	rr->RecordContext = (void *)hi;
2205 	}
2206 
2207 mDNSlocal void FoundStaticHostname(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2208 	{
2209 	const domainname *pktname = &answer->rdata->u.name;
2210 	domainname *storedname = &m->StaticHostname;
2211 	HostnameInfo *h = m->Hostnames;
2212 
2213 	(void)question;
2214 
2215 	if (answer->rdlength != 0)
2216 		LogInfo("FoundStaticHostname: question %##s -> answer %##s (%s)", question->qname.c, answer->rdata->u.name.c, AddRecord ? "ADD" : "RMV");
2217 	else
2218 		LogInfo("FoundStaticHostname: question %##s -> answer NULL (%s)", question->qname.c, AddRecord ? "ADD" : "RMV");
2219 
2220 	if (AddRecord && answer->rdlength != 0 && !SameDomainName(pktname, storedname))
2221 		{
2222 		AssignDomainName(storedname, pktname);
2223 		while (h)
2224 			{
2225 			if (h->arv4.state == regState_Pending || h->arv4.state == regState_NATMap || h->arv6.state == regState_Pending)
2226 				{
2227 				// if we're in the process of registering a dynamic hostname, delay SRV update so we don't have to reregister services if the dynamic name succeeds
2228 				m->NextSRVUpdate = NonZeroTime(m->timenow + 5 * mDNSPlatformOneSecond);
2229 				debugf("FoundStaticHostname: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
2230 				return;
2231 				}
2232 			h = h->next;
2233 			}
2234 		mDNS_Lock(m);
2235 		m->NextSRVUpdate = NonZeroTime(m->timenow);
2236 		mDNS_Unlock(m);
2237 		}
2238 	else if (!AddRecord && SameDomainName(pktname, storedname))
2239 		{
2240 		mDNS_Lock(m);
2241 		storedname->c[0] = 0;
2242 		m->NextSRVUpdate = NonZeroTime(m->timenow);
2243 		mDNS_Unlock(m);
2244 		}
2245 	}
2246 
2247 // Called with lock held
2248 mDNSlocal void GetStaticHostname(mDNS *m)
2249 	{
2250 	char buf[MAX_REVERSE_MAPPING_NAME_V4];
2251 	DNSQuestion *q = &m->ReverseMap;
2252 	mDNSu8 *ip = m->AdvertisedV4.ip.v4.b;
2253 	mStatus err;
2254 
2255 	if (m->ReverseMap.ThisQInterval != -1) return; // already running
2256 	if (mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4)) return;
2257 
2258 	mDNSPlatformMemZero(q, sizeof(*q));
2259 	// Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
2260 	mDNS_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa.", ip[3], ip[2], ip[1], ip[0]);
2261 	if (!MakeDomainNameFromDNSNameString(&q->qname, buf)) { LogMsg("Error: GetStaticHostname - bad name %s", buf); return; }
2262 
2263 	q->InterfaceID      = mDNSInterface_Any;
2264 	q->Target           = zeroAddr;
2265 	q->qtype            = kDNSType_PTR;
2266 	q->qclass           = kDNSClass_IN;
2267 	q->LongLived        = mDNSfalse;
2268 	q->ExpectUnique     = mDNSfalse;
2269 	q->ForceMCast       = mDNSfalse;
2270 	q->ReturnIntermed   = mDNStrue;
2271 	q->SuppressUnusable = mDNSfalse;
2272 	q->SearchListIndex  = 0;
2273 	q->AppendSearchDomains = 0;
2274 	q->RetryWithSearchDomains = mDNSfalse;
2275 	q->TimeoutQuestion  = 0;
2276 	q->WakeOnResolve    = 0;
2277 	q->qnameOrig        = mDNSNULL;
2278 	q->QuestionCallback = FoundStaticHostname;
2279 	q->QuestionContext  = mDNSNULL;
2280 
2281 	LogInfo("GetStaticHostname: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2282 	err = mDNS_StartQuery_internal(m, q);
2283 	if (err) LogMsg("Error: GetStaticHostname - StartQuery returned error %d", err);
2284 	}
2285 
2286 mDNSexport void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext)
2287    {
2288 	HostnameInfo **ptr = &m->Hostnames;
2289 
2290 	LogInfo("mDNS_AddDynDNSHostName %##s", fqdn);
2291 
2292 	while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
2293 	if (*ptr) { LogMsg("DynDNSHostName %##s already in list", fqdn->c); return; }
2294 
2295 	// allocate and format new address record
2296 	*ptr = mDNSPlatformMemAllocate(sizeof(**ptr));
2297 	if (!*ptr) { LogMsg("ERROR: mDNS_AddDynDNSHostName - malloc"); return; }
2298 
2299 	mDNSPlatformMemZero(*ptr, sizeof(**ptr));
2300 	AssignDomainName(&(*ptr)->fqdn, fqdn);
2301 	(*ptr)->arv4.state     = regState_Unregistered;
2302 	(*ptr)->arv6.state     = regState_Unregistered;
2303 	(*ptr)->StatusCallback = StatusCallback;
2304 	(*ptr)->StatusContext  = StatusContext;
2305 
2306 	AdvertiseHostname(m, *ptr);
2307 	}
2308 
2309 mDNSexport void mDNS_RemoveDynDNSHostName(mDNS *m, const domainname *fqdn)
2310 	{
2311 	HostnameInfo **ptr = &m->Hostnames;
2312 
2313 	LogInfo("mDNS_RemoveDynDNSHostName %##s", fqdn);
2314 
2315 	while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
2316 	if (!*ptr) LogMsg("mDNS_RemoveDynDNSHostName: no such domainname %##s", fqdn->c);
2317 	else
2318 		{
2319 		HostnameInfo *hi = *ptr;
2320 		// We do it this way because, if we have no active v6 record, the "mDNS_Deregister_internal(m, &hi->arv4);"
2321 		// below could free the memory, and we have to make sure we don't touch hi fields after that.
2322 		mDNSBool f4 = hi->arv4.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv4.state != regState_Unregistered;
2323 		mDNSBool f6 = hi->arv6.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv6.state != regState_Unregistered;
2324 		if (f4) LogInfo("mDNS_RemoveDynDNSHostName removing v4 %##s", fqdn);
2325 		if (f6) LogInfo("mDNS_RemoveDynDNSHostName removing v6 %##s", fqdn);
2326 		*ptr = (*ptr)->next; // unlink
2327 		if (f4) mDNS_Deregister_internal(m, &hi->arv4, mDNS_Dereg_normal);
2328 		if (f6) mDNS_Deregister_internal(m, &hi->arv6, mDNS_Dereg_normal);
2329 		// When both deregistrations complete we'll free the memory in the mStatus_MemFree callback
2330 		}
2331 	if (!m->mDNS_busy) LogMsg("mDNS_RemoveDynDNSHostName: ERROR: Lock not held");
2332 	m->NextSRVUpdate = NonZeroTime(m->timenow);
2333 	}
2334 
2335 // Currently called without holding the lock
2336 // Maybe we should change that?
2337 mDNSexport void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *v4addr, const mDNSAddr *v6addr, const mDNSAddr *router)
2338 	{
2339 	mDNSBool v4Changed, v6Changed, RouterChanged;
2340 
2341 	if (m->mDNS_busy != m->mDNS_reentrancy)
2342 		LogMsg("mDNS_SetPrimaryInterfaceInfo: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
2343 
2344 	if (v4addr && v4addr->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo v4 address - incorrect type.  Discarding. %#a", v4addr); return; }
2345 	if (v6addr && v6addr->type != mDNSAddrType_IPv6) { LogMsg("mDNS_SetPrimaryInterfaceInfo v6 address - incorrect type.  Discarding. %#a", v6addr); return; }
2346 	if (router && router->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-v4 router.  Discarding. %#a",        router); return; }
2347 
2348 	mDNS_Lock(m);
2349 
2350 	v4Changed     = !mDNSSameIPv4Address(m->AdvertisedV4.ip.v4, v4addr ? v4addr->ip.v4 : zerov4Addr);
2351 	v6Changed     = !mDNSSameIPv6Address(m->AdvertisedV6.ip.v6, v6addr ? v6addr->ip.v6 : zerov6Addr);
2352 	RouterChanged = !mDNSSameIPv4Address(m->Router.ip.v4,       router ? router->ip.v4 : zerov4Addr);
2353 
2354 	if (v4addr && (v4Changed || RouterChanged))
2355 		debugf("mDNS_SetPrimaryInterfaceInfo: address changed from %#a to %#a", &m->AdvertisedV4, v4addr);
2356 
2357 	if (v4addr) m->AdvertisedV4 = *v4addr; else m->AdvertisedV4.ip.v4 = zerov4Addr;
2358 	if (v6addr) m->AdvertisedV6 = *v6addr; else m->AdvertisedV6.ip.v6 = zerov6Addr;
2359 	if (router) m->Router       = *router; else m->Router      .ip.v4 = zerov4Addr;
2360 	// setting router to zero indicates that nat mappings must be reestablished when router is reset
2361 
2362 	if (v4Changed || RouterChanged || v6Changed)
2363 		{
2364 		HostnameInfo *i;
2365 		LogInfo("mDNS_SetPrimaryInterfaceInfo: %s%s%s%#a %#a %#a",
2366 			v4Changed     ? "v4Changed "     : "",
2367 			RouterChanged ? "RouterChanged " : "",
2368 			v6Changed     ? "v6Changed "     : "", v4addr, v6addr, router);
2369 
2370 		for (i = m->Hostnames; i; i = i->next)
2371 			{
2372 			LogInfo("mDNS_SetPrimaryInterfaceInfo updating host name registrations for %##s", i->fqdn.c);
2373 
2374 			if (i->arv4.resrec.RecordType > kDNSRecordTypeDeregistering &&
2375 				!mDNSSameIPv4Address(i->arv4.resrec.rdata->u.ipv4, m->AdvertisedV4.ip.v4))
2376 				{
2377 				LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv4));
2378 				mDNS_Deregister_internal(m, &i->arv4, mDNS_Dereg_normal);
2379 				}
2380 
2381 			if (i->arv6.resrec.RecordType > kDNSRecordTypeDeregistering &&
2382 				!mDNSSameIPv6Address(i->arv6.resrec.rdata->u.ipv6, m->AdvertisedV6.ip.v6))
2383 				{
2384 				LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv6));
2385 				mDNS_Deregister_internal(m, &i->arv6, mDNS_Dereg_normal);
2386 				}
2387 
2388 			// AdvertiseHostname will only register new address records.
2389 			// For records still in the process of deregistering it will ignore them, and let the mStatus_MemFree callback handle them.
2390 			AdvertiseHostname(m, i);
2391 			}
2392 
2393 		if (v4Changed || RouterChanged)
2394 			{
2395 			// If we have a non-zero IPv4 address, we should try immediately to see if we have a NAT gateway
2396 			// If we have no IPv4 address, we don't want to be in quite such a hurry to report failures to our clients
2397 			// <rdar://problem/6935929> Sleeping server sometimes briefly disappears over Back to My Mac after it wakes up
2398 			m->ExternalAddress      = zerov4Addr;
2399 			m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
2400 			m->retryGetAddr         = m->timenow + (v4addr ? 0 : mDNSPlatformOneSecond * 5);
2401 			m->NextScheduledNATOp   = m->timenow;
2402 			m->LastNATMapResultCode = NATErr_None;
2403 #ifdef _LEGACY_NAT_TRAVERSAL_
2404 			LNT_ClearState(m);
2405 #endif // _LEGACY_NAT_TRAVERSAL_
2406 			LogInfo("mDNS_SetPrimaryInterfaceInfo:%s%s: retryGetAddr in %d %d",
2407 				v4Changed     ? " v4Changed"     : "",
2408 				RouterChanged ? " RouterChanged" : "",
2409 				m->retryGetAddr - m->timenow, m->timenow);
2410 			}
2411 
2412 		if (m->ReverseMap.ThisQInterval != -1) mDNS_StopQuery_internal(m, &m->ReverseMap);
2413 		m->StaticHostname.c[0] = 0;
2414 
2415 		m->NextSRVUpdate = NonZeroTime(m->timenow);
2416 
2417 #if APPLE_OSX_mDNSResponder
2418 		if (RouterChanged)	uuid_generate(m->asl_uuid);
2419 		UpdateAutoTunnelDomainStatuses(m);
2420 #endif
2421 		}
2422 
2423 	mDNS_Unlock(m);
2424 	}
2425 
2426 // ***************************************************************************
2427 #if COMPILER_LIKES_PRAGMA_MARK
2428 #pragma mark - Incoming Message Processing
2429 #endif
2430 
2431 mDNSlocal mStatus ParseTSIGError(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end, const domainname *const displayname)
2432 	{
2433 	const mDNSu8 *ptr;
2434 	mStatus err = mStatus_NoError;
2435 	int i;
2436 
2437 	ptr = LocateAdditionals(msg, end);
2438 	if (!ptr) goto finish;
2439 
2440 	for (i = 0; i < msg->h.numAdditionals; i++)
2441 		{
2442 		ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
2443 		if (!ptr) goto finish;
2444 		if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_TSIG)
2445 			{
2446 			mDNSu32 macsize;
2447 			mDNSu8 *rd = m->rec.r.resrec.rdata->u.data;
2448 			mDNSu8 *rdend = rd + m->rec.r.resrec.rdlength;
2449 			int alglen = DomainNameLengthLimit(&m->rec.r.resrec.rdata->u.name, rdend);
2450 			if (alglen > MAX_DOMAIN_NAME) goto finish;
2451 			rd += alglen;                                       // algorithm name
2452 			if (rd + 6 > rdend) goto finish;
2453 			rd += 6;                                            // 48-bit timestamp
2454 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2455 			rd += sizeof(mDNSOpaque16);                         // fudge
2456 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2457 			macsize = mDNSVal16(*(mDNSOpaque16 *)rd);
2458 			rd += sizeof(mDNSOpaque16);                         // MAC size
2459 			if (rd + macsize > rdend) goto finish;
2460 			rd += macsize;
2461 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2462 			rd += sizeof(mDNSOpaque16);                         // orig id
2463 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2464 			err = mDNSVal16(*(mDNSOpaque16 *)rd);               // error code
2465 
2466 			if      (err == TSIG_ErrBadSig)  { LogMsg("%##s: bad signature", displayname->c);              err = mStatus_BadSig;     }
2467 			else if (err == TSIG_ErrBadKey)  { LogMsg("%##s: bad key", displayname->c);                    err = mStatus_BadKey;     }
2468 			else if (err == TSIG_ErrBadTime) { LogMsg("%##s: bad time", displayname->c);                   err = mStatus_BadTime;    }
2469 			else if (err)                    { LogMsg("%##s: unknown tsig error %d", displayname->c, err); err = mStatus_UnknownErr; }
2470 			goto finish;
2471 			}
2472 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
2473 		}
2474 
2475 	finish:
2476 	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
2477 	return err;
2478 	}
2479 
2480 mDNSlocal mStatus checkUpdateResult(mDNS *const m, const domainname *const displayname, const mDNSu8 rcode, const DNSMessage *const msg, const mDNSu8 *const end)
2481 	{
2482 	(void)msg;	// currently unused, needed for TSIG errors
2483 	if (!rcode) return mStatus_NoError;
2484 	else if (rcode == kDNSFlag1_RC_YXDomain)
2485 		{
2486 		debugf("name in use: %##s", displayname->c);
2487 		return mStatus_NameConflict;
2488 		}
2489 	else if (rcode == kDNSFlag1_RC_Refused)
2490 		{
2491 		LogMsg("Update %##s refused", displayname->c);
2492 		return mStatus_Refused;
2493 		}
2494 	else if (rcode == kDNSFlag1_RC_NXRRSet)
2495 		{
2496 		LogMsg("Reregister refused (NXRRSET): %##s", displayname->c);
2497 		return mStatus_NoSuchRecord;
2498 		}
2499 	else if (rcode == kDNSFlag1_RC_NotAuth)
2500 		{
2501 		// TSIG errors should come with FormErr as per RFC 2845, but BIND 9 sends them with NotAuth so we look here too
2502 		mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
2503 		if (!tsigerr)
2504 			{
2505 			LogMsg("Permission denied (NOAUTH): %##s", displayname->c);
2506 			return mStatus_UnknownErr;
2507 			}
2508 		else return tsigerr;
2509 		}
2510 	else if (rcode == kDNSFlag1_RC_FormErr)
2511 		{
2512 		mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
2513 		if (!tsigerr)
2514 			{
2515 			LogMsg("Format Error: %##s", displayname->c);
2516 			return mStatus_UnknownErr;
2517 			}
2518 		else return tsigerr;
2519 		}
2520 	else
2521 		{
2522 		LogMsg("Update %##s failed with rcode %d", displayname->c, rcode);
2523 		return mStatus_UnknownErr;
2524 		}
2525 	}
2526 
2527 // We add three Additional Records for unicast resource record registrations
2528 // which is a function of AuthInfo and AutoTunnel properties
2529 mDNSlocal mDNSu32 RRAdditionalSize(mDNS *const m, DomainAuthInfo *AuthInfo)
2530 	{
2531 	mDNSu32 leaseSize, hinfoSize, tsigSize;
2532 	mDNSu32 rr_base_size = 10; // type (2) class (2) TTL (4) rdlength (2)
2533 
2534 	// OPT RR : Emptyname(.) + base size + rdataOPT
2535 	leaseSize = 1 + rr_base_size + sizeof(rdataOPT);
2536 
2537 	// HINFO: Resource Record Name + base size + RDATA
2538 	// HINFO is added only for autotunnels
2539 	hinfoSize = 0;
2540 	if (AuthInfo && AuthInfo->AutoTunnel)
2541 		hinfoSize = (m->hostlabel.c[0] + 1) + DomainNameLength(&AuthInfo->domain) +
2542 			rr_base_size + (2 + m->HIHardware.c[0] + m->HISoftware.c[0]);
2543 
2544 	//TSIG: Resource Record Name + base size + RDATA
2545 	// RDATA:
2546     // 	Algorithm name: hmac-md5.sig-alg.reg.int (8+7+3+3 + 5 bytes for length = 26 bytes)
2547     // 	Time: 6 bytes
2548 	// 	Fudge: 2 bytes
2549     // 	Mac Size: 2 bytes
2550 	// 	Mac: 16 bytes
2551 	// 	ID: 2 bytes
2552     // 	Error: 2 bytes
2553     // 	Len: 2 bytes
2554 	// 	Total: 58 bytes
2555 	tsigSize = 0;
2556 	if (AuthInfo) tsigSize = DomainNameLength(&AuthInfo->keyname) + rr_base_size + 58;
2557 
2558 	return (leaseSize + hinfoSize + tsigSize);
2559 	}
2560 
2561 //Note: Make sure that RREstimatedSize is updated accordingly if anything that is done here
2562 //would modify rdlength/rdestimate
2563 mDNSlocal mDNSu8* BuildUpdateMessage(mDNS *const m, mDNSu8 *ptr, AuthRecord *rr, mDNSu8 *limit)
2564 	{
2565 	//If this record is deregistering, then just send the deletion record
2566 	if (rr->state == regState_DeregPending)
2567 		{
2568 		rr->expire = 0;		// Indicate that we have no active registration any more
2569 		ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit);
2570 		if (!ptr) goto exit;
2571 		return ptr;
2572 		}
2573 
2574 	// This is a common function to both sending an update in a group or individual
2575 	// records separately. Hence, we change the state here.
2576 	if (rr->state == regState_Registered) rr->state = regState_Refresh;
2577 	if (rr->state != regState_Refresh && rr->state != regState_UpdatePending)
2578 		rr->state = regState_Pending;
2579 
2580 	// For Advisory records like e.g., _services._dns-sd, which is shared, don't send goodbyes as multiple
2581 	// host might be registering records and deregistering from one does not make sense
2582 	if (rr->resrec.RecordType != kDNSRecordTypeAdvisory) rr->RequireGoodbye = mDNStrue;
2583 
2584 	if ((rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHostAndNATMAP) &&
2585 		!mDNSIPPortIsZero(rr->NATinfo.ExternalPort))
2586 		{
2587 		rr->resrec.rdata->u.srv.port = rr->NATinfo.ExternalPort;
2588 		}
2589 
2590 	if (rr->state == regState_UpdatePending)
2591 		{
2592 		// delete old RData
2593 		SetNewRData(&rr->resrec, rr->OrigRData, rr->OrigRDLen);
2594 		if (!(ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit))) goto exit; // delete old rdata
2595 
2596 		// add new RData
2597 		SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
2598 		if (!(ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit)))  goto exit;
2599 		}
2600 	else
2601 		{
2602 		if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
2603 			{
2604 			// KnownUnique : Delete any previous value
2605 			// For Unicast registrations, we don't verify that it is unique, but set to verified and hence we want to
2606 			// delete any previous value
2607 			ptr = putDeleteRRSetWithLimit(&m->omsg, ptr, rr->resrec.name, rr->resrec.rrtype, limit);
2608 			if (!ptr) goto exit;
2609 			}
2610 		else if (rr->resrec.RecordType != kDNSRecordTypeShared)
2611 			{
2612 			// For now don't do this, until we have the logic for intelligent grouping of individual records into logical service record sets
2613 			//ptr = putPrereqNameNotInUse(rr->resrec.name, &m->omsg, ptr, end);
2614 			if (!ptr) goto exit;
2615 			}
2616 
2617 		ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
2618 		if (!ptr) goto exit;
2619 		}
2620 
2621 	return ptr;
2622 exit:
2623 	LogMsg("BuildUpdateMessage: Error formatting message for %s", ARDisplayString(m, rr));
2624 	return mDNSNULL;
2625 	}
2626 
2627 // Called with lock held
2628 mDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr)
2629 	{
2630 	mDNSu8 *ptr = m->omsg.data;
2631 	mStatus err = mStatus_UnknownErr;
2632 	mDNSu8 *limit;
2633 	DomainAuthInfo *AuthInfo;
2634 
2635 	// For the ability to register large TXT records, we limit the single record registrations
2636 	// to AbsoluteMaxDNSMessageData
2637 	limit = ptr + AbsoluteMaxDNSMessageData;
2638 
2639 	AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
2640 	limit -= RRAdditionalSize(m, AuthInfo);
2641 
2642 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
2643 		LogMsg("SendRecordRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
2644 
2645 	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
2646 		{
2647 		// We never call this function when there is no zone information . Log a message if it ever happens.
2648 		LogMsg("SendRecordRegistration: No Zone information, should not happen %s", ARDisplayString(m, rr));
2649 		return;
2650 		}
2651 
2652 	rr->updateid = mDNS_NewMessageID(m);
2653 	InitializeDNSMessage(&m->omsg.h, rr->updateid, UpdateReqFlags);
2654 
2655 	// set zone
2656 	ptr = putZone(&m->omsg, ptr, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
2657 	if (!ptr) goto exit;
2658 
2659 	if (!(ptr = BuildUpdateMessage(m, ptr, rr, limit))) goto exit;
2660 
2661 	if (rr->uselease)
2662 		{
2663 		ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
2664 		if (!ptr) goto exit;
2665 		}
2666 	if (rr->Private)
2667 		{
2668 		LogInfo("SendRecordRegistration TCP %p %s", rr->tcp, ARDisplayString(m, rr));
2669 		if (rr->tcp) LogInfo("SendRecordRegistration: Disposing existing TCP connection for %s", ARDisplayString(m, rr));
2670 		if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2671 		if (!rr->nta) { LogMsg("SendRecordRegistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
2672 		rr->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &rr->nta->Addr, rr->nta->Port, &rr->nta->Host, mDNSNULL, rr);
2673 		}
2674 	else
2675 		{
2676 		LogInfo("SendRecordRegistration UDP %s", ARDisplayString(m, rr));
2677 		if (!rr->nta) { LogMsg("SendRecordRegistration:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
2678 		err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &rr->nta->Addr, rr->nta->Port, mDNSNULL, GetAuthInfoForName_internal(m, rr->resrec.name));
2679 		if (err) debugf("ERROR: SendRecordRegistration - mDNSSendDNSMessage - %d", err);
2680 		}
2681 
2682 	SetRecordRetry(m, rr, 0);
2683 	return;
2684 exit:
2685 	LogMsg("SendRecordRegistration: Error formatting message for %s, disabling further updates", ARDisplayString(m, rr));
2686 	// Disable this record from future updates
2687 	rr->state = regState_NoTarget;
2688 	}
2689 
2690 // Is the given record "rr" eligible for merging ?
2691 mDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time)
2692 	{
2693 	DomainAuthInfo *info;
2694 	(void) m; //unused
2695 	// A record is eligible for merge, if the following properties are met.
2696 	//
2697 	// 1. uDNS Resource Record
2698 	// 2. It is time to send them now
2699 	// 3. It is in proper state
2700 	// 4. Update zone has been resolved
2701 	// 5. if DomainAuthInfo exists for the zone, it should not be soon deleted
2702 	// 6. Zone information is present
2703 	// 7. Update server is not zero
2704 	// 8. It has a non-null zone
2705 	// 9. It uses a lease option
2706 	// 10. DontMerge is not set
2707 	//
2708 	// Following code is implemented as separate "if" statements instead of one "if" statement
2709 	// is for better debugging purposes e.g., we know exactly what failed if debugging turned on.
2710 
2711 	if (!AuthRecord_uDNS(rr)) return mDNSfalse;
2712 
2713 	if (rr->LastAPTime + rr->ThisAPInterval - time > 0)
2714 		{ debugf("IsRecordMergeable: Time %d not reached for %s", rr->LastAPTime + rr->ThisAPInterval - m->timenow, ARDisplayString(m, rr)); return mDNSfalse; }
2715 
2716 	if (!rr->zone) return mDNSfalse;
2717 
2718 	info = GetAuthInfoForName_internal(m, rr->zone);
2719 
2720 	if (info && info->deltime && m->timenow - info->deltime >= 0) {debugf("IsRecordMergeable: Domain %##s will be deleted soon", info->domain.c); return mDNSfalse;}
2721 
2722 	if (rr->state != regState_DeregPending && rr->state != regState_Pending && rr->state != regState_Registered && rr->state != regState_Refresh && rr->state != regState_UpdatePending)
2723 		{ debugf("IsRecordMergeable: state %d not right  %s", rr->state, ARDisplayString(m, rr)); return mDNSfalse; }
2724 
2725 	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4)) return mDNSfalse;
2726 
2727 	if (!rr->uselease) return mDNSfalse;
2728 
2729 	if (rr->mState == mergeState_DontMerge) {debugf("IsRecordMergeable Dontmerge true %s", ARDisplayString(m, rr));return mDNSfalse;}
2730 	debugf("IsRecordMergeable: Returning true for %s", ARDisplayString(m, rr));
2731 	return mDNStrue;
2732 	}
2733 
2734 // Is the resource record "rr" eligible to merge to with "currentRR" ?
2735 mDNSlocal mDNSBool AreRecordsMergeable(mDNS *const m, AuthRecord *currentRR, AuthRecord *rr, mDNSs32 time)
2736 	{
2737 	// A record is eligible to merge with another record as long it is eligible for merge in itself
2738 	// and it has the same zone information as the other record
2739 	if (!IsRecordMergeable(m, rr, time)) return mDNSfalse;
2740 
2741 	if (!SameDomainName(currentRR->zone, rr->zone))
2742 		{ debugf("AreRecordMergeable zone mismatch current rr Zone %##s, rr zone  %##s", currentRR->zone->c, rr->zone->c); return mDNSfalse; }
2743 
2744 	if (!mDNSSameIPv4Address(currentRR->nta->Addr.ip.v4, rr->nta->Addr.ip.v4)) return mDNSfalse;
2745 
2746 	if (!mDNSSameIPPort(currentRR->nta->Port, rr->nta->Port)) return mDNSfalse;
2747 
2748 	debugf("AreRecordsMergeable: Returning true for %s", ARDisplayString(m, rr));
2749 	return mDNStrue;
2750 	}
2751 
2752 // If we can't build the message successfully because of problems in pre-computing
2753 // the space, we disable merging for all the current records
2754 mDNSlocal void RRMergeFailure(mDNS *const m)
2755 	{
2756 	AuthRecord *rr;
2757 	for (rr = m->ResourceRecords; rr; rr = rr->next)
2758 		{
2759 		rr->mState = mergeState_DontMerge;
2760 		rr->SendRNow = mDNSNULL;
2761 		// Restarting the registration is much simpler than saving and restoring
2762 		// the exact time
2763 		ActivateUnicastRegistration(m, rr);
2764 		}
2765 	}
2766 
2767 mDNSlocal void SendGroupRRMessage(mDNS *const m, AuthRecord *anchorRR, mDNSu8 *ptr, DomainAuthInfo *info)
2768 	{
2769 	mDNSu8 *limit;
2770 	if (!anchorRR) {debugf("SendGroupRRMessage: Could not merge records"); return;}
2771 
2772 	if (info && info->AutoTunnel) limit = m->omsg.data + AbsoluteMaxDNSMessageData;
2773 	else limit = m->omsg.data + NormalMaxDNSMessageData;
2774 
2775 	// This has to go in the additional section and hence need to be done last
2776 	ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
2777 	if (!ptr)
2778 		{
2779 		LogMsg("SendGroupRRMessage: ERROR: Could not put lease option, failing the group registration");
2780 		// if we can't put the lease, we need to undo the merge
2781 		RRMergeFailure(m);
2782 		return;
2783 		}
2784 	if (anchorRR->Private)
2785 		{
2786 		if (anchorRR->tcp) debugf("SendGroupRRMessage: Disposing existing TCP connection for %s", ARDisplayString(m, anchorRR));
2787 		if (anchorRR->tcp) { DisposeTCPConn(anchorRR->tcp); anchorRR->tcp = mDNSNULL; }
2788 		if (!anchorRR->nta) { LogMsg("SendGroupRRMessage:ERROR!! nta is NULL for %s", ARDisplayString(m, anchorRR)); return; }
2789 		anchorRR->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &anchorRR->nta->Addr, anchorRR->nta->Port, &anchorRR->nta->Host, mDNSNULL, anchorRR);
2790 		if (!anchorRR->tcp) LogInfo("SendGroupRRMessage: Cannot establish TCP connection for %s", ARDisplayString(m, anchorRR));
2791 		else LogInfo("SendGroupRRMessage: Sent a group update ID: %d start %p, end %p, limit %p", mDNSVal16(m->omsg.h.id), m->omsg.data, ptr, limit);
2792 		}
2793 	else
2794 		{
2795 		mStatus err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &anchorRR->nta->Addr, anchorRR->nta->Port, mDNSNULL, info);
2796 		if (err) LogInfo("SendGroupRRMessage: Cannot send UDP message for %s", ARDisplayString(m, anchorRR));
2797 		else LogInfo("SendGroupRRMessage: Sent a group UDP update ID: %d start %p, end %p, limit %p", mDNSVal16(m->omsg.h.id), m->omsg.data, ptr, limit);
2798 		}
2799 	return;
2800 	}
2801 
2802 // As we always include the zone information and the resource records contain zone name
2803 // at the end, it will get compressed. Hence, we subtract zoneSize and add two bytes for
2804 // the compression pointer
2805 mDNSlocal mDNSu32 RREstimatedSize(AuthRecord *rr, int zoneSize)
2806 	{
2807 	int rdlength;
2808 
2809 	// Note: Estimation of the record size has to mirror the logic in BuildUpdateMessage, otherwise estimation
2810 	// would be wrong. Currently BuildUpdateMessage calls SetNewRData in UpdatePending case. Hence, we need
2811 	// to account for that here. Otherwise, we might under estimate the size.
2812 	if (rr->state == regState_UpdatePending)
2813 		// old RData that will be deleted
2814 		// new RData that will be added
2815 		rdlength = rr->OrigRDLen + rr->InFlightRDLen;
2816 	else
2817 		rdlength = rr->resrec.rdestimate;
2818 
2819 	if (rr->state == regState_DeregPending)
2820 		{
2821 		debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
2822 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
2823 		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
2824 		}
2825 
2826 	// For SRV, TXT, AAAA etc. that are Unique/Verified, we also send a Deletion Record
2827 	if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
2828 		{
2829 		// Deletion Record: Resource Record Name + Base size (10) + 0
2830 		// Record: Resource Record Name (Compressed = 2) + Base size (10) + rdestimate
2831 
2832 		debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
2833 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
2834 		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + 2 + 10 + rdlength;
2835 		}
2836 	else
2837 		{
2838 		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
2839 		}
2840 	}
2841 
2842 mDNSlocal AuthRecord *MarkRRForSending(mDNS *const m)
2843 	{
2844 	AuthRecord *rr;
2845 	AuthRecord *firstRR = mDNSNULL;
2846 
2847 	// Look for records that needs to be sent in the next two seconds (MERGE_DELAY_TIME is set to 1 second).
2848 	// The logic is as follows.
2849 	//
2850 	// 1. Record 1 finishes getting zone data and its registration gets delayed by 1 second
2851 	// 2. Record 2 comes 0.1 second later, finishes getting its zone data and its registration is also delayed by
2852 	//    1 second which is now scheduled at 1.1 second
2853 	//
2854 	// By looking for 1 second into the future (m->timenow + MERGE_DELAY_TIME below does that) we have merged both
2855 	// of the above records. Note that we can't look for records too much into the future as this will affect the
2856 	// retry logic. The first retry is scheduled at 3 seconds. Hence, we should always look smaller than that.
2857 	// Anything more than one second will affect the first retry to happen sooner.
2858 	//
2859 	// Note: As a side effect of looking one second into the future to facilitate merging, the retries happen
2860 	// one second sooner.
2861 	for (rr = m->ResourceRecords; rr; rr = rr->next)
2862 		{
2863 		if (!firstRR)
2864 			{
2865 			if (!IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME)) continue;
2866 			firstRR = rr;
2867 			}
2868 		else if (!AreRecordsMergeable(m, firstRR, rr, m->timenow + MERGE_DELAY_TIME)) continue;
2869 
2870 		if (rr->SendRNow) LogMsg("MarkRRForSending: Resourcerecord %s already marked for sending", ARDisplayString(m, rr));
2871 		rr->SendRNow = mDNSInterfaceMark;
2872 		}
2873 
2874 	// We parsed through all records and found something to send. The services/records might
2875 	// get registered at different times but we want the refreshes to be all merged and sent
2876 	// as one update. Hence, we accelerate some of the records so that they will sync up in
2877 	// the future. Look at the records excluding the ones that we have already sent in the
2878 	// previous pass. If it half way through its scheduled refresh/retransmit, merge them
2879 	// into this packet.
2880 	//
2881 	// Note that we only look at Registered/Refresh state to keep it simple. As we don't know
2882 	// whether the current update will fit into one or more packets, merging a resource record
2883 	// (which is in a different state) that has been scheduled for retransmit would trigger
2884 	// sending more packets.
2885 	if (firstRR)
2886 		{
2887 		int acc = 0;
2888 		for (rr = m->ResourceRecords; rr; rr = rr->next)
2889 			{
2890 			if ((rr->state != regState_Registered && rr->state != regState_Refresh) ||
2891 				(rr->SendRNow == mDNSInterfaceMark) ||
2892 				(!AreRecordsMergeable(m, firstRR, rr, m->timenow + rr->ThisAPInterval/2)))
2893 				continue;
2894 			rr->SendRNow = mDNSInterfaceMark;
2895 			acc++;
2896 			}
2897 		if (acc) LogInfo("MarkRRForSending: Accelereated %d records", acc);
2898 		}
2899 	return firstRR;
2900 	}
2901 
2902 mDNSlocal mDNSBool SendGroupUpdates(mDNS *const m)
2903 	{
2904 	mDNSOpaque16 msgid;
2905 	mDNSs32 spaceleft = 0;
2906 	mDNSs32 zoneSize, rrSize;
2907 	mDNSu8 *oldnext; // for debugging
2908 	mDNSu8 *next = m->omsg.data;
2909 	AuthRecord *rr;
2910 	AuthRecord *anchorRR = mDNSNULL;
2911 	int nrecords = 0;
2912 	AuthRecord *startRR = m->ResourceRecords;
2913 	mDNSu8 *limit = mDNSNULL;
2914 	DomainAuthInfo *AuthInfo = mDNSNULL;
2915 	mDNSBool sentallRecords = mDNStrue;
2916 
2917 
2918 	// We try to fit as many ResourceRecords as possible in AbsoluteNormal/MaxDNSMessageData. Before we start
2919 	// putting in resource records, we need to reserve space for a few things. Every group/packet should
2920 	// have the following.
2921 	//
2922 	// 1) Needs space for the Zone information (which needs to be at the beginning)
2923 	// 2) Additional section MUST have space for lease option, HINFO and TSIG option (which needs to
2924 	//    to be at the end)
2925 	//
2926 	// In future we need to reserve space for the pre-requisites which also goes at the beginning.
2927 	// To accomodate pre-requisites in the future, first we walk the whole list marking records
2928 	// that can be sent in this packet and computing the space needed for these records.
2929 	// For TXT and SRV records, we delete the previous record if any by sending the same
2930 	// resource record with ANY RDATA and zero rdlen. Hence, we need to have space for both of them.
2931 
2932 	while (startRR)
2933 		{
2934 		AuthInfo = mDNSNULL;
2935 		anchorRR = mDNSNULL;
2936 		nrecords = 0;
2937 		zoneSize = 0;
2938 		for (rr = startRR; rr; rr = rr->next)
2939 			{
2940 			if (rr->SendRNow != mDNSInterfaceMark) continue;
2941 
2942 			rr->SendRNow = mDNSNULL;
2943 
2944 			if (!anchorRR)
2945 				{
2946 				AuthInfo = GetAuthInfoForName_internal(m, rr->zone);
2947 
2948 				// Though we allow single record registrations for UDP to be AbsoluteMaxDNSMessageData (See
2949 				// SendRecordRegistration) to handle large TXT records, to avoid fragmentation we limit UDP
2950 				// message to NormalMaxDNSMessageData
2951 				if (AuthInfo && AuthInfo->AutoTunnel) spaceleft = AbsoluteMaxDNSMessageData;
2952 				else spaceleft = NormalMaxDNSMessageData;
2953 
2954 				next = m->omsg.data;
2955 				spaceleft -= RRAdditionalSize(m, AuthInfo);
2956 				if (spaceleft <= 0)
2957 					{
2958 					LogMsg("SendGroupUpdates: ERROR!!: spaceleft is zero at the beginning");
2959 					RRMergeFailure(m);
2960 					return mDNSfalse;
2961 					}
2962 				limit = next + spaceleft;
2963 
2964 				// Build the initial part of message before putting in the other records
2965  				msgid = mDNS_NewMessageID(m);
2966 				InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
2967 
2968 				// We need zone information at the beginning of the packet. Length: ZNAME, ZTYPE(2), ZCLASS(2)
2969 				// zone has to be non-NULL for a record to be mergeable, hence it is safe to set/ examine zone
2970 				//without checking for NULL.
2971 				zoneSize = DomainNameLength(rr->zone) + 4;
2972 				spaceleft -= zoneSize;
2973 				if (spaceleft <= 0)
2974 					{
2975 					LogMsg("SendGroupUpdates: ERROR no space for zone information, disabling merge");
2976 					RRMergeFailure(m);
2977 					return mDNSfalse;
2978 					}
2979 				next = putZone(&m->omsg, next, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
2980 				if (!next)
2981 					{
2982 					LogMsg("SendGroupUpdates: ERROR! Cannot put zone, disabling merge");
2983 					RRMergeFailure(m);
2984 					return mDNSfalse;
2985 					}
2986 				anchorRR = rr;
2987 				}
2988 
2989 			rrSize = RREstimatedSize(rr, zoneSize - 4);
2990 
2991 			if ((spaceleft - rrSize) < 0)
2992 				{
2993 				// If we can't fit even a single message, skip it, it will be sent separately
2994 				// in CheckRecordUpdates
2995 				if (!nrecords)
2996 					{
2997 					LogInfo("SendGroupUpdates: Skipping message %s, spaceleft %d, rrSize %d", ARDisplayString(m, rr), spaceleft, rrSize);
2998 					// Mark this as not sent so that the caller knows about it
2999 					rr->SendRNow = mDNSInterfaceMark;
3000 					// We need to remove the merge delay so that we can send it immediately
3001 					rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3002 					rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3003 					rr = rr->next;
3004 					anchorRR = mDNSNULL;
3005 					sentallRecords = mDNSfalse;
3006 					}
3007 				else
3008 					{
3009 					LogInfo("SendGroupUpdates:1: Parsed %d records and sending using %s, spaceleft %d, rrSize %d", nrecords, ARDisplayString(m, anchorRR), spaceleft, rrSize);
3010 					SendGroupRRMessage(m, anchorRR, next, AuthInfo);
3011 					}
3012 				break;		// breaks out of for loop
3013 				}
3014 			spaceleft -= rrSize;
3015 			oldnext = next;
3016 			LogInfo("SendGroupUpdates: Building a message with resource record %s, next %p, state %d, ttl %d", ARDisplayString(m, rr), next, rr->state, rr->resrec.rroriginalttl);
3017 			if (!(next = BuildUpdateMessage(m, next, rr, limit)))
3018 				{
3019 				// We calculated the space and if we can't fit in, we had some bug in the calculation,
3020 				// disable merge completely.
3021 				LogMsg("SendGroupUpdates: ptr NULL while building message with %s", ARDisplayString(m, rr));
3022 				RRMergeFailure(m);
3023 				return mDNSfalse;
3024 				}
3025 			// If our estimate was higher, adjust to the actual size
3026 			if ((next - oldnext) > rrSize)
3027 				LogMsg("SendGroupUpdates: ERROR!! Record size estimation is wrong for %s, Estimate %d, Actual %d, state %d", ARDisplayString(m, rr), rrSize, next - oldnext, rr->state);
3028 			else { spaceleft += rrSize; spaceleft -= (next - oldnext); }
3029 
3030 			nrecords++;
3031 			// We could have sent an update earlier with this "rr" as anchorRR for which we never got a response.
3032 			// To preserve ordering, we blow away the previous connection before sending this.
3033 			if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL;}
3034 			rr->updateid = msgid;
3035 
3036 			// By setting the retry time interval here, we will not be looking at these records
3037 			// again when we return to CheckGroupRecordUpdates.
3038 			SetRecordRetry(m, rr, 0);
3039 			}
3040 			// Either we have parsed all the records or stopped at "rr" above due to lack of space
3041 			startRR = rr;
3042 		}
3043 
3044 	if (anchorRR)
3045 		{
3046 		LogInfo("SendGroupUpdates: Parsed %d records and sending using %s", nrecords, ARDisplayString(m, anchorRR));
3047 		SendGroupRRMessage(m, anchorRR, next, AuthInfo);
3048 		}
3049 	return sentallRecords;
3050 	}
3051 
3052 // Merge the record registrations and send them as a group only if they
3053 // have same DomainAuthInfo and hence the same key to put the TSIG
3054 mDNSlocal void CheckGroupRecordUpdates(mDNS *const m)
3055 	{
3056 	AuthRecord *rr, *nextRR;
3057 	// Keep sending as long as there is at least one record to be sent
3058 	while (MarkRRForSending(m))
3059 		{
3060 		if (!SendGroupUpdates(m))
3061 			{
3062 			// if everything that was marked was not sent, send them out individually
3063 			for (rr = m->ResourceRecords; rr; rr = nextRR)
3064 				{
3065 				// SendRecordRegistrtion might delete the rr from list, hence
3066 				// dereference nextRR before calling the function
3067 				nextRR = rr->next;
3068 				if (rr->SendRNow == mDNSInterfaceMark)
3069 					{
3070 					// Any records marked for sending should be eligible to be sent out
3071 					// immediately. Just being cautious
3072 					if (rr->LastAPTime + rr->ThisAPInterval - m->timenow > 0)
3073 						{ LogMsg("CheckGroupRecordUpdates: ERROR!! Resourcerecord %s not ready", ARDisplayString(m, rr)); continue; }
3074 					rr->SendRNow = mDNSNULL;
3075 					SendRecordRegistration(m, rr);
3076 					}
3077 				}
3078 			}
3079 		}
3080 
3081 	debugf("CheckGroupRecordUpdates: No work, returning");
3082 	return;
3083 	}
3084 
3085 mDNSlocal void hndlSRVChanged(mDNS *const m, AuthRecord *rr)
3086 	{
3087 	// Reevaluate the target always as NAT/Target could have changed while
3088 	// we were registering/deeregistering
3089 	domainname *dt;
3090 	const domainname *target = GetServiceTarget(m, rr);
3091 	if (!target || target->c[0] == 0)
3092 		{
3093 		// we don't have a target, if we just derregistered, then we don't have to do anything
3094 		if (rr->state == regState_DeregPending)
3095 			{
3096 			LogInfo("hndlSRVChanged: SRVChanged, No Target, SRV Deregistered for %##s, state %d", rr->resrec.name->c,
3097 				rr->state);
3098 			rr->SRVChanged = mDNSfalse;
3099 			dt = GetRRDomainNameTarget(&rr->resrec);
3100 			if (dt) dt->c[0] = 0;
3101 			rr->state = regState_NoTarget;	// Wait for the next target change
3102 			rr->resrec.rdlength = rr->resrec.rdestimate = 0;
3103 			return;
3104 			}
3105 
3106 		// we don't have a target, if we just registered, we need to deregister
3107 		if (rr->state == regState_Pending)
3108 			{
3109 			LogInfo("hndlSRVChanged: SRVChanged, No Target, Deregistering again %##s, state %d", rr->resrec.name->c, rr->state);
3110 			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3111 			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3112 			rr->state = regState_DeregPending;
3113 			return;
3114 			}
3115 		LogInfo("hndlSRVChanged: Not in DeregPending or RegPending state %##s, state %d", rr->resrec.name->c, rr->state);
3116 		}
3117 	else
3118 		{
3119 		// If we were in registered state and SRV changed to NULL, we deregister and come back here
3120 		// if we have a target, we need to register again.
3121 		//
3122 		// if we just registered check to see if it is same. If it is different just re-register the
3123 		// SRV and its assoicated records
3124 		//
3125 		// UpdateOneSRVRecord takes care of re-registering all service records
3126 		if ((rr->state == regState_DeregPending) ||
3127 		   (rr->state == regState_Pending && !SameDomainName(target, &rr->resrec.rdata->u.srv.target)))
3128 			{
3129 			dt = GetRRDomainNameTarget(&rr->resrec);
3130 			if (dt) dt->c[0] = 0;
3131 			rr->state = regState_NoTarget;	// NoTarget will allow us to pick up new target OR nat traversal state
3132 			rr->resrec.rdlength = rr->resrec.rdestimate = 0;
3133 			LogInfo("hndlSRVChanged: SRVChanged, Valid Target %##s, Registering all records for %##s, state %d",
3134 				target->c, rr->resrec.name->c, rr->state);
3135 			rr->SRVChanged = mDNSfalse;
3136 			UpdateOneSRVRecord(m, rr);
3137 			return;
3138 			}
3139 		// Target did not change while this record was registering. Hence, we go to
3140 		// Registered state - the state we started from.
3141 		if (rr->state == regState_Pending) rr->state = regState_Registered;
3142 		}
3143 
3144 	rr->SRVChanged = mDNSfalse;
3145 	}
3146 
3147 // Called with lock held
3148 mDNSlocal void hndlRecordUpdateReply(mDNS *m, AuthRecord *rr, mStatus err, mDNSu32 random)
3149 	{
3150 	mDNSBool InvokeCallback = mDNStrue;
3151 	mDNSIPPort UpdatePort = zeroIPPort;
3152 
3153 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
3154 		LogMsg("hndlRecordUpdateReply: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
3155 
3156 	LogInfo("hndlRecordUpdateReply: err %d ID %d state %d %s(%p)", err, mDNSVal16(rr->updateid), rr->state, ARDisplayString(m, rr), rr);
3157 
3158 	rr->updateError = err;
3159 #if APPLE_OSX_mDNSResponder
3160 	if (err == mStatus_BadSig || err == mStatus_BadKey) UpdateAutoTunnelDomainStatuses(m);
3161 #endif
3162 
3163 	SetRecordRetry(m, rr, random);
3164 
3165 	rr->updateid = zeroID;	// Make sure that this is not considered as part of a group anymore
3166 	// Later when need to send an update, we will get the zone data again. Thus we avoid
3167 	// using stale information.
3168 	//
3169 	// Note: By clearing out the zone info here, it also helps better merging of records
3170 	// in some cases. For example, when we get out regState_NoTarget state e.g., move out
3171 	// of Double NAT, we want all the records to be in one update. Some BTMM records like
3172 	// _autotunnel6 and host records are registered/deregistered when NAT state changes.
3173 	// As they are re-registered the zone information is cleared out. To merge with other
3174 	// records that might be possibly going out, clearing out the information here helps
3175 	// as all of them try to get the zone data.
3176 	if (rr->nta)
3177 		{
3178 		// We always expect the question to be stopped when we get a valid response from the server.
3179 		// If the zone info tries to change during this time, updateid would be different and hence
3180 		// this response should not have been accepted.
3181 		if (rr->nta->question.ThisQInterval != -1)
3182 			LogMsg("hndlRecordUpdateReply: ResourceRecord %s, zone info question %##s (%s) interval %d not -1",
3183 				ARDisplayString(m, rr), rr->nta->question.qname.c, DNSTypeName(rr->nta->question.qtype), rr->nta->question.ThisQInterval);
3184 		UpdatePort = rr->nta->Port;
3185 		CancelGetZoneData(m, rr->nta);
3186 		rr->nta = mDNSNULL;
3187 		}
3188 
3189 	// If we are deregistering the record, then complete the deregistration. Ignore any NAT/SRV change
3190 	// that could have happened during that time.
3191 	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->state == regState_DeregPending)
3192 		{
3193 		debugf("hndlRecordUpdateReply: Received reply for deregister record %##s type %d", rr->resrec.name->c, rr->resrec.rrtype);
3194 		if (err) LogMsg("ERROR: Deregistration of record %##s type %d failed with error %d",
3195 						rr->resrec.name->c, rr->resrec.rrtype, err);
3196 		rr->state = regState_Unregistered;
3197 		CompleteDeregistration(m, rr);
3198 		return;
3199 		}
3200 
3201 	// We are returning early without updating the state. When we come back from sleep we will re-register after
3202 	// re-initializing all the state as though it is a first registration. If the record can't be registered e.g.,
3203 	// no target, it will be deregistered. Hence, the updating to the right state should not matter when going
3204 	// to sleep.
3205 	if (m->SleepState)
3206 		{
3207 		// Need to set it to NoTarget state so that RecordReadyForSleep knows that
3208 		// we are done
3209 		if (rr->resrec.rrtype == kDNSType_SRV && rr->state == regState_DeregPending)
3210 			rr->state = regState_NoTarget;
3211 		return;
3212 		}
3213 
3214 	if (rr->state == regState_UpdatePending)
3215 		{
3216 		if (err) LogMsg("Update record failed for %##s (err %d)", rr->resrec.name->c, err);
3217 		rr->state = regState_Registered;
3218 		// deallocate old RData
3219 		if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->OrigRData, rr->OrigRDLen);
3220 		SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
3221 		rr->OrigRData = mDNSNULL;
3222 		rr->InFlightRData = mDNSNULL;
3223 		}
3224 
3225 	if (rr->SRVChanged)
3226 		{
3227 		if (rr->resrec.rrtype == kDNSType_SRV)
3228 			hndlSRVChanged(m, rr);
3229 		else
3230 			{
3231 			LogInfo("hndlRecordUpdateReply: Deregistered %##s (%s), state %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->state);
3232 			rr->SRVChanged = mDNSfalse;
3233 			if (rr->state != regState_DeregPending) LogMsg("hndlRecordUpdateReply: ResourceRecord %s not in DeregPending state %d", ARDisplayString(m, rr), rr->state);
3234 			rr->state = regState_NoTarget;	// Wait for the next target change
3235 			}
3236 		return;
3237 		}
3238 
3239 	if (rr->state == regState_Pending || rr->state == regState_Refresh)
3240 		{
3241 		if (!err)
3242 			{
3243 			if (rr->state == regState_Refresh) InvokeCallback = mDNSfalse;
3244 			rr->state = regState_Registered;
3245 			}
3246 		else
3247 			{
3248 			// Retry without lease only for non-Private domains
3249 			LogMsg("hndlRecordUpdateReply: Registration of record %##s type %d failed with error %d", rr->resrec.name->c, rr->resrec.rrtype, err);
3250 			if (!rr->Private && rr->uselease && err == mStatus_UnknownErr && mDNSSameIPPort(UpdatePort, UnicastDNSPort))
3251 				{
3252 				LogMsg("hndlRecordUpdateReply: Will retry update of record %##s without lease option", rr->resrec.name->c);
3253 				rr->uselease = mDNSfalse;
3254 				rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3255 				rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3256 				return;
3257 				}
3258 			// Communicate the error to the application in the callback below
3259 			}
3260 		}
3261 
3262 	if (rr->QueuedRData && rr->state == regState_Registered)
3263 		{
3264 		rr->state = regState_UpdatePending;
3265 		rr->InFlightRData = rr->QueuedRData;
3266 		rr->InFlightRDLen = rr->QueuedRDLen;
3267 		rr->OrigRData = rr->resrec.rdata;
3268 		rr->OrigRDLen = rr->resrec.rdlength;
3269 		rr->QueuedRData = mDNSNULL;
3270 		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3271 		rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3272 		return;
3273 		}
3274 
3275 	// Don't invoke the callback on error as this may not be useful to the client.
3276 	// The client may potentially delete the resource record on error which we normally
3277 	// delete during deregistration
3278 	if (!err && InvokeCallback && rr->RecordCallback)
3279 		{
3280 		LogInfo("hndlRecordUpdateReply: Calling record callback on %##s", rr->resrec.name->c);
3281 		mDNS_DropLockBeforeCallback();
3282 		rr->RecordCallback(m, rr, err);
3283 		mDNS_ReclaimLockAfterCallback();
3284 		}
3285 	// CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
3286 	// is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
3287 	}
3288 
3289 mDNSexport void uDNS_ReceiveNATPMPPacket(mDNS *m, const mDNSInterfaceID InterfaceID, mDNSu8 *pkt, mDNSu16 len)
3290 	{
3291 	NATTraversalInfo *ptr;
3292 	NATAddrReply     *AddrReply    = (NATAddrReply    *)pkt;
3293 	NATPortMapReply  *PortMapReply = (NATPortMapReply *)pkt;
3294 	mDNSu32 nat_elapsed, our_elapsed;
3295 
3296 	// Minimum packet is vers (1) opcode (1) err (2) upseconds (4) = 8 bytes
3297 	if (!AddrReply->err && len < 8) { LogMsg("NAT Traversal message too short (%d bytes)", len); return; }
3298 	if (AddrReply->vers != NATMAP_VERS) { LogMsg("Received NAT Traversal response with version %d (expected %d)", pkt[0], NATMAP_VERS); return; }
3299 
3300 	// Read multi-byte numeric values (fields are identical in a NATPortMapReply)
3301 	AddrReply->err       = (mDNSu16) (                                                (mDNSu16)pkt[2] << 8 | pkt[3]);
3302 	AddrReply->upseconds = (mDNSs32) ((mDNSs32)pkt[4] << 24 | (mDNSs32)pkt[5] << 16 | (mDNSs32)pkt[6] << 8 | pkt[7]);
3303 
3304 	nat_elapsed = AddrReply->upseconds - m->LastNATupseconds;
3305 	our_elapsed = (m->timenow - m->LastNATReplyLocalTime) / mDNSPlatformOneSecond;
3306 	debugf("uDNS_ReceiveNATPMPPacket %X upseconds %u nat_elapsed %d our_elapsed %d", AddrReply->opcode, AddrReply->upseconds, nat_elapsed, our_elapsed);
3307 
3308 	// We compute a conservative estimate of how much the NAT gateways's clock should have advanced
3309 	// 1. We subtract 12.5% from our own measured elapsed time, to allow for NAT gateways that have an inacurate clock that runs slowly
3310 	// 2. We add a two-second safety margin to allow for rounding errors: e.g.
3311 	//    -- if NAT gateway sends a packet at t=2.000 seconds, then one at t=7.999, that's approximately 6 real seconds,
3312 	//       but based on the values in the packet (2,7) the apparent difference according to the packet is only 5 seconds
3313 	//    -- if we're slow handling packets and/or we have coarse clock granularity,
3314 	//       we could receive the t=2 packet at our t=1.999 seconds, which we round down to 1
3315 	//       and the t=7.999 packet at our t=8.000 seconds, which we record as 8,
3316 	//       giving an apparent local time difference of 7 seconds
3317 	//    The two-second safety margin coves this possible calculation discrepancy
3318 	if (AddrReply->upseconds < m->LastNATupseconds || nat_elapsed + 2 < our_elapsed - our_elapsed/8)
3319 		{ LogMsg("NAT gateway %#a rebooted", &m->Router); RecreateNATMappings(m); }
3320 
3321 	m->LastNATupseconds      = AddrReply->upseconds;
3322 	m->LastNATReplyLocalTime = m->timenow;
3323 #ifdef _LEGACY_NAT_TRAVERSAL_
3324 	LNT_ClearState(m);
3325 #endif // _LEGACY_NAT_TRAVERSAL_
3326 
3327 	if (AddrReply->opcode == NATOp_AddrResponse)
3328 		{
3329 #if APPLE_OSX_mDNSResponder
3330 		static char msgbuf[16];
3331 		mDNS_snprintf(msgbuf, sizeof(msgbuf), "%d", AddrReply->err);
3332 		mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.AddressRequest", AddrReply->err ? "failure" : "success", msgbuf, "");
3333 #endif
3334 		if (!AddrReply->err && len < sizeof(NATAddrReply)) { LogMsg("NAT Traversal AddrResponse message too short (%d bytes)", len); return; }
3335 		natTraversalHandleAddressReply(m, AddrReply->err, AddrReply->ExtAddr);
3336 		}
3337 	else if (AddrReply->opcode == NATOp_MapUDPResponse || AddrReply->opcode == NATOp_MapTCPResponse)
3338 		{
3339 		mDNSu8 Protocol = AddrReply->opcode & 0x7F;
3340 #if APPLE_OSX_mDNSResponder
3341 		static char msgbuf[16];
3342 		mDNS_snprintf(msgbuf, sizeof(msgbuf), "%s - %d", AddrReply->opcode == NATOp_MapUDPResponse ? "UDP" : "TCP", PortMapReply->err);
3343 		mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.PortMapRequest", PortMapReply->err ? "failure" : "success", msgbuf, "");
3344 #endif
3345 		if (!PortMapReply->err)
3346 			{
3347 			if (len < sizeof(NATPortMapReply)) { LogMsg("NAT Traversal PortMapReply message too short (%d bytes)", len); return; }
3348 			PortMapReply->NATRep_lease = (mDNSu32) ((mDNSu32)pkt[12] << 24 | (mDNSu32)pkt[13] << 16 | (mDNSu32)pkt[14] << 8 | pkt[15]);
3349 			}
3350 
3351 		// Since some NAT-PMP server implementations don't return the requested internal port in
3352 		// the reply, we can't associate this reply with a particular NATTraversalInfo structure.
3353 		// We globally keep track of the most recent error code for mappings.
3354 		m->LastNATMapResultCode = PortMapReply->err;
3355 
3356 		for (ptr = m->NATTraversals; ptr; ptr=ptr->next)
3357 			if (ptr->Protocol == Protocol && mDNSSameIPPort(ptr->IntPort, PortMapReply->intport))
3358 				natTraversalHandlePortMapReply(m, ptr, InterfaceID, PortMapReply->err, PortMapReply->extport, PortMapReply->NATRep_lease);
3359 		}
3360 	else { LogMsg("Received NAT Traversal response with version unknown opcode 0x%X", AddrReply->opcode); return; }
3361 
3362 	// Don't need an SSDP socket if we get a NAT-PMP packet
3363 	if (m->SSDPSocket) { debugf("uDNS_ReceiveNATPMPPacket destroying SSDPSocket %p", &m->SSDPSocket); mDNSPlatformUDPClose(m->SSDPSocket); m->SSDPSocket = mDNSNULL; }
3364 	}
3365 
3366 // <rdar://problem/3925163> Shorten DNS-SD queries to avoid NAT bugs
3367 // <rdar://problem/4288449> Add check to avoid crashing NAT gateways that have buggy DNS relay code
3368 //
3369 // We know of bugs in home NAT gateways that cause them to crash if they receive certain DNS queries.
3370 // The DNS queries that make them crash are perfectly legal DNS queries, but even if they weren't,
3371 // the gateway shouldn't crash -- in today's world of viruses and network attacks, software has to
3372 // be written assuming that a malicious attacker could send them any packet, properly-formed or not.
3373 // Still, we don't want to be crashing people's home gateways, so we go out of our way to avoid
3374 // the queries that crash them.
3375 //
3376 // Some examples:
3377 //
3378 // 1. Any query where the name ends in ".in-addr.arpa." and the text before this is 32 or more bytes.
3379 //    The query type does not need to be PTR -- the gateway will crash for any query type.
3380 //    e.g. "ping long-name-crashes-the-buggy-router.in-addr.arpa" will crash one of these.
3381 //
3382 // 2. Any query that results in a large response with the TC bit set.
3383 //
3384 // 3. Any PTR query that doesn't begin with four decimal numbers.
3385 //    These gateways appear to assume that the only possible PTR query is a reverse-mapping query
3386 //    (e.g. "1.0.168.192.in-addr.arpa") and if they ever get a PTR query where the first four
3387 //    labels are not all decimal numbers in the range 0-255, they handle that by crashing.
3388 //    These gateways also ignore the remainder of the name following the four decimal numbers
3389 //    -- whether or not it actually says in-addr.arpa, they just make up an answer anyway.
3390 //
3391 // The challenge therefore is to craft a query that will discern whether the DNS server
3392 // is one of these buggy ones, without crashing it. Furthermore we don't want our test
3393 // queries making it all the way to the root name servers, putting extra load on those
3394 // name servers and giving Apple a bad reputation. To this end we send this query:
3395 //     dig -t ptr 1.0.0.127.dnsbugtest.1.0.0.127.in-addr.arpa.
3396 //
3397 // The text preceding the ".in-addr.arpa." is under 32 bytes, so it won't cause crash (1).
3398 // It will not yield a large response with the TC bit set, so it won't cause crash (2).
3399 // It starts with four decimal numbers, so it won't cause crash (3).
3400 // The name falls within the "1.0.0.127.in-addr.arpa." domain, the reverse-mapping name for the local
3401 // loopback address, and therefore the query will black-hole at the first properly-configured DNS server
3402 // it reaches, making it highly unlikely that this query will make it all the way to the root.
3403 //
3404 // Finally, the correct response to this query is NXDOMAIN or a similar error, but the
3405 // gateways that ignore the remainder of the name following the four decimal numbers
3406 // give themselves away by actually returning a result for this nonsense query.
3407 
3408 mDNSlocal const domainname *DNSRelayTestQuestion = (const domainname*)
3409 	"\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\xa" "dnsbugtest"
3410 	"\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\x7" "in-addr" "\x4" "arpa";
3411 
3412 // See comments above for DNSRelayTestQuestion
3413 // If this is the kind of query that has the risk of crashing buggy DNS servers, we do a test question first
3414 mDNSlocal mDNSBool NoTestQuery(DNSQuestion *q)
3415 	{
3416 	int i;
3417 	mDNSu8 *p = q->qname.c;
3418 	if (q->AuthInfo) return(mDNStrue);		// Don't need a test query for private queries sent directly to authoritative server over TLS/TCP
3419 	if (q->qtype != kDNSType_PTR) return(mDNStrue);		// Don't need a test query for any non-PTR queries
3420 	for (i=0; i<4; i++)		// If qname does not begin with num.num.num.num, can't skip the test query
3421 		{
3422 		if (p[0] < 1 || p[0] > 3) return(mDNSfalse);
3423 		if (              p[1] < '0' || p[1] > '9' ) return(mDNSfalse);
3424 		if (p[0] >= 2 && (p[2] < '0' || p[2] > '9')) return(mDNSfalse);
3425 		if (p[0] >= 3 && (p[3] < '0' || p[3] > '9')) return(mDNSfalse);
3426 		p += 1 + p[0];
3427 		}
3428 	// If remainder of qname is ".in-addr.arpa.", this is a vanilla reverse-mapping query and
3429 	// we can safely do it without needing a test query first, otherwise we need the test query.
3430 	return(SameDomainName((domainname*)p, (const domainname*)"\x7" "in-addr" "\x4" "arpa"));
3431 	}
3432 
3433 // Returns mDNStrue if response was handled
3434 mDNSlocal mDNSBool uDNS_ReceiveTestQuestionResponse(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
3435 	const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
3436 	{
3437 	const mDNSu8 *ptr = msg->data;
3438 	DNSQuestion pktq;
3439 	DNSServer *s;
3440 	mDNSu32 result = 0;
3441 
3442 	// 1. Find out if this is an answer to one of our test questions
3443 	if (msg->h.numQuestions != 1) return(mDNSfalse);
3444 	ptr = getQuestion(msg, ptr, end, mDNSInterface_Any, &pktq);
3445 	if (!ptr) return(mDNSfalse);
3446 	if (pktq.qtype != kDNSType_PTR || pktq.qclass != kDNSClass_IN) return(mDNSfalse);
3447 	if (!SameDomainName(&pktq.qname, DNSRelayTestQuestion)) return(mDNSfalse);
3448 
3449 	// 2. If the DNS relay gave us a positive response, then it's got buggy firmware
3450 	// else, if the DNS relay gave us an error or no-answer response, it passed our test
3451 	if ((msg->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr && msg->h.numAnswers > 0)
3452 		result = DNSServer_Failed;
3453 	else
3454 		result = DNSServer_Passed;
3455 
3456 	// 3. Find occurrences of this server in our list, and mark them appropriately
3457 	for (s = m->DNSServers; s; s = s->next)
3458 		{
3459 		mDNSBool matchaddr = (s->teststate != result && mDNSSameAddress(srcaddr, &s->addr) && mDNSSameIPPort(srcport, s->port));
3460 		mDNSBool matchid   = (s->teststate == DNSServer_Untested && mDNSSameOpaque16(msg->h.id, s->testid));
3461 		if (matchaddr || matchid)
3462 			{
3463 			DNSQuestion *q;
3464 			s->teststate = result;
3465 			if (result == DNSServer_Passed)
3466 				{
3467 				LogInfo("DNS Server %#a:%d (%#a:%d) %d passed%s",
3468 					&s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
3469 					matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
3470 				}
3471 			else
3472 				{
3473 				LogMsg("NOTE: Wide-Area Service Discovery disabled to avoid crashing defective DNS relay %#a:%d (%#a:%d) %d%s",
3474 					&s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
3475 					matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
3476 				}
3477 
3478 			// If this server has just changed state from DNSServer_Untested to DNSServer_Passed, then retrigger any waiting questions.
3479 			// We use the NoTestQuery() test so that we only retrigger questions that were actually blocked waiting for this test to complete.
3480 			if (result == DNSServer_Passed)		// Unblock any questions that were waiting for this result
3481 				for (q = m->Questions; q; q=q->next)
3482 					if (q->qDNSServer == s && !NoTestQuery(q))
3483 						{
3484 						q->ThisQInterval = INIT_UCAST_POLL_INTERVAL / QuestionIntervalStep;
3485 						q->unansweredQueries = 0;
3486 						q->LastQTime = m->timenow - q->ThisQInterval;
3487 						m->NextScheduledQuery = m->timenow;
3488 						}
3489 			}
3490 		}
3491 
3492 	return(mDNStrue); // Return mDNStrue to tell uDNS_ReceiveMsg it doesn't need to process this packet further
3493 	}
3494 
3495 // Called from mDNSCoreReceive with the lock held
3496 mDNSexport void uDNS_ReceiveMsg(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end, const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
3497 	{
3498 	DNSQuestion *qptr;
3499 	mStatus err = mStatus_NoError;
3500 
3501 	mDNSu8 StdR    = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
3502 	mDNSu8 UpdateR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
3503 	mDNSu8 QR_OP   = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
3504 	mDNSu8 rcode   = (mDNSu8)(msg->h.flags.b[1] & kDNSFlag1_RC_Mask);
3505 
3506 	(void)srcport; // Unused
3507 
3508 	debugf("uDNS_ReceiveMsg from %#-15a with "
3509 		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
3510 		srcaddr,
3511 		msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
3512 		msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
3513 		msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
3514 		msg->h.numAdditionals, msg->h.numAdditionals == 1 ? ""     : "s", end - msg->data);
3515 
3516 	if (QR_OP == StdR)
3517 		{
3518 		//if (srcaddr && recvLLQResponse(m, msg, end, srcaddr, srcport)) return;
3519 		if (uDNS_ReceiveTestQuestionResponse(m, msg, end, srcaddr, srcport)) return;
3520 		for (qptr = m->Questions; qptr; qptr = qptr->next)
3521 			if (msg->h.flags.b[0] & kDNSFlag0_TC && mDNSSameOpaque16(qptr->TargetQID, msg->h.id) && m->timenow - qptr->LastQTime < RESPONSE_WINDOW)
3522 				{
3523 				if (!srcaddr) LogMsg("uDNS_ReceiveMsg: TCP DNS response had TC bit set: ignoring");
3524 				else
3525 					{
3526 					// Don't reuse TCP connections. We might have failed over to a different DNS server
3527 					// while the first TCP connection is in progress. We need a new TCP connection to the
3528 					// new DNS server. So, always try to establish a new connection.
3529 					if (qptr->tcp) { DisposeTCPConn(qptr->tcp); qptr->tcp = mDNSNULL; }
3530 					qptr->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_Zero, srcaddr, srcport, mDNSNULL, qptr, mDNSNULL);
3531 					}
3532 				}
3533 		}
3534 
3535 	if (QR_OP == UpdateR)
3536 		{
3537 		mDNSu32 lease = GetPktLease(m, msg, end);
3538 		mDNSs32 expire = m->timenow + (mDNSs32)lease * mDNSPlatformOneSecond;
3539 		mDNSu32 random = mDNSRandom((mDNSs32)lease * mDNSPlatformOneSecond/10);
3540 
3541 		//rcode = kDNSFlag1_RC_ServFail;	// Simulate server failure (rcode 2)
3542 
3543 		// Walk through all the records that matches the messageID. There could be multiple
3544 		// records if we had sent them in a group
3545 		if (m->CurrentRecord)
3546 			LogMsg("uDNS_ReceiveMsg ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3547 		m->CurrentRecord = m->ResourceRecords;
3548 		while (m->CurrentRecord)
3549 			{
3550 			AuthRecord *rptr = m->CurrentRecord;
3551 			m->CurrentRecord = m->CurrentRecord->next;
3552 			if (AuthRecord_uDNS(rptr) && mDNSSameOpaque16(rptr->updateid, msg->h.id))
3553 				{
3554 				err = checkUpdateResult(m, rptr->resrec.name, rcode, msg, end);
3555 				if (!err && rptr->uselease && lease)
3556 					if (rptr->expire - expire >= 0 || rptr->state != regState_UpdatePending)
3557 						{
3558 						rptr->expire = expire;
3559 						rptr->refreshCount = 0;
3560 						}
3561 				// We pass the random value to make sure that if we update multiple
3562 				// records, they all get the same random value
3563 				hndlRecordUpdateReply(m, rptr, err, random);
3564 				}
3565 			}
3566 		}
3567 	debugf("Received unexpected response: ID %d matches no active records", mDNSVal16(msg->h.id));
3568 	}
3569 
3570 // ***************************************************************************
3571 #if COMPILER_LIKES_PRAGMA_MARK
3572 #pragma mark - Query Routines
3573 #endif
3574 
3575 mDNSexport void sendLLQRefresh(mDNS *m, DNSQuestion *q)
3576 	{
3577 	mDNSu8 *end;
3578 	LLQOptData llq;
3579 	mDNSu8 *limit = m->omsg.data + AbsoluteMaxDNSMessageData;
3580 
3581 	if (q->ReqLease)
3582 		if ((q->state == LLQ_Established && q->ntries >= kLLQ_MAX_TRIES) || q->expire - m->timenow < 0)
3583 			{
3584 			LogMsg("Unable to refresh LLQ %##s (%s) - will retry in %d seconds", q->qname.c, DNSTypeName(q->qtype), LLQ_POLL_INTERVAL / mDNSPlatformOneSecond);
3585 			StartLLQPolling(m,q);
3586 			return;
3587 			}
3588 
3589 	llq.vers     = kLLQ_Vers;
3590 	llq.llqOp    = kLLQOp_Refresh;
3591 	llq.err      = q->tcp ? GetLLQEventPort(m, &q->servAddr) : LLQErr_NoError;	// If using TCP tell server what UDP port to send notifications to
3592 	llq.id       = q->id;
3593 	llq.llqlease = q->ReqLease;
3594 
3595 	InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
3596 	end = putLLQ(&m->omsg, m->omsg.data, q, &llq);
3597 	if (!end) { LogMsg("sendLLQRefresh: putLLQ failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3598 
3599 	// Note that we (conditionally) add HINFO and TSIG here, since the question might be going away,
3600 	// so we may not be able to reference it (most importantly it's AuthInfo) when we actually send the message
3601 	end = putHINFO(m, &m->omsg, end, q->AuthInfo, limit);
3602 	if (!end) { LogMsg("sendLLQRefresh: putHINFO failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3603 
3604 	if (PrivateQuery(q))
3605 		{
3606 		DNSDigest_SignMessageHostByteOrder(&m->omsg, &end, q->AuthInfo);
3607 		if (!end) { LogMsg("sendLLQRefresh: DNSDigest_SignMessage failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3608 		}
3609 
3610 	if (PrivateQuery(q) && !q->tcp)
3611 		{
3612 		LogInfo("sendLLQRefresh setting up new TLS session %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3613 		if (!q->nta) { LogMsg("sendLLQRefresh:ERROR!! q->nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3614 		q->tcp = MakeTCPConn(m, &m->omsg, end, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
3615 		}
3616 	else
3617 		{
3618 		mStatus err;
3619 
3620 		// if AuthInfo and AuthInfo->AutoTunnel is set, we use the TCP socket but don't need to pass the AuthInfo as
3621 		// we already protected the message above.
3622 		LogInfo("sendLLQRefresh: using existing %s session %##s (%s)", PrivateQuery(q) ? "TLS" : "UDP",
3623 			q->qname.c, DNSTypeName(q->qtype));
3624 
3625 		err = mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, q->tcp ? q->tcp->sock : mDNSNULL, mDNSNULL);
3626 		if (err)
3627 			{
3628 			LogMsg("sendLLQRefresh: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err);
3629 			if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
3630 			}
3631 		}
3632 
3633 	q->ntries++;
3634 
3635 	debugf("sendLLQRefresh ntries %d %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
3636 
3637 	q->LastQTime = m->timenow;
3638 	SetNextQueryTime(m, q);
3639 	}
3640 
3641 mDNSexport void LLQGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
3642 	{
3643 	DNSQuestion *q = (DNSQuestion *)zoneInfo->ZoneDataContext;
3644 
3645 	mDNS_Lock(m);
3646 
3647 	// If we get here it means that the GetZoneData operation has completed.
3648 	// We hold on to the zone data if it is AutoTunnel as we use the hostname
3649 	// in zoneInfo during the TLS connection setup.
3650 	q->servAddr = zeroAddr;
3651 	q->servPort = zeroIPPort;
3652 
3653 	if (!err && zoneInfo && !mDNSIPPortIsZero(zoneInfo->Port) && !mDNSAddressIsZero(&zoneInfo->Addr) && zoneInfo->Host.c[0])
3654 		{
3655 		q->servAddr = zoneInfo->Addr;
3656 		q->servPort = zoneInfo->Port;
3657 		if (!PrivateQuery(q))
3658 			{
3659 			// We don't need the zone data as we use it only for the Host information which we
3660 			// don't need if we are not going to use TLS connections.
3661 			if (q->nta)
3662 				{
3663 				if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
3664 				CancelGetZoneData(m, q->nta);
3665 				q->nta = mDNSNULL;
3666 				}
3667 			}
3668 		q->ntries = 0;
3669 		debugf("LLQGotZoneData %#a:%d", &q->servAddr, mDNSVal16(q->servPort));
3670 		startLLQHandshake(m, q);
3671 		}
3672 	else
3673 		{
3674 		if (q->nta)
3675 			{
3676 			if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
3677 			CancelGetZoneData(m, q->nta);
3678 			q->nta = mDNSNULL;
3679 			}
3680 		StartLLQPolling(m,q);
3681 		if (err == mStatus_NoSuchNameErr)
3682 			{
3683 			// this actually failed, so mark it by setting address to all ones
3684 			q->servAddr.type = mDNSAddrType_IPv4;
3685 			q->servAddr.ip.v4 = onesIPv4Addr;
3686 			}
3687 		}
3688 
3689 	mDNS_Unlock(m);
3690 	}
3691 
3692 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
3693 mDNSlocal void PrivateQueryGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
3694 	{
3695 	DNSQuestion *q = (DNSQuestion *) zoneInfo->ZoneDataContext;
3696 
3697 	LogInfo("PrivateQueryGotZoneData %##s (%s) err %d Zone %##s Private %d", q->qname.c, DNSTypeName(q->qtype), err, zoneInfo->ZoneName.c, zoneInfo->ZonePrivate);
3698 
3699 	if (q->nta != zoneInfo) LogMsg("PrivateQueryGotZoneData:ERROR!!: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
3700 
3701 	if (err || !zoneInfo || mDNSAddressIsZero(&zoneInfo->Addr) || mDNSIPPortIsZero(zoneInfo->Port) || !zoneInfo->Host.c[0])
3702 		{
3703 		LogInfo("PrivateQueryGotZoneData: ERROR!! %##s (%s) invoked with error code %d %p %#a:%d",
3704 			q->qname.c, DNSTypeName(q->qtype), err, zoneInfo,
3705 			zoneInfo ? &zoneInfo->Addr : mDNSNULL,
3706 			zoneInfo ? mDNSVal16(zoneInfo->Port) : 0);
3707 		CancelGetZoneData(m, q->nta);
3708 		q->nta = mDNSNULL;
3709 		return;
3710 		}
3711 
3712 	if (!zoneInfo->ZonePrivate)
3713 		{
3714 		debugf("Private port lookup failed -- retrying without TLS -- %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3715 		q->AuthInfo      = mDNSNULL;		// Clear AuthInfo so we try again non-private
3716 		q->ThisQInterval = InitialQuestionInterval;
3717 		q->LastQTime     = m->timenow - q->ThisQInterval;
3718 		CancelGetZoneData(m, q->nta);
3719 		q->nta = mDNSNULL;
3720 		mDNS_Lock(m);
3721 		SetNextQueryTime(m, q);
3722 		mDNS_Unlock(m);
3723 		return;
3724 		// Next call to uDNS_CheckCurrentQuestion() will do this as a non-private query
3725 		}
3726 
3727 	if (!PrivateQuery(q))
3728 		{
3729 		LogMsg("PrivateQueryGotZoneData: ERROR!! Not a private query %##s (%s) AuthInfo %p", q->qname.c, DNSTypeName(q->qtype), q->AuthInfo);
3730 		CancelGetZoneData(m, q->nta);
3731 		q->nta = mDNSNULL;
3732 		return;
3733 		}
3734 
3735 	q->TargetQID = mDNS_NewMessageID(m);
3736 	if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
3737 	if (!q->nta) { LogMsg("PrivateQueryGotZoneData:ERROR!! nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3738 	q->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_UseTLS, &zoneInfo->Addr, zoneInfo->Port, &q->nta->Host, q, mDNSNULL);
3739 	if (q->nta) { CancelGetZoneData(m, q->nta); q->nta = mDNSNULL; }
3740 	}
3741 
3742 // ***************************************************************************
3743 #if COMPILER_LIKES_PRAGMA_MARK
3744 #pragma mark - Dynamic Updates
3745 #endif
3746 
3747 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
3748 mDNSexport void RecordRegistrationGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneData)
3749 	{
3750 	AuthRecord *newRR = (AuthRecord*)zoneData->ZoneDataContext;
3751 	AuthRecord *ptr;
3752 	int c1, c2;
3753 
3754 	if (newRR->nta != zoneData)
3755 		LogMsg("RecordRegistrationGotZoneData: nta (%p) != zoneData (%p)  %##s (%s)", newRR->nta, zoneData, newRR->resrec.name->c, DNSTypeName(newRR->resrec.rrtype));
3756 
3757 	if (m->mDNS_busy != m->mDNS_reentrancy)
3758 		LogMsg("RecordRegistrationGotZoneData: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
3759 
3760 	// make sure record is still in list (!!!)
3761 	for (ptr = m->ResourceRecords; ptr; ptr = ptr->next) if (ptr == newRR) break;
3762 	if (!ptr)
3763 		{
3764 		LogMsg("RecordRegistrationGotZoneData - RR no longer in list.  Discarding.");
3765 		CancelGetZoneData(m, newRR->nta);
3766 		newRR->nta = mDNSNULL;
3767 		return;
3768 		}
3769 
3770 	// check error/result
3771 	if (err)
3772 		{
3773 		if (err != mStatus_NoSuchNameErr) LogMsg("RecordRegistrationGotZoneData: error %d", err);
3774 		CancelGetZoneData(m, newRR->nta);
3775 		newRR->nta = mDNSNULL;
3776 		return;
3777 		}
3778 
3779 	if (!zoneData) { LogMsg("ERROR: RecordRegistrationGotZoneData invoked with NULL result and no error"); return; }
3780 
3781 	if (newRR->resrec.rrclass != zoneData->ZoneClass)
3782 		{
3783 		LogMsg("ERROR: New resource record's class (%d) does not match zone class (%d)", newRR->resrec.rrclass, zoneData->ZoneClass);
3784 		CancelGetZoneData(m, newRR->nta);
3785 		newRR->nta = mDNSNULL;
3786 		return;
3787 		}
3788 
3789 	// Don't try to do updates to the root name server.
3790 	// We might be tempted also to block updates to any single-label name server (e.g. com, edu, net, etc.) but some
3791 	// organizations use their own private pseudo-TLD, like ".home", etc, and we don't want to block that.
3792 	if (zoneData->ZoneName.c[0] == 0)
3793 		{
3794 		LogInfo("RecordRegistrationGotZoneData: No name server found claiming responsibility for \"%##s\"!", newRR->resrec.name->c);
3795 		CancelGetZoneData(m, newRR->nta);
3796 		newRR->nta = mDNSNULL;
3797 		return;
3798 		}
3799 
3800 	// Store discovered zone data
3801 	c1 = CountLabels(newRR->resrec.name);
3802 	c2 = CountLabels(&zoneData->ZoneName);
3803 	if (c2 > c1)
3804 		{
3805 		LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" is longer than \"%##s\"", zoneData->ZoneName.c, newRR->resrec.name->c);
3806 		CancelGetZoneData(m, newRR->nta);
3807 		newRR->nta = mDNSNULL;
3808 		return;
3809 		}
3810 	newRR->zone = SkipLeadingLabels(newRR->resrec.name, c1-c2);
3811 	if (!SameDomainName(newRR->zone, &zoneData->ZoneName))
3812 		{
3813 		LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" does not match \"%##s\" for \"%##s\"", newRR->zone->c, zoneData->ZoneName.c, newRR->resrec.name->c);
3814 		CancelGetZoneData(m, newRR->nta);
3815 		newRR->nta = mDNSNULL;
3816 		return;
3817 		}
3818 
3819 	if (mDNSIPPortIsZero(zoneData->Port) || mDNSAddressIsZero(&zoneData->Addr) || !zoneData->Host.c[0])
3820 		{
3821 		LogInfo("RecordRegistrationGotZoneData: No _dns-update._udp service found for \"%##s\"!", newRR->resrec.name->c);
3822 		CancelGetZoneData(m, newRR->nta);
3823 		newRR->nta = mDNSNULL;
3824 		return;
3825 		}
3826 
3827 	newRR->Private      = zoneData->ZonePrivate;
3828 	debugf("RecordRegistrationGotZoneData: Set zone information for %##s %##s to %#a:%d",
3829 		newRR->resrec.name->c, zoneData->ZoneName.c, &zoneData->Addr, mDNSVal16(zoneData->Port));
3830 
3831 	// If we are deregistering, uDNS_DeregisterRecord will do that as it has the zone data now.
3832 	if (newRR->state == regState_DeregPending)
3833 		{
3834 		mDNS_Lock(m);
3835 		uDNS_DeregisterRecord(m, newRR);
3836 		mDNS_Unlock(m);
3837 		return;
3838 		}
3839 
3840 	if (newRR->resrec.rrtype == kDNSType_SRV)
3841 		{
3842 		const domainname *target;
3843 		// Reevaluate the target always as NAT/Target could have changed while
3844 		// we were fetching zone data.
3845 		mDNS_Lock(m);
3846 		target = GetServiceTarget(m, newRR);
3847 		mDNS_Unlock(m);
3848 		if (!target || target->c[0] == 0)
3849 			{
3850 			domainname *t = GetRRDomainNameTarget(&newRR->resrec);
3851 			LogInfo("RecordRegistrationGotZoneData - no target for %##s", newRR->resrec.name->c);
3852 			if (t) t->c[0] = 0;
3853 			newRR->resrec.rdlength = newRR->resrec.rdestimate = 0;
3854 			newRR->state = regState_NoTarget;
3855 			CancelGetZoneData(m, newRR->nta);
3856 			newRR->nta = mDNSNULL;
3857 			return;
3858 			}
3859 		}
3860 	// If we have non-zero service port (always?)
3861 	// and a private address, and update server is non-private
3862 	// and this service is AutoTarget
3863 	// then initiate a NAT mapping request. On completion it will do SendRecordRegistration() for us
3864 	if (newRR->resrec.rrtype == kDNSType_SRV && !mDNSIPPortIsZero(newRR->resrec.rdata->u.srv.port) &&
3865 		mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && newRR->nta && !mDNSAddrIsRFC1918(&newRR->nta->Addr) &&
3866 		newRR->AutoTarget == Target_AutoHostAndNATMAP)
3867 		{
3868 		DomainAuthInfo *AuthInfo;
3869 		AuthInfo = GetAuthInfoForName(m, newRR->resrec.name);
3870 		if (AuthInfo && AuthInfo->AutoTunnel)
3871 			{
3872 			domainname *t = GetRRDomainNameTarget(&newRR->resrec);
3873 			LogMsg("RecordRegistrationGotZoneData: ERROR!! AutoTunnel has Target_AutoHostAndNATMAP for %s", ARDisplayString(m, newRR));
3874 			if (t) t->c[0] = 0;
3875 			newRR->resrec.rdlength = newRR->resrec.rdestimate = 0;
3876 			newRR->state = regState_NoTarget;
3877 			CancelGetZoneData(m, newRR->nta);
3878 			newRR->nta = mDNSNULL;
3879 			return;
3880 			}
3881 		// During network transitions, we are called multiple times in different states. Setup NAT
3882 		// state just once for this record.
3883 		if (!newRR->NATinfo.clientContext)
3884 			{
3885 			LogInfo("RecordRegistrationGotZoneData StartRecordNatMap %s", ARDisplayString(m, newRR));
3886 			newRR->state = regState_NATMap;
3887 			StartRecordNatMap(m, newRR);
3888 			return;
3889 			}
3890 		else LogInfo("RecordRegistrationGotZoneData: StartRecordNatMap for %s, state %d, context %p", ARDisplayString(m, newRR), newRR->state, newRR->NATinfo.clientContext);
3891 		}
3892 	mDNS_Lock(m);
3893 	// We want IsRecordMergeable to check whether it is a record whose update can be
3894 	// sent with others. We set the time before we call IsRecordMergeable, so that
3895 	// it does not fail this record based on time. We are interested in other checks
3896 	// at this time. If a previous update resulted in error, then don't reset the
3897 	// interval. Preserve the back-off so that we don't keep retrying aggressively.
3898 	if (newRR->updateError == mStatus_NoError)
3899 		{
3900 		newRR->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3901 		newRR->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3902 		}
3903 	if (IsRecordMergeable(m, newRR, m->timenow + MERGE_DELAY_TIME))
3904 		{
3905 		// Delay the record registration by MERGE_DELAY_TIME so that we can merge them
3906 		// into one update
3907 		LogInfo("RecordRegistrationGotZoneData: Delayed registration for %s", ARDisplayString(m, newRR));
3908 		newRR->LastAPTime += MERGE_DELAY_TIME;
3909 		}
3910 	mDNS_Unlock(m);
3911 	}
3912 
3913 mDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr)
3914 	{
3915 	mDNSu8 *ptr = m->omsg.data;
3916 	mDNSu8 *limit;
3917 	DomainAuthInfo *AuthInfo;
3918 
3919 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
3920 		LogMsg("SendRecordDeRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
3921 
3922 	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
3923 		{
3924 		LogMsg("SendRecordDeRegistration: No zone info for Resource record %s RecordType %d", ARDisplayString(m, rr), rr->resrec.RecordType);
3925 		return;
3926 		}
3927 
3928 	limit = ptr + AbsoluteMaxDNSMessageData;
3929 	AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
3930 	limit -= RRAdditionalSize(m, AuthInfo);
3931 
3932 	rr->updateid = mDNS_NewMessageID(m);
3933 	InitializeDNSMessage(&m->omsg.h, rr->updateid, UpdateReqFlags);
3934 
3935 	// set zone
3936 	ptr = putZone(&m->omsg, ptr, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
3937 	if (!ptr) goto exit;
3938 
3939 	ptr = BuildUpdateMessage(m, ptr, rr, limit);
3940 
3941 	if (!ptr) goto exit;
3942 
3943 	if (rr->Private)
3944 		{
3945 		LogInfo("SendRecordDeregistration TCP %p %s", rr->tcp, ARDisplayString(m, rr));
3946 		if (rr->tcp) LogInfo("SendRecordDeregistration: Disposing existing TCP connection for %s", ARDisplayString(m, rr));
3947 		if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
3948 		if (!rr->nta) { LogMsg("SendRecordDeregistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
3949 		rr->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &rr->nta->Addr, rr->nta->Port, &rr->nta->Host, mDNSNULL, rr);
3950 		}
3951 	else
3952 		{
3953 		mStatus err;
3954 		LogInfo("SendRecordDeregistration UDP %s", ARDisplayString(m, rr));
3955 		if (!rr->nta) { LogMsg("SendRecordDeregistration:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
3956 		err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &rr->nta->Addr, rr->nta->Port, mDNSNULL, GetAuthInfoForName_internal(m, rr->resrec.name));
3957 		if (err) debugf("ERROR: SendRecordDeregistration - mDNSSendDNSMessage - %d", err);
3958 		//if (rr->state == regState_DeregPending) CompleteDeregistration(m, rr);		// Don't touch rr after this
3959 		}
3960 	SetRecordRetry(m, rr, 0);
3961 	return;
3962 exit:
3963 	LogMsg("SendRecordDeregistration: Error formatting message for %s", ARDisplayString(m, rr));
3964 	}
3965 
3966 mDNSexport mStatus uDNS_DeregisterRecord(mDNS *const m, AuthRecord *const rr)
3967 	{
3968 	DomainAuthInfo *info;
3969 
3970 	LogInfo("uDNS_DeregisterRecord: Resource Record %s, state %d", ARDisplayString(m, rr), rr->state);
3971 
3972 	switch (rr->state)
3973 		{
3974 		case regState_Refresh:
3975 		case regState_Pending:
3976 		case regState_UpdatePending:
3977 		case regState_Registered: break;
3978 		case regState_DeregPending: break;
3979 
3980 		case regState_NATError:
3981 		case regState_NATMap:
3982 		// A record could be in NoTarget to start with if the corresponding SRV record could not find a target.
3983 		// It is also possible to reenter the NoTarget state when we move to a network with a NAT that has
3984 		// no NAT-PMP/UPnP support. In that case before we entered NoTarget, we already deregistered with
3985 		// the server.
3986 		case regState_NoTarget:
3987 		case regState_Unregistered:
3988 		case regState_Zero:
3989 		default:
3990 			LogInfo("uDNS_DeregisterRecord: State %d for %##s type %s", rr->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
3991 			// This function may be called during sleep when there are no sleep proxy servers
3992 			if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) CompleteDeregistration(m, rr);
3993 			return mStatus_NoError;
3994 		}
3995 
3996 	// If a current group registration is pending, we can't send this deregisration till that registration
3997 	// has reached the server i.e., the ordering is important. Previously, if we did not send this
3998 	// registration in a group, then the previous connection will be torn down as part of sending the
3999 	// deregistration. If we send this in a group, we need to locate the resource record that was used
4000 	// to send this registration and terminate that connection. This means all the updates on that might
4001 	// be lost (assuming the response is not waiting for us at the socket) and the retry will send the
4002 	// update again sometime in the near future.
4003 	//
4004 	// NOTE: SSL handshake failures normally free the TCP connection immediately. Hence, you may not
4005 	// find the TCP below there. This case can happen only when tcp is trying to actively retransmit
4006 	// the request or SSL negotiation taking time i.e resource record is actively trying to get the
4007 	// message to the server. During that time a deregister has to happen.
4008 
4009 	if (!mDNSOpaque16IsZero(rr->updateid))
4010 		{
4011 		AuthRecord *anchorRR;
4012 		mDNSBool found = mDNSfalse;
4013 		for (anchorRR = m->ResourceRecords; anchorRR; anchorRR = anchorRR->next)
4014 			{
4015 			if (AuthRecord_uDNS(rr) && mDNSSameOpaque16(anchorRR->updateid, rr->updateid) && anchorRR->tcp)
4016 				{
4017 				LogInfo("uDNS_DeregisterRecord: Found Anchor RR %s terminated", ARDisplayString(m, anchorRR));
4018 				if (found)
4019 					LogMsg("uDNS_DeregisterRecord: ERROR: Another anchorRR %s found", ARDisplayString(m, anchorRR));
4020 				DisposeTCPConn(anchorRR->tcp);
4021 				anchorRR->tcp = mDNSNULL;
4022 				found = mDNStrue;
4023 				}
4024 			}
4025 		if (!found) LogInfo("uDNSDeregisterRecord: Cannot find the anchor Resource Record for %s, not an error", ARDisplayString(m, rr));
4026 		}
4027 
4028 	// Retry logic for deregistration should be no different from sending registration the first time.
4029 	// Currently ThisAPInterval most likely is set to the refresh interval
4030 	rr->state          = regState_DeregPending;
4031 	rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
4032 	rr->LastAPTime     = m->timenow - INIT_RECORD_REG_INTERVAL;
4033 	info = GetAuthInfoForName_internal(m, rr->resrec.name);
4034 	if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
4035 		{
4036 		// Delay the record deregistration by MERGE_DELAY_TIME so that we can merge them
4037 		// into one update. If the domain is being deleted, delay by 2 * MERGE_DELAY_TIME
4038 		// so that we can merge all the AutoTunnel records and the service records in
4039 		// one update (they get deregistered a little apart)
4040 		if (info && info->deltime) rr->LastAPTime += (2 * MERGE_DELAY_TIME);
4041 		else rr->LastAPTime += MERGE_DELAY_TIME;
4042 		}
4043 	// IsRecordMergeable could have returned false for several reasons e.g., DontMerge is set or
4044 	// no zone information. Most likely it is the latter, CheckRecordUpdates will fetch the zone
4045 	// data when it encounters this record.
4046 
4047 	if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4048 		m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
4049 
4050 	return mStatus_NoError;
4051 	}
4052 
4053 mDNSexport mStatus uDNS_UpdateRecord(mDNS *m, AuthRecord *rr)
4054 	{
4055 	LogInfo("uDNS_UpdateRecord: Resource Record %##s, state %d", rr->resrec.name->c, rr->state);
4056 	switch(rr->state)
4057 		{
4058 		case regState_DeregPending:
4059 		case regState_Unregistered:
4060 			// not actively registered
4061 			goto unreg_error;
4062 
4063 		case regState_NATMap:
4064 		case regState_NoTarget:
4065 			// change rdata directly since it hasn't been sent yet
4066 			if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->resrec.rdata, rr->resrec.rdlength);
4067 			SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
4068 			rr->NewRData = mDNSNULL;
4069 			return mStatus_NoError;
4070 
4071 		case regState_Pending:
4072 		case regState_Refresh:
4073 		case regState_UpdatePending:
4074 			// registration in-flight. queue rdata and return
4075 			if (rr->QueuedRData && rr->UpdateCallback)
4076 				// if unsent rdata is already queued, free it before we replace it
4077 				rr->UpdateCallback(m, rr, rr->QueuedRData, rr->QueuedRDLen);
4078 			rr->QueuedRData = rr->NewRData;
4079 			rr->QueuedRDLen = rr->newrdlength;
4080 			rr->NewRData = mDNSNULL;
4081 			return mStatus_NoError;
4082 
4083 		case regState_Registered:
4084 			rr->OrigRData = rr->resrec.rdata;
4085 			rr->OrigRDLen = rr->resrec.rdlength;
4086 			rr->InFlightRData = rr->NewRData;
4087 			rr->InFlightRDLen = rr->newrdlength;
4088 			rr->NewRData = mDNSNULL;
4089 			rr->state = regState_UpdatePending;
4090 			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
4091 			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
4092 			return mStatus_NoError;
4093 
4094 		case regState_NATError:
4095 			LogMsg("ERROR: uDNS_UpdateRecord called for record %##s with bad state regState_NATError", rr->resrec.name->c);
4096 			return mStatus_UnknownErr;	// states for service records only
4097 
4098 		default: LogMsg("uDNS_UpdateRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
4099 		}
4100 
4101 	unreg_error:
4102 	LogMsg("uDNS_UpdateRecord: Requested update of record %##s type %d, in erroneous state %d",
4103 		   rr->resrec.name->c, rr->resrec.rrtype, rr->state);
4104 	return mStatus_Invalid;
4105 	}
4106 
4107 // ***************************************************************************
4108 #if COMPILER_LIKES_PRAGMA_MARK
4109 #pragma mark - Periodic Execution Routines
4110 #endif
4111 
4112 mDNSlocal const mDNSu8 *mDNS_WABLabels[] =
4113 	{
4114 	(const mDNSu8 *)"\001b",
4115 	(const mDNSu8 *)"\002db",
4116 	(const mDNSu8 *)"\002lb",
4117 	(const mDNSu8 *)"\001r",
4118 	(const mDNSu8 *)"\002dr",
4119 	(const mDNSu8 *)mDNSNULL,
4120 	};
4121 
4122 // Returns true if it is a WAB question
4123 mDNSlocal mDNSBool WABQuestion(const domainname *qname)
4124 	{
4125  	const mDNSu8 *sd = (const mDNSu8 *)"\007_dns-sd";
4126 	const mDNSu8 *prot = (const mDNSu8 *)"\004_udp";
4127 	const domainname *d = qname;
4128 	const mDNSu8 *label;
4129 	int i = 0;
4130 
4131 	// We need at least 3 labels (WAB prefix) + one more label to make
4132 	// a meaningful WAB query
4133 	if (CountLabels(qname) < 4) { debugf("WABQuestion: question %##s, not enough labels", qname->c); return mDNSfalse; }
4134 
4135 	label = (const mDNSu8 *)d;
4136 	while (mDNS_WABLabels[i] != (const mDNSu8 *)mDNSNULL)
4137 		{
4138 		if (SameDomainLabel(mDNS_WABLabels[i], label)) {debugf("WABquestion: WAB question %##s, label1 match", qname->c); break;}
4139 		i++;
4140 		}
4141 	if (mDNS_WABLabels[i] == (const mDNSu8 *)mDNSNULL)
4142 		{
4143 		debugf("WABquestion: Not a WAB question %##s, label1 mismatch", qname->c);
4144 		return mDNSfalse;
4145 		}
4146 	// CountLabels already verified the number of labels
4147 	d = (const domainname *)(d->c + 1 + d->c[0]);	// Second Label
4148 	label = (const mDNSu8 *)d;
4149 	if (!SameDomainLabel(label, sd)){ debugf("WABquestion: Not a WAB question %##s, label2 mismatch", qname->c);return(mDNSfalse); }
4150 	debugf("WABquestion: WAB question %##s, label2 match", qname->c);
4151 
4152 	d = (const domainname *)(d->c + 1 + d->c[0]); 	// Third Label
4153 	label = (const mDNSu8 *)d;
4154 	if (!SameDomainLabel(label, prot)){ debugf("WABquestion: Not a WAB question %##s, label3 mismatch", qname->c);return(mDNSfalse); }
4155 	debugf("WABquestion: WAB question %##s, label3 match", qname->c);
4156 
4157 	LogInfo("WABquestion: Question %##s is a WAB question", qname->c);
4158 
4159 	return mDNStrue;
4160 	}
4161 
4162 // The question to be checked is not passed in as an explicit parameter;
4163 // instead it is implicit that the question to be checked is m->CurrentQuestion.
4164 mDNSexport void uDNS_CheckCurrentQuestion(mDNS *const m)
4165 	{
4166 	DNSQuestion *q = m->CurrentQuestion;
4167 	if (m->timenow - NextQSendTime(q) < 0) return;
4168 
4169 	if (q->LongLived)
4170 		{
4171 		switch (q->state)
4172 			{
4173 			case LLQ_InitialRequest:   startLLQHandshake(m, q); break;
4174 			case LLQ_SecondaryRequest:
4175 									   // For PrivateQueries, we need to start the handshake again as we don't do the Challenge/Response step
4176 									   if (PrivateQuery(q))
4177 										   startLLQHandshake(m, q);
4178 									   else
4179 									  	   sendChallengeResponse(m, q, mDNSNULL);
4180 									   break;
4181 			case LLQ_Established:      sendLLQRefresh(m, q); break;
4182 			case LLQ_Poll:             break;	// Do nothing (handled below)
4183 			}
4184 		}
4185 
4186 	// We repeat the check above (rather than just making this the "else" case) because startLLQHandshake can change q->state to LLQ_Poll
4187 	if (!(q->LongLived && q->state != LLQ_Poll))
4188 		{
4189 		if (q->unansweredQueries >= MAX_UCAST_UNANSWERED_QUERIES)
4190 			{
4191 			DNSServer *orig = q->qDNSServer;
4192 			if (orig)
4193 				LogInfo("uDNS_CheckCurrentQuestion: Sent %d unanswered queries for %##s (%s) to %#a:%d (%##s)",
4194 					q->unansweredQueries, q->qname.c, DNSTypeName(q->qtype), &orig->addr, mDNSVal16(orig->port), orig->domain.c);
4195 
4196 			PenalizeDNSServer(m, q);
4197 			q->noServerResponse = 1;
4198 			}
4199 		// There are two cases here.
4200 		//
4201 		// 1. We have only one DNS server for this question. It is not responding even after we sent MAX_UCAST_UNANSWERED_QUERIES.
4202 		//    In that case, we need to keep retrying till we get a response. But we need to backoff as we retry. We set
4203 		//    noServerResponse in the block above and below we do not touch the question interval. When we come here, we
4204 		//    already waited for the response. We need to send another query right at this moment. We do that below by
4205 		//    reinitializing dns servers and reissuing the query.
4206 		//
4207 		// 2. We have more than one DNS server. If at least one server did not respond, we would have set noServerResponse
4208 		//    either now (the last server in the list) or before (non-last server in the list). In either case, if we have
4209 		//    reached the end of DNS server list, we need to try again from the beginning. Ideally we should try just the
4210 		//    servers that did not respond, but for simplicity we try all the servers. Once we reached the end of list, we
4211 		//    set triedAllServersOnce so that we don't try all the servers aggressively. See PenalizeDNSServer.
4212 		if (!q->qDNSServer && q->noServerResponse)
4213 			{
4214 			DNSServer *new;
4215 			DNSQuestion *qptr;
4216 			q->triedAllServersOnce = 1;
4217 			// Re-initialize all DNS servers for this question. If we have a DNSServer, DNSServerChangeForQuestion will
4218 			// handle all the work including setting the new DNS server.
4219 			SetValidDNSServers(m, q);
4220 			new = GetServerForQuestion(m, q);
4221 			if (new)
4222 				{
4223 				LogInfo("uDNS_checkCurrentQuestion: Retrying question %p %##s (%s) DNS Server %#a:%d ThisQInterval %d",
4224 					q, q->qname.c, DNSTypeName(q->qtype), new ? &new->addr : mDNSNULL, mDNSVal16(new ? new->port : zeroIPPort), q->ThisQInterval);
4225 				DNSServerChangeForQuestion(m, q, new);
4226 				}
4227 			for (qptr = q->next ; qptr; qptr = qptr->next)
4228 				if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
4229 			}
4230 		if (q->qDNSServer && q->qDNSServer->teststate != DNSServer_Disabled)
4231 			{
4232 			mDNSu8 *end = m->omsg.data;
4233 			mStatus err = mStatus_NoError;
4234 			mDNSBool private = mDNSfalse;
4235 
4236 			InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
4237 
4238 			if (q->qDNSServer->teststate != DNSServer_Untested || NoTestQuery(q))
4239 				{
4240 				end = putQuestion(&m->omsg, m->omsg.data, m->omsg.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
4241 				private = PrivateQuery(q);
4242 				}
4243 			else if (m->timenow - q->qDNSServer->lasttest >= INIT_UCAST_POLL_INTERVAL)	// Make sure at least three seconds has elapsed since last test query
4244 				{
4245 				LogInfo("Sending DNS test query to %#a:%d", &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port));
4246 				q->ThisQInterval = INIT_UCAST_POLL_INTERVAL / QuestionIntervalStep;
4247 				q->qDNSServer->lasttest = m->timenow;
4248 				end = putQuestion(&m->omsg, m->omsg.data, m->omsg.data + AbsoluteMaxDNSMessageData, DNSRelayTestQuestion, kDNSType_PTR, kDNSClass_IN);
4249 				q->qDNSServer->testid = m->omsg.h.id;
4250 				}
4251 
4252 			if (end > m->omsg.data && (q->qDNSServer->teststate != DNSServer_Failed || NoTestQuery(q)))
4253 				{
4254 				//LogMsg("uDNS_CheckCurrentQuestion %p %d %p %##s (%s)", q, NextQSendTime(q) - m->timenow, private, q->qname.c, DNSTypeName(q->qtype));
4255 				if (private)
4256 					{
4257 					if (q->nta) CancelGetZoneData(m, q->nta);
4258 					q->nta = StartGetZoneData(m, &q->qname, q->LongLived ? ZoneServiceLLQ : ZoneServiceQuery, PrivateQueryGotZoneData, q);
4259 					if (q->state == LLQ_Poll) q->ThisQInterval = (LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10)) / QuestionIntervalStep;
4260 					}
4261 				else
4262 					{
4263 				    debugf("uDNS_CheckCurrentQuestion sending %p %##s (%s) %#a:%d UnansweredQueries %d",
4264 				    	q, q->qname.c, DNSTypeName(q->qtype),
4265 				    	q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL, mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort), q->unansweredQueries);
4266 					if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
4267 					if (!q->LocalSocket) err = mStatus_NoMemoryErr;	// If failed to make socket (should be very rare), we'll try again next time
4268 					else err = mDNSSendDNSMessage(m, &m->omsg, end, q->qDNSServer->interface, q->LocalSocket, &q->qDNSServer->addr, q->qDNSServer->port, mDNSNULL, mDNSNULL);
4269 					}
4270 				}
4271 
4272 			if (err) debugf("ERROR: uDNS_idle - mDNSSendDNSMessage - %d", err); // surpress syslog messages if we have no network
4273 			else
4274 				{
4275 				q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;	// Only increase interval if send succeeded
4276 				q->unansweredQueries++;
4277 				if (q->ThisQInterval > MAX_UCAST_POLL_INTERVAL)
4278 					q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
4279 				if (private && q->state != LLQ_Poll)
4280 					{
4281 					// We don't want to retransmit too soon. Hence, we always schedule our first
4282 					// retransmisson at 3 seconds rather than one second
4283 					if (q->ThisQInterval < (3 * mDNSPlatformOneSecond))
4284 						q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;
4285 					if (q->ThisQInterval > LLQ_POLL_INTERVAL)
4286 						q->ThisQInterval = LLQ_POLL_INTERVAL;
4287 					LogInfo("uDNS_CheckCurrentQuestion: private non polling question for %##s (%s) will be retried in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
4288 					}
4289 				debugf("Increased ThisQInterval to %d for %##s (%s)", q->ThisQInterval, q->qname.c, DNSTypeName(q->qtype));
4290 				}
4291 			q->LastQTime = m->timenow;
4292 			SetNextQueryTime(m, q);
4293 			}
4294 		else
4295 			{
4296 			// If we have no server for this query, or the only server is a disabled one, then we deliver
4297 			// a transient failure indication to the client. This is important for things like iPhone
4298 			// where we want to return timely feedback to the user when no network is available.
4299 			// After calling MakeNegativeCacheRecord() we store the resulting record in the
4300 			// cache so that it will be visible to other clients asking the same question.
4301 			// (When we have a group of identical questions, only the active representative of the group gets
4302 			// passed to uDNS_CheckCurrentQuestion -- we only want one set of query packets hitting the wire --
4303 			// but we want *all* of the questions to get answer callbacks.)
4304 
4305 			CacheRecord *rr;
4306 			const mDNSu32 slot = HashSlot(&q->qname);
4307 			CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
4308 			if (cg)
4309 				for (rr = cg->members; rr; rr=rr->next)
4310 					if (SameNameRecordAnswersQuestion(&rr->resrec, q)) mDNS_PurgeCacheResourceRecord(m, rr);
4311 
4312 			if (!q->qDNSServer)
4313 				{
4314 				if (!mDNSOpaque64IsZero(&q->validDNSServers))
4315 					LogMsg("uDNS_CheckCurrentQuestion: ERROR!!: valid DNSServer bits not zero 0x%x, 0x%x for question %##s (%s)",
4316 						q->validDNSServers.l[1], q->validDNSServers.l[0], q->qname.c, DNSTypeName(q->qtype));
4317 				// If we reached the end of list while picking DNS servers, then we don't want to deactivate the
4318 				// question. Try after 60 seconds. We find this by looking for valid DNSServers for this question,
4319 				// if we find any, then we must have tried them before we came here. This avoids maintaining
4320 				// another state variable to see if we had valid DNS servers for this question.
4321 				SetValidDNSServers(m, q);
4322 				if (mDNSOpaque64IsZero(&q->validDNSServers))
4323 					{
4324 					LogInfo("uDNS_CheckCurrentQuestion: no DNS server for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4325 					q->ThisQInterval = 0;
4326 					}
4327 				else
4328 					{
4329 					DNSQuestion *qptr;
4330 					// Pretend that we sent this question. As this is an ActiveQuestion, the NextScheduledQuery should
4331 					// be set properly. Also, we need to properly backoff in cases where we don't set the question to
4332 					// MaxQuestionInterval when we answer the question e.g., LongLived, we need to keep backing off
4333 					q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;
4334 					q->LastQTime = m->timenow;
4335 					SetNextQueryTime(m, q);
4336 					// Pick a new DNS server now. Otherwise, when the cache is 80% of its expiry, we will try
4337 					// to send a query and come back to the same place here and log the above message.
4338 					q->qDNSServer = GetServerForQuestion(m, q);
4339 					for (qptr = q->next ; qptr; qptr = qptr->next)
4340 						if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
4341 					LogInfo("uDNS_checkCurrentQuestion: Tried all DNS servers, retry question %p SuppressUnusable %d %##s (%s) with DNS Server %#a:%d after 60 seconds, ThisQInterval %d",
4342 						q, q->SuppressUnusable, q->qname.c, DNSTypeName(q->qtype),
4343 						q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL, mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort), q->ThisQInterval);
4344 					}
4345 				}
4346 			else
4347 				{
4348 				q->ThisQInterval = 0;
4349 				LogMsg("uDNS_CheckCurrentQuestion DNS server %#a:%d for %##s is disabled", &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qname.c);
4350 				}
4351 
4352 			// For some of the WAB queries that we generate form within the mDNSResponder, most of the home routers
4353 			// don't understand and return ServFail/NXDomain. In those cases, we don't want to try too often. We try
4354 			// every fifteen minutes in that case
4355 			MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, (WABQuestion(&q->qname) ? 60 * 15 : 60), mDNSInterface_Any, q->qDNSServer);
4356 			q->unansweredQueries = 0;
4357 			// We're already using the m->CurrentQuestion pointer, so CacheRecordAdd can't use it to walk the question list.
4358 			// To solve this problem we set rr->DelayDelivery to a nonzero value (which happens to be 'now') so that we
4359 			// momentarily defer generating answer callbacks until mDNS_Execute time.
4360 			CreateNewCacheEntry(m, slot, cg, NonZeroTime(m->timenow));
4361 			ScheduleNextCacheCheckTime(m, slot, NonZeroTime(m->timenow));
4362 			m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
4363 			// MUST NOT touch m->CurrentQuestion (or q) after this -- client callback could have deleted it
4364 			}
4365 		}
4366 	}
4367 
4368 mDNSexport void CheckNATMappings(mDNS *m)
4369 	{
4370 	mStatus err = mStatus_NoError;
4371 	mDNSBool rfc1918 = mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4);
4372 	mDNSBool HaveRoutable = !rfc1918 && !mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4);
4373 	m->NextScheduledNATOp = m->timenow + 0x3FFFFFFF;
4374 
4375 	if (HaveRoutable) m->ExternalAddress = m->AdvertisedV4.ip.v4;
4376 
4377 	if (m->NATTraversals && rfc1918)			// Do we need to open NAT-PMP socket to receive multicast announcements from router?
4378 		{
4379 		if (m->NATMcastRecvskt == mDNSNULL)		// If we are behind a NAT and the socket hasn't been opened yet, open it
4380 			{
4381 			// we need to log a message if we can't get our socket, but only the first time (after success)
4382 			static mDNSBool needLog = mDNStrue;
4383 			m->NATMcastRecvskt = mDNSPlatformUDPSocket(m, NATPMPAnnouncementPort);
4384 			if (!m->NATMcastRecvskt)
4385 				{
4386 				if (needLog)
4387 					{
4388 					LogMsg("CheckNATMappings: Failed to allocate port 5350 UDP multicast socket for NAT-PMP announcements");
4389 					needLog = mDNSfalse;
4390 					}
4391 				}
4392 			else
4393 				needLog = mDNStrue;
4394 			}
4395 		}
4396 	else										// else, we don't want to listen for announcements, so close them if they're open
4397 		{
4398 		if (m->NATMcastRecvskt) { mDNSPlatformUDPClose(m->NATMcastRecvskt); m->NATMcastRecvskt = mDNSNULL; }
4399 		if (m->SSDPSocket)      { debugf("CheckNATMappings destroying SSDPSocket %p", &m->SSDPSocket); mDNSPlatformUDPClose(m->SSDPSocket); m->SSDPSocket = mDNSNULL; }
4400 		}
4401 
4402 	if (!m->NATTraversals)
4403 		m->retryGetAddr = m->timenow + 0x78000000;
4404 	else
4405 		{
4406 		if (m->timenow - m->retryGetAddr >= 0)
4407 			{
4408 			err = uDNS_SendNATMsg(m, mDNSNULL);		// Will also do UPnP discovery for us, if necessary
4409 			if (!err)
4410 				{
4411 				if      (m->retryIntervalGetAddr < NATMAP_INIT_RETRY)             m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
4412 				else if (m->retryIntervalGetAddr < NATMAP_MAX_RETRY_INTERVAL / 2) m->retryIntervalGetAddr *= 2;
4413 				else                                                              m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
4414 				}
4415 			LogInfo("CheckNATMappings retryGetAddr sent address request err %d interval %d", err, m->retryIntervalGetAddr);
4416 
4417 			// Always update m->retryGetAddr, even if we fail to send the packet. Otherwise in cases where we can't send the packet
4418 			// (like when we have no active interfaces) we'll spin in an infinite loop repeatedly failing to send the packet
4419 			m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
4420 			}
4421 		// Even when we didn't send the GetAddr packet, still need to make sure NextScheduledNATOp is set correctly
4422 		if (m->NextScheduledNATOp - m->retryGetAddr > 0)
4423 			m->NextScheduledNATOp = m->retryGetAddr;
4424 		}
4425 
4426 	if (m->CurrentNATTraversal) LogMsg("WARNING m->CurrentNATTraversal already in use");
4427 	m->CurrentNATTraversal = m->NATTraversals;
4428 
4429 	while (m->CurrentNATTraversal)
4430 		{
4431 		NATTraversalInfo *cur = m->CurrentNATTraversal;
4432 		m->CurrentNATTraversal = m->CurrentNATTraversal->next;
4433 
4434 		if (HaveRoutable)		// If not RFC 1918 address, our own address and port are effectively our external address and port
4435 			{
4436 			cur->ExpiryTime = 0;
4437 			cur->NewResult  = mStatus_NoError;
4438 			}
4439 		else if (cur->Protocol)		// Check if it's time to send port mapping packets
4440 			{
4441 			if (m->timenow - cur->retryPortMap >= 0)						// Time to do something with this mapping
4442 				{
4443 				if (cur->ExpiryTime && cur->ExpiryTime - m->timenow < 0)	// Mapping has expired
4444 					{
4445 					cur->ExpiryTime    = 0;
4446 					cur->retryInterval = NATMAP_INIT_RETRY;
4447 					}
4448 
4449 				//LogMsg("uDNS_SendNATMsg");
4450 				err = uDNS_SendNATMsg(m, cur);
4451 
4452 				if (cur->ExpiryTime)						// If have active mapping then set next renewal time halfway to expiry
4453 					NATSetNextRenewalTime(m, cur);
4454 				else										// else no mapping; use exponential backoff sequence
4455 					{
4456 					if      (cur->retryInterval < NATMAP_INIT_RETRY            ) cur->retryInterval = NATMAP_INIT_RETRY;
4457 					else if (cur->retryInterval < NATMAP_MAX_RETRY_INTERVAL / 2) cur->retryInterval *= 2;
4458 					else                                                         cur->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
4459 					cur->retryPortMap = m->timenow + cur->retryInterval;
4460 					}
4461 				}
4462 
4463 			if (m->NextScheduledNATOp - cur->retryPortMap > 0)
4464 				m->NextScheduledNATOp = cur->retryPortMap;
4465 			}
4466 
4467 		// Notify the client if necessary. We invoke the callback if:
4468 		// (1) we have an ExternalAddress, or we've tried and failed a couple of times to discover it
4469 		// and (2) the client doesn't want a mapping, or the client won't need a mapping, or the client has a successful mapping, or we've tried and failed a couple of times
4470 		// and (3) we have new data to give the client that's changed since the last callback
4471 		// Time line is: Send, Wait 500ms, Send, Wait 1sec, Send, Wait 2sec, Send
4472 		// At this point we've sent three requests without an answer, we've just sent our fourth request,
4473 		// retryIntervalGetAddr is now 4 seconds, which is greater than NATMAP_INIT_RETRY * 8 (2 seconds),
4474 		// so we return an error result to the caller.
4475 		if (!mDNSIPv4AddressIsZero(m->ExternalAddress) || m->retryIntervalGetAddr > NATMAP_INIT_RETRY * 8)
4476 			{
4477 			const mStatus EffectiveResult = cur->NewResult ? cur->NewResult : mDNSv4AddrIsRFC1918(&m->ExternalAddress) ? mStatus_DoubleNAT : mStatus_NoError;
4478 			const mDNSIPPort ExternalPort = HaveRoutable ? cur->IntPort :
4479 				!mDNSIPv4AddressIsZero(m->ExternalAddress) && cur->ExpiryTime ? cur->RequestedPort : zeroIPPort;
4480 			if (!cur->Protocol || HaveRoutable || cur->ExpiryTime || cur->retryInterval > NATMAP_INIT_RETRY * 8)
4481 				if (!mDNSSameIPv4Address(cur->ExternalAddress, m->ExternalAddress) ||
4482 					!mDNSSameIPPort     (cur->ExternalPort,       ExternalPort)    ||
4483 					cur->Result != EffectiveResult)
4484 					{
4485 					//LogMsg("NAT callback %d %d %d", cur->Protocol, cur->ExpiryTime, cur->retryInterval);
4486 					if (cur->Protocol && mDNSIPPortIsZero(ExternalPort) && !mDNSIPv4AddressIsZero(m->Router.ip.v4))
4487 						{
4488 						if (!EffectiveResult)
4489 							LogInfo("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4490 								cur, &m->Router, &m->ExternalAddress, mDNSVal16(cur->IntPort), cur->retryInterval, EffectiveResult);
4491 						else
4492 							LogMsg("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4493 								cur, &m->Router, &m->ExternalAddress, mDNSVal16(cur->IntPort), cur->retryInterval, EffectiveResult);
4494 						}
4495 
4496 					cur->ExternalAddress = m->ExternalAddress;
4497 					cur->ExternalPort    = ExternalPort;
4498 					cur->Lifetime        = cur->ExpiryTime && !mDNSIPPortIsZero(ExternalPort) ?
4499 						(cur->ExpiryTime - m->timenow + mDNSPlatformOneSecond/2) / mDNSPlatformOneSecond : 0;
4500 					cur->Result          = EffectiveResult;
4501 					mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
4502 					if (cur->clientCallback)
4503 						cur->clientCallback(m, cur);
4504 					mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
4505 					// MUST NOT touch cur after invoking the callback
4506 					}
4507 			}
4508 		}
4509 	}
4510 
4511 mDNSlocal mDNSs32 CheckRecordUpdates(mDNS *m)
4512 	{
4513 	AuthRecord *rr;
4514 	mDNSs32 nextevent = m->timenow + 0x3FFFFFFF;
4515 
4516 	CheckGroupRecordUpdates(m);
4517 
4518 	for (rr = m->ResourceRecords; rr; rr = rr->next)
4519 		{
4520 		if (!AuthRecord_uDNS(rr)) continue;
4521 		if (rr->state == regState_NoTarget) {debugf("CheckRecordUpdates: Record %##s in NoTarget", rr->resrec.name->c); continue;}
4522 		// While we are waiting for the port mapping, we have nothing to do. The port mapping callback
4523 		// will take care of this
4524 		if (rr->state == regState_NATMap) {debugf("CheckRecordUpdates: Record %##s in NATMap", rr->resrec.name->c); continue;}
4525 		if (rr->state == regState_Pending || rr->state == regState_DeregPending || rr->state == regState_UpdatePending ||
4526 			rr->state == regState_Refresh || rr->state == regState_Registered)
4527 			{
4528 			if (rr->LastAPTime + rr->ThisAPInterval - m->timenow <= 0)
4529 				{
4530 				if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
4531 				if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
4532 					{
4533 					// Zero out the updateid so that if we have a pending response from the server, it won't
4534 					// be accepted as a valid response. If we accept the response, we might free the new "nta"
4535 					if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
4536 					rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
4537 
4538 					// We have just started the GetZoneData. We need to wait for it to finish. SetRecordRetry here
4539 					// schedules the update timer to fire in the future.
4540 					//
4541 					// There are three cases.
4542 					//
4543 					// 1) When the updates are sent the first time, the first retry is intended to be at three seconds
4544 					//    in the future. But by calling SetRecordRetry here we set it to nine seconds. But it does not
4545 					//    matter because when the answer comes back, RecordRegistrationGotZoneData resets the interval
4546 					//    back to INIT_RECORD_REG_INTERVAL. This also gives enough time for the query.
4547 					//
4548 					// 2) In the case of update errors (updateError), this causes further backoff as
4549 					//    RecordRegistrationGotZoneData does not reset the timer. This is intentional as in the case of
4550 					//    errors, we don't want to update aggressively.
4551 					//
4552 					// 3) We might be refreshing the update. This is very similar to case (1). RecordRegistrationGotZoneData
4553 					//    resets it back to INIT_RECORD_REG_INTERVAL.
4554 					//
4555 					SetRecordRetry(m, rr, 0);
4556 					}
4557 				else if (rr->state == regState_DeregPending) SendRecordDeregistration(m, rr);
4558 				else SendRecordRegistration(m, rr);
4559 				}
4560 			}
4561 		if (nextevent - (rr->LastAPTime + rr->ThisAPInterval) > 0)
4562 			nextevent = (rr->LastAPTime + rr->ThisAPInterval);
4563 		}
4564 	return nextevent;
4565 	}
4566 
4567 mDNSexport void uDNS_Tasks(mDNS *const m)
4568 	{
4569 	mDNSs32 nexte;
4570 	DNSServer *d;
4571 
4572 	m->NextuDNSEvent = m->timenow + 0x3FFFFFFF;
4573 
4574 	nexte = CheckRecordUpdates(m);
4575 	if (m->NextuDNSEvent - nexte > 0)
4576 		m->NextuDNSEvent = nexte;
4577 
4578 	for (d = m->DNSServers; d; d=d->next)
4579 		if (d->penaltyTime)
4580 			{
4581 			if (m->timenow - d->penaltyTime >= 0)
4582 				{
4583 				LogInfo("DNS server %#a:%d out of penalty box", &d->addr, mDNSVal16(d->port));
4584 				d->penaltyTime = 0;
4585 				}
4586 			else
4587 				if (m->NextuDNSEvent - d->penaltyTime > 0)
4588 					m->NextuDNSEvent = d->penaltyTime;
4589 			}
4590 
4591 	if (m->CurrentQuestion)
4592 		LogMsg("uDNS_Tasks ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4593 	m->CurrentQuestion = m->Questions;
4594 	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4595 		{
4596 		DNSQuestion *const q = m->CurrentQuestion;
4597 		if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID))
4598 			{
4599 			uDNS_CheckCurrentQuestion(m);
4600 			if (q == m->CurrentQuestion)
4601 				if (m->NextuDNSEvent - NextQSendTime(q) > 0)
4602 					m->NextuDNSEvent = NextQSendTime(q);
4603 			}
4604 		// If m->CurrentQuestion wasn't modified out from under us, advance it now
4605 		// We can't do this at the start of the loop because uDNS_CheckCurrentQuestion()
4606 		// depends on having m->CurrentQuestion point to the right question
4607 		if (m->CurrentQuestion == q)
4608 			m->CurrentQuestion = q->next;
4609 		}
4610 	m->CurrentQuestion = mDNSNULL;
4611 	}
4612 
4613 // ***************************************************************************
4614 #if COMPILER_LIKES_PRAGMA_MARK
4615 #pragma mark - Startup, Shutdown, and Sleep
4616 #endif
4617 
4618 mDNSexport void SleepRecordRegistrations(mDNS *m)
4619 	{
4620 	AuthRecord *rr;
4621 	for (rr = m->ResourceRecords; rr; rr=rr->next)
4622 		{
4623 		if (AuthRecord_uDNS(rr))
4624 			{
4625 			// Zero out the updateid so that if we have a pending response from the server, it won't
4626 			// be accepted as a valid response.
4627 			if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
4628 
4629 			if (rr->NATinfo.clientContext)
4630 				{
4631 				mDNS_StopNATOperation_internal(m, &rr->NATinfo);
4632 				rr->NATinfo.clientContext = mDNSNULL;
4633 				}
4634 			// We are waiting to update the resource record. The original data of the record is
4635 			// in OrigRData and the updated value is in InFlightRData. Free the old and the new
4636 			// one will be registered when we come back.
4637 			if (rr->state == regState_UpdatePending)
4638 				{
4639 				// act as if the update succeeded, since we're about to delete the name anyway
4640 				rr->state = regState_Registered;
4641 				// deallocate old RData
4642 				if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->OrigRData, rr->OrigRDLen);
4643 				SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
4644 				rr->OrigRData = mDNSNULL;
4645 				rr->InFlightRData = mDNSNULL;
4646 				}
4647 
4648 			// If we have not begun the registration process i.e., never sent a registration packet,
4649 			// then uDNS_DeregisterRecord will not send a deregistration
4650 			uDNS_DeregisterRecord(m, rr);
4651 
4652 			// When we wake, we call ActivateUnicastRegistration which starts at StartGetZoneData
4653 			}
4654 		}
4655 	}
4656 
4657 mDNSexport void mDNS_AddSearchDomain(const domainname *const domain, mDNSInterfaceID InterfaceID)
4658 	{
4659 	SearchListElem **p;
4660 	SearchListElem *tmp = mDNSNULL;
4661 
4662 	// Check to see if we already have this domain in our list
4663 	for (p = &SearchList; *p; p = &(*p)->next)
4664 		if (((*p)->InterfaceID == InterfaceID) && SameDomainName(&(*p)->domain, domain))
4665 			{
4666 			// If domain is already in list, and marked for deletion, unmark the delete
4667 			// Be careful not to touch the other flags that may be present
4668 			LogInfo("mDNS_AddSearchDomain already in list %##s", domain->c);
4669 			if ((*p)->flag & SLE_DELETE) (*p)->flag &= ~SLE_DELETE;
4670 			tmp = *p;
4671 			*p = tmp->next;
4672 			tmp->next = mDNSNULL;
4673 			break;
4674 			}
4675 
4676 
4677 	// move to end of list so that we maintain the same order
4678 	while (*p) p = &(*p)->next;
4679 
4680 	if (tmp) *p = tmp;
4681 	else
4682 		{
4683 		// if domain not in list, add to list, mark as add (1)
4684 		*p = mDNSPlatformMemAllocate(sizeof(SearchListElem));
4685 		if (!*p) { LogMsg("ERROR: mDNS_AddSearchDomain - malloc"); return; }
4686 		mDNSPlatformMemZero(*p, sizeof(SearchListElem));
4687 		AssignDomainName(&(*p)->domain, domain);
4688 		(*p)->next = mDNSNULL;
4689 		(*p)->InterfaceID = InterfaceID;
4690 		LogInfo("mDNS_AddSearchDomain created new %##s, InterfaceID %p", domain->c, InterfaceID);
4691 		}
4692 	}
4693 
4694 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
4695 	{
4696 	(void)m;	// unused
4697 	if (result == mStatus_MemFree) mDNSPlatformMemFree(rr->RecordContext);
4698 	}
4699 
4700 mDNSlocal void FoundDomain(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
4701 	{
4702 	SearchListElem *slElem = question->QuestionContext;
4703 	mStatus err;
4704 	const char *name;
4705 
4706 	if (answer->rrtype != kDNSType_PTR) return;
4707 	if (answer->RecordType == kDNSRecordTypePacketNegative) return;
4708 	if (answer->InterfaceID == mDNSInterface_LocalOnly) return;
4709 
4710 	if      (question == &slElem->BrowseQ)          name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowse];
4711 	else if (question == &slElem->DefBrowseQ)       name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowseDefault];
4712 	else if (question == &slElem->AutomaticBrowseQ) name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowseAutomatic];
4713 	else if (question == &slElem->RegisterQ)        name = mDNS_DomainTypeNames[mDNS_DomainTypeRegistration];
4714 	else if (question == &slElem->DefRegisterQ)     name = mDNS_DomainTypeNames[mDNS_DomainTypeRegistrationDefault];
4715 	else { LogMsg("FoundDomain - unknown question"); return; }
4716 
4717 	LogInfo("FoundDomain: %p %s %s Q %##s A %s", answer->InterfaceID, AddRecord ? "Add" : "Rmv", name, question->qname.c, RRDisplayString(m, answer));
4718 
4719 	if (AddRecord)
4720 		{
4721 		ARListElem *arElem = mDNSPlatformMemAllocate(sizeof(ARListElem));
4722 		if (!arElem) { LogMsg("ERROR: FoundDomain out of memory"); return; }
4723 		mDNS_SetupResourceRecord(&arElem->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, arElem);
4724 		MakeDomainNameFromDNSNameString(&arElem->ar.namestorage, name);
4725 		AppendDNSNameString            (&arElem->ar.namestorage, "local");
4726 		AssignDomainName(&arElem->ar.resrec.rdata->u.name, &answer->rdata->u.name);
4727 		LogInfo("FoundDomain: Registering %s", ARDisplayString(m, &arElem->ar));
4728 		err = mDNS_Register(m, &arElem->ar);
4729 		if (err) { LogMsg("ERROR: FoundDomain - mDNS_Register returned %d", err); mDNSPlatformMemFree(arElem); return; }
4730 		arElem->next = slElem->AuthRecs;
4731 		slElem->AuthRecs = arElem;
4732 		}
4733 	else
4734 		{
4735 		ARListElem **ptr = &slElem->AuthRecs;
4736 		while (*ptr)
4737 			{
4738 			if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, &answer->rdata->u.name))
4739 				{
4740 				ARListElem *dereg = *ptr;
4741 				*ptr = (*ptr)->next;
4742 				LogInfo("FoundDomain: Deregistering %s", ARDisplayString(m, &dereg->ar));
4743 				err = mDNS_Deregister(m, &dereg->ar);
4744 				if (err) LogMsg("ERROR: FoundDomain - mDNS_Deregister returned %d", err);
4745 				// Memory will be freed in the FreeARElemCallback
4746 				}
4747 			else
4748 				ptr = &(*ptr)->next;
4749 			}
4750 		}
4751 	}
4752 
4753 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4754 mDNSexport void udns_validatelists(void *const v)
4755 	{
4756 	mDNS *const m = v;
4757 
4758 	NATTraversalInfo *n;
4759 	for (n = m->NATTraversals; n; n=n->next)
4760 		if (n->next == (NATTraversalInfo *)~0 || n->clientCallback == (NATTraversalClientCallback)~0)
4761 			LogMemCorruption("m->NATTraversals: %p is garbage", n);
4762 
4763 	DNSServer *d;
4764 	for (d = m->DNSServers; d; d=d->next)
4765 		if (d->next == (DNSServer *)~0 || d->teststate > DNSServer_Disabled)
4766 			LogMemCorruption("m->DNSServers: %p is garbage (%d)", d, d->teststate);
4767 
4768 	DomainAuthInfo *info;
4769 	for (info = m->AuthInfoList; info; info = info->next)
4770 		if (info->next == (DomainAuthInfo *)~0 || info->AutoTunnel == (const char*)~0)
4771 			LogMemCorruption("m->AuthInfoList: %p is garbage (%X)", info, info->AutoTunnel);
4772 
4773 	HostnameInfo *hi;
4774 	for (hi = m->Hostnames; hi; hi = hi->next)
4775 		if (hi->next == (HostnameInfo *)~0 || hi->StatusCallback == (mDNSRecordCallback*)~0)
4776 			LogMemCorruption("m->Hostnames: %p is garbage", n);
4777 
4778 	SearchListElem *ptr;
4779 	for (ptr = SearchList; ptr; ptr = ptr->next)
4780 		if (ptr->next == (SearchListElem *)~0 || ptr->AuthRecs == (void*)~0)
4781 			LogMemCorruption("SearchList: %p is garbage (%X)", ptr, ptr->AuthRecs);
4782 	}
4783 #endif
4784 
4785 // This should probably move to the UDS daemon -- the concept of legacy clients and automatic registration / automatic browsing
4786 // is really a UDS API issue, not something intrinsic to uDNS
4787 
4788 mDNSexport mStatus uDNS_SetupSearchDomains(mDNS *const m, int action)
4789 	{
4790 	SearchListElem **p = &SearchList, *ptr;
4791 	mStatus err;
4792 
4793 	// step 1: mark each element for removal
4794 	for (ptr = SearchList; ptr; ptr = ptr->next) ptr->flag |= SLE_DELETE;
4795 
4796 	// Make sure we have the search domains from the platform layer so that if we start the WAB
4797 	// queries below, we have the latest information
4798 	mDNS_Lock(m);
4799 	mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNStrue, mDNSNULL, mDNSNULL, mDNSNULL);
4800 	mDNS_Unlock(m);
4801 
4802 	if (action & UDNS_START_WAB_QUERY)
4803 		m->StartWABQueries = mDNStrue;
4804 
4805 	// delete elems marked for removal, do queries for elems marked add
4806 	while (*p)
4807 		{
4808 		ptr = *p;
4809 		LogInfo("uDNS_SetupSearchDomains:action %d: Flags %d,  AuthRecs %p, InterfaceID %p %##s", action, ptr->flag, ptr->AuthRecs, ptr->InterfaceID, ptr->domain.c);
4810 		if (ptr->flag & SLE_DELETE)
4811 			{
4812 			ARListElem *arList = ptr->AuthRecs;
4813 			ptr->AuthRecs = mDNSNULL;
4814 			*p = ptr->next;
4815 
4816 			// If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries
4817 			// We suppressed the domain enumeration for scoped search domains below. When we enable that
4818 			// enable this.
4819 			if ((ptr->flag & SLE_WAB_QUERY_STARTED) &&
4820 				!SameDomainName(&ptr->domain, &localdomain) && (ptr->InterfaceID == mDNSInterface_Any))
4821 				{
4822 				mDNS_StopGetDomains(m, &ptr->BrowseQ);
4823 				mDNS_StopGetDomains(m, &ptr->RegisterQ);
4824 				mDNS_StopGetDomains(m, &ptr->DefBrowseQ);
4825 				mDNS_StopGetDomains(m, &ptr->DefRegisterQ);
4826 				mDNS_StopGetDomains(m, &ptr->AutomaticBrowseQ);
4827 				}
4828 
4829 			mDNSPlatformMemFree(ptr);
4830 
4831 	        // deregister records generated from answers to the query
4832 			while (arList)
4833 				{
4834 				ARListElem *dereg = arList;
4835 				arList = arList->next;
4836 				debugf("Deregistering PTR %##s -> %##s", dereg->ar.resrec.name->c, dereg->ar.resrec.rdata->u.name.c);
4837 				err = mDNS_Deregister(m, &dereg->ar);
4838 				if (err) LogMsg("uDNS_SetupSearchDomains:: ERROR!! mDNS_Deregister returned %d", err);
4839 				// Memory will be freed in the FreeARElemCallback
4840 				}
4841 			continue;
4842 			}
4843 
4844 		if ((action & UDNS_START_WAB_QUERY) && !(ptr->flag & SLE_WAB_QUERY_STARTED))
4845 			{
4846 			// If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries.
4847 			// Also, suppress the domain enumeration for scoped search domains for now until there is a need.
4848 			if (!SameDomainName(&ptr->domain, &localdomain) && (ptr->InterfaceID == mDNSInterface_Any))
4849 				{
4850 				mStatus err1, err2, err3, err4, err5;
4851 				err1 = mDNS_GetDomains(m, &ptr->BrowseQ,          mDNS_DomainTypeBrowse,              &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
4852 				err2 = mDNS_GetDomains(m, &ptr->DefBrowseQ,       mDNS_DomainTypeBrowseDefault,       &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
4853 				err3 = mDNS_GetDomains(m, &ptr->RegisterQ,        mDNS_DomainTypeRegistration,        &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
4854 				err4 = mDNS_GetDomains(m, &ptr->DefRegisterQ,     mDNS_DomainTypeRegistrationDefault, &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
4855 				err5 = mDNS_GetDomains(m, &ptr->AutomaticBrowseQ, mDNS_DomainTypeBrowseAutomatic,     &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
4856 				if (err1 || err2 || err3 || err4 || err5)
4857 					LogMsg("uDNS_SetupSearchDomains: GetDomains for domain %##s returned error(s):\n"
4858 						   "%d (mDNS_DomainTypeBrowse)\n"
4859 						   "%d (mDNS_DomainTypeBrowseDefault)\n"
4860 						   "%d (mDNS_DomainTypeRegistration)\n"
4861 						   "%d (mDNS_DomainTypeRegistrationDefault)"
4862 						   "%d (mDNS_DomainTypeBrowseAutomatic)\n",
4863 						   ptr->domain.c, err1, err2, err3, err4, err5);
4864 				ptr->flag |= SLE_WAB_QUERY_STARTED;
4865 				}
4866 			}
4867 
4868 		p = &ptr->next;
4869 		}
4870 	return mStatus_NoError;
4871 	}
4872 
4873 mDNSexport domainname  *uDNS_GetNextSearchDomain(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSs8 *searchIndex, mDNSBool ignoreDotLocal)
4874 	{
4875 	SearchListElem *p = SearchList;
4876 	int count = *searchIndex;
4877 	(void) m; // unused
4878 
4879 	if (count < 0) { LogMsg("uDNS_GetNextSearchDomain: count %d less than zero", count); return mDNSNULL; }
4880 
4881 	// skip the  domains that we already looked at before
4882 	for (; count; count--) p = p->next;
4883 
4884 	while (p)
4885 		{
4886 		int labels = CountLabels(&p->domain);
4887 		if (labels > 0)
4888 			{
4889 			const domainname *d = SkipLeadingLabels(&p->domain, labels - 1);
4890 			if (SameDomainLabel(d->c, (const mDNSu8 *)"\x4""arpa"))
4891 				{
4892 				LogInfo("uDNS_GetNextSearchDomain: skipping search domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
4893 				(*searchIndex)++;
4894 				p = p->next;
4895 				continue;
4896 				}
4897 			if (ignoreDotLocal && SameDomainLabel(d->c, (const mDNSu8 *)"\x5""local"))
4898 				{
4899 				LogInfo("uDNS_GetNextSearchDomain: skipping local domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
4900 				(*searchIndex)++;
4901 				p = p->next;
4902 				continue;
4903 				}
4904 			}
4905 		// Point to the next one in the list which we will look at next time.
4906 		(*searchIndex)++;
4907 		// When we are appending search domains in a ActiveDirectory domain, the question's InterfaceID
4908 		// set to mDNSInterface_Unicast. Match the unscoped entries in that case.
4909 		if (((InterfaceID == mDNSInterface_Unicast) && (p->InterfaceID == mDNSInterface_Any)) ||
4910 			p->InterfaceID == InterfaceID)
4911 			{
4912 			LogInfo("uDNS_GetNextSearchDomain returning domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
4913 			return &p->domain;
4914 			}
4915 		LogInfo("uDNS_GetNextSearchDomain skipping domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
4916 		p = p->next;
4917 		}
4918 	return mDNSNULL;
4919 	}
4920 
4921 mDNSlocal void FlushAddressCacheRecords(mDNS *const m)
4922 	{
4923 	mDNSu32 slot;
4924 	CacheGroup *cg;
4925 	CacheRecord *cr;
4926 	FORALL_CACHERECORDS(slot, cg, cr)
4927 		{
4928 		if (cr->resrec.InterfaceID) continue;
4929 
4930 		// If a resource record can answer A or AAAA, they need to be flushed so that we will
4931 		// never used to deliver an ADD or RMV
4932 		if (RRTypeAnswersQuestionType(&cr->resrec, kDNSType_A) ||
4933 			RRTypeAnswersQuestionType(&cr->resrec, kDNSType_AAAA))
4934 			{
4935 			LogInfo("FlushAddressCacheRecords: Purging Resourcerecord %s", CRDisplayString(m, cr));
4936 			mDNS_PurgeCacheResourceRecord(m, cr);
4937 			}
4938 		}
4939 	}
4940 
4941 // Retry questions which has seach domains appended
4942 mDNSexport void RetrySearchDomainQuestions(mDNS *const m)
4943 	{
4944 	// Purge all the A/AAAA cache records and restart the queries. mDNSCoreRestartAddressQueries
4945 	// does this. When we restart the question,  we first want to try the new search domains rather
4946 	// than use the entries that is already in the cache. When we appended search domains, we might
4947 	// have created cache entries which is no longer valid as there are new search domains now
4948 
4949 	LogInfo("RetrySearchDomainQuestions: Calling mDNSCoreRestartAddressQueries");
4950 	mDNSCoreRestartAddressQueries(m, mDNStrue, FlushAddressCacheRecords, mDNSNULL, mDNSNULL);
4951 	}
4952 
4953 // Construction of Default Browse domain list (i.e. when clients pass NULL) is as follows:
4954 // 1) query for b._dns-sd._udp.local on LocalOnly interface
4955 //    (.local manually generated via explicit callback)
4956 // 2) for each search domain (from prefs pane), query for b._dns-sd._udp.<searchdomain>.
4957 // 3) for each result from (2), register LocalOnly PTR record b._dns-sd._udp.local. -> <result>
4958 // 4) result above should generate a callback from question in (1).  result added to global list
4959 // 5) global list delivered to client via GetSearchDomainList()
4960 // 6) client calls to enumerate domains now go over LocalOnly interface
4961 //    (!!!KRS may add outgoing interface in addition)
4962 
4963 struct CompileTimeAssertionChecks_uDNS
4964 	{
4965 	// Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4966 	// other overly-large structures instead of having a pointer to them, can inadvertently
4967 	// cause structure sizes (and therefore memory usage) to balloon unreasonably.
4968 	char sizecheck_tcpInfo_t     [(sizeof(tcpInfo_t)      <=  9056) ? 1 : -1];
4969 	char sizecheck_SearchListElem[(sizeof(SearchListElem) <=  5000) ? 1 : -1];
4970 	};
4971