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