Home | History | Annotate | Download | only in mDNSCore
      1 /* -*- Mode: C; tab-width: 4 -*-
      2  *
      3  * Copyright (c) 2002-2006 Apple Computer, Inc. All rights reserved.
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16 
     17  * To Do:
     18  * Elimate all mDNSPlatformMemAllocate/mDNSPlatformMemFree from this code -- the core code
     19  * is supposed to be malloc-free so that it runs in constant memory determined at compile-time.
     20  * Any dynamic run-time requirements should be handled by the platform layer below or client layer above
     21  */
     22 
     23 #if APPLE_OSX_mDNSResponder
     24 #include <TargetConditionals.h>
     25 #endif
     26 #include "uDNS.h"
     27 
     28 #if(defined(_MSC_VER))
     29 	// Disable "assignment within conditional expression".
     30 	// Other compilers understand the convention that if you place the assignment expression within an extra pair
     31 	// of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
     32 	// The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
     33 	// to the compiler that the assignment is intentional, we have to just turn this warning off completely.
     34 	#pragma warning(disable:4706)
     35 #endif
     36 
     37 // For domain enumeration and automatic browsing
     38 // This is the user's DNS search list.
     39 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
     40 // to discover recommended domains for domain enumeration (browse, default browse, registration,
     41 // default registration) and possibly one or more recommended automatic browsing domains.
     42 mDNSexport SearchListElem *SearchList = mDNSNULL;
     43 
     44 // The value can be set to true by the Platform code e.g., MacOSX uses the plist mechanism
     45 mDNSBool StrictUnicastOrdering = mDNSfalse;
     46 
     47 // We keep track of the number of unicast DNS servers and log a message when we exceed 64.
     48 // Currently the unicast queries maintain a 64 bit map to track the valid DNS servers for that
     49 // question. Bit position is the index into the DNS server list. This is done so to try all
     50 // the servers exactly once before giving up. If we could allocate memory in the core, then
     51 // arbitrary limitation of 64 DNSServers can be removed.
     52 mDNSu8 NumUnicastDNSServers = 0;
     53 #define MAX_UNICAST_DNS_SERVERS	64
     54 
     55 // ***************************************************************************
     56 #if COMPILER_LIKES_PRAGMA_MARK
     57 #pragma mark - General Utility Functions
     58 #endif
     59 
     60 // set retry timestamp for record with exponential backoff
     61 mDNSlocal void SetRecordRetry(mDNS *const m, AuthRecord *rr, mDNSu32 random)
     62 	{
     63 	rr->LastAPTime = m->timenow;
     64 
     65 	if (rr->expire && rr->refreshCount < MAX_UPDATE_REFRESH_COUNT)
     66 		{
     67 		mDNSs32 remaining = rr->expire - m->timenow;
     68 		rr->refreshCount++;
     69 		if (remaining > MIN_UPDATE_REFRESH_TIME)
     70 			{
     71 			// Refresh at 70% + random (currently it is 0 to 10%)
     72 			rr->ThisAPInterval =  7 * (remaining/10) + (random ? random : mDNSRandom(remaining/10));
     73 			// Don't update more often than 5 minutes
     74 			if (rr->ThisAPInterval < MIN_UPDATE_REFRESH_TIME)
     75 				rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
     76 			LogInfo("SetRecordRetry refresh in %d of %d for %s",
     77 				rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
     78 			}
     79 		else
     80 			{
     81 			rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
     82 			LogInfo("SetRecordRetry clamping to min refresh in %d of %d for %s",
     83 				rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
     84 			}
     85 		return;
     86 		}
     87 
     88 	rr->expire = 0;
     89 
     90 	rr->ThisAPInterval = rr->ThisAPInterval * QuestionIntervalStep;	// Same Retry logic as Unicast Queries
     91 	if (rr->ThisAPInterval < INIT_RECORD_REG_INTERVAL)
     92 		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
     93 	if (rr->ThisAPInterval > MAX_RECORD_REG_INTERVAL)
     94 		rr->ThisAPInterval = MAX_RECORD_REG_INTERVAL;
     95 
     96 	LogInfo("SetRecordRetry retry in %d ms for %s", rr->ThisAPInterval, ARDisplayString(m, rr));
     97 	}
     98 
     99 // ***************************************************************************
    100 #if COMPILER_LIKES_PRAGMA_MARK
    101 #pragma mark - Name Server List Management
    102 #endif
    103 
    104 mDNSexport DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, const mDNSAddr *addr, const mDNSIPPort port, mDNSBool scoped, mDNSu32 timeout)
    105 	{
    106 	DNSServer **p = &m->DNSServers;
    107 	DNSServer *tmp = mDNSNULL;
    108 
    109 	if ((NumUnicastDNSServers + 1) > MAX_UNICAST_DNS_SERVERS)
    110 		{
    111 		LogMsg("mDNS_AddDNSServer: DNS server limit of %d reached, not adding this server", MAX_UNICAST_DNS_SERVERS);
    112 		return mDNSNULL;
    113 		}
    114 
    115 	if (!d) d = (const domainname *)"";
    116 
    117 	LogInfo("mDNS_AddDNSServer: Adding %#a for %##s, InterfaceID %p, scoped %d", addr, d->c, interface, scoped);
    118 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
    119 		LogMsg("mDNS_AddDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
    120 
    121 	while (*p)	// Check if we already have this {interface,address,port,domain} tuple registered
    122 		{
    123 		if ((*p)->scoped == scoped && (*p)->interface == interface && (*p)->teststate != DNSServer_Disabled &&
    124 			mDNSSameAddress(&(*p)->addr, addr) && mDNSSameIPPort((*p)->port, port) && SameDomainName(&(*p)->domain, d))
    125 			{
    126 			if (!((*p)->flags & DNSServer_FlagDelete)) debugf("Note: DNS Server %#a:%d for domain %##s (%p) registered more than once", addr, mDNSVal16(port), d->c, interface);
    127 			(*p)->flags &= ~DNSServer_FlagDelete;
    128 			tmp = *p;
    129 			*p = tmp->next;
    130 			tmp->next = mDNSNULL;
    131 			}
    132 		else
    133 			p=&(*p)->next;
    134 		}
    135 
    136 	if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
    137 	else
    138 		{
    139 		// allocate, add to list
    140 		*p = mDNSPlatformMemAllocate(sizeof(**p));
    141 		if (!*p) LogMsg("Error: mDNS_AddDNSServer - malloc");
    142 		else
    143 			{
    144 			NumUnicastDNSServers++;
    145 			(*p)->scoped	= scoped;
    146 			(*p)->interface = interface;
    147 			(*p)->addr      = *addr;
    148 			(*p)->port      = port;
    149 			(*p)->flags     = DNSServer_FlagNew;
    150 			(*p)->teststate = /* DNSServer_Untested */ DNSServer_Passed;
    151 			(*p)->lasttest  = m->timenow - INIT_UCAST_POLL_INTERVAL;
    152 			(*p)->timeout   = timeout;
    153 			AssignDomainName(&(*p)->domain, d);
    154 			(*p)->next = mDNSNULL;
    155 			}
    156 		}
    157 	(*p)->penaltyTime = 0;
    158 	return(*p);
    159 	}
    160 
    161 // PenalizeDNSServer is called when the number of queries to the unicast
    162 // DNS server exceeds MAX_UCAST_UNANSWERED_QUERIES or when we receive an
    163 // error e.g., SERV_FAIL from DNS server.
    164 mDNSexport void PenalizeDNSServer(mDNS *const m, DNSQuestion *q)
    165 	{
    166 	DNSServer *new;
    167 	DNSServer *orig = q->qDNSServer;
    168 
    169 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
    170 		LogMsg("PenalizeDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
    171 
    172 	// This should never happen. Whenever we change DNS server, we change the ID on the question and hence
    173 	// we should never accept a response after we penalize a DNS server e.g., send two queries, no response,
    174 	// penalize DNS server and no new servers to pick for the question and hence qDNSServer is NULL. If we
    175 	// receive a response now, the DNS server can be NULL. But we won't because the ID already has been
    176 	// changed.
    177 	if (!q->qDNSServer)
    178 		{
    179 		LogMsg("PenalizeDNSServer: ERROR!! Null DNS server for %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), q->unansweredQueries);
    180 		goto end;
    181 		}
    182 
    183 	LogInfo("PenalizeDNSServer: Penalizing DNS server %#a:%d question (%##s) for question %p %##s (%s) SuppressUnusable %d",
    184 		&q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c, q, q->qname.c, DNSTypeName(q->qtype),
    185 		q->SuppressUnusable);
    186 
    187 	// If strict ordering of unicast servers needs to be preserved, we just lookup
    188 	// the next best match server below
    189 	//
    190 	// If strict ordering is not required which is the default behavior, we penalize the server
    191 	// for DNSSERVER_PENALTY_TIME. We may also use additional logic e.g., don't penalize for PTR
    192 	// in the future.
    193 
    194 	if (!StrictUnicastOrdering)
    195 		{
    196 		LogInfo("PenalizeDNSServer: Strict Unicast Ordering is FALSE");
    197 		// We penalize the server so that new queries don't pick this server for DNSSERVER_PENALTY_TIME
    198 		// XXX Include other logic here to see if this server should really be penalized
    199 		//
    200 		if (q->qtype == kDNSType_PTR)
    201 			{
    202 			LogInfo("PenalizeDNSServer: Not Penalizing PTR question");
    203 			}
    204 		else
    205 			{
    206 			LogInfo("PenalizeDNSServer: Penalizing question type %d", q->qtype);
    207 			q->qDNSServer->penaltyTime = NonZeroTime(m->timenow + DNSSERVER_PENALTY_TIME);
    208 			}
    209 		}
    210 	else
    211 		{
    212 		LogInfo("PenalizeDNSServer: Strict Unicast Ordering is TRUE");
    213 		}
    214 
    215 end:
    216 	new = GetServerForQuestion(m, q);
    217 
    218 
    219 	if (new == orig)
    220 		{
    221 		if (new)
    222 			LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server %#a:%d", &new->addr,
    223 		    	mDNSVal16(new->port));
    224 		else
    225 			LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server NULL");
    226 		q->ThisQInterval = 0;	// Inactivate this question so that we dont bombard the network
    227 		}
    228 	else
    229 		{
    230 		// The new DNSServer is set in DNSServerChangeForQuestion
    231 		DNSServerChangeForQuestion(m, q, new);
    232 
    233 		if (new)
    234 			{
    235 			LogInfo("PenalizeDNSServer: Server for %##s (%s) changed to %#a:%d (%##s)",
    236 				q->qname.c, DNSTypeName(q->qtype), &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c);
    237 			// We want to try the next server immediately. As the question may already have backed off, reset
    238 			// the interval. We do this only the first time when we try all the DNS servers. Once we reached the end of
    239 			// list and retrying all the servers again e.g., at least one server failed to respond in the previous try, we
    240 			// use the normal backoff which is done in uDNS_CheckCurrentQuestion when we send the packet out.
    241 			if (!q->triedAllServersOnce)
    242 				{
    243 				q->ThisQInterval = InitialQuestionInterval;
    244 				q->LastQTime  = m->timenow - q->ThisQInterval;
    245 				SetNextQueryTime(m, q);
    246 				}
    247 			}
    248 		else
    249 			{
    250 			// We don't have any more DNS servers for this question. If some server in the list did not return
    251 			// any response, we need to keep retrying till we get a response. uDNS_CheckCurrentQuestion handles
    252 			// this case.
    253 			//
    254 			// If all servers responded with a negative response, We need to do two things. First, generate a
    255 			// negative response so that applications get a reply. We also need to reinitialize the DNS servers
    256 			// so that when the cache expires, we can restart the query.
    257 			//
    258 			// Negative response may be generated in two ways.
    259 			//
    260 			// 1. AnswerQuestionForDNSServerChanges (called from DNSServerChangedForQuestion) might find some
    261 			//    cache entries and answer this question.
    262 			// 2. uDNS_CheckCurrentQuestion will create a new cache entry and answer this question
    263 			//
    264 			// For (1), it might be okay to reinitialize the DNS servers here. But for (2), we can't do it here
    265 			// because uDNS_CheckCurrentQuestion will try resending the queries. Hence, to be consistent, we
    266 			// defer reintializing the DNS servers up until generating a negative cache response.
    267 			//
    268 			// Be careful not to touch the ThisQInterval here. For a normal question, when we answer the question
    269 			// in AnswerCurrentQuestionWithResourceRecord will set ThisQInterval to MaxQuestionInterval and hence
    270 			// the next query will not happen until cache expiry. If it is a long lived question,
    271 			// AnswerCurrentQuestionWithResourceRecord will not set it to MaxQuestionInterval. In that case,
    272 			// we want the normal backoff to work.
    273 			LogInfo("PenalizeDNSServer: Server for %p, %##s (%s) changed to NULL, Interval %d", q, q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
    274 			}
    275 		q->unansweredQueries = 0;
    276 
    277 		}
    278 	}
    279 
    280 // ***************************************************************************
    281 #if COMPILER_LIKES_PRAGMA_MARK
    282 #pragma mark - authorization management
    283 #endif
    284 
    285 mDNSlocal DomainAuthInfo *GetAuthInfoForName_direct(mDNS *m, const domainname *const name)
    286 	{
    287 	const domainname *n = name;
    288 	while (n->c[0])
    289 		{
    290 		DomainAuthInfo *ptr;
    291 		for (ptr = m->AuthInfoList; ptr; ptr = ptr->next)
    292 			if (SameDomainName(&ptr->domain, n))
    293 				{
    294 				debugf("GetAuthInfoForName %##s Matched %##s Key name %##s", name->c, ptr->domain.c, ptr->keyname.c);
    295 				return(ptr);
    296 				}
    297 		n = (const domainname *)(n->c + 1 + n->c[0]);
    298 		}
    299 	//LogInfo("GetAuthInfoForName none found for %##s", name->c);
    300 	return mDNSNULL;
    301 	}
    302 
    303 // MUST be called with lock held
    304 mDNSexport DomainAuthInfo *GetAuthInfoForName_internal(mDNS *m, const domainname *const name)
    305 	{
    306 	DomainAuthInfo **p = &m->AuthInfoList;
    307 
    308 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
    309 		LogMsg("GetAuthInfoForName_internal: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
    310 
    311 	// First purge any dead keys from the list
    312 	while (*p)
    313 		{
    314 		if ((*p)->deltime && m->timenow - (*p)->deltime >= 0 && AutoTunnelUnregistered(*p))
    315 			{
    316 			DNSQuestion *q;
    317 			DomainAuthInfo *info = *p;
    318 			LogInfo("GetAuthInfoForName_internal deleting expired key %##s %##s", info->domain.c, info->keyname.c);
    319 			*p = info->next;	// Cut DomainAuthInfo from list *before* scanning our question list updating AuthInfo pointers
    320 			for (q = m->Questions; q; q=q->next)
    321 				if (q->AuthInfo == info)
    322 					{
    323 					q->AuthInfo = GetAuthInfoForName_direct(m, &q->qname);
    324 					debugf("GetAuthInfoForName_internal updated q->AuthInfo from %##s to %##s for %##s (%s)",
    325 						info->domain.c, q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
    326 					}
    327 
    328 			// Probably not essential, but just to be safe, zero out the secret key data
    329 			// so we don't leave it hanging around in memory
    330 			// (where it could potentially get exposed via some other bug)
    331 			mDNSPlatformMemZero(info, sizeof(*info));
    332 			mDNSPlatformMemFree(info);
    333 			}
    334 		else
    335 			p = &(*p)->next;
    336 		}
    337 
    338 	return(GetAuthInfoForName_direct(m, name));
    339 	}
    340 
    341 mDNSexport DomainAuthInfo *GetAuthInfoForName(mDNS *m, const domainname *const name)
    342 	{
    343 	DomainAuthInfo *d;
    344 	mDNS_Lock(m);
    345 	d = GetAuthInfoForName_internal(m, name);
    346 	mDNS_Unlock(m);
    347 	return(d);
    348 	}
    349 
    350 // MUST be called with the lock held
    351 mDNSexport mStatus mDNS_SetSecretForDomain(mDNS *m, DomainAuthInfo *info,
    352 	const domainname *domain, const domainname *keyname, const char *b64keydata, const domainname *hostname, mDNSIPPort *port, const char *autoTunnelPrefix)
    353 	{
    354 	DNSQuestion *q;
    355 	DomainAuthInfo **p = &m->AuthInfoList;
    356 	if (!info || !b64keydata) { LogMsg("mDNS_SetSecretForDomain: ERROR: info %p b64keydata %p", info, b64keydata); return(mStatus_BadParamErr); }
    357 
    358 	LogInfo("mDNS_SetSecretForDomain: domain %##s key %##s%s%s", domain->c, keyname->c, autoTunnelPrefix ? " prefix " : "", autoTunnelPrefix ? autoTunnelPrefix : "");
    359 
    360 	info->AutoTunnel = autoTunnelPrefix;
    361 	AssignDomainName(&info->domain,  domain);
    362 	AssignDomainName(&info->keyname, keyname);
    363 	if (hostname)
    364 		AssignDomainName(&info->hostname, hostname);
    365 	else
    366 		info->hostname.c[0] = 0;
    367 	if (port)
    368 		info->port = *port;
    369 	else
    370 		info->port = zeroIPPort;
    371 	mDNS_snprintf(info->b64keydata, sizeof(info->b64keydata), "%s", b64keydata);
    372 
    373 	if (DNSDigest_ConstructHMACKeyfromBase64(info, b64keydata) < 0)
    374 		{
    375 		LogMsg("mDNS_SetSecretForDomain: ERROR: Could not convert shared secret from base64: domain %##s key %##s %s", domain->c, keyname->c, mDNS_LoggingEnabled ? b64keydata : "");
    376 		return(mStatus_BadParamErr);
    377 		}
    378 
    379 	// Don't clear deltime until after we've ascertained that b64keydata is valid
    380 	info->deltime = 0;
    381 
    382 	while (*p && (*p) != info) p=&(*p)->next;
    383 	if (*p) {LogInfo("mDNS_SetSecretForDomain: Domain %##s Already in list", (*p)->domain.c); return(mStatus_AlreadyRegistered);}
    384 
    385 	// Caution: Only zero AutoTunnelHostRecord.namestorage and AutoTunnelNAT.clientContext AFTER we've determined that this is a NEW DomainAuthInfo
    386 	// being added to the list. Otherwise we risk smashing our AutoTunnel host records and NATOperation that are already active and in use.
    387 	info->AutoTunnelHostRecord.resrec.RecordType = kDNSRecordTypeUnregistered;
    388 	info->AutoTunnelHostRecord.namestorage.c[0] = 0;
    389 	info->AutoTunnelTarget    .resrec.RecordType = kDNSRecordTypeUnregistered;
    390 	info->AutoTunnelDeviceInfo.resrec.RecordType = kDNSRecordTypeUnregistered;
    391 	info->AutoTunnelService   .resrec.RecordType = kDNSRecordTypeUnregistered;
    392 	info->AutoTunnel6Record   .resrec.RecordType = kDNSRecordTypeUnregistered;
    393 	info->AutoTunnelNAT.clientContext = mDNSNULL;
    394 	info->next = mDNSNULL;
    395 	*p = info;
    396 
    397 	// Check to see if adding this new DomainAuthInfo has changed the credentials for any of our questions
    398 	for (q = m->Questions; q; q=q->next)
    399 		{
    400 		DomainAuthInfo *newinfo = GetAuthInfoForQuestion(m, q);
    401 		if (q->AuthInfo != newinfo)
    402 			{
    403 			debugf("mDNS_SetSecretForDomain updating q->AuthInfo from %##s to %##s for %##s (%s)",
    404 				q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL,
    405 				newinfo     ? newinfo    ->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
    406 			q->AuthInfo = newinfo;
    407 			}
    408 		}
    409 
    410 	return(mStatus_NoError);
    411 	}
    412 
    413 // ***************************************************************************
    414 #if COMPILER_LIKES_PRAGMA_MARK
    415 #pragma mark -
    416 #pragma mark - NAT Traversal
    417 #endif
    418 
    419 mDNSlocal mStatus uDNS_SendNATMsg(mDNS *m, NATTraversalInfo *info)
    420 	{
    421 	mStatus err = mStatus_NoError;
    422 
    423 	// send msg if we have a router and it is a private address
    424 	if (!mDNSIPv4AddressIsZero(m->Router.ip.v4) && mDNSv4AddrIsRFC1918(&m->Router.ip.v4))
    425 		{
    426 		union { NATAddrRequest NATAddrReq; NATPortMapRequest NATPortReq; } u = { { NATMAP_VERS, NATOp_AddrRequest } } ;
    427 		const mDNSu8 *end = (mDNSu8 *)&u + sizeof(NATAddrRequest);
    428 
    429 		if (info)			// For NATOp_MapUDP and NATOp_MapTCP, fill in additional fields
    430 			{
    431 			mDNSu8 *p = (mDNSu8 *)&u.NATPortReq.NATReq_lease;
    432 			u.NATPortReq.opcode  = info->Protocol;
    433 			u.NATPortReq.unused  = zeroID;
    434 			u.NATPortReq.intport = info->IntPort;
    435 			u.NATPortReq.extport = info->RequestedPort;
    436 			p[0] = (mDNSu8)((info->NATLease >> 24) &  0xFF);
    437 			p[1] = (mDNSu8)((info->NATLease >> 16) &  0xFF);
    438 			p[2] = (mDNSu8)((info->NATLease >>  8) &  0xFF);
    439 			p[3] = (mDNSu8)( info->NATLease        &  0xFF);
    440 			end = (mDNSu8 *)&u + sizeof(NATPortMapRequest);
    441 			}
    442 
    443 		err = mDNSPlatformSendUDP(m, (mDNSu8 *)&u, end, 0, mDNSNULL, &m->Router, NATPMPPort);
    444 
    445 #ifdef _LEGACY_NAT_TRAVERSAL_
    446 		if (mDNSIPPortIsZero(m->UPnPRouterPort) || mDNSIPPortIsZero(m->UPnPSOAPPort)) LNT_SendDiscoveryMsg(m);
    447 		else if (info) err = LNT_MapPort(m, info);
    448 		else err = LNT_GetExternalAddress(m);
    449 #endif // _LEGACY_NAT_TRAVERSAL_
    450 		}
    451 	return(err);
    452 	}
    453 
    454 mDNSexport void RecreateNATMappings(mDNS *const m)
    455 	{
    456 	NATTraversalInfo *n;
    457 	for (n = m->NATTraversals; n; n=n->next)
    458 		{
    459 		n->ExpiryTime    = 0;		// Mark this mapping as expired
    460 		n->retryInterval = NATMAP_INIT_RETRY;
    461 		n->retryPortMap  = m->timenow;
    462 #ifdef _LEGACY_NAT_TRAVERSAL_
    463 		if (n->tcpInfo.sock) { mDNSPlatformTCPCloseConnection(n->tcpInfo.sock); n->tcpInfo.sock = mDNSNULL; }
    464 #endif // _LEGACY_NAT_TRAVERSAL_
    465 		}
    466 
    467 	m->NextScheduledNATOp = m->timenow;		// Need to send packets immediately
    468 	}
    469 
    470 mDNSexport void natTraversalHandleAddressReply(mDNS *const m, mDNSu16 err, mDNSv4Addr ExtAddr)
    471 	{
    472 	static mDNSu16 last_err = 0;
    473 
    474 	if (err)
    475 		{
    476 		if (err != last_err) LogMsg("Error getting external address %d", err);
    477 		ExtAddr = zerov4Addr;
    478 		}
    479 	else
    480 		{
    481 		LogInfo("Received external IP address %.4a from NAT", &ExtAddr);
    482 		if (mDNSv4AddrIsRFC1918(&ExtAddr))
    483 			LogMsg("Double NAT (external NAT gateway address %.4a is also a private RFC 1918 address)", &ExtAddr);
    484 		if (mDNSIPv4AddressIsZero(ExtAddr))
    485 			err = NATErr_NetFail; // fake error to handle routers that pathologically report success with the zero address
    486 		}
    487 
    488 	if (!mDNSSameIPv4Address(m->ExternalAddress, ExtAddr))
    489 		{
    490 		m->ExternalAddress = ExtAddr;
    491 		RecreateNATMappings(m);		// Also sets NextScheduledNATOp for us
    492 		}
    493 
    494 	if (!err) // Success, back-off to maximum interval
    495 		m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
    496 	else if (!last_err) // Failure after success, retry quickly (then back-off exponentially)
    497 		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
    498 	// else back-off normally in case of pathological failures
    499 
    500 	m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
    501 	if (m->NextScheduledNATOp - m->retryIntervalGetAddr > 0)
    502 		m->NextScheduledNATOp = m->retryIntervalGetAddr;
    503 
    504 	last_err = err;
    505 	}
    506 
    507 // Both places that call NATSetNextRenewalTime() update m->NextScheduledNATOp correctly afterwards
    508 mDNSlocal void NATSetNextRenewalTime(mDNS *const m, NATTraversalInfo *n)
    509 	{
    510 	n->retryInterval = (n->ExpiryTime - m->timenow)/2;
    511 	if (n->retryInterval < NATMAP_MIN_RETRY_INTERVAL)	// Min retry interval is 2 seconds
    512 		n->retryInterval = NATMAP_MIN_RETRY_INTERVAL;
    513 	n->retryPortMap = m->timenow + n->retryInterval;
    514 	}
    515 
    516 // Note: When called from handleLNTPortMappingResponse() only pkt->err, pkt->extport and pkt->NATRep_lease fields are filled in
    517 mDNSexport void natTraversalHandlePortMapReply(mDNS *const m, NATTraversalInfo *n, const mDNSInterfaceID InterfaceID, mDNSu16 err, mDNSIPPort extport, mDNSu32 lease)
    518 	{
    519 	const char *prot = n->Protocol == NATOp_MapUDP ? "UDP" : n->Protocol == NATOp_MapTCP ? "TCP" : "?";
    520 	(void)prot;
    521 	n->NewResult = err;
    522 	if (err || lease == 0 || mDNSIPPortIsZero(extport))
    523 		{
    524 		LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d error %d",
    525 			n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease, err);
    526 		n->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
    527 		n->retryPortMap = m->timenow + NATMAP_MAX_RETRY_INTERVAL;
    528 		// No need to set m->NextScheduledNATOp here, since we're only ever extending the m->retryPortMap time
    529 		if      (err == NATErr_Refused)                     n->NewResult = mStatus_NATPortMappingDisabled;
    530 		else if (err > NATErr_None && err <= NATErr_Opcode) n->NewResult = mStatus_NATPortMappingUnsupported;
    531 		}
    532 	else
    533 		{
    534 		if (lease > 999999999UL / mDNSPlatformOneSecond)
    535 			lease = 999999999UL / mDNSPlatformOneSecond;
    536 		n->ExpiryTime = NonZeroTime(m->timenow + lease * mDNSPlatformOneSecond);
    537 
    538 		if (!mDNSSameIPPort(n->RequestedPort, extport))
    539 			LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d changed to %5d",
    540 				n, prot, mDNSVal16(n->IntPort), mDNSVal16(n->RequestedPort), mDNSVal16(extport));
    541 
    542 		n->InterfaceID   = InterfaceID;
    543 		n->RequestedPort = extport;
    544 
    545 		LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d",
    546 			n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease);
    547 
    548 		NATSetNextRenewalTime(m, n);			// Got our port mapping; now set timer to renew it at halfway point
    549 		m->NextScheduledNATOp = m->timenow;		// May need to invoke client callback immediately
    550 		}
    551 	}
    552 
    553 // Must be called with the mDNS_Lock held
    554 mDNSexport mStatus mDNS_StartNATOperation_internal(mDNS *const m, NATTraversalInfo *traversal)
    555 	{
    556 	NATTraversalInfo **n;
    557 
    558 	LogInfo("mDNS_StartNATOperation_internal %p Protocol %d IntPort %d RequestedPort %d NATLease %d", traversal,
    559 		traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
    560 
    561 	// Note: It important that new traversal requests are appended at the *end* of the list, not prepended at the start
    562 	for (n = &m->NATTraversals; *n; n=&(*n)->next)
    563 		{
    564 		if (traversal == *n)
    565 			{
    566 			LogMsg("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
    567 				traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease);
    568 			#if ForceAlerts
    569 				*(long*)0 = 0;
    570 			#endif
    571 			return(mStatus_AlreadyRegistered);
    572 			}
    573 		if (traversal->Protocol && traversal->Protocol == (*n)->Protocol && mDNSSameIPPort(traversal->IntPort, (*n)->IntPort) &&
    574 			!mDNSSameIPPort(traversal->IntPort, SSHPort))
    575 			LogMsg("Warning: Created port mapping request %p Prot %d Int %d TTL %d "
    576 				"duplicates existing port mapping request %p Prot %d Int %d TTL %d",
    577 				traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
    578 				*n,        (*n)     ->Protocol, mDNSVal16((*n)     ->IntPort), (*n)     ->NATLease);
    579 		}
    580 
    581 	// Initialize necessary fields
    582 	traversal->next            = mDNSNULL;
    583 	traversal->ExpiryTime      = 0;
    584 	traversal->retryInterval   = NATMAP_INIT_RETRY;
    585 	traversal->retryPortMap    = m->timenow;
    586 	traversal->NewResult       = mStatus_NoError;
    587 	traversal->ExternalAddress = onesIPv4Addr;
    588 	traversal->ExternalPort    = zeroIPPort;
    589 	traversal->Lifetime        = 0;
    590 	traversal->Result          = mStatus_NoError;
    591 
    592 	// set default lease if necessary
    593 	if (!traversal->NATLease) traversal->NATLease = NATMAP_DEFAULT_LEASE;
    594 
    595 #ifdef _LEGACY_NAT_TRAVERSAL_
    596 	mDNSPlatformMemZero(&traversal->tcpInfo, sizeof(traversal->tcpInfo));
    597 #endif // _LEGACY_NAT_TRAVERSAL_
    598 
    599 	if (!m->NATTraversals)		// If this is our first NAT request, kick off an address request too
    600 		{
    601 		m->retryGetAddr         = m->timenow;
    602 		m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
    603 		}
    604 
    605 	m->NextScheduledNATOp = m->timenow;	// This will always trigger sending the packet ASAP, and generate client callback if necessary
    606 
    607 	*n = traversal;		// Append new NATTraversalInfo to the end of our list
    608 
    609 	return(mStatus_NoError);
    610 	}
    611 
    612 // Must be called with the mDNS_Lock held
    613 mDNSexport mStatus mDNS_StopNATOperation_internal(mDNS *m, NATTraversalInfo *traversal)
    614 	{
    615 	mDNSBool unmap = mDNStrue;
    616 	NATTraversalInfo *p;
    617 	NATTraversalInfo **ptr = &m->NATTraversals;
    618 
    619 	while (*ptr && *ptr != traversal) ptr=&(*ptr)->next;
    620 	if (*ptr) *ptr = (*ptr)->next;		// If we found it, cut this NATTraversalInfo struct from our list
    621 	else
    622 		{
    623 		LogMsg("mDNS_StopNATOperation_internal: NATTraversalInfo %p not found in list", traversal);
    624 		return(mStatus_BadReferenceErr);
    625 		}
    626 
    627 	LogInfo("mDNS_StopNATOperation_internal %p %d %d %d %d", traversal,
    628 		traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
    629 
    630 	if (m->CurrentNATTraversal == traversal)
    631 		m->CurrentNATTraversal = m->CurrentNATTraversal->next;
    632 
    633 	if (traversal->Protocol)
    634 		for (p = m->NATTraversals; p; p=p->next)
    635 			if (traversal->Protocol == p->Protocol && mDNSSameIPPort(traversal->IntPort, p->IntPort))
    636 				{
    637 				if (!mDNSSameIPPort(traversal->IntPort, SSHPort))
    638 					LogMsg("Warning: Removed port mapping request %p Prot %d Int %d TTL %d "
    639 						"duplicates existing port mapping request %p Prot %d Int %d TTL %d",
    640 						traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
    641 						p,         p        ->Protocol, mDNSVal16(p        ->IntPort), p        ->NATLease);
    642 				unmap = mDNSfalse;
    643 				}
    644 
    645 	if (traversal->ExpiryTime && unmap)
    646 		{
    647 		traversal->NATLease = 0;
    648 		traversal->retryInterval = 0;
    649 		uDNS_SendNATMsg(m, traversal);
    650 		}
    651 
    652 	// 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
    653 	#ifdef _LEGACY_NAT_TRAVERSAL_
    654 		{
    655 		mStatus err = LNT_UnmapPort(m, traversal);
    656 		if (err) LogMsg("Legacy NAT Traversal - unmap request failed with error %d", err);
    657 		}
    658 	#endif // _LEGACY_NAT_TRAVERSAL_
    659 
    660 	return(mStatus_NoError);
    661 	}
    662 
    663 mDNSexport mStatus mDNS_StartNATOperation(mDNS *const m, NATTraversalInfo *traversal)
    664 	{
    665 	mStatus status;
    666 	mDNS_Lock(m);
    667 	status = mDNS_StartNATOperation_internal(m, traversal);
    668 	mDNS_Unlock(m);
    669 	return(status);
    670 	}
    671 
    672 mDNSexport mStatus mDNS_StopNATOperation(mDNS *const m, NATTraversalInfo *traversal)
    673 	{
    674 	mStatus status;
    675 	mDNS_Lock(m);
    676 	status = mDNS_StopNATOperation_internal(m, traversal);
    677 	mDNS_Unlock(m);
    678 	return(status);
    679 	}
    680 
    681 // ***************************************************************************
    682 #if COMPILER_LIKES_PRAGMA_MARK
    683 #pragma mark -
    684 #pragma mark - Long-Lived Queries
    685 #endif
    686 
    687 // Lock must be held -- otherwise m->timenow is undefined
    688 mDNSlocal void StartLLQPolling(mDNS *const m, DNSQuestion *q)
    689 	{
    690 	debugf("StartLLQPolling: %##s", q->qname.c);
    691 	q->state = LLQ_Poll;
    692 	q->ThisQInterval = INIT_UCAST_POLL_INTERVAL;
    693 	// We want to send our poll query ASAP, but the "+ 1" is because if we set the time to now,
    694 	// we risk causing spurious "SendQueries didn't send all its queries" log messages
    695 	q->LastQTime     = m->timenow - q->ThisQInterval + 1;
    696 	SetNextQueryTime(m, q);
    697 #if APPLE_OSX_mDNSResponder
    698 	UpdateAutoTunnelDomainStatuses(m);
    699 #endif
    700 	}
    701 
    702 mDNSlocal mDNSu8 *putLLQ(DNSMessage *const msg, mDNSu8 *ptr, const DNSQuestion *const question, const LLQOptData *const data)
    703 	{
    704 	AuthRecord rr;
    705 	ResourceRecord *opt = &rr.resrec;
    706 	rdataOPT *optRD;
    707 
    708 	//!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
    709 	ptr = putQuestion(msg, ptr, msg->data + AbsoluteMaxDNSMessageData, &question->qname, question->qtype, question->qclass);
    710 	if (!ptr) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL; }
    711 
    712 	// locate OptRR if it exists, set pointer to end
    713 	// !!!KRS implement me
    714 
    715 	// format opt rr (fields not specified are zero-valued)
    716 	mDNS_SetupResourceRecord(&rr, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
    717 	opt->rrclass    = NormalMaxDNSMessageData;
    718 	opt->rdlength   = sizeof(rdataOPT);	// One option in this OPT record
    719 	opt->rdestimate = sizeof(rdataOPT);
    720 
    721 	optRD = &rr.resrec.rdata->u.opt[0];
    722 	optRD->opt = kDNSOpt_LLQ;
    723 	optRD->u.llq = *data;
    724 	ptr = PutResourceRecordTTLJumbo(msg, ptr, &msg->h.numAdditionals, opt, 0);
    725 	if (!ptr) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL; }
    726 
    727 	return ptr;
    728 	}
    729 
    730 // Normally we'd just request event packets be sent directly to m->LLQNAT.ExternalPort, except...
    731 // with LLQs over TLS/TCP we're doing a weird thing where instead of requesting packets be sent to ExternalAddress:ExternalPort
    732 // we're requesting that packets be sent to ExternalPort, but at the source address of our outgoing TCP connection.
    733 // Normally, after going through the NAT gateway, the source address of our outgoing TCP connection is the same as ExternalAddress,
    734 // so this is fine, except when the TCP connection ends up going over a VPN tunnel instead.
    735 // 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
    736 // LLQ server to send events to us directly at port 5353 on that address, instead of at our mapped external NAT port.
    737 
    738 mDNSlocal mDNSu16 GetLLQEventPort(const mDNS *const m, const mDNSAddr *const dst)
    739 	{
    740 	mDNSAddr src;
    741 	mDNSPlatformSourceAddrForDest(&src, dst);
    742 	//LogMsg("GetLLQEventPort: src %#a for dst %#a (%d)", &src, dst, mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : 0);
    743 	return(mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : mDNSVal16(MulticastDNSPort));
    744 	}
    745 
    746 // Normally called with llq set.
    747 // May be called with llq NULL, when retransmitting a lost Challenge Response
    748 mDNSlocal void sendChallengeResponse(mDNS *const m, DNSQuestion *const q, const LLQOptData *llq)
    749 	{
    750 	mDNSu8 *responsePtr = m->omsg.data;
    751 	LLQOptData llqBuf;
    752 
    753 	if (q->tcp) { LogMsg("sendChallengeResponse: ERROR!!: question %##s (%s) tcp non-NULL", q->qname.c, DNSTypeName(q->qtype)); return; }
    754 
    755 	if (PrivateQuery(q)) { LogMsg("sendChallengeResponse: ERROR!!: Private Query %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
    756 
    757 	if (q->ntries++ == kLLQ_MAX_TRIES)
    758 		{
    759 		LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s", kLLQ_MAX_TRIES, q->qname.c);
    760 		StartLLQPolling(m,q);
    761 		return;
    762 		}
    763 
    764 	if (!llq)		// Retransmission: need to make a new LLQOptData
    765 		{
    766 		llqBuf.vers     = kLLQ_Vers;
    767 		llqBuf.llqOp    = kLLQOp_Setup;
    768 		llqBuf.err      = LLQErr_NoError;	// Don't need to tell server UDP notification port when sending over UDP
    769 		llqBuf.id       = q->id;
    770 		llqBuf.llqlease = q->ReqLease;
    771 		llq = &llqBuf;
    772 		}
    773 
    774 	q->LastQTime     = m->timenow;
    775 	q->ThisQInterval = q->tcp ? 0 : (kLLQ_INIT_RESEND * q->ntries * mDNSPlatformOneSecond);		// If using TCP, don't need to retransmit
    776 	SetNextQueryTime(m, q);
    777 
    778 	// To simulate loss of challenge response packet, uncomment line below
    779 	//if (q->ntries == 1) return;
    780 
    781 	InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
    782 	responsePtr = putLLQ(&m->omsg, responsePtr, q, llq);
    783 	if (responsePtr)
    784 		{
    785 		mStatus err = mDNSSendDNSMessage(m, &m->omsg, responsePtr, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
    786 		if (err) { LogMsg("sendChallengeResponse: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err); }
    787 		}
    788 	else StartLLQPolling(m,q);
    789 	}
    790 
    791 mDNSlocal void SetLLQTimer(mDNS *const m, DNSQuestion *const q, const LLQOptData *const llq)
    792 	{
    793 	mDNSs32 lease = (mDNSs32)llq->llqlease * mDNSPlatformOneSecond;
    794 	q->ReqLease      = llq->llqlease;
    795 	q->LastQTime     = m->timenow;
    796 	q->expire        = m->timenow + lease;
    797 	q->ThisQInterval = lease/2 + mDNSRandom(lease/10);
    798 	debugf("SetLLQTimer setting %##s (%s) to %d %d", q->qname.c, DNSTypeName(q->qtype), lease/mDNSPlatformOneSecond, q->ThisQInterval/mDNSPlatformOneSecond);
    799 	SetNextQueryTime(m, q);
    800 	}
    801 
    802 mDNSlocal void recvSetupResponse(mDNS *const m, mDNSu8 rcode, DNSQuestion *const q, const LLQOptData *const llq)
    803 	{
    804 	if (rcode && rcode != kDNSFlag1_RC_NXDomain)
    805 		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - rcode && rcode != kDNSFlag1_RC_NXDomain", q->qname.c, DNSTypeName(q->qtype)); return; }
    806 
    807 	if (llq->llqOp != kLLQOp_Setup)
    808 		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - bad op %d", q->qname.c, DNSTypeName(q->qtype), llq->llqOp); return; }
    809 
    810 	if (llq->vers != kLLQ_Vers)
    811 		{ LogMsg("ERROR: recvSetupResponse %##s (%s) - bad vers %d", q->qname.c, DNSTypeName(q->qtype), llq->vers); return; }
    812 
    813 	if (q->state == LLQ_InitialRequest)
    814 		{
    815 		//LogInfo("Got LLQ_InitialRequest");
    816 
    817 		if (llq->err) { LogMsg("recvSetupResponse - received llq->err %d from server", llq->err); StartLLQPolling(m,q); return; }
    818 
    819 		if (q->ReqLease != llq->llqlease)
    820 			debugf("recvSetupResponse: requested lease %lu, granted lease %lu", q->ReqLease, llq->llqlease);
    821 
    822 		// cache expiration in case we go to sleep before finishing setup
    823 		q->ReqLease = llq->llqlease;
    824 		q->expire = m->timenow + ((mDNSs32)llq->llqlease * mDNSPlatformOneSecond);
    825 
    826 		// update state
    827 		q->state  = LLQ_SecondaryRequest;
    828 		q->id     = llq->id;
    829 		q->ntries = 0; // first attempt to send response
    830 		sendChallengeResponse(m, q, llq);
    831 		}
    832 	else if (q->state == LLQ_SecondaryRequest)
    833 		{
    834 		//LogInfo("Got LLQ_SecondaryRequest");
    835 
    836 		// Fix this immediately if not sooner.  Copy the id from the LLQOptData into our DNSQuestion struct.  This is only
    837 		// an issue for private LLQs, because we skip parts 2 and 3 of the handshake.  This is related to a bigger
    838 		// problem of the current implementation of TCP LLQ setup: we're not handling state transitions correctly
    839 		// if the server sends back SERVFULL or STATIC.
    840 		if (PrivateQuery(q))
    841 			{
    842 			LogInfo("Private LLQ_SecondaryRequest; copying id %08X%08X", llq->id.l[0], llq->id.l[1]);
    843 			q->id = llq->id;
    844 			}
    845 
    846 		if (llq->err) { LogMsg("ERROR: recvSetupResponse %##s (%s) code %d from server", q->qname.c, DNSTypeName(q->qtype), llq->err); StartLLQPolling(m,q); return; }
    847 		if (!mDNSSameOpaque64(&q->id, &llq->id))
    848 			{ LogMsg("recvSetupResponse - ID changed.  discarding"); return; } // this can happen rarely (on packet loss + reordering)
    849 		q->state         = LLQ_Established;
    850 		q->ntries        = 0;
    851 		SetLLQTimer(m, q, llq);
    852 #if APPLE_OSX_mDNSResponder
    853 		UpdateAutoTunnelDomainStatuses(m);
    854 #endif
    855 		}
    856 	}
    857 
    858 mDNSexport uDNS_LLQType uDNS_recvLLQResponse(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
    859 	const mDNSAddr *const srcaddr, const mDNSIPPort srcport, DNSQuestion **matchQuestion)
    860 	{
    861 	DNSQuestion pktQ, *q;
    862 	if (msg->h.numQuestions && getQuestion(msg, msg->data, end, 0, &pktQ))
    863 		{
    864 		const rdataOPT *opt = GetLLQOptData(m, msg, end);
    865 
    866 		for (q = m->Questions; q; q = q->next)
    867 			{
    868 			if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->qtype == pktQ.qtype && q->qnamehash == pktQ.qnamehash && SameDomainName(&q->qname, &pktQ.qname))
    869 				{
    870 				debugf("uDNS_recvLLQResponse found %##s (%s) %d %#a %#a %X %X %X %X %d",
    871 					q->qname.c, DNSTypeName(q->qtype), q->state, srcaddr, &q->servAddr,
    872 					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);
    873 				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));
    874 				if (q->state == LLQ_Poll && mDNSSameOpaque16(msg->h.id, q->TargetQID))
    875 					{
    876 					m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
    877 
    878 					// Don't reset the state to IntialRequest as we may write that to the dynamic store
    879 					// and PrefPane might wrongly think that we are "Starting" instead of "Polling". If
    880 					// we are in polling state because of NAT-PMP disabled or DoubleNAT, next LLQNATCallback
    881 					// would kick us back to LLQInitialRequest. So, resetting the state here may not be useful.
    882 					//
    883 					// If we have a good NAT (neither NAT-PMP disabled nor Double-NAT), then we should not be
    884 					// possibly in polling state. To be safe, we want to retry from the start in that case
    885 					// as there may not be another LLQNATCallback
    886 					//
    887 					// NOTE: We can be in polling state if we cannot resolve the SOA record i.e, servAddr is set to
    888 					// all ones. In that case, we would set it in LLQ_InitialRequest as it overrides the NAT-PMP or
    889 					// Double-NAT state.
    890 					if (!mDNSAddressIsOnes(&q->servAddr) && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) &&
    891 						!m->LLQNAT.Result)
    892 						{
    893 						debugf("uDNS_recvLLQResponse got poll response; moving to LLQ_InitialRequest for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
    894 						q->state         = LLQ_InitialRequest;
    895 						}
    896 					q->servPort      = zeroIPPort;		// Clear servPort so that startLLQHandshake will retry the GetZoneData processing
    897 					q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry LLQ setup in approx 15 minutes
    898 					q->LastQTime     = m->timenow;
    899 					SetNextQueryTime(m, q);
    900 					*matchQuestion = q;
    901 					return uDNS_LLQ_Entire;		// uDNS_LLQ_Entire means flush stale records; assume a large effective TTL
    902 					}
    903 				// 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
    904 				else if (opt && q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Event && mDNSSameOpaque64(&opt->u.llq.id, &q->id))
    905 					{
    906 					mDNSu8 *ackEnd;
    907 					//debugf("Sending LLQ ack for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
    908 					InitializeDNSMessage(&m->omsg.h, msg->h.id, ResponseFlags);
    909 					ackEnd = putLLQ(&m->omsg, m->omsg.data, q, &opt->u.llq);
    910 					if (ackEnd) mDNSSendDNSMessage(m, &m->omsg, ackEnd, mDNSInterface_Any, q->LocalSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
    911 					m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
    912 					debugf("uDNS_LLQ_Events: q->state == LLQ_Established msg->h.id %d q->TargetQID %d", mDNSVal16(msg->h.id), mDNSVal16(q->TargetQID));
    913 					*matchQuestion = q;
    914 					return uDNS_LLQ_Events;
    915 					}
    916 				if (opt && mDNSSameOpaque16(msg->h.id, q->TargetQID))
    917 					{
    918 					if (q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Refresh && mDNSSameOpaque64(&opt->u.llq.id, &q->id) && msg->h.numAdditionals && !msg->h.numAnswers)
    919 						{
    920 						if (opt->u.llq.err != LLQErr_NoError) LogMsg("recvRefreshReply: received error %d from server", opt->u.llq.err);
    921 						else
    922 							{
    923 							//LogInfo("Received refresh confirmation ntries %d for %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
    924 							// If we're waiting to go to sleep, then this LLQ deletion may have been the thing
    925 							// we were waiting for, so schedule another check to see if we can sleep now.
    926 							if (opt->u.llq.llqlease == 0 && m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
    927 							GrantCacheExtensions(m, q, opt->u.llq.llqlease);
    928 							SetLLQTimer(m, q, &opt->u.llq);
    929 							q->ntries = 0;
    930 							}
    931 						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
    932 						*matchQuestion = q;
    933 						return uDNS_LLQ_Ignore;
    934 						}
    935 					if (q->state < LLQ_Established && mDNSSameAddress(srcaddr, &q->servAddr))
    936 						{
    937 						LLQ_State oldstate = q->state;
    938 						recvSetupResponse(m, msg->h.flags.b[1] & kDNSFlag1_RC_Mask, q, &opt->u.llq);
    939 						m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
    940 						// We have a protocol anomaly here in the LLQ definition.
    941 						// Both the challenge packet from the server and the ack+answers packet have opt->u.llq.llqOp == kLLQOp_Setup.
    942 						// However, we need to treat them differently:
    943 						// The challenge packet has no answers in it, and tells us nothing about whether our cache entries
    944 						// are still valid, so this packet should not cause us to do anything that messes with our cache.
    945 						// The ack+answers packet gives us the whole truth, so we should handle it by updating our cache
    946 						// to match the answers in the packet, and only the answers in the packet.
    947 						*matchQuestion = q;
    948 						return (oldstate == LLQ_SecondaryRequest ? uDNS_LLQ_Entire : uDNS_LLQ_Ignore);
    949 						}
    950 					}
    951 				}
    952 			}
    953 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
    954 		}
    955 	*matchQuestion = mDNSNULL;
    956 	return uDNS_LLQ_Not;
    957 	}
    958 
    959 // Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
    960 struct TCPSocket_struct { TCPSocketFlags flags; /* ... */ };
    961 
    962 // tcpCallback is called to handle events (e.g. connection opening and data reception) on TCP connections for
    963 // Private DNS operations -- private queries, private LLQs, private record updates and private service updates
    964 mDNSlocal void tcpCallback(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err)
    965 	{
    966 	tcpInfo_t *tcpInfo = (tcpInfo_t *)context;
    967 	mDNSBool   closed  = mDNSfalse;
    968 	mDNS      *m       = tcpInfo->m;
    969 	DNSQuestion *const q = tcpInfo->question;
    970 	tcpInfo_t **backpointer =
    971 		q                 ? &q           ->tcp :
    972 		tcpInfo->rr       ? &tcpInfo->rr ->tcp : mDNSNULL;
    973 	if (backpointer && *backpointer != tcpInfo)
    974 		LogMsg("tcpCallback: %d backpointer %p incorrect tcpInfo %p question %p rr %p",
    975 			mDNSPlatformTCPGetFD(tcpInfo->sock), *backpointer, tcpInfo, q, tcpInfo->rr);
    976 
    977 	if (err) goto exit;
    978 
    979 	if (ConnectionEstablished)
    980 		{
    981 		mDNSu8    *end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
    982 		DomainAuthInfo *AuthInfo;
    983 
    984 		// Defensive coding for <rdar://problem/5546824> Crash in mDNSResponder at GetAuthInfoForName_internal + 366
    985 		// 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
    986 		if (tcpInfo->rr && tcpInfo->rr->resrec.name != &tcpInfo->rr->namestorage)
    987 			LogMsg("tcpCallback: ERROR: tcpInfo->rr->resrec.name %p != &tcpInfo->rr->namestorage %p",
    988 				tcpInfo->rr->resrec.name, &tcpInfo->rr->namestorage);
    989 		if (tcpInfo->rr  && tcpInfo->rr->        resrec.name != &tcpInfo->rr->        namestorage) return;
    990 
    991 		AuthInfo =  tcpInfo->rr  ? GetAuthInfoForName(m, tcpInfo->rr->resrec.name)         : mDNSNULL;
    992 
    993 		// connection is established - send the message
    994 		if (q && q->LongLived && q->state == LLQ_Established)
    995 			{
    996 			// Lease renewal over TCP, resulting from opening a TCP connection in sendLLQRefresh
    997 			end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
    998 			}
    999 		else if (q && q->LongLived && q->state != LLQ_Poll && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) && !mDNSIPPortIsZero(q->servPort))
   1000 			{
   1001 			// Notes:
   1002 			// If we have a NAT port mapping, ExternalPort is the external port
   1003 			// If we have a routable address so we don't need a port mapping, ExternalPort is the same as our own internal port
   1004 			// If we need a NAT port mapping but can't get one, then ExternalPort is zero
   1005 			LLQOptData llqData;			// set llq rdata
   1006 			llqData.vers  = kLLQ_Vers;
   1007 			llqData.llqOp = kLLQOp_Setup;
   1008 			llqData.err   = GetLLQEventPort(m, &tcpInfo->Addr);	// We're using TCP; tell server what UDP port to send notifications to
   1009 			LogInfo("tcpCallback: eventPort %d", llqData.err);
   1010 			llqData.id    = zeroOpaque64;
   1011 			llqData.llqlease = kLLQ_DefLease;
   1012 			InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
   1013 			end = putLLQ(&tcpInfo->request, tcpInfo->request.data, q, &llqData);
   1014 			if (!end) { LogMsg("ERROR: tcpCallback - putLLQ"); err = mStatus_UnknownErr; goto exit; }
   1015 			AuthInfo = q->AuthInfo;		// Need to add TSIG to this message
   1016 			q->ntries = 0; // Reset ntries so that tcp/tls connection failures don't affect sendChallengeResponse failures
   1017 			}
   1018 		else if (q)
   1019 			{
   1020 			// LLQ Polling mode or non-LLQ uDNS over TCP
   1021 			InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
   1022 			end = putQuestion(&tcpInfo->request, tcpInfo->request.data, tcpInfo->request.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
   1023 			AuthInfo = q->AuthInfo;		// Need to add TSIG to this message
   1024 			}
   1025 
   1026 		err = mDNSSendDNSMessage(m, &tcpInfo->request, end, mDNSInterface_Any, mDNSNULL, &tcpInfo->Addr, tcpInfo->Port, sock, AuthInfo);
   1027 		if (err) { debugf("ERROR: tcpCallback: mDNSSendDNSMessage - %d", err); err = mStatus_UnknownErr; goto exit; }
   1028 
   1029 		// Record time we sent this question
   1030 		if (q)
   1031 			{
   1032 			mDNS_Lock(m);
   1033 			q->LastQTime = m->timenow;
   1034 			if (q->ThisQInterval < (256 * mDNSPlatformOneSecond))	// Now we have a TCP connection open, make sure we wait at least 256 seconds before retrying
   1035 				q->ThisQInterval = (256 * mDNSPlatformOneSecond);
   1036 			SetNextQueryTime(m, q);
   1037 			mDNS_Unlock(m);
   1038 			}
   1039 		}
   1040 	else
   1041 		{
   1042 		long n;
   1043 		if (tcpInfo->nread < 2)			// First read the two-byte length preceeding the DNS message
   1044 			{
   1045 			mDNSu8 *lenptr = (mDNSu8 *)&tcpInfo->replylen;
   1046 			n = mDNSPlatformReadTCP(sock, lenptr + tcpInfo->nread, 2 - tcpInfo->nread, &closed);
   1047 			if (n < 0)
   1048 				{
   1049 				LogMsg("ERROR: tcpCallback - attempt to read message length failed (%d)", n);
   1050 				err = mStatus_ConnFailed;
   1051 				goto exit;
   1052 				}
   1053 			else if (closed)
   1054 				{
   1055 				// It's perfectly fine for this socket to close after the first reply. The server might
   1056 				// be sending gratuitous replies using UDP and doesn't have a need to leave the TCP socket open.
   1057 				// We'll only log this event if we've never received a reply before.
   1058 				// BIND 9 appears to close an idle connection after 30 seconds.
   1059 				if (tcpInfo->numReplies == 0)
   1060 					{
   1061 					LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
   1062 					err = mStatus_ConnFailed;
   1063 					goto exit;
   1064 					}
   1065 				else
   1066 					{
   1067 					// Note that we may not be doing the best thing if an error occurs after we've sent a second request
   1068 					// over this tcp connection.  That is, we only track whether we've received at least one response
   1069 					// which may have been to a previous request sent over this tcp connection.
   1070 					if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
   1071 					DisposeTCPConn(tcpInfo);
   1072 					return;
   1073 					}
   1074 				}
   1075 
   1076 			tcpInfo->nread += n;
   1077 			if (tcpInfo->nread < 2) goto exit;
   1078 
   1079 			tcpInfo->replylen = (mDNSu16)((mDNSu16)lenptr[0] << 8 | lenptr[1]);
   1080 			if (tcpInfo->replylen < sizeof(DNSMessageHeader))
   1081 				{ LogMsg("ERROR: tcpCallback - length too short (%d bytes)", tcpInfo->replylen); err = mStatus_UnknownErr; goto exit; }
   1082 
   1083 			tcpInfo->reply = mDNSPlatformMemAllocate(tcpInfo->replylen);
   1084 			if (!tcpInfo->reply) { LogMsg("ERROR: tcpCallback - malloc failed"); err = mStatus_NoMemoryErr; goto exit; }
   1085 			}
   1086 
   1087 		n = mDNSPlatformReadTCP(sock, ((char *)tcpInfo->reply) + (tcpInfo->nread - 2), tcpInfo->replylen - (tcpInfo->nread - 2), &closed);
   1088 
   1089 		if (n < 0)
   1090 			{
   1091 			LogMsg("ERROR: tcpCallback - read returned %d", n);
   1092 			err = mStatus_ConnFailed;
   1093 			goto exit;
   1094 			}
   1095 		else if (closed)
   1096 			{
   1097 			if (tcpInfo->numReplies == 0)
   1098 				{
   1099 				LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
   1100 				err = mStatus_ConnFailed;
   1101 				goto exit;
   1102 				}
   1103 			else
   1104 				{
   1105 				// Note that we may not be doing the best thing if an error occurs after we've sent a second request
   1106 				// over this tcp connection.  That is, we only track whether we've received at least one response
   1107 				// which may have been to a previous request sent over this tcp connection.
   1108 				if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
   1109 				DisposeTCPConn(tcpInfo);
   1110 				return;
   1111 				}
   1112 			}
   1113 
   1114 		tcpInfo->nread += n;
   1115 
   1116 		if ((tcpInfo->nread - 2) == tcpInfo->replylen)
   1117 			{
   1118 			mDNSBool tls;
   1119 			DNSMessage *reply = tcpInfo->reply;
   1120 			mDNSu8     *end   = (mDNSu8 *)tcpInfo->reply + tcpInfo->replylen;
   1121 			mDNSAddr    Addr  = tcpInfo->Addr;
   1122 			mDNSIPPort  Port  = tcpInfo->Port;
   1123 			mDNSIPPort srcPort = zeroIPPort;
   1124 			tcpInfo->numReplies++;
   1125 			tcpInfo->reply    = mDNSNULL;	// Detach reply buffer from tcpInfo_t, to make sure client callback can't cause it to be disposed
   1126 			tcpInfo->nread    = 0;
   1127 			tcpInfo->replylen = 0;
   1128 
   1129 			// If we're going to dispose this connection, do it FIRST, before calling client callback
   1130 			// Note: Sleep code depends on us clearing *backpointer here -- it uses the clearing of rr->tcp
   1131 			// as the signal that the DNS deregistration operation with the server has completed, and the machine may now sleep
   1132 			// If we clear the tcp pointer in the question, mDNSCoreReceiveResponse cannot find a matching question. Hence
   1133 			// we store the minimal information i.e., the source port of the connection in the question itself.
   1134 			// Dereference sock before it is disposed in DisposeTCPConn below.
   1135 
   1136 			if (sock->flags & kTCPSocketFlags_UseTLS) tls = mDNStrue;
   1137 			else tls = mDNSfalse;
   1138 
   1139 			if (q && q->tcp) {srcPort = q->tcp->SrcPort; q->tcpSrcPort = srcPort;}
   1140 
   1141 			if (backpointer)
   1142 				if (!q || !q->LongLived || m->SleepState)
   1143 					{ *backpointer = mDNSNULL; DisposeTCPConn(tcpInfo); }
   1144 
   1145 			mDNSCoreReceive(m, reply, end, &Addr, Port, tls ? (mDNSAddr *)1 : mDNSNULL, srcPort, 0);
   1146 			// USE CAUTION HERE: Invoking mDNSCoreReceive may have caused the environment to change, including canceling this operation itself
   1147 
   1148 			mDNSPlatformMemFree(reply);
   1149 			return;
   1150 			}
   1151 		}
   1152 
   1153 exit:
   1154 
   1155 	if (err)
   1156 		{
   1157 		// Clear client backpointer FIRST -- that way if one of the callbacks cancels its operation
   1158 		// we won't end up double-disposing our tcpInfo_t
   1159 		if (backpointer) *backpointer = mDNSNULL;
   1160 
   1161 		mDNS_Lock(m);		// Need to grab the lock to get m->timenow
   1162 
   1163 		if (q)
   1164 			{
   1165 			if (q->ThisQInterval == 0)
   1166 				{
   1167 				// 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.
   1168 				// Note that ThisQInterval is also zero when sendChallengeResponse resends the LLQ request on an extant TCP/TLS connection.
   1169 				q->LastQTime = m->timenow;
   1170 				if (q->LongLived)
   1171 					{
   1172 					// We didn't get the chance to send our request packet before the TCP/TLS connection failed.
   1173 					// We want to retry quickly, but want to back off exponentially in case the server is having issues.
   1174 					// Since ThisQInterval was 0, we can't just multiply by QuestionIntervalStep, we must track the number
   1175 					// of TCP/TLS connection failures using ntries.
   1176 					mDNSu32 count = q->ntries + 1; // want to wait at least 1 second before retrying
   1177 
   1178 					q->ThisQInterval = InitialQuestionInterval;
   1179 
   1180 					for (;count;count--)
   1181 						q->ThisQInterval *= QuestionIntervalStep;
   1182 
   1183 					if (q->ThisQInterval > LLQ_POLL_INTERVAL)
   1184 						q->ThisQInterval = LLQ_POLL_INTERVAL;
   1185 					else
   1186 						q->ntries++;
   1187 
   1188 					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);
   1189 					}
   1190 				else
   1191 					{
   1192 					q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
   1193 					LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
   1194 					}
   1195 				SetNextQueryTime(m, q);
   1196 				}
   1197 			else if (NextQSendTime(q) - m->timenow > (q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL))
   1198 				{
   1199 				// If we get an error and our next scheduled query for this question is more than the max interval from now,
   1200 				// reset the next query to ensure we wait no longer the maximum interval from now before trying again.
   1201 				q->LastQTime     = m->timenow;
   1202 				q->ThisQInterval = q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL;
   1203 				SetNextQueryTime(m, q);
   1204 				LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
   1205 				}
   1206 
   1207 			// We're about to dispose of the TCP connection, so we must reset the state to retry over TCP/TLS
   1208 			// because sendChallengeResponse will send the query via UDP if we don't have a tcp pointer.
   1209 			// Resetting to LLQ_InitialRequest will cause uDNS_CheckCurrentQuestion to call startLLQHandshake, which
   1210 			// will attempt to establish a new tcp connection.
   1211 			if (q->LongLived && q->state == LLQ_SecondaryRequest)
   1212 				q->state = LLQ_InitialRequest;
   1213 
   1214 			// ConnFailed may happen if the server sends a TCP reset or TLS fails, in which case we want to retry establishing the LLQ
   1215 			// quickly rather than switching to polling mode.  This case is handled by the above code to set q->ThisQInterval just above.
   1216 			// If the error isn't ConnFailed, then the LLQ is in bad shape, so we switch to polling mode.
   1217 			if (err != mStatus_ConnFailed)
   1218 				{
   1219 				if (q->LongLived && q->state != LLQ_Poll) StartLLQPolling(m, q);
   1220 				}
   1221 			}
   1222 
   1223 		mDNS_Unlock(m);
   1224 
   1225 		DisposeTCPConn(tcpInfo);
   1226 		}
   1227 	}
   1228 
   1229 mDNSlocal tcpInfo_t *MakeTCPConn(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
   1230 	TCPSocketFlags flags, const mDNSAddr *const Addr, const mDNSIPPort Port, domainname *hostname,
   1231 	DNSQuestion *const question, AuthRecord *const rr)
   1232 	{
   1233 	mStatus err;
   1234 	mDNSIPPort srcport = zeroIPPort;
   1235 	tcpInfo_t *info;
   1236 
   1237 	if ((flags & kTCPSocketFlags_UseTLS) && (!hostname || !hostname->c[0]))
   1238 		{ LogMsg("MakeTCPConn: TLS connection being setup with NULL hostname"); return mDNSNULL; }
   1239 
   1240 	info = (tcpInfo_t *)mDNSPlatformMemAllocate(sizeof(tcpInfo_t));
   1241 	if (!info) { LogMsg("ERROR: MakeTCP - memallocate failed"); return(mDNSNULL); }
   1242 	mDNSPlatformMemZero(info, sizeof(tcpInfo_t));
   1243 
   1244 	info->m          = m;
   1245 	info->sock       = mDNSPlatformTCPSocket(m, flags, &srcport);
   1246 	info->requestLen = 0;
   1247 	info->question   = question;
   1248 	info->rr         = rr;
   1249 	info->Addr       = *Addr;
   1250 	info->Port       = Port;
   1251 	info->reply      = mDNSNULL;
   1252 	info->replylen   = 0;
   1253 	info->nread      = 0;
   1254 	info->numReplies = 0;
   1255 	info->SrcPort = srcport;
   1256 
   1257 	if (msg)
   1258 		{
   1259 		info->requestLen = (int) (end - ((mDNSu8*)msg));
   1260 		mDNSPlatformMemCopy(&info->request, msg, info->requestLen);
   1261 		}
   1262 
   1263 	if (!info->sock) { LogMsg("MakeTCPConn: unable to create TCP socket"); mDNSPlatformMemFree(info); return(mDNSNULL); }
   1264 	err = mDNSPlatformTCPConnect(info->sock, Addr, Port, hostname, (question ? question->InterfaceID : mDNSNULL), tcpCallback, info);
   1265 
   1266 	// Probably suboptimal here.
   1267 	// Instead of returning mDNSNULL here on failure, we should probably invoke the callback with an error code.
   1268 	// That way clients can put all the error handling and retry/recovery code in one place,
   1269 	// instead of having to handle immediate errors in one place and async errors in another.
   1270 	// Also: "err == mStatus_ConnEstablished" probably never happens.
   1271 
   1272 	// Don't need to log "connection failed" in customer builds -- it happens quite often during sleep, wake, configuration changes, etc.
   1273 	if      (err == mStatus_ConnEstablished) { tcpCallback(info->sock, info, mDNStrue, mStatus_NoError); }
   1274 	else if (err != mStatus_ConnPending    ) { LogInfo("MakeTCPConn: connection failed"); DisposeTCPConn(info); return(mDNSNULL); }
   1275 	return(info);
   1276 	}
   1277 
   1278 mDNSexport void DisposeTCPConn(struct tcpInfo_t *tcp)
   1279 	{
   1280 	mDNSPlatformTCPCloseConnection(tcp->sock);
   1281 	if (tcp->reply) mDNSPlatformMemFree(tcp->reply);
   1282 	mDNSPlatformMemFree(tcp);
   1283 	}
   1284 
   1285 // Lock must be held
   1286 mDNSexport void startLLQHandshake(mDNS *m, DNSQuestion *q)
   1287 	{
   1288 	if (mDNSIPv4AddressIsOnes(m->LLQNAT.ExternalAddress))
   1289 		{
   1290 		LogInfo("startLLQHandshake: waiting for NAT status for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
   1291 		q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry in approx 15 minutes
   1292 		q->LastQTime = m->timenow;
   1293 		SetNextQueryTime(m, q);
   1294 		return;
   1295 		}
   1296 
   1297 	// Either we don't have NAT-PMP support (ExternalPort is zero) or behind a Double NAT that may or
   1298 	// may not have NAT-PMP support (NATResult is non-zero)
   1299 	if (mDNSIPPortIsZero(m->LLQNAT.ExternalPort) || m->LLQNAT.Result)
   1300 		{
   1301 		LogInfo("startLLQHandshake: Cannot receive inbound packets; will poll for %##s (%s) External Port %d, NAT Result %d",
   1302 			q->qname.c, DNSTypeName(q->qtype), mDNSVal16(m->LLQNAT.ExternalPort), m->LLQNAT.Result);
   1303 		StartLLQPolling(m, q);
   1304 		return;
   1305 		}
   1306 
   1307 	if (mDNSIPPortIsZero(q->servPort))
   1308 		{
   1309 		debugf("startLLQHandshake: StartGetZoneData for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
   1310 		q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);	// Retry in approx 15 minutes
   1311 		q->LastQTime     = m->timenow;
   1312 		SetNextQueryTime(m, q);
   1313 		q->servAddr = zeroAddr;
   1314 		// We know q->servPort is zero because of check above
   1315 		if (q->nta) CancelGetZoneData(m, q->nta);
   1316 		q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
   1317 		return;
   1318 		}
   1319 
   1320 	if (PrivateQuery(q))
   1321 		{
   1322 		if (q->tcp) LogInfo("startLLQHandshake: Disposing existing TCP connection for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
   1323 		if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
   1324 		if (!q->nta)
   1325 			{
   1326 			// Normally we lookup the zone data and then call this function. And we never free the zone data
   1327 			// for "PrivateQuery". But sometimes this can happen due to some race conditions. When we
   1328 			// switch networks, we might end up "Polling" the network e.g., we are behind a Double NAT.
   1329 			// When we poll, we free the zone information as we send the query to the server (See
   1330 			// PrivateQueryGotZoneData). The NAT callback (LLQNATCallback) may happen soon after that. If we
   1331 			// are still behind Double NAT, we would have returned early in this function. But we could
   1332 			// have switched to a network with no NATs and we should get the zone data again.
   1333 			LogInfo("startLLQHandshake: nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
   1334 			q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
   1335 			return;
   1336 			}
   1337 		else if (!q->nta->Host.c[0])
   1338 			{
   1339 			// This should not happen. If it happens, we print a log and MakeTCPConn will fail if it can't find a hostname
   1340 			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);
   1341 			}
   1342 		q->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
   1343 		if (!q->tcp)
   1344 			q->ThisQInterval = mDNSPlatformOneSecond * 5;	// If TCP failed (transient networking glitch) try again in five seconds
   1345 		else
   1346 			{
   1347 			q->state         = LLQ_SecondaryRequest;		// Right now, for private DNS, we skip the four-way LLQ handshake
   1348 			q->ReqLease      = kLLQ_DefLease;
   1349 			q->ThisQInterval = 0;
   1350 			}
   1351 		q->LastQTime     = m->timenow;
   1352 		SetNextQueryTime(m, q);
   1353 		}
   1354 	else
   1355 		{
   1356 		debugf("startLLQHandshake: m->AdvertisedV4 %#a%s Server %#a:%d%s %##s (%s)",
   1357 			&m->AdvertisedV4,                     mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) ? " (RFC 1918)" : "",
   1358 			&q->servAddr, mDNSVal16(q->servPort), mDNSAddrIsRFC1918(&q->servAddr)             ? " (RFC 1918)" : "",
   1359 			q->qname.c, DNSTypeName(q->qtype));
   1360 
   1361 		if (q->ntries++ >= kLLQ_MAX_TRIES)
   1362 			{
   1363 			LogMsg("startLLQHandshake: %d failed attempts for LLQ %##s Polling.", kLLQ_MAX_TRIES, q->qname.c);
   1364 			StartLLQPolling(m, q);
   1365 			}
   1366 		else
   1367 			{
   1368 			mDNSu8 *end;
   1369 			LLQOptData llqData;
   1370 
   1371 			// set llq rdata
   1372 			llqData.vers  = kLLQ_Vers;
   1373 			llqData.llqOp = kLLQOp_Setup;
   1374 			llqData.err   = LLQErr_NoError;	// Don't need to tell server UDP notification port when sending over UDP
   1375 			llqData.id    = zeroOpaque64;
   1376 			llqData.llqlease = kLLQ_DefLease;
   1377 
   1378 			InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
   1379 			end = putLLQ(&m->omsg, m->omsg.data, q, &llqData);
   1380 			if (!end) { LogMsg("ERROR: startLLQHandshake - putLLQ"); StartLLQPolling(m,q); return; }
   1381 
   1382 			mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
   1383 
   1384 			// update question state
   1385 			q->state         = LLQ_InitialRequest;
   1386 			q->ReqLease      = kLLQ_DefLease;
   1387 			q->ThisQInterval = (kLLQ_INIT_RESEND * mDNSPlatformOneSecond);
   1388 			q->LastQTime     = m->timenow;
   1389 			SetNextQueryTime(m, q);
   1390 			}
   1391 		}
   1392 	}
   1393 
   1394 // forward declaration so GetServiceTarget can do reverse lookup if needed
   1395 mDNSlocal void GetStaticHostname(mDNS *m);
   1396 
   1397 mDNSexport const domainname *GetServiceTarget(mDNS *m, AuthRecord *const rr)
   1398 	{
   1399 	debugf("GetServiceTarget %##s", rr->resrec.name->c);
   1400 
   1401 	if (!rr->AutoTarget)		// If not automatically tracking this host's current name, just return the existing target
   1402 		return(&rr->resrec.rdata->u.srv.target);
   1403 	else
   1404 		{
   1405 #if APPLE_OSX_mDNSResponder
   1406 		DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
   1407 		if (AuthInfo && AuthInfo->AutoTunnel)
   1408 			{
   1409 			// If this AutoTunnel is not yet active, start it now (which entails activating its NAT Traversal request,
   1410 			// which will subsequently advertise the appropriate records when the NAT Traversal returns a result)
   1411 			if (!AuthInfo->AutoTunnelNAT.clientContext && m->AutoTunnelHostAddr.b[0])
   1412 				{
   1413 				LogInfo("GetServiceTarget: Calling SetupLocalAutoTunnelInterface_internal");
   1414 				SetupLocalAutoTunnelInterface_internal(m, mDNStrue);
   1415 				}
   1416 			if (AuthInfo->AutoTunnelHostRecord.namestorage.c[0] == 0) return(mDNSNULL);
   1417 			debugf("GetServiceTarget: Returning %##s", AuthInfo->AutoTunnelHostRecord.namestorage.c);
   1418 			return(&AuthInfo->AutoTunnelHostRecord.namestorage);
   1419 			}
   1420 		else
   1421 #endif // APPLE_OSX_mDNSResponder
   1422 			{
   1423 			const int srvcount = CountLabels(rr->resrec.name);
   1424 			HostnameInfo *besthi = mDNSNULL, *hi;
   1425 			int best = 0;
   1426 			for (hi = m->Hostnames; hi; hi = hi->next)
   1427 				if (hi->arv4.state == regState_Registered || hi->arv4.state == regState_Refresh ||
   1428 					hi->arv6.state == regState_Registered || hi->arv6.state == regState_Refresh)
   1429 					{
   1430 					int x, hostcount = CountLabels(&hi->fqdn);
   1431 					for (x = hostcount < srvcount ? hostcount : srvcount; x > 0 && x > best; x--)
   1432 						if (SameDomainName(SkipLeadingLabels(rr->resrec.name, srvcount - x), SkipLeadingLabels(&hi->fqdn, hostcount - x)))
   1433 							{ best = x; besthi = hi; }
   1434 					}
   1435 
   1436 			if (besthi) return(&besthi->fqdn);
   1437 			}
   1438 		if (m->StaticHostname.c[0]) return(&m->StaticHostname);
   1439 		else GetStaticHostname(m); // asynchronously do reverse lookup for primary IPv4 address
   1440 		LogInfo("GetServiceTarget: Returning NULL for %s", ARDisplayString(m, rr));
   1441 		return(mDNSNULL);
   1442 		}
   1443 	}
   1444 
   1445 mDNSlocal const domainname *PUBLIC_UPDATE_SERVICE_TYPE  = (const domainname*)"\x0B_dns-update"     "\x04_udp";
   1446 mDNSlocal const domainname *PUBLIC_LLQ_SERVICE_TYPE     = (const domainname*)"\x08_dns-llq"        "\x04_udp";
   1447 
   1448 mDNSlocal const domainname *PRIVATE_UPDATE_SERVICE_TYPE = (const domainname*)"\x0F_dns-update-tls" "\x04_tcp";
   1449 mDNSlocal const domainname *PRIVATE_QUERY_SERVICE_TYPE  = (const domainname*)"\x0E_dns-query-tls"  "\x04_tcp";
   1450 mDNSlocal const domainname *PRIVATE_LLQ_SERVICE_TYPE    = (const domainname*)"\x0C_dns-llq-tls"    "\x04_tcp";
   1451 
   1452 #define ZoneDataSRV(X) (\
   1453 	(X)->ZoneService == ZoneServiceUpdate ? ((X)->ZonePrivate ? PRIVATE_UPDATE_SERVICE_TYPE : PUBLIC_UPDATE_SERVICE_TYPE) : \
   1454 	(X)->ZoneService == ZoneServiceQuery  ? ((X)->ZonePrivate ? PRIVATE_QUERY_SERVICE_TYPE  : (const domainname*)""     ) : \
   1455 	(X)->ZoneService == ZoneServiceLLQ    ? ((X)->ZonePrivate ? PRIVATE_LLQ_SERVICE_TYPE    : PUBLIC_LLQ_SERVICE_TYPE   ) : (const domainname*)"")
   1456 
   1457 // Forward reference: GetZoneData_StartQuery references GetZoneData_QuestionCallback, and
   1458 // GetZoneData_QuestionCallback calls GetZoneData_StartQuery
   1459 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype);
   1460 
   1461 // GetZoneData_QuestionCallback is called from normal client callback context (core API calls allowed)
   1462 mDNSlocal void GetZoneData_QuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
   1463 	{
   1464 	ZoneData *zd = (ZoneData*)question->QuestionContext;
   1465 
   1466 	debugf("GetZoneData_QuestionCallback: %s %s", AddRecord ? "Add" : "Rmv", RRDisplayString(m, answer));
   1467 
   1468 	if (!AddRecord) return;												// Don't care about REMOVE events
   1469 	if (AddRecord == QC_addnocache && answer->rdlength == 0) return;	// Don't care about transient failure indications
   1470 	if (answer->rrtype != question->qtype) return;						// Don't care about CNAMEs
   1471 
   1472 	if (answer->rrtype == kDNSType_SOA)
   1473 		{
   1474 		debugf("GetZoneData GOT SOA %s", RRDisplayString(m, answer));
   1475 		mDNS_StopQuery(m, question);
   1476 		if (question->ThisQInterval != -1)
   1477 			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
   1478 		if (answer->rdlength)
   1479 			{
   1480 			AssignDomainName(&zd->ZoneName, answer->name);
   1481 			zd->ZoneClass = answer->rrclass;
   1482 			AssignDomainName(&zd->question.qname, &zd->ZoneName);
   1483 			GetZoneData_StartQuery(m, zd, kDNSType_SRV);
   1484 			}
   1485 		else if (zd->CurrentSOA->c[0])
   1486 			{
   1487 			DomainAuthInfo *AuthInfo = GetAuthInfoForName(m, zd->CurrentSOA);
   1488 			if (AuthInfo && AuthInfo->AutoTunnel)
   1489 				{
   1490 				// To keep the load on the server down, we don't chop down on
   1491 				// SOA lookups for AutoTunnels
   1492 				LogInfo("GetZoneData_QuestionCallback: not chopping labels for %##s", zd->CurrentSOA->c);
   1493 				zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
   1494 				}
   1495 			else
   1496 				{
   1497 				zd->CurrentSOA = (domainname *)(zd->CurrentSOA->c + zd->CurrentSOA->c[0]+1);
   1498 				AssignDomainName(&zd->question.qname, zd->CurrentSOA);
   1499 				GetZoneData_StartQuery(m, zd, kDNSType_SOA);
   1500 				}
   1501 			}
   1502 		else
   1503 			{
   1504 			LogInfo("GetZoneData recursed to root label of %##s without finding SOA", zd->ChildName.c);
   1505 			zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
   1506 			}
   1507 		}
   1508 	else if (answer->rrtype == kDNSType_SRV)
   1509 		{
   1510 		debugf("GetZoneData GOT SRV %s", RRDisplayString(m, answer));
   1511 		mDNS_StopQuery(m, question);
   1512 		if (question->ThisQInterval != -1)
   1513 			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
   1514 // Right now we don't want to fail back to non-encrypted operations
   1515 // If the AuthInfo has the AutoTunnel field set, then we want private or nothing
   1516 // <rdar://problem/5687667> BTMM: Don't fallback to unencrypted operations when SRV lookup fails
   1517 #if 0
   1518 		if (!answer->rdlength && zd->ZonePrivate && zd->ZoneService != ZoneServiceQuery)
   1519 			{
   1520 			zd->ZonePrivate = mDNSfalse;	// Causes ZoneDataSRV() to yield a different SRV name when building the query
   1521 			GetZoneData_StartQuery(m, zd, kDNSType_SRV);		// Try again, non-private this time
   1522 			}
   1523 		else
   1524 #endif
   1525 			{
   1526 			if (answer->rdlength)
   1527 				{
   1528 				AssignDomainName(&zd->Host, &answer->rdata->u.srv.target);
   1529 				zd->Port = answer->rdata->u.srv.port;
   1530 				AssignDomainName(&zd->question.qname, &zd->Host);
   1531 				GetZoneData_StartQuery(m, zd, kDNSType_A);
   1532 				}
   1533 			else
   1534 				{
   1535 				zd->ZonePrivate = mDNSfalse;
   1536 				zd->Host.c[0] = 0;
   1537 				zd->Port = zeroIPPort;
   1538 				zd->Addr = zeroAddr;
   1539 				zd->ZoneDataCallback(m, mStatus_NoError, zd);
   1540 				}
   1541 			}
   1542 		}
   1543 	else if (answer->rrtype == kDNSType_A)
   1544 		{
   1545 		debugf("GetZoneData GOT A %s", RRDisplayString(m, answer));
   1546 		mDNS_StopQuery(m, question);
   1547 		if (question->ThisQInterval != -1)
   1548 			LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
   1549 		zd->Addr.type  = mDNSAddrType_IPv4;
   1550 		zd->Addr.ip.v4 = (answer->rdlength == 4) ? answer->rdata->u.ipv4 : zerov4Addr;
   1551 		// In order to simulate firewalls blocking our outgoing TCP connections, returning immediate ICMP errors or TCP resets,
   1552 		// the code below will make us try to connect to loopback, resulting in an immediate "port unreachable" failure.
   1553 		// This helps us test to make sure we handle this case gracefully
   1554 		// <rdar://problem/5607082> BTMM: mDNSResponder taking 100 percent CPU after upgrading to 10.5.1
   1555 #if 0
   1556 		zd->Addr.ip.v4.b[0] = 127;
   1557 		zd->Addr.ip.v4.b[1] = 0;
   1558 		zd->Addr.ip.v4.b[2] = 0;
   1559 		zd->Addr.ip.v4.b[3] = 1;
   1560 #endif
   1561 		// The caller needs to free the memory when done with zone data
   1562 		zd->ZoneDataCallback(m, mStatus_NoError, zd);
   1563 		}
   1564 	}
   1565 
   1566 // GetZoneData_StartQuery is called from normal client context (lock not held, or client callback)
   1567 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype)
   1568 	{
   1569 	if (qtype == kDNSType_SRV)
   1570 		{
   1571 		AssignDomainName(&zd->question.qname, ZoneDataSRV(zd));
   1572 		AppendDomainName(&zd->question.qname, &zd->ZoneName);
   1573 		debugf("lookupDNSPort %##s", zd->question.qname.c);
   1574 		}
   1575 
   1576 	// CancelGetZoneData can get called at any time. We should stop the question if it has not been
   1577 	// stopped already. A value of -1 for ThisQInterval indicates that the question is not active
   1578 	// yet.
   1579 	zd->question.ThisQInterval       = -1;
   1580 	zd->question.InterfaceID         = mDNSInterface_Any;
   1581 	zd->question.Target              = zeroAddr;
   1582 	//zd->question.qname.c[0]        = 0;			// Already set
   1583 	zd->question.qtype               = qtype;
   1584 	zd->question.qclass              = kDNSClass_IN;
   1585 	zd->question.LongLived           = mDNSfalse;
   1586 	zd->question.ExpectUnique        = mDNStrue;
   1587 	zd->question.ForceMCast          = mDNSfalse;
   1588 	zd->question.ReturnIntermed      = mDNStrue;
   1589 	zd->question.SuppressUnusable    = mDNSfalse;
   1590 	zd->question.SearchListIndex     = 0;
   1591 	zd->question.AppendSearchDomains = 0;
   1592 	zd->question.RetryWithSearchDomains = mDNSfalse;
   1593 	zd->question.TimeoutQuestion     = 0;
   1594 	zd->question.WakeOnResolve       = 0;
   1595 	zd->question.qnameOrig           = mDNSNULL;
   1596 	zd->question.QuestionCallback    = GetZoneData_QuestionCallback;
   1597 	zd->question.QuestionContext     = zd;
   1598 
   1599 	//LogMsg("GetZoneData_StartQuery %##s (%s) %p", zd->question.qname.c, DNSTypeName(zd->question.qtype), zd->question.Private);
   1600 	return(mDNS_StartQuery(m, &zd->question));
   1601 	}
   1602 
   1603 // StartGetZoneData is an internal routine (i.e. must be called with the lock already held)
   1604 mDNSexport ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *ZoneDataContext)
   1605 	{
   1606 	DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, name);
   1607 	int initialskip = (AuthInfo && AuthInfo->AutoTunnel) ? DomainNameLength(name) - DomainNameLength(&AuthInfo->domain) : 0;
   1608 	ZoneData *zd = (ZoneData*)mDNSPlatformMemAllocate(sizeof(ZoneData));
   1609 	if (!zd) { LogMsg("ERROR: StartGetZoneData - mDNSPlatformMemAllocate failed"); return mDNSNULL; }
   1610 	mDNSPlatformMemZero(zd, sizeof(ZoneData));
   1611 	AssignDomainName(&zd->ChildName, name);
   1612 	zd->ZoneService      = target;
   1613 	zd->CurrentSOA       = (domainname *)(&zd->ChildName.c[initialskip]);
   1614 	zd->ZoneName.c[0]    = 0;
   1615 	zd->ZoneClass        = 0;
   1616 	zd->Host.c[0]        = 0;
   1617 	zd->Port             = zeroIPPort;
   1618 	zd->Addr             = zeroAddr;
   1619 	zd->ZonePrivate      = AuthInfo && AuthInfo->AutoTunnel ? mDNStrue : mDNSfalse;
   1620 	zd->ZoneDataCallback = callback;
   1621 	zd->ZoneDataContext  = ZoneDataContext;
   1622 
   1623 	zd->question.QuestionContext = zd;
   1624 
   1625 	mDNS_DropLockBeforeCallback();		// GetZoneData_StartQuery expects to be called from a normal callback, so we emulate that here
   1626 	if (AuthInfo && AuthInfo->AutoTunnel && !mDNSIPPortIsZero(AuthInfo->port))
   1627 		{
   1628 		LogInfo("StartGetZoneData: Bypassing SOA, SRV query for %##s", AuthInfo->domain.c);
   1629 		// We bypass SOA and SRV queries if we know the hostname and port already from the configuration.
   1630 		// Today this is only true for AutoTunnel. As we bypass, we need to infer a few things:
   1631 		//
   1632 		// 1. Zone name is the same as the AuthInfo domain
   1633 		// 2. ZoneClass is kDNSClass_IN which should be a safe assumption
   1634 		//
   1635 		// If we want to make this bypass mechanism work for non-AutoTunnels also, (1) has to hold
   1636 		// good. Otherwise, it has to be configured also.
   1637 
   1638 		AssignDomainName(&zd->ZoneName, &AuthInfo->domain);
   1639 		zd->ZoneClass = kDNSClass_IN;
   1640 		AssignDomainName(&zd->Host, &AuthInfo->hostname);
   1641 		zd->Port = AuthInfo->port;
   1642 		AssignDomainName(&zd->question.qname, &zd->Host);
   1643 		GetZoneData_StartQuery(m, zd, kDNSType_A);
   1644 		}
   1645 	else
   1646 		{
   1647 		if (AuthInfo && AuthInfo->AutoTunnel) LogInfo("StartGetZoneData: Not Bypassing SOA, SRV query for %##s", AuthInfo->domain.c);
   1648 		AssignDomainName(&zd->question.qname, zd->CurrentSOA);
   1649 		GetZoneData_StartQuery(m, zd, kDNSType_SOA);
   1650 		}
   1651 	mDNS_ReclaimLockAfterCallback();
   1652 
   1653 	return zd;
   1654 	}
   1655 
   1656 // Returns if the question is a GetZoneData question. These questions are special in
   1657 // that they are created internally while resolving a private query or LLQs.
   1658 mDNSexport mDNSBool IsGetZoneDataQuestion(DNSQuestion *q)
   1659 	{
   1660 	if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNStrue);
   1661 	else return(mDNSfalse);
   1662 	}
   1663 
   1664 // GetZoneData queries are a special case -- even if we have a key for them, we don't do them privately,
   1665 // because that would result in an infinite loop (i.e. to do a private query we first need to get
   1666 // the _dns-query-tls SRV record for the zone, and we can't do *that* privately because to do so
   1667 // we'd need to already know the _dns-query-tls SRV record.
   1668 // Also, as a general rule, we never do SOA queries privately
   1669 mDNSexport DomainAuthInfo *GetAuthInfoForQuestion(mDNS *m, const DNSQuestion *const q)	// Must be called with lock held
   1670 	{
   1671 	if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNSNULL);
   1672 	if (q->qtype            == kDNSType_SOA                ) return(mDNSNULL);
   1673 	return(GetAuthInfoForName_internal(m, &q->qname));
   1674 	}
   1675 
   1676 // ***************************************************************************
   1677 #if COMPILER_LIKES_PRAGMA_MARK
   1678 #pragma mark - host name and interface management
   1679 #endif
   1680 
   1681 mDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr);
   1682 mDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr);
   1683 mDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time);
   1684 
   1685 // When this function is called, service record is already deregistered. We just
   1686 // have to deregister the PTR and TXT records.
   1687 mDNSlocal void UpdateAllServiceRecords(mDNS *const m, AuthRecord *rr, mDNSBool reg)
   1688 	{
   1689 	AuthRecord *r, *srvRR;
   1690 
   1691 	if (rr->resrec.rrtype != kDNSType_SRV) { LogMsg("UpdateAllServiceRecords:ERROR!! ResourceRecord not a service record %s", ARDisplayString(m, rr)); return; }
   1692 
   1693 	if (reg && rr->state == regState_NoTarget) { LogMsg("UpdateAllServiceRecords:ERROR!! SRV record %s in noTarget state during registration", ARDisplayString(m, rr)); return; }
   1694 
   1695 	LogInfo("UpdateAllServiceRecords: ResourceRecord %s", ARDisplayString(m, rr));
   1696 
   1697 	for (r = m->ResourceRecords; r; r=r->next)
   1698 		{
   1699 		if (!AuthRecord_uDNS(r)) continue;
   1700 		srvRR = mDNSNULL;
   1701 		if (r->resrec.rrtype == kDNSType_PTR)
   1702 			srvRR = r->Additional1;
   1703 		else if (r->resrec.rrtype == kDNSType_TXT)
   1704 			srvRR = r->DependentOn;
   1705 		if (srvRR && srvRR->resrec.rrtype != kDNSType_SRV)
   1706 			LogMsg("UpdateAllServiceRecords: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
   1707 		if (srvRR == rr)
   1708 			{
   1709 			if (!reg)
   1710 				{
   1711 				LogInfo("UpdateAllServiceRecords: deregistering %s", ARDisplayString(m, r));
   1712 				r->SRVChanged = mDNStrue;
   1713 				r->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   1714 				r->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   1715 				r->state = regState_DeregPending;
   1716 				}
   1717 			else
   1718 				{
   1719 				// Clearing SRVchanged is a safety measure. If our pevious dereg never
   1720 				// came back and we had a target change, we are starting fresh
   1721 				r->SRVChanged = mDNSfalse;
   1722 				// if it is already registered or in the process of registering, then don't
   1723 				// bother re-registering. This happens today for non-BTMM domains where the
   1724 				// TXT and PTR get registered before SRV records because of the delay in
   1725 				// getting the port mapping. There is no point in re-registering the TXT
   1726 				// and PTR records.
   1727 				if ((r->state == regState_Registered) ||
   1728 				    (r->state == regState_Pending && r->nta && !mDNSIPv4AddressIsZero(r->nta->Addr.ip.v4)))
   1729 					LogInfo("UpdateAllServiceRecords: not registering %s, state %d", ARDisplayString(m, r), r->state);
   1730 				else
   1731 					{
   1732 					LogInfo("UpdateAllServiceRecords: registering %s, state %d", ARDisplayString(m, r), r->state);
   1733 					ActivateUnicastRegistration(m, r);
   1734 					}
   1735 				}
   1736 			}
   1737 		}
   1738 	}
   1739 
   1740 // Called in normal client context (lock not held)
   1741 // Currently only supports SRV records for nat mapping
   1742 mDNSlocal void CompleteRecordNatMap(mDNS *m, NATTraversalInfo *n)
   1743 	{
   1744 	const domainname *target;
   1745 	domainname *srvt;
   1746 	AuthRecord *rr = (AuthRecord *)n->clientContext;
   1747 	debugf("SRVNatMap complete %.4a IntPort %u ExternalPort %u NATLease %u", &n->ExternalAddress, mDNSVal16(n->IntPort), mDNSVal16(n->ExternalPort), n->NATLease);
   1748 
   1749 	if (!rr) { LogMsg("CompleteRecordNatMap called with unknown AuthRecord object"); return; }
   1750 	if (!n->NATLease) { LogMsg("CompleteRecordNatMap No NATLease for %s", ARDisplayString(m, rr)); return; }
   1751 
   1752 	if (rr->resrec.rrtype != kDNSType_SRV) {LogMsg("CompleteRecordNatMap: Not a service record %s", ARDisplayString(m, rr)); return; }
   1753 
   1754 	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) { LogInfo("CompleteRecordNatMap called for %s, Service deregistering", ARDisplayString(m, rr)); return; }
   1755 
   1756 	if (rr->state == regState_DeregPending) { LogInfo("CompleteRecordNatMap called for %s, record in DeregPending", ARDisplayString(m, rr)); return; }
   1757 
   1758 	// As we free the zone info after registering/deregistering with the server (See hndlRecordUpdateReply),
   1759 	// we need to restart the get zone data and nat mapping request to get the latest mapping result as we can't handle it
   1760 	// at this moment. Restart from the beginning.
   1761 	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
   1762 		{
   1763 		LogInfo("CompleteRecordNatMap called for %s but no zone information!", ARDisplayString(m, rr));
   1764 		// We need to clear out the NATinfo state so that it will result in re-acquiring the mapping
   1765 		// and hence this callback called again.
   1766 		if (rr->NATinfo.clientContext)
   1767 			{
   1768 			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
   1769 			rr->NATinfo.clientContext = mDNSNULL;
   1770 			}
   1771 		rr->state = regState_Pending;
   1772 		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   1773 		rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   1774 		return;
   1775 		}
   1776 
   1777 	mDNS_Lock(m);
   1778 	// Reevaluate the target always as Target could have changed while
   1779 	// we were getting the port mapping (See UpdateOneSRVRecord)
   1780 	target = GetServiceTarget(m, rr);
   1781 	srvt = GetRRDomainNameTarget(&rr->resrec);
   1782 	if (!target || target->c[0] == 0 || mDNSIPPortIsZero(n->ExternalPort))
   1783 		{
   1784 		if (target && target->c[0])
   1785 			LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
   1786 		else
   1787 			LogInfo("CompleteRecordNatMap - no target for %##s, ExternalPort %d", rr->resrec.name->c, mDNSVal16(n->ExternalPort));
   1788 		if (srvt) srvt->c[0] = 0;
   1789 		rr->state = regState_NoTarget;
   1790 		rr->resrec.rdlength = rr->resrec.rdestimate = 0;
   1791 		mDNS_Unlock(m);
   1792 		UpdateAllServiceRecords(m, rr, mDNSfalse);
   1793 		return;
   1794 		}
   1795 	LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
   1796 	// This function might get called multiple times during a network transition event. Previosuly, we could
   1797 	// have put the SRV record in NoTarget state above and deregistered all the other records. When this
   1798 	// function gets called again with a non-zero ExternalPort, we need to set the target and register the
   1799 	// other records again.
   1800 	if (srvt && !SameDomainName(srvt, target))
   1801 		{
   1802 		AssignDomainName(srvt, target);
   1803 		SetNewRData(&rr->resrec, mDNSNULL, 0);		// Update rdlength, rdestimate, rdatahash
   1804 		}
   1805 
   1806 	// SRVChanged is set when when the target of the SRV record changes (See UpdateOneSRVRecord).
   1807 	// As a result of the target change, we might register just that SRV Record if it was
   1808 	// previously registered and we have a new target OR deregister SRV (and the associated
   1809 	// PTR/TXT records) if we don't have a target anymore. When we get a response from the server,
   1810 	// SRVChanged state tells that we registered/deregistered because of a target change
   1811 	// and hence handle accordingly e.g., if we deregistered, put the records in NoTarget state OR
   1812 	// if we registered then put it in Registered state.
   1813 	//
   1814 	// Here, we are registering all the records again from the beginning. Treat this as first time
   1815 	// registration rather than a temporary target change.
   1816 	rr->SRVChanged = mDNSfalse;
   1817 
   1818 	// We want IsRecordMergeable to check whether it is a record whose update can be
   1819 	// sent with others. We set the time before we call IsRecordMergeable, so that
   1820 	// it does not fail this record based on time. We are interested in other checks
   1821 	// at this time
   1822 	rr->state = regState_Pending;
   1823 	rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   1824 	rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   1825 	if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
   1826 		// Delay the record registration by MERGE_DELAY_TIME so that we can merge them
   1827 		// into one update
   1828 		rr->LastAPTime += MERGE_DELAY_TIME;
   1829 	mDNS_Unlock(m);
   1830 	// We call this always even though it may not be necessary always e.g., normal registration
   1831 	// process where TXT and PTR gets registered followed by the SRV record after it gets
   1832 	// the port mapping. In that case, UpdateAllServiceRecords handles the optimization. The
   1833 	// update of TXT and PTR record is required if we entered noTargetState before as explained
   1834 	// above.
   1835 	UpdateAllServiceRecords(m, rr, mDNStrue);
   1836 	}
   1837 
   1838 mDNSlocal void StartRecordNatMap(mDNS *m, AuthRecord *rr)
   1839 	{
   1840 	const mDNSu8 *p;
   1841 	mDNSu8 protocol;
   1842 
   1843 	if (rr->resrec.rrtype != kDNSType_SRV)
   1844 		{
   1845 		LogInfo("StartRecordNatMap: Resource Record %##s type %d, not supported", rr->resrec.name->c, rr->resrec.rrtype);
   1846 		return;
   1847 		}
   1848 	p = rr->resrec.name->c;
   1849 	//Assume <Service Instance>.<App Protocol>.<Transport protocol>.<Name>
   1850 	// Skip the first two labels to get to the transport protocol
   1851 	if (p[0]) p += 1 + p[0];
   1852 	if (p[0]) p += 1 + p[0];
   1853 	if      (SameDomainLabel(p, (mDNSu8 *)"\x4" "_tcp")) protocol = NATOp_MapTCP;
   1854 	else if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_udp")) protocol = NATOp_MapUDP;
   1855 	else { LogMsg("StartRecordNatMap: could not determine transport protocol of service %##s", rr->resrec.name->c); return; }
   1856 
   1857 	//LogMsg("StartRecordNatMap: clientContext %p IntPort %d srv.port %d %s",
   1858 	//	rr->NATinfo.clientContext, mDNSVal16(rr->NATinfo.IntPort), mDNSVal16(rr->resrec.rdata->u.srv.port), ARDisplayString(m, rr));
   1859 	if (rr->NATinfo.clientContext) mDNS_StopNATOperation_internal(m, &rr->NATinfo);
   1860 	rr->NATinfo.Protocol       = protocol;
   1861 
   1862 	// Shouldn't be trying to set IntPort here --
   1863 	// BuildUpdateMessage overwrites srs->RR_SRV.resrec.rdata->u.srv.port with external (mapped) port number
   1864 	rr->NATinfo.IntPort        = rr->resrec.rdata->u.srv.port;
   1865 	rr->NATinfo.RequestedPort  = rr->resrec.rdata->u.srv.port;
   1866 	rr->NATinfo.NATLease       = 0;		// Request default lease
   1867 	rr->NATinfo.clientCallback = CompleteRecordNatMap;
   1868 	rr->NATinfo.clientContext  = rr;
   1869 	mDNS_StartNATOperation_internal(m, &rr->NATinfo);
   1870 	}
   1871 
   1872 // Unlink an Auth Record from the m->ResourceRecords list.
   1873 // When a resource record enters regState_NoTarget initially, mDNS_Register_internal
   1874 // does not initialize completely e.g., it cannot check for duplicates etc. The resource
   1875 // record is temporarily left in the ResourceRecords list so that we can initialize later
   1876 // when the target is resolvable. Similarly, when host name changes, we enter regState_NoTarget
   1877 // and we do the same.
   1878 
   1879 // This UnlinkResourceRecord routine is very worrying. It bypasses all the normal cleanup performed
   1880 // by mDNS_Deregister_internal and just unceremoniously cuts the record from the active list.
   1881 // This is why re-regsitering this record was producing syslog messages like this:
   1882 // "Error! Tried to add a NAT traversal that's already in the active list"
   1883 // Right now UnlinkResourceRecord is fortunately only called by RegisterAllServiceRecords,
   1884 // which then immediately calls mDNS_Register_internal to re-register the record, which probably
   1885 // masked more serious problems. Any other use of UnlinkResourceRecord is likely to lead to crashes.
   1886 // For now we'll workaround that specific problem by explicitly calling mDNS_StopNATOperation_internal,
   1887 // but long-term we should either stop cancelling the record registration and then re-registering it,
   1888 // or if we really do need to do this for some reason it should be done via the usual
   1889 // mDNS_Deregister_internal path instead of just cutting the record from the list.
   1890 
   1891 mDNSlocal mStatus UnlinkResourceRecord(mDNS *const m, AuthRecord *const rr)
   1892 	{
   1893 	AuthRecord **list = &m->ResourceRecords;
   1894 	while (*list && *list != rr) list = &(*list)->next;
   1895 	if (*list)
   1896 		{
   1897 		*list = rr->next;
   1898 		rr->next = mDNSNULL;
   1899 
   1900 		// Temporary workaround to cancel any active NAT mapping operation
   1901 		if (rr->NATinfo.clientContext)
   1902 			{
   1903 			mDNS_StopNATOperation_internal(m, &rr->NATinfo);
   1904 			rr->NATinfo.clientContext = mDNSNULL;
   1905 			if (rr->resrec.rrtype == kDNSType_SRV) rr->resrec.rdata->u.srv.port = rr->NATinfo.IntPort;
   1906 			}
   1907 
   1908 		return(mStatus_NoError);
   1909 		}
   1910 	LogMsg("UnlinkResourceRecord:ERROR!! - no such active record %##s", rr->resrec.name->c);
   1911 	return(mStatus_NoSuchRecord);
   1912 	}
   1913 
   1914 // We need to go through mDNS_Register again as we did not complete the
   1915 // full initialization last time e.g., duplicate checks.
   1916 // After we register, we will be in regState_GetZoneData.
   1917 mDNSlocal void RegisterAllServiceRecords(mDNS *const m, AuthRecord *rr)
   1918 	{
   1919 	LogInfo("RegisterAllServiceRecords: Service Record %##s", rr->resrec.name->c);
   1920 	// First Register the service record, we do this differently from other records because
   1921 	// when it entered NoTarget state, it did not go through complete initialization
   1922 	rr->SRVChanged = mDNSfalse;
   1923 	UnlinkResourceRecord(m, rr);
   1924 	mDNS_Register_internal(m, rr);
   1925 	// Register the other records
   1926 	UpdateAllServiceRecords(m, rr, mDNStrue);
   1927 	}
   1928 
   1929 // Called with lock held
   1930 mDNSlocal void UpdateOneSRVRecord(mDNS *m, AuthRecord *rr)
   1931 	{
   1932 	// Target change if:
   1933 	// We have a target and were previously waiting for one, or
   1934 	// We had a target and no longer do, or
   1935 	// The target has changed
   1936 
   1937 	domainname *curtarget = &rr->resrec.rdata->u.srv.target;
   1938 	const domainname *const nt = GetServiceTarget(m, rr);
   1939 	const domainname *const newtarget = nt ? nt : (domainname*)"";
   1940 	mDNSBool TargetChanged = (newtarget->c[0] && rr->state == regState_NoTarget) || !SameDomainName(curtarget, newtarget);
   1941 	mDNSBool HaveZoneData  = rr->nta && !mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4);
   1942 
   1943 	// Nat state change if:
   1944 	// We were behind a NAT, and now we are behind a new NAT, or
   1945 	// We're not behind a NAT but our port was previously mapped to a different external port
   1946 	// We were not behind a NAT and now we are
   1947 
   1948 	mDNSIPPort port        = rr->resrec.rdata->u.srv.port;
   1949 	mDNSBool NowNeedNATMAP = (rr->AutoTarget == Target_AutoHostAndNATMAP && !mDNSIPPortIsZero(port) && mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && rr->nta && !mDNSAddrIsRFC1918(&rr->nta->Addr));
   1950 	mDNSBool WereBehindNAT = (rr->NATinfo.clientContext != mDNSNULL);
   1951 	mDNSBool PortWasMapped = (rr->NATinfo.clientContext && !mDNSSameIPPort(rr->NATinfo.RequestedPort, port));		// I think this is always false -- SC Sept 07
   1952 	mDNSBool NATChanged    = (!WereBehindNAT && NowNeedNATMAP) || (!NowNeedNATMAP && PortWasMapped);
   1953 
   1954 	(void)HaveZoneData; //unused
   1955 
   1956 	LogInfo("UpdateOneSRVRecord: Resource Record %s TargetChanged %d, NewTarget %##s", ARDisplayString(m, rr), TargetChanged, nt->c);
   1957 
   1958 	debugf("UpdateOneSRVRecord: %##s newtarget %##s TargetChanged %d HaveZoneData %d port %d NowNeedNATMAP %d WereBehindNAT %d PortWasMapped %d NATChanged %d",
   1959 		rr->resrec.name->c, newtarget,
   1960 		TargetChanged, HaveZoneData, mDNSVal16(port), NowNeedNATMAP, WereBehindNAT, PortWasMapped, NATChanged);
   1961 
   1962 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
   1963 		LogMsg("UpdateOneSRVRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
   1964 
   1965 	if (!TargetChanged && !NATChanged) return;
   1966 
   1967 	// If we are deregistering the record, then ignore any NAT/Target change.
   1968 	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
   1969 		{
   1970 		LogInfo("UpdateOneSRVRecord: Deregistering record, Ignoring TargetChanged %d, NATChanged %d for %##s, state %d", TargetChanged, NATChanged,
   1971 			rr->resrec.name->c, rr->state);
   1972 		return;
   1973 		}
   1974 
   1975 	if (newtarget)
   1976 		LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, newtarget %##s", TargetChanged, NATChanged, rr->resrec.name->c, rr->state, newtarget->c);
   1977 	else
   1978 		LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, null newtarget", TargetChanged, NATChanged, rr->resrec.name->c, rr->state);
   1979 	switch(rr->state)
   1980 		{
   1981 		case regState_NATMap:
   1982 			// In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
   1983 			// or is in the process of, or has already been, deregistered. This assumes that whenever we transition out
   1984 			// of this state, we need to look at the target again.
   1985 			return;
   1986 
   1987 		case regState_UpdatePending:
   1988 			// We are getting a Target change/NAT change while the SRV record is being updated ?
   1989 			// let us not do anything for now.
   1990 			return;
   1991 
   1992 		case regState_NATError:
   1993 			if (!NATChanged) return;
   1994 			// if nat changed, register if we have a target (below)
   1995 
   1996 		case regState_NoTarget:
   1997 			if (!newtarget->c[0])
   1998 				{
   1999 				LogInfo("UpdateOneSRVRecord: No target yet for Resource Record %s", ARDisplayString(m, rr));
   2000 				return;
   2001 				}
   2002 			RegisterAllServiceRecords(m , rr);
   2003 			return;
   2004 		case regState_DeregPending:
   2005 			// We are in DeregPending either because the service was deregistered from above or we handled
   2006 			// a NAT/Target change before and sent the deregistration below. There are a few race conditions
   2007 			// possible
   2008 			//
   2009 			// 1. We are handling a second NAT/Target change while the first dereg is in progress. It is possible
   2010 			//    that first dereg never made it through because there was no network connectivity e.g., disconnecting
   2011 			//    from network triggers this function due to a target change and later connecting to the network
   2012 			//    retriggers this function but the deregistration never made it through yet. Just fall through.
   2013 			//    If there is a target register otherwise deregister.
   2014 			//
   2015 			// 2. While we sent the dereg during a previous NAT/Target change, uDNS_DeregisterRecord gets
   2016 			//    called as part of service deregistration. When the response comes back, we call
   2017 			//    CompleteDeregistration rather than handle NAT/Target change because the record is in
   2018 			//    kDNSRecordTypeDeregistering state.
   2019 			//
   2020 			// 3. If the upper layer deregisters the service, we check for kDNSRecordTypeDeregistering both
   2021 			//    here in this function to avoid handling NAT/Target change and in hndlRecordUpdateReply to call
   2022 			//    CompleteDeregistration instead of handling NAT/Target change. Hence, we are not concerned
   2023 			//    about that case here.
   2024 			//
   2025 			// We just handle case (1) by falling through
   2026 		case regState_Pending:
   2027 		case regState_Refresh:
   2028 		case regState_Registered:
   2029 			// target or nat changed.  deregister service.  upon completion, we'll look for a new target
   2030 			rr->SRVChanged = mDNStrue;
   2031 			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   2032 			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   2033 			if (newtarget->c[0])
   2034 				{
   2035 				LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s, registering with new target %##s",
   2036 					rr->resrec.name->c, newtarget->c);
   2037 				rr->state = regState_Pending;
   2038 				}
   2039 			else
   2040 				{
   2041 				LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s de-registering", rr->resrec.name->c);
   2042 				rr->state = regState_DeregPending;
   2043 				UpdateAllServiceRecords(m, rr, mDNSfalse);
   2044 				}
   2045 			return;
   2046 		case regState_Unregistered:
   2047 		default: LogMsg("UpdateOneSRVRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
   2048 		}
   2049 	}
   2050 
   2051 mDNSexport void UpdateAllSRVRecords(mDNS *m)
   2052 	{
   2053 	m->NextSRVUpdate = 0;
   2054 	LogInfo("UpdateAllSRVRecords %d", m->SleepState);
   2055 
   2056 	if (m->CurrentRecord)
   2057 		LogMsg("UpdateAllSRVRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
   2058 	m->CurrentRecord = m->ResourceRecords;
   2059 	while (m->CurrentRecord)
   2060 		{
   2061 		AuthRecord *rptr = m->CurrentRecord;
   2062 		m->CurrentRecord = m->CurrentRecord->next;
   2063 		if (AuthRecord_uDNS(rptr) && rptr->resrec.rrtype == kDNSType_SRV)
   2064 			UpdateOneSRVRecord(m, rptr);
   2065 		}
   2066 	}
   2067 
   2068 // Forward reference: AdvertiseHostname references HostnameCallback, and HostnameCallback calls AdvertiseHostname
   2069 mDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
   2070 
   2071 // Called in normal client context (lock not held)
   2072 mDNSlocal void hostnameGetPublicAddressCallback(mDNS *m, NATTraversalInfo *n)
   2073 	{
   2074 	HostnameInfo *h = (HostnameInfo *)n->clientContext;
   2075 
   2076 	if (!h) { LogMsg("RegisterHostnameRecord: registration cancelled"); return; }
   2077 
   2078 	if (!n->Result)
   2079 		{
   2080 		if (mDNSIPv4AddressIsZero(n->ExternalAddress) || mDNSv4AddrIsRFC1918(&n->ExternalAddress)) return;
   2081 
   2082 		if (h->arv4.resrec.RecordType)
   2083 			{
   2084 			if (mDNSSameIPv4Address(h->arv4.resrec.rdata->u.ipv4, n->ExternalAddress)) return;	// If address unchanged, do nothing
   2085 			LogInfo("Updating hostname %p %##s IPv4 from %.4a to %.4a (NAT gateway's external address)",n,
   2086 				h->arv4.resrec.name->c, &h->arv4.resrec.rdata->u.ipv4, &n->ExternalAddress);
   2087 			mDNS_Deregister(m, &h->arv4);	// mStatus_MemFree callback will re-register with new address
   2088 			}
   2089 		else
   2090 			{
   2091 			LogInfo("Advertising hostname %##s IPv4 %.4a (NAT gateway's external address)", h->arv4.resrec.name->c, &n->ExternalAddress);
   2092 			h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
   2093 			h->arv4.resrec.rdata->u.ipv4 = n->ExternalAddress;
   2094 			mDNS_Register(m, &h->arv4);
   2095 			}
   2096 		}
   2097 	}
   2098 
   2099 // register record or begin NAT traversal
   2100 mDNSlocal void AdvertiseHostname(mDNS *m, HostnameInfo *h)
   2101 	{
   2102 	if (!mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4) && h->arv4.resrec.RecordType == kDNSRecordTypeUnregistered)
   2103 		{
   2104 		mDNS_SetupResourceRecord(&h->arv4, mDNSNULL, mDNSInterface_Any, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnregistered, AuthRecordAny, HostnameCallback, h);
   2105 		AssignDomainName(&h->arv4.namestorage, &h->fqdn);
   2106 		h->arv4.resrec.rdata->u.ipv4 = m->AdvertisedV4.ip.v4;
   2107 		h->arv4.state = regState_Unregistered;
   2108 		if (mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4))
   2109 			{
   2110 			// If we already have a NAT query active, stop it and restart it to make sure we get another callback
   2111 			if (h->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &h->natinfo);
   2112 			h->natinfo.Protocol         = 0;
   2113 			h->natinfo.IntPort          = zeroIPPort;
   2114 			h->natinfo.RequestedPort    = zeroIPPort;
   2115 			h->natinfo.NATLease         = 0;
   2116 			h->natinfo.clientCallback   = hostnameGetPublicAddressCallback;
   2117 			h->natinfo.clientContext    = h;
   2118 			mDNS_StartNATOperation_internal(m, &h->natinfo);
   2119 			}
   2120 		else
   2121 			{
   2122 			LogInfo("Advertising hostname %##s IPv4 %.4a", h->arv4.resrec.name->c, &m->AdvertisedV4.ip.v4);
   2123 			h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
   2124 			mDNS_Register_internal(m, &h->arv4);
   2125 			}
   2126 		}
   2127 
   2128 	if (!mDNSIPv6AddressIsZero(m->AdvertisedV6.ip.v6) && h->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
   2129 		{
   2130 		mDNS_SetupResourceRecord(&h->arv6, mDNSNULL, mDNSInterface_Any, kDNSType_AAAA, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, HostnameCallback, h);
   2131 		AssignDomainName(&h->arv6.namestorage, &h->fqdn);
   2132 		h->arv6.resrec.rdata->u.ipv6 = m->AdvertisedV6.ip.v6;
   2133 		h->arv6.state = regState_Unregistered;
   2134 		LogInfo("Advertising hostname %##s IPv6 %.16a", h->arv6.resrec.name->c, &m->AdvertisedV6.ip.v6);
   2135 		mDNS_Register_internal(m, &h->arv6);
   2136 		}
   2137 	}
   2138 
   2139 mDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
   2140 	{
   2141 	HostnameInfo *hi = (HostnameInfo *)rr->RecordContext;
   2142 
   2143 	if (result == mStatus_MemFree)
   2144 		{
   2145 		if (hi)
   2146 			{
   2147 			// If we're still in the Hostnames list, update to new address
   2148 			HostnameInfo *i;
   2149 			LogInfo("HostnameCallback: Got mStatus_MemFree for %p %p %s", hi, rr, ARDisplayString(m, rr));
   2150 			for (i = m->Hostnames; i; i = i->next)
   2151 				if (rr == &i->arv4 || rr == &i->arv6)
   2152 					{ mDNS_Lock(m); AdvertiseHostname(m, i); mDNS_Unlock(m); return; }
   2153 
   2154 			// Else, we're not still in the Hostnames list, so free the memory
   2155 			if (hi->arv4.resrec.RecordType == kDNSRecordTypeUnregistered &&
   2156 				hi->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
   2157 				{
   2158 				if (hi->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &hi->natinfo);
   2159 				hi->natinfo.clientContext = mDNSNULL;
   2160 				mDNSPlatformMemFree(hi);	// free hi when both v4 and v6 AuthRecs deallocated
   2161 				}
   2162 			}
   2163 		return;
   2164 		}
   2165 
   2166 	if (result)
   2167 		{
   2168 		// don't unlink or free - we can retry when we get a new address/router
   2169 		if (rr->resrec.rrtype == kDNSType_A)
   2170 			LogMsg("HostnameCallback: Error %d for registration of %##s IP %.4a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
   2171 		else
   2172 			LogMsg("HostnameCallback: Error %d for registration of %##s IP %.16a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
   2173 		if (!hi) { mDNSPlatformMemFree(rr); return; }
   2174 		if (rr->state != regState_Unregistered) LogMsg("Error: HostnameCallback invoked with error code for record not in regState_Unregistered!");
   2175 
   2176 		if (hi->arv4.state == regState_Unregistered &&
   2177 			hi->arv6.state == regState_Unregistered)
   2178 			{
   2179 			// only deliver status if both v4 and v6 fail
   2180 			rr->RecordContext = (void *)hi->StatusContext;
   2181 			if (hi->StatusCallback)
   2182 				hi->StatusCallback(m, rr, result); // client may NOT make API calls here
   2183 			rr->RecordContext = (void *)hi;
   2184 			}
   2185 		return;
   2186 		}
   2187 
   2188 	// register any pending services that require a target
   2189 	mDNS_Lock(m);
   2190 	m->NextSRVUpdate = NonZeroTime(m->timenow);
   2191 	mDNS_Unlock(m);
   2192 
   2193 	// Deliver success to client
   2194 	if (!hi) { LogMsg("HostnameCallback invoked with orphaned address record"); return; }
   2195 	if (rr->resrec.rrtype == kDNSType_A)
   2196 		LogInfo("Registered hostname %##s IP %.4a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
   2197 	else
   2198 		LogInfo("Registered hostname %##s IP %.16a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
   2199 
   2200 	rr->RecordContext = (void *)hi->StatusContext;
   2201 	if (hi->StatusCallback)
   2202 		hi->StatusCallback(m, rr, result); // client may NOT make API calls here
   2203 	rr->RecordContext = (void *)hi;
   2204 	}
   2205 
   2206 mDNSlocal void FoundStaticHostname(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
   2207 	{
   2208 	const domainname *pktname = &answer->rdata->u.name;
   2209 	domainname *storedname = &m->StaticHostname;
   2210 	HostnameInfo *h = m->Hostnames;
   2211 
   2212 	(void)question;
   2213 
   2214 	if (answer->rdlength != 0)
   2215 		LogInfo("FoundStaticHostname: question %##s -> answer %##s (%s)", question->qname.c, answer->rdata->u.name.c, AddRecord ? "ADD" : "RMV");
   2216 	else
   2217 		LogInfo("FoundStaticHostname: question %##s -> answer NULL (%s)", question->qname.c, AddRecord ? "ADD" : "RMV");
   2218 
   2219 	if (AddRecord && answer->rdlength != 0 && !SameDomainName(pktname, storedname))
   2220 		{
   2221 		AssignDomainName(storedname, pktname);
   2222 		while (h)
   2223 			{
   2224 			if (h->arv4.state == regState_Pending || h->arv4.state == regState_NATMap || h->arv6.state == regState_Pending)
   2225 				{
   2226 				// 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
   2227 				m->NextSRVUpdate = NonZeroTime(m->timenow + 5 * mDNSPlatformOneSecond);
   2228 				debugf("FoundStaticHostname: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
   2229 				return;
   2230 				}
   2231 			h = h->next;
   2232 			}
   2233 		mDNS_Lock(m);
   2234 		m->NextSRVUpdate = NonZeroTime(m->timenow);
   2235 		mDNS_Unlock(m);
   2236 		}
   2237 	else if (!AddRecord && SameDomainName(pktname, storedname))
   2238 		{
   2239 		mDNS_Lock(m);
   2240 		storedname->c[0] = 0;
   2241 		m->NextSRVUpdate = NonZeroTime(m->timenow);
   2242 		mDNS_Unlock(m);
   2243 		}
   2244 	}
   2245 
   2246 // Called with lock held
   2247 mDNSlocal void GetStaticHostname(mDNS *m)
   2248 	{
   2249 	char buf[MAX_REVERSE_MAPPING_NAME_V4];
   2250 	DNSQuestion *q = &m->ReverseMap;
   2251 	mDNSu8 *ip = m->AdvertisedV4.ip.v4.b;
   2252 	mStatus err;
   2253 
   2254 	if (m->ReverseMap.ThisQInterval != -1) return; // already running
   2255 	if (mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4)) return;
   2256 
   2257 	mDNSPlatformMemZero(q, sizeof(*q));
   2258 	// Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
   2259 	mDNS_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa.", ip[3], ip[2], ip[1], ip[0]);
   2260 	if (!MakeDomainNameFromDNSNameString(&q->qname, buf)) { LogMsg("Error: GetStaticHostname - bad name %s", buf); return; }
   2261 
   2262 	q->InterfaceID      = mDNSInterface_Any;
   2263 	q->Target           = zeroAddr;
   2264 	q->qtype            = kDNSType_PTR;
   2265 	q->qclass           = kDNSClass_IN;
   2266 	q->LongLived        = mDNSfalse;
   2267 	q->ExpectUnique     = mDNSfalse;
   2268 	q->ForceMCast       = mDNSfalse;
   2269 	q->ReturnIntermed   = mDNStrue;
   2270 	q->SuppressUnusable = mDNSfalse;
   2271 	q->SearchListIndex  = 0;
   2272 	q->AppendSearchDomains = 0;
   2273 	q->RetryWithSearchDomains = mDNSfalse;
   2274 	q->TimeoutQuestion  = 0;
   2275 	q->WakeOnResolve    = 0;
   2276 	q->qnameOrig        = mDNSNULL;
   2277 	q->QuestionCallback = FoundStaticHostname;
   2278 	q->QuestionContext  = mDNSNULL;
   2279 
   2280 	LogInfo("GetStaticHostname: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
   2281 	err = mDNS_StartQuery_internal(m, q);
   2282 	if (err) LogMsg("Error: GetStaticHostname - StartQuery returned error %d", err);
   2283 	}
   2284 
   2285 mDNSexport void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext)
   2286    {
   2287 	HostnameInfo **ptr = &m->Hostnames;
   2288 
   2289 	LogInfo("mDNS_AddDynDNSHostName %##s", fqdn);
   2290 
   2291 	while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
   2292 	if (*ptr) { LogMsg("DynDNSHostName %##s already in list", fqdn->c); return; }
   2293 
   2294 	// allocate and format new address record
   2295 	*ptr = mDNSPlatformMemAllocate(sizeof(**ptr));
   2296 	if (!*ptr) { LogMsg("ERROR: mDNS_AddDynDNSHostName - malloc"); return; }
   2297 
   2298 	mDNSPlatformMemZero(*ptr, sizeof(**ptr));
   2299 	AssignDomainName(&(*ptr)->fqdn, fqdn);
   2300 	(*ptr)->arv4.state     = regState_Unregistered;
   2301 	(*ptr)->arv6.state     = regState_Unregistered;
   2302 	(*ptr)->StatusCallback = StatusCallback;
   2303 	(*ptr)->StatusContext  = StatusContext;
   2304 
   2305 	AdvertiseHostname(m, *ptr);
   2306 	}
   2307 
   2308 mDNSexport void mDNS_RemoveDynDNSHostName(mDNS *m, const domainname *fqdn)
   2309 	{
   2310 	HostnameInfo **ptr = &m->Hostnames;
   2311 
   2312 	LogInfo("mDNS_RemoveDynDNSHostName %##s", fqdn);
   2313 
   2314 	while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
   2315 	if (!*ptr) LogMsg("mDNS_RemoveDynDNSHostName: no such domainname %##s", fqdn->c);
   2316 	else
   2317 		{
   2318 		HostnameInfo *hi = *ptr;
   2319 		// We do it this way because, if we have no active v6 record, the "mDNS_Deregister_internal(m, &hi->arv4);"
   2320 		// below could free the memory, and we have to make sure we don't touch hi fields after that.
   2321 		mDNSBool f4 = hi->arv4.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv4.state != regState_Unregistered;
   2322 		mDNSBool f6 = hi->arv6.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv6.state != regState_Unregistered;
   2323 		if (f4) LogInfo("mDNS_RemoveDynDNSHostName removing v4 %##s", fqdn);
   2324 		if (f6) LogInfo("mDNS_RemoveDynDNSHostName removing v6 %##s", fqdn);
   2325 		*ptr = (*ptr)->next; // unlink
   2326 		if (f4) mDNS_Deregister_internal(m, &hi->arv4, mDNS_Dereg_normal);
   2327 		if (f6) mDNS_Deregister_internal(m, &hi->arv6, mDNS_Dereg_normal);
   2328 		// When both deregistrations complete we'll free the memory in the mStatus_MemFree callback
   2329 		}
   2330 	if (!m->mDNS_busy) LogMsg("mDNS_RemoveDynDNSHostName: ERROR: Lock not held");
   2331 	m->NextSRVUpdate = NonZeroTime(m->timenow);
   2332 	}
   2333 
   2334 // Currently called without holding the lock
   2335 // Maybe we should change that?
   2336 mDNSexport void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *v4addr, const mDNSAddr *v6addr, const mDNSAddr *router)
   2337 	{
   2338 	mDNSBool v4Changed, v6Changed, RouterChanged;
   2339 
   2340 	if (m->mDNS_busy != m->mDNS_reentrancy)
   2341 		LogMsg("mDNS_SetPrimaryInterfaceInfo: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
   2342 
   2343 	if (v4addr && v4addr->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo v4 address - incorrect type.  Discarding. %#a", v4addr); return; }
   2344 	if (v6addr && v6addr->type != mDNSAddrType_IPv6) { LogMsg("mDNS_SetPrimaryInterfaceInfo v6 address - incorrect type.  Discarding. %#a", v6addr); return; }
   2345 	if (router && router->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-v4 router.  Discarding. %#a",        router); return; }
   2346 
   2347 	mDNS_Lock(m);
   2348 
   2349 	v4Changed     = !mDNSSameIPv4Address(m->AdvertisedV4.ip.v4, v4addr ? v4addr->ip.v4 : zerov4Addr);
   2350 	v6Changed     = !mDNSSameIPv6Address(m->AdvertisedV6.ip.v6, v6addr ? v6addr->ip.v6 : zerov6Addr);
   2351 	RouterChanged = !mDNSSameIPv4Address(m->Router.ip.v4,       router ? router->ip.v4 : zerov4Addr);
   2352 
   2353 	if (v4addr && (v4Changed || RouterChanged))
   2354 		debugf("mDNS_SetPrimaryInterfaceInfo: address changed from %#a to %#a", &m->AdvertisedV4, v4addr);
   2355 
   2356 	if (v4addr) m->AdvertisedV4 = *v4addr; else m->AdvertisedV4.ip.v4 = zerov4Addr;
   2357 	if (v6addr) m->AdvertisedV6 = *v6addr; else m->AdvertisedV6.ip.v6 = zerov6Addr;
   2358 	if (router) m->Router       = *router; else m->Router      .ip.v4 = zerov4Addr;
   2359 	// setting router to zero indicates that nat mappings must be reestablished when router is reset
   2360 
   2361 	if (v4Changed || RouterChanged || v6Changed)
   2362 		{
   2363 		HostnameInfo *i;
   2364 		LogInfo("mDNS_SetPrimaryInterfaceInfo: %s%s%s%#a %#a %#a",
   2365 			v4Changed     ? "v4Changed "     : "",
   2366 			RouterChanged ? "RouterChanged " : "",
   2367 			v6Changed     ? "v6Changed "     : "", v4addr, v6addr, router);
   2368 
   2369 		for (i = m->Hostnames; i; i = i->next)
   2370 			{
   2371 			LogInfo("mDNS_SetPrimaryInterfaceInfo updating host name registrations for %##s", i->fqdn.c);
   2372 
   2373 			if (i->arv4.resrec.RecordType > kDNSRecordTypeDeregistering &&
   2374 				!mDNSSameIPv4Address(i->arv4.resrec.rdata->u.ipv4, m->AdvertisedV4.ip.v4))
   2375 				{
   2376 				LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv4));
   2377 				mDNS_Deregister_internal(m, &i->arv4, mDNS_Dereg_normal);
   2378 				}
   2379 
   2380 			if (i->arv6.resrec.RecordType > kDNSRecordTypeDeregistering &&
   2381 				!mDNSSameIPv6Address(i->arv6.resrec.rdata->u.ipv6, m->AdvertisedV6.ip.v6))
   2382 				{
   2383 				LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv6));
   2384 				mDNS_Deregister_internal(m, &i->arv6, mDNS_Dereg_normal);
   2385 				}
   2386 
   2387 			// AdvertiseHostname will only register new address records.
   2388 			// For records still in the process of deregistering it will ignore them, and let the mStatus_MemFree callback handle them.
   2389 			AdvertiseHostname(m, i);
   2390 			}
   2391 
   2392 		if (v4Changed || RouterChanged)
   2393 			{
   2394 			// If we have a non-zero IPv4 address, we should try immediately to see if we have a NAT gateway
   2395 			// If we have no IPv4 address, we don't want to be in quite such a hurry to report failures to our clients
   2396 			// <rdar://problem/6935929> Sleeping server sometimes briefly disappears over Back to My Mac after it wakes up
   2397 			m->ExternalAddress      = zerov4Addr;
   2398 			m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
   2399 			m->retryGetAddr         = m->timenow + (v4addr ? 0 : mDNSPlatformOneSecond * 5);
   2400 			m->NextScheduledNATOp   = m->timenow;
   2401 			m->LastNATMapResultCode = NATErr_None;
   2402 #ifdef _LEGACY_NAT_TRAVERSAL_
   2403 			LNT_ClearState(m);
   2404 #endif // _LEGACY_NAT_TRAVERSAL_
   2405 			LogInfo("mDNS_SetPrimaryInterfaceInfo:%s%s: retryGetAddr in %d %d",
   2406 				v4Changed     ? " v4Changed"     : "",
   2407 				RouterChanged ? " RouterChanged" : "",
   2408 				m->retryGetAddr - m->timenow, m->timenow);
   2409 			}
   2410 
   2411 		if (m->ReverseMap.ThisQInterval != -1) mDNS_StopQuery_internal(m, &m->ReverseMap);
   2412 		m->StaticHostname.c[0] = 0;
   2413 
   2414 		m->NextSRVUpdate = NonZeroTime(m->timenow);
   2415 
   2416 #if APPLE_OSX_mDNSResponder
   2417 		if (RouterChanged)	uuid_generate(m->asl_uuid);
   2418 		UpdateAutoTunnelDomainStatuses(m);
   2419 #endif
   2420 		}
   2421 
   2422 	mDNS_Unlock(m);
   2423 	}
   2424 
   2425 // ***************************************************************************
   2426 #if COMPILER_LIKES_PRAGMA_MARK
   2427 #pragma mark - Incoming Message Processing
   2428 #endif
   2429 
   2430 mDNSlocal mStatus ParseTSIGError(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end, const domainname *const displayname)
   2431 	{
   2432 	const mDNSu8 *ptr;
   2433 	mStatus err = mStatus_NoError;
   2434 	int i;
   2435 
   2436 	ptr = LocateAdditionals(msg, end);
   2437 	if (!ptr) goto finish;
   2438 
   2439 	for (i = 0; i < msg->h.numAdditionals; i++)
   2440 		{
   2441 		ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
   2442 		if (!ptr) goto finish;
   2443 		if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_TSIG)
   2444 			{
   2445 			mDNSu32 macsize;
   2446 			mDNSu8 *rd = m->rec.r.resrec.rdata->u.data;
   2447 			mDNSu8 *rdend = rd + m->rec.r.resrec.rdlength;
   2448 			int alglen = DomainNameLengthLimit(&m->rec.r.resrec.rdata->u.name, rdend);
   2449 			if (alglen > MAX_DOMAIN_NAME) goto finish;
   2450 			rd += alglen;                                       // algorithm name
   2451 			if (rd + 6 > rdend) goto finish;
   2452 			rd += 6;                                            // 48-bit timestamp
   2453 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
   2454 			rd += sizeof(mDNSOpaque16);                         // fudge
   2455 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
   2456 			macsize = mDNSVal16(*(mDNSOpaque16 *)rd);
   2457 			rd += sizeof(mDNSOpaque16);                         // MAC size
   2458 			if (rd + macsize > rdend) goto finish;
   2459 			rd += macsize;
   2460 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
   2461 			rd += sizeof(mDNSOpaque16);                         // orig id
   2462 			if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
   2463 			err = mDNSVal16(*(mDNSOpaque16 *)rd);               // error code
   2464 
   2465 			if      (err == TSIG_ErrBadSig)  { LogMsg("%##s: bad signature", displayname->c);              err = mStatus_BadSig;     }
   2466 			else if (err == TSIG_ErrBadKey)  { LogMsg("%##s: bad key", displayname->c);                    err = mStatus_BadKey;     }
   2467 			else if (err == TSIG_ErrBadTime) { LogMsg("%##s: bad time", displayname->c);                   err = mStatus_BadTime;    }
   2468 			else if (err)                    { LogMsg("%##s: unknown tsig error %d", displayname->c, err); err = mStatus_UnknownErr; }
   2469 			goto finish;
   2470 			}
   2471 		m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
   2472 		}
   2473 
   2474 	finish:
   2475 	m->rec.r.resrec.RecordType = 0;		// Clear RecordType to show we're not still using it
   2476 	return err;
   2477 	}
   2478 
   2479 mDNSlocal mStatus checkUpdateResult(mDNS *const m, const domainname *const displayname, const mDNSu8 rcode, const DNSMessage *const msg, const mDNSu8 *const end)
   2480 	{
   2481 	(void)msg;	// currently unused, needed for TSIG errors
   2482 	if (!rcode) return mStatus_NoError;
   2483 	else if (rcode == kDNSFlag1_RC_YXDomain)
   2484 		{
   2485 		debugf("name in use: %##s", displayname->c);
   2486 		return mStatus_NameConflict;
   2487 		}
   2488 	else if (rcode == kDNSFlag1_RC_Refused)
   2489 		{
   2490 		LogMsg("Update %##s refused", displayname->c);
   2491 		return mStatus_Refused;
   2492 		}
   2493 	else if (rcode == kDNSFlag1_RC_NXRRSet)
   2494 		{
   2495 		LogMsg("Reregister refused (NXRRSET): %##s", displayname->c);
   2496 		return mStatus_NoSuchRecord;
   2497 		}
   2498 	else if (rcode == kDNSFlag1_RC_NotAuth)
   2499 		{
   2500 		// TSIG errors should come with FormErr as per RFC 2845, but BIND 9 sends them with NotAuth so we look here too
   2501 		mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
   2502 		if (!tsigerr)
   2503 			{
   2504 			LogMsg("Permission denied (NOAUTH): %##s", displayname->c);
   2505 			return mStatus_UnknownErr;
   2506 			}
   2507 		else return tsigerr;
   2508 		}
   2509 	else if (rcode == kDNSFlag1_RC_FormErr)
   2510 		{
   2511 		mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
   2512 		if (!tsigerr)
   2513 			{
   2514 			LogMsg("Format Error: %##s", displayname->c);
   2515 			return mStatus_UnknownErr;
   2516 			}
   2517 		else return tsigerr;
   2518 		}
   2519 	else
   2520 		{
   2521 		LogMsg("Update %##s failed with rcode %d", displayname->c, rcode);
   2522 		return mStatus_UnknownErr;
   2523 		}
   2524 	}
   2525 
   2526 // We add three Additional Records for unicast resource record registrations
   2527 // which is a function of AuthInfo and AutoTunnel properties
   2528 mDNSlocal mDNSu32 RRAdditionalSize(mDNS *const m, DomainAuthInfo *AuthInfo)
   2529 	{
   2530 	mDNSu32 leaseSize, hinfoSize, tsigSize;
   2531 	mDNSu32 rr_base_size = 10; // type (2) class (2) TTL (4) rdlength (2)
   2532 
   2533 	// OPT RR : Emptyname(.) + base size + rdataOPT
   2534 	leaseSize = 1 + rr_base_size + sizeof(rdataOPT);
   2535 
   2536 	// HINFO: Resource Record Name + base size + RDATA
   2537 	// HINFO is added only for autotunnels
   2538 	hinfoSize = 0;
   2539 	if (AuthInfo && AuthInfo->AutoTunnel)
   2540 		hinfoSize = (m->hostlabel.c[0] + 1) + DomainNameLength(&AuthInfo->domain) +
   2541 			rr_base_size + (2 + m->HIHardware.c[0] + m->HISoftware.c[0]);
   2542 
   2543 	//TSIG: Resource Record Name + base size + RDATA
   2544 	// RDATA:
   2545     // 	Algorithm name: hmac-md5.sig-alg.reg.int (8+7+3+3 + 5 bytes for length = 26 bytes)
   2546     // 	Time: 6 bytes
   2547 	// 	Fudge: 2 bytes
   2548     // 	Mac Size: 2 bytes
   2549 	// 	Mac: 16 bytes
   2550 	// 	ID: 2 bytes
   2551     // 	Error: 2 bytes
   2552     // 	Len: 2 bytes
   2553 	// 	Total: 58 bytes
   2554 	tsigSize = 0;
   2555 	if (AuthInfo) tsigSize = DomainNameLength(&AuthInfo->keyname) + rr_base_size + 58;
   2556 
   2557 	return (leaseSize + hinfoSize + tsigSize);
   2558 	}
   2559 
   2560 //Note: Make sure that RREstimatedSize is updated accordingly if anything that is done here
   2561 //would modify rdlength/rdestimate
   2562 mDNSlocal mDNSu8* BuildUpdateMessage(mDNS *const m, mDNSu8 *ptr, AuthRecord *rr, mDNSu8 *limit)
   2563 	{
   2564 	//If this record is deregistering, then just send the deletion record
   2565 	if (rr->state == regState_DeregPending)
   2566 		{
   2567 		rr->expire = 0;		// Indicate that we have no active registration any more
   2568 		ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit);
   2569 		if (!ptr) goto exit;
   2570 		return ptr;
   2571 		}
   2572 
   2573 	// This is a common function to both sending an update in a group or individual
   2574 	// records separately. Hence, we change the state here.
   2575 	if (rr->state == regState_Registered) rr->state = regState_Refresh;
   2576 	if (rr->state != regState_Refresh && rr->state != regState_UpdatePending)
   2577 		rr->state = regState_Pending;
   2578 
   2579 	// For Advisory records like e.g., _services._dns-sd, which is shared, don't send goodbyes as multiple
   2580 	// host might be registering records and deregistering from one does not make sense
   2581 	if (rr->resrec.RecordType != kDNSRecordTypeAdvisory) rr->RequireGoodbye = mDNStrue;
   2582 
   2583 	if ((rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHostAndNATMAP) &&
   2584 		!mDNSIPPortIsZero(rr->NATinfo.ExternalPort))
   2585 		{
   2586 		rr->resrec.rdata->u.srv.port = rr->NATinfo.ExternalPort;
   2587 		}
   2588 
   2589 	if (rr->state == regState_UpdatePending)
   2590 		{
   2591 		// delete old RData
   2592 		SetNewRData(&rr->resrec, rr->OrigRData, rr->OrigRDLen);
   2593 		if (!(ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit))) goto exit; // delete old rdata
   2594 
   2595 		// add new RData
   2596 		SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
   2597 		if (!(ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit)))  goto exit;
   2598 		}
   2599 	else
   2600 		{
   2601 		if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
   2602 			{
   2603 			// KnownUnique : Delete any previous value
   2604 			// For Unicast registrations, we don't verify that it is unique, but set to verified and hence we want to
   2605 			// delete any previous value
   2606 			ptr = putDeleteRRSetWithLimit(&m->omsg, ptr, rr->resrec.name, rr->resrec.rrtype, limit);
   2607 			if (!ptr) goto exit;
   2608 			}
   2609 		else if (rr->resrec.RecordType != kDNSRecordTypeShared)
   2610 			{
   2611 			// For now don't do this, until we have the logic for intelligent grouping of individual records into logical service record sets
   2612 			//ptr = putPrereqNameNotInUse(rr->resrec.name, &m->omsg, ptr, end);
   2613 			if (!ptr) goto exit;
   2614 			}
   2615 
   2616 		ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
   2617 		if (!ptr) goto exit;
   2618 		}
   2619 
   2620 	return ptr;
   2621 exit:
   2622 	LogMsg("BuildUpdateMessage: Error formatting message for %s", ARDisplayString(m, rr));
   2623 	return mDNSNULL;
   2624 	}
   2625 
   2626 // Called with lock held
   2627 mDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr)
   2628 	{
   2629 	mDNSu8 *ptr = m->omsg.data;
   2630 	mStatus err = mStatus_UnknownErr;
   2631 	mDNSu8 *limit;
   2632 	DomainAuthInfo *AuthInfo;
   2633 
   2634 	// For the ability to register large TXT records, we limit the single record registrations
   2635 	// to AbsoluteMaxDNSMessageData
   2636 	limit = ptr + AbsoluteMaxDNSMessageData;
   2637 
   2638 	AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
   2639 	limit -= RRAdditionalSize(m, AuthInfo);
   2640 
   2641 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
   2642 		LogMsg("SendRecordRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
   2643 
   2644 	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
   2645 		{
   2646 		// We never call this function when there is no zone information . Log a message if it ever happens.
   2647 		LogMsg("SendRecordRegistration: No Zone information, should not happen %s", ARDisplayString(m, rr));
   2648 		return;
   2649 		}
   2650 
   2651 	rr->updateid = mDNS_NewMessageID(m);
   2652 	InitializeDNSMessage(&m->omsg.h, rr->updateid, UpdateReqFlags);
   2653 
   2654 	// set zone
   2655 	ptr = putZone(&m->omsg, ptr, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
   2656 	if (!ptr) goto exit;
   2657 
   2658 	if (!(ptr = BuildUpdateMessage(m, ptr, rr, limit))) goto exit;
   2659 
   2660 	if (rr->uselease)
   2661 		{
   2662 		ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
   2663 		if (!ptr) goto exit;
   2664 		}
   2665 	if (rr->Private)
   2666 		{
   2667 		LogInfo("SendRecordRegistration TCP %p %s", rr->tcp, ARDisplayString(m, rr));
   2668 		if (rr->tcp) LogInfo("SendRecordRegistration: Disposing existing TCP connection for %s", ARDisplayString(m, rr));
   2669 		if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
   2670 		if (!rr->nta) { LogMsg("SendRecordRegistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
   2671 		rr->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &rr->nta->Addr, rr->nta->Port, &rr->nta->Host, mDNSNULL, rr);
   2672 		}
   2673 	else
   2674 		{
   2675 		LogInfo("SendRecordRegistration UDP %s", ARDisplayString(m, rr));
   2676 		if (!rr->nta) { LogMsg("SendRecordRegistration:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
   2677 		err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &rr->nta->Addr, rr->nta->Port, mDNSNULL, GetAuthInfoForName_internal(m, rr->resrec.name));
   2678 		if (err) debugf("ERROR: SendRecordRegistration - mDNSSendDNSMessage - %d", err);
   2679 		}
   2680 
   2681 	SetRecordRetry(m, rr, 0);
   2682 	return;
   2683 exit:
   2684 	LogMsg("SendRecordRegistration: Error formatting message for %s, disabling further updates", ARDisplayString(m, rr));
   2685 	// Disable this record from future updates
   2686 	rr->state = regState_NoTarget;
   2687 	}
   2688 
   2689 // Is the given record "rr" eligible for merging ?
   2690 mDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time)
   2691 	{
   2692 	DomainAuthInfo *info;
   2693 	(void) m; //unused
   2694 	// A record is eligible for merge, if the following properties are met.
   2695 	//
   2696 	// 1. uDNS Resource Record
   2697 	// 2. It is time to send them now
   2698 	// 3. It is in proper state
   2699 	// 4. Update zone has been resolved
   2700 	// 5. if DomainAuthInfo exists for the zone, it should not be soon deleted
   2701 	// 6. Zone information is present
   2702 	// 7. Update server is not zero
   2703 	// 8. It has a non-null zone
   2704 	// 9. It uses a lease option
   2705 	// 10. DontMerge is not set
   2706 	//
   2707 	// Following code is implemented as separate "if" statements instead of one "if" statement
   2708 	// is for better debugging purposes e.g., we know exactly what failed if debugging turned on.
   2709 
   2710 	if (!AuthRecord_uDNS(rr)) return mDNSfalse;
   2711 
   2712 	if (rr->LastAPTime + rr->ThisAPInterval - time > 0)
   2713 		{ debugf("IsRecordMergeable: Time %d not reached for %s", rr->LastAPTime + rr->ThisAPInterval - m->timenow, ARDisplayString(m, rr)); return mDNSfalse; }
   2714 
   2715 	if (!rr->zone) return mDNSfalse;
   2716 
   2717 	info = GetAuthInfoForName_internal(m, rr->zone);
   2718 
   2719 	if (info && info->deltime && m->timenow - info->deltime >= 0) {debugf("IsRecordMergeable: Domain %##s will be deleted soon", info->domain.c); return mDNSfalse;}
   2720 
   2721 	if (rr->state != regState_DeregPending && rr->state != regState_Pending && rr->state != regState_Registered && rr->state != regState_Refresh && rr->state != regState_UpdatePending)
   2722 		{ debugf("IsRecordMergeable: state %d not right  %s", rr->state, ARDisplayString(m, rr)); return mDNSfalse; }
   2723 
   2724 	if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4)) return mDNSfalse;
   2725 
   2726 	if (!rr->uselease) return mDNSfalse;
   2727 
   2728 	if (rr->mState == mergeState_DontMerge) {debugf("IsRecordMergeable Dontmerge true %s", ARDisplayString(m, rr));return mDNSfalse;}
   2729 	debugf("IsRecordMergeable: Returning true for %s", ARDisplayString(m, rr));
   2730 	return mDNStrue;
   2731 	}
   2732 
   2733 // Is the resource record "rr" eligible to merge to with "currentRR" ?
   2734 mDNSlocal mDNSBool AreRecordsMergeable(mDNS *const m, AuthRecord *currentRR, AuthRecord *rr, mDNSs32 time)
   2735 	{
   2736 	// A record is eligible to merge with another record as long it is eligible for merge in itself
   2737 	// and it has the same zone information as the other record
   2738 	if (!IsRecordMergeable(m, rr, time)) return mDNSfalse;
   2739 
   2740 	if (!SameDomainName(currentRR->zone, rr->zone))
   2741 		{ debugf("AreRecordMergeable zone mismatch current rr Zone %##s, rr zone  %##s", currentRR->zone->c, rr->zone->c); return mDNSfalse; }
   2742 
   2743 	if (!mDNSSameIPv4Address(currentRR->nta->Addr.ip.v4, rr->nta->Addr.ip.v4)) return mDNSfalse;
   2744 
   2745 	if (!mDNSSameIPPort(currentRR->nta->Port, rr->nta->Port)) return mDNSfalse;
   2746 
   2747 	debugf("AreRecordsMergeable: Returning true for %s", ARDisplayString(m, rr));
   2748 	return mDNStrue;
   2749 	}
   2750 
   2751 // If we can't build the message successfully because of problems in pre-computing
   2752 // the space, we disable merging for all the current records
   2753 mDNSlocal void RRMergeFailure(mDNS *const m)
   2754 	{
   2755 	AuthRecord *rr;
   2756 	for (rr = m->ResourceRecords; rr; rr = rr->next)
   2757 		{
   2758 		rr->mState = mergeState_DontMerge;
   2759 		rr->SendRNow = mDNSNULL;
   2760 		// Restarting the registration is much simpler than saving and restoring
   2761 		// the exact time
   2762 		ActivateUnicastRegistration(m, rr);
   2763 		}
   2764 	}
   2765 
   2766 mDNSlocal void SendGroupRRMessage(mDNS *const m, AuthRecord *anchorRR, mDNSu8 *ptr, DomainAuthInfo *info)
   2767 	{
   2768 	mDNSu8 *limit;
   2769 	if (!anchorRR) {debugf("SendGroupRRMessage: Could not merge records"); return;}
   2770 
   2771 	if (info && info->AutoTunnel) limit = m->omsg.data + AbsoluteMaxDNSMessageData;
   2772 	else limit = m->omsg.data + NormalMaxDNSMessageData;
   2773 
   2774 	// This has to go in the additional section and hence need to be done last
   2775 	ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
   2776 	if (!ptr)
   2777 		{
   2778 		LogMsg("SendGroupRRMessage: ERROR: Could not put lease option, failing the group registration");
   2779 		// if we can't put the lease, we need to undo the merge
   2780 		RRMergeFailure(m);
   2781 		return;
   2782 		}
   2783 	if (anchorRR->Private)
   2784 		{
   2785 		if (anchorRR->tcp) debugf("SendGroupRRMessage: Disposing existing TCP connection for %s", ARDisplayString(m, anchorRR));
   2786 		if (anchorRR->tcp) { DisposeTCPConn(anchorRR->tcp); anchorRR->tcp = mDNSNULL; }
   2787 		if (!anchorRR->nta) { LogMsg("SendGroupRRMessage:ERROR!! nta is NULL for %s", ARDisplayString(m, anchorRR)); return; }
   2788 		anchorRR->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &anchorRR->nta->Addr, anchorRR->nta->Port, &anchorRR->nta->Host, mDNSNULL, anchorRR);
   2789 		if (!anchorRR->tcp) LogInfo("SendGroupRRMessage: Cannot establish TCP connection for %s", ARDisplayString(m, anchorRR));
   2790 		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);
   2791 		}
   2792 	else
   2793 		{
   2794 		mStatus err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &anchorRR->nta->Addr, anchorRR->nta->Port, mDNSNULL, info);
   2795 		if (err) LogInfo("SendGroupRRMessage: Cannot send UDP message for %s", ARDisplayString(m, anchorRR));
   2796 		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);
   2797 		}
   2798 	return;
   2799 	}
   2800 
   2801 // As we always include the zone information and the resource records contain zone name
   2802 // at the end, it will get compressed. Hence, we subtract zoneSize and add two bytes for
   2803 // the compression pointer
   2804 mDNSlocal mDNSu32 RREstimatedSize(AuthRecord *rr, int zoneSize)
   2805 	{
   2806 	int rdlength;
   2807 
   2808 	// Note: Estimation of the record size has to mirror the logic in BuildUpdateMessage, otherwise estimation
   2809 	// would be wrong. Currently BuildUpdateMessage calls SetNewRData in UpdatePending case. Hence, we need
   2810 	// to account for that here. Otherwise, we might under estimate the size.
   2811 	if (rr->state == regState_UpdatePending)
   2812 		// old RData that will be deleted
   2813 		// new RData that will be added
   2814 		rdlength = rr->OrigRDLen + rr->InFlightRDLen;
   2815 	else
   2816 		rdlength = rr->resrec.rdestimate;
   2817 
   2818 	if (rr->state == regState_DeregPending)
   2819 		{
   2820 		debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
   2821 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
   2822 		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
   2823 		}
   2824 
   2825 	// For SRV, TXT, AAAA etc. that are Unique/Verified, we also send a Deletion Record
   2826 	if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
   2827 		{
   2828 		// Deletion Record: Resource Record Name + Base size (10) + 0
   2829 		// Record: Resource Record Name (Compressed = 2) + Base size (10) + rdestimate
   2830 
   2831 		debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
   2832 				rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
   2833 		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + 2 + 10 + rdlength;
   2834 		}
   2835 	else
   2836 		{
   2837 		return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
   2838 		}
   2839 	}
   2840 
   2841 mDNSlocal AuthRecord *MarkRRForSending(mDNS *const m)
   2842 	{
   2843 	AuthRecord *rr;
   2844 	AuthRecord *firstRR = mDNSNULL;
   2845 
   2846 	// Look for records that needs to be sent in the next two seconds (MERGE_DELAY_TIME is set to 1 second).
   2847 	// The logic is as follows.
   2848 	//
   2849 	// 1. Record 1 finishes getting zone data and its registration gets delayed by 1 second
   2850 	// 2. Record 2 comes 0.1 second later, finishes getting its zone data and its registration is also delayed by
   2851 	//    1 second which is now scheduled at 1.1 second
   2852 	//
   2853 	// By looking for 1 second into the future (m->timenow + MERGE_DELAY_TIME below does that) we have merged both
   2854 	// of the above records. Note that we can't look for records too much into the future as this will affect the
   2855 	// retry logic. The first retry is scheduled at 3 seconds. Hence, we should always look smaller than that.
   2856 	// Anything more than one second will affect the first retry to happen sooner.
   2857 	//
   2858 	// Note: As a side effect of looking one second into the future to facilitate merging, the retries happen
   2859 	// one second sooner.
   2860 	for (rr = m->ResourceRecords; rr; rr = rr->next)
   2861 		{
   2862 		if (!firstRR)
   2863 			{
   2864 			if (!IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME)) continue;
   2865 			firstRR = rr;
   2866 			}
   2867 		else if (!AreRecordsMergeable(m, firstRR, rr, m->timenow + MERGE_DELAY_TIME)) continue;
   2868 
   2869 		if (rr->SendRNow) LogMsg("MarkRRForSending: Resourcerecord %s already marked for sending", ARDisplayString(m, rr));
   2870 		rr->SendRNow = mDNSInterfaceMark;
   2871 		}
   2872 
   2873 	// We parsed through all records and found something to send. The services/records might
   2874 	// get registered at different times but we want the refreshes to be all merged and sent
   2875 	// as one update. Hence, we accelerate some of the records so that they will sync up in
   2876 	// the future. Look at the records excluding the ones that we have already sent in the
   2877 	// previous pass. If it half way through its scheduled refresh/retransmit, merge them
   2878 	// into this packet.
   2879 	//
   2880 	// Note that we only look at Registered/Refresh state to keep it simple. As we don't know
   2881 	// whether the current update will fit into one or more packets, merging a resource record
   2882 	// (which is in a different state) that has been scheduled for retransmit would trigger
   2883 	// sending more packets.
   2884 	if (firstRR)
   2885 		{
   2886 		int acc = 0;
   2887 		for (rr = m->ResourceRecords; rr; rr = rr->next)
   2888 			{
   2889 			if ((rr->state != regState_Registered && rr->state != regState_Refresh) ||
   2890 				(rr->SendRNow == mDNSInterfaceMark) ||
   2891 				(!AreRecordsMergeable(m, firstRR, rr, m->timenow + rr->ThisAPInterval/2)))
   2892 				continue;
   2893 			rr->SendRNow = mDNSInterfaceMark;
   2894 			acc++;
   2895 			}
   2896 		if (acc) LogInfo("MarkRRForSending: Accelereated %d records", acc);
   2897 		}
   2898 	return firstRR;
   2899 	}
   2900 
   2901 mDNSlocal mDNSBool SendGroupUpdates(mDNS *const m)
   2902 	{
   2903 	mDNSOpaque16 msgid;
   2904 	mDNSs32 spaceleft = 0;
   2905 	mDNSs32 zoneSize, rrSize;
   2906 	mDNSu8 *oldnext; // for debugging
   2907 	mDNSu8 *next = m->omsg.data;
   2908 	AuthRecord *rr;
   2909 	AuthRecord *anchorRR = mDNSNULL;
   2910 	int nrecords = 0;
   2911 	AuthRecord *startRR = m->ResourceRecords;
   2912 	mDNSu8 *limit = mDNSNULL;
   2913 	DomainAuthInfo *AuthInfo = mDNSNULL;
   2914 	mDNSBool sentallRecords = mDNStrue;
   2915 
   2916 
   2917 	// We try to fit as many ResourceRecords as possible in AbsoluteNormal/MaxDNSMessageData. Before we start
   2918 	// putting in resource records, we need to reserve space for a few things. Every group/packet should
   2919 	// have the following.
   2920 	//
   2921 	// 1) Needs space for the Zone information (which needs to be at the beginning)
   2922 	// 2) Additional section MUST have space for lease option, HINFO and TSIG option (which needs to
   2923 	//    to be at the end)
   2924 	//
   2925 	// In future we need to reserve space for the pre-requisites which also goes at the beginning.
   2926 	// To accomodate pre-requisites in the future, first we walk the whole list marking records
   2927 	// that can be sent in this packet and computing the space needed for these records.
   2928 	// For TXT and SRV records, we delete the previous record if any by sending the same
   2929 	// resource record with ANY RDATA and zero rdlen. Hence, we need to have space for both of them.
   2930 
   2931 	while (startRR)
   2932 		{
   2933 		AuthInfo = mDNSNULL;
   2934 		anchorRR = mDNSNULL;
   2935 		nrecords = 0;
   2936 		zoneSize = 0;
   2937 		for (rr = startRR; rr; rr = rr->next)
   2938 			{
   2939 			if (rr->SendRNow != mDNSInterfaceMark) continue;
   2940 
   2941 			rr->SendRNow = mDNSNULL;
   2942 
   2943 			if (!anchorRR)
   2944 				{
   2945 				AuthInfo = GetAuthInfoForName_internal(m, rr->zone);
   2946 
   2947 				// Though we allow single record registrations for UDP to be AbsoluteMaxDNSMessageData (See
   2948 				// SendRecordRegistration) to handle large TXT records, to avoid fragmentation we limit UDP
   2949 				// message to NormalMaxDNSMessageData
   2950 				if (AuthInfo && AuthInfo->AutoTunnel) spaceleft = AbsoluteMaxDNSMessageData;
   2951 				else spaceleft = NormalMaxDNSMessageData;
   2952 
   2953 				next = m->omsg.data;
   2954 				spaceleft -= RRAdditionalSize(m, AuthInfo);
   2955 				if (spaceleft <= 0)
   2956 					{
   2957 					LogMsg("SendGroupUpdates: ERROR!!: spaceleft is zero at the beginning");
   2958 					RRMergeFailure(m);
   2959 					return mDNSfalse;
   2960 					}
   2961 				limit = next + spaceleft;
   2962 
   2963 				// Build the initial part of message before putting in the other records
   2964  				msgid = mDNS_NewMessageID(m);
   2965 				InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
   2966 
   2967 				// We need zone information at the beginning of the packet. Length: ZNAME, ZTYPE(2), ZCLASS(2)
   2968 				// zone has to be non-NULL for a record to be mergeable, hence it is safe to set/ examine zone
   2969 				//without checking for NULL.
   2970 				zoneSize = DomainNameLength(rr->zone) + 4;
   2971 				spaceleft -= zoneSize;
   2972 				if (spaceleft <= 0)
   2973 					{
   2974 					LogMsg("SendGroupUpdates: ERROR no space for zone information, disabling merge");
   2975 					RRMergeFailure(m);
   2976 					return mDNSfalse;
   2977 					}
   2978 				next = putZone(&m->omsg, next, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
   2979 				if (!next)
   2980 					{
   2981 					LogMsg("SendGroupUpdates: ERROR! Cannot put zone, disabling merge");
   2982 					RRMergeFailure(m);
   2983 					return mDNSfalse;
   2984 					}
   2985 				anchorRR = rr;
   2986 				}
   2987 
   2988 			rrSize = RREstimatedSize(rr, zoneSize - 4);
   2989 
   2990 			if ((spaceleft - rrSize) < 0)
   2991 				{
   2992 				// If we can't fit even a single message, skip it, it will be sent separately
   2993 				// in CheckRecordUpdates
   2994 				if (!nrecords)
   2995 					{
   2996 					LogInfo("SendGroupUpdates: Skipping message %s, spaceleft %d, rrSize %d", ARDisplayString(m, rr), spaceleft, rrSize);
   2997 					// Mark this as not sent so that the caller knows about it
   2998 					rr->SendRNow = mDNSInterfaceMark;
   2999 					// We need to remove the merge delay so that we can send it immediately
   3000 					rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   3001 					rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   3002 					rr = rr->next;
   3003 					anchorRR = mDNSNULL;
   3004 					sentallRecords = mDNSfalse;
   3005 					}
   3006 				else
   3007 					{
   3008 					LogInfo("SendGroupUpdates:1: Parsed %d records and sending using %s, spaceleft %d, rrSize %d", nrecords, ARDisplayString(m, anchorRR), spaceleft, rrSize);
   3009 					SendGroupRRMessage(m, anchorRR, next, AuthInfo);
   3010 					}
   3011 				break;		// breaks out of for loop
   3012 				}
   3013 			spaceleft -= rrSize;
   3014 			oldnext = next;
   3015 			LogInfo("SendGroupUpdates: Building a message with resource record %s, next %p, state %d, ttl %d", ARDisplayString(m, rr), next, rr->state, rr->resrec.rroriginalttl);
   3016 			if (!(next = BuildUpdateMessage(m, next, rr, limit)))
   3017 				{
   3018 				// We calculated the space and if we can't fit in, we had some bug in the calculation,
   3019 				// disable merge completely.
   3020 				LogMsg("SendGroupUpdates: ptr NULL while building message with %s", ARDisplayString(m, rr));
   3021 				RRMergeFailure(m);
   3022 				return mDNSfalse;
   3023 				}
   3024 			// If our estimate was higher, adjust to the actual size
   3025 			if ((next - oldnext) > rrSize)
   3026 				LogMsg("SendGroupUpdates: ERROR!! Record size estimation is wrong for %s, Estimate %d, Actual %d, state %d", ARDisplayString(m, rr), rrSize, next - oldnext, rr->state);
   3027 			else { spaceleft += rrSize; spaceleft -= (next - oldnext); }
   3028 
   3029 			nrecords++;
   3030 			// We could have sent an update earlier with this "rr" as anchorRR for which we never got a response.
   3031 			// To preserve ordering, we blow away the previous connection before sending this.
   3032 			if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL;}
   3033 			rr->updateid = msgid;
   3034 
   3035 			// By setting the retry time interval here, we will not be looking at these records
   3036 			// again when we return to CheckGroupRecordUpdates.
   3037 			SetRecordRetry(m, rr, 0);
   3038 			}
   3039 			// Either we have parsed all the records or stopped at "rr" above due to lack of space
   3040 			startRR = rr;
   3041 		}
   3042 
   3043 	if (anchorRR)
   3044 		{
   3045 		LogInfo("SendGroupUpdates: Parsed %d records and sending using %s", nrecords, ARDisplayString(m, anchorRR));
   3046 		SendGroupRRMessage(m, anchorRR, next, AuthInfo);
   3047 		}
   3048 	return sentallRecords;
   3049 	}
   3050 
   3051 // Merge the record registrations and send them as a group only if they
   3052 // have same DomainAuthInfo and hence the same key to put the TSIG
   3053 mDNSlocal void CheckGroupRecordUpdates(mDNS *const m)
   3054 	{
   3055 	AuthRecord *rr, *nextRR;
   3056 	// Keep sending as long as there is at least one record to be sent
   3057 	while (MarkRRForSending(m))
   3058 		{
   3059 		if (!SendGroupUpdates(m))
   3060 			{
   3061 			// if everything that was marked was not sent, send them out individually
   3062 			for (rr = m->ResourceRecords; rr; rr = nextRR)
   3063 				{
   3064 				// SendRecordRegistrtion might delete the rr from list, hence
   3065 				// dereference nextRR before calling the function
   3066 				nextRR = rr->next;
   3067 				if (rr->SendRNow == mDNSInterfaceMark)
   3068 					{
   3069 					// Any records marked for sending should be eligible to be sent out
   3070 					// immediately. Just being cautious
   3071 					if (rr->LastAPTime + rr->ThisAPInterval - m->timenow > 0)
   3072 						{ LogMsg("CheckGroupRecordUpdates: ERROR!! Resourcerecord %s not ready", ARDisplayString(m, rr)); continue; }
   3073 					rr->SendRNow = mDNSNULL;
   3074 					SendRecordRegistration(m, rr);
   3075 					}
   3076 				}
   3077 			}
   3078 		}
   3079 
   3080 	debugf("CheckGroupRecordUpdates: No work, returning");
   3081 	return;
   3082 	}
   3083 
   3084 mDNSlocal void hndlSRVChanged(mDNS *const m, AuthRecord *rr)
   3085 	{
   3086 	// Reevaluate the target always as NAT/Target could have changed while
   3087 	// we were registering/deeregistering
   3088 	domainname *dt;
   3089 	const domainname *target = GetServiceTarget(m, rr);
   3090 	if (!target || target->c[0] == 0)
   3091 		{
   3092 		// we don't have a target, if we just derregistered, then we don't have to do anything
   3093 		if (rr->state == regState_DeregPending)
   3094 			{
   3095 			LogInfo("hndlSRVChanged: SRVChanged, No Target, SRV Deregistered for %##s, state %d", rr->resrec.name->c,
   3096 				rr->state);
   3097 			rr->SRVChanged = mDNSfalse;
   3098 			dt = GetRRDomainNameTarget(&rr->resrec);
   3099 			if (dt) dt->c[0] = 0;
   3100 			rr->state = regState_NoTarget;	// Wait for the next target change
   3101 			rr->resrec.rdlength = rr->resrec.rdestimate = 0;
   3102 			return;
   3103 			}
   3104 
   3105 		// we don't have a target, if we just registered, we need to deregister
   3106 		if (rr->state == regState_Pending)
   3107 			{
   3108 			LogInfo("hndlSRVChanged: SRVChanged, No Target, Deregistering again %##s, state %d", rr->resrec.name->c, rr->state);
   3109 			rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   3110 			rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   3111 			rr->state = regState_DeregPending;
   3112 			return;
   3113 			}
   3114 		LogInfo("hndlSRVChanged: Not in DeregPending or RegPending state %##s, state %d", rr->resrec.name->c, rr->state);
   3115 		}
   3116 	else
   3117 		{
   3118 		// If we were in registered state and SRV changed to NULL, we deregister and come back here
   3119 		// if we have a target, we need to register again.
   3120 		//
   3121 		// if we just registered check to see if it is same. If it is different just re-register the
   3122 		// SRV and its assoicated records
   3123 		//
   3124 		// UpdateOneSRVRecord takes care of re-registering all service records
   3125 		if ((rr->state == regState_DeregPending) ||
   3126 		   (rr->state == regState_Pending && !SameDomainName(target, &rr->resrec.rdata->u.srv.target)))
   3127 			{
   3128 			dt = GetRRDomainNameTarget(&rr->resrec);
   3129 			if (dt) dt->c[0] = 0;
   3130 			rr->state = regState_NoTarget;	// NoTarget will allow us to pick up new target OR nat traversal state
   3131 			rr->resrec.rdlength = rr->resrec.rdestimate = 0;
   3132 			LogInfo("hndlSRVChanged: SRVChanged, Valid Target %##s, Registering all records for %##s, state %d",
   3133 				target->c, rr->resrec.name->c, rr->state);
   3134 			rr->SRVChanged = mDNSfalse;
   3135 			UpdateOneSRVRecord(m, rr);
   3136 			return;
   3137 			}
   3138 		// Target did not change while this record was registering. Hence, we go to
   3139 		// Registered state - the state we started from.
   3140 		if (rr->state == regState_Pending) rr->state = regState_Registered;
   3141 		}
   3142 
   3143 	rr->SRVChanged = mDNSfalse;
   3144 	}
   3145 
   3146 // Called with lock held
   3147 mDNSlocal void hndlRecordUpdateReply(mDNS *m, AuthRecord *rr, mStatus err, mDNSu32 random)
   3148 	{
   3149 	mDNSBool InvokeCallback = mDNStrue;
   3150 	mDNSIPPort UpdatePort = zeroIPPort;
   3151 
   3152 	if (m->mDNS_busy != m->mDNS_reentrancy+1)
   3153 		LogMsg("hndlRecordUpdateReply: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
   3154 
   3155 	LogInfo("hndlRecordUpdateReply: err %d ID %d state %d %s(%p)", err, mDNSVal16(rr->updateid), rr->state, ARDisplayString(m, rr), rr);
   3156 
   3157 	rr->updateError = err;
   3158 #if APPLE_OSX_mDNSResponder
   3159 	if (err == mStatus_BadSig || err == mStatus_BadKey) UpdateAutoTunnelDomainStatuses(m);
   3160 #endif
   3161 
   3162 	SetRecordRetry(m, rr, random);
   3163 
   3164 	rr->updateid = zeroID;	// Make sure that this is not considered as part of a group anymore
   3165 	// Later when need to send an update, we will get the zone data again. Thus we avoid
   3166 	// using stale information.
   3167 	//
   3168 	// Note: By clearing out the zone info here, it also helps better merging of records
   3169 	// in some cases. For example, when we get out regState_NoTarget state e.g., move out
   3170 	// of Double NAT, we want all the records to be in one update. Some BTMM records like
   3171 	// _autotunnel6 and host records are registered/deregistered when NAT state changes.
   3172 	// As they are re-registered the zone information is cleared out. To merge with other
   3173 	// records that might be possibly going out, clearing out the information here helps
   3174 	// as all of them try to get the zone data.
   3175 	if (rr->nta)
   3176 		{
   3177 		// We always expect the question to be stopped when we get a valid response from the server.
   3178 		// If the zone info tries to change during this time, updateid would be different and hence
   3179 		// this response should not have been accepted.
   3180 		if (rr->nta->question.ThisQInterval != -1)
   3181 			LogMsg("hndlRecordUpdateReply: ResourceRecord %s, zone info question %##s (%s) interval %d not -1",
   3182 				ARDisplayString(m, rr), rr->nta->question.qname.c, DNSTypeName(rr->nta->question.qtype), rr->nta->question.ThisQInterval);
   3183 		UpdatePort = rr->nta->Port;
   3184 		CancelGetZoneData(m, rr->nta);
   3185 		rr->nta = mDNSNULL;
   3186 		}
   3187 
   3188 	// If we are deregistering the record, then complete the deregistration. Ignore any NAT/SRV change
   3189 	// that could have happened during that time.
   3190 	if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->state == regState_DeregPending)
   3191 		{
   3192 		debugf("hndlRecordUpdateReply: Received reply for deregister record %##s type %d", rr->resrec.name->c, rr->resrec.rrtype);
   3193 		if (err) LogMsg("ERROR: Deregistration of record %##s type %d failed with error %d",
   3194 						rr->resrec.name->c, rr->resrec.rrtype, err);
   3195 		rr->state = regState_Unregistered;
   3196 		CompleteDeregistration(m, rr);
   3197 		return;
   3198 		}
   3199 
   3200 	// We are returning early without updating the state. When we come back from sleep we will re-register after
   3201 	// re-initializing all the state as though it is a first registration. If the record can't be registered e.g.,
   3202 	// no target, it will be deregistered. Hence, the updating to the right state should not matter when going
   3203 	// to sleep.
   3204 	if (m->SleepState)
   3205 		{
   3206 		// Need to set it to NoTarget state so that RecordReadyForSleep knows that
   3207 		// we are done
   3208 		if (rr->resrec.rrtype == kDNSType_SRV && rr->state == regState_DeregPending)
   3209 			rr->state = regState_NoTarget;
   3210 		return;
   3211 		}
   3212 
   3213 	if (rr->state == regState_UpdatePending)
   3214 		{
   3215 		if (err) LogMsg("Update record failed for %##s (err %d)", rr->resrec.name->c, err);
   3216 		rr->state = regState_Registered;
   3217 		// deallocate old RData
   3218 		if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->OrigRData, rr->OrigRDLen);
   3219 		SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
   3220 		rr->OrigRData = mDNSNULL;
   3221 		rr->InFlightRData = mDNSNULL;
   3222 		}
   3223 
   3224 	if (rr->SRVChanged)
   3225 		{
   3226 		if (rr->resrec.rrtype == kDNSType_SRV)
   3227 			hndlSRVChanged(m, rr);
   3228 		else
   3229 			{
   3230 			LogInfo("hndlRecordUpdateReply: Deregistered %##s (%s), state %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->state);
   3231 			rr->SRVChanged = mDNSfalse;
   3232 			if (rr->state != regState_DeregPending) LogMsg("hndlRecordUpdateReply: ResourceRecord %s not in DeregPending state %d", ARDisplayString(m, rr), rr->state);
   3233 			rr->state = regState_NoTarget;	// Wait for the next target change
   3234 			}
   3235 		return;
   3236 		}
   3237 
   3238 	if (rr->state == regState_Pending || rr->state == regState_Refresh)
   3239 		{
   3240 		if (!err)
   3241 			{
   3242 			if (rr->state == regState_Refresh) InvokeCallback = mDNSfalse;
   3243 			rr->state = regState_Registered;
   3244 			}
   3245 		else
   3246 			{
   3247 			// Retry without lease only for non-Private domains
   3248 			LogMsg("hndlRecordUpdateReply: Registration of record %##s type %d failed with error %d", rr->resrec.name->c, rr->resrec.rrtype, err);
   3249 			if (!rr->Private && rr->uselease && err == mStatus_UnknownErr && mDNSSameIPPort(UpdatePort, UnicastDNSPort))
   3250 				{
   3251 				LogMsg("hndlRecordUpdateReply: Will retry update of record %##s without lease option", rr->resrec.name->c);
   3252 				rr->uselease = mDNSfalse;
   3253 				rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   3254 				rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   3255 				return;
   3256 				}
   3257 			// Communicate the error to the application in the callback below
   3258 			}
   3259 		}
   3260 
   3261 	if (rr->QueuedRData && rr->state == regState_Registered)
   3262 		{
   3263 		rr->state = regState_UpdatePending;
   3264 		rr->InFlightRData = rr->QueuedRData;
   3265 		rr->InFlightRDLen = rr->QueuedRDLen;
   3266 		rr->OrigRData = rr->resrec.rdata;
   3267 		rr->OrigRDLen = rr->resrec.rdlength;
   3268 		rr->QueuedRData = mDNSNULL;
   3269 		rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
   3270 		rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
   3271 		return;
   3272 		}
   3273 
   3274 	// Don't invoke the callback on error as this may not be useful to the client.
   3275 	// The client may potentially delete the resource record on error which we normally
   3276 	// delete during deregistration
   3277 	if (!err && InvokeCallback && rr->RecordCallback)
   3278 		{
   3279 		LogInfo("hndlRecordUpdateReply: Calling record callback on %##s", rr->resrec.name->c);
   3280 		mDNS_DropLockBeforeCallback();
   3281 		rr->RecordCallback(m, rr, err);
   3282 		mDNS_ReclaimLockAfterCallback();
   3283 		}
   3284 	// CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
   3285 	// is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
   3286 	}
   3287 
   3288 mDNSexport void uDNS_ReceiveNATPMPPacket(mDNS *m, const mDNSInterfaceID InterfaceID, mDNSu8 *pkt, mDNSu16 len)
   3289 	{
   3290 	NATTraversalInfo *ptr;
   3291 	NATAddrReply     *AddrReply    = (NATAddrReply    *)pkt;
   3292 	NATPortMapReply  *PortMapReply = (NATPortMapReply *)pkt;
   3293 	mDNSu32 nat_elapsed, our_elapsed;
   3294 
   3295 	// Minimum packet is vers (1) opcode (1) err (2) upseconds (4) = 8 bytes
   3296 	if (!AddrReply->err && len < 8) { LogMsg("NAT Traversal message too short (%d bytes)", len); return; }
   3297 	if (AddrReply->vers != NATMAP_VERS) { LogMsg("Received NAT Traversal response with version %d (expected %d)", pkt[0], NATMAP_VERS); return; }
   3298 
   3299 	// Read multi-byte numeric values (fields are identical in a NATPortMapReply)
   3300 	AddrReply->err       = (mDNSu16) (                                                (mDNSu16)pkt[2] << 8 | pkt[3]);
   3301 	AddrReply->upseconds = (mDNSs32) ((mDNSs32)pkt[4] << 24 | (mDNSs32)pkt[5] << 16 | (mDNSs32)pkt[6] << 8 | pkt[7]);
   3302 
   3303 	nat_elapsed = AddrReply->upseconds - m->LastNATupseconds;
   3304 	our_elapsed = (m->timenow - m->LastNATReplyLocalTime) / mDNSPlatformOneSecond;
   3305 	debugf("uDNS_ReceiveNATPMPPacket %X upseconds %u nat_elapsed %d our_elapsed %d", AddrReply->opcode, AddrReply->upseconds, nat_elapsed, our_elapsed);
   3306 
   3307 	// We compute a conservative estimate of how much the NAT gateways's clock should have advanced
   3308 	// 1. We subtract 12.5% from our own measured elapsed time, to allow for NAT gateways that have an inacurate clock that runs slowly
   3309 	// 2. We add a two-second safety margin to allow for rounding errors: e.g.
   3310 	//    -- if NAT gateway sends a packet at t=2.000 seconds, then one at t=7.999, that's approximately 6 real seconds,
   3311 	//       but based on the values in the packet (2,7) the apparent difference according to the packet is only 5 seconds
   3312 	//    -- if we're slow handling packets and/or we have coarse clock granularity,
   3313 	//       we could receive the t=2 packet at our t=1.999 seconds, which we round down to 1
   3314 	//       and the t=7.999 packet at our t=8.000 seconds, which we record as 8,
   3315 	//       giving an apparent local time difference of 7 seconds
   3316 	//    The two-second safety margin coves this possible calculation discrepancy
   3317 	if (AddrReply->upseconds < m->LastNATupseconds || nat_elapsed + 2 < our_elapsed - our_elapsed/8)
   3318 		{ LogMsg("NAT gateway %#a rebooted", &m->Router); RecreateNATMappings(m); }
   3319 
   3320 	m->LastNATupseconds      = AddrReply->upseconds;
   3321 	m->LastNATReplyLocalTime = m->timenow;
   3322 #ifdef _LEGACY_NAT_TRAVERSAL_
   3323 	LNT_ClearState(m);
   3324 #endif // _LEGACY_NAT_TRAVERSAL_
   3325 
   3326 	if (AddrReply->opcode == NATOp_AddrResponse)
   3327 		{
   3328 #if APPLE_OSX_mDNSResponder
   3329 		static char msgbuf[16];
   3330 		mDNS_snprintf(msgbuf, sizeof(msgbuf), "%d", AddrReply->err);
   3331 		mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.AddressRequest", AddrReply->err ? "failure" : "success", msgbuf, "");
   3332 #endif
   3333 		if (!AddrReply->err && len < sizeof(NATAddrReply)) { LogMsg("NAT Traversal AddrResponse message too short (%d bytes)", len); return; }
   3334 		natTraversalHandleAddressReply(m, AddrReply->err, AddrReply->ExtAddr);
   3335 		}
   3336 	else if (AddrReply->opcode == NATOp_MapUDPResponse || AddrReply->opcode == NATOp_MapTCPResponse)
   3337 		{
   3338 		mDNSu8 Protocol = AddrReply->opcode & 0x7F;
   3339 #if APPLE_OSX_mDNSResponder
   3340 		static char msgbuf[16];
   3341 		mDNS_snprintf(msgbuf, sizeof(msgbuf), "%s - %d", AddrReply->opcode == NATOp_MapUDPResponse ? "UDP" : "TCP", PortMapReply->err);
   3342 		mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.PortMapRequest", PortMapReply->err ? "failure" : "success", msgbuf, "");
   3343 #endif
   3344 		if (!PortMapReply->err)
   3345 			{
   3346 			if (len < sizeof(NATPortMapReply)) { LogMsg("NAT Traversal PortMapReply message too short (%d bytes)", len); return; }
   3347 			PortMapReply->NATRep_lease = (mDNSu32) ((mDNSu32)pkt[12] << 24 | (mDNSu32)pkt[13] << 16 | (mDNSu32)pkt[14] << 8 | pkt[15]);
   3348 			}
   3349 
   3350 		// Since some NAT-PMP server implementations don't return the requested internal port in
   3351 		// the reply, we can't associate this reply with a particular NATTraversalInfo structure.
   3352 		// We globally keep track of the most recent error code for mappings.
   3353 		m->LastNATMapResultCode = PortMapReply->err;
   3354 
   3355 		for (ptr = m->NATTraversals; ptr; ptr=ptr->next)
   3356 			if (ptr->Protocol == Protocol && mDNSSameIPPort(ptr->IntPort, PortMapReply->intport))
   3357 				natTraversalHandlePortMapReply(m, ptr, InterfaceID, PortMapReply->err, PortMapReply->extport, PortMapReply->NATRep_lease);
   3358 		}
   3359 	else { LogMsg("Received NAT Traversal response with version unknown opcode 0x%X", AddrReply->opcode); return; }
   3360 
   3361 	// Don't need an SSDP socket if we get a NAT-PMP packet
   3362 	if (m->SSDPSocket) { debugf("uDNS_ReceiveNATPMPPacket destroying SSDPSocket %p", &m->SSDPSocket); mDNSPlatformUDPClose(m->SSDPSocket); m->SSDPSocket = mDNSNULL; }
   3363 	}
   3364 
   3365 // <rdar://problem/3925163> Shorten DNS-SD queries to avoid NAT bugs
   3366 // <rdar://problem/4288449> Add check to avoid crashing NAT gateways that have buggy DNS relay code
   3367 //
   3368 // We know of bugs in home NAT gateways that cause them to crash if they receive certain DNS queries.
   3369 // The DNS queries that make them crash are perfectly legal DNS queries, but even if they weren't,
   3370 // the gateway shouldn't crash -- in today's world of viruses and network attacks, software has to
   3371 // be written assuming that a malicious attacker could send them any packet, properly-formed or not.
   3372 // Still, we don't want to be crashing people's home gateways, so we go out of our way to avoid
   3373 // the queries that crash them.
   3374 //
   3375 // Some examples:
   3376 //
   3377 // 1. Any query where the name ends in ".in-addr.arpa." and the text before this is 32 or more bytes.
   3378 //    The query type does not need to be PTR -- the gateway will crash for any query type.
   3379 //    e.g. "ping long-name-crashes-the-buggy-router.in-addr.arpa" will crash one of these.
   3380 //
   3381 // 2. Any query that results in a large response with the TC bit set.
   3382 //
   3383 // 3. Any PTR query that doesn't begin with four decimal numbers.
   3384 //    These gateways appear to assume that the only possible PTR query is a reverse-mapping query
   3385 //    (e.g. "1.0.168.192.in-addr.arpa") and if they ever get a PTR query where the first four
   3386 //    labels are not all decimal numbers in the range 0-255, they handle that by crashing.
   3387 //    These gateways also ignore the remainder of the name following the four decimal numbers
   3388 //    -- whether or not it actually says in-addr.arpa, they just make up an answer anyway.
   3389 //
   3390 // The challenge therefore is to craft a query that will discern whether the DNS server
   3391 // is one of these buggy ones, without crashing it. Furthermore we don't want our test
   3392 // queries making it all the way to the root name servers, putting extra load on those
   3393 // name servers and giving Apple a bad reputation. To this end we send this query:
   3394 //     dig -t ptr 1.0.0.127.dnsbugtest.1.0.0.127.in-addr.arpa.
   3395 //
   3396 // The text preceding the ".in-addr.arpa." is under 32 bytes, so it won't cause crash (1).
   3397 // It will not yield a large response with the TC bit set, so it won't cause crash (2).
   3398 // It starts with four decimal numbers, so it won't cause crash (3).
   3399 // The name falls within the "1.0.0.127.in-addr.arpa." domain, the reverse-mapping name for the local
   3400 // loopback address, and therefore the query will black-hole at the first properly-configured DNS server
   3401 // it reaches, making it highly unlikely that this query will make it all the way to the root.
   3402 //
   3403 // Finally, the correct response to this query is NXDOMAIN or a similar error, but the
   3404 // gateways that ignore the remainder of the name following the four decimal numbers
   3405 // give themselves away by actually returning a result for this nonsense query.
   3406 
   3407 mDNSlocal const domainname *DNSRelayTestQuestion = (const domainname*)
   3408 	"\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\xa" "dnsbugtest"
   3409 	"\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\x7" "in-addr" "\x4" "arpa";
   3410 
   3411 // See comments above for DNSRelayTestQuestion
   3412 // If this is the kind of query that has the risk of crashing buggy DNS servers, we do a test question first
   3413 mDNSlocal mDNSBool NoTestQuery(DNSQuestion *q)
   3414 	{
   3415 	int i;
   3416 	mDNSu8 *p = q->qname.c;
   3417 	if (q->AuthInfo) return(mDNStrue);		// Don't need a test query for private queries sent directly to authoritative server over TLS/TCP
   3418 	if (q->qtype != kDNSType_PTR) return(mDNStrue);		// Don't need a test query for any non-PTR queries
   3419 	for (i=0; i<4; i++)		// If qname does not begin with num.num.num.num, can't skip the test query
   3420 		{
   3421 		if (p[0] < 1 || p[0] > 3) return(mDNSfalse);
   3422 		if (              p[1] < '0' || p[1] > '9' ) return(mDNSfalse);
   3423 		if (p[0] >= 2 && (p[2] < '0' || p[2] > '9')) return(mDNSfalse);
   3424 		if (p[0] >= 3 && (p[3] < '0' || p[3] > '9')) return(mDNSfalse);
   3425 		p += 1 + p[0];
   3426 		}
   3427 	// If remainder of qname is ".in-addr.arpa.", this is a vanilla reverse-mapping query and
   3428 	// we can safely do it without needing a test query first, otherwise we need the test query.
   3429 	return(SameDomainName((domainname*)p, (const domainname*)"\x7" "in-addr" "\x4" "arpa"));
   3430 	}
   3431 
   3432 // Returns mDNStrue if response was handled
   3433 mDNSlocal mDNSBool uDNS_ReceiveTestQuestionResponse(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
   3434 	const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
   3435 	{
   3436 	const mDNSu8 *ptr = msg->data;
   3437 	DNSQuestion pktq;
   3438 	DNSServer *s;
   3439 	mDNSu32 result = 0;
   3440 
   3441 	// 1. Find out if this is an answer to one of our test questions
   3442 	if (msg->h.numQuestions != 1) return(mDNSfalse);
   3443 	ptr = getQuestion(msg, ptr, end, mDNSInterface_Any, &pktq);
   3444 	if (!ptr) return(mDNSfalse);
   3445 	if (pktq.qtype != kDNSType_PTR || pktq.qclass != kDNSClass_IN) return(mDNSfalse);
   3446 	if (!SameDomainName(&pktq.qname, DNSRelayTestQuestion)) return(mDNSfalse);
   3447 
   3448 	// 2. If the DNS relay gave us a positive response, then it's got buggy firmware
   3449 	// else, if the DNS relay gave us an error or no-answer response, it passed our test
   3450 	if ((msg->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr && msg->h.numAnswers > 0)
   3451 		result = DNSServer_Failed;
   3452 	else
   3453 		result = DNSServer_Passed;
   3454 
   3455 	// 3. Find occurrences of this server in our list, and mark them appropriately
   3456 	for (s = m->DNSServers; s; s = s->next)
   3457 		{
   3458 		mDNSBool matchaddr = (s->teststate != result && mDNSSameAddress(srcaddr, &s->addr) && mDNSSameIPPort(srcport, s->port));
   3459 		mDNSBool matchid   = (s->teststate == DNSServer_Untested && mDNSSameOpaque16(msg->h.id, s->testid));
   3460 		if (matchaddr || matchid)
   3461 			{
   3462 			DNSQuestion *q;
   3463 			s->teststate = result;
   3464 			if (result == DNSServer_Passed)
   3465 				{
   3466 				LogInfo("DNS Server %#a:%d (%#a:%d) %d passed%s",
   3467 					&s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
   3468 					matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
   3469 				}
   3470 			else
   3471 				{
   3472 				LogMsg("NOTE: Wide-Area Service Discovery disabled to avoid crashing defective DNS relay %#a:%d (%#a:%d) %d%s",
   3473 					&s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
   3474 					matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
   3475 				}
   3476 
   3477 			// If this server has just changed state from DNSServer_Untested to DNSServer_Passed, then retrigger any waiting questions.
   3478 			// We use the NoTestQuery() test so that we only retrigger questions that were actually blocked waiting for this test to complete.
   3479 			if (result == DNSServer_Passed)		// Unblock any questions that were waiting for this result
   3480 				for (q = m->Questions; q; q=q->next)
   3481 					if (q->qDNSServer == s && !NoTestQuery(q))
   3482 						{
   3483 						q->ThisQInterval = INIT_UCAST_POLL_INTERVAL / QuestionIntervalStep;
   3484 						q->unansweredQueries = 0;
   3485 						q->LastQTime = m->timenow - q->ThisQInterval;
   3486 						m->NextScheduledQuery = m->timenow;
   3487 						}
   3488 			}
   3489 		}
   3490 
   3491 	return(mDNStrue); // Return mDNStrue to tell uDNS_ReceiveMsg it doesn't need to process this packet further
   3492 	}
   3493 
   3494 // Called from mDNSCoreReceive with the lock held
   3495 mDNSexport void uDNS_ReceiveMsg(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end, const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
   3496 	{
   3497 	DNSQuestion *qptr;
   3498 	mStatus err = mStatus_NoError;
   3499 
   3500 	mDNSu8 StdR    = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
   3501 	mDNSu8 UpdateR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
   3502 	mDNSu8 QR_OP   = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
   3503 	mDNSu8 rcode   = (mDNSu8)(msg->h.flags.b[1] & kDNSFlag1_RC_Mask);
   3504 
   3505 	(void)srcport; // Unused
   3506 
   3507 	debugf("uDNS_ReceiveMsg from %#-15a with "
   3508 		"%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
   3509 		srcaddr,
   3510 		msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
   3511 		msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
   3512 		msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
   3513 		msg->h.numAdditionals, msg->h.numAdditionals == 1 ? ""     : "s", end - msg->data);
   3514 
   3515 	if (QR_OP == StdR)
   3516 		{
   3517 		//if (srcaddr && recvLLQResponse(m, msg, end, srcaddr, srcport)) return;
   3518 		if (uDNS_ReceiveTestQuestionResponse(m, msg, end, srcaddr, srcport)) return;
   3519 		for (qptr = m->Questions; qptr; qptr = qptr->next)
   3520 			if (msg->h.flags.b[0] & kDNSFlag0_TC && mDNSSameOpaque16(qptr->TargetQID, msg->h.id) && m->timenow - qptr->LastQTime < RESPONSE_WINDOW)
   3521 				{
   3522 				if (!srcaddr) LogMsg("uDNS_ReceiveMsg: TCP DNS response had TC bit set: ignoring");
   3523 				else
   3524 					{
   3525 					// Don't reuse TCP connections. We might have failed over to a different DNS server
   3526 					// while the first TCP connection is in progress. We need a new TCP connection to the
   3527 					// new DNS server. So, always try to establish a new connection.
   3528 					if (qptr->tcp) { DisposeTCPConn(qptr->tcp); qptr->tcp = mDNSNULL; }
   3529 					qptr->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_Zero, srcaddr, srcport, mDNSNULL, qptr, mDNSNULL);
   3530 					}
   3531 				}
   3532 		}
   3533 
   3534 	if (QR_OP == UpdateR)
   3535 		{
   3536 		mDNSu32 lease = GetPktLease(m, msg, end);
   3537 		mDNSs32 expire = m->timenow + (mDNSs32)lease * mDNSPlatformOneSecond;
   3538 		mDNSu32 random = mDNSRandom((mDNSs32)lease * mDNSPlatformOneSecond/10);
   3539 
   3540 		//rcode = kDNSFlag1_RC_ServFail;	// Simulate server failure (rcode 2)
   3541 
   3542 		// Walk through all the records that matches the messageID. There could be multiple
   3543 		// records if we had sent them in a group
   3544 		if (m->CurrentRecord)
   3545 			LogMsg("uDNS_ReceiveMsg ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
   3546 		m->CurrentRecord = m->ResourceRecords;
   3547 		while (m->CurrentRecord)
   3548 			{
   3549 			AuthRecord *rptr = m->CurrentRecord;
   3550 			m->CurrentRecord = m->CurrentRecord->next;
   3551 			if (AuthRecord_uDNS(rptr) && mDNSSameOpaque16(rptr->updateid, msg->h.id))
   3552 				{
   3553 				err = checkUpdateResult(m, rptr->resrec.name, rcode, msg, end);
   3554 				if (!err && rptr->uselease && lease)
   3555 					if (rptr->expire - expire >= 0 || rptr->state != regState_UpdatePending)
   3556 						{
   3557 						rptr->expire = expire;
   3558 						rptr->refreshCount = 0;
   3559 						}
   3560 				// We pass the random value to make sure that if we update multiple
   3561 				// records, they all get the same random value
   3562 				hndlRecordUpdateReply(m, rptr, err, random);
   3563 				}
   3564 			}
   3565 		}
   3566 	debugf("Received unexpected response: ID %d matches no active records", mDNSVal16(msg->h.id));
   3567 	}
   3568 
   3569 // ***************************************************************************
   3570 #if COMPILER_LIKES_PRAGMA_MARK
   3571 #pragma mark - Query Routines
   3572 #endif
   3573 
   3574 mDNSexport void sendLLQRefresh(mDNS *m, DNSQuestion *q)
   3575 	{
   3576 	mDNSu8 *end;
   3577 	LLQOptData llq;
   3578 	mDNSu8 *limit = m->omsg.data + AbsoluteMaxDNSMessageData;
   3579 
   3580 	if (q->ReqLease)
   3581 		if ((q->state == LLQ_Established && q->ntries >= kLLQ_MAX_TRIES) || q->expire - m->timenow < 0)
   3582 			{
   3583 			LogMsg("Unable to refresh LLQ %##s (%s) - will retry in %d seconds", q->qname.c, DNSTypeName(q->qtype), LLQ_POLL_INTERVAL / mDNSPlatformOneSecond);
   3584 			StartLLQPolling(m,q);
   3585 			return;
   3586 			}
   3587 
   3588 	llq.vers     = kLLQ_Vers;
   3589 	llq.llqOp    = kLLQOp_Refresh;
   3590 	llq.err      = q->tcp ? GetLLQEventPort(m, &q->servAddr) : LLQErr_NoError;	// If using TCP tell server what UDP port to send notifications to
   3591 	llq.id       = q->id;
   3592 	llq.llqlease = q->ReqLease;
   3593 
   3594 	InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
   3595 	end = putLLQ(&m->omsg, m->omsg.data, q, &llq);
   3596 	if (!end) { LogMsg("sendLLQRefresh: putLLQ failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
   3597 
   3598 	// Note that we (conditionally) add HINFO and TSIG here, since the question might be going away,
   3599 	// so we may not be able to reference it (most importantly it's AuthInfo) when we actually send the message
   3600 	end = putHINFO(m, &m->omsg, end, q->AuthInfo, limit);
   3601 	if (!end) { LogMsg("sendLLQRefresh: putHINFO failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
   3602 
   3603 	if (PrivateQuery(q))
   3604 		{
   3605 		DNSDigest_SignMessageHostByteOrder(&m->omsg, &end, q->AuthInfo);
   3606 		if (!end) { LogMsg("sendLLQRefresh: DNSDigest_SignMessage failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
   3607 		}
   3608 
   3609 	if (PrivateQuery(q) && !q->tcp)
   3610 		{
   3611 		LogInfo("sendLLQRefresh setting up new TLS session %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
   3612 		if (!q->nta) { LogMsg("sendLLQRefresh:ERROR!! q->nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
   3613 		q->tcp = MakeTCPConn(m, &m->omsg, end, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
   3614 		}
   3615 	else
   3616 		{
   3617 		mStatus err;
   3618 
   3619 		// if AuthInfo and AuthInfo->AutoTunnel is set, we use the TCP socket but don't need to pass the AuthInfo as
   3620 		// we already protected the message above.
   3621 		LogInfo("sendLLQRefresh: using existing %s session %##s (%s)", PrivateQuery(q) ? "TLS" : "UDP",
   3622 			q->qname.c, DNSTypeName(q->qtype));
   3623 
   3624 		err = mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, q->tcp ? q->tcp->sock : mDNSNULL, mDNSNULL);
   3625 		if (err)
   3626 			{
   3627 			LogMsg("sendLLQRefresh: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err);
   3628 			if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
   3629 			}
   3630 		}
   3631 
   3632 	q->ntries++;
   3633 
   3634 	debugf("sendLLQRefresh ntries %d %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
   3635 
   3636 	q->LastQTime = m->timenow;
   3637 	SetNextQueryTime(m, q);
   3638 	}
   3639 
   3640 mDNSexport void LLQGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
   3641 	{
   3642 	DNSQuestion *q = (DNSQuestion *)zoneInfo->ZoneDataContext;
   3643 
   3644 	mDNS_Lock(m);
   3645 
   3646 	// If we get here it means that the GetZoneData operation has completed.
   3647 	// We hold on to the zone data if it is AutoTunnel as we use the hostname
   3648 	// in zoneInfo during the TLS connection setup.
   3649 	q->servAddr = zeroAddr;
   3650 	q->servPort = zeroIPPort;
   3651 
   3652 	if (!err && zoneInfo && !mDNSIPPortIsZero(zoneInfo->Port) && !mDNSAddressIsZero(&zoneInfo->Addr) && zoneInfo->Host.c[0])
   3653 		{
   3654 		q->servAddr = zoneInfo->Addr;
   3655 		q->servPort = zoneInfo->Port;
   3656 		if (!PrivateQuery(q))
   3657 			{
   3658 			// We don't need the zone data as we use it only for the Host information which we
   3659 			// don't need if we are not going to use TLS connections.
   3660 			if (q->nta)
   3661 				{
   3662 				if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
   3663 				CancelGetZoneData(m, q->nta);
   3664 				q->nta = mDNSNULL;
   3665 				}
   3666 			}
   3667 		q->ntries = 0;
   3668 		debugf("LLQGotZoneData %#a:%d", &q->servAddr, mDNSVal16(q->servPort));
   3669 		startLLQHandshake(m, q);
   3670 		}
   3671 	else
   3672 		{
   3673 		if (q->nta)
   3674 			{
   3675 			if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
   3676 			CancelGetZoneData(m, q->nta);
   3677 			q->nta = mDNSNULL;
   3678 			}
   3679 		StartLLQPolling(m,q);
   3680 		if (err == mStatus_NoSuchNameErr)
   3681 			{
   3682 			// this actually failed, so mark it by setting address to all ones
   3683 			q->servAddr.type = mDNSAddrType_IPv4;
   3684 			q->servAddr.ip.v4 = onesIPv4Addr;
   3685 			}
   3686 		}
   3687 
   3688 	mDNS_Unlock(m);
   3689 	}
   3690 
   3691 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
   3692 mDNSlocal void PrivateQueryGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
   3693 	{
   3694 	DNSQuestion *q = (DNSQuestion *) zoneInfo->ZoneDataContext;
   3695 
   3696 	LogInfo("PrivateQueryGotZoneData %##s (%s) err %d Zone %##s Private %d", q->qname.c, DNSTypeName(q->qtype), err, zoneInfo->ZoneName.c, zoneInfo->ZonePrivate);
   3697 
   3698 	if (q->nta != zoneInfo) LogMsg("PrivateQueryGotZoneData:ERROR!!: nta (%p) != zoneInfo (%p)  %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
   3699 
   3700 	if (err || !zoneInfo || mDNSAddressIsZero(&zoneInfo->Addr) || mDNSIPPortIsZero(zoneInfo->Port) || !zoneInfo->Host.c[0])
   3701 		{
   3702 		LogInfo("PrivateQueryGotZoneData: ERROR!! %##s (%s) invoked with error code %d %p %#a:%d",
   3703 			q->qname.c, DNSTypeName(q->qtype), err, zoneInfo,
   3704 			zoneInfo ? &zoneInfo->Addr : mDNSNULL,
   3705 			zoneInfo ? mDNSVal16(zoneInfo->Port) : 0);
   3706 		CancelGetZoneData(m, q->nta);
   3707 		q->nta = mDNSNULL;
   3708 		return;
   3709 		}
   3710