147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt/* -*- Mode: C; tab-width: 4 -*-
247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt *
347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * Copyright (c) 2002-2006 Apple Computer, Inc. All rights reserved.
447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt *
547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * Licensed under the Apache License, Version 2.0 (the "License");
647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * you may not use this file except in compliance with the License.
747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * You may obtain a copy of the License at
847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt *
947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt *     http://www.apache.org/licenses/LICENSE-2.0
1047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt *
1147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * Unless required by applicable law or agreed to in writing, software
1247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * distributed under the License is distributed on an "AS IS" BASIS,
1347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * See the License for the specific language governing permissions and
1547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * limitations under the License.
1647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
1747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * To Do:
1847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * Elimate all mDNSPlatformMemAllocate/mDNSPlatformMemFree from this code -- the core code
1947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * is supposed to be malloc-free so that it runs in constant memory determined at compile-time.
2047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt * Any dynamic run-time requirements should be handled by the platform layer below or client layer above
2147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt */
2247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
2347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
2447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#include <TargetConditionals.h>
2547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
2647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#include "uDNS.h"
2747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
2847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if(defined(_MSC_VER))
2947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Disable "assignment within conditional expression".
3047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Other compilers understand the convention that if you place the assignment expression within an extra pair
3147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
3247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
3347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// to the compiler that the assignment is intentional, we have to just turn this warning off completely.
3447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	#pragma warning(disable:4706)
3547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
3647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
3747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// For domain enumeration and automatic browsing
3847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// This is the user's DNS search list.
3947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
4047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// to discover recommended domains for domain enumeration (browse, default browse, registration,
4147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// default registration) and possibly one or more recommended automatic browsing domains.
4247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport SearchListElem *SearchList = mDNSNULL;
4347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
4447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// The value can be set to true by the Platform code e.g., MacOSX uses the plist mechanism
4547e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSBool StrictUnicastOrdering = mDNSfalse;
4647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
4747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// We keep track of the number of unicast DNS servers and log a message when we exceed 64.
4847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Currently the unicast queries maintain a 64 bit map to track the valid DNS servers for that
4947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// question. Bit position is the index into the DNS server list. This is done so to try all
5047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// the servers exactly once before giving up. If we could allocate memory in the core, then
5147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// arbitrary limitation of 64 DNSServers can be removed.
5247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSu8 NumUnicastDNSServers = 0;
5347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#define MAX_UNICAST_DNS_SERVERS	64
5447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
5547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
5647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
5747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - General Utility Functions
5847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
5947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
6047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// set retry timestamp for record with exponential backoff
6147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void SetRecordRetry(mDNS *const m, AuthRecord *rr, mDNSu32 random)
6247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
6347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->LastAPTime = m->timenow;
6447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
6547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->expire && rr->refreshCount < MAX_UPDATE_REFRESH_COUNT)
6647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
6747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSs32 remaining = rr->expire - m->timenow;
6847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->refreshCount++;
6947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (remaining > MIN_UPDATE_REFRESH_TIME)
7047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
7147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Refresh at 70% + random (currently it is 0 to 10%)
7247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->ThisAPInterval =  7 * (remaining/10) + (random ? random : mDNSRandom(remaining/10));
7347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Don't update more often than 5 minutes
7447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->ThisAPInterval < MIN_UPDATE_REFRESH_TIME)
7547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
7647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("SetRecordRetry refresh in %d of %d for %s",
7747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
7847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
7947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
8047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
8147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
8247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("SetRecordRetry clamping to min refresh in %d of %d for %s",
8347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
8447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
8547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
8647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
8747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
8847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->expire = 0;
8947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
9047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->ThisAPInterval = rr->ThisAPInterval * QuestionIntervalStep;	// Same Retry logic as Unicast Queries
9147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->ThisAPInterval < INIT_RECORD_REG_INTERVAL)
9247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
9347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->ThisAPInterval > MAX_RECORD_REG_INTERVAL)
9447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->ThisAPInterval = MAX_RECORD_REG_INTERVAL;
9547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
9647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("SetRecordRetry retry in %d ms for %s", rr->ThisAPInterval, ARDisplayString(m, rr));
9747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
9847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
9947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
10047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
10147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - Name Server List Management
10247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
10347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
10447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, const mDNSAddr *addr, const mDNSIPPort port, mDNSBool scoped, mDNSu32 timeout)
10547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
10647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSServer **p = &m->DNSServers;
10747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSServer *tmp = mDNSNULL;
10847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
10947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if ((NumUnicastDNSServers + 1) > MAX_UNICAST_DNS_SERVERS)
11047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
11147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("mDNS_AddDNSServer: DNS server limit of %d reached, not adding this server", MAX_UNICAST_DNS_SERVERS);
11247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return mDNSNULL;
11347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
11447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
11547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!d) d = (const domainname *)"";
11647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
11747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("mDNS_AddDNSServer: Adding %#a for %##s, InterfaceID %p, scoped %d", addr, d->c, interface, scoped);
11847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy+1)
11947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("mDNS_AddDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
12047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
12147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*p)	// Check if we already have this {interface,address,port,domain} tuple registered
12247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
12347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if ((*p)->scoped == scoped && (*p)->interface == interface && (*p)->teststate != DNSServer_Disabled &&
12447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSSameAddress(&(*p)->addr, addr) && mDNSSameIPPort((*p)->port, port) && SameDomainName(&(*p)->domain, d))
12547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
12647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			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);
12747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->flags &= ~DNSServer_FlagDelete;
12847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tmp = *p;
12947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			*p = tmp->next;
13047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tmp->next = mDNSNULL;
13147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
13247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
13347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			p=&(*p)->next;
13447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
13547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
13647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
13747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
13847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
13947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// allocate, add to list
14047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		*p = mDNSPlatformMemAllocate(sizeof(**p));
14147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!*p) LogMsg("Error: mDNS_AddDNSServer - malloc");
14247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
14347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
14447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			NumUnicastDNSServers++;
14547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->scoped	= scoped;
14647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->interface = interface;
14747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->addr      = *addr;
14847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->port      = port;
14947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->flags     = DNSServer_FlagNew;
15047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->teststate = /* DNSServer_Untested */ DNSServer_Passed;
15147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->lasttest  = m->timenow - INIT_UCAST_POLL_INTERVAL;
15247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->timeout   = timeout;
15347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			AssignDomainName(&(*p)->domain, d);
15447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			(*p)->next = mDNSNULL;
15547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
15647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
15747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(*p)->penaltyTime = 0;
15847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(*p);
15947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
16047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
16147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// PenalizeDNSServer is called when the number of queries to the unicast
16247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// DNS server exceeds MAX_UCAST_UNANSWERED_QUERIES or when we receive an
16347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// error e.g., SERV_FAIL from DNS server.
16447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void PenalizeDNSServer(mDNS *const m, DNSQuestion *q)
16547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
16647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSServer *new;
16747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSServer *orig = q->qDNSServer;
16847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
16947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy+1)
17047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("PenalizeDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
17147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
17247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// This should never happen. Whenever we change DNS server, we change the ID on the question and hence
17347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// we should never accept a response after we penalize a DNS server e.g., send two queries, no response,
17447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// penalize DNS server and no new servers to pick for the question and hence qDNSServer is NULL. If we
17547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// receive a response now, the DNS server can be NULL. But we won't because the ID already has been
17647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// changed.
17747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!q->qDNSServer)
17847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
17947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("PenalizeDNSServer: ERROR!! Null DNS server for %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), q->unansweredQueries);
18047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		goto end;
18147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
18247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
18347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("PenalizeDNSServer: Penalizing DNS server %#a:%d question (%##s) for question %p %##s (%s) SuppressUnusable %d",
18447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		&q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c, q, q->qname.c, DNSTypeName(q->qtype),
18547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->SuppressUnusable);
18647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
18747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If strict ordering of unicast servers needs to be preserved, we just lookup
18847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// the next best match server below
18947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
19047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If strict ordering is not required which is the default behavior, we penalize the server
19147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// for DNSSERVER_PENALTY_TIME. We may also use additional logic e.g., don't penalize for PTR
19247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// in the future.
19347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
19447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!StrictUnicastOrdering)
19547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
19647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("PenalizeDNSServer: Strict Unicast Ordering is FALSE");
19747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We penalize the server so that new queries don't pick this server for DNSSERVER_PENALTY_TIME
19847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// XXX Include other logic here to see if this server should really be penalized
19947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//
20047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->qtype == kDNSType_PTR)
20147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
20247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("PenalizeDNSServer: Not Penalizing PTR question");
20347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
20447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
20547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
20647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("PenalizeDNSServer: Penalizing question type %d", q->qtype);
20747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->qDNSServer->penaltyTime = NonZeroTime(m->timenow + DNSSERVER_PENALTY_TIME);
20847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
20947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
21047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
21147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
21247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("PenalizeDNSServer: Strict Unicast Ordering is TRUE");
21347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
21447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
21547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwaltend:
21647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	new = GetServerForQuestion(m, q);
21747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
21847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
21947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (new == orig)
22047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
22147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (new)
22247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server %#a:%d", &new->addr,
22347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		    	mDNSVal16(new->port));
22447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
22547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server NULL");
22647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ThisQInterval = 0;	// Inactivate this question so that we dont bombard the network
22747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
22847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
22947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
23047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// The new DNSServer is set in DNSServerChangeForQuestion
23147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DNSServerChangeForQuestion(m, q, new);
23247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
23347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (new)
23447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
23547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("PenalizeDNSServer: Server for %##s (%s) changed to %#a:%d (%##s)",
23647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->qname.c, DNSTypeName(q->qtype), &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c);
23747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We want to try the next server immediately. As the question may already have backed off, reset
23847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// the interval. We do this only the first time when we try all the DNS servers. Once we reached the end of
23947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// list and retrying all the servers again e.g., at least one server failed to respond in the previous try, we
24047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// use the normal backoff which is done in uDNS_CheckCurrentQuestion when we send the packet out.
24147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!q->triedAllServersOnce)
24247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
24347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->ThisQInterval = InitialQuestionInterval;
24447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->LastQTime  = m->timenow - q->ThisQInterval;
24547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				SetNextQueryTime(m, q);
24647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
24747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
24847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
24947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
25047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We don't have any more DNS servers for this question. If some server in the list did not return
25147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// any response, we need to keep retrying till we get a response. uDNS_CheckCurrentQuestion handles
25247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// this case.
25347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
25447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If all servers responded with a negative response, We need to do two things. First, generate a
25547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// negative response so that applications get a reply. We also need to reinitialize the DNS servers
25647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// so that when the cache expires, we can restart the query.
25747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
25847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Negative response may be generated in two ways.
25947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
26047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// 1. AnswerQuestionForDNSServerChanges (called from DNSServerChangedForQuestion) might find some
26147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    cache entries and answer this question.
26247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// 2. uDNS_CheckCurrentQuestion will create a new cache entry and answer this question
26347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
26447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// For (1), it might be okay to reinitialize the DNS servers here. But for (2), we can't do it here
26547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// because uDNS_CheckCurrentQuestion will try resending the queries. Hence, to be consistent, we
26647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// defer reintializing the DNS servers up until generating a negative cache response.
26747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
26847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Be careful not to touch the ThisQInterval here. For a normal question, when we answer the question
26947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// in AnswerCurrentQuestionWithResourceRecord will set ThisQInterval to MaxQuestionInterval and hence
27047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// the next query will not happen until cache expiry. If it is a long lived question,
27147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// AnswerCurrentQuestionWithResourceRecord will not set it to MaxQuestionInterval. In that case,
27247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// we want the normal backoff to work.
27347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("PenalizeDNSServer: Server for %p, %##s (%s) changed to NULL, Interval %d", q, q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
27447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
27547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->unansweredQueries = 0;
27647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
27747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
27847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
27947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
28047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
28147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
28247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - authorization management
28347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
28447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
28547e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal DomainAuthInfo *GetAuthInfoForName_direct(mDNS *m, const domainname *const name)
28647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
28747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *n = name;
28847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (n->c[0])
28947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
29047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DomainAuthInfo *ptr;
29147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (ptr = m->AuthInfoList; ptr; ptr = ptr->next)
29247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (SameDomainName(&ptr->domain, n))
29347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
29447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				debugf("GetAuthInfoForName %##s Matched %##s Key name %##s", name->c, ptr->domain.c, ptr->keyname.c);
29547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				return(ptr);
29647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
29747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n = (const domainname *)(n->c + 1 + n->c[0]);
29847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
29947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//LogInfo("GetAuthInfoForName none found for %##s", name->c);
30047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mDNSNULL;
30147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
30247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
30347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// MUST be called with lock held
30447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport DomainAuthInfo *GetAuthInfoForName_internal(mDNS *m, const domainname *const name)
30547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
30647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo **p = &m->AuthInfoList;
30747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
30847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy+1)
30947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("GetAuthInfoForName_internal: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
31047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
31147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// First purge any dead keys from the list
31247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*p)
31347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
31447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if ((*p)->deltime && m->timenow - (*p)->deltime >= 0 && AutoTunnelUnregistered(*p))
31547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
31647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DNSQuestion *q;
31747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DomainAuthInfo *info = *p;
31847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("GetAuthInfoForName_internal deleting expired key %##s %##s", info->domain.c, info->keyname.c);
31947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			*p = info->next;	// Cut DomainAuthInfo from list *before* scanning our question list updating AuthInfo pointers
32047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			for (q = m->Questions; q; q=q->next)
32147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (q->AuthInfo == info)
32247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
32347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->AuthInfo = GetAuthInfoForName_direct(m, &q->qname);
32447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					debugf("GetAuthInfoForName_internal updated q->AuthInfo from %##s to %##s for %##s (%s)",
32547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						info->domain.c, q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
32647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
32747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
32847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Probably not essential, but just to be safe, zero out the secret key data
32947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// so we don't leave it hanging around in memory
33047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// (where it could potentially get exposed via some other bug)
33147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSPlatformMemZero(info, sizeof(*info));
33247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSPlatformMemFree(info);
33347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
33447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
33547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			p = &(*p)->next;
33647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
33747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
33847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(GetAuthInfoForName_direct(m, name));
33947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
34047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
34147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport DomainAuthInfo *GetAuthInfoForName(mDNS *m, const domainname *const name)
34247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
34347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *d;
34447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
34547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	d = GetAuthInfoForName_internal(m, name);
34647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
34747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(d);
34847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
34947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
35047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// MUST be called with the lock held
35147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus mDNS_SetSecretForDomain(mDNS *m, DomainAuthInfo *info,
35247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *domain, const domainname *keyname, const char *b64keydata, const domainname *hostname, mDNSIPPort *port, const char *autoTunnelPrefix)
35347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
35447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *q;
35547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo **p = &m->AuthInfoList;
35647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!info || !b64keydata) { LogMsg("mDNS_SetSecretForDomain: ERROR: info %p b64keydata %p", info, b64keydata); return(mStatus_BadParamErr); }
35747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
35847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("mDNS_SetSecretForDomain: domain %##s key %##s%s%s", domain->c, keyname->c, autoTunnelPrefix ? " prefix " : "", autoTunnelPrefix ? autoTunnelPrefix : "");
35947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
36047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnel = autoTunnelPrefix;
36147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AssignDomainName(&info->domain,  domain);
36247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AssignDomainName(&info->keyname, keyname);
36347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (hostname)
36447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&info->hostname, hostname);
36547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
36647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		info->hostname.c[0] = 0;
36747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (port)
36847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		info->port = *port;
36947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
37047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		info->port = zeroIPPort;
37147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_snprintf(info->b64keydata, sizeof(info->b64keydata), "%s", b64keydata);
37247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
37347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (DNSDigest_ConstructHMACKeyfromBase64(info, b64keydata) < 0)
37447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
37547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("mDNS_SetSecretForDomain: ERROR: Could not convert shared secret from base64: domain %##s key %##s %s", domain->c, keyname->c, mDNS_LoggingEnabled ? b64keydata : "");
37647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return(mStatus_BadParamErr);
37747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
37847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
37947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Don't clear deltime until after we've ascertained that b64keydata is valid
38047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->deltime = 0;
38147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
38247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*p && (*p) != info) p=&(*p)->next;
38347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (*p) {LogInfo("mDNS_SetSecretForDomain: Domain %##s Already in list", (*p)->domain.c); return(mStatus_AlreadyRegistered);}
38447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
38547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Caution: Only zero AutoTunnelHostRecord.namestorage and AutoTunnelNAT.clientContext AFTER we've determined that this is a NEW DomainAuthInfo
38647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// being added to the list. Otherwise we risk smashing our AutoTunnel host records and NATOperation that are already active and in use.
38747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnelHostRecord.resrec.RecordType = kDNSRecordTypeUnregistered;
38847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnelHostRecord.namestorage.c[0] = 0;
38947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnelTarget    .resrec.RecordType = kDNSRecordTypeUnregistered;
39047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnelDeviceInfo.resrec.RecordType = kDNSRecordTypeUnregistered;
39147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnelService   .resrec.RecordType = kDNSRecordTypeUnregistered;
39247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnel6Record   .resrec.RecordType = kDNSRecordTypeUnregistered;
39347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->AutoTunnelNAT.clientContext = mDNSNULL;
39447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->next = mDNSNULL;
39547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	*p = info;
39647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
39747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Check to see if adding this new DomainAuthInfo has changed the credentials for any of our questions
39847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (q = m->Questions; q; q=q->next)
39947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
40047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DomainAuthInfo *newinfo = GetAuthInfoForQuestion(m, q);
40147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->AuthInfo != newinfo)
40247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
40347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			debugf("mDNS_SetSecretForDomain updating q->AuthInfo from %##s to %##s for %##s (%s)",
40447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL,
40547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				newinfo     ? newinfo    ->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
40647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->AuthInfo = newinfo;
40747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
40847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
40947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
41047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(mStatus_NoError);
41147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
41247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
41347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
41447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
41547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark -
41647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - NAT Traversal
41747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
41847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
41947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mStatus uDNS_SendNATMsg(mDNS *m, NATTraversalInfo *info)
42047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
42147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err = mStatus_NoError;
42247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
42347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// send msg if we have a router and it is a private address
42447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!mDNSIPv4AddressIsZero(m->Router.ip.v4) && mDNSv4AddrIsRFC1918(&m->Router.ip.v4))
42547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
42647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		union { NATAddrRequest NATAddrReq; NATPortMapRequest NATPortReq; } u = { { NATMAP_VERS, NATOp_AddrRequest } } ;
42747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		const mDNSu8 *end = (mDNSu8 *)&u + sizeof(NATAddrRequest);
42847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
42947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (info)			// For NATOp_MapUDP and NATOp_MapTCP, fill in additional fields
43047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
43147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu8 *p = (mDNSu8 *)&u.NATPortReq.NATReq_lease;
43247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			u.NATPortReq.opcode  = info->Protocol;
43347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			u.NATPortReq.unused  = zeroID;
43447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			u.NATPortReq.intport = info->IntPort;
43547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			u.NATPortReq.extport = info->RequestedPort;
43647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			p[0] = (mDNSu8)((info->NATLease >> 24) &  0xFF);
43747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			p[1] = (mDNSu8)((info->NATLease >> 16) &  0xFF);
43847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			p[2] = (mDNSu8)((info->NATLease >>  8) &  0xFF);
43947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			p[3] = (mDNSu8)( info->NATLease        &  0xFF);
44047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			end = (mDNSu8 *)&u + sizeof(NATPortMapRequest);
44147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
44247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
44347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		err = mDNSPlatformSendUDP(m, (mDNSu8 *)&u, end, 0, mDNSNULL, &m->Router, NATPMPPort);
44447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
44547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#ifdef _LEGACY_NAT_TRAVERSAL_
44647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (mDNSIPPortIsZero(m->UPnPRouterPort) || mDNSIPPortIsZero(m->UPnPSOAPPort)) LNT_SendDiscoveryMsg(m);
44747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (info) err = LNT_MapPort(m, info);
44847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else err = LNT_GetExternalAddress(m);
44947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif // _LEGACY_NAT_TRAVERSAL_
45047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
45147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(err);
45247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
45347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
45447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void RecreateNATMappings(mDNS *const m)
45547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
45647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATTraversalInfo *n;
45747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (n = m->NATTraversals; n; n=n->next)
45847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
45947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->ExpiryTime    = 0;		// Mark this mapping as expired
46047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->retryInterval = NATMAP_INIT_RETRY;
46147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->retryPortMap  = m->timenow;
46247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#ifdef _LEGACY_NAT_TRAVERSAL_
46347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (n->tcpInfo.sock) { mDNSPlatformTCPCloseConnection(n->tcpInfo.sock); n->tcpInfo.sock = mDNSNULL; }
46447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif // _LEGACY_NAT_TRAVERSAL_
46547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
46647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
46747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->NextScheduledNATOp = m->timenow;		// Need to send packets immediately
46847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
46947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
47047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void natTraversalHandleAddressReply(mDNS *const m, mDNSu16 err, mDNSv4Addr ExtAddr)
47147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
47247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	static mDNSu16 last_err = 0;
47347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
47447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err)
47547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
47647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err != last_err) LogMsg("Error getting external address %d", err);
47747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ExtAddr = zerov4Addr;
47847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
47947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
48047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
48147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("Received external IP address %.4a from NAT", &ExtAddr);
48247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (mDNSv4AddrIsRFC1918(&ExtAddr))
48347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("Double NAT (external NAT gateway address %.4a is also a private RFC 1918 address)", &ExtAddr);
48447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (mDNSIPv4AddressIsZero(ExtAddr))
48547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			err = NATErr_NetFail; // fake error to handle routers that pathologically report success with the zero address
48647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
48747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
48847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!mDNSSameIPv4Address(m->ExternalAddress, ExtAddr))
48947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
49047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->ExternalAddress = ExtAddr;
49147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		RecreateNATMappings(m);		// Also sets NextScheduledNATOp for us
49247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
49347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
49447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!err) // Success, back-off to maximum interval
49547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
49647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (!last_err) // Failure after success, retry quickly (then back-off exponentially)
49747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
49847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// else back-off normally in case of pathological failures
49947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
50047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
50147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->NextScheduledNATOp - m->retryIntervalGetAddr > 0)
50247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->NextScheduledNATOp = m->retryIntervalGetAddr;
50347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
50447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	last_err = err;
50547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
50647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
50747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Both places that call NATSetNextRenewalTime() update m->NextScheduledNATOp correctly afterwards
50847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void NATSetNextRenewalTime(mDNS *const m, NATTraversalInfo *n)
50947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
51047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	n->retryInterval = (n->ExpiryTime - m->timenow)/2;
51147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (n->retryInterval < NATMAP_MIN_RETRY_INTERVAL)	// Min retry interval is 2 seconds
51247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->retryInterval = NATMAP_MIN_RETRY_INTERVAL;
51347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	n->retryPortMap = m->timenow + n->retryInterval;
51447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
51547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
51647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Note: When called from handleLNTPortMappingResponse() only pkt->err, pkt->extport and pkt->NATRep_lease fields are filled in
51747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void natTraversalHandlePortMapReply(mDNS *const m, NATTraversalInfo *n, const mDNSInterfaceID InterfaceID, mDNSu16 err, mDNSIPPort extport, mDNSu32 lease)
51847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
51947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const char *prot = n->Protocol == NATOp_MapUDP ? "UDP" : n->Protocol == NATOp_MapTCP ? "TCP" : "?";
52047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void)prot;
52147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	n->NewResult = err;
52247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err || lease == 0 || mDNSIPPortIsZero(extport))
52347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
52447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d error %d",
52547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease, err);
52647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
52747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->retryPortMap = m->timenow + NATMAP_MAX_RETRY_INTERVAL;
52847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// No need to set m->NextScheduledNATOp here, since we're only ever extending the m->retryPortMap time
52947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if      (err == NATErr_Refused)                     n->NewResult = mStatus_NATPortMappingDisabled;
53047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (err > NATErr_None && err <= NATErr_Opcode) n->NewResult = mStatus_NATPortMappingUnsupported;
53147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
53247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
53347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
53447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (lease > 999999999UL / mDNSPlatformOneSecond)
53547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			lease = 999999999UL / mDNSPlatformOneSecond;
53647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->ExpiryTime = NonZeroTime(m->timenow + lease * mDNSPlatformOneSecond);
53747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
53847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!mDNSSameIPPort(n->RequestedPort, extport))
53947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d changed to %5d",
54047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				n, prot, mDNSVal16(n->IntPort), mDNSVal16(n->RequestedPort), mDNSVal16(extport));
54147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
54247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->InterfaceID   = InterfaceID;
54347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n->RequestedPort = extport;
54447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
54547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d",
54647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease);
54747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
54847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		NATSetNextRenewalTime(m, n);			// Got our port mapping; now set timer to renew it at halfway point
54947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->NextScheduledNATOp = m->timenow;		// May need to invoke client callback immediately
55047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
55147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
55247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
55347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Must be called with the mDNS_Lock held
55447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus mDNS_StartNATOperation_internal(mDNS *const m, NATTraversalInfo *traversal)
55547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
55647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATTraversalInfo **n;
55747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
55847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("mDNS_StartNATOperation_internal %p Protocol %d IntPort %d RequestedPort %d NATLease %d", traversal,
55947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
56047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
56147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Note: It important that new traversal requests are appended at the *end* of the list, not prepended at the start
56247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (n = &m->NATTraversals; *n; n=&(*n)->next)
56347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
56447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (traversal == *n)
56547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
56647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
56747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease);
56847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			#if ForceAlerts
56947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				*(long*)0 = 0;
57047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			#endif
57147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return(mStatus_AlreadyRegistered);
57247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
57347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (traversal->Protocol && traversal->Protocol == (*n)->Protocol && mDNSSameIPPort(traversal->IntPort, (*n)->IntPort) &&
57447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			!mDNSSameIPPort(traversal->IntPort, SSHPort))
57547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("Warning: Created port mapping request %p Prot %d Int %d TTL %d "
57647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				"duplicates existing port mapping request %p Prot %d Int %d TTL %d",
57747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
57847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				*n,        (*n)     ->Protocol, mDNSVal16((*n)     ->IntPort), (*n)     ->NATLease);
57947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
58047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
58147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Initialize necessary fields
58247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->next            = mDNSNULL;
58347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->ExpiryTime      = 0;
58447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->retryInterval   = NATMAP_INIT_RETRY;
58547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->retryPortMap    = m->timenow;
58647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->NewResult       = mStatus_NoError;
58747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->ExternalAddress = onesIPv4Addr;
58847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->ExternalPort    = zeroIPPort;
58947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->Lifetime        = 0;
59047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	traversal->Result          = mStatus_NoError;
59147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
59247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// set default lease if necessary
59347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!traversal->NATLease) traversal->NATLease = NATMAP_DEFAULT_LEASE;
59447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
59547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#ifdef _LEGACY_NAT_TRAVERSAL_
59647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformMemZero(&traversal->tcpInfo, sizeof(traversal->tcpInfo));
59747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif // _LEGACY_NAT_TRAVERSAL_
59847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
59947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!m->NATTraversals)		// If this is our first NAT request, kick off an address request too
60047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
60147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->retryGetAddr         = m->timenow;
60247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
60347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
60447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
60547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->NextScheduledNATOp = m->timenow;	// This will always trigger sending the packet ASAP, and generate client callback if necessary
60647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
60747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	*n = traversal;		// Append new NATTraversalInfo to the end of our list
60847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
60947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(mStatus_NoError);
61047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
61147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
61247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Must be called with the mDNS_Lock held
61347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus mDNS_StopNATOperation_internal(mDNS *m, NATTraversalInfo *traversal)
61447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
61547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool unmap = mDNStrue;
61647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATTraversalInfo *p;
61747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATTraversalInfo **ptr = &m->NATTraversals;
61847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
61947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*ptr && *ptr != traversal) ptr=&(*ptr)->next;
62047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (*ptr) *ptr = (*ptr)->next;		// If we found it, cut this NATTraversalInfo struct from our list
62147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
62247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
62347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("mDNS_StopNATOperation_internal: NATTraversalInfo %p not found in list", traversal);
62447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return(mStatus_BadReferenceErr);
62547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
62647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
62747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("mDNS_StopNATOperation_internal %p %d %d %d %d", traversal,
62847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
62947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
63047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->CurrentNATTraversal == traversal)
63147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->CurrentNATTraversal = m->CurrentNATTraversal->next;
63247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
63347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (traversal->Protocol)
63447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (p = m->NATTraversals; p; p=p->next)
63547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (traversal->Protocol == p->Protocol && mDNSSameIPPort(traversal->IntPort, p->IntPort))
63647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
63747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!mDNSSameIPPort(traversal->IntPort, SSHPort))
63847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("Warning: Removed port mapping request %p Prot %d Int %d TTL %d "
63947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						"duplicates existing port mapping request %p Prot %d Int %d TTL %d",
64047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
64147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						p,         p        ->Protocol, mDNSVal16(p        ->IntPort), p        ->NATLease);
64247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				unmap = mDNSfalse;
64347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
64447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
64547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (traversal->ExpiryTime && unmap)
64647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
64747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		traversal->NATLease = 0;
64847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		traversal->retryInterval = 0;
64947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		uDNS_SendNATMsg(m, traversal);
65047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
65147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
65247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 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
65347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	#ifdef _LEGACY_NAT_TRAVERSAL_
65447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
65547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mStatus err = LNT_UnmapPort(m, traversal);
65647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) LogMsg("Legacy NAT Traversal - unmap request failed with error %d", err);
65747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
65847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	#endif // _LEGACY_NAT_TRAVERSAL_
65947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
66047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(mStatus_NoError);
66147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
66247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
66347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus mDNS_StartNATOperation(mDNS *const m, NATTraversalInfo *traversal)
66447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
66547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus status;
66647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
66747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	status = mDNS_StartNATOperation_internal(m, traversal);
66847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
66947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(status);
67047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
67147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
67247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus mDNS_StopNATOperation(mDNS *const m, NATTraversalInfo *traversal)
67347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
67447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus status;
67547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
67647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	status = mDNS_StopNATOperation_internal(m, traversal);
67747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
67847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(status);
67947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
68047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
68147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
68247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
68347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark -
68447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - Long-Lived Queries
68547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
68647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
68747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Lock must be held -- otherwise m->timenow is undefined
68847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void StartLLQPolling(mDNS *const m, DNSQuestion *q)
68947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
69047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("StartLLQPolling: %##s", q->qname.c);
69147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->state = LLQ_Poll;
69247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ThisQInterval = INIT_UCAST_POLL_INTERVAL;
69347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We want to send our poll query ASAP, but the "+ 1" is because if we set the time to now,
69447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// we risk causing spurious "SendQueries didn't send all its queries" log messages
69547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->LastQTime     = m->timenow - q->ThisQInterval + 1;
69647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SetNextQueryTime(m, q);
69747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
69847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	UpdateAutoTunnelDomainStatuses(m);
69947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
70047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
70147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
70247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSu8 *putLLQ(DNSMessage *const msg, mDNSu8 *ptr, const DNSQuestion *const question, const LLQOptData *const data)
70347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
70447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord rr;
70547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ResourceRecord *opt = &rr.resrec;
70647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rdataOPT *optRD;
70747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
70847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
70947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = putQuestion(msg, ptr, msg->data + AbsoluteMaxDNSMessageData, &question->qname, question->qtype, question->qclass);
71047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL; }
71147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
71247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// locate OptRR if it exists, set pointer to end
71347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// !!!KRS implement me
71447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
71547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// format opt rr (fields not specified are zero-valued)
71647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_SetupResourceRecord(&rr, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
71747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	opt->rrclass    = NormalMaxDNSMessageData;
71847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	opt->rdlength   = sizeof(rdataOPT);	// One option in this OPT record
71947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	opt->rdestimate = sizeof(rdataOPT);
72047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
72147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	optRD = &rr.resrec.rdata->u.opt[0];
72247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	optRD->opt = kDNSOpt_LLQ;
72347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	optRD->u.llq = *data;
72447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = PutResourceRecordTTLJumbo(msg, ptr, &msg->h.numAdditionals, opt, 0);
72547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL; }
72647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
72747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return ptr;
72847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
72947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
73047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Normally we'd just request event packets be sent directly to m->LLQNAT.ExternalPort, except...
73147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// with LLQs over TLS/TCP we're doing a weird thing where instead of requesting packets be sent to ExternalAddress:ExternalPort
73247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// we're requesting that packets be sent to ExternalPort, but at the source address of our outgoing TCP connection.
73347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Normally, after going through the NAT gateway, the source address of our outgoing TCP connection is the same as ExternalAddress,
73447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// so this is fine, except when the TCP connection ends up going over a VPN tunnel instead.
73547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 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
73647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// LLQ server to send events to us directly at port 5353 on that address, instead of at our mapped external NAT port.
73747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
73847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSu16 GetLLQEventPort(const mDNS *const m, const mDNSAddr *const dst)
73947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
74047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSAddr src;
74147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformSourceAddrForDest(&src, dst);
74247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//LogMsg("GetLLQEventPort: src %#a for dst %#a (%d)", &src, dst, mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : 0);
74347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : mDNSVal16(MulticastDNSPort));
74447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
74547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
74647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Normally called with llq set.
74747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// May be called with llq NULL, when retransmitting a lost Challenge Response
74847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void sendChallengeResponse(mDNS *const m, DNSQuestion *const q, const LLQOptData *llq)
74947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
75047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *responsePtr = m->omsg.data;
75147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LLQOptData llqBuf;
75247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
75347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->tcp) { LogMsg("sendChallengeResponse: ERROR!!: question %##s (%s) tcp non-NULL", q->qname.c, DNSTypeName(q->qtype)); return; }
75447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
75547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (PrivateQuery(q)) { LogMsg("sendChallengeResponse: ERROR!!: Private Query %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
75647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
75747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->ntries++ == kLLQ_MAX_TRIES)
75847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
75947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s", kLLQ_MAX_TRIES, q->qname.c);
76047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		StartLLQPolling(m,q);
76147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
76247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
76347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
76447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!llq)		// Retransmission: need to make a new LLQOptData
76547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
76647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		llqBuf.vers     = kLLQ_Vers;
76747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		llqBuf.llqOp    = kLLQOp_Setup;
76847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		llqBuf.err      = LLQErr_NoError;	// Don't need to tell server UDP notification port when sending over UDP
76947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		llqBuf.id       = q->id;
77047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		llqBuf.llqlease = q->ReqLease;
77147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		llq = &llqBuf;
77247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
77347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
77447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->LastQTime     = m->timenow;
77547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ThisQInterval = q->tcp ? 0 : (kLLQ_INIT_RESEND * q->ntries * mDNSPlatformOneSecond);		// If using TCP, don't need to retransmit
77647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SetNextQueryTime(m, q);
77747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
77847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// To simulate loss of challenge response packet, uncomment line below
77947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//if (q->ntries == 1) return;
78047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
78147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
78247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	responsePtr = putLLQ(&m->omsg, responsePtr, q, llq);
78347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (responsePtr)
78447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
78547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mStatus err = mDNSSendDNSMessage(m, &m->omsg, responsePtr, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
78647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) { LogMsg("sendChallengeResponse: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err); }
78747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
78847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else StartLLQPolling(m,q);
78947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
79047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
79147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void SetLLQTimer(mDNS *const m, DNSQuestion *const q, const LLQOptData *const llq)
79247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
79347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSs32 lease = (mDNSs32)llq->llqlease * mDNSPlatformOneSecond;
79447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ReqLease      = llq->llqlease;
79547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->LastQTime     = m->timenow;
79647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->expire        = m->timenow + lease;
79747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ThisQInterval = lease/2 + mDNSRandom(lease/10);
79847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("SetLLQTimer setting %##s (%s) to %d %d", q->qname.c, DNSTypeName(q->qtype), lease/mDNSPlatformOneSecond, q->ThisQInterval/mDNSPlatformOneSecond);
79947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SetNextQueryTime(m, q);
80047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
80147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
80247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void recvSetupResponse(mDNS *const m, mDNSu8 rcode, DNSQuestion *const q, const LLQOptData *const llq)
80347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
80447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rcode && rcode != kDNSFlag1_RC_NXDomain)
80547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - rcode && rcode != kDNSFlag1_RC_NXDomain", q->qname.c, DNSTypeName(q->qtype)); return; }
80647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
80747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (llq->llqOp != kLLQOp_Setup)
80847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - bad op %d", q->qname.c, DNSTypeName(q->qtype), llq->llqOp); return; }
80947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
81047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (llq->vers != kLLQ_Vers)
81147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - bad vers %d", q->qname.c, DNSTypeName(q->qtype), llq->vers); return; }
81247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
81347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->state == LLQ_InitialRequest)
81447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
81547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//LogInfo("Got LLQ_InitialRequest");
81647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
81747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (llq->err) { LogMsg("recvSetupResponse - received llq->err %d from server", llq->err); StartLLQPolling(m,q); return; }
81847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
81947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->ReqLease != llq->llqlease)
82047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			debugf("recvSetupResponse: requested lease %lu, granted lease %lu", q->ReqLease, llq->llqlease);
82147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
82247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// cache expiration in case we go to sleep before finishing setup
82347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ReqLease = llq->llqlease;
82447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->expire = m->timenow + ((mDNSs32)llq->llqlease * mDNSPlatformOneSecond);
82547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
82647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// update state
82747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->state  = LLQ_SecondaryRequest;
82847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->id     = llq->id;
82947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ntries = 0; // first attempt to send response
83047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		sendChallengeResponse(m, q, llq);
83147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
83247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (q->state == LLQ_SecondaryRequest)
83347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
83447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//LogInfo("Got LLQ_SecondaryRequest");
83547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
83647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Fix this immediately if not sooner.  Copy the id from the LLQOptData into our DNSQuestion struct.  This is only
83747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// an issue for private LLQs, because we skip parts 2 and 3 of the handshake.  This is related to a bigger
83847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// problem of the current implementation of TCP LLQ setup: we're not handling state transitions correctly
83947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// if the server sends back SERVFULL or STATIC.
84047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (PrivateQuery(q))
84147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
84247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("Private LLQ_SecondaryRequest; copying id %08X%08X", llq->id.l[0], llq->id.l[1]);
84347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->id = llq->id;
84447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
84547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
84647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (llq->err) { LogMsg("ERROR: recvSetupResponse %##s (%s) code %d from server", q->qname.c, DNSTypeName(q->qtype), llq->err); StartLLQPolling(m,q); return; }
84747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!mDNSSameOpaque64(&q->id, &llq->id))
84847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{ LogMsg("recvSetupResponse - ID changed.  discarding"); return; } // this can happen rarely (on packet loss + reordering)
84947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->state         = LLQ_Established;
85047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ntries        = 0;
85147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetLLQTimer(m, q, llq);
85247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
85347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		UpdateAutoTunnelDomainStatuses(m);
85447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
85547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
85647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
85747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
85847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport uDNS_LLQType uDNS_recvLLQResponse(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
85947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const mDNSAddr *const srcaddr, const mDNSIPPort srcport, DNSQuestion **matchQuestion)
86047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
86147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion pktQ, *q;
86247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (msg->h.numQuestions && getQuestion(msg, msg->data, end, 0, &pktQ))
86347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
86447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		const rdataOPT *opt = GetLLQOptData(m, msg, end);
86547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
86647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (q = m->Questions; q; q = q->next)
86747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
86847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->qtype == pktQ.qtype && q->qnamehash == pktQ.qnamehash && SameDomainName(&q->qname, &pktQ.qname))
86947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
87047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				debugf("uDNS_recvLLQResponse found %##s (%s) %d %#a %#a %X %X %X %X %d",
87147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->qname.c, DNSTypeName(q->qtype), q->state, srcaddr, &q->servAddr,
87247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					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);
87347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				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));
87447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (q->state == LLQ_Poll && mDNSSameOpaque16(msg->h.id, q->TargetQID))
87547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
87647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
87747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
87847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Don't reset the state to IntialRequest as we may write that to the dynamic store
87947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// and PrefPane might wrongly think that we are "Starting" instead of "Polling". If
88047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// we are in polling state because of NAT-PMP disabled or DoubleNAT, next LLQNATCallback
88147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// would kick us back to LLQInitialRequest. So, resetting the state here may not be useful.
88247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//
88347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// If we have a good NAT (neither NAT-PMP disabled nor Double-NAT), then we should not be
88447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// possibly in polling state. To be safe, we want to retry from the start in that case
88547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// as there may not be another LLQNATCallback
88647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//
88747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// NOTE: We can be in polling state if we cannot resolve the SOA record i.e, servAddr is set to
88847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// all ones. In that case, we would set it in LLQ_InitialRequest as it overrides the NAT-PMP or
88947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Double-NAT state.
89047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (!mDNSAddressIsOnes(&q->servAddr) && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) &&
89147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						!m->LLQNAT.Result)
89247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						{
89347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						debugf("uDNS_recvLLQResponse got poll response; moving to LLQ_InitialRequest for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
89447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->state         = LLQ_InitialRequest;
89547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						}
89647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->servPort      = zeroIPPort;		// Clear servPort so that startLLQHandshake will retry the GetZoneData processing
89747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry LLQ setup in approx 15 minutes
89847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->LastQTime     = m->timenow;
89947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					SetNextQueryTime(m, q);
90047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					*matchQuestion = q;
90147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					return uDNS_LLQ_Entire;		// uDNS_LLQ_Entire means flush stale records; assume a large effective TTL
90247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
90347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// 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
90447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else if (opt && q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Event && mDNSSameOpaque64(&opt->u.llq.id, &q->id))
90547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
90647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					mDNSu8 *ackEnd;
90747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//debugf("Sending LLQ ack for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
90847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					InitializeDNSMessage(&m->omsg.h, msg->h.id, ResponseFlags);
90947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					ackEnd = putLLQ(&m->omsg, m->omsg.data, q, &opt->u.llq);
91047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (ackEnd) mDNSSendDNSMessage(m, &m->omsg, ackEnd, mDNSInterface_Any, q->LocalSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
91147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
91247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					debugf("uDNS_LLQ_Events: q->state == LLQ_Established msg->h.id %d q->TargetQID %d", mDNSVal16(msg->h.id), mDNSVal16(q->TargetQID));
91347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					*matchQuestion = q;
91447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					return uDNS_LLQ_Events;
91547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
91647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (opt && mDNSSameOpaque16(msg->h.id, q->TargetQID))
91747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
91847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Refresh && mDNSSameOpaque64(&opt->u.llq.id, &q->id) && msg->h.numAdditionals && !msg->h.numAnswers)
91947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						{
92047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						if (opt->u.llq.err != LLQErr_NoError) LogMsg("recvRefreshReply: received error %d from server", opt->u.llq.err);
92147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						else
92247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							{
92347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							//LogInfo("Received refresh confirmation ntries %d for %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
92447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							// If we're waiting to go to sleep, then this LLQ deletion may have been the thing
92547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							// we were waiting for, so schedule another check to see if we can sleep now.
92647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							if (opt->u.llq.llqlease == 0 && m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
92747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							GrantCacheExtensions(m, q, opt->u.llq.llqlease);
92847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							SetLLQTimer(m, q, &opt->u.llq);
92947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							q->ntries = 0;
93047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							}
93147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
93247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						*matchQuestion = q;
93347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						return uDNS_LLQ_Ignore;
93447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						}
93547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->state < LLQ_Established && mDNSSameAddress(srcaddr, &q->servAddr))
93647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						{
93747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						LLQ_State oldstate = q->state;
93847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						recvSetupResponse(m, msg->h.flags.b[1] & kDNSFlag1_RC_Mask, q, &opt->u.llq);
93947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
94047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						// We have a protocol anomaly here in the LLQ definition.
94147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						// Both the challenge packet from the server and the ack+answers packet have opt->u.llq.llqOp == kLLQOp_Setup.
94247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						// However, we need to treat them differently:
94347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						// The challenge packet has no answers in it, and tells us nothing about whether our cache entries
94447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						// are still valid, so this packet should not cause us to do anything that messes with our cache.
94547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						// The ack+answers packet gives us the whole truth, so we should handle it by updating our cache
94647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						// to match the answers in the packet, and only the answers in the packet.
94747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						*matchQuestion = q;
94847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						return (oldstate == LLQ_SecondaryRequest ? uDNS_LLQ_Entire : uDNS_LLQ_Ignore);
94947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						}
95047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
95147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
95247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
95347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
95447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
95547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	*matchQuestion = mDNSNULL;
95647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return uDNS_LLQ_Not;
95747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
95847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
95947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
96047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwaltstruct TCPSocket_struct { TCPSocketFlags flags; /* ... */ };
96147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
96247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// tcpCallback is called to handle events (e.g. connection opening and data reception) on TCP connections for
96347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Private DNS operations -- private queries, private LLQs, private record updates and private service updates
96447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void tcpCallback(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err)
96547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
96647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	tcpInfo_t *tcpInfo = (tcpInfo_t *)context;
96747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool   closed  = mDNSfalse;
96847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS      *m       = tcpInfo->m;
96947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *const q = tcpInfo->question;
97047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	tcpInfo_t **backpointer =
97147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q                 ? &q           ->tcp :
97247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		tcpInfo->rr       ? &tcpInfo->rr ->tcp : mDNSNULL;
97347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (backpointer && *backpointer != tcpInfo)
97447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("tcpCallback: %d backpointer %p incorrect tcpInfo %p question %p rr %p",
97547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSPlatformTCPGetFD(tcpInfo->sock), *backpointer, tcpInfo, q, tcpInfo->rr);
97647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
97747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err) goto exit;
97847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
97947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (ConnectionEstablished)
98047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
98147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSu8    *end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
98247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DomainAuthInfo *AuthInfo;
98347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
98447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Defensive coding for <rdar://problem/5546824> Crash in mDNSResponder at GetAuthInfoForName_internal + 366
98547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// 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
98647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (tcpInfo->rr && tcpInfo->rr->resrec.name != &tcpInfo->rr->namestorage)
98747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("tcpCallback: ERROR: tcpInfo->rr->resrec.name %p != &tcpInfo->rr->namestorage %p",
98847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				tcpInfo->rr->resrec.name, &tcpInfo->rr->namestorage);
98947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (tcpInfo->rr  && tcpInfo->rr->        resrec.name != &tcpInfo->rr->        namestorage) return;
99047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
99147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AuthInfo =  tcpInfo->rr  ? GetAuthInfoForName(m, tcpInfo->rr->resrec.name)         : mDNSNULL;
99247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
99347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// connection is established - send the message
99447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q && q->LongLived && q->state == LLQ_Established)
99547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
99647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Lease renewal over TCP, resulting from opening a TCP connection in sendLLQRefresh
99747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
99847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
99947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (q && q->LongLived && q->state != LLQ_Poll && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) && !mDNSIPPortIsZero(q->servPort))
100047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
100147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Notes:
100247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we have a NAT port mapping, ExternalPort is the external port
100347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we have a routable address so we don't need a port mapping, ExternalPort is the same as our own internal port
100447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we need a NAT port mapping but can't get one, then ExternalPort is zero
100547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LLQOptData llqData;			// set llq rdata
100647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.vers  = kLLQ_Vers;
100747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.llqOp = kLLQOp_Setup;
100847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.err   = GetLLQEventPort(m, &tcpInfo->Addr);	// We're using TCP; tell server what UDP port to send notifications to
100947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("tcpCallback: eventPort %d", llqData.err);
101047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.id    = zeroOpaque64;
101147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.llqlease = kLLQ_DefLease;
101247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
101347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			end = putLLQ(&tcpInfo->request, tcpInfo->request.data, q, &llqData);
101447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!end) { LogMsg("ERROR: tcpCallback - putLLQ"); err = mStatus_UnknownErr; goto exit; }
101547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			AuthInfo = q->AuthInfo;		// Need to add TSIG to this message
101647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->ntries = 0; // Reset ntries so that tcp/tls connection failures don't affect sendChallengeResponse failures
101747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
101847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (q)
101947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
102047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// LLQ Polling mode or non-LLQ uDNS over TCP
102147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
102247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			end = putQuestion(&tcpInfo->request, tcpInfo->request.data, tcpInfo->request.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
102347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			AuthInfo = q->AuthInfo;		// Need to add TSIG to this message
102447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
102547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
102647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		err = mDNSSendDNSMessage(m, &tcpInfo->request, end, mDNSInterface_Any, mDNSNULL, &tcpInfo->Addr, tcpInfo->Port, sock, AuthInfo);
102747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) { debugf("ERROR: tcpCallback: mDNSSendDNSMessage - %d", err); err = mStatus_UnknownErr; goto exit; }
102847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
102947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Record time we sent this question
103047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q)
103147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
103247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_Lock(m);
103347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->LastQTime = m->timenow;
103447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q->ThisQInterval < (256 * mDNSPlatformOneSecond))	// Now we have a TCP connection open, make sure we wait at least 256 seconds before retrying
103547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->ThisQInterval = (256 * mDNSPlatformOneSecond);
103647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			SetNextQueryTime(m, q);
103747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_Unlock(m);
103847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
103947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
104047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
104147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
104247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		long n;
104347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (tcpInfo->nread < 2)			// First read the two-byte length preceeding the DNS message
104447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
104547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu8 *lenptr = (mDNSu8 *)&tcpInfo->replylen;
104647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			n = mDNSPlatformReadTCP(sock, lenptr + tcpInfo->nread, 2 - tcpInfo->nread, &closed);
104747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (n < 0)
104847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
104947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("ERROR: tcpCallback - attempt to read message length failed (%d)", n);
105047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err = mStatus_ConnFailed;
105147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				goto exit;
105247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
105347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else if (closed)
105447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
105547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// It's perfectly fine for this socket to close after the first reply. The server might
105647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// be sending gratuitous replies using UDP and doesn't have a need to leave the TCP socket open.
105747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// We'll only log this event if we've never received a reply before.
105847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// BIND 9 appears to close an idle connection after 30 seconds.
105947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (tcpInfo->numReplies == 0)
106047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
106147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
106247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					err = mStatus_ConnFailed;
106347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					goto exit;
106447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
106547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else
106647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
106747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Note that we may not be doing the best thing if an error occurs after we've sent a second request
106847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// over this tcp connection.  That is, we only track whether we've received at least one response
106947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// which may have been to a previous request sent over this tcp connection.
107047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
107147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					DisposeTCPConn(tcpInfo);
107247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					return;
107347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
107447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
107547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
107647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tcpInfo->nread += n;
107747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (tcpInfo->nread < 2) goto exit;
107847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
107947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tcpInfo->replylen = (mDNSu16)((mDNSu16)lenptr[0] << 8 | lenptr[1]);
108047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (tcpInfo->replylen < sizeof(DNSMessageHeader))
108147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{ LogMsg("ERROR: tcpCallback - length too short (%d bytes)", tcpInfo->replylen); err = mStatus_UnknownErr; goto exit; }
108247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
108347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tcpInfo->reply = mDNSPlatformMemAllocate(tcpInfo->replylen);
108447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!tcpInfo->reply) { LogMsg("ERROR: tcpCallback - malloc failed"); err = mStatus_NoMemoryErr; goto exit; }
108547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
108647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
108747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		n = mDNSPlatformReadTCP(sock, ((char *)tcpInfo->reply) + (tcpInfo->nread - 2), tcpInfo->replylen - (tcpInfo->nread - 2), &closed);
108847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
108947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (n < 0)
109047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
109147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("ERROR: tcpCallback - read returned %d", n);
109247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			err = mStatus_ConnFailed;
109347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			goto exit;
109447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
109547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (closed)
109647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
109747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (tcpInfo->numReplies == 0)
109847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
109947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
110047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err = mStatus_ConnFailed;
110147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				goto exit;
110247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
110347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
110447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
110547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// Note that we may not be doing the best thing if an error occurs after we've sent a second request
110647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// over this tcp connection.  That is, we only track whether we've received at least one response
110747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// which may have been to a previous request sent over this tcp connection.
110847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
110947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				DisposeTCPConn(tcpInfo);
111047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				return;
111147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
111247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
111347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
111447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		tcpInfo->nread += n;
111547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
111647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if ((tcpInfo->nread - 2) == tcpInfo->replylen)
111747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
111847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSBool tls;
111947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DNSMessage *reply = tcpInfo->reply;
112047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu8     *end   = (mDNSu8 *)tcpInfo->reply + tcpInfo->replylen;
112147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSAddr    Addr  = tcpInfo->Addr;
112247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSIPPort  Port  = tcpInfo->Port;
112347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSIPPort srcPort = zeroIPPort;
112447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tcpInfo->numReplies++;
112547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tcpInfo->reply    = mDNSNULL;	// Detach reply buffer from tcpInfo_t, to make sure client callback can't cause it to be disposed
112647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tcpInfo->nread    = 0;
112747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tcpInfo->replylen = 0;
112847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
112947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we're going to dispose this connection, do it FIRST, before calling client callback
113047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Note: Sleep code depends on us clearing *backpointer here -- it uses the clearing of rr->tcp
113147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// as the signal that the DNS deregistration operation with the server has completed, and the machine may now sleep
113247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we clear the tcp pointer in the question, mDNSCoreReceiveResponse cannot find a matching question. Hence
113347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// we store the minimal information i.e., the source port of the connection in the question itself.
113447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Dereference sock before it is disposed in DisposeTCPConn below.
113547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
113647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (sock->flags & kTCPSocketFlags_UseTLS) tls = mDNStrue;
113747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else tls = mDNSfalse;
113847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
113947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q && q->tcp) {srcPort = q->tcp->SrcPort; q->tcpSrcPort = srcPort;}
114047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
114147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (backpointer)
114247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!q || !q->LongLived || m->SleepState)
114347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{ *backpointer = mDNSNULL; DisposeTCPConn(tcpInfo); }
114447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
114547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSCoreReceive(m, reply, end, &Addr, Port, tls ? (mDNSAddr *)1 : mDNSNULL, srcPort, 0);
114647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// USE CAUTION HERE: Invoking mDNSCoreReceive may have caused the environment to change, including canceling this operation itself
114747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
114847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSPlatformMemFree(reply);
114947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
115047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
115147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
115247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
115347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwaltexit:
115447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
115547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err)
115647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
115747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Clear client backpointer FIRST -- that way if one of the callbacks cancels its operation
115847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// we won't end up double-disposing our tcpInfo_t
115947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (backpointer) *backpointer = mDNSNULL;
116047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
116147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Lock(m);		// Need to grab the lock to get m->timenow
116247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
116347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q)
116447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
116547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q->ThisQInterval == 0)
116647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
116747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// 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.
116847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// Note that ThisQInterval is also zero when sendChallengeResponse resends the LLQ request on an extant TCP/TLS connection.
116947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->LastQTime = m->timenow;
117047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (q->LongLived)
117147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
117247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// We didn't get the chance to send our request packet before the TCP/TLS connection failed.
117347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// We want to retry quickly, but want to back off exponentially in case the server is having issues.
117447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Since ThisQInterval was 0, we can't just multiply by QuestionIntervalStep, we must track the number
117547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// of TCP/TLS connection failures using ntries.
117647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					mDNSu32 count = q->ntries + 1; // want to wait at least 1 second before retrying
117747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
117847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->ThisQInterval = InitialQuestionInterval;
117947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
118047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					for (;count;count--)
118147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->ThisQInterval *= QuestionIntervalStep;
118247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
118347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->ThisQInterval > LLQ_POLL_INTERVAL)
118447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->ThisQInterval = LLQ_POLL_INTERVAL;
118547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					else
118647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->ntries++;
118747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
118847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					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);
118947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
119047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else
119147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
119247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
119347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
119447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
119547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				SetNextQueryTime(m, q);
119647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
119747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else if (NextQSendTime(q) - m->timenow > (q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL))
119847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
119947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// If we get an error and our next scheduled query for this question is more than the max interval from now,
120047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// reset the next query to ensure we wait no longer the maximum interval from now before trying again.
120147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->LastQTime     = m->timenow;
120247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->ThisQInterval = q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL;
120347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				SetNextQueryTime(m, q);
120447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
120547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
120647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
120747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We're about to dispose of the TCP connection, so we must reset the state to retry over TCP/TLS
120847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// because sendChallengeResponse will send the query via UDP if we don't have a tcp pointer.
120947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Resetting to LLQ_InitialRequest will cause uDNS_CheckCurrentQuestion to call startLLQHandshake, which
121047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// will attempt to establish a new tcp connection.
121147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q->LongLived && q->state == LLQ_SecondaryRequest)
121247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->state = LLQ_InitialRequest;
121347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
121447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// ConnFailed may happen if the server sends a TCP reset or TLS fails, in which case we want to retry establishing the LLQ
121547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// quickly rather than switching to polling mode.  This case is handled by the above code to set q->ThisQInterval just above.
121647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If the error isn't ConnFailed, then the LLQ is in bad shape, so we switch to polling mode.
121747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (err != mStatus_ConnFailed)
121847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
121947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (q->LongLived && q->state != LLQ_Poll) StartLLQPolling(m, q);
122047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
122147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
122247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
122347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Unlock(m);
122447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
122547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DisposeTCPConn(tcpInfo);
122647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
122747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
122847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
122947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal tcpInfo_t *MakeTCPConn(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
123047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	TCPSocketFlags flags, const mDNSAddr *const Addr, const mDNSIPPort Port, domainname *hostname,
123147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *const question, AuthRecord *const rr)
123247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
123347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err;
123447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSIPPort srcport = zeroIPPort;
123547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	tcpInfo_t *info;
123647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
123747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if ((flags & kTCPSocketFlags_UseTLS) && (!hostname || !hostname->c[0]))
123847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ LogMsg("MakeTCPConn: TLS connection being setup with NULL hostname"); return mDNSNULL; }
123947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
124047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info = (tcpInfo_t *)mDNSPlatformMemAllocate(sizeof(tcpInfo_t));
124147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!info) { LogMsg("ERROR: MakeTCP - memallocate failed"); return(mDNSNULL); }
124247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformMemZero(info, sizeof(tcpInfo_t));
124347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
124447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->m          = m;
124547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->sock       = mDNSPlatformTCPSocket(m, flags, &srcport);
124647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->requestLen = 0;
124747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->question   = question;
124847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->rr         = rr;
124947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->Addr       = *Addr;
125047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->Port       = Port;
125147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->reply      = mDNSNULL;
125247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->replylen   = 0;
125347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->nread      = 0;
125447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->numReplies = 0;
125547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info->SrcPort = srcport;
125647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
125747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (msg)
125847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
125947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		info->requestLen = (int) (end - ((mDNSu8*)msg));
126047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSPlatformMemCopy(&info->request, msg, info->requestLen);
126147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
126247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
126347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!info->sock) { LogMsg("MakeTCPConn: unable to create TCP socket"); mDNSPlatformMemFree(info); return(mDNSNULL); }
126447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	err = mDNSPlatformTCPConnect(info->sock, Addr, Port, hostname, (question ? question->InterfaceID : mDNSNULL), tcpCallback, info);
126547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
126647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Probably suboptimal here.
126747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Instead of returning mDNSNULL here on failure, we should probably invoke the callback with an error code.
126847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// That way clients can put all the error handling and retry/recovery code in one place,
126947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// instead of having to handle immediate errors in one place and async errors in another.
127047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Also: "err == mStatus_ConnEstablished" probably never happens.
127147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
127247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Don't need to log "connection failed" in customer builds -- it happens quite often during sleep, wake, configuration changes, etc.
127347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if      (err == mStatus_ConnEstablished) { tcpCallback(info->sock, info, mDNStrue, mStatus_NoError); }
127447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (err != mStatus_ConnPending    ) { LogInfo("MakeTCPConn: connection failed"); DisposeTCPConn(info); return(mDNSNULL); }
127547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(info);
127647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
127747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
127847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void DisposeTCPConn(struct tcpInfo_t *tcp)
127947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
128047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformTCPCloseConnection(tcp->sock);
128147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (tcp->reply) mDNSPlatformMemFree(tcp->reply);
128247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformMemFree(tcp);
128347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
128447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
128547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Lock must be held
128647e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void startLLQHandshake(mDNS *m, DNSQuestion *q)
128747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
128847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (mDNSIPv4AddressIsOnes(m->LLQNAT.ExternalAddress))
128947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
129047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("startLLQHandshake: waiting for NAT status for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
129147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry in approx 15 minutes
129247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->LastQTime = m->timenow;
129347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNextQueryTime(m, q);
129447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
129547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
129647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
129747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Either we don't have NAT-PMP support (ExternalPort is zero) or behind a Double NAT that may or
129847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// may not have NAT-PMP support (NATResult is non-zero)
129947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (mDNSIPPortIsZero(m->LLQNAT.ExternalPort) || m->LLQNAT.Result)
130047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
130147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("startLLQHandshake: Cannot receive inbound packets; will poll for %##s (%s) External Port %d, NAT Result %d",
130247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->qname.c, DNSTypeName(q->qtype), mDNSVal16(m->LLQNAT.ExternalPort), m->LLQNAT.Result);
130347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		StartLLQPolling(m, q);
130447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
130547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
130647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
130747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (mDNSIPPortIsZero(q->servPort))
130847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
130947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("startLLQHandshake: StartGetZoneData for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
131047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry in approx 15 minutes
131147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->LastQTime     = m->timenow;
131247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNextQueryTime(m, q);
131347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->servAddr = zeroAddr;
131447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We know q->servPort is zero because of check above
131547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->nta) CancelGetZoneData(m, q->nta);
131647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
131747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
131847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
131947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
132047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (PrivateQuery(q))
132147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
132247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->tcp) LogInfo("startLLQHandshake: Disposing existing TCP connection for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
132347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
132447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!q->nta)
132547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
132647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Normally we lookup the zone data and then call this function. And we never free the zone data
132747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// for "PrivateQuery". But sometimes this can happen due to some race conditions. When we
132847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// switch networks, we might end up "Polling" the network e.g., we are behind a Double NAT.
132947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// When we poll, we free the zone information as we send the query to the server (See
133047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// PrivateQueryGotZoneData). The NAT callback (LLQNATCallback) may happen soon after that. If we
133147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// are still behind Double NAT, we would have returned early in this function. But we could
133247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// have switched to a network with no NATs and we should get the zone data again.
133347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("startLLQHandshake: nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
133447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
133547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
133647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
133747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (!q->nta->Host.c[0])
133847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
133947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// This should not happen. If it happens, we print a log and MakeTCPConn will fail if it can't find a hostname
134047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			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);
134147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
134247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
134347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!q->tcp)
134447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->ThisQInterval = mDNSPlatformOneSecond * 5;	// If TCP failed (transient networking glitch) try again in five seconds
134547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
134647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
134747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->state         = LLQ_SecondaryRequest;		// Right now, for private DNS, we skip the four-way LLQ handshake
134847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->ReqLease      = kLLQ_DefLease;
134947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->ThisQInterval = 0;
135047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
135147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->LastQTime     = m->timenow;
135247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNextQueryTime(m, q);
135347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
135447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
135547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
135647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("startLLQHandshake: m->AdvertisedV4 %#a%s Server %#a:%d%s %##s (%s)",
135747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			&m->AdvertisedV4,                     mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) ? " (RFC 1918)" : "",
135847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			&q->servAddr, mDNSVal16(q->servPort), mDNSAddrIsRFC1918(&q->servAddr)             ? " (RFC 1918)" : "",
135947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->qname.c, DNSTypeName(q->qtype));
136047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
136147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->ntries++ >= kLLQ_MAX_TRIES)
136247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
136347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("startLLQHandshake: %d failed attempts for LLQ %##s Polling.", kLLQ_MAX_TRIES, q->qname.c);
136447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			StartLLQPolling(m, q);
136547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
136647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
136747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
136847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu8 *end;
136947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LLQOptData llqData;
137047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
137147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// set llq rdata
137247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.vers  = kLLQ_Vers;
137347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.llqOp = kLLQOp_Setup;
137447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.err   = LLQErr_NoError;	// Don't need to tell server UDP notification port when sending over UDP
137547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.id    = zeroOpaque64;
137647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			llqData.llqlease = kLLQ_DefLease;
137747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
137847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
137947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			end = putLLQ(&m->omsg, m->omsg.data, q, &llqData);
138047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!end) { LogMsg("ERROR: startLLQHandshake - putLLQ"); StartLLQPolling(m,q); return; }
138147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
138247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
138347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
138447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// update question state
138547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->state         = LLQ_InitialRequest;
138647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->ReqLease      = kLLQ_DefLease;
138747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->ThisQInterval = (kLLQ_INIT_RESEND * mDNSPlatformOneSecond);
138847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->LastQTime     = m->timenow;
138947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			SetNextQueryTime(m, q);
139047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
139147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
139247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
139347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
139447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// forward declaration so GetServiceTarget can do reverse lookup if needed
139547e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void GetStaticHostname(mDNS *m);
139647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
139747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport const domainname *GetServiceTarget(mDNS *m, AuthRecord *const rr)
139847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
139947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("GetServiceTarget %##s", rr->resrec.name->c);
140047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
140147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr->AutoTarget)		// If not automatically tracking this host's current name, just return the existing target
140247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return(&rr->resrec.rdata->u.srv.target);
140347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
140447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
140547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
140647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
140747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (AuthInfo && AuthInfo->AutoTunnel)
140847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
140947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If this AutoTunnel is not yet active, start it now (which entails activating its NAT Traversal request,
141047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// which will subsequently advertise the appropriate records when the NAT Traversal returns a result)
141147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!AuthInfo->AutoTunnelNAT.clientContext && m->AutoTunnelHostAddr.b[0])
141247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
141347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("GetServiceTarget: Calling SetupLocalAutoTunnelInterface_internal");
141447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				SetupLocalAutoTunnelInterface_internal(m, mDNStrue);
141547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
141647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (AuthInfo->AutoTunnelHostRecord.namestorage.c[0] == 0) return(mDNSNULL);
141747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			debugf("GetServiceTarget: Returning %##s", AuthInfo->AutoTunnelHostRecord.namestorage.c);
141847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return(&AuthInfo->AutoTunnelHostRecord.namestorage);
141947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
142047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
142147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif // APPLE_OSX_mDNSResponder
142247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
142347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			const int srvcount = CountLabels(rr->resrec.name);
142447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			HostnameInfo *besthi = mDNSNULL, *hi;
142547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			int best = 0;
142647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			for (hi = m->Hostnames; hi; hi = hi->next)
142747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (hi->arv4.state == regState_Registered || hi->arv4.state == regState_Refresh ||
142847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					hi->arv6.state == regState_Registered || hi->arv6.state == regState_Refresh)
142947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
143047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					int x, hostcount = CountLabels(&hi->fqdn);
143147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					for (x = hostcount < srvcount ? hostcount : srvcount; x > 0 && x > best; x--)
143247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						if (SameDomainName(SkipLeadingLabels(rr->resrec.name, srvcount - x), SkipLeadingLabels(&hi->fqdn, hostcount - x)))
143347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							{ best = x; besthi = hi; }
143447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
143547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
143647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (besthi) return(&besthi->fqdn);
143747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
143847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->StaticHostname.c[0]) return(&m->StaticHostname);
143947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else GetStaticHostname(m); // asynchronously do reverse lookup for primary IPv4 address
144047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("GetServiceTarget: Returning NULL for %s", ARDisplayString(m, rr));
144147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return(mDNSNULL);
144247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
144347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
144447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
144547e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal const domainname *PUBLIC_UPDATE_SERVICE_TYPE  = (const domainname*)"\x0B_dns-update"     "\x04_udp";
144647e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal const domainname *PUBLIC_LLQ_SERVICE_TYPE     = (const domainname*)"\x08_dns-llq"        "\x04_udp";
144747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
144847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal const domainname *PRIVATE_UPDATE_SERVICE_TYPE = (const domainname*)"\x0F_dns-update-tls" "\x04_tcp";
144947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal const domainname *PRIVATE_QUERY_SERVICE_TYPE  = (const domainname*)"\x0E_dns-query-tls"  "\x04_tcp";
145047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal const domainname *PRIVATE_LLQ_SERVICE_TYPE    = (const domainname*)"\x0C_dns-llq-tls"    "\x04_tcp";
145147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
145247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#define ZoneDataSRV(X) (\
145347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(X)->ZoneService == ZoneServiceUpdate ? ((X)->ZonePrivate ? PRIVATE_UPDATE_SERVICE_TYPE : PUBLIC_UPDATE_SERVICE_TYPE) : \
145447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(X)->ZoneService == ZoneServiceQuery  ? ((X)->ZonePrivate ? PRIVATE_QUERY_SERVICE_TYPE  : (const domainname*)""     ) : \
145547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(X)->ZoneService == ZoneServiceLLQ    ? ((X)->ZonePrivate ? PRIVATE_LLQ_SERVICE_TYPE    : PUBLIC_LLQ_SERVICE_TYPE   ) : (const domainname*)"")
145647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
145747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Forward reference: GetZoneData_StartQuery references GetZoneData_QuestionCallback, and
145847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// GetZoneData_QuestionCallback calls GetZoneData_StartQuery
145947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype);
146047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
146147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// GetZoneData_QuestionCallback is called from normal client callback context (core API calls allowed)
146247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void GetZoneData_QuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
146347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
146447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ZoneData *zd = (ZoneData*)question->QuestionContext;
146547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
146647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("GetZoneData_QuestionCallback: %s %s", AddRecord ? "Add" : "Rmv", RRDisplayString(m, answer));
146747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
146847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!AddRecord) return;												// Don't care about REMOVE events
146947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AddRecord == QC_addnocache && answer->rdlength == 0) return;	// Don't care about transient failure indications
147047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (answer->rrtype != question->qtype) return;						// Don't care about CNAMEs
147147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
147247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (answer->rrtype == kDNSType_SOA)
147347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
147447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("GetZoneData GOT SOA %s", RRDisplayString(m, answer));
147547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_StopQuery(m, question);
147647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (question->ThisQInterval != -1)
147747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
147847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (answer->rdlength)
147947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
148047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			AssignDomainName(&zd->ZoneName, answer->name);
148147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			zd->ZoneClass = answer->rrclass;
148247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			AssignDomainName(&zd->question.qname, &zd->ZoneName);
148347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			GetZoneData_StartQuery(m, zd, kDNSType_SRV);
148447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
148547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (zd->CurrentSOA->c[0])
148647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
148747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DomainAuthInfo *AuthInfo = GetAuthInfoForName(m, zd->CurrentSOA);
148847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (AuthInfo && AuthInfo->AutoTunnel)
148947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
149047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// To keep the load on the server down, we don't chop down on
149147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// SOA lookups for AutoTunnels
149247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("GetZoneData_QuestionCallback: not chopping labels for %##s", zd->CurrentSOA->c);
149347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
149447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
149547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
149647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
149747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->CurrentSOA = (domainname *)(zd->CurrentSOA->c + zd->CurrentSOA->c[0]+1);
149847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				AssignDomainName(&zd->question.qname, zd->CurrentSOA);
149947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				GetZoneData_StartQuery(m, zd, kDNSType_SOA);
150047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
150147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
150247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
150347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
150447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("GetZoneData recursed to root label of %##s without finding SOA", zd->ChildName.c);
150547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
150647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
150747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
150847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (answer->rrtype == kDNSType_SRV)
150947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
151047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("GetZoneData GOT SRV %s", RRDisplayString(m, answer));
151147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_StopQuery(m, question);
151247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (question->ThisQInterval != -1)
151347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
151447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Right now we don't want to fail back to non-encrypted operations
151547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// If the AuthInfo has the AutoTunnel field set, then we want private or nothing
151647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// <rdar://problem/5687667> BTMM: Don't fallback to unencrypted operations when SRV lookup fails
151747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if 0
151847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!answer->rdlength && zd->ZonePrivate && zd->ZoneService != ZoneServiceQuery)
151947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
152047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			zd->ZonePrivate = mDNSfalse;	// Causes ZoneDataSRV() to yield a different SRV name when building the query
152147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			GetZoneData_StartQuery(m, zd, kDNSType_SRV);		// Try again, non-private this time
152247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
152347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
152447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
152547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
152647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (answer->rdlength)
152747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
152847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				AssignDomainName(&zd->Host, &answer->rdata->u.srv.target);
152947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->Port = answer->rdata->u.srv.port;
153047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				AssignDomainName(&zd->question.qname, &zd->Host);
153147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				GetZoneData_StartQuery(m, zd, kDNSType_A);
153247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
153347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
153447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
153547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->ZonePrivate = mDNSfalse;
153647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->Host.c[0] = 0;
153747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->Port = zeroIPPort;
153847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->Addr = zeroAddr;
153947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zd->ZoneDataCallback(m, mStatus_NoError, zd);
154047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
154147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
154247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
154347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (answer->rrtype == kDNSType_A)
154447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
154547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("GetZoneData GOT A %s", RRDisplayString(m, answer));
154647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_StopQuery(m, question);
154747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (question->ThisQInterval != -1)
154847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
154947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->Addr.type  = mDNSAddrType_IPv4;
155047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->Addr.ip.v4 = (answer->rdlength == 4) ? answer->rdata->u.ipv4 : zerov4Addr;
155147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// In order to simulate firewalls blocking our outgoing TCP connections, returning immediate ICMP errors or TCP resets,
155247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// the code below will make us try to connect to loopback, resulting in an immediate "port unreachable" failure.
155347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// This helps us test to make sure we handle this case gracefully
155447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// <rdar://problem/5607082> BTMM: mDNSResponder taking 100 percent CPU after upgrading to 10.5.1
155547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if 0
155647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->Addr.ip.v4.b[0] = 127;
155747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->Addr.ip.v4.b[1] = 0;
155847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->Addr.ip.v4.b[2] = 0;
155947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->Addr.ip.v4.b[3] = 1;
156047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
156147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// The caller needs to free the memory when done with zone data
156247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->ZoneDataCallback(m, mStatus_NoError, zd);
156347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
156447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
156547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
156647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// GetZoneData_StartQuery is called from normal client context (lock not held, or client callback)
156747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype)
156847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
156947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (qtype == kDNSType_SRV)
157047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
157147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&zd->question.qname, ZoneDataSRV(zd));
157247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AppendDomainName(&zd->question.qname, &zd->ZoneName);
157347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("lookupDNSPort %##s", zd->question.qname.c);
157447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
157547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
157647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// CancelGetZoneData can get called at any time. We should stop the question if it has not been
157747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// stopped already. A value of -1 for ThisQInterval indicates that the question is not active
157847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// yet.
157947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.ThisQInterval       = -1;
158047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.InterfaceID         = mDNSInterface_Any;
158147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.Target              = zeroAddr;
158247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//zd->question.qname.c[0]        = 0;			// Already set
158347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.qtype               = qtype;
158447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.qclass              = kDNSClass_IN;
158547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.LongLived           = mDNSfalse;
158647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.ExpectUnique        = mDNStrue;
158747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.ForceMCast          = mDNSfalse;
158847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.ReturnIntermed      = mDNStrue;
158947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.SuppressUnusable    = mDNSfalse;
159047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.SearchListIndex     = 0;
159147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.AppendSearchDomains = 0;
159247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.RetryWithSearchDomains = mDNSfalse;
159347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.TimeoutQuestion     = 0;
159447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.WakeOnResolve       = 0;
159547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.qnameOrig           = mDNSNULL;
159647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.QuestionCallback    = GetZoneData_QuestionCallback;
159747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.QuestionContext     = zd;
159847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
159947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//LogMsg("GetZoneData_StartQuery %##s (%s) %p", zd->question.qname.c, DNSTypeName(zd->question.qtype), zd->question.Private);
160047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(mDNS_StartQuery(m, &zd->question));
160147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
160247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
160347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// StartGetZoneData is an internal routine (i.e. must be called with the lock already held)
160447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *ZoneDataContext)
160547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
160647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, name);
160747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int initialskip = (AuthInfo && AuthInfo->AutoTunnel) ? DomainNameLength(name) - DomainNameLength(&AuthInfo->domain) : 0;
160847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ZoneData *zd = (ZoneData*)mDNSPlatformMemAllocate(sizeof(ZoneData));
160947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!zd) { LogMsg("ERROR: StartGetZoneData - mDNSPlatformMemAllocate failed"); return mDNSNULL; }
161047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformMemZero(zd, sizeof(ZoneData));
161147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AssignDomainName(&zd->ChildName, name);
161247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->ZoneService      = target;
161347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->CurrentSOA       = (domainname *)(&zd->ChildName.c[initialskip]);
161447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->ZoneName.c[0]    = 0;
161547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->ZoneClass        = 0;
161647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->Host.c[0]        = 0;
161747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->Port             = zeroIPPort;
161847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->Addr             = zeroAddr;
161947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->ZonePrivate      = AuthInfo && AuthInfo->AutoTunnel ? mDNStrue : mDNSfalse;
162047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->ZoneDataCallback = callback;
162147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->ZoneDataContext  = ZoneDataContext;
162247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
162347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	zd->question.QuestionContext = zd;
162447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
162547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_DropLockBeforeCallback();		// GetZoneData_StartQuery expects to be called from a normal callback, so we emulate that here
162647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AuthInfo && AuthInfo->AutoTunnel && !mDNSIPPortIsZero(AuthInfo->port))
162747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
162847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("StartGetZoneData: Bypassing SOA, SRV query for %##s", AuthInfo->domain.c);
162947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We bypass SOA and SRV queries if we know the hostname and port already from the configuration.
163047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Today this is only true for AutoTunnel. As we bypass, we need to infer a few things:
163147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//
163247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// 1. Zone name is the same as the AuthInfo domain
163347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// 2. ZoneClass is kDNSClass_IN which should be a safe assumption
163447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//
163547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// If we want to make this bypass mechanism work for non-AutoTunnels also, (1) has to hold
163647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// good. Otherwise, it has to be configured also.
163747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
163847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&zd->ZoneName, &AuthInfo->domain);
163947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->ZoneClass = kDNSClass_IN;
164047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&zd->Host, &AuthInfo->hostname);
164147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zd->Port = AuthInfo->port;
164247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&zd->question.qname, &zd->Host);
164347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		GetZoneData_StartQuery(m, zd, kDNSType_A);
164447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
164547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
164647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
164747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (AuthInfo && AuthInfo->AutoTunnel) LogInfo("StartGetZoneData: Not Bypassing SOA, SRV query for %##s", AuthInfo->domain.c);
164847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&zd->question.qname, zd->CurrentSOA);
164947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		GetZoneData_StartQuery(m, zd, kDNSType_SOA);
165047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
165147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_ReclaimLockAfterCallback();
165247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
165347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return zd;
165447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
165547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
165647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Returns if the question is a GetZoneData question. These questions are special in
165747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// that they are created internally while resolving a private query or LLQs.
165847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mDNSBool IsGetZoneDataQuestion(DNSQuestion *q)
165947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
166047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNStrue);
166147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else return(mDNSfalse);
166247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
166347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
166447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// GetZoneData queries are a special case -- even if we have a key for them, we don't do them privately,
166547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// because that would result in an infinite loop (i.e. to do a private query we first need to get
166647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// the _dns-query-tls SRV record for the zone, and we can't do *that* privately because to do so
166747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// we'd need to already know the _dns-query-tls SRV record.
166847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Also, as a general rule, we never do SOA queries privately
166947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport DomainAuthInfo *GetAuthInfoForQuestion(mDNS *m, const DNSQuestion *const q)	// Must be called with lock held
167047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
167147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNSNULL);
167247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->qtype            == kDNSType_SOA                ) return(mDNSNULL);
167347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(GetAuthInfoForName_internal(m, &q->qname));
167447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
167547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
167647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
167747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
167847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - host name and interface management
167947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
168047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
168147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr);
168247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr);
168347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time);
168447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
168547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// When this function is called, service record is already deregistered. We just
168647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// have to deregister the PTR and TXT records.
168747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void UpdateAllServiceRecords(mDNS *const m, AuthRecord *rr, mDNSBool reg)
168847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
168947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *r, *srvRR;
169047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
169147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.rrtype != kDNSType_SRV) { LogMsg("UpdateAllServiceRecords:ERROR!! ResourceRecord not a service record %s", ARDisplayString(m, rr)); return; }
169247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
169347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (reg && rr->state == regState_NoTarget) { LogMsg("UpdateAllServiceRecords:ERROR!! SRV record %s in noTarget state during registration", ARDisplayString(m, rr)); return; }
169447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
169547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("UpdateAllServiceRecords: ResourceRecord %s", ARDisplayString(m, rr));
169647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
169747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (r = m->ResourceRecords; r; r=r->next)
169847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
169947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!AuthRecord_uDNS(r)) continue;
170047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		srvRR = mDNSNULL;
170147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (r->resrec.rrtype == kDNSType_PTR)
170247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			srvRR = r->Additional1;
170347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (r->resrec.rrtype == kDNSType_TXT)
170447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			srvRR = r->DependentOn;
170547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (srvRR && srvRR->resrec.rrtype != kDNSType_SRV)
170647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("UpdateAllServiceRecords: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
170747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (srvRR == rr)
170847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
170947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!reg)
171047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
171147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("UpdateAllServiceRecords: deregistering %s", ARDisplayString(m, r));
171247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				r->SRVChanged = mDNStrue;
171347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				r->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
171447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				r->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
171547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				r->state = regState_DeregPending;
171647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
171747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
171847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
171947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// Clearing SRVchanged is a safety measure. If our pevious dereg never
172047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// came back and we had a target change, we are starting fresh
172147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				r->SRVChanged = mDNSfalse;
172247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// if it is already registered or in the process of registering, then don't
172347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// bother re-registering. This happens today for non-BTMM domains where the
172447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// TXT and PTR get registered before SRV records because of the delay in
172547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// getting the port mapping. There is no point in re-registering the TXT
172647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// and PTR records.
172747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if ((r->state == regState_Registered) ||
172847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				    (r->state == regState_Pending && r->nta && !mDNSIPv4AddressIsZero(r->nta->Addr.ip.v4)))
172947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogInfo("UpdateAllServiceRecords: not registering %s, state %d", ARDisplayString(m, r), r->state);
173047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else
173147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
173247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogInfo("UpdateAllServiceRecords: registering %s, state %d", ARDisplayString(m, r), r->state);
173347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					ActivateUnicastRegistration(m, r);
173447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
173547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
173647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
173747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
173847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
173947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
174047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called in normal client context (lock not held)
174147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Currently only supports SRV records for nat mapping
174247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void CompleteRecordNatMap(mDNS *m, NATTraversalInfo *n)
174347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
174447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *target;
174547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	domainname *srvt;
174647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *rr = (AuthRecord *)n->clientContext;
174747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("SRVNatMap complete %.4a IntPort %u ExternalPort %u NATLease %u", &n->ExternalAddress, mDNSVal16(n->IntPort), mDNSVal16(n->ExternalPort), n->NATLease);
174847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
174947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr) { LogMsg("CompleteRecordNatMap called with unknown AuthRecord object"); return; }
175047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!n->NATLease) { LogMsg("CompleteRecordNatMap No NATLease for %s", ARDisplayString(m, rr)); return; }
175147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
175247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.rrtype != kDNSType_SRV) {LogMsg("CompleteRecordNatMap: Not a service record %s", ARDisplayString(m, rr)); return; }
175347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
175447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) { LogInfo("CompleteRecordNatMap called for %s, Service deregistering", ARDisplayString(m, rr)); return; }
175547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
175647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_DeregPending) { LogInfo("CompleteRecordNatMap called for %s, record in DeregPending", ARDisplayString(m, rr)); return; }
175747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
175847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// As we free the zone info after registering/deregistering with the server (See hndlRecordUpdateReply),
175947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// we need to restart the get zone data and nat mapping request to get the latest mapping result as we can't handle it
176047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// at this moment. Restart from the beginning.
176147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
176247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
176347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("CompleteRecordNatMap called for %s but no zone information!", ARDisplayString(m, rr));
176447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We need to clear out the NATinfo state so that it will result in re-acquiring the mapping
176547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// and hence this callback called again.
176647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->NATinfo.clientContext)
176747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
176847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
176947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->NATinfo.clientContext = mDNSNULL;
177047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
177147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->state = regState_Pending;
177247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
177347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
177447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
177547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
177647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
177747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
177847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Reevaluate the target always as Target could have changed while
177947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// we were getting the port mapping (See UpdateOneSRVRecord)
178047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	target = GetServiceTarget(m, rr);
178147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	srvt = GetRRDomainNameTarget(&rr->resrec);
178247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!target || target->c[0] == 0 || mDNSIPPortIsZero(n->ExternalPort))
178347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
178447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (target && target->c[0])
178547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
178647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
178747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("CompleteRecordNatMap - no target for %##s, ExternalPort %d", rr->resrec.name->c, mDNSVal16(n->ExternalPort));
178847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (srvt) srvt->c[0] = 0;
178947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->state = regState_NoTarget;
179047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->resrec.rdlength = rr->resrec.rdestimate = 0;
179147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Unlock(m);
179247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		UpdateAllServiceRecords(m, rr, mDNSfalse);
179347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
179447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
179547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
179647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// This function might get called multiple times during a network transition event. Previosuly, we could
179747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// have put the SRV record in NoTarget state above and deregistered all the other records. When this
179847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// function gets called again with a non-zero ExternalPort, we need to set the target and register the
179947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// other records again.
180047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (srvt && !SameDomainName(srvt, target))
180147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
180247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(srvt, target);
180347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNewRData(&rr->resrec, mDNSNULL, 0);		// Update rdlength, rdestimate, rdatahash
180447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
180547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
180647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// SRVChanged is set when when the target of the SRV record changes (See UpdateOneSRVRecord).
180747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// As a result of the target change, we might register just that SRV Record if it was
180847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// previously registered and we have a new target OR deregister SRV (and the associated
180947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// PTR/TXT records) if we don't have a target anymore. When we get a response from the server,
181047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// SRVChanged state tells that we registered/deregistered because of a target change
181147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// and hence handle accordingly e.g., if we deregistered, put the records in NoTarget state OR
181247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// if we registered then put it in Registered state.
181347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
181447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Here, we are registering all the records again from the beginning. Treat this as first time
181547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// registration rather than a temporary target change.
181647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->SRVChanged = mDNSfalse;
181747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
181847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We want IsRecordMergeable to check whether it is a record whose update can be
181947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// sent with others. We set the time before we call IsRecordMergeable, so that
182047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// it does not fail this record based on time. We are interested in other checks
182147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// at this time
182247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->state = regState_Pending;
182347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
182447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
182547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
182647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Delay the record registration by MERGE_DELAY_TIME so that we can merge them
182747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// into one update
182847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->LastAPTime += MERGE_DELAY_TIME;
182947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
183047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We call this always even though it may not be necessary always e.g., normal registration
183147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// process where TXT and PTR gets registered followed by the SRV record after it gets
183247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// the port mapping. In that case, UpdateAllServiceRecords handles the optimization. The
183347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// update of TXT and PTR record is required if we entered noTargetState before as explained
183447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// above.
183547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	UpdateAllServiceRecords(m, rr, mDNStrue);
183647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
183747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
183847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void StartRecordNatMap(mDNS *m, AuthRecord *rr)
183947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
184047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const mDNSu8 *p;
184147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 protocol;
184247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
184347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.rrtype != kDNSType_SRV)
184447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
184547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("StartRecordNatMap: Resource Record %##s type %d, not supported", rr->resrec.name->c, rr->resrec.rrtype);
184647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
184747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
184847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	p = rr->resrec.name->c;
184947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//Assume <Service Instance>.<App Protocol>.<Transport protocol>.<Name>
185047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Skip the first two labels to get to the transport protocol
185147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (p[0]) p += 1 + p[0];
185247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (p[0]) p += 1 + p[0];
185347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if      (SameDomainLabel(p, (mDNSu8 *)"\x4" "_tcp")) protocol = NATOp_MapTCP;
185447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_udp")) protocol = NATOp_MapUDP;
185547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else { LogMsg("StartRecordNatMap: could not determine transport protocol of service %##s", rr->resrec.name->c); return; }
185647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
185747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//LogMsg("StartRecordNatMap: clientContext %p IntPort %d srv.port %d %s",
185847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//	rr->NATinfo.clientContext, mDNSVal16(rr->NATinfo.IntPort), mDNSVal16(rr->resrec.rdata->u.srv.port), ARDisplayString(m, rr));
185947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->NATinfo.clientContext) mDNS_StopNATOperation_internal(m, &rr->NATinfo);
186047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->NATinfo.Protocol       = protocol;
186147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
186247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Shouldn't be trying to set IntPort here --
186347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// BuildUpdateMessage overwrites srs->RR_SRV.resrec.rdata->u.srv.port with external (mapped) port number
186447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->NATinfo.IntPort        = rr->resrec.rdata->u.srv.port;
186547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->NATinfo.RequestedPort  = rr->resrec.rdata->u.srv.port;
186647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->NATinfo.NATLease       = 0;		// Request default lease
186747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->NATinfo.clientCallback = CompleteRecordNatMap;
186847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->NATinfo.clientContext  = rr;
186947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_StartNATOperation_internal(m, &rr->NATinfo);
187047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
187147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
187247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Unlink an Auth Record from the m->ResourceRecords list.
187347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// When a resource record enters regState_NoTarget initially, mDNS_Register_internal
187447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// does not initialize completely e.g., it cannot check for duplicates etc. The resource
187547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// record is temporarily left in the ResourceRecords list so that we can initialize later
187647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// when the target is resolvable. Similarly, when host name changes, we enter regState_NoTarget
187747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// and we do the same.
187847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
187947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// This UnlinkResourceRecord routine is very worrying. It bypasses all the normal cleanup performed
188047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// by mDNS_Deregister_internal and just unceremoniously cuts the record from the active list.
188147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// This is why re-regsitering this record was producing syslog messages like this:
188247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// "Error! Tried to add a NAT traversal that's already in the active list"
188347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Right now UnlinkResourceRecord is fortunately only called by RegisterAllServiceRecords,
188447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// which then immediately calls mDNS_Register_internal to re-register the record, which probably
188547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// masked more serious problems. Any other use of UnlinkResourceRecord is likely to lead to crashes.
188647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// For now we'll workaround that specific problem by explicitly calling mDNS_StopNATOperation_internal,
188747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// but long-term we should either stop cancelling the record registration and then re-registering it,
188847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// or if we really do need to do this for some reason it should be done via the usual
188947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// mDNS_Deregister_internal path instead of just cutting the record from the list.
189047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
189147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mStatus UnlinkResourceRecord(mDNS *const m, AuthRecord *const rr)
189247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
189347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord **list = &m->ResourceRecords;
189447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*list && *list != rr) list = &(*list)->next;
189547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (*list)
189647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
189747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		*list = rr->next;
189847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->next = mDNSNULL;
189947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
190047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Temporary workaround to cancel any active NAT mapping operation
190147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->NATinfo.clientContext)
190247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
190347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
190447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->NATinfo.clientContext = mDNSNULL;
190547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->resrec.rrtype == kDNSType_SRV) rr->resrec.rdata->u.srv.port = rr->NATinfo.IntPort;
190647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
190747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
190847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return(mStatus_NoError);
190947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
191047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogMsg("UnlinkResourceRecord:ERROR!! - no such active record %##s", rr->resrec.name->c);
191147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(mStatus_NoSuchRecord);
191247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
191347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
191447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// We need to go through mDNS_Register again as we did not complete the
191547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// full initialization last time e.g., duplicate checks.
191647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// After we register, we will be in regState_GetZoneData.
191747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void RegisterAllServiceRecords(mDNS *const m, AuthRecord *rr)
191847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
191947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("RegisterAllServiceRecords: Service Record %##s", rr->resrec.name->c);
192047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// First Register the service record, we do this differently from other records because
192147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// when it entered NoTarget state, it did not go through complete initialization
192247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->SRVChanged = mDNSfalse;
192347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	UnlinkResourceRecord(m, rr);
192447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Register_internal(m, rr);
192547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Register the other records
192647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	UpdateAllServiceRecords(m, rr, mDNStrue);
192747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
192847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
192947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called with lock held
193047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void UpdateOneSRVRecord(mDNS *m, AuthRecord *rr)
193147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
193247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Target change if:
193347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We have a target and were previously waiting for one, or
193447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We had a target and no longer do, or
193547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// The target has changed
193647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
193747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	domainname *curtarget = &rr->resrec.rdata->u.srv.target;
193847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *const nt = GetServiceTarget(m, rr);
193947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *const newtarget = nt ? nt : (domainname*)"";
194047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool TargetChanged = (newtarget->c[0] && rr->state == regState_NoTarget) || !SameDomainName(curtarget, newtarget);
194147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool HaveZoneData  = rr->nta && !mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4);
194247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
194347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Nat state change if:
194447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We were behind a NAT, and now we are behind a new NAT, or
194547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We're not behind a NAT but our port was previously mapped to a different external port
194647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We were not behind a NAT and now we are
194747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
194847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSIPPort port        = rr->resrec.rdata->u.srv.port;
194947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool NowNeedNATMAP = (rr->AutoTarget == Target_AutoHostAndNATMAP && !mDNSIPPortIsZero(port) && mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && rr->nta && !mDNSAddrIsRFC1918(&rr->nta->Addr));
195047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool WereBehindNAT = (rr->NATinfo.clientContext != mDNSNULL);
195147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool PortWasMapped = (rr->NATinfo.clientContext && !mDNSSameIPPort(rr->NATinfo.RequestedPort, port));		// I think this is always false -- SC Sept 07
195247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool NATChanged    = (!WereBehindNAT && NowNeedNATMAP) || (!NowNeedNATMAP && PortWasMapped);
195347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
195447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void)HaveZoneData; //unused
195547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
195647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("UpdateOneSRVRecord: Resource Record %s TargetChanged %d, NewTarget %##s", ARDisplayString(m, rr), TargetChanged, nt->c);
195747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
195847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("UpdateOneSRVRecord: %##s newtarget %##s TargetChanged %d HaveZoneData %d port %d NowNeedNATMAP %d WereBehindNAT %d PortWasMapped %d NATChanged %d",
195947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->resrec.name->c, newtarget,
196047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		TargetChanged, HaveZoneData, mDNSVal16(port), NowNeedNATMAP, WereBehindNAT, PortWasMapped, NATChanged);
196147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
196247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy+1)
196347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("UpdateOneSRVRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
196447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
196547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!TargetChanged && !NATChanged) return;
196647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
196747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If we are deregistering the record, then ignore any NAT/Target change.
196847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
196947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
197047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("UpdateOneSRVRecord: Deregistering record, Ignoring TargetChanged %d, NATChanged %d for %##s, state %d", TargetChanged, NATChanged,
197147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->resrec.name->c, rr->state);
197247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
197347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
197447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
197547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (newtarget)
197647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, newtarget %##s", TargetChanged, NATChanged, rr->resrec.name->c, rr->state, newtarget->c);
197747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
197847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, null newtarget", TargetChanged, NATChanged, rr->resrec.name->c, rr->state);
197947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	switch(rr->state)
198047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
198147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NATMap:
198247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
198347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// or is in the process of, or has already been, deregistered. This assumes that whenever we transition out
198447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// of this state, we need to look at the target again.
198547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
198647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
198747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_UpdatePending:
198847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We are getting a Target change/NAT change while the SRV record is being updated ?
198947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// let us not do anything for now.
199047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
199147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
199247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NATError:
199347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!NATChanged) return;
199447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// if nat changed, register if we have a target (below)
199547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
199647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NoTarget:
199747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!newtarget->c[0])
199847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
199947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("UpdateOneSRVRecord: No target yet for Resource Record %s", ARDisplayString(m, rr));
200047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				return;
200147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
200247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			RegisterAllServiceRecords(m , rr);
200347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
200447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_DeregPending:
200547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We are in DeregPending either because the service was deregistered from above or we handled
200647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// a NAT/Target change before and sent the deregistration below. There are a few race conditions
200747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// possible
200847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
200947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// 1. We are handling a second NAT/Target change while the first dereg is in progress. It is possible
201047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    that first dereg never made it through because there was no network connectivity e.g., disconnecting
201147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    from network triggers this function due to a target change and later connecting to the network
201247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    retriggers this function but the deregistration never made it through yet. Just fall through.
201347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    If there is a target register otherwise deregister.
201447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
201547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// 2. While we sent the dereg during a previous NAT/Target change, uDNS_DeregisterRecord gets
201647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    called as part of service deregistration. When the response comes back, we call
201747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    CompleteDeregistration rather than handle NAT/Target change because the record is in
201847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    kDNSRecordTypeDeregistering state.
201947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
202047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// 3. If the upper layer deregisters the service, we check for kDNSRecordTypeDeregistering both
202147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    here in this function to avoid handling NAT/Target change and in hndlRecordUpdateReply to call
202247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    CompleteDeregistration instead of handling NAT/Target change. Hence, we are not concerned
202347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//    about that case here.
202447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//
202547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We just handle case (1) by falling through
202647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Pending:
202747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Refresh:
202847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Registered:
202947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// target or nat changed.  deregister service.  upon completion, we'll look for a new target
203047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->SRVChanged = mDNStrue;
203147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
203247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
203347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (newtarget->c[0])
203447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
203547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s, registering with new target %##s",
203647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					rr->resrec.name->c, newtarget->c);
203747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->state = regState_Pending;
203847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
203947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
204047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
204147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s de-registering", rr->resrec.name->c);
204247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->state = regState_DeregPending;
204347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				UpdateAllServiceRecords(m, rr, mDNSfalse);
204447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
204547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
204647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Unregistered:
204747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		default: LogMsg("UpdateOneSRVRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
204847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
204947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
205047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
205147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void UpdateAllSRVRecords(mDNS *m)
205247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
205347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->NextSRVUpdate = 0;
205447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("UpdateAllSRVRecords %d", m->SleepState);
205547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
205647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->CurrentRecord)
205747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("UpdateAllSRVRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
205847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->CurrentRecord = m->ResourceRecords;
205947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (m->CurrentRecord)
206047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
206147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AuthRecord *rptr = m->CurrentRecord;
206247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->CurrentRecord = m->CurrentRecord->next;
206347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (AuthRecord_uDNS(rptr) && rptr->resrec.rrtype == kDNSType_SRV)
206447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			UpdateOneSRVRecord(m, rptr);
206547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
206647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
206747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
206847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Forward reference: AdvertiseHostname references HostnameCallback, and HostnameCallback calls AdvertiseHostname
206947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
207047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
207147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called in normal client context (lock not held)
207247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void hostnameGetPublicAddressCallback(mDNS *m, NATTraversalInfo *n)
207347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
207447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	HostnameInfo *h = (HostnameInfo *)n->clientContext;
207547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
207647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!h) { LogMsg("RegisterHostnameRecord: registration cancelled"); return; }
207747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
207847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!n->Result)
207947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
208047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (mDNSIPv4AddressIsZero(n->ExternalAddress) || mDNSv4AddrIsRFC1918(&n->ExternalAddress)) return;
208147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
208247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (h->arv4.resrec.RecordType)
208347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
208447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (mDNSSameIPv4Address(h->arv4.resrec.rdata->u.ipv4, n->ExternalAddress)) return;	// If address unchanged, do nothing
208547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("Updating hostname %p %##s IPv4 from %.4a to %.4a (NAT gateway's external address)",n,
208647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				h->arv4.resrec.name->c, &h->arv4.resrec.rdata->u.ipv4, &n->ExternalAddress);
208747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_Deregister(m, &h->arv4);	// mStatus_MemFree callback will re-register with new address
208847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
208947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
209047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
209147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("Advertising hostname %##s IPv4 %.4a (NAT gateway's external address)", h->arv4.resrec.name->c, &n->ExternalAddress);
209247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
209347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->arv4.resrec.rdata->u.ipv4 = n->ExternalAddress;
209447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_Register(m, &h->arv4);
209547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
209647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
209747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
209847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
209947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// register record or begin NAT traversal
210047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void AdvertiseHostname(mDNS *m, HostnameInfo *h)
210147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
210247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4) && h->arv4.resrec.RecordType == kDNSRecordTypeUnregistered)
210347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
210447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_SetupResourceRecord(&h->arv4, mDNSNULL, mDNSInterface_Any, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnregistered, AuthRecordAny, HostnameCallback, h);
210547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&h->arv4.namestorage, &h->fqdn);
210647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		h->arv4.resrec.rdata->u.ipv4 = m->AdvertisedV4.ip.v4;
210747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		h->arv4.state = regState_Unregistered;
210847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4))
210947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
211047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we already have a NAT query active, stop it and restart it to make sure we get another callback
211147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (h->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &h->natinfo);
211247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->natinfo.Protocol         = 0;
211347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->natinfo.IntPort          = zeroIPPort;
211447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->natinfo.RequestedPort    = zeroIPPort;
211547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->natinfo.NATLease         = 0;
211647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->natinfo.clientCallback   = hostnameGetPublicAddressCallback;
211747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->natinfo.clientContext    = h;
211847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_StartNATOperation_internal(m, &h->natinfo);
211947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
212047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
212147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
212247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("Advertising hostname %##s IPv4 %.4a", h->arv4.resrec.name->c, &m->AdvertisedV4.ip.v4);
212347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
212447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_Register_internal(m, &h->arv4);
212547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
212647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
212747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
212847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!mDNSIPv6AddressIsZero(m->AdvertisedV6.ip.v6) && h->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
212947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
213047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_SetupResourceRecord(&h->arv6, mDNSNULL, mDNSInterface_Any, kDNSType_AAAA, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, HostnameCallback, h);
213147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&h->arv6.namestorage, &h->fqdn);
213247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		h->arv6.resrec.rdata->u.ipv6 = m->AdvertisedV6.ip.v6;
213347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		h->arv6.state = regState_Unregistered;
213447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("Advertising hostname %##s IPv6 %.16a", h->arv6.resrec.name->c, &m->AdvertisedV6.ip.v6);
213547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Register_internal(m, &h->arv6);
213647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
213747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
213847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
213947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
214047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
214147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	HostnameInfo *hi = (HostnameInfo *)rr->RecordContext;
214247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
214347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (result == mStatus_MemFree)
214447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
214547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (hi)
214647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
214747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we're still in the Hostnames list, update to new address
214847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			HostnameInfo *i;
214947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("HostnameCallback: Got mStatus_MemFree for %p %p %s", hi, rr, ARDisplayString(m, rr));
215047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			for (i = m->Hostnames; i; i = i->next)
215147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (rr == &i->arv4 || rr == &i->arv6)
215247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{ mDNS_Lock(m); AdvertiseHostname(m, i); mDNS_Unlock(m); return; }
215347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
215447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Else, we're not still in the Hostnames list, so free the memory
215547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (hi->arv4.resrec.RecordType == kDNSRecordTypeUnregistered &&
215647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				hi->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
215747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
215847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (hi->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &hi->natinfo);
215947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				hi->natinfo.clientContext = mDNSNULL;
216047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNSPlatformMemFree(hi);	// free hi when both v4 and v6 AuthRecs deallocated
216147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
216247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
216347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
216447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
216547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
216647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (result)
216747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
216847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// don't unlink or free - we can retry when we get a new address/router
216947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->resrec.rrtype == kDNSType_A)
217047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("HostnameCallback: Error %d for registration of %##s IP %.4a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
217147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
217247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("HostnameCallback: Error %d for registration of %##s IP %.16a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
217347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!hi) { mDNSPlatformMemFree(rr); return; }
217447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->state != regState_Unregistered) LogMsg("Error: HostnameCallback invoked with error code for record not in regState_Unregistered!");
217547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
217647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (hi->arv4.state == regState_Unregistered &&
217747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			hi->arv6.state == regState_Unregistered)
217847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
217947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// only deliver status if both v4 and v6 fail
218047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->RecordContext = (void *)hi->StatusContext;
218147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (hi->StatusCallback)
218247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				hi->StatusCallback(m, rr, result); // client may NOT make API calls here
218347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->RecordContext = (void *)hi;
218447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
218547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
218647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
218747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
218847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// register any pending services that require a target
218947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
219047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->NextSRVUpdate = NonZeroTime(m->timenow);
219147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
219247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
219347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Deliver success to client
219447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!hi) { LogMsg("HostnameCallback invoked with orphaned address record"); return; }
219547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.rrtype == kDNSType_A)
219647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("Registered hostname %##s IP %.4a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
219747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
219847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("Registered hostname %##s IP %.16a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
219947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
220047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->RecordContext = (void *)hi->StatusContext;
220147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (hi->StatusCallback)
220247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		hi->StatusCallback(m, rr, result); // client may NOT make API calls here
220347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->RecordContext = (void *)hi;
220447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
220547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
220647e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void FoundStaticHostname(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
220747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
220847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *pktname = &answer->rdata->u.name;
220947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	domainname *storedname = &m->StaticHostname;
221047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	HostnameInfo *h = m->Hostnames;
221147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
221247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void)question;
221347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
221447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (answer->rdlength != 0)
221547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("FoundStaticHostname: question %##s -> answer %##s (%s)", question->qname.c, answer->rdata->u.name.c, AddRecord ? "ADD" : "RMV");
221647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
221747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("FoundStaticHostname: question %##s -> answer NULL (%s)", question->qname.c, AddRecord ? "ADD" : "RMV");
221847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
221947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AddRecord && answer->rdlength != 0 && !SameDomainName(pktname, storedname))
222047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
222147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(storedname, pktname);
222247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		while (h)
222347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
222447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (h->arv4.state == regState_Pending || h->arv4.state == regState_NATMap || h->arv6.state == regState_Pending)
222547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
222647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// 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
222747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				m->NextSRVUpdate = NonZeroTime(m->timenow + 5 * mDNSPlatformOneSecond);
222847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				debugf("FoundStaticHostname: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
222947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				return;
223047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
223147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			h = h->next;
223247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
223347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Lock(m);
223447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->NextSRVUpdate = NonZeroTime(m->timenow);
223547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Unlock(m);
223647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
223747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (!AddRecord && SameDomainName(pktname, storedname))
223847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
223947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Lock(m);
224047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		storedname->c[0] = 0;
224147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->NextSRVUpdate = NonZeroTime(m->timenow);
224247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Unlock(m);
224347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
224447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
224547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
224647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called with lock held
224747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void GetStaticHostname(mDNS *m)
224847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
224947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	char buf[MAX_REVERSE_MAPPING_NAME_V4];
225047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *q = &m->ReverseMap;
225147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *ip = m->AdvertisedV4.ip.v4.b;
225247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err;
225347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
225447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->ReverseMap.ThisQInterval != -1) return; // already running
225547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4)) return;
225647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
225747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformMemZero(q, sizeof(*q));
225847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
225947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa.", ip[3], ip[2], ip[1], ip[0]);
226047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!MakeDomainNameFromDNSNameString(&q->qname, buf)) { LogMsg("Error: GetStaticHostname - bad name %s", buf); return; }
226147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
226247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->InterfaceID      = mDNSInterface_Any;
226347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->Target           = zeroAddr;
226447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->qtype            = kDNSType_PTR;
226547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->qclass           = kDNSClass_IN;
226647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->LongLived        = mDNSfalse;
226747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ExpectUnique     = mDNSfalse;
226847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ForceMCast       = mDNSfalse;
226947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ReturnIntermed   = mDNStrue;
227047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->SuppressUnusable = mDNSfalse;
227147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->SearchListIndex  = 0;
227247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->AppendSearchDomains = 0;
227347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->RetryWithSearchDomains = mDNSfalse;
227447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->TimeoutQuestion  = 0;
227547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->WakeOnResolve    = 0;
227647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->qnameOrig        = mDNSNULL;
227747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->QuestionCallback = FoundStaticHostname;
227847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->QuestionContext  = mDNSNULL;
227947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
228047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("GetStaticHostname: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
228147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	err = mDNS_StartQuery_internal(m, q);
228247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err) LogMsg("Error: GetStaticHostname - StartQuery returned error %d", err);
228347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
228447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
228547e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext)
228647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt   {
228747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	HostnameInfo **ptr = &m->Hostnames;
228847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
228947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("mDNS_AddDynDNSHostName %##s", fqdn);
229047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
229147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
229247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (*ptr) { LogMsg("DynDNSHostName %##s already in list", fqdn->c); return; }
229347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
229447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// allocate and format new address record
229547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	*ptr = mDNSPlatformMemAllocate(sizeof(**ptr));
229647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!*ptr) { LogMsg("ERROR: mDNS_AddDynDNSHostName - malloc"); return; }
229747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
229847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformMemZero(*ptr, sizeof(**ptr));
229947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AssignDomainName(&(*ptr)->fqdn, fqdn);
230047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(*ptr)->arv4.state     = regState_Unregistered;
230147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(*ptr)->arv6.state     = regState_Unregistered;
230247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(*ptr)->StatusCallback = StatusCallback;
230347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(*ptr)->StatusContext  = StatusContext;
230447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
230547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AdvertiseHostname(m, *ptr);
230647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
230747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
230847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void mDNS_RemoveDynDNSHostName(mDNS *m, const domainname *fqdn)
230947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
231047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	HostnameInfo **ptr = &m->Hostnames;
231147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
231247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("mDNS_RemoveDynDNSHostName %##s", fqdn);
231347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
231447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
231547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!*ptr) LogMsg("mDNS_RemoveDynDNSHostName: no such domainname %##s", fqdn->c);
231647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
231747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
231847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		HostnameInfo *hi = *ptr;
231947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We do it this way because, if we have no active v6 record, the "mDNS_Deregister_internal(m, &hi->arv4);"
232047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// below could free the memory, and we have to make sure we don't touch hi fields after that.
232147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSBool f4 = hi->arv4.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv4.state != regState_Unregistered;
232247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSBool f6 = hi->arv6.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv6.state != regState_Unregistered;
232347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (f4) LogInfo("mDNS_RemoveDynDNSHostName removing v4 %##s", fqdn);
232447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (f6) LogInfo("mDNS_RemoveDynDNSHostName removing v6 %##s", fqdn);
232547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		*ptr = (*ptr)->next; // unlink
232647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (f4) mDNS_Deregister_internal(m, &hi->arv4, mDNS_Dereg_normal);
232747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (f6) mDNS_Deregister_internal(m, &hi->arv6, mDNS_Dereg_normal);
232847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// When both deregistrations complete we'll free the memory in the mStatus_MemFree callback
232947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
233047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!m->mDNS_busy) LogMsg("mDNS_RemoveDynDNSHostName: ERROR: Lock not held");
233147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->NextSRVUpdate = NonZeroTime(m->timenow);
233247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
233347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
233447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Currently called without holding the lock
233547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Maybe we should change that?
233647e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *v4addr, const mDNSAddr *v6addr, const mDNSAddr *router)
233747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
233847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool v4Changed, v6Changed, RouterChanged;
233947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
234047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy)
234147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("mDNS_SetPrimaryInterfaceInfo: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
234247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
234347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (v4addr && v4addr->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo v4 address - incorrect type.  Discarding. %#a", v4addr); return; }
234447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (v6addr && v6addr->type != mDNSAddrType_IPv6) { LogMsg("mDNS_SetPrimaryInterfaceInfo v6 address - incorrect type.  Discarding. %#a", v6addr); return; }
234547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (router && router->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-v4 router.  Discarding. %#a",        router); return; }
234647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
234747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
234847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
234947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	v4Changed     = !mDNSSameIPv4Address(m->AdvertisedV4.ip.v4, v4addr ? v4addr->ip.v4 : zerov4Addr);
235047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	v6Changed     = !mDNSSameIPv6Address(m->AdvertisedV6.ip.v6, v6addr ? v6addr->ip.v6 : zerov6Addr);
235147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	RouterChanged = !mDNSSameIPv4Address(m->Router.ip.v4,       router ? router->ip.v4 : zerov4Addr);
235247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
235347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (v4addr && (v4Changed || RouterChanged))
235447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("mDNS_SetPrimaryInterfaceInfo: address changed from %#a to %#a", &m->AdvertisedV4, v4addr);
235547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
235647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (v4addr) m->AdvertisedV4 = *v4addr; else m->AdvertisedV4.ip.v4 = zerov4Addr;
235747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (v6addr) m->AdvertisedV6 = *v6addr; else m->AdvertisedV6.ip.v6 = zerov6Addr;
235847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (router) m->Router       = *router; else m->Router      .ip.v4 = zerov4Addr;
235947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// setting router to zero indicates that nat mappings must be reestablished when router is reset
236047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
236147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (v4Changed || RouterChanged || v6Changed)
236247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
236347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		HostnameInfo *i;
236447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("mDNS_SetPrimaryInterfaceInfo: %s%s%s%#a %#a %#a",
236547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			v4Changed     ? "v4Changed "     : "",
236647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			RouterChanged ? "RouterChanged " : "",
236747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			v6Changed     ? "v6Changed "     : "", v4addr, v6addr, router);
236847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
236947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (i = m->Hostnames; i; i = i->next)
237047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
237147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("mDNS_SetPrimaryInterfaceInfo updating host name registrations for %##s", i->fqdn.c);
237247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
237347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (i->arv4.resrec.RecordType > kDNSRecordTypeDeregistering &&
237447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				!mDNSSameIPv4Address(i->arv4.resrec.rdata->u.ipv4, m->AdvertisedV4.ip.v4))
237547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
237647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv4));
237747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_Deregister_internal(m, &i->arv4, mDNS_Dereg_normal);
237847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
237947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
238047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (i->arv6.resrec.RecordType > kDNSRecordTypeDeregistering &&
238147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				!mDNSSameIPv6Address(i->arv6.resrec.rdata->u.ipv6, m->AdvertisedV6.ip.v6))
238247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
238347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv6));
238447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_Deregister_internal(m, &i->arv6, mDNS_Dereg_normal);
238547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
238647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
238747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// AdvertiseHostname will only register new address records.
238847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// For records still in the process of deregistering it will ignore them, and let the mStatus_MemFree callback handle them.
238947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			AdvertiseHostname(m, i);
239047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
239147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
239247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (v4Changed || RouterChanged)
239347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
239447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we have a non-zero IPv4 address, we should try immediately to see if we have a NAT gateway
239547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we have no IPv4 address, we don't want to be in quite such a hurry to report failures to our clients
239647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// <rdar://problem/6935929> Sleeping server sometimes briefly disappears over Back to My Mac after it wakes up
239747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->ExternalAddress      = zerov4Addr;
239847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
239947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->retryGetAddr         = m->timenow + (v4addr ? 0 : mDNSPlatformOneSecond * 5);
240047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->NextScheduledNATOp   = m->timenow;
240147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->LastNATMapResultCode = NATErr_None;
240247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#ifdef _LEGACY_NAT_TRAVERSAL_
240347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LNT_ClearState(m);
240447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif // _LEGACY_NAT_TRAVERSAL_
240547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("mDNS_SetPrimaryInterfaceInfo:%s%s: retryGetAddr in %d %d",
240647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				v4Changed     ? " v4Changed"     : "",
240747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				RouterChanged ? " RouterChanged" : "",
240847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				m->retryGetAddr - m->timenow, m->timenow);
240947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
241047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
241147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->ReverseMap.ThisQInterval != -1) mDNS_StopQuery_internal(m, &m->ReverseMap);
241247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->StaticHostname.c[0] = 0;
241347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
241447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->NextSRVUpdate = NonZeroTime(m->timenow);
241547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
241647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
241747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (RouterChanged)	uuid_generate(m->asl_uuid);
241847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		UpdateAutoTunnelDomainStatuses(m);
241947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
242047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
242147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
242247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
242347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
242447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
242547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
242647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
242747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - Incoming Message Processing
242847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
242947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
243047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mStatus ParseTSIGError(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end, const domainname *const displayname)
243147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
243247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const mDNSu8 *ptr;
243347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err = mStatus_NoError;
243447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int i;
243547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
243647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = LocateAdditionals(msg, end);
243747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr) goto finish;
243847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
243947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (i = 0; i < msg->h.numAdditionals; i++)
244047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
244147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
244247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!ptr) goto finish;
244347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_TSIG)
244447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
244547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu32 macsize;
244647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu8 *rd = m->rec.r.resrec.rdata->u.data;
244747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu8 *rdend = rd + m->rec.r.resrec.rdlength;
244847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			int alglen = DomainNameLengthLimit(&m->rec.r.resrec.rdata->u.name, rdend);
244947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (alglen > MAX_DOMAIN_NAME) goto finish;
245047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rd += alglen;                                       // algorithm name
245147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rd + 6 > rdend) goto finish;
245247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rd += 6;                                            // 48-bit timestamp
245347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
245447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rd += sizeof(mDNSOpaque16);                         // fudge
245547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
245647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			macsize = mDNSVal16(*(mDNSOpaque16 *)rd);
245747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rd += sizeof(mDNSOpaque16);                         // MAC size
245847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rd + macsize > rdend) goto finish;
245947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rd += macsize;
246047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
246147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rd += sizeof(mDNSOpaque16);                         // orig id
246247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
246347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			err = mDNSVal16(*(mDNSOpaque16 *)rd);               // error code
246447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
246547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if      (err == TSIG_ErrBadSig)  { LogMsg("%##s: bad signature", displayname->c);              err = mStatus_BadSig;     }
246647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else if (err == TSIG_ErrBadKey)  { LogMsg("%##s: bad key", displayname->c);                    err = mStatus_BadKey;     }
246747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else if (err == TSIG_ErrBadTime) { LogMsg("%##s: bad time", displayname->c);                   err = mStatus_BadTime;    }
246847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else if (err)                    { LogMsg("%##s: unknown tsig error %d", displayname->c, err); err = mStatus_UnknownErr; }
246947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			goto finish;
247047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
247147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
247247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
247347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
247447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	finish:
247547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
247647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return err;
247747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
247847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
247947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mStatus checkUpdateResult(mDNS *const m, const domainname *const displayname, const mDNSu8 rcode, const DNSMessage *const msg, const mDNSu8 *const end)
248047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
248147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void)msg;	// currently unused, needed for TSIG errors
248247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rcode) return mStatus_NoError;
248347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (rcode == kDNSFlag1_RC_YXDomain)
248447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
248547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("name in use: %##s", displayname->c);
248647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return mStatus_NameConflict;
248747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
248847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (rcode == kDNSFlag1_RC_Refused)
248947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
249047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("Update %##s refused", displayname->c);
249147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return mStatus_Refused;
249247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
249347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (rcode == kDNSFlag1_RC_NXRRSet)
249447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
249547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("Reregister refused (NXRRSET): %##s", displayname->c);
249647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return mStatus_NoSuchRecord;
249747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
249847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (rcode == kDNSFlag1_RC_NotAuth)
249947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
250047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// TSIG errors should come with FormErr as per RFC 2845, but BIND 9 sends them with NotAuth so we look here too
250147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
250247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!tsigerr)
250347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
250447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("Permission denied (NOAUTH): %##s", displayname->c);
250547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return mStatus_UnknownErr;
250647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
250747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else return tsigerr;
250847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
250947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (rcode == kDNSFlag1_RC_FormErr)
251047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
251147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
251247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!tsigerr)
251347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
251447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("Format Error: %##s", displayname->c);
251547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return mStatus_UnknownErr;
251647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
251747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else return tsigerr;
251847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
251947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
252047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
252147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("Update %##s failed with rcode %d", displayname->c, rcode);
252247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return mStatus_UnknownErr;
252347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
252447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
252547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
252647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// We add three Additional Records for unicast resource record registrations
252747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// which is a function of AuthInfo and AutoTunnel properties
252847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSu32 RRAdditionalSize(mDNS *const m, DomainAuthInfo *AuthInfo)
252947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
253047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu32 leaseSize, hinfoSize, tsigSize;
253147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu32 rr_base_size = 10; // type (2) class (2) TTL (4) rdlength (2)
253247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
253347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// OPT RR : Emptyname(.) + base size + rdataOPT
253447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	leaseSize = 1 + rr_base_size + sizeof(rdataOPT);
253547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
253647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// HINFO: Resource Record Name + base size + RDATA
253747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// HINFO is added only for autotunnels
253847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	hinfoSize = 0;
253947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AuthInfo && AuthInfo->AutoTunnel)
254047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		hinfoSize = (m->hostlabel.c[0] + 1) + DomainNameLength(&AuthInfo->domain) +
254147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr_base_size + (2 + m->HIHardware.c[0] + m->HISoftware.c[0]);
254247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
254347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//TSIG: Resource Record Name + base size + RDATA
254447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// RDATA:
254547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt    // 	Algorithm name: hmac-md5.sig-alg.reg.int (8+7+3+3 + 5 bytes for length = 26 bytes)
254647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt    // 	Time: 6 bytes
254747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 	Fudge: 2 bytes
254847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt    // 	Mac Size: 2 bytes
254947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 	Mac: 16 bytes
255047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 	ID: 2 bytes
255147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt    // 	Error: 2 bytes
255247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt    // 	Len: 2 bytes
255347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 	Total: 58 bytes
255447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	tsigSize = 0;
255547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AuthInfo) tsigSize = DomainNameLength(&AuthInfo->keyname) + rr_base_size + 58;
255647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
255747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return (leaseSize + hinfoSize + tsigSize);
255847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
255947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
256047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//Note: Make sure that RREstimatedSize is updated accordingly if anything that is done here
256147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//would modify rdlength/rdestimate
256247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSu8* BuildUpdateMessage(mDNS *const m, mDNSu8 *ptr, AuthRecord *rr, mDNSu8 *limit)
256347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
256447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//If this record is deregistering, then just send the deletion record
256547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_DeregPending)
256647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
256747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->expire = 0;		// Indicate that we have no active registration any more
256847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit);
256947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!ptr) goto exit;
257047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return ptr;
257147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
257247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
257347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// This is a common function to both sending an update in a group or individual
257447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// records separately. Hence, we change the state here.
257547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_Registered) rr->state = regState_Refresh;
257647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state != regState_Refresh && rr->state != regState_UpdatePending)
257747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->state = regState_Pending;
257847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
257947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// For Advisory records like e.g., _services._dns-sd, which is shared, don't send goodbyes as multiple
258047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// host might be registering records and deregistering from one does not make sense
258147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.RecordType != kDNSRecordTypeAdvisory) rr->RequireGoodbye = mDNStrue;
258247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
258347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if ((rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHostAndNATMAP) &&
258447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		!mDNSIPPortIsZero(rr->NATinfo.ExternalPort))
258547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
258647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->resrec.rdata->u.srv.port = rr->NATinfo.ExternalPort;
258747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
258847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
258947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_UpdatePending)
259047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
259147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// delete old RData
259247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNewRData(&rr->resrec, rr->OrigRData, rr->OrigRDLen);
259347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!(ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit))) goto exit; // delete old rdata
259447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
259547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// add new RData
259647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
259747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!(ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit)))  goto exit;
259847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
259947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
260047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
260147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
260247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
260347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// KnownUnique : Delete any previous value
260447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// For Unicast registrations, we don't verify that it is unique, but set to verified and hence we want to
260547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// delete any previous value
260647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			ptr = putDeleteRRSetWithLimit(&m->omsg, ptr, rr->resrec.name, rr->resrec.rrtype, limit);
260747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!ptr) goto exit;
260847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
260947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (rr->resrec.RecordType != kDNSRecordTypeShared)
261047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
261147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// For now don't do this, until we have the logic for intelligent grouping of individual records into logical service record sets
261247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			//ptr = putPrereqNameNotInUse(rr->resrec.name, &m->omsg, ptr, end);
261347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!ptr) goto exit;
261447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
261547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
261647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
261747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!ptr) goto exit;
261847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
261947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
262047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return ptr;
262147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwaltexit:
262247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogMsg("BuildUpdateMessage: Error formatting message for %s", ARDisplayString(m, rr));
262347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mDNSNULL;
262447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
262547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
262647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called with lock held
262747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr)
262847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
262947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *ptr = m->omsg.data;
263047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err = mStatus_UnknownErr;
263147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *limit;
263247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *AuthInfo;
263347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
263447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// For the ability to register large TXT records, we limit the single record registrations
263547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// to AbsoluteMaxDNSMessageData
263647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	limit = ptr + AbsoluteMaxDNSMessageData;
263747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
263847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
263947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	limit -= RRAdditionalSize(m, AuthInfo);
264047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
264147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy+1)
264247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("SendRecordRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
264347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
264447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
264547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
264647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We never call this function when there is no zone information . Log a message if it ever happens.
264747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("SendRecordRegistration: No Zone information, should not happen %s", ARDisplayString(m, rr));
264847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
264947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
265047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
265147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->updateid = mDNS_NewMessageID(m);
265247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	InitializeDNSMessage(&m->omsg.h, rr->updateid, UpdateReqFlags);
265347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
265447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// set zone
265547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = putZone(&m->omsg, ptr, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
265647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr) goto exit;
265747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
265847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!(ptr = BuildUpdateMessage(m, ptr, rr, limit))) goto exit;
265947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
266047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->uselease)
266147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
266247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
266347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!ptr) goto exit;
266447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
266547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->Private)
266647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
266747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("SendRecordRegistration TCP %p %s", rr->tcp, ARDisplayString(m, rr));
266847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->tcp) LogInfo("SendRecordRegistration: Disposing existing TCP connection for %s", ARDisplayString(m, rr));
266947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
267047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!rr->nta) { LogMsg("SendRecordRegistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
267147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &rr->nta->Addr, rr->nta->Port, &rr->nta->Host, mDNSNULL, rr);
267247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
267347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
267447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
267547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("SendRecordRegistration UDP %s", ARDisplayString(m, rr));
267647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!rr->nta) { LogMsg("SendRecordRegistration:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
267747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &rr->nta->Addr, rr->nta->Port, mDNSNULL, GetAuthInfoForName_internal(m, rr->resrec.name));
267847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) debugf("ERROR: SendRecordRegistration - mDNSSendDNSMessage - %d", err);
267947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
268047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
268147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SetRecordRetry(m, rr, 0);
268247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return;
268347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwaltexit:
268447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogMsg("SendRecordRegistration: Error formatting message for %s, disabling further updates", ARDisplayString(m, rr));
268547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Disable this record from future updates
268647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->state = regState_NoTarget;
268747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
268847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
268947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Is the given record "rr" eligible for merging ?
269047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time)
269147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
269247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *info;
269347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void) m; //unused
269447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// A record is eligible for merge, if the following properties are met.
269547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
269647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 1. uDNS Resource Record
269747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 2. It is time to send them now
269847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 3. It is in proper state
269947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 4. Update zone has been resolved
270047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 5. if DomainAuthInfo exists for the zone, it should not be soon deleted
270147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 6. Zone information is present
270247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 7. Update server is not zero
270347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 8. It has a non-null zone
270447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 9. It uses a lease option
270547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 10. DontMerge is not set
270647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
270747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Following code is implemented as separate "if" statements instead of one "if" statement
270847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// is for better debugging purposes e.g., we know exactly what failed if debugging turned on.
270947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
271047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!AuthRecord_uDNS(rr)) return mDNSfalse;
271147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
271247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->LastAPTime + rr->ThisAPInterval - time > 0)
271347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ debugf("IsRecordMergeable: Time %d not reached for %s", rr->LastAPTime + rr->ThisAPInterval - m->timenow, ARDisplayString(m, rr)); return mDNSfalse; }
271447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
271547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr->zone) return mDNSfalse;
271647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
271747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info = GetAuthInfoForName_internal(m, rr->zone);
271847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
271947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (info && info->deltime && m->timenow - info->deltime >= 0) {debugf("IsRecordMergeable: Domain %##s will be deleted soon", info->domain.c); return mDNSfalse;}
272047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
272147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state != regState_DeregPending && rr->state != regState_Pending && rr->state != regState_Registered && rr->state != regState_Refresh && rr->state != regState_UpdatePending)
272247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ debugf("IsRecordMergeable: state %d not right  %s", rr->state, ARDisplayString(m, rr)); return mDNSfalse; }
272347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
272447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4)) return mDNSfalse;
272547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
272647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr->uselease) return mDNSfalse;
272747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
272847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->mState == mergeState_DontMerge) {debugf("IsRecordMergeable Dontmerge true %s", ARDisplayString(m, rr));return mDNSfalse;}
272947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("IsRecordMergeable: Returning true for %s", ARDisplayString(m, rr));
273047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mDNStrue;
273147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
273247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
273347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Is the resource record "rr" eligible to merge to with "currentRR" ?
273447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSBool AreRecordsMergeable(mDNS *const m, AuthRecord *currentRR, AuthRecord *rr, mDNSs32 time)
273547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
273647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// A record is eligible to merge with another record as long it is eligible for merge in itself
273747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// and it has the same zone information as the other record
273847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!IsRecordMergeable(m, rr, time)) return mDNSfalse;
273947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
274047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!SameDomainName(currentRR->zone, rr->zone))
274147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ debugf("AreRecordMergeable zone mismatch current rr Zone %##s, rr zone  %##s", currentRR->zone->c, rr->zone->c); return mDNSfalse; }
274247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
274347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!mDNSSameIPv4Address(currentRR->nta->Addr.ip.v4, rr->nta->Addr.ip.v4)) return mDNSfalse;
274447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
274547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!mDNSSameIPPort(currentRR->nta->Port, rr->nta->Port)) return mDNSfalse;
274647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
274747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("AreRecordsMergeable: Returning true for %s", ARDisplayString(m, rr));
274847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mDNStrue;
274947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
275047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
275147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// If we can't build the message successfully because of problems in pre-computing
275247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// the space, we disable merging for all the current records
275347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void RRMergeFailure(mDNS *const m)
275447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
275547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *rr;
275647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (rr = m->ResourceRecords; rr; rr = rr->next)
275747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
275847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->mState = mergeState_DontMerge;
275947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->SendRNow = mDNSNULL;
276047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Restarting the registration is much simpler than saving and restoring
276147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// the exact time
276247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ActivateUnicastRegistration(m, rr);
276347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
276447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
276547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
276647e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void SendGroupRRMessage(mDNS *const m, AuthRecord *anchorRR, mDNSu8 *ptr, DomainAuthInfo *info)
276747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
276847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *limit;
276947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!anchorRR) {debugf("SendGroupRRMessage: Could not merge records"); return;}
277047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
277147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (info && info->AutoTunnel) limit = m->omsg.data + AbsoluteMaxDNSMessageData;
277247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else limit = m->omsg.data + NormalMaxDNSMessageData;
277347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
277447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// This has to go in the additional section and hence need to be done last
277547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
277647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr)
277747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
277847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("SendGroupRRMessage: ERROR: Could not put lease option, failing the group registration");
277947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// if we can't put the lease, we need to undo the merge
278047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		RRMergeFailure(m);
278147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
278247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
278347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (anchorRR->Private)
278447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
278547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (anchorRR->tcp) debugf("SendGroupRRMessage: Disposing existing TCP connection for %s", ARDisplayString(m, anchorRR));
278647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (anchorRR->tcp) { DisposeTCPConn(anchorRR->tcp); anchorRR->tcp = mDNSNULL; }
278747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!anchorRR->nta) { LogMsg("SendGroupRRMessage:ERROR!! nta is NULL for %s", ARDisplayString(m, anchorRR)); return; }
278847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		anchorRR->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &anchorRR->nta->Addr, anchorRR->nta->Port, &anchorRR->nta->Host, mDNSNULL, anchorRR);
278947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!anchorRR->tcp) LogInfo("SendGroupRRMessage: Cannot establish TCP connection for %s", ARDisplayString(m, anchorRR));
279047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		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);
279147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
279247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
279347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
279447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mStatus err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &anchorRR->nta->Addr, anchorRR->nta->Port, mDNSNULL, info);
279547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) LogInfo("SendGroupRRMessage: Cannot send UDP message for %s", ARDisplayString(m, anchorRR));
279647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		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);
279747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
279847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return;
279947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
280047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
280147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// As we always include the zone information and the resource records contain zone name
280247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// at the end, it will get compressed. Hence, we subtract zoneSize and add two bytes for
280347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// the compression pointer
280447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSu32 RREstimatedSize(AuthRecord *rr, int zoneSize)
280547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
280647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int rdlength;
280747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
280847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Note: Estimation of the record size has to mirror the logic in BuildUpdateMessage, otherwise estimation
280947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// would be wrong. Currently BuildUpdateMessage calls SetNewRData in UpdatePending case. Hence, we need
281047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// to account for that here. Otherwise, we might under estimate the size.
281147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_UpdatePending)
281247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// old RData that will be deleted
281347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// new RData that will be added
281447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rdlength = rr->OrigRDLen + rr->InFlightRDLen;
281547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
281647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rdlength = rr->resrec.rdestimate;
281747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
281847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_DeregPending)
281947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
282047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
282147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
282247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
282347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
282447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
282547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// For SRV, TXT, AAAA etc. that are Unique/Verified, we also send a Deletion Record
282647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
282747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
282847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Deletion Record: Resource Record Name + Base size (10) + 0
282947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Record: Resource Record Name (Compressed = 2) + Base size (10) + rdestimate
283047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
283147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
283247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
283347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + 2 + 10 + rdlength;
283447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
283547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
283647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
283747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
283847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
283947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
284047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
284147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal AuthRecord *MarkRRForSending(mDNS *const m)
284247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
284347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *rr;
284447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *firstRR = mDNSNULL;
284547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
284647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Look for records that needs to be sent in the next two seconds (MERGE_DELAY_TIME is set to 1 second).
284747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// The logic is as follows.
284847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
284947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 1. Record 1 finishes getting zone data and its registration gets delayed by 1 second
285047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 2. Record 2 comes 0.1 second later, finishes getting its zone data and its registration is also delayed by
285147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//    1 second which is now scheduled at 1.1 second
285247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
285347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// By looking for 1 second into the future (m->timenow + MERGE_DELAY_TIME below does that) we have merged both
285447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// of the above records. Note that we can't look for records too much into the future as this will affect the
285547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// retry logic. The first retry is scheduled at 3 seconds. Hence, we should always look smaller than that.
285647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Anything more than one second will affect the first retry to happen sooner.
285747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
285847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Note: As a side effect of looking one second into the future to facilitate merging, the retries happen
285947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// one second sooner.
286047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (rr = m->ResourceRecords; rr; rr = rr->next)
286147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
286247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!firstRR)
286347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
286447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME)) continue;
286547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			firstRR = rr;
286647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
286747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (!AreRecordsMergeable(m, firstRR, rr, m->timenow + MERGE_DELAY_TIME)) continue;
286847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
286947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->SendRNow) LogMsg("MarkRRForSending: Resourcerecord %s already marked for sending", ARDisplayString(m, rr));
287047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->SendRNow = mDNSInterfaceMark;
287147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
287247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
287347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We parsed through all records and found something to send. The services/records might
287447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// get registered at different times but we want the refreshes to be all merged and sent
287547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// as one update. Hence, we accelerate some of the records so that they will sync up in
287647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// the future. Look at the records excluding the ones that we have already sent in the
287747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// previous pass. If it half way through its scheduled refresh/retransmit, merge them
287847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// into this packet.
287947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
288047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Note that we only look at Registered/Refresh state to keep it simple. As we don't know
288147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// whether the current update will fit into one or more packets, merging a resource record
288247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// (which is in a different state) that has been scheduled for retransmit would trigger
288347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// sending more packets.
288447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (firstRR)
288547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
288647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		int acc = 0;
288747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (rr = m->ResourceRecords; rr; rr = rr->next)
288847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
288947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if ((rr->state != regState_Registered && rr->state != regState_Refresh) ||
289047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				(rr->SendRNow == mDNSInterfaceMark) ||
289147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				(!AreRecordsMergeable(m, firstRR, rr, m->timenow + rr->ThisAPInterval/2)))
289247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				continue;
289347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->SendRNow = mDNSInterfaceMark;
289447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			acc++;
289547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
289647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (acc) LogInfo("MarkRRForSending: Accelereated %d records", acc);
289747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
289847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return firstRR;
289947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
290047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
290147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSBool SendGroupUpdates(mDNS *const m)
290247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
290347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSOpaque16 msgid;
290447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSs32 spaceleft = 0;
290547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSs32 zoneSize, rrSize;
290647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *oldnext; // for debugging
290747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *next = m->omsg.data;
290847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *rr;
290947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *anchorRR = mDNSNULL;
291047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int nrecords = 0;
291147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *startRR = m->ResourceRecords;
291247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *limit = mDNSNULL;
291347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *AuthInfo = mDNSNULL;
291447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool sentallRecords = mDNStrue;
291547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
291647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
291747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We try to fit as many ResourceRecords as possible in AbsoluteNormal/MaxDNSMessageData. Before we start
291847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// putting in resource records, we need to reserve space for a few things. Every group/packet should
291947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// have the following.
292047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
292147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 1) Needs space for the Zone information (which needs to be at the beginning)
292247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 2) Additional section MUST have space for lease option, HINFO and TSIG option (which needs to
292347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//    to be at the end)
292447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
292547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// In future we need to reserve space for the pre-requisites which also goes at the beginning.
292647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// To accomodate pre-requisites in the future, first we walk the whole list marking records
292747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// that can be sent in this packet and computing the space needed for these records.
292847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// For TXT and SRV records, we delete the previous record if any by sending the same
292947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// resource record with ANY RDATA and zero rdlen. Hence, we need to have space for both of them.
293047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
293147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (startRR)
293247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
293347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AuthInfo = mDNSNULL;
293447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		anchorRR = mDNSNULL;
293547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		nrecords = 0;
293647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		zoneSize = 0;
293747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (rr = startRR; rr; rr = rr->next)
293847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
293947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->SendRNow != mDNSInterfaceMark) continue;
294047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
294147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->SendRNow = mDNSNULL;
294247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
294347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!anchorRR)
294447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
294547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				AuthInfo = GetAuthInfoForName_internal(m, rr->zone);
294647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
294747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// Though we allow single record registrations for UDP to be AbsoluteMaxDNSMessageData (See
294847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// SendRecordRegistration) to handle large TXT records, to avoid fragmentation we limit UDP
294947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// message to NormalMaxDNSMessageData
295047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (AuthInfo && AuthInfo->AutoTunnel) spaceleft = AbsoluteMaxDNSMessageData;
295147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else spaceleft = NormalMaxDNSMessageData;
295247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
295347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				next = m->omsg.data;
295447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				spaceleft -= RRAdditionalSize(m, AuthInfo);
295547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (spaceleft <= 0)
295647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
295747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("SendGroupUpdates: ERROR!!: spaceleft is zero at the beginning");
295847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					RRMergeFailure(m);
295947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					return mDNSfalse;
296047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
296147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				limit = next + spaceleft;
296247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
296347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// Build the initial part of message before putting in the other records
296447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt 				msgid = mDNS_NewMessageID(m);
296547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
296647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
296747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// We need zone information at the beginning of the packet. Length: ZNAME, ZTYPE(2), ZCLASS(2)
296847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// zone has to be non-NULL for a record to be mergeable, hence it is safe to set/ examine zone
296947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				//without checking for NULL.
297047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				zoneSize = DomainNameLength(rr->zone) + 4;
297147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				spaceleft -= zoneSize;
297247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (spaceleft <= 0)
297347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
297447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("SendGroupUpdates: ERROR no space for zone information, disabling merge");
297547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					RRMergeFailure(m);
297647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					return mDNSfalse;
297747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
297847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				next = putZone(&m->omsg, next, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
297947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!next)
298047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
298147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("SendGroupUpdates: ERROR! Cannot put zone, disabling merge");
298247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					RRMergeFailure(m);
298347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					return mDNSfalse;
298447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
298547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				anchorRR = rr;
298647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
298747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
298847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rrSize = RREstimatedSize(rr, zoneSize - 4);
298947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
299047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if ((spaceleft - rrSize) < 0)
299147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
299247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// If we can't fit even a single message, skip it, it will be sent separately
299347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// in CheckRecordUpdates
299447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!nrecords)
299547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
299647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogInfo("SendGroupUpdates: Skipping message %s, spaceleft %d, rrSize %d", ARDisplayString(m, rr), spaceleft, rrSize);
299747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Mark this as not sent so that the caller knows about it
299847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					rr->SendRNow = mDNSInterfaceMark;
299947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// We need to remove the merge delay so that we can send it immediately
300047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
300147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
300247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					rr = rr->next;
300347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					anchorRR = mDNSNULL;
300447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					sentallRecords = mDNSfalse;
300547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
300647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else
300747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
300847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogInfo("SendGroupUpdates:1: Parsed %d records and sending using %s, spaceleft %d, rrSize %d", nrecords, ARDisplayString(m, anchorRR), spaceleft, rrSize);
300947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					SendGroupRRMessage(m, anchorRR, next, AuthInfo);
301047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
301147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				break;		// breaks out of for loop
301247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
301347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			spaceleft -= rrSize;
301447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			oldnext = next;
301547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("SendGroupUpdates: Building a message with resource record %s, next %p, state %d, ttl %d", ARDisplayString(m, rr), next, rr->state, rr->resrec.rroriginalttl);
301647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!(next = BuildUpdateMessage(m, next, rr, limit)))
301747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
301847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// We calculated the space and if we can't fit in, we had some bug in the calculation,
301947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// disable merge completely.
302047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("SendGroupUpdates: ptr NULL while building message with %s", ARDisplayString(m, rr));
302147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				RRMergeFailure(m);
302247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				return mDNSfalse;
302347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
302447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If our estimate was higher, adjust to the actual size
302547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if ((next - oldnext) > rrSize)
302647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("SendGroupUpdates: ERROR!! Record size estimation is wrong for %s, Estimate %d, Actual %d, state %d", ARDisplayString(m, rr), rrSize, next - oldnext, rr->state);
302747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else { spaceleft += rrSize; spaceleft -= (next - oldnext); }
302847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
302947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			nrecords++;
303047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We could have sent an update earlier with this "rr" as anchorRR for which we never got a response.
303147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// To preserve ordering, we blow away the previous connection before sending this.
303247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL;}
303347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->updateid = msgid;
303447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
303547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// By setting the retry time interval here, we will not be looking at these records
303647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// again when we return to CheckGroupRecordUpdates.
303747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			SetRecordRetry(m, rr, 0);
303847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
303947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Either we have parsed all the records or stopped at "rr" above due to lack of space
304047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			startRR = rr;
304147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
304247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
304347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (anchorRR)
304447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
304547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("SendGroupUpdates: Parsed %d records and sending using %s", nrecords, ARDisplayString(m, anchorRR));
304647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SendGroupRRMessage(m, anchorRR, next, AuthInfo);
304747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
304847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return sentallRecords;
304947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
305047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
305147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Merge the record registrations and send them as a group only if they
305247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// have same DomainAuthInfo and hence the same key to put the TSIG
305347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void CheckGroupRecordUpdates(mDNS *const m)
305447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
305547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *rr, *nextRR;
305647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Keep sending as long as there is at least one record to be sent
305747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (MarkRRForSending(m))
305847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
305947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!SendGroupUpdates(m))
306047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
306147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// if everything that was marked was not sent, send them out individually
306247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			for (rr = m->ResourceRecords; rr; rr = nextRR)
306347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
306447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// SendRecordRegistrtion might delete the rr from list, hence
306547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// dereference nextRR before calling the function
306647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				nextRR = rr->next;
306747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (rr->SendRNow == mDNSInterfaceMark)
306847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
306947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Any records marked for sending should be eligible to be sent out
307047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// immediately. Just being cautious
307147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (rr->LastAPTime + rr->ThisAPInterval - m->timenow > 0)
307247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						{ LogMsg("CheckGroupRecordUpdates: ERROR!! Resourcerecord %s not ready", ARDisplayString(m, rr)); continue; }
307347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					rr->SendRNow = mDNSNULL;
307447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					SendRecordRegistration(m, rr);
307547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
307647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
307747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
307847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
307947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
308047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("CheckGroupRecordUpdates: No work, returning");
308147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return;
308247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
308347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
308447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void hndlSRVChanged(mDNS *const m, AuthRecord *rr)
308547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
308647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Reevaluate the target always as NAT/Target could have changed while
308747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// we were registering/deeregistering
308847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	domainname *dt;
308947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *target = GetServiceTarget(m, rr);
309047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!target || target->c[0] == 0)
309147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
309247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// we don't have a target, if we just derregistered, then we don't have to do anything
309347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->state == regState_DeregPending)
309447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
309547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("hndlSRVChanged: SRVChanged, No Target, SRV Deregistered for %##s, state %d", rr->resrec.name->c,
309647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->state);
309747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->SRVChanged = mDNSfalse;
309847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			dt = GetRRDomainNameTarget(&rr->resrec);
309947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (dt) dt->c[0] = 0;
310047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state = regState_NoTarget;	// Wait for the next target change
310147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->resrec.rdlength = rr->resrec.rdestimate = 0;
310247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
310347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
310447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
310547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// we don't have a target, if we just registered, we need to deregister
310647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->state == regState_Pending)
310747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
310847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("hndlSRVChanged: SRVChanged, No Target, Deregistering again %##s, state %d", rr->resrec.name->c, rr->state);
310947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
311047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
311147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state = regState_DeregPending;
311247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
311347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
311447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("hndlSRVChanged: Not in DeregPending or RegPending state %##s, state %d", rr->resrec.name->c, rr->state);
311547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
311647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
311747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
311847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// If we were in registered state and SRV changed to NULL, we deregister and come back here
311947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// if we have a target, we need to register again.
312047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//
312147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// if we just registered check to see if it is same. If it is different just re-register the
312247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// SRV and its assoicated records
312347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//
312447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// UpdateOneSRVRecord takes care of re-registering all service records
312547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if ((rr->state == regState_DeregPending) ||
312647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		   (rr->state == regState_Pending && !SameDomainName(target, &rr->resrec.rdata->u.srv.target)))
312747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
312847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			dt = GetRRDomainNameTarget(&rr->resrec);
312947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (dt) dt->c[0] = 0;
313047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state = regState_NoTarget;	// NoTarget will allow us to pick up new target OR nat traversal state
313147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->resrec.rdlength = rr->resrec.rdestimate = 0;
313247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("hndlSRVChanged: SRVChanged, Valid Target %##s, Registering all records for %##s, state %d",
313347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				target->c, rr->resrec.name->c, rr->state);
313447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->SRVChanged = mDNSfalse;
313547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			UpdateOneSRVRecord(m, rr);
313647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
313747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
313847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Target did not change while this record was registering. Hence, we go to
313947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Registered state - the state we started from.
314047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->state == regState_Pending) rr->state = regState_Registered;
314147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
314247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
314347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->SRVChanged = mDNSfalse;
314447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
314547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
314647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called with lock held
314747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void hndlRecordUpdateReply(mDNS *m, AuthRecord *rr, mStatus err, mDNSu32 random)
314847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
314947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool InvokeCallback = mDNStrue;
315047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSIPPort UpdatePort = zeroIPPort;
315147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
315247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy+1)
315347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("hndlRecordUpdateReply: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
315447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
315547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("hndlRecordUpdateReply: err %d ID %d state %d %s(%p)", err, mDNSVal16(rr->updateid), rr->state, ARDisplayString(m, rr), rr);
315647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
315747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->updateError = err;
315847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
315947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err == mStatus_BadSig || err == mStatus_BadKey) UpdateAutoTunnelDomainStatuses(m);
316047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
316147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
316247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SetRecordRetry(m, rr, random);
316347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
316447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->updateid = zeroID;	// Make sure that this is not considered as part of a group anymore
316547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Later when need to send an update, we will get the zone data again. Thus we avoid
316647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// using stale information.
316747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
316847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Note: By clearing out the zone info here, it also helps better merging of records
316947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// in some cases. For example, when we get out regState_NoTarget state e.g., move out
317047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// of Double NAT, we want all the records to be in one update. Some BTMM records like
317147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// _autotunnel6 and host records are registered/deregistered when NAT state changes.
317247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// As they are re-registered the zone information is cleared out. To merge with other
317347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// records that might be possibly going out, clearing out the information here helps
317447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// as all of them try to get the zone data.
317547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->nta)
317647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
317747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We always expect the question to be stopped when we get a valid response from the server.
317847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// If the zone info tries to change during this time, updateid would be different and hence
317947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// this response should not have been accepted.
318047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->nta->question.ThisQInterval != -1)
318147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("hndlRecordUpdateReply: ResourceRecord %s, zone info question %##s (%s) interval %d not -1",
318247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				ARDisplayString(m, rr), rr->nta->question.qname.c, DNSTypeName(rr->nta->question.qtype), rr->nta->question.ThisQInterval);
318347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		UpdatePort = rr->nta->Port;
318447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, rr->nta);
318547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->nta = mDNSNULL;
318647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
318747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
318847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If we are deregistering the record, then complete the deregistration. Ignore any NAT/SRV change
318947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// that could have happened during that time.
319047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->state == regState_DeregPending)
319147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
319247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("hndlRecordUpdateReply: Received reply for deregister record %##s type %d", rr->resrec.name->c, rr->resrec.rrtype);
319347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) LogMsg("ERROR: Deregistration of record %##s type %d failed with error %d",
319447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						rr->resrec.name->c, rr->resrec.rrtype, err);
319547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->state = regState_Unregistered;
319647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CompleteDeregistration(m, rr);
319747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
319847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
319947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
320047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We are returning early without updating the state. When we come back from sleep we will re-register after
320147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// re-initializing all the state as though it is a first registration. If the record can't be registered e.g.,
320247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// no target, it will be deregistered. Hence, the updating to the right state should not matter when going
320347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// to sleep.
320447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->SleepState)
320547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
320647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Need to set it to NoTarget state so that RecordReadyForSleep knows that
320747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// we are done
320847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->resrec.rrtype == kDNSType_SRV && rr->state == regState_DeregPending)
320947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state = regState_NoTarget;
321047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
321147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
321247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
321347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_UpdatePending)
321447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
321547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) LogMsg("Update record failed for %##s (err %d)", rr->resrec.name->c, err);
321647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->state = regState_Registered;
321747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// deallocate old RData
321847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->OrigRData, rr->OrigRDLen);
321947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
322047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->OrigRData = mDNSNULL;
322147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->InFlightRData = mDNSNULL;
322247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
322347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
322447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->SRVChanged)
322547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
322647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->resrec.rrtype == kDNSType_SRV)
322747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			hndlSRVChanged(m, rr);
322847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
322947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
323047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("hndlRecordUpdateReply: Deregistered %##s (%s), state %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->state);
323147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->SRVChanged = mDNSfalse;
323247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->state != regState_DeregPending) LogMsg("hndlRecordUpdateReply: ResourceRecord %s not in DeregPending state %d", ARDisplayString(m, rr), rr->state);
323347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state = regState_NoTarget;	// Wait for the next target change
323447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
323547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
323647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
323747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
323847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->state == regState_Pending || rr->state == regState_Refresh)
323947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
324047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!err)
324147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
324247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->state == regState_Refresh) InvokeCallback = mDNSfalse;
324347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state = regState_Registered;
324447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
324547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
324647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
324747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Retry without lease only for non-Private domains
324847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("hndlRecordUpdateReply: Registration of record %##s type %d failed with error %d", rr->resrec.name->c, rr->resrec.rrtype, err);
324947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!rr->Private && rr->uselease && err == mStatus_UnknownErr && mDNSSameIPPort(UpdatePort, UnicastDNSPort))
325047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
325147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("hndlRecordUpdateReply: Will retry update of record %##s without lease option", rr->resrec.name->c);
325247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->uselease = mDNSfalse;
325347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
325447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
325547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				return;
325647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
325747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Communicate the error to the application in the callback below
325847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
325947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
326047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
326147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->QueuedRData && rr->state == regState_Registered)
326247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
326347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->state = regState_UpdatePending;
326447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->InFlightRData = rr->QueuedRData;
326547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->InFlightRDLen = rr->QueuedRDLen;
326647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->OrigRData = rr->resrec.rdata;
326747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->OrigRDLen = rr->resrec.rdlength;
326847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->QueuedRData = mDNSNULL;
326947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
327047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
327147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
327247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
327347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
327447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Don't invoke the callback on error as this may not be useful to the client.
327547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// The client may potentially delete the resource record on error which we normally
327647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// delete during deregistration
327747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!err && InvokeCallback && rr->RecordCallback)
327847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
327947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("hndlRecordUpdateReply: Calling record callback on %##s", rr->resrec.name->c);
328047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_DropLockBeforeCallback();
328147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->RecordCallback(m, rr, err);
328247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_ReclaimLockAfterCallback();
328347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
328447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
328547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
328647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
328747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
328847e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void uDNS_ReceiveNATPMPPacket(mDNS *m, const mDNSInterfaceID InterfaceID, mDNSu8 *pkt, mDNSu16 len)
328947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
329047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATTraversalInfo *ptr;
329147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATAddrReply     *AddrReply    = (NATAddrReply    *)pkt;
329247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATPortMapReply  *PortMapReply = (NATPortMapReply *)pkt;
329347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu32 nat_elapsed, our_elapsed;
329447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
329547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Minimum packet is vers (1) opcode (1) err (2) upseconds (4) = 8 bytes
329647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!AddrReply->err && len < 8) { LogMsg("NAT Traversal message too short (%d bytes)", len); return; }
329747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AddrReply->vers != NATMAP_VERS) { LogMsg("Received NAT Traversal response with version %d (expected %d)", pkt[0], NATMAP_VERS); return; }
329847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
329947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Read multi-byte numeric values (fields are identical in a NATPortMapReply)
330047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AddrReply->err       = (mDNSu16) (                                                (mDNSu16)pkt[2] << 8 | pkt[3]);
330147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AddrReply->upseconds = (mDNSs32) ((mDNSs32)pkt[4] << 24 | (mDNSs32)pkt[5] << 16 | (mDNSs32)pkt[6] << 8 | pkt[7]);
330247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
330347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	nat_elapsed = AddrReply->upseconds - m->LastNATupseconds;
330447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	our_elapsed = (m->timenow - m->LastNATReplyLocalTime) / mDNSPlatformOneSecond;
330547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("uDNS_ReceiveNATPMPPacket %X upseconds %u nat_elapsed %d our_elapsed %d", AddrReply->opcode, AddrReply->upseconds, nat_elapsed, our_elapsed);
330647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
330747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We compute a conservative estimate of how much the NAT gateways's clock should have advanced
330847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 1. We subtract 12.5% from our own measured elapsed time, to allow for NAT gateways that have an inacurate clock that runs slowly
330947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 2. We add a two-second safety margin to allow for rounding errors: e.g.
331047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//    -- if NAT gateway sends a packet at t=2.000 seconds, then one at t=7.999, that's approximately 6 real seconds,
331147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//       but based on the values in the packet (2,7) the apparent difference according to the packet is only 5 seconds
331247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//    -- if we're slow handling packets and/or we have coarse clock granularity,
331347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//       we could receive the t=2 packet at our t=1.999 seconds, which we round down to 1
331447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//       and the t=7.999 packet at our t=8.000 seconds, which we record as 8,
331547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//       giving an apparent local time difference of 7 seconds
331647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//    The two-second safety margin coves this possible calculation discrepancy
331747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AddrReply->upseconds < m->LastNATupseconds || nat_elapsed + 2 < our_elapsed - our_elapsed/8)
331847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{ LogMsg("NAT gateway %#a rebooted", &m->Router); RecreateNATMappings(m); }
331947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
332047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->LastNATupseconds      = AddrReply->upseconds;
332147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->LastNATReplyLocalTime = m->timenow;
332247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#ifdef _LEGACY_NAT_TRAVERSAL_
332347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LNT_ClearState(m);
332447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif // _LEGACY_NAT_TRAVERSAL_
332547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
332647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AddrReply->opcode == NATOp_AddrResponse)
332747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
332847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
332947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		static char msgbuf[16];
333047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_snprintf(msgbuf, sizeof(msgbuf), "%d", AddrReply->err);
333147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.AddressRequest", AddrReply->err ? "failure" : "success", msgbuf, "");
333247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
333347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!AddrReply->err && len < sizeof(NATAddrReply)) { LogMsg("NAT Traversal AddrResponse message too short (%d bytes)", len); return; }
333447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		natTraversalHandleAddressReply(m, AddrReply->err, AddrReply->ExtAddr);
333547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
333647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (AddrReply->opcode == NATOp_MapUDPResponse || AddrReply->opcode == NATOp_MapTCPResponse)
333747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
333847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSu8 Protocol = AddrReply->opcode & 0x7F;
333947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder
334047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		static char msgbuf[16];
334147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_snprintf(msgbuf, sizeof(msgbuf), "%s - %d", AddrReply->opcode == NATOp_MapUDPResponse ? "UDP" : "TCP", PortMapReply->err);
334247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.PortMapRequest", PortMapReply->err ? "failure" : "success", msgbuf, "");
334347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
334447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!PortMapReply->err)
334547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
334647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (len < sizeof(NATPortMapReply)) { LogMsg("NAT Traversal PortMapReply message too short (%d bytes)", len); return; }
334747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			PortMapReply->NATRep_lease = (mDNSu32) ((mDNSu32)pkt[12] << 24 | (mDNSu32)pkt[13] << 16 | (mDNSu32)pkt[14] << 8 | pkt[15]);
334847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
334947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
335047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Since some NAT-PMP server implementations don't return the requested internal port in
335147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// the reply, we can't associate this reply with a particular NATTraversalInfo structure.
335247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We globally keep track of the most recent error code for mappings.
335347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->LastNATMapResultCode = PortMapReply->err;
335447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
335547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (ptr = m->NATTraversals; ptr; ptr=ptr->next)
335647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (ptr->Protocol == Protocol && mDNSSameIPPort(ptr->IntPort, PortMapReply->intport))
335747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				natTraversalHandlePortMapReply(m, ptr, InterfaceID, PortMapReply->err, PortMapReply->extport, PortMapReply->NATRep_lease);
335847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
335947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else { LogMsg("Received NAT Traversal response with version unknown opcode 0x%X", AddrReply->opcode); return; }
336047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
336147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Don't need an SSDP socket if we get a NAT-PMP packet
336247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->SSDPSocket) { debugf("uDNS_ReceiveNATPMPPacket destroying SSDPSocket %p", &m->SSDPSocket); mDNSPlatformUDPClose(m->SSDPSocket); m->SSDPSocket = mDNSNULL; }
336347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
336447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
336547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// <rdar://problem/3925163> Shorten DNS-SD queries to avoid NAT bugs
336647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// <rdar://problem/4288449> Add check to avoid crashing NAT gateways that have buggy DNS relay code
336747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
336847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// We know of bugs in home NAT gateways that cause them to crash if they receive certain DNS queries.
336947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// The DNS queries that make them crash are perfectly legal DNS queries, but even if they weren't,
337047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// the gateway shouldn't crash -- in today's world of viruses and network attacks, software has to
337147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// be written assuming that a malicious attacker could send them any packet, properly-formed or not.
337247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Still, we don't want to be crashing people's home gateways, so we go out of our way to avoid
337347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// the queries that crash them.
337447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
337547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Some examples:
337647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
337747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 1. Any query where the name ends in ".in-addr.arpa." and the text before this is 32 or more bytes.
337847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    The query type does not need to be PTR -- the gateway will crash for any query type.
337947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    e.g. "ping long-name-crashes-the-buggy-router.in-addr.arpa" will crash one of these.
338047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
338147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 2. Any query that results in a large response with the TC bit set.
338247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
338347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 3. Any PTR query that doesn't begin with four decimal numbers.
338447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    These gateways appear to assume that the only possible PTR query is a reverse-mapping query
338547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    (e.g. "1.0.168.192.in-addr.arpa") and if they ever get a PTR query where the first four
338647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    labels are not all decimal numbers in the range 0-255, they handle that by crashing.
338747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    These gateways also ignore the remainder of the name following the four decimal numbers
338847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    -- whether or not it actually says in-addr.arpa, they just make up an answer anyway.
338947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
339047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// The challenge therefore is to craft a query that will discern whether the DNS server
339147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// is one of these buggy ones, without crashing it. Furthermore we don't want our test
339247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// queries making it all the way to the root name servers, putting extra load on those
339347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// name servers and giving Apple a bad reputation. To this end we send this query:
339447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//     dig -t ptr 1.0.0.127.dnsbugtest.1.0.0.127.in-addr.arpa.
339547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
339647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// The text preceding the ".in-addr.arpa." is under 32 bytes, so it won't cause crash (1).
339747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// It will not yield a large response with the TC bit set, so it won't cause crash (2).
339847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// It starts with four decimal numbers, so it won't cause crash (3).
339947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// The name falls within the "1.0.0.127.in-addr.arpa." domain, the reverse-mapping name for the local
340047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// loopback address, and therefore the query will black-hole at the first properly-configured DNS server
340147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// it reaches, making it highly unlikely that this query will make it all the way to the root.
340247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//
340347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Finally, the correct response to this query is NXDOMAIN or a similar error, but the
340447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// gateways that ignore the remainder of the name following the four decimal numbers
340547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// give themselves away by actually returning a result for this nonsense query.
340647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
340747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal const domainname *DNSRelayTestQuestion = (const domainname*)
340847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	"\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\xa" "dnsbugtest"
340947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	"\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\x7" "in-addr" "\x4" "arpa";
341047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
341147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// See comments above for DNSRelayTestQuestion
341247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// If this is the kind of query that has the risk of crashing buggy DNS servers, we do a test question first
341347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSBool NoTestQuery(DNSQuestion *q)
341447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
341547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int i;
341647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *p = q->qname.c;
341747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->AuthInfo) return(mDNStrue);		// Don't need a test query for private queries sent directly to authoritative server over TLS/TCP
341847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->qtype != kDNSType_PTR) return(mDNStrue);		// Don't need a test query for any non-PTR queries
341947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (i=0; i<4; i++)		// If qname does not begin with num.num.num.num, can't skip the test query
342047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
342147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (p[0] < 1 || p[0] > 3) return(mDNSfalse);
342247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (              p[1] < '0' || p[1] > '9' ) return(mDNSfalse);
342347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (p[0] >= 2 && (p[2] < '0' || p[2] > '9')) return(mDNSfalse);
342447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (p[0] >= 3 && (p[3] < '0' || p[3] > '9')) return(mDNSfalse);
342547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		p += 1 + p[0];
342647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
342747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If remainder of qname is ".in-addr.arpa.", this is a vanilla reverse-mapping query and
342847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// we can safely do it without needing a test query first, otherwise we need the test query.
342947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(SameDomainName((domainname*)p, (const domainname*)"\x7" "in-addr" "\x4" "arpa"));
343047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
343147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
343247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Returns mDNStrue if response was handled
343347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSBool uDNS_ReceiveTestQuestionResponse(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
343447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
343547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
343647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const mDNSu8 *ptr = msg->data;
343747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion pktq;
343847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSServer *s;
343947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu32 result = 0;
344047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
344147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 1. Find out if this is an answer to one of our test questions
344247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (msg->h.numQuestions != 1) return(mDNSfalse);
344347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = getQuestion(msg, ptr, end, mDNSInterface_Any, &pktq);
344447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr) return(mDNSfalse);
344547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (pktq.qtype != kDNSType_PTR || pktq.qclass != kDNSClass_IN) return(mDNSfalse);
344647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!SameDomainName(&pktq.qname, DNSRelayTestQuestion)) return(mDNSfalse);
344747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
344847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 2. If the DNS relay gave us a positive response, then it's got buggy firmware
344947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// else, if the DNS relay gave us an error or no-answer response, it passed our test
345047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if ((msg->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr && msg->h.numAnswers > 0)
345147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		result = DNSServer_Failed;
345247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
345347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		result = DNSServer_Passed;
345447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
345547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// 3. Find occurrences of this server in our list, and mark them appropriately
345647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (s = m->DNSServers; s; s = s->next)
345747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
345847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSBool matchaddr = (s->teststate != result && mDNSSameAddress(srcaddr, &s->addr) && mDNSSameIPPort(srcport, s->port));
345947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSBool matchid   = (s->teststate == DNSServer_Untested && mDNSSameOpaque16(msg->h.id, s->testid));
346047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (matchaddr || matchid)
346147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
346247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DNSQuestion *q;
346347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			s->teststate = result;
346447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (result == DNSServer_Passed)
346547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
346647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("DNS Server %#a:%d (%#a:%d) %d passed%s",
346747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					&s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
346847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
346947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
347047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
347147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
347247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("NOTE: Wide-Area Service Discovery disabled to avoid crashing defective DNS relay %#a:%d (%#a:%d) %d%s",
347347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					&s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
347447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
347547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
347647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
347747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If this server has just changed state from DNSServer_Untested to DNSServer_Passed, then retrigger any waiting questions.
347847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We use the NoTestQuery() test so that we only retrigger questions that were actually blocked waiting for this test to complete.
347947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (result == DNSServer_Passed)		// Unblock any questions that were waiting for this result
348047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				for (q = m->Questions; q; q=q->next)
348147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->qDNSServer == s && !NoTestQuery(q))
348247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						{
348347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->ThisQInterval = INIT_UCAST_POLL_INTERVAL / QuestionIntervalStep;
348447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->unansweredQueries = 0;
348547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->LastQTime = m->timenow - q->ThisQInterval;
348647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						m->NextScheduledQuery = m->timenow;
348747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						}
348847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
348947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
349047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
349147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return(mDNStrue); // Return mDNStrue to tell uDNS_ReceiveMsg it doesn't need to process this packet further
349247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
349347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
349447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called from mDNSCoreReceive with the lock held
349547e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void uDNS_ReceiveMsg(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end, const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
349647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
349747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *qptr;
349847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err = mStatus_NoError;
349947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
350047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 StdR    = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
350147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 UpdateR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
350247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 QR_OP   = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
350347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 rcode   = (mDNSu8)(msg->h.flags.b[1] & kDNSFlag1_RC_Mask);
350447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
350547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void)srcport; // Unused
350647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
350747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("uDNS_ReceiveMsg from %#-15a with "
350847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
350947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		srcaddr,
351047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
351147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
351247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
351347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		msg->h.numAdditionals, msg->h.numAdditionals == 1 ? ""     : "s", end - msg->data);
351447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
351547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (QR_OP == StdR)
351647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
351747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//if (srcaddr && recvLLQResponse(m, msg, end, srcaddr, srcport)) return;
351847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (uDNS_ReceiveTestQuestionResponse(m, msg, end, srcaddr, srcport)) return;
351947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (qptr = m->Questions; qptr; qptr = qptr->next)
352047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (msg->h.flags.b[0] & kDNSFlag0_TC && mDNSSameOpaque16(qptr->TargetQID, msg->h.id) && m->timenow - qptr->LastQTime < RESPONSE_WINDOW)
352147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
352247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!srcaddr) LogMsg("uDNS_ReceiveMsg: TCP DNS response had TC bit set: ignoring");
352347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else
352447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
352547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Don't reuse TCP connections. We might have failed over to a different DNS server
352647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// while the first TCP connection is in progress. We need a new TCP connection to the
352747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// new DNS server. So, always try to establish a new connection.
352847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (qptr->tcp) { DisposeTCPConn(qptr->tcp); qptr->tcp = mDNSNULL; }
352947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					qptr->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_Zero, srcaddr, srcport, mDNSNULL, qptr, mDNSNULL);
353047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
353147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
353247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
353347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
353447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (QR_OP == UpdateR)
353547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
353647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSu32 lease = GetPktLease(m, msg, end);
353747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSs32 expire = m->timenow + (mDNSs32)lease * mDNSPlatformOneSecond;
353847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSu32 random = mDNSRandom((mDNSs32)lease * mDNSPlatformOneSecond/10);
353947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
354047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//rcode = kDNSFlag1_RC_ServFail;	// Simulate server failure (rcode 2)
354147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
354247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Walk through all the records that matches the messageID. There could be multiple
354347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// records if we had sent them in a group
354447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->CurrentRecord)
354547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("uDNS_ReceiveMsg ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
354647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->CurrentRecord = m->ResourceRecords;
354747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		while (m->CurrentRecord)
354847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
354947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			AuthRecord *rptr = m->CurrentRecord;
355047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->CurrentRecord = m->CurrentRecord->next;
355147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (AuthRecord_uDNS(rptr) && mDNSSameOpaque16(rptr->updateid, msg->h.id))
355247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
355347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err = checkUpdateResult(m, rptr->resrec.name, rcode, msg, end);
355447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!err && rptr->uselease && lease)
355547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (rptr->expire - expire >= 0 || rptr->state != regState_UpdatePending)
355647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						{
355747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						rptr->expire = expire;
355847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						rptr->refreshCount = 0;
355947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						}
356047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// We pass the random value to make sure that if we update multiple
356147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// records, they all get the same random value
356247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				hndlRecordUpdateReply(m, rptr, err, random);
356347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
356447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
356547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
356647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("Received unexpected response: ID %d matches no active records", mDNSVal16(msg->h.id));
356747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
356847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
356947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
357047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
357147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - Query Routines
357247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
357347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
357447e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void sendLLQRefresh(mDNS *m, DNSQuestion *q)
357547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
357647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *end;
357747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LLQOptData llq;
357847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *limit = m->omsg.data + AbsoluteMaxDNSMessageData;
357947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
358047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->ReqLease)
358147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if ((q->state == LLQ_Established && q->ntries >= kLLQ_MAX_TRIES) || q->expire - m->timenow < 0)
358247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
358347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("Unable to refresh LLQ %##s (%s) - will retry in %d seconds", q->qname.c, DNSTypeName(q->qtype), LLQ_POLL_INTERVAL / mDNSPlatformOneSecond);
358447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			StartLLQPolling(m,q);
358547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
358647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
358747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
358847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	llq.vers     = kLLQ_Vers;
358947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	llq.llqOp    = kLLQOp_Refresh;
359047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	llq.err      = q->tcp ? GetLLQEventPort(m, &q->servAddr) : LLQErr_NoError;	// If using TCP tell server what UDP port to send notifications to
359147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	llq.id       = q->id;
359247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	llq.llqlease = q->ReqLease;
359347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
359447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
359547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	end = putLLQ(&m->omsg, m->omsg.data, q, &llq);
359647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!end) { LogMsg("sendLLQRefresh: putLLQ failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
359747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
359847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Note that we (conditionally) add HINFO and TSIG here, since the question might be going away,
359947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// so we may not be able to reference it (most importantly it's AuthInfo) when we actually send the message
360047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	end = putHINFO(m, &m->omsg, end, q->AuthInfo, limit);
360147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!end) { LogMsg("sendLLQRefresh: putHINFO failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
360247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
360347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (PrivateQuery(q))
360447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
360547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DNSDigest_SignMessageHostByteOrder(&m->omsg, &end, q->AuthInfo);
360647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!end) { LogMsg("sendLLQRefresh: DNSDigest_SignMessage failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
360747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
360847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
360947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (PrivateQuery(q) && !q->tcp)
361047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
361147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("sendLLQRefresh setting up new TLS session %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
361247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!q->nta) { LogMsg("sendLLQRefresh:ERROR!! q->nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
361347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->tcp = MakeTCPConn(m, &m->omsg, end, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
361447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
361547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
361647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
361747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mStatus err;
361847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
361947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// if AuthInfo and AuthInfo->AutoTunnel is set, we use the TCP socket but don't need to pass the AuthInfo as
362047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// we already protected the message above.
362147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("sendLLQRefresh: using existing %s session %##s (%s)", PrivateQuery(q) ? "TLS" : "UDP",
362247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->qname.c, DNSTypeName(q->qtype));
362347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
362447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		err = mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, q->tcp ? q->tcp->sock : mDNSNULL, mDNSNULL);
362547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err)
362647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
362747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("sendLLQRefresh: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err);
362847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
362947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
363047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
363147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
363247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->ntries++;
363347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
363447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("sendLLQRefresh ntries %d %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
363547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
363647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->LastQTime = m->timenow;
363747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SetNextQueryTime(m, q);
363847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
363947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
364047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void LLQGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
364147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
364247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *q = (DNSQuestion *)zoneInfo->ZoneDataContext;
364347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
364447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
364547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
364647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If we get here it means that the GetZoneData operation has completed.
364747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We hold on to the zone data if it is AutoTunnel as we use the hostname
364847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// in zoneInfo during the TLS connection setup.
364947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->servAddr = zeroAddr;
365047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->servPort = zeroIPPort;
365147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
365247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!err && zoneInfo && !mDNSIPPortIsZero(zoneInfo->Port) && !mDNSAddressIsZero(&zoneInfo->Addr) && zoneInfo->Host.c[0])
365347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
365447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->servAddr = zoneInfo->Addr;
365547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->servPort = zoneInfo->Port;
365647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!PrivateQuery(q))
365747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
365847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We don't need the zone data as we use it only for the Host information which we
365947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// don't need if we are not going to use TLS connections.
366047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q->nta)
366147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
366247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
366347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				CancelGetZoneData(m, q->nta);
366447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->nta = mDNSNULL;
366547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
366647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
366747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ntries = 0;
366847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("LLQGotZoneData %#a:%d", &q->servAddr, mDNSVal16(q->servPort));
366947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		startLLQHandshake(m, q);
367047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
367147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
367247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
367347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->nta)
367447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
367547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
367647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			CancelGetZoneData(m, q->nta);
367747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->nta = mDNSNULL;
367847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
367947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		StartLLQPolling(m,q);
368047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err == mStatus_NoSuchNameErr)
368147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
368247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// this actually failed, so mark it by setting address to all ones
368347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->servAddr.type = mDNSAddrType_IPv4;
368447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->servAddr.ip.v4 = onesIPv4Addr;
368547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
368647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
368747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
368847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
368947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
369047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
369147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
369247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void PrivateQueryGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
369347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
369447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *q = (DNSQuestion *) zoneInfo->ZoneDataContext;
369547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
369647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("PrivateQueryGotZoneData %##s (%s) err %d Zone %##s Private %d", q->qname.c, DNSTypeName(q->qtype), err, zoneInfo->ZoneName.c, zoneInfo->ZonePrivate);
369747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
369847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->nta != zoneInfo) LogMsg("PrivateQueryGotZoneData:ERROR!!: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
369947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
370047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err || !zoneInfo || mDNSAddressIsZero(&zoneInfo->Addr) || mDNSIPPortIsZero(zoneInfo->Port) || !zoneInfo->Host.c[0])
370147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
370247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("PrivateQueryGotZoneData: ERROR!! %##s (%s) invoked with error code %d %p %#a:%d",
370347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->qname.c, DNSTypeName(q->qtype), err, zoneInfo,
370447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			zoneInfo ? &zoneInfo->Addr : mDNSNULL,
370547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			zoneInfo ? mDNSVal16(zoneInfo->Port) : 0);
370647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, q->nta);
370747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->nta = mDNSNULL;
370847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
370947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
371047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
371147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!zoneInfo->ZonePrivate)
371247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
371347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("Private port lookup failed -- retrying without TLS -- %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
371447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->AuthInfo      = mDNSNULL;		// Clear AuthInfo so we try again non-private
371547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->ThisQInterval = InitialQuestionInterval;
371647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->LastQTime     = m->timenow - q->ThisQInterval;
371747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, q->nta);
371847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->nta = mDNSNULL;
371947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Lock(m);
372047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		SetNextQueryTime(m, q);
372147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Unlock(m);
372247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
372347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Next call to uDNS_CheckCurrentQuestion() will do this as a non-private query
372447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
372547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
372647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!PrivateQuery(q))
372747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
372847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("PrivateQueryGotZoneData: ERROR!! Not a private query %##s (%s) AuthInfo %p", q->qname.c, DNSTypeName(q->qtype), q->AuthInfo);
372947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, q->nta);
373047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		q->nta = mDNSNULL;
373147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
373247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
373347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
373447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->TargetQID = mDNS_NewMessageID(m);
373547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
373647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!q->nta) { LogMsg("PrivateQueryGotZoneData:ERROR!! nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
373747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	q->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_UseTLS, &zoneInfo->Addr, zoneInfo->Port, &q->nta->Host, q, mDNSNULL);
373847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->nta) { CancelGetZoneData(m, q->nta); q->nta = mDNSNULL; }
373947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
374047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
374147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
374247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
374347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - Dynamic Updates
374447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
374547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
374647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
374747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void RecordRegistrationGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneData)
374847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
374947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *newRR = (AuthRecord*)zoneData->ZoneDataContext;
375047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *ptr;
375147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int c1, c2;
375247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
375347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (newRR->nta != zoneData)
375447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("RecordRegistrationGotZoneData: nta (%p) != zoneData (%p)  %##s (%s)", newRR->nta, zoneData, newRR->resrec.name->c, DNSTypeName(newRR->resrec.rrtype));
375547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
375647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy)
375747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("RecordRegistrationGotZoneData: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
375847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
375947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// make sure record is still in list (!!!)
376047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (ptr = m->ResourceRecords; ptr; ptr = ptr->next) if (ptr == newRR) break;
376147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr)
376247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
376347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("RecordRegistrationGotZoneData - RR no longer in list.  Discarding.");
376447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, newRR->nta);
376547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->nta = mDNSNULL;
376647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
376747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
376847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
376947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// check error/result
377047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (err)
377147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
377247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err != mStatus_NoSuchNameErr) LogMsg("RecordRegistrationGotZoneData: error %d", err);
377347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, newRR->nta);
377447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->nta = mDNSNULL;
377547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
377647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
377747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
377847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!zoneData) { LogMsg("ERROR: RecordRegistrationGotZoneData invoked with NULL result and no error"); return; }
377947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
378047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (newRR->resrec.rrclass != zoneData->ZoneClass)
378147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
378247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("ERROR: New resource record's class (%d) does not match zone class (%d)", newRR->resrec.rrclass, zoneData->ZoneClass);
378347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, newRR->nta);
378447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->nta = mDNSNULL;
378547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
378647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
378747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
378847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Don't try to do updates to the root name server.
378947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We might be tempted also to block updates to any single-label name server (e.g. com, edu, net, etc.) but some
379047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// organizations use their own private pseudo-TLD, like ".home", etc, and we don't want to block that.
379147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (zoneData->ZoneName.c[0] == 0)
379247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
379347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("RecordRegistrationGotZoneData: No name server found claiming responsibility for \"%##s\"!", newRR->resrec.name->c);
379447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, newRR->nta);
379547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->nta = mDNSNULL;
379647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
379747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
379847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
379947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Store discovered zone data
380047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	c1 = CountLabels(newRR->resrec.name);
380147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	c2 = CountLabels(&zoneData->ZoneName);
380247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (c2 > c1)
380347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
380447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" is longer than \"%##s\"", zoneData->ZoneName.c, newRR->resrec.name->c);
380547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, newRR->nta);
380647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->nta = mDNSNULL;
380747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
380847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
380947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	newRR->zone = SkipLeadingLabels(newRR->resrec.name, c1-c2);
381047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!SameDomainName(newRR->zone, &zoneData->ZoneName))
381147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
381247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" does not match \"%##s\" for \"%##s\"", newRR->zone->c, zoneData->ZoneName.c, newRR->resrec.name->c);
381347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, newRR->nta);
381447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->nta = mDNSNULL;
381547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
381647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
381747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
381847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (mDNSIPPortIsZero(zoneData->Port) || mDNSAddressIsZero(&zoneData->Addr) || !zoneData->Host.c[0])
381947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
382047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("RecordRegistrationGotZoneData: No _dns-update._udp service found for \"%##s\"!", newRR->resrec.name->c);
382147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		CancelGetZoneData(m, newRR->nta);
382247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->nta = mDNSNULL;
382347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
382447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
382547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
382647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	newRR->Private      = zoneData->ZonePrivate;
382747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("RecordRegistrationGotZoneData: Set zone information for %##s %##s to %#a:%d",
382847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->resrec.name->c, zoneData->ZoneName.c, &zoneData->Addr, mDNSVal16(zoneData->Port));
382947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
383047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If we are deregistering, uDNS_DeregisterRecord will do that as it has the zone data now.
383147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (newRR->state == regState_DeregPending)
383247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
383347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Lock(m);
383447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		uDNS_DeregisterRecord(m, newRR);
383547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Unlock(m);
383647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
383747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
383847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
383947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (newRR->resrec.rrtype == kDNSType_SRV)
384047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
384147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		const domainname *target;
384247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Reevaluate the target always as NAT/Target could have changed while
384347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// we were fetching zone data.
384447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Lock(m);
384547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		target = GetServiceTarget(m, newRR);
384647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_Unlock(m);
384747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!target || target->c[0] == 0)
384847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
384947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			domainname *t = GetRRDomainNameTarget(&newRR->resrec);
385047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("RecordRegistrationGotZoneData - no target for %##s", newRR->resrec.name->c);
385147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (t) t->c[0] = 0;
385247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			newRR->resrec.rdlength = newRR->resrec.rdestimate = 0;
385347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			newRR->state = regState_NoTarget;
385447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			CancelGetZoneData(m, newRR->nta);
385547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			newRR->nta = mDNSNULL;
385647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
385747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
385847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
385947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If we have non-zero service port (always?)
386047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// and a private address, and update server is non-private
386147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// and this service is AutoTarget
386247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// then initiate a NAT mapping request. On completion it will do SendRecordRegistration() for us
386347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (newRR->resrec.rrtype == kDNSType_SRV && !mDNSIPPortIsZero(newRR->resrec.rdata->u.srv.port) &&
386447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && newRR->nta && !mDNSAddrIsRFC1918(&newRR->nta->Addr) &&
386547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->AutoTarget == Target_AutoHostAndNATMAP)
386647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
386747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DomainAuthInfo *AuthInfo;
386847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AuthInfo = GetAuthInfoForName(m, newRR->resrec.name);
386947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (AuthInfo && AuthInfo->AutoTunnel)
387047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
387147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			domainname *t = GetRRDomainNameTarget(&newRR->resrec);
387247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("RecordRegistrationGotZoneData: ERROR!! AutoTunnel has Target_AutoHostAndNATMAP for %s", ARDisplayString(m, newRR));
387347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (t) t->c[0] = 0;
387447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			newRR->resrec.rdlength = newRR->resrec.rdestimate = 0;
387547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			newRR->state = regState_NoTarget;
387647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			CancelGetZoneData(m, newRR->nta);
387747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			newRR->nta = mDNSNULL;
387847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
387947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
388047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// During network transitions, we are called multiple times in different states. Setup NAT
388147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// state just once for this record.
388247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!newRR->NATinfo.clientContext)
388347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
388447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("RecordRegistrationGotZoneData StartRecordNatMap %s", ARDisplayString(m, newRR));
388547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			newRR->state = regState_NATMap;
388647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			StartRecordNatMap(m, newRR);
388747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return;
388847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
388947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else LogInfo("RecordRegistrationGotZoneData: StartRecordNatMap for %s, state %d, context %p", ARDisplayString(m, newRR), newRR->state, newRR->NATinfo.clientContext);
389047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
389147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
389247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We want IsRecordMergeable to check whether it is a record whose update can be
389347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// sent with others. We set the time before we call IsRecordMergeable, so that
389447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// it does not fail this record based on time. We are interested in other checks
389547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// at this time. If a previous update resulted in error, then don't reset the
389647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// interval. Preserve the back-off so that we don't keep retrying aggressively.
389747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (newRR->updateError == mStatus_NoError)
389847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
389947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
390047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
390147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
390247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (IsRecordMergeable(m, newRR, m->timenow + MERGE_DELAY_TIME))
390347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
390447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Delay the record registration by MERGE_DELAY_TIME so that we can merge them
390547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// into one update
390647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("RecordRegistrationGotZoneData: Delayed registration for %s", ARDisplayString(m, newRR));
390747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		newRR->LastAPTime += MERGE_DELAY_TIME;
390847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
390947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
391047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
391147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
391247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr)
391347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
391447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *ptr = m->omsg.data;
391547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu8 *limit;
391647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *AuthInfo;
391747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
391847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->mDNS_busy != m->mDNS_reentrancy+1)
391947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("SendRecordDeRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
392047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
392147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
392247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
392347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("SendRecordDeRegistration: No zone info for Resource record %s RecordType %d", ARDisplayString(m, rr), rr->resrec.RecordType);
392447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return;
392547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
392647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
392747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	limit = ptr + AbsoluteMaxDNSMessageData;
392847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
392947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	limit -= RRAdditionalSize(m, AuthInfo);
393047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
393147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->updateid = mDNS_NewMessageID(m);
393247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	InitializeDNSMessage(&m->omsg.h, rr->updateid, UpdateReqFlags);
393347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
393447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// set zone
393547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = putZone(&m->omsg, ptr, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
393647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr) goto exit;
393747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
393847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	ptr = BuildUpdateMessage(m, ptr, rr, limit);
393947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
394047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!ptr) goto exit;
394147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
394247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (rr->Private)
394347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
394447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("SendRecordDeregistration TCP %p %s", rr->tcp, ARDisplayString(m, rr));
394547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->tcp) LogInfo("SendRecordDeregistration: Disposing existing TCP connection for %s", ARDisplayString(m, rr));
394647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
394747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!rr->nta) { LogMsg("SendRecordDeregistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
394847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		rr->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &rr->nta->Addr, rr->nta->Port, &rr->nta->Host, mDNSNULL, rr);
394947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
395047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
395147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
395247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mStatus err;
395347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("SendRecordDeregistration UDP %s", ARDisplayString(m, rr));
395447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!rr->nta) { LogMsg("SendRecordDeregistration:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
395547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &rr->nta->Addr, rr->nta->Port, mDNSNULL, GetAuthInfoForName_internal(m, rr->resrec.name));
395647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) debugf("ERROR: SendRecordDeregistration - mDNSSendDNSMessage - %d", err);
395747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//if (rr->state == regState_DeregPending) CompleteDeregistration(m, rr);		// Don't touch rr after this
395847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
395947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SetRecordRetry(m, rr, 0);
396047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return;
396147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwaltexit:
396247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogMsg("SendRecordDeregistration: Error formatting message for %s", ARDisplayString(m, rr));
396347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
396447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
396547e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus uDNS_DeregisterRecord(mDNS *const m, AuthRecord *const rr)
396647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
396747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *info;
396847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
396947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("uDNS_DeregisterRecord: Resource Record %s, state %d", ARDisplayString(m, rr), rr->state);
397047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
397147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	switch (rr->state)
397247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
397347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Refresh:
397447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Pending:
397547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_UpdatePending:
397647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Registered: break;
397747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_DeregPending: break;
397847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
397947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NATError:
398047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NATMap:
398147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// A record could be in NoTarget to start with if the corresponding SRV record could not find a target.
398247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// It is also possible to reenter the NoTarget state when we move to a network with a NAT that has
398347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// no NAT-PMP/UPnP support. In that case before we entered NoTarget, we already deregistered with
398447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// the server.
398547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NoTarget:
398647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Unregistered:
398747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Zero:
398847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		default:
398947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("uDNS_DeregisterRecord: State %d for %##s type %s", rr->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
399047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// This function may be called during sleep when there are no sleep proxy servers
399147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) CompleteDeregistration(m, rr);
399247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return mStatus_NoError;
399347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
399447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
399547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// If a current group registration is pending, we can't send this deregisration till that registration
399647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// has reached the server i.e., the ordering is important. Previously, if we did not send this
399747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// registration in a group, then the previous connection will be torn down as part of sending the
399847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// deregistration. If we send this in a group, we need to locate the resource record that was used
399947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// to send this registration and terminate that connection. This means all the updates on that might
400047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// be lost (assuming the response is not waiting for us at the socket) and the retry will send the
400147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// update again sometime in the near future.
400247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	//
400347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// NOTE: SSL handshake failures normally free the TCP connection immediately. Hence, you may not
400447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// find the TCP below there. This case can happen only when tcp is trying to actively retransmit
400547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// the request or SSL negotiation taking time i.e resource record is actively trying to get the
400647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// message to the server. During that time a deregister has to happen.
400747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
400847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!mDNSOpaque16IsZero(rr->updateid))
400947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
401047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AuthRecord *anchorRR;
401147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSBool found = mDNSfalse;
401247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		for (anchorRR = m->ResourceRecords; anchorRR; anchorRR = anchorRR->next)
401347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
401447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (AuthRecord_uDNS(rr) && mDNSSameOpaque16(anchorRR->updateid, rr->updateid) && anchorRR->tcp)
401547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
401647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("uDNS_DeregisterRecord: Found Anchor RR %s terminated", ARDisplayString(m, anchorRR));
401747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (found)
401847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("uDNS_DeregisterRecord: ERROR: Another anchorRR %s found", ARDisplayString(m, anchorRR));
401947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				DisposeTCPConn(anchorRR->tcp);
402047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				anchorRR->tcp = mDNSNULL;
402147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				found = mDNStrue;
402247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
402347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
402447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!found) LogInfo("uDNSDeregisterRecord: Cannot find the anchor Resource Record for %s, not an error", ARDisplayString(m, rr));
402547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
402647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
402747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Retry logic for deregistration should be no different from sending registration the first time.
402847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Currently ThisAPInterval most likely is set to the refresh interval
402947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->state          = regState_DeregPending;
403047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
403147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	rr->LastAPTime     = m->timenow - INIT_RECORD_REG_INTERVAL;
403247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	info = GetAuthInfoForName_internal(m, rr->resrec.name);
403347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
403447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
403547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Delay the record deregistration by MERGE_DELAY_TIME so that we can merge them
403647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// into one update. If the domain is being deleted, delay by 2 * MERGE_DELAY_TIME
403747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// so that we can merge all the AutoTunnel records and the service records in
403847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// one update (they get deregistered a little apart)
403947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (info && info->deltime) rr->LastAPTime += (2 * MERGE_DELAY_TIME);
404047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else rr->LastAPTime += MERGE_DELAY_TIME;
404147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
404247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// IsRecordMergeable could have returned false for several reasons e.g., DontMerge is set or
404347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// no zone information. Most likely it is the latter, CheckRecordUpdates will fetch the zone
404447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// data when it encounters this record.
404547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
404647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
404747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
404847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
404947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mStatus_NoError;
405047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
405147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
405247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus uDNS_UpdateRecord(mDNS *m, AuthRecord *rr)
405347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
405447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("uDNS_UpdateRecord: Resource Record %##s, state %d", rr->resrec.name->c, rr->state);
405547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	switch(rr->state)
405647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
405747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_DeregPending:
405847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Unregistered:
405947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// not actively registered
406047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			goto unreg_error;
406147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
406247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NATMap:
406347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NoTarget:
406447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// change rdata directly since it hasn't been sent yet
406547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->resrec.rdata, rr->resrec.rdlength);
406647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
406747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->NewRData = mDNSNULL;
406847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return mStatus_NoError;
406947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
407047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Pending:
407147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Refresh:
407247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_UpdatePending:
407347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// registration in-flight. queue rdata and return
407447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->QueuedRData && rr->UpdateCallback)
407547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// if unsent rdata is already queued, free it before we replace it
407647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->UpdateCallback(m, rr, rr->QueuedRData, rr->QueuedRDLen);
407747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->QueuedRData = rr->NewRData;
407847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->QueuedRDLen = rr->newrdlength;
407947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->NewRData = mDNSNULL;
408047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return mStatus_NoError;
408147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
408247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_Registered:
408347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->OrigRData = rr->resrec.rdata;
408447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->OrigRDLen = rr->resrec.rdlength;
408547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->InFlightRData = rr->NewRData;
408647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->InFlightRDLen = rr->newrdlength;
408747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->NewRData = mDNSNULL;
408847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state = regState_UpdatePending;
408947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
409047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
409147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return mStatus_NoError;
409247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
409347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		case regState_NATError:
409447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMsg("ERROR: uDNS_UpdateRecord called for record %##s with bad state regState_NATError", rr->resrec.name->c);
409547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return mStatus_UnknownErr;	// states for service records only
409647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
409747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		default: LogMsg("uDNS_UpdateRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
409847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
409947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
410047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	unreg_error:
410147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogMsg("uDNS_UpdateRecord: Requested update of record %##s type %d, in erroneous state %d",
410247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		   rr->resrec.name->c, rr->resrec.rrtype, rr->state);
410347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mStatus_Invalid;
410447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
410547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
410647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
410747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
410847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - Periodic Execution Routines
410947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
411047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
411147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal const mDNSu8 *mDNS_WABLabels[] =
411247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
411347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(const mDNSu8 *)"\001b",
411447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(const mDNSu8 *)"\002db",
411547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(const mDNSu8 *)"\002lb",
411647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(const mDNSu8 *)"\001r",
411747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(const mDNSu8 *)"\002dr",
411847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(const mDNSu8 *)mDNSNULL,
411947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	};
412047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
412147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Returns true if it is a WAB question
412247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSBool WABQuestion(const domainname *qname)
412347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
412447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt 	const mDNSu8 *sd = (const mDNSu8 *)"\007_dns-sd";
412547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const mDNSu8 *prot = (const mDNSu8 *)"\004_udp";
412647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const domainname *d = qname;
412747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const mDNSu8 *label;
412847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int i = 0;
412947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
413047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We need at least 3 labels (WAB prefix) + one more label to make
413147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// a meaningful WAB query
413247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (CountLabels(qname) < 4) { debugf("WABQuestion: question %##s, not enough labels", qname->c); return mDNSfalse; }
413347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
413447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	label = (const mDNSu8 *)d;
413547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (mDNS_WABLabels[i] != (const mDNSu8 *)mDNSNULL)
413647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
413747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (SameDomainLabel(mDNS_WABLabels[i], label)) {debugf("WABquestion: WAB question %##s, label1 match", qname->c); break;}
413847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		i++;
413947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
414047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (mDNS_WABLabels[i] == (const mDNSu8 *)mDNSNULL)
414147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
414247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		debugf("WABquestion: Not a WAB question %##s, label1 mismatch", qname->c);
414347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		return mDNSfalse;
414447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
414547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// CountLabels already verified the number of labels
414647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	d = (const domainname *)(d->c + 1 + d->c[0]);	// Second Label
414747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	label = (const mDNSu8 *)d;
414847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!SameDomainLabel(label, sd)){ debugf("WABquestion: Not a WAB question %##s, label2 mismatch", qname->c);return(mDNSfalse); }
414947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("WABquestion: WAB question %##s, label2 match", qname->c);
415047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
415147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	d = (const domainname *)(d->c + 1 + d->c[0]); 	// Third Label
415247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	label = (const mDNSu8 *)d;
415347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!SameDomainLabel(label, prot)){ debugf("WABquestion: Not a WAB question %##s, label3 mismatch", qname->c);return(mDNSfalse); }
415447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	debugf("WABquestion: WAB question %##s, label3 match", qname->c);
415547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
415647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("WABquestion: Question %##s is a WAB question", qname->c);
415747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
415847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mDNStrue;
415947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
416047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
416147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// The question to be checked is not passed in as an explicit parameter;
416247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// instead it is implicit that the question to be checked is m->CurrentQuestion.
416347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void uDNS_CheckCurrentQuestion(mDNS *const m)
416447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
416547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSQuestion *q = m->CurrentQuestion;
416647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->timenow - NextQSendTime(q) < 0) return;
416747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
416847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (q->LongLived)
416947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
417047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		switch (q->state)
417147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
417247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			case LLQ_InitialRequest:   startLLQHandshake(m, q); break;
417347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			case LLQ_SecondaryRequest:
417447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt									   // For PrivateQueries, we need to start the handshake again as we don't do the Challenge/Response step
417547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt									   if (PrivateQuery(q))
417647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt										   startLLQHandshake(m, q);
417747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt									   else
417847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt									  	   sendChallengeResponse(m, q, mDNSNULL);
417947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt									   break;
418047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			case LLQ_Established:      sendLLQRefresh(m, q); break;
418147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			case LLQ_Poll:             break;	// Do nothing (handled below)
418247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
418347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
418447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
418547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// We repeat the check above (rather than just making this the "else" case) because startLLQHandshake can change q->state to LLQ_Poll
418647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!(q->LongLived && q->state != LLQ_Poll))
418747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
418847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->unansweredQueries >= MAX_UCAST_UNANSWERED_QUERIES)
418947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
419047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DNSServer *orig = q->qDNSServer;
419147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (orig)
419247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("uDNS_CheckCurrentQuestion: Sent %d unanswered queries for %##s (%s) to %#a:%d (%##s)",
419347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->unansweredQueries, q->qname.c, DNSTypeName(q->qtype), &orig->addr, mDNSVal16(orig->port), orig->domain.c);
419447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
419547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			PenalizeDNSServer(m, q);
419647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->noServerResponse = 1;
419747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
419847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// There are two cases here.
419947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//
420047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// 1. We have only one DNS server for this question. It is not responding even after we sent MAX_UCAST_UNANSWERED_QUERIES.
420147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    In that case, we need to keep retrying till we get a response. But we need to backoff as we retry. We set
420247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    noServerResponse in the block above and below we do not touch the question interval. When we come here, we
420347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    already waited for the response. We need to send another query right at this moment. We do that below by
420447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    reinitializing dns servers and reissuing the query.
420547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//
420647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// 2. We have more than one DNS server. If at least one server did not respond, we would have set noServerResponse
420747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    either now (the last server in the list) or before (non-last server in the list). In either case, if we have
420847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    reached the end of DNS server list, we need to try again from the beginning. Ideally we should try just the
420947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    servers that did not respond, but for simplicity we try all the servers. Once we reached the end of list, we
421047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		//    set triedAllServersOnce so that we don't try all the servers aggressively. See PenalizeDNSServer.
421147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!q->qDNSServer && q->noServerResponse)
421247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
421347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DNSServer *new;
421447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			DNSQuestion *qptr;
421547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->triedAllServersOnce = 1;
421647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Re-initialize all DNS servers for this question. If we have a DNSServer, DNSServerChangeForQuestion will
421747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// handle all the work including setting the new DNS server.
421847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			SetValidDNSServers(m, q);
421947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			new = GetServerForQuestion(m, q);
422047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (new)
422147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
422247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("uDNS_checkCurrentQuestion: Retrying question %p %##s (%s) DNS Server %#a:%d ThisQInterval %d",
422347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q, q->qname.c, DNSTypeName(q->qtype), new ? &new->addr : mDNSNULL, mDNSVal16(new ? new->port : zeroIPPort), q->ThisQInterval);
422447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				DNSServerChangeForQuestion(m, q, new);
422547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
422647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			for (qptr = q->next ; qptr; qptr = qptr->next)
422747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
422847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
422947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (q->qDNSServer && q->qDNSServer->teststate != DNSServer_Disabled)
423047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
423147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSu8 *end = m->omsg.data;
423247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mStatus err = mStatus_NoError;
423347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSBool private = mDNSfalse;
423447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
423547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
423647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
423747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q->qDNSServer->teststate != DNSServer_Untested || NoTestQuery(q))
423847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
423947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				end = putQuestion(&m->omsg, m->omsg.data, m->omsg.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
424047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				private = PrivateQuery(q);
424147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
424247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else if (m->timenow - q->qDNSServer->lasttest >= INIT_UCAST_POLL_INTERVAL)	// Make sure at least three seconds has elapsed since last test query
424347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
424447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("Sending DNS test query to %#a:%d", &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port));
424547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->ThisQInterval = INIT_UCAST_POLL_INTERVAL / QuestionIntervalStep;
424647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->qDNSServer->lasttest = m->timenow;
424747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				end = putQuestion(&m->omsg, m->omsg.data, m->omsg.data + AbsoluteMaxDNSMessageData, DNSRelayTestQuestion, kDNSType_PTR, kDNSClass_IN);
424847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->qDNSServer->testid = m->omsg.h.id;
424947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
425047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
425147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (end > m->omsg.data && (q->qDNSServer->teststate != DNSServer_Failed || NoTestQuery(q)))
425247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
425347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				//LogMsg("uDNS_CheckCurrentQuestion %p %d %p %##s (%s)", q, NextQSendTime(q) - m->timenow, private, q->qname.c, DNSTypeName(q->qtype));
425447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (private)
425547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
425647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->nta) CancelGetZoneData(m, q->nta);
425747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->nta = StartGetZoneData(m, &q->qname, q->LongLived ? ZoneServiceLLQ : ZoneServiceQuery, PrivateQueryGotZoneData, q);
425847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->state == LLQ_Poll) q->ThisQInterval = (LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10)) / QuestionIntervalStep;
425947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
426047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else
426147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
426247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				    debugf("uDNS_CheckCurrentQuestion sending %p %##s (%s) %#a:%d UnansweredQueries %d",
426347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				    	q, q->qname.c, DNSTypeName(q->qtype),
426447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				    	q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL, mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort), q->unansweredQueries);
426547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
426647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (!q->LocalSocket) err = mStatus_NoMemoryErr;	// If failed to make socket (should be very rare), we'll try again next time
426747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					else err = mDNSSendDNSMessage(m, &m->omsg, end, q->qDNSServer->interface, q->LocalSocket, &q->qDNSServer->addr, q->qDNSServer->port, mDNSNULL, mDNSNULL);
426847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
426947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
427047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
427147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (err) debugf("ERROR: uDNS_idle - mDNSSendDNSMessage - %d", err); // surpress syslog messages if we have no network
427247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
427347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
427447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;	// Only increase interval if send succeeded
427547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->unansweredQueries++;
427647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (q->ThisQInterval > MAX_UCAST_POLL_INTERVAL)
427747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
427847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (private && q->state != LLQ_Poll)
427947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
428047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// We don't want to retransmit too soon. Hence, we always schedule our first
428147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// retransmisson at 3 seconds rather than one second
428247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->ThisQInterval < (3 * mDNSPlatformOneSecond))
428347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;
428447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (q->ThisQInterval > LLQ_POLL_INTERVAL)
428547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->ThisQInterval = LLQ_POLL_INTERVAL;
428647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogInfo("uDNS_CheckCurrentQuestion: private non polling question for %##s (%s) will be retried in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
428747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
428847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				debugf("Increased ThisQInterval to %d for %##s (%s)", q->ThisQInterval, q->qname.c, DNSTypeName(q->qtype));
428947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
429047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->LastQTime = m->timenow;
429147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			SetNextQueryTime(m, q);
429247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
429347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else
429447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
429547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we have no server for this query, or the only server is a disabled one, then we deliver
429647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// a transient failure indication to the client. This is important for things like iPhone
429747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// where we want to return timely feedback to the user when no network is available.
429847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// After calling MakeNegativeCacheRecord() we store the resulting record in the
429947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// cache so that it will be visible to other clients asking the same question.
430047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// (When we have a group of identical questions, only the active representative of the group gets
430147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// passed to uDNS_CheckCurrentQuestion -- we only want one set of query packets hitting the wire --
430247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// but we want *all* of the questions to get answer callbacks.)
430347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
430447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			CacheRecord *rr;
430547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			const mDNSu32 slot = HashSlot(&q->qname);
430647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
430747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (cg)
430847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				for (rr = cg->members; rr; rr=rr->next)
430947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (SameNameRecordAnswersQuestion(&rr->resrec, q)) mDNS_PurgeCacheResourceRecord(m, rr);
431047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
431147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!q->qDNSServer)
431247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
431347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!mDNSOpaque64IsZero(&q->validDNSServers))
431447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("uDNS_CheckCurrentQuestion: ERROR!!: valid DNSServer bits not zero 0x%x, 0x%x for question %##s (%s)",
431547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->validDNSServers.l[1], q->validDNSServers.l[0], q->qname.c, DNSTypeName(q->qtype));
431647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// If we reached the end of list while picking DNS servers, then we don't want to deactivate the
431747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// question. Try after 60 seconds. We find this by looking for valid DNSServers for this question,
431847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// if we find any, then we must have tried them before we came here. This avoids maintaining
431947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// another state variable to see if we had valid DNS servers for this question.
432047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				SetValidDNSServers(m, q);
432147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (mDNSOpaque64IsZero(&q->validDNSServers))
432247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
432347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogInfo("uDNS_CheckCurrentQuestion: no DNS server for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
432447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->ThisQInterval = 0;
432547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
432647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else
432747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
432847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					DNSQuestion *qptr;
432947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Pretend that we sent this question. As this is an ActiveQuestion, the NextScheduledQuery should
433047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// be set properly. Also, we need to properly backoff in cases where we don't set the question to
433147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// MaxQuestionInterval when we answer the question e.g., LongLived, we need to keep backing off
433247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;
433347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->LastQTime = m->timenow;
433447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					SetNextQueryTime(m, q);
433547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Pick a new DNS server now. Otherwise, when the cache is 80% of its expiry, we will try
433647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// to send a query and come back to the same place here and log the above message.
433747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					q->qDNSServer = GetServerForQuestion(m, q);
433847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					for (qptr = q->next ; qptr; qptr = qptr->next)
433947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
434047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogInfo("uDNS_checkCurrentQuestion: Tried all DNS servers, retry question %p SuppressUnusable %d %##s (%s) with DNS Server %#a:%d after 60 seconds, ThisQInterval %d",
434147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q, q->SuppressUnusable, q->qname.c, DNSTypeName(q->qtype),
434247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL, mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort), q->ThisQInterval);
434347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
434447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
434547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
434647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
434747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				q->ThisQInterval = 0;
434847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogMsg("uDNS_CheckCurrentQuestion DNS server %#a:%d for %##s is disabled", &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qname.c);
434947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
435047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
435147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// For some of the WAB queries that we generate form within the mDNSResponder, most of the home routers
435247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// don't understand and return ServFail/NXDomain. In those cases, we don't want to try too often. We try
435347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// every fifteen minutes in that case
435447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, (WABQuestion(&q->qname) ? 60 * 15 : 60), mDNSInterface_Any, q->qDNSServer);
435547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			q->unansweredQueries = 0;
435647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We're already using the m->CurrentQuestion pointer, so CacheRecordAdd can't use it to walk the question list.
435747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// To solve this problem we set rr->DelayDelivery to a nonzero value (which happens to be 'now') so that we
435847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// momentarily defer generating answer callbacks until mDNS_Execute time.
435947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			CreateNewCacheEntry(m, slot, cg, NonZeroTime(m->timenow));
436047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			ScheduleNextCacheCheckTime(m, slot, NonZeroTime(m->timenow));
436147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
436247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// MUST NOT touch m->CurrentQuestion (or q) after this -- client callback could have deleted it
436347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
436447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
436547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
436647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
436747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void CheckNATMappings(mDNS *m)
436847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
436947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err = mStatus_NoError;
437047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool rfc1918 = mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4);
437147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSBool HaveRoutable = !rfc1918 && !mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4);
437247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->NextScheduledNATOp = m->timenow + 0x3FFFFFFF;
437347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
437447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (HaveRoutable) m->ExternalAddress = m->AdvertisedV4.ip.v4;
437547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
437647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->NATTraversals && rfc1918)			// Do we need to open NAT-PMP socket to receive multicast announcements from router?
437747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
437847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->NATMcastRecvskt == mDNSNULL)		// If we are behind a NAT and the socket hasn't been opened yet, open it
437947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
438047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// we need to log a message if we can't get our socket, but only the first time (after success)
438147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			static mDNSBool needLog = mDNStrue;
438247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->NATMcastRecvskt = mDNSPlatformUDPSocket(m, NATPMPAnnouncementPort);
438347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!m->NATMcastRecvskt)
438447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
438547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (needLog)
438647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
438747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("CheckNATMappings: Failed to allocate port 5350 UDP multicast socket for NAT-PMP announcements");
438847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					needLog = mDNSfalse;
438947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
439047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
439147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
439247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				needLog = mDNStrue;
439347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
439447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
439547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else										// else, we don't want to listen for announcements, so close them if they're open
439647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
439747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->NATMcastRecvskt) { mDNSPlatformUDPClose(m->NATMcastRecvskt); m->NATMcastRecvskt = mDNSNULL; }
439847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->SSDPSocket)      { debugf("CheckNATMappings destroying SSDPSocket %p", &m->SSDPSocket); mDNSPlatformUDPClose(m->SSDPSocket); m->SSDPSocket = mDNSNULL; }
439947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
440047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
440147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (!m->NATTraversals)
440247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->retryGetAddr = m->timenow + 0x78000000;
440347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
440447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
440547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->timenow - m->retryGetAddr >= 0)
440647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
440747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			err = uDNS_SendNATMsg(m, mDNSNULL);		// Will also do UPnP discovery for us, if necessary
440847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!err)
440947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
441047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if      (m->retryIntervalGetAddr < NATMAP_INIT_RETRY)             m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
441147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else if (m->retryIntervalGetAddr < NATMAP_MAX_RETRY_INTERVAL / 2) m->retryIntervalGetAddr *= 2;
441247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else                                                              m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
441347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
441447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("CheckNATMappings retryGetAddr sent address request err %d interval %d", err, m->retryIntervalGetAddr);
441547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
441647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Always update m->retryGetAddr, even if we fail to send the packet. Otherwise in cases where we can't send the packet
441747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// (like when we have no active interfaces) we'll spin in an infinite loop repeatedly failing to send the packet
441847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
441947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
442047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Even when we didn't send the GetAddr packet, still need to make sure NextScheduledNATOp is set correctly
442147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->NextScheduledNATOp - m->retryGetAddr > 0)
442247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->NextScheduledNATOp = m->retryGetAddr;
442347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
442447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
442547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->CurrentNATTraversal) LogMsg("WARNING m->CurrentNATTraversal already in use");
442647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->CurrentNATTraversal = m->NATTraversals;
442747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
442847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (m->CurrentNATTraversal)
442947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
443047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		NATTraversalInfo *cur = m->CurrentNATTraversal;
443147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->CurrentNATTraversal = m->CurrentNATTraversal->next;
443247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
443347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (HaveRoutable)		// If not RFC 1918 address, our own address and port are effectively our external address and port
443447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
443547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			cur->ExpiryTime = 0;
443647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			cur->NewResult  = mStatus_NoError;
443747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
443847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		else if (cur->Protocol)		// Check if it's time to send port mapping packets
443947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
444047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (m->timenow - cur->retryPortMap >= 0)						// Time to do something with this mapping
444147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
444247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (cur->ExpiryTime && cur->ExpiryTime - m->timenow < 0)	// Mapping has expired
444347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
444447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->ExpiryTime    = 0;
444547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->retryInterval = NATMAP_INIT_RETRY;
444647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
444747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
444847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				//LogMsg("uDNS_SendNATMsg");
444947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err = uDNS_SendNATMsg(m, cur);
445047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
445147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (cur->ExpiryTime)						// If have active mapping then set next renewal time halfway to expiry
445247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					NATSetNextRenewalTime(m, cur);
445347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else										// else no mapping; use exponential backoff sequence
445447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
445547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if      (cur->retryInterval < NATMAP_INIT_RETRY            ) cur->retryInterval = NATMAP_INIT_RETRY;
445647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					else if (cur->retryInterval < NATMAP_MAX_RETRY_INTERVAL / 2) cur->retryInterval *= 2;
445747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					else                                                         cur->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
445847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->retryPortMap = m->timenow + cur->retryInterval;
445947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
446047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
446147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
446247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (m->NextScheduledNATOp - cur->retryPortMap > 0)
446347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				m->NextScheduledNATOp = cur->retryPortMap;
446447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
446547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
446647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Notify the client if necessary. We invoke the callback if:
446747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// (1) we have an ExternalAddress, or we've tried and failed a couple of times to discover it
446847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// 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
446947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// and (3) we have new data to give the client that's changed since the last callback
447047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Time line is: Send, Wait 500ms, Send, Wait 1sec, Send, Wait 2sec, Send
447147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// At this point we've sent three requests without an answer, we've just sent our fourth request,
447247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// retryIntervalGetAddr is now 4 seconds, which is greater than NATMAP_INIT_RETRY * 8 (2 seconds),
447347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// so we return an error result to the caller.
447447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!mDNSIPv4AddressIsZero(m->ExternalAddress) || m->retryIntervalGetAddr > NATMAP_INIT_RETRY * 8)
447547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
447647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			const mStatus EffectiveResult = cur->NewResult ? cur->NewResult : mDNSv4AddrIsRFC1918(&m->ExternalAddress) ? mStatus_DoubleNAT : mStatus_NoError;
447747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			const mDNSIPPort ExternalPort = HaveRoutable ? cur->IntPort :
447847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				!mDNSIPv4AddressIsZero(m->ExternalAddress) && cur->ExpiryTime ? cur->RequestedPort : zeroIPPort;
447947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!cur->Protocol || HaveRoutable || cur->ExpiryTime || cur->retryInterval > NATMAP_INIT_RETRY * 8)
448047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!mDNSSameIPv4Address(cur->ExternalAddress, m->ExternalAddress) ||
448147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					!mDNSSameIPPort     (cur->ExternalPort,       ExternalPort)    ||
448247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->Result != EffectiveResult)
448347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
448447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//LogMsg("NAT callback %d %d %d", cur->Protocol, cur->ExpiryTime, cur->retryInterval);
448547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (cur->Protocol && mDNSIPPortIsZero(ExternalPort) && !mDNSIPv4AddressIsZero(m->Router.ip.v4))
448647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						{
448747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						if (!EffectiveResult)
448847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							LogInfo("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
448947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt								cur, &m->Router, &m->ExternalAddress, mDNSVal16(cur->IntPort), cur->retryInterval, EffectiveResult);
449047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						else
449147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt							LogMsg("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
449247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt								cur, &m->Router, &m->ExternalAddress, mDNSVal16(cur->IntPort), cur->retryInterval, EffectiveResult);
449347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						}
449447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
449547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->ExternalAddress = m->ExternalAddress;
449647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->ExternalPort    = ExternalPort;
449747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->Lifetime        = cur->ExpiryTime && !mDNSIPPortIsZero(ExternalPort) ?
449847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						(cur->ExpiryTime - m->timenow + mDNSPlatformOneSecond/2) / mDNSPlatformOneSecond : 0;
449947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					cur->Result          = EffectiveResult;
450047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					mDNS_DropLockBeforeCallback();		// Allow client to legally make mDNS API calls from the callback
450147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (cur->clientCallback)
450247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						cur->clientCallback(m, cur);
450347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					mDNS_ReclaimLockAfterCallback();	// Decrement mDNS_reentrancy to block mDNS API calls again
450447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// MUST NOT touch cur after invoking the callback
450547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
450647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
450747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
450847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
450947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
451047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal mDNSs32 CheckRecordUpdates(mDNS *m)
451147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
451247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *rr;
451347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSs32 nextevent = m->timenow + 0x3FFFFFFF;
451447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
451547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	CheckGroupRecordUpdates(m);
451647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
451747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (rr = m->ResourceRecords; rr; rr = rr->next)
451847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
451947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!AuthRecord_uDNS(rr)) continue;
452047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->state == regState_NoTarget) {debugf("CheckRecordUpdates: Record %##s in NoTarget", rr->resrec.name->c); continue;}
452147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// While we are waiting for the port mapping, we have nothing to do. The port mapping callback
452247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// will take care of this
452347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->state == regState_NATMap) {debugf("CheckRecordUpdates: Record %##s in NATMap", rr->resrec.name->c); continue;}
452447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (rr->state == regState_Pending || rr->state == regState_DeregPending || rr->state == regState_UpdatePending ||
452547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			rr->state == regState_Refresh || rr->state == regState_Registered)
452647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
452747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->LastAPTime + rr->ThisAPInterval - m->timenow <= 0)
452847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
452947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
453047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
453147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					{
453247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// Zero out the updateid so that if we have a pending response from the server, it won't
453347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// be accepted as a valid response. If we accept the response, we might free the new "nta"
453447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
453547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
453647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
453747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// We have just started the GetZoneData. We need to wait for it to finish. SetRecordRetry here
453847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// schedules the update timer to fire in the future.
453947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//
454047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// There are three cases.
454147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//
454247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// 1) When the updates are sent the first time, the first retry is intended to be at three seconds
454347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//    in the future. But by calling SetRecordRetry here we set it to nine seconds. But it does not
454447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//    matter because when the answer comes back, RecordRegistrationGotZoneData resets the interval
454547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//    back to INIT_RECORD_REG_INTERVAL. This also gives enough time for the query.
454647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//
454747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// 2) In the case of update errors (updateError), this causes further backoff as
454847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//    RecordRegistrationGotZoneData does not reset the timer. This is intentional as in the case of
454947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//    errors, we don't want to update aggressively.
455047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//
455147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					// 3) We might be refreshing the update. This is very similar to case (1). RecordRegistrationGotZoneData
455247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//    resets it back to INIT_RECORD_REG_INTERVAL.
455347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					//
455447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					SetRecordRetry(m, rr, 0);
455547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					}
455647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else if (rr->state == regState_DeregPending) SendRecordDeregistration(m, rr);
455747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				else SendRecordRegistration(m, rr);
455847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
455947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
456047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (nextevent - (rr->LastAPTime + rr->ThisAPInterval) > 0)
456147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			nextevent = (rr->LastAPTime + rr->ThisAPInterval);
456247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
456347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return nextevent;
456447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
456547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
456647e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void uDNS_Tasks(mDNS *const m)
456747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
456847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSs32 nexte;
456947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSServer *d;
457047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
457147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->NextuDNSEvent = m->timenow + 0x3FFFFFFF;
457247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
457347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	nexte = CheckRecordUpdates(m);
457447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->NextuDNSEvent - nexte > 0)
457547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->NextuDNSEvent = nexte;
457647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
457747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (d = m->DNSServers; d; d=d->next)
457847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (d->penaltyTime)
457947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
458047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (m->timenow - d->penaltyTime >= 0)
458147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
458247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("DNS server %#a:%d out of penalty box", &d->addr, mDNSVal16(d->port));
458347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				d->penaltyTime = 0;
458447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
458547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
458647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (m->NextuDNSEvent - d->penaltyTime > 0)
458747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					m->NextuDNSEvent = d->penaltyTime;
458847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
458947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
459047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (m->CurrentQuestion)
459147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogMsg("uDNS_Tasks ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
459247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->CurrentQuestion = m->Questions;
459347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
459447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
459547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		DNSQuestion *const q = m->CurrentQuestion;
459647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID))
459747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
459847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			uDNS_CheckCurrentQuestion(m);
459947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (q == m->CurrentQuestion)
460047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (m->NextuDNSEvent - NextQSendTime(q) > 0)
460147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					m->NextuDNSEvent = NextQSendTime(q);
460247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
460347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// If m->CurrentQuestion wasn't modified out from under us, advance it now
460447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// We can't do this at the start of the loop because uDNS_CheckCurrentQuestion()
460547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// depends on having m->CurrentQuestion point to the right question
460647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (m->CurrentQuestion == q)
460747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			m->CurrentQuestion = q->next;
460847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
460947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	m->CurrentQuestion = mDNSNULL;
461047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
461147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
461247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// ***************************************************************************
461347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if COMPILER_LIKES_PRAGMA_MARK
461447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#pragma mark - Startup, Shutdown, and Sleep
461547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
461647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
461747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void SleepRecordRegistrations(mDNS *m)
461847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
461947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	AuthRecord *rr;
462047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (rr = m->ResourceRecords; rr; rr=rr->next)
462147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
462247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (AuthRecord_uDNS(rr))
462347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
462447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Zero out the updateid so that if we have a pending response from the server, it won't
462547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// be accepted as a valid response.
462647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
462747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
462847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->NATinfo.clientContext)
462947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
463047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_StopNATOperation_internal(m, &rr->NATinfo);
463147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->NATinfo.clientContext = mDNSNULL;
463247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
463347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We are waiting to update the resource record. The original data of the record is
463447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// in OrigRData and the updated value is in InFlightRData. Free the old and the new
463547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// one will be registered when we come back.
463647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (rr->state == regState_UpdatePending)
463747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
463847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// act as if the update succeeded, since we're about to delete the name anyway
463947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->state = regState_Registered;
464047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// deallocate old RData
464147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->OrigRData, rr->OrigRDLen);
464247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
464347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->OrigRData = mDNSNULL;
464447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				rr->InFlightRData = mDNSNULL;
464547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
464647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
464747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If we have not begun the registration process i.e., never sent a registration packet,
464847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// then uDNS_DeregisterRecord will not send a deregistration
464947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			uDNS_DeregisterRecord(m, rr);
465047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
465147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// When we wake, we call ActivateUnicastRegistration which starts at StartGetZoneData
465247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
465347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
465447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
465547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
465647e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void mDNS_AddSearchDomain(const domainname *const domain, mDNSInterfaceID InterfaceID)
465747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
465847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SearchListElem **p;
465947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SearchListElem *tmp = mDNSNULL;
466047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
466147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Check to see if we already have this domain in our list
466247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (p = &SearchList; *p; p = &(*p)->next)
466347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (((*p)->InterfaceID == InterfaceID) && SameDomainName(&(*p)->domain, domain))
466447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
466547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If domain is already in list, and marked for deletion, unmark the delete
466647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Be careful not to touch the other flags that may be present
466747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("mDNS_AddSearchDomain already in list %##s", domain->c);
466847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if ((*p)->flag & SLE_DELETE) (*p)->flag &= ~SLE_DELETE;
466947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tmp = *p;
467047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			*p = tmp->next;
467147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			tmp->next = mDNSNULL;
467247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			break;
467347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
467447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
467547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
467647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// move to end of list so that we maintain the same order
467747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*p) p = &(*p)->next;
467847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
467947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (tmp) *p = tmp;
468047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
468147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
468247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// if domain not in list, add to list, mark as add (1)
468347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		*p = mDNSPlatformMemAllocate(sizeof(SearchListElem));
468447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!*p) { LogMsg("ERROR: mDNS_AddSearchDomain - malloc"); return; }
468547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNSPlatformMemZero(*p, sizeof(SearchListElem));
468647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&(*p)->domain, domain);
468747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		(*p)->next = mDNSNULL;
468847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		(*p)->InterfaceID = InterfaceID;
468947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("mDNS_AddSearchDomain created new %##s, InterfaceID %p", domain->c, InterfaceID);
469047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
469147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
469247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
469347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
469447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
469547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void)m;	// unused
469647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (result == mStatus_MemFree) mDNSPlatformMemFree(rr->RecordContext);
469747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
469847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
469947e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void FoundDomain(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
470047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
470147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SearchListElem *slElem = question->QuestionContext;
470247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err;
470347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	const char *name;
470447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
470547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (answer->rrtype != kDNSType_PTR) return;
470647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (answer->RecordType == kDNSRecordTypePacketNegative) return;
470747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (answer->InterfaceID == mDNSInterface_LocalOnly) return;
470847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
470947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if      (question == &slElem->BrowseQ)          name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowse];
471047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (question == &slElem->DefBrowseQ)       name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowseDefault];
471147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (question == &slElem->AutomaticBrowseQ) name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowseAutomatic];
471247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (question == &slElem->RegisterQ)        name = mDNS_DomainTypeNames[mDNS_DomainTypeRegistration];
471347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else if (question == &slElem->DefRegisterQ)     name = mDNS_DomainTypeNames[mDNS_DomainTypeRegistrationDefault];
471447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else { LogMsg("FoundDomain - unknown question"); return; }
471547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
471647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("FoundDomain: %p %s %s Q %##s A %s", answer->InterfaceID, AddRecord ? "Add" : "Rmv", name, question->qname.c, RRDisplayString(m, answer));
471747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
471847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (AddRecord)
471947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
472047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ARListElem *arElem = mDNSPlatformMemAllocate(sizeof(ARListElem));
472147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (!arElem) { LogMsg("ERROR: FoundDomain out of memory"); return; }
472247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		mDNS_SetupResourceRecord(&arElem->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, arElem);
472347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		MakeDomainNameFromDNSNameString(&arElem->ar.namestorage, name);
472447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AppendDNSNameString            (&arElem->ar.namestorage, "local");
472547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		AssignDomainName(&arElem->ar.resrec.rdata->u.name, &answer->rdata->u.name);
472647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("FoundDomain: Registering %s", ARDisplayString(m, &arElem->ar));
472747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		err = mDNS_Register(m, &arElem->ar);
472847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (err) { LogMsg("ERROR: FoundDomain - mDNS_Register returned %d", err); mDNSPlatformMemFree(arElem); return; }
472947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		arElem->next = slElem->AuthRecs;
473047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		slElem->AuthRecs = arElem;
473147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
473247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	else
473347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
473447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ARListElem **ptr = &slElem->AuthRecs;
473547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		while (*ptr)
473647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
473747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, &answer->rdata->u.name))
473847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
473947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				ARListElem *dereg = *ptr;
474047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				*ptr = (*ptr)->next;
474147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("FoundDomain: Deregistering %s", ARDisplayString(m, &dereg->ar));
474247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err = mDNS_Deregister(m, &dereg->ar);
474347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (err) LogMsg("ERROR: FoundDomain - mDNS_Deregister returned %d", err);
474447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// Memory will be freed in the FreeARElemCallback
474547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
474647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			else
474747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				ptr = &(*ptr)->next;
474847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
474947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
475047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
475147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
475247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
475347e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void udns_validatelists(void *const v)
475447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
475547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS *const m = v;
475647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
475747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	NATTraversalInfo *n;
475847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (n = m->NATTraversals; n; n=n->next)
475947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (n->next == (NATTraversalInfo *)~0 || n->clientCallback == (NATTraversalClientCallback)~0)
476047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMemCorruption("m->NATTraversals: %p is garbage", n);
476147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
476247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DNSServer *d;
476347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (d = m->DNSServers; d; d=d->next)
476447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (d->next == (DNSServer *)~0 || d->teststate > DNSServer_Disabled)
476547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMemCorruption("m->DNSServers: %p is garbage (%d)", d, d->teststate);
476647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
476747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	DomainAuthInfo *info;
476847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (info = m->AuthInfoList; info; info = info->next)
476947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (info->next == (DomainAuthInfo *)~0 || info->AutoTunnel == (const char*)~0)
477047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMemCorruption("m->AuthInfoList: %p is garbage (%X)", info, info->AutoTunnel);
477147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
477247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	HostnameInfo *hi;
477347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (hi = m->Hostnames; hi; hi = hi->next)
477447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (hi->next == (HostnameInfo *)~0 || hi->StatusCallback == (mDNSRecordCallback*)~0)
477547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMemCorruption("m->Hostnames: %p is garbage", n);
477647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
477747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SearchListElem *ptr;
477847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (ptr = SearchList; ptr; ptr = ptr->next)
477947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (ptr->next == (SearchListElem *)~0 || ptr->AuthRecs == (void*)~0)
478047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogMemCorruption("SearchList: %p is garbage (%X)", ptr, ptr->AuthRecs);
478147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
478247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt#endif
478347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
478447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// This should probably move to the UDS daemon -- the concept of legacy clients and automatic registration / automatic browsing
478547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// is really a UDS API issue, not something intrinsic to uDNS
478647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
478747e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport mStatus uDNS_SetupSearchDomains(mDNS *const m, int action)
478847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
478947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SearchListElem **p = &SearchList, *ptr;
479047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mStatus err;
479147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
479247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// step 1: mark each element for removal
479347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (ptr = SearchList; ptr; ptr = ptr->next) ptr->flag |= SLE_DELETE;
479447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
479547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Make sure we have the search domains from the platform layer so that if we start the WAB
479647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// queries below, we have the latest information
479747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Lock(m);
479847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNStrue, mDNSNULL, mDNSNULL, mDNSNULL);
479947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNS_Unlock(m);
480047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
480147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (action & UDNS_START_WAB_QUERY)
480247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		m->StartWABQueries = mDNStrue;
480347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
480447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// delete elems marked for removal, do queries for elems marked add
480547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (*p)
480647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
480747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		ptr = *p;
480847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("uDNS_SetupSearchDomains:action %d: Flags %d,  AuthRecs %p, InterfaceID %p %##s", action, ptr->flag, ptr->AuthRecs, ptr->InterfaceID, ptr->domain.c);
480947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (ptr->flag & SLE_DELETE)
481047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
481147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			ARListElem *arList = ptr->AuthRecs;
481247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			ptr->AuthRecs = mDNSNULL;
481347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			*p = ptr->next;
481447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
481547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries
481647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// We suppressed the domain enumeration for scoped search domains below. When we enable that
481747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// enable this.
481847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if ((ptr->flag & SLE_WAB_QUERY_STARTED) &&
481947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				!SameDomainName(&ptr->domain, &localdomain) && (ptr->InterfaceID == mDNSInterface_Any))
482047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
482147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_StopGetDomains(m, &ptr->BrowseQ);
482247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_StopGetDomains(m, &ptr->RegisterQ);
482347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_StopGetDomains(m, &ptr->DefBrowseQ);
482447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_StopGetDomains(m, &ptr->DefRegisterQ);
482547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mDNS_StopGetDomains(m, &ptr->AutomaticBrowseQ);
482647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
482747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
482847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNSPlatformMemFree(ptr);
482947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
483047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	        // deregister records generated from answers to the query
483147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			while (arList)
483247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
483347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				ARListElem *dereg = arList;
483447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				arList = arList->next;
483547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				debugf("Deregistering PTR %##s -> %##s", dereg->ar.resrec.name->c, dereg->ar.resrec.rdata->u.name.c);
483647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err = mDNS_Deregister(m, &dereg->ar);
483747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (err) LogMsg("uDNS_SetupSearchDomains:: ERROR!! mDNS_Deregister returned %d", err);
483847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				// Memory will be freed in the FreeARElemCallback
483947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
484047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			continue;
484147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
484247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
484347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if ((action & UDNS_START_WAB_QUERY) && !(ptr->flag & SLE_WAB_QUERY_STARTED))
484447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
484547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries.
484647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			// Also, suppress the domain enumeration for scoped search domains for now until there is a need.
484747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (!SameDomainName(&ptr->domain, &localdomain) && (ptr->InterfaceID == mDNSInterface_Any))
484847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
484947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				mStatus err1, err2, err3, err4, err5;
485047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err1 = mDNS_GetDomains(m, &ptr->BrowseQ,          mDNS_DomainTypeBrowse,              &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
485147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err2 = mDNS_GetDomains(m, &ptr->DefBrowseQ,       mDNS_DomainTypeBrowseDefault,       &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
485247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err3 = mDNS_GetDomains(m, &ptr->RegisterQ,        mDNS_DomainTypeRegistration,        &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
485347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err4 = mDNS_GetDomains(m, &ptr->DefRegisterQ,     mDNS_DomainTypeRegistrationDefault, &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
485447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				err5 = mDNS_GetDomains(m, &ptr->AutomaticBrowseQ, mDNS_DomainTypeBrowseAutomatic,     &ptr->domain, ptr->InterfaceID, FoundDomain, ptr);
485547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				if (err1 || err2 || err3 || err4 || err5)
485647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt					LogMsg("uDNS_SetupSearchDomains: GetDomains for domain %##s returned error(s):\n"
485747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						   "%d (mDNS_DomainTypeBrowse)\n"
485847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						   "%d (mDNS_DomainTypeBrowseDefault)\n"
485947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						   "%d (mDNS_DomainTypeRegistration)\n"
486047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						   "%d (mDNS_DomainTypeRegistrationDefault)"
486147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						   "%d (mDNS_DomainTypeBrowseAutomatic)\n",
486247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt						   ptr->domain.c, err1, err2, err3, err4, err5);
486347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				ptr->flag |= SLE_WAB_QUERY_STARTED;
486447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
486547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
486647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
486747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		p = &ptr->next;
486847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
486947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mStatus_NoError;
487047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
487147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
487247e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport domainname  *uDNS_GetNextSearchDomain(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSs8 *searchIndex, mDNSBool ignoreDotLocal)
487347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
487447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	SearchListElem *p = SearchList;
487547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	int count = *searchIndex;
487647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	(void) m; // unused
487747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
487847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	if (count < 0) { LogMsg("uDNS_GetNextSearchDomain: count %d less than zero", count); return mDNSNULL; }
487947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
488047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// skip the  domains that we already looked at before
488147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	for (; count; count--) p = p->next;
488247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
488347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	while (p)
488447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
488547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		int labels = CountLabels(&p->domain);
488647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (labels > 0)
488747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
488847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			const domainname *d = SkipLeadingLabels(&p->domain, labels - 1);
488947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (SameDomainLabel(d->c, (const mDNSu8 *)"\x4""arpa"))
489047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
489147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("uDNS_GetNextSearchDomain: skipping search domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
489247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				(*searchIndex)++;
489347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				p = p->next;
489447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				continue;
489547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
489647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			if (ignoreDotLocal && SameDomainLabel(d->c, (const mDNSu8 *)"\x5""local"))
489747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				{
489847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				LogInfo("uDNS_GetNextSearchDomain: skipping local domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
489947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				(*searchIndex)++;
490047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				p = p->next;
490147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				continue;
490247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt				}
490347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
490447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// Point to the next one in the list which we will look at next time.
490547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		(*searchIndex)++;
490647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// When we are appending search domains in a ActiveDirectory domain, the question's InterfaceID
490747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// set to mDNSInterface_Unicast. Match the unscoped entries in that case.
490847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (((InterfaceID == mDNSInterface_Unicast) && (p->InterfaceID == mDNSInterface_Any)) ||
490947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			p->InterfaceID == InterfaceID)
491047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
491147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("uDNS_GetNextSearchDomain returning domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
491247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			return &p->domain;
491347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
491447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		LogInfo("uDNS_GetNextSearchDomain skipping domain %##s, InterfaceID %p", p->domain.c, p->InterfaceID);
491547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		p = p->next;
491647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
491747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	return mDNSNULL;
491847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
491947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
492047e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSlocal void FlushAddressCacheRecords(mDNS *const m)
492147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
492247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSu32 slot;
492347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	CacheGroup *cg;
492447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	CacheRecord *cr;
492547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	FORALL_CACHERECORDS(slot, cg, cr)
492647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		{
492747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (cr->resrec.InterfaceID) continue;
492847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
492947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// If a resource record can answer A or AAAA, they need to be flushed so that we will
493047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		// never used to deliver an ADD or RMV
493147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		if (RRTypeAnswersQuestionType(&cr->resrec, kDNSType_A) ||
493247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			RRTypeAnswersQuestionType(&cr->resrec, kDNSType_AAAA))
493347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			{
493447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			LogInfo("FlushAddressCacheRecords: Purging Resourcerecord %s", CRDisplayString(m, cr));
493547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			mDNS_PurgeCacheResourceRecord(m, cr);
493647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt			}
493747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt		}
493847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
493947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
494047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Retry questions which has seach domains appended
494147e4cebad7397422144bb03a21f3f7682c062c4aRobert GreenwaltmDNSexport void RetrySearchDomainQuestions(mDNS *const m)
494247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
494347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Purge all the A/AAAA cache records and restart the queries. mDNSCoreRestartAddressQueries
494447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// does this. When we restart the question,  we first want to try the new search domains rather
494547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// than use the entries that is already in the cache. When we appended search domains, we might
494647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// have created cache entries which is no longer valid as there are new search domains now
494747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
494847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	LogInfo("RetrySearchDomainQuestions: Calling mDNSCoreRestartAddressQueries");
494947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	mDNSCoreRestartAddressQueries(m, mDNStrue, FlushAddressCacheRecords, mDNSNULL, mDNSNULL);
495047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	}
495147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
495247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// Construction of Default Browse domain list (i.e. when clients pass NULL) is as follows:
495347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 1) query for b._dns-sd._udp.local on LocalOnly interface
495447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    (.local manually generated via explicit callback)
495547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 2) for each search domain (from prefs pane), query for b._dns-sd._udp.<searchdomain>.
495647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 3) for each result from (2), register LocalOnly PTR record b._dns-sd._udp.local. -> <result>
495747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 4) result above should generate a callback from question in (1).  result added to global list
495847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 5) global list delivered to client via GetSearchDomainList()
495947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt// 6) client calls to enumerate domains now go over LocalOnly interface
496047e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt//    (!!!KRS may add outgoing interface in addition)
496147e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt
496247e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwaltstruct CompileTimeAssertionChecks_uDNS
496347e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	{
496447e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// Check our structures are reasonable sizes. Including overly-large buffers, or embedding
496547e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// other overly-large structures instead of having a pointer to them, can inadvertently
496647e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	// cause structure sizes (and therefore memory usage) to balloon unreasonably.
496747e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	char sizecheck_tcpInfo_t     [(sizeof(tcpInfo_t)      <=  9056) ? 1 : -1];
496847e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	char sizecheck_SearchListElem[(sizeof(SearchListElem) <=  5000) ? 1 : -1];
496947e4cebad7397422144bb03a21f3f7682c062c4aRobert Greenwalt	};
4970