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