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