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