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