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