1 /*
2  * Copyright (c) 2002-2020 Apple Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15 
16  * To Do:
17  * Elimate all mDNSPlatformMemAllocate/mDNSPlatformMemFree from this code -- the core code
18  * is supposed to be malloc-free so that it runs in constant memory determined at compile-time.
19  * Any dynamic run-time requirements should be handled by the platform layer below or client layer above
20  */
21 
22 #include "uDNS.h"
23 
24 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
25 #include "Metrics.h"
26 #endif
27 
28 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
29 #include "SymptomReporter.h"
30 #endif
31 
32 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
33 #include "QuerierSupport.h"
34 #endif
35 
36 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
37 #include "dnssec_v2.h"
38 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
39 
40 #if (defined(_MSC_VER))
41 // Disable "assignment within conditional expression".
42 // Other compilers understand the convention that if you place the assignment expression within an extra pair
43 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
44 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
45 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
46     #pragma warning(disable:4706)
47 #endif
48 
49 // For domain enumeration and automatic browsing
50 // This is the user's DNS search list.
51 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
52 // to discover recommended domains for domain enumeration (browse, default browse, registration,
53 // default registration) and possibly one or more recommended automatic browsing domains.
54 mDNSexport SearchListElem *SearchList = mDNSNULL;
55 
56 // The value can be set to true by the Platform code e.g., MacOSX uses the plist mechanism
57 mDNSBool StrictUnicastOrdering = mDNSfalse;
58 
59 extern mDNS mDNSStorage;
60 
61 // We keep track of the number of unicast DNS servers and log a message when we exceed 64.
62 // Currently the unicast queries maintain a 128 bit map to track the valid DNS servers for that
63 // question. Bit position is the index into the DNS server list. This is done so to try all
64 // the servers exactly once before giving up. If we could allocate memory in the core, then
65 // arbitrary limitation of 128 DNSServers can be removed.
66 #define MAX_UNICAST_DNS_SERVERS 128
67 
68 #define SetNextuDNSEvent(m, rr) { \
69         if ((m)->NextuDNSEvent - ((rr)->LastAPTime + (rr)->ThisAPInterval) >= 0)                                                                              \
70             (m)->NextuDNSEvent = ((rr)->LastAPTime + (rr)->ThisAPInterval);                                                                         \
71 }
72 
73 #ifndef UNICAST_DISABLED
74 
75 // ***************************************************************************
76 #if COMPILER_LIKES_PRAGMA_MARK
77 #pragma mark - General Utility Functions
78 #endif
79 
80 // set retry timestamp for record with exponential backoff
SetRecordRetry(mDNS * const m,AuthRecord * rr,mDNSu32 random)81 mDNSlocal void SetRecordRetry(mDNS *const m, AuthRecord *rr, mDNSu32 random)
82 {
83     rr->LastAPTime = m->timenow;
84 
85     if (rr->expire && rr->refreshCount < MAX_UPDATE_REFRESH_COUNT)
86     {
87         mDNSs32 remaining = rr->expire - m->timenow;
88         rr->refreshCount++;
89         if (remaining > MIN_UPDATE_REFRESH_TIME)
90         {
91             // Refresh at 70% + random (currently it is 0 to 10%)
92             rr->ThisAPInterval =  7 * (remaining/10) + (random ? random : mDNSRandom(remaining/10));
93             // Don't update more often than 5 minutes
94             if (rr->ThisAPInterval < MIN_UPDATE_REFRESH_TIME)
95                 rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
96             LogInfo("SetRecordRetry refresh in %d of %d for %s",
97                     rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
98         }
99         else
100         {
101             rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
102             LogInfo("SetRecordRetry clamping to min refresh in %d of %d for %s",
103                     rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
104         }
105         return;
106     }
107 
108     rr->expire = 0;
109 
110     rr->ThisAPInterval = rr->ThisAPInterval * QuestionIntervalStep; // Same Retry logic as Unicast Queries
111     if (rr->ThisAPInterval < INIT_RECORD_REG_INTERVAL)
112         rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
113     if (rr->ThisAPInterval > MAX_RECORD_REG_INTERVAL)
114         rr->ThisAPInterval = MAX_RECORD_REG_INTERVAL;
115 
116     LogInfo("SetRecordRetry retry in %d ms for %s", rr->ThisAPInterval, ARDisplayString(m, rr));
117 }
118 
119 // ***************************************************************************
120 #if COMPILER_LIKES_PRAGMA_MARK
121 #pragma mark - Name Server List Management
122 #endif
123 
124 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
mDNS_AddDNSServer(mDNS * const m,const domainname * domain,const mDNSInterfaceID interface,const mDNSs32 serviceID,const mDNSAddr * addr,const mDNSIPPort port,ScopeType scopeType,mDNSu32 timeout,mDNSBool isCell,mDNSBool isExpensive,mDNSBool isConstrained,mDNSBool isCLAT46,mDNSu32 resGroupID,mDNSBool usableA,mDNSBool usableAAAA,mDNSBool reqDO)125 mDNSexport DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *domain, const mDNSInterfaceID interface,
126     const mDNSs32 serviceID, const mDNSAddr *addr, const mDNSIPPort port, ScopeType scopeType, mDNSu32 timeout,
127     mDNSBool isCell, mDNSBool isExpensive, mDNSBool isConstrained, mDNSBool isCLAT46, mDNSu32 resGroupID,
128     mDNSBool usableA, mDNSBool usableAAAA, mDNSBool reqDO)
129 {
130     DNSServer **p;
131     DNSServer *server;
132     int       dnsCount = CountOfUnicastDNSServers(m);
133     if (dnsCount >= MAX_UNICAST_DNS_SERVERS)
134     {
135         LogMsg("mDNS_AddDNSServer: DNS server count of %d reached, not adding this server", dnsCount);
136         return mDNSNULL;
137     }
138 
139     if (!domain) domain = (const domainname *)"";
140 
141     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
142         "mDNS_AddDNSServer(%d): Adding " PRI_IP_ADDR " for " PRI_DM_NAME " interface " PUB_S " (%p), serviceID %u, "
143         "scopeType %d, resGroupID %u" PUB_S PUB_S PUB_S PUB_S PUB_S PUB_S PUB_S,
144         dnsCount + 1, addr, DM_NAME_PARAM(domain), InterfaceNameForID(&mDNSStorage, interface), interface, serviceID,
145         (int)scopeType, resGroupID,
146         usableA       ? ", usableA"     : "",
147         usableAAAA    ? ", usableAAAA"  : "",
148         isCell        ? ", cell"        : "",
149         isExpensive   ? ", expensive"   : "",
150         isConstrained ? ", constrained" : "",
151         isCLAT46      ? ", CLAT46"      : "",
152         reqDO         ? ", reqDO"       : "");
153 
154     // Scan our existing list to see if we already have a matching record for this DNS resolver
155     for (p = &m->DNSServers; (server = *p) != mDNSNULL; p = &server->next)
156     {
157         if (server->interface       != interface)       continue;
158         if (server->serviceID       != serviceID)       continue;
159         if (!mDNSSameAddress(&server->addr, addr))      continue;
160         if (!mDNSSameIPPort(server->port, port))        continue;
161         if (!SameDomainName(&server->domain, domain))   continue;
162         if (server->scopeType       != scopeType)       continue;
163         if (server->timeout         != timeout)         continue;
164         if (!server->usableA        != !usableA)        continue;
165         if (!server->usableAAAA     != !usableAAAA)     continue;
166         if (!server->isCell         != !isCell)         continue;
167         if (!(server->flags & DNSServerFlag_Delete))
168         {
169             debugf("Note: DNS Server %#a:%d for domain %##s (%p) registered more than once",
170                 addr, mDNSVal16(port), domain->c, interface);
171         }
172         // If we found a matching record, cut it from the list
173         // (and if we’re *not* resurrecting a record that was marked for deletion, it’s a duplicate,
174         // and the debugf message signifies that we’re collapsing duplicate entries into one)
175         *p = server->next;
176         server->next = mDNSNULL;
177         break;
178     }
179 
180     // If we broke out because we found an existing matching record, advance our pointer to the end of the list
181     while (*p)
182     {
183         p = &(*p)->next;
184     }
185 
186     if (server)
187     {
188         if (server->flags & DNSServerFlag_Delete)
189         {
190 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
191             server->flags &= ~DNSServerFlag_Unreachable;
192 #endif
193             server->flags &= ~DNSServerFlag_Delete;
194         }
195         server->isExpensive   = isExpensive;
196         server->isConstrained = isConstrained;
197         server->isCLAT46      = isCLAT46;
198         *p = server;    // Append resurrected record at end of list
199     }
200     else
201     {
202         server = (DNSServer *) mDNSPlatformMemAllocateClear(sizeof(*server));
203         if (!server)
204         {
205             LogMsg("Error: mDNS_AddDNSServer - malloc");
206         }
207         else
208         {
209             server->interface     = interface;
210             server->serviceID     = serviceID;
211             server->addr          = *addr;
212             server->port          = port;
213             server->scopeType     = scopeType;
214             server->timeout       = timeout;
215             server->usableA       = usableA;
216             server->usableAAAA    = usableAAAA;
217             server->isCell        = isCell;
218             server->isExpensive   = isExpensive;
219             server->isConstrained = isConstrained;
220             server->isCLAT46      = isCLAT46;
221             AssignDomainName(&server->domain, domain);
222             *p = server; // Append new record at end of list
223         }
224     }
225     if (server)
226     {
227         server->penaltyTime = 0;
228         // We always update the ID (not just when we allocate a new instance) because we want
229         // all the resGroupIDs for a particular domain to match.
230         server->resGroupID  = resGroupID;
231     }
232     return(server);
233 }
234 
235 // PenalizeDNSServer is called when the number of queries to the unicast
236 // DNS server exceeds MAX_UCAST_UNANSWERED_QUERIES or when we receive an
237 // error e.g., SERV_FAIL from DNS server.
PenalizeDNSServer(mDNS * const m,DNSQuestion * q,mDNSOpaque16 responseFlags)238 mDNSexport void PenalizeDNSServer(mDNS *const m, DNSQuestion *q, mDNSOpaque16 responseFlags)
239 {
240     DNSServer *new;
241     DNSServer *orig = q->qDNSServer;
242     mDNSu8 rcode = '\0';
243 
244     mDNS_CheckLock(m);
245 
246     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
247               "PenalizeDNSServer: Penalizing DNS server " PRI_IP_ADDR " question for question %p " PRI_DM_NAME " (" PUB_S ") SuppressUnusable %d",
248               (q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->SuppressUnusable);
249 
250     // If we get error from any DNS server, remember the error. If all of the servers,
251     // return the error, then return the first error.
252     if (mDNSOpaque16IsZero(q->responseFlags))
253         q->responseFlags = responseFlags;
254 
255     rcode = (mDNSu8)(responseFlags.b[1] & kDNSFlag1_RC_Mask);
256 
257     // After we reset the qDNSServer to NULL, we could get more SERV_FAILS that might end up
258     // penalizing again.
259     if (!q->qDNSServer)
260         goto end;
261 
262     // If strict ordering of unicast servers needs to be preserved, we just lookup
263     // the next best match server below
264     //
265     // If strict ordering is not required which is the default behavior, we penalize the server
266     // for DNSSERVER_PENALTY_TIME. We may also use additional logic e.g., don't penalize for PTR
267     // in the future.
268 
269     if (!StrictUnicastOrdering)
270     {
271         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "PenalizeDNSServer: Strict Unicast Ordering is FALSE");
272         // We penalize the server so that new queries don't pick this server for DNSSERVER_PENALTY_TIME
273         // XXX Include other logic here to see if this server should really be penalized
274         //
275         if (q->qtype == kDNSType_PTR)
276         {
277             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "PenalizeDNSServer: Not Penalizing PTR question");
278         }
279         else if ((rcode == kDNSFlag1_RC_FormErr) || (rcode == kDNSFlag1_RC_ServFail) || (rcode == kDNSFlag1_RC_NotImpl))
280         {
281             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
282                       "PenalizeDNSServer: Not Penalizing DNS Server since it at least responded with rcode %d", rcode);
283         }
284         else
285         {
286             const char *reason = "";
287             if (rcode == kDNSFlag1_RC_Refused)
288             {
289                 reason = " because server refused to answer";
290             }
291             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "PenalizeDNSServer: Penalizing question type %d" PUB_S,
292                       q->qtype, reason);
293             q->qDNSServer->penaltyTime = NonZeroTime(m->timenow + DNSSERVER_PENALTY_TIME);
294         }
295     }
296     else
297     {
298         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "PenalizeDNSServer: Strict Unicast Ordering is TRUE");
299     }
300 
301 end:
302     new = GetServerForQuestion(m, q);
303 
304     if (new == orig)
305     {
306         if (new)
307         {
308             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
309                       "PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server " PRI_IP_ADDR ":%d",
310                       &new->addr, mDNSVal16(new->port));
311             q->ThisQInterval = 0;   // Inactivate this question so that we dont bombard the network
312         }
313         else
314         {
315             // When we have no more DNS servers, we might end up calling PenalizeDNSServer multiple
316             // times when we receive SERVFAIL from delayed packets in the network e.g., DNS server
317             // is slow in responding and we have sent three queries. When we repeatedly call, it is
318             // okay to receive the same NULL DNS server. Next time we try to send the query, we will
319             // realize and re-initialize the DNS servers.
320             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "PenalizeDNSServer: GetServerForQuestion returned the same server NULL");
321         }
322     }
323     else
324     {
325         // The new DNSServer is set in DNSServerChangeForQuestion
326         DNSServerChangeForQuestion(m, q, new);
327 
328         if (new)
329         {
330             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
331                       "PenalizeDNSServer: Server for " PRI_DM_NAME " (" PUB_S ") changed to " PRI_IP_ADDR ":%d (" PRI_DM_NAME ")",
332                       DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), DM_NAME_PARAM(&q->qDNSServer->domain));
333             // We want to try the next server immediately. As the question may already have backed off, reset
334             // the interval. We do this only the first time when we try all the DNS servers. Once we reached the end of
335             // list and retrying all the servers again e.g., at least one server failed to respond in the previous try, we
336             // use the normal backoff which is done in uDNS_CheckCurrentQuestion when we send the packet out.
337             if (!q->triedAllServersOnce)
338             {
339                 q->ThisQInterval = InitialQuestionInterval;
340                 q->LastQTime  = m->timenow - q->ThisQInterval;
341                 SetNextQueryTime(m, q);
342             }
343         }
344         else
345         {
346             // We don't have any more DNS servers for this question. If some server in the list did not return
347             // any response, we need to keep retrying till we get a response. uDNS_CheckCurrentQuestion handles
348             // this case.
349             //
350             // If all servers responded with a negative response, We need to do two things. First, generate a
351             // negative response so that applications get a reply. We also need to reinitialize the DNS servers
352             // so that when the cache expires, we can restart the query.  We defer this up until we generate
353             // a negative cache response in uDNS_CheckCurrentQuestion.
354             //
355             // Be careful not to touch the ThisQInterval here. For a normal question, when we answer the question
356             // in AnswerCurrentQuestionWithResourceRecord will set ThisQInterval to MaxQuestionInterval and hence
357             // the next query will not happen until cache expiry. If it is a long lived question,
358             // AnswerCurrentQuestionWithResourceRecord will not set it to MaxQuestionInterval. In that case,
359             // we want the normal backoff to work.
360             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
361                       "PenalizeDNSServer: Server for %p, " PRI_DM_NAME " (" PUB_S ") changed to NULL, Interval %d",
362                       q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->ThisQInterval);
363         }
364         q->unansweredQueries = 0;
365 
366     }
367 }
368 #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
369 
370 // ***************************************************************************
371 #if COMPILER_LIKES_PRAGMA_MARK
372 #pragma mark - authorization management
373 #endif
374 
GetAuthInfoForName_direct(mDNS * m,const domainname * const name)375 mDNSlocal DomainAuthInfo *GetAuthInfoForName_direct(mDNS *m, const domainname *const name)
376 {
377     const domainname *n = name;
378     while (n->c[0])
379     {
380         DomainAuthInfo *ptr;
381         for (ptr = m->AuthInfoList; ptr; ptr = ptr->next)
382             if (SameDomainName(&ptr->domain, n))
383             {
384                 debugf("GetAuthInfoForName %##s Matched %##s Key name %##s", name->c, ptr->domain.c, ptr->keyname.c);
385                 return(ptr);
386             }
387         n = (const domainname *)(n->c + 1 + n->c[0]);
388     }
389     //LogInfo("GetAuthInfoForName none found for %##s", name->c);
390     return mDNSNULL;
391 }
392 
393 // MUST be called with lock held
GetAuthInfoForName_internal(mDNS * m,const domainname * const name)394 mDNSexport DomainAuthInfo *GetAuthInfoForName_internal(mDNS *m, const domainname *const name)
395 {
396     DomainAuthInfo **p = &m->AuthInfoList;
397 
398     mDNS_CheckLock(m);
399 
400     // First purge any dead keys from the list
401     while (*p)
402     {
403         if ((*p)->deltime && m->timenow - (*p)->deltime >= 0)
404         {
405             DNSQuestion *q;
406             DomainAuthInfo *info = *p;
407             LogInfo("GetAuthInfoForName_internal deleting expired key %##s %##s", info->domain.c, info->keyname.c);
408             *p = info->next;    // Cut DomainAuthInfo from list *before* scanning our question list updating AuthInfo pointers
409             for (q = m->Questions; q; q=q->next)
410                 if (q->AuthInfo == info)
411                 {
412                     q->AuthInfo = GetAuthInfoForName_direct(m, &q->qname);
413                     debugf("GetAuthInfoForName_internal updated q->AuthInfo from %##s to %##s for %##s (%s)",
414                            info->domain.c, q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
415                 }
416 
417             // Probably not essential, but just to be safe, zero out the secret key data
418             // so we don't leave it hanging around in memory
419             // (where it could potentially get exposed via some other bug)
420             mDNSPlatformMemZero(info, sizeof(*info));
421             mDNSPlatformMemFree(info);
422         }
423         else
424             p = &(*p)->next;
425     }
426 
427     return(GetAuthInfoForName_direct(m, name));
428 }
429 
GetAuthInfoForName(mDNS * m,const domainname * const name)430 mDNSexport DomainAuthInfo *GetAuthInfoForName(mDNS *m, const domainname *const name)
431 {
432     DomainAuthInfo *d;
433     mDNS_Lock(m);
434     d = GetAuthInfoForName_internal(m, name);
435     mDNS_Unlock(m);
436     return(d);
437 }
438 
439 // MUST be called with the lock held
mDNS_SetSecretForDomain(mDNS * m,DomainAuthInfo * info,const domainname * domain,const domainname * keyname,const char * b64keydata,const domainname * hostname,mDNSIPPort * port)440 mDNSexport mStatus mDNS_SetSecretForDomain(mDNS *m, DomainAuthInfo *info,
441                                            const domainname *domain, const domainname *keyname, const char *b64keydata, const domainname *hostname, mDNSIPPort *port)
442 {
443     DNSQuestion *q;
444     DomainAuthInfo **p = &m->AuthInfoList;
445     if (!info || !b64keydata) { LogMsg("mDNS_SetSecretForDomain: ERROR: info %p b64keydata %p", info, b64keydata); return(mStatus_BadParamErr); }
446 
447     LogInfo("mDNS_SetSecretForDomain: domain %##s key %##s", domain->c, keyname->c);
448 
449     AssignDomainName(&info->domain,  domain);
450     AssignDomainName(&info->keyname, keyname);
451     if (hostname)
452         AssignDomainName(&info->hostname, hostname);
453     else
454         info->hostname.c[0] = 0;
455     if (port)
456         info->port = *port;
457     else
458         info->port = zeroIPPort;
459     mDNS_snprintf(info->b64keydata, sizeof(info->b64keydata), "%s", b64keydata);
460 
461     if (DNSDigest_ConstructHMACKeyfromBase64(info, b64keydata) < 0)
462     {
463         LogMsg("mDNS_SetSecretForDomain: ERROR: Could not convert shared secret from base64: domain %##s key %##s %s", domain->c, keyname->c, mDNS_LoggingEnabled ? b64keydata : "");
464         return(mStatus_BadParamErr);
465     }
466 
467     // Don't clear deltime until after we've ascertained that b64keydata is valid
468     info->deltime = 0;
469 
470     while (*p && (*p) != info) p=&(*p)->next;
471     if (*p) {LogInfo("mDNS_SetSecretForDomain: Domain %##s Already in list", (*p)->domain.c); return(mStatus_AlreadyRegistered);}
472 
473     info->next = mDNSNULL;
474     *p = info;
475 
476     // Check to see if adding this new DomainAuthInfo has changed the credentials for any of our questions
477     for (q = m->Questions; q; q=q->next)
478     {
479         DomainAuthInfo *newinfo = GetAuthInfoForQuestion(m, q);
480         if (q->AuthInfo != newinfo)
481         {
482             debugf("mDNS_SetSecretForDomain updating q->AuthInfo from %##s to %##s for %##s (%s)",
483                    q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL,
484                    newinfo     ? newinfo->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
485             q->AuthInfo = newinfo;
486         }
487     }
488 
489     return(mStatus_NoError);
490 }
491 
492 // ***************************************************************************
493 #if COMPILER_LIKES_PRAGMA_MARK
494 #pragma mark -
495 #pragma mark - NAT Traversal
496 #endif
497 
498 // Keep track of when to request/refresh the external address using NAT-PMP or UPnP/IGD,
499 // and do so when necessary
uDNS_RequestAddress(mDNS * m)500 mDNSlocal mStatus uDNS_RequestAddress(mDNS *m)
501 {
502     mStatus err = mStatus_NoError;
503 
504     if (!m->NATTraversals)
505     {
506         m->retryGetAddr = NonZeroTime(m->timenow + FutureTime);
507         LogInfo("uDNS_RequestAddress: Setting retryGetAddr to future");
508     }
509     else if (m->timenow - m->retryGetAddr >= 0)
510     {
511         if (mDNSv4AddrIsRFC1918(&m->Router.ip.v4))
512         {
513             static NATAddrRequest req = {NATMAP_VERS, NATOp_AddrRequest};
514             static mDNSu8* start = (mDNSu8*)&req;
515             mDNSu8* end = start + sizeof(NATAddrRequest);
516             err = mDNSPlatformSendUDP(m, start, end, 0, mDNSNULL, &m->Router, NATPMPPort, mDNSfalse);
517             debugf("uDNS_RequestAddress: Sent NAT-PMP external address request %d", err);
518 
519 #ifdef _LEGACY_NAT_TRAVERSAL_
520             if (mDNSIPPortIsZero(m->UPnPRouterPort) || mDNSIPPortIsZero(m->UPnPSOAPPort))
521             {
522                 LNT_SendDiscoveryMsg(m);
523                 debugf("uDNS_RequestAddress: LNT_SendDiscoveryMsg");
524             }
525             else
526             {
527                 mStatus lnterr = LNT_GetExternalAddress(m);
528                 if (lnterr)
529                     LogMsg("uDNS_RequestAddress: LNT_GetExternalAddress returned error %d", lnterr);
530 
531                 err = err ? err : lnterr; // NAT-PMP error takes precedence
532             }
533 #endif // _LEGACY_NAT_TRAVERSAL_
534         }
535 
536         // Always update the interval and retry time, so that even if we fail to send the
537         // packet, we won't spin in an infinite loop repeatedly failing to send the packet
538         if (m->retryIntervalGetAddr < NATMAP_INIT_RETRY)
539         {
540             m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
541         }
542         else if (m->retryIntervalGetAddr < NATMAP_MAX_RETRY_INTERVAL / 2)
543         {
544             m->retryIntervalGetAddr *= 2;
545         }
546         else
547         {
548             m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
549         }
550 
551         m->retryGetAddr = NonZeroTime(m->timenow + m->retryIntervalGetAddr);
552     }
553     else
554     {
555         debugf("uDNS_RequestAddress: Not time to send address request");
556     }
557 
558     // Always update NextScheduledNATOp, even if we didn't change retryGetAddr, so we'll
559     // be called when we need to send the request(s)
560     if (m->NextScheduledNATOp - m->retryGetAddr > 0)
561         m->NextScheduledNATOp = m->retryGetAddr;
562 
563     return err;
564 }
565 
uDNS_SendNATMsg(mDNS * m,NATTraversalInfo * info,mDNSBool usePCP,mDNSBool unmapping)566 mDNSlocal mStatus uDNS_SendNATMsg(mDNS *m, NATTraversalInfo *info, mDNSBool usePCP, mDNSBool unmapping)
567 {
568     mStatus err = mStatus_NoError;
569 
570     if (!info)
571     {
572         LogMsg("uDNS_SendNATMsg called unexpectedly with NULL info");
573         return mStatus_BadParamErr;
574     }
575 
576     // send msg if the router's address is private (which means it's non-zero)
577     if (mDNSv4AddrIsRFC1918(&m->Router.ip.v4))
578     {
579         if (!usePCP)
580         {
581             if (!info->sentNATPMP)
582             {
583                 if (info->Protocol)
584                 {
585                     static NATPortMapRequest NATPortReq;
586                     static const mDNSu8* end = (mDNSu8 *)&NATPortReq + sizeof(NATPortMapRequest);
587                     mDNSu8 *p = (mDNSu8 *)&NATPortReq.NATReq_lease;
588 
589                     NATPortReq.vers    = NATMAP_VERS;
590                     NATPortReq.opcode  = info->Protocol;
591                     NATPortReq.unused  = zeroID;
592                     NATPortReq.intport = info->IntPort;
593                     NATPortReq.extport = info->RequestedPort;
594                     p[0] = (mDNSu8)((info->NATLease >> 24) &  0xFF);
595                     p[1] = (mDNSu8)((info->NATLease >> 16) &  0xFF);
596                     p[2] = (mDNSu8)((info->NATLease >>  8) &  0xFF);
597                     p[3] = (mDNSu8)( info->NATLease        &  0xFF);
598 
599                     err = mDNSPlatformSendUDP(m, (mDNSu8 *)&NATPortReq, end, 0, mDNSNULL, &m->Router, NATPMPPort, mDNSfalse);
600                     debugf("uDNS_SendNATMsg: Sent NAT-PMP mapping request %d", err);
601                 }
602 
603                 // In case the address request already went out for another NAT-T,
604                 // set the NewAddress to the currently known global external address, so
605                 // Address-only operations will get the callback immediately
606                 info->NewAddress = m->ExtAddress;
607 
608                 // Remember that we just sent a NAT-PMP packet, so we won't resend one later.
609                 // We do this because the NAT-PMP "Unsupported Version" response has no
610                 // information about the (PCP) request that triggered it, so we must send
611                 // NAT-PMP requests for all operations. Without this, we'll send n PCP
612                 // requests for n operations, receive n NAT-PMP "Unsupported Version"
613                 // responses, and send n NAT-PMP requests for each of those responses,
614                 // resulting in (n + n^2) packets sent. We only want to send 2n packets:
615                 // n PCP requests followed by n NAT-PMP requests.
616                 info->sentNATPMP = mDNStrue;
617             }
618         }
619         else
620         {
621             PCPMapRequest req;
622             mDNSu8* start = (mDNSu8*)&req;
623             mDNSu8* end = start + sizeof(req);
624             mDNSu8* p = (mDNSu8*)&req.lifetime;
625 
626             req.version = PCP_VERS;
627             req.opCode = PCPOp_Map;
628             req.reserved = zeroID;
629 
630             p[0] = (mDNSu8)((info->NATLease >> 24) &  0xFF);
631             p[1] = (mDNSu8)((info->NATLease >> 16) &  0xFF);
632             p[2] = (mDNSu8)((info->NATLease >>  8) &  0xFF);
633             p[3] = (mDNSu8)( info->NATLease        &  0xFF);
634 
635             mDNSAddrMapIPv4toIPv6(&m->AdvertisedV4.ip.v4, &req.clientAddr);
636 
637             req.nonce[0] = m->PCPNonce[0];
638             req.nonce[1] = m->PCPNonce[1];
639             req.nonce[2] = m->PCPNonce[2];
640 
641             req.protocol = (info->Protocol == NATOp_MapUDP ? PCPProto_UDP : PCPProto_TCP);
642 
643             req.reservedMapOp[0] = 0;
644             req.reservedMapOp[1] = 0;
645             req.reservedMapOp[2] = 0;
646 
647             req.intPort = info->Protocol ? info->IntPort : DiscardPort;
648             req.extPort = info->RequestedPort;
649 
650             // Since we only support IPv4, even if using the all-zeros address, map it, so
651             // the PCP gateway will give us an IPv4 address & not an IPv6 address.
652             mDNSAddrMapIPv4toIPv6(&info->NewAddress, &req.extAddress);
653 
654             err = mDNSPlatformSendUDP(m, start, end, 0, mDNSNULL, &m->Router, NATPMPPort, mDNSfalse);
655             debugf("uDNS_SendNATMsg: Sent PCP Mapping request %d", err);
656 
657             // Unset the sentNATPMP flag, so that we'll send a NAT-PMP packet if we
658             // receive a NAT-PMP "Unsupported Version" packet. This will result in every
659             // renewal, retransmission, etc. being tried first as PCP, then if a NAT-PMP
660             // "Unsupported Version" response is received, fall-back & send the request
661             // using NAT-PMP.
662             info->sentNATPMP = mDNSfalse;
663 
664 #ifdef _LEGACY_NAT_TRAVERSAL_
665             // If an unmapping is being performed, then don't send an LNT discovery message or an LNT port map request.
666             if (!unmapping)
667             {
668                 if (mDNSIPPortIsZero(m->UPnPRouterPort) || mDNSIPPortIsZero(m->UPnPSOAPPort))
669                 {
670                     LNT_SendDiscoveryMsg(m);
671                     debugf("uDNS_SendNATMsg: LNT_SendDiscoveryMsg");
672                 }
673                 else
674                 {
675                     mStatus lnterr = LNT_MapPort(m, info);
676                     if (lnterr)
677                         LogMsg("uDNS_SendNATMsg: LNT_MapPort returned error %d", lnterr);
678 
679                     err = err ? err : lnterr; // PCP error takes precedence
680                 }
681             }
682 #else
683             (void)unmapping; // Unused
684 #endif // _LEGACY_NAT_TRAVERSAL_
685         }
686     }
687 
688     return(err);
689 }
690 
RecreateNATMappings(mDNS * const m,const mDNSu32 waitTicks)691 mDNSexport void RecreateNATMappings(mDNS *const m, const mDNSu32 waitTicks)
692 {
693     mDNSu32 when = NonZeroTime(m->timenow + waitTicks);
694     NATTraversalInfo *n;
695     for (n = m->NATTraversals; n; n=n->next)
696     {
697         n->ExpiryTime    = 0;       // Mark this mapping as expired
698         n->retryInterval = NATMAP_INIT_RETRY;
699         n->retryPortMap  = when;
700         n->lastSuccessfulProtocol = NATTProtocolNone;
701         if (!n->Protocol) n->NewResult = mStatus_NoError;
702 #ifdef _LEGACY_NAT_TRAVERSAL_
703         if (n->tcpInfo.sock) { mDNSPlatformTCPCloseConnection(n->tcpInfo.sock); n->tcpInfo.sock = mDNSNULL; }
704 #endif // _LEGACY_NAT_TRAVERSAL_
705     }
706 
707     m->PCPNonce[0] = mDNSRandom(-1);
708     m->PCPNonce[1] = mDNSRandom(-1);
709     m->PCPNonce[2] = mDNSRandom(-1);
710     m->retryIntervalGetAddr = 0;
711     m->retryGetAddr = when;
712 
713 #ifdef _LEGACY_NAT_TRAVERSAL_
714     LNT_ClearState(m);
715 #endif // _LEGACY_NAT_TRAVERSAL_
716 
717     m->NextScheduledNATOp = m->timenow;     // Need to send packets immediately
718 }
719 
natTraversalHandleAddressReply(mDNS * const m,mDNSu16 err,mDNSv4Addr ExtAddr)720 mDNSexport void natTraversalHandleAddressReply(mDNS *const m, mDNSu16 err, mDNSv4Addr ExtAddr)
721 {
722     static mDNSu16 last_err = 0;
723     NATTraversalInfo *n;
724 
725     if (err)
726     {
727         if (err != last_err) LogMsg("Error getting external address %d", err);
728         ExtAddr = zerov4Addr;
729     }
730     else
731     {
732         LogInfo("Received external IP address %.4a from NAT", &ExtAddr);
733         if (mDNSv4AddrIsRFC1918(&ExtAddr))
734             LogMsg("Double NAT (external NAT gateway address %.4a is also a private RFC 1918 address)", &ExtAddr);
735         if (mDNSIPv4AddressIsZero(ExtAddr))
736             err = NATErr_NetFail; // fake error to handle routers that pathologically report success with the zero address
737     }
738 
739     // Globally remember the most recently discovered address, so it can be used in each
740     // new NATTraversal structure
741     m->ExtAddress = ExtAddr;
742 
743     if (!err) // Success, back-off to maximum interval
744         m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
745     else if (!last_err) // Failure after success, retry quickly (then back-off exponentially)
746         m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
747     // else back-off normally in case of pathological failures
748 
749     m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
750     if (m->NextScheduledNATOp - m->retryGetAddr > 0)
751         m->NextScheduledNATOp = m->retryGetAddr;
752 
753     last_err = err;
754 
755     for (n = m->NATTraversals; n; n=n->next)
756     {
757         // We should change n->NewAddress only when n is one of:
758         // 1) a mapping operation that most recently succeeded using NAT-PMP or UPnP/IGD,
759         //    because such an operation needs the update now. If the lastSuccessfulProtocol
760         //    is currently none, then natTraversalHandlePortMapReplyWithAddress() will be
761         //    called should NAT-PMP or UPnP/IGD succeed in the future.
762         // 2) an address-only operation that did not succeed via PCP, because when such an
763         //    operation succeeds via PCP, it's for the TCP discard port just to learn the
764         //    address. And that address may be different than the external address
765         //    discovered via NAT-PMP or UPnP/IGD. If the lastSuccessfulProtocol
766         //    is currently none, we must update the NewAddress as PCP may not succeed.
767         if (!mDNSSameIPv4Address(n->NewAddress, ExtAddr) &&
768              (n->Protocol ?
769                (n->lastSuccessfulProtocol == NATTProtocolNATPMP || n->lastSuccessfulProtocol == NATTProtocolUPNPIGD) :
770                (n->lastSuccessfulProtocol != NATTProtocolPCP)))
771         {
772             // Needs an update immediately
773             n->NewAddress    = ExtAddr;
774             n->ExpiryTime    = 0;
775             n->retryInterval = NATMAP_INIT_RETRY;
776             n->retryPortMap  = m->timenow;
777 #ifdef _LEGACY_NAT_TRAVERSAL_
778             if (n->tcpInfo.sock) { mDNSPlatformTCPCloseConnection(n->tcpInfo.sock); n->tcpInfo.sock = mDNSNULL; }
779 #endif // _LEGACY_NAT_TRAVERSAL_
780 
781             m->NextScheduledNATOp = m->timenow;     // Need to send packets immediately
782         }
783     }
784 }
785 
786 // Both places that call NATSetNextRenewalTime() update m->NextScheduledNATOp correctly afterwards
NATSetNextRenewalTime(mDNS * const m,NATTraversalInfo * n)787 mDNSlocal void NATSetNextRenewalTime(mDNS *const m, NATTraversalInfo *n)
788 {
789     n->retryInterval = (n->ExpiryTime - m->timenow)/2;
790     if (n->retryInterval < NATMAP_MIN_RETRY_INTERVAL)   // Min retry interval is 2 seconds
791         n->retryInterval = NATMAP_MIN_RETRY_INTERVAL;
792     n->retryPortMap = m->timenow + n->retryInterval;
793 }
794 
natTraversalHandlePortMapReplyWithAddress(mDNS * const m,NATTraversalInfo * n,const mDNSInterfaceID InterfaceID,mDNSu16 err,mDNSv4Addr extaddr,mDNSIPPort extport,mDNSu32 lease,NATTProtocol protocol)795 mDNSlocal void natTraversalHandlePortMapReplyWithAddress(mDNS *const m, NATTraversalInfo *n, const mDNSInterfaceID InterfaceID, mDNSu16 err, mDNSv4Addr extaddr, mDNSIPPort extport, mDNSu32 lease, NATTProtocol protocol)
796 {
797     const char *prot = n->Protocol == 0 ? "Add" : n->Protocol == NATOp_MapUDP ? "UDP" : n->Protocol == NATOp_MapTCP ? "TCP" : "???";
798     (void)prot;
799     n->NewResult = err;
800     if (err || lease == 0 || mDNSIPPortIsZero(extport))
801     {
802         LogInfo("natTraversalHandlePortMapReplyWithAddress: %p Response %s Port %5d External %.4a:%d lease %d error %d",
803                 n, prot, mDNSVal16(n->IntPort), &extaddr, mDNSVal16(extport), lease, err);
804         n->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
805         n->retryPortMap = m->timenow + NATMAP_MAX_RETRY_INTERVAL;
806         // No need to set m->NextScheduledNATOp here, since we're only ever extending the m->retryPortMap time
807         if      (err == NATErr_Refused) n->NewResult = mStatus_NATPortMappingDisabled;
808         else if (err > NATErr_None && err <= NATErr_Opcode) n->NewResult = mStatus_NATPortMappingUnsupported;
809     }
810     else
811     {
812         if (lease > 999999999UL / mDNSPlatformOneSecond)
813             lease = 999999999UL / mDNSPlatformOneSecond;
814         n->ExpiryTime = NonZeroTime(m->timenow + lease * mDNSPlatformOneSecond);
815 
816         if (!mDNSSameIPv4Address(n->NewAddress, extaddr) || !mDNSSameIPPort(n->RequestedPort, extport))
817             LogInfo("natTraversalHandlePortMapReplyWithAddress: %p %s Response %s Port %5d External %.4a:%d changed to %.4a:%d lease %d",
818                     n,
819                     (n->lastSuccessfulProtocol == NATTProtocolNone    ? "None    " :
820                      n->lastSuccessfulProtocol == NATTProtocolNATPMP  ? "NAT-PMP " :
821                      n->lastSuccessfulProtocol == NATTProtocolUPNPIGD ? "UPnP/IGD" :
822                      n->lastSuccessfulProtocol == NATTProtocolPCP     ? "PCP     " :
823                      /* else */                                         "Unknown " ),
824                     prot, mDNSVal16(n->IntPort), &n->NewAddress, mDNSVal16(n->RequestedPort),
825                     &extaddr, mDNSVal16(extport), lease);
826 
827         n->InterfaceID   = InterfaceID;
828         n->NewAddress    = extaddr;
829         if (n->Protocol) n->RequestedPort = extport; // Don't report the (PCP) external port to address-only operations
830         n->lastSuccessfulProtocol = protocol;
831 
832         NATSetNextRenewalTime(m, n);            // Got our port mapping; now set timer to renew it at halfway point
833         m->NextScheduledNATOp = m->timenow;     // May need to invoke client callback immediately
834     }
835 }
836 
837 // To be called for NAT-PMP or UPnP/IGD mappings, to use currently discovered (global) address
natTraversalHandlePortMapReply(mDNS * const m,NATTraversalInfo * n,const mDNSInterfaceID InterfaceID,mDNSu16 err,mDNSIPPort extport,mDNSu32 lease,NATTProtocol protocol)838 mDNSexport void natTraversalHandlePortMapReply(mDNS *const m, NATTraversalInfo *n, const mDNSInterfaceID InterfaceID, mDNSu16 err, mDNSIPPort extport, mDNSu32 lease, NATTProtocol protocol)
839 {
840     natTraversalHandlePortMapReplyWithAddress(m, n, InterfaceID, err, m->ExtAddress, extport, lease, protocol);
841 }
842 
843 // Must be called with the mDNS_Lock held
mDNS_StartNATOperation_internal(mDNS * const m,NATTraversalInfo * traversal)844 mDNSexport mStatus mDNS_StartNATOperation_internal(mDNS *const m, NATTraversalInfo *traversal)
845 {
846     NATTraversalInfo **n;
847 
848     LogInfo("mDNS_StartNATOperation_internal %p Protocol %d IntPort %d RequestedPort %d NATLease %d", traversal,
849             traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
850 
851     // Note: It important that new traversal requests are appended at the *end* of the list, not prepended at the start
852     for (n = &m->NATTraversals; *n; n=&(*n)->next)
853     {
854         if (traversal == *n)
855         {
856             LogFatalError("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
857                    traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease);
858             return(mStatus_AlreadyRegistered);
859         }
860         if (traversal->Protocol && traversal->Protocol == (*n)->Protocol && mDNSSameIPPort(traversal->IntPort, (*n)->IntPort) &&
861             !mDNSSameIPPort(traversal->IntPort, SSHPort))
862             LogMsg("Warning: Created port mapping request %p Prot %d Int %d TTL %d "
863                    "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
864                    traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
865                    *n,        (*n)->Protocol, mDNSVal16((*n)->IntPort), (*n)->NATLease);
866     }
867 
868     // Initialize necessary fields
869     traversal->next            = mDNSNULL;
870     traversal->ExpiryTime      = 0;
871     traversal->retryInterval   = NATMAP_INIT_RETRY;
872     traversal->retryPortMap    = m->timenow;
873     traversal->NewResult       = mStatus_NoError;
874     traversal->lastSuccessfulProtocol = NATTProtocolNone;
875     traversal->sentNATPMP      = mDNSfalse;
876     traversal->ExternalAddress = onesIPv4Addr;
877     traversal->NewAddress      = zerov4Addr;
878     traversal->ExternalPort    = zeroIPPort;
879     traversal->Lifetime        = 0;
880     traversal->Result          = mStatus_NoError;
881 
882     // set default lease if necessary
883     if (!traversal->NATLease) traversal->NATLease = NATMAP_DEFAULT_LEASE;
884 
885 #ifdef _LEGACY_NAT_TRAVERSAL_
886     mDNSPlatformMemZero(&traversal->tcpInfo, sizeof(traversal->tcpInfo));
887 #endif // _LEGACY_NAT_TRAVERSAL_
888 
889     if (!m->NATTraversals)      // If this is our first NAT request, kick off an address request too
890     {
891         m->retryGetAddr         = m->timenow;
892         m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
893     }
894 
895     // If this is an address-only operation, initialize to the current global address,
896     // or (in non-PCP environments) we won't know the address until the next external
897     // address request/response.
898     if (!traversal->Protocol)
899     {
900         traversal->NewAddress = m->ExtAddress;
901     }
902 
903     m->NextScheduledNATOp = m->timenow; // This will always trigger sending the packet ASAP, and generate client callback if necessary
904 
905     *n = traversal;     // Append new NATTraversalInfo to the end of our list
906 
907     return(mStatus_NoError);
908 }
909 
910 // Must be called with the mDNS_Lock held
mDNS_StopNATOperation_internal(mDNS * m,NATTraversalInfo * traversal)911 mDNSexport mStatus mDNS_StopNATOperation_internal(mDNS *m, NATTraversalInfo *traversal)
912 {
913     mDNSBool unmap = mDNStrue;
914     NATTraversalInfo *p;
915     NATTraversalInfo **ptr = &m->NATTraversals;
916 
917     while (*ptr && *ptr != traversal) ptr=&(*ptr)->next;
918     if (*ptr) *ptr = (*ptr)->next;      // If we found it, cut this NATTraversalInfo struct from our list
919     else
920     {
921         LogMsg("mDNS_StopNATOperation_internal: NATTraversalInfo %p not found in list", traversal);
922         return(mStatus_BadReferenceErr);
923     }
924 
925     LogInfo("mDNS_StopNATOperation_internal %p %d %d %d %d", traversal,
926             traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
927 
928     if (m->CurrentNATTraversal == traversal)
929         m->CurrentNATTraversal = m->CurrentNATTraversal->next;
930 
931     // If there is a match for the operation being stopped, don't send a deletion request (unmap)
932     for (p = m->NATTraversals; p; p=p->next)
933     {
934         if (traversal->Protocol ?
935             ((traversal->Protocol == p->Protocol && mDNSSameIPPort(traversal->IntPort, p->IntPort)) ||
936              (!p->Protocol && traversal->Protocol == NATOp_MapTCP && mDNSSameIPPort(traversal->IntPort, DiscardPort))) :
937             (!p->Protocol || (p->Protocol == NATOp_MapTCP && mDNSSameIPPort(p->IntPort, DiscardPort))))
938         {
939             LogInfo("Warning: Removed port mapping request %p Prot %d Int %d TTL %d "
940                     "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
941                     traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
942                             p,         p->Protocol, mDNSVal16(        p->IntPort),         p->NATLease);
943             unmap = mDNSfalse;
944         }
945     }
946 
947     // Even if we DIDN'T make a successful UPnP mapping yet, we might still have a partially-open TCP connection we need to clean up
948     // Before zeroing traversal->RequestedPort below, perform the LNT unmapping, which requires the mapping's external port,
949     // held by the traversal->RequestedPort variable.
950     #ifdef _LEGACY_NAT_TRAVERSAL_
951     {
952         mStatus err = LNT_UnmapPort(m, traversal);
953         if (err) LogMsg("Legacy NAT Traversal - unmap request failed with error %d", err);
954     }
955     #endif // _LEGACY_NAT_TRAVERSAL_
956 
957     if (traversal->ExpiryTime && unmap)
958     {
959         traversal->NATLease = 0;
960         traversal->retryInterval = 0;
961 
962         // In case we most recently sent NAT-PMP, we need to set sentNATPMP to false so
963         // that we'll send a NAT-PMP request to destroy the mapping. We do this because
964         // the NATTraversal struct has already been cut from the list, and the client
965         // layer will destroy the memory upon returning from this function, so we can't
966         // try PCP first and then fall-back to NAT-PMP. That is, if we most recently
967         // created/renewed the mapping using NAT-PMP, we need to destroy it using NAT-PMP
968         // now, because we won't get a chance later.
969         traversal->sentNATPMP = mDNSfalse;
970 
971         // Both NAT-PMP & PCP RFCs state that the suggested port in deletion requests
972         // should be zero. And for PCP, the suggested external address should also be
973         // zero, specifically, the all-zeros IPv4-mapped address, since we would only
974         // would have requested an IPv4 address.
975         traversal->RequestedPort = zeroIPPort;
976         traversal->NewAddress = zerov4Addr;
977 
978         uDNS_SendNATMsg(m, traversal, traversal->lastSuccessfulProtocol != NATTProtocolNATPMP, mDNStrue);
979     }
980 
981     return(mStatus_NoError);
982 }
983 
mDNS_StartNATOperation(mDNS * const m,NATTraversalInfo * traversal)984 mDNSexport mStatus mDNS_StartNATOperation(mDNS *const m, NATTraversalInfo *traversal)
985 {
986     mStatus status;
987     mDNS_Lock(m);
988     status = mDNS_StartNATOperation_internal(m, traversal);
989     mDNS_Unlock(m);
990     return(status);
991 }
992 
mDNS_StopNATOperation(mDNS * const m,NATTraversalInfo * traversal)993 mDNSexport mStatus mDNS_StopNATOperation(mDNS *const m, NATTraversalInfo *traversal)
994 {
995     mStatus status;
996     mDNS_Lock(m);
997     status = mDNS_StopNATOperation_internal(m, traversal);
998     mDNS_Unlock(m);
999     return(status);
1000 }
1001 
1002 // ***************************************************************************
1003 #if COMPILER_LIKES_PRAGMA_MARK
1004 #pragma mark -
1005 #pragma mark - Long-Lived Queries
1006 #endif
1007 
1008 // Lock must be held -- otherwise m->timenow is undefined
StartLLQPolling(mDNS * const m,DNSQuestion * q)1009 mDNSlocal void StartLLQPolling(mDNS *const m, DNSQuestion *q)
1010 {
1011     debugf("StartLLQPolling: %##s", q->qname.c);
1012     q->state = LLQ_Poll;
1013     q->ThisQInterval = INIT_UCAST_POLL_INTERVAL;
1014     // We want to send our poll query ASAP, but the "+ 1" is because if we set the time to now,
1015     // we risk causing spurious "SendQueries didn't send all its queries" log messages
1016     q->LastQTime     = m->timenow - q->ThisQInterval + 1;
1017     SetNextQueryTime(m, q);
1018 }
1019 
putLLQ(DNSMessage * const msg,mDNSu8 * ptr,const DNSQuestion * const question,const LLQOptData * const data)1020 mDNSlocal mDNSu8 *putLLQ(DNSMessage *const msg, mDNSu8 *ptr, const DNSQuestion *const question, const LLQOptData *const data)
1021 {
1022     AuthRecord rr;
1023     ResourceRecord *opt = &rr.resrec;
1024     rdataOPT *optRD;
1025 
1026     //!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
1027     ptr = putQuestion(msg, ptr, msg->data + AbsoluteMaxDNSMessageData, &question->qname, question->qtype, question->qclass);
1028     if (!ptr) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL; }
1029 
1030     // locate OptRR if it exists, set pointer to end
1031     // !!!KRS implement me
1032 
1033     // format opt rr (fields not specified are zero-valued)
1034     mDNS_SetupResourceRecord(&rr, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
1035     opt->rrclass    = NormalMaxDNSMessageData;
1036     opt->rdlength   = sizeof(rdataOPT); // One option in this OPT record
1037     opt->rdestimate = sizeof(rdataOPT);
1038 
1039     optRD = &rr.resrec.rdata->u.opt[0];
1040     optRD->opt = kDNSOpt_LLQ;
1041     optRD->u.llq = *data;
1042     ptr = PutResourceRecordTTLJumbo(msg, ptr, &msg->h.numAdditionals, opt, 0);
1043     if (!ptr) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL; }
1044 
1045     return ptr;
1046 }
1047 
1048 // Normally we'd just request event packets be sent directly to m->LLQNAT.ExternalPort, except...
1049 // with LLQs over TLS/TCP we're doing a weird thing where instead of requesting packets be sent to ExternalAddress:ExternalPort
1050 // we're requesting that packets be sent to ExternalPort, but at the source address of our outgoing TCP connection.
1051 // Normally, after going through the NAT gateway, the source address of our outgoing TCP connection is the same as ExternalAddress,
1052 // so this is fine, except when the TCP connection ends up going over a VPN tunnel instead.
1053 // To work around this, if we find that the source address for our TCP connection is not a private address, we tell the Dot Mac
1054 // LLQ server to send events to us directly at port 5353 on that address, instead of at our mapped external NAT port.
1055 
GetLLQEventPort(const mDNS * const m,const mDNSAddr * const dst)1056 mDNSlocal mDNSu16 GetLLQEventPort(const mDNS *const m, const mDNSAddr *const dst)
1057 {
1058     mDNSAddr src;
1059     mDNSPlatformSourceAddrForDest(&src, dst);
1060     //LogMsg("GetLLQEventPort: src %#a for dst %#a (%d)", &src, dst, mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : 0);
1061     return(mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : mDNSVal16(MulticastDNSPort));
1062 }
1063 
1064 // Normally called with llq set.
1065 // May be called with llq NULL, when retransmitting a lost Challenge Response
sendChallengeResponse(mDNS * const m,DNSQuestion * const q,const LLQOptData * llq)1066 mDNSlocal void sendChallengeResponse(mDNS *const m, DNSQuestion *const q, const LLQOptData *llq)
1067 {
1068     mDNSu8 *responsePtr = m->omsg.data;
1069     LLQOptData llqBuf;
1070 
1071     if (q->tcp) { LogMsg("sendChallengeResponse: ERROR!!: question %##s (%s) tcp non-NULL", q->qname.c, DNSTypeName(q->qtype)); return; }
1072 
1073     if (q->ntries++ == kLLQ_MAX_TRIES)
1074     {
1075         LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s", kLLQ_MAX_TRIES, q->qname.c);
1076         StartLLQPolling(m,q);
1077         return;
1078     }
1079 
1080     if (!llq)       // Retransmission: need to make a new LLQOptData
1081     {
1082         llqBuf.vers     = kLLQ_Vers;
1083         llqBuf.llqOp    = kLLQOp_Setup;
1084         llqBuf.err      = LLQErr_NoError;   // Don't need to tell server UDP notification port when sending over UDP
1085         llqBuf.id       = q->id;
1086         llqBuf.llqlease = q->ReqLease;
1087         llq = &llqBuf;
1088     }
1089 
1090     q->LastQTime     = m->timenow;
1091     q->ThisQInterval = q->tcp ? 0 : (kLLQ_INIT_RESEND * q->ntries * mDNSPlatformOneSecond);     // If using TCP, don't need to retransmit
1092     SetNextQueryTime(m, q);
1093 
1094     // To simulate loss of challenge response packet, uncomment line below
1095     //if (q->ntries == 1) return;
1096 
1097     InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
1098     responsePtr = putLLQ(&m->omsg, responsePtr, q, llq);
1099     if (responsePtr)
1100     {
1101         mStatus err = mDNSSendDNSMessage(m, &m->omsg, responsePtr, mDNSInterface_Any, mDNSNULL, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSfalse);
1102         if (err) { LogMsg("sendChallengeResponse: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err); }
1103     }
1104     else StartLLQPolling(m,q);
1105 }
1106 
SetLLQTimer(mDNS * const m,DNSQuestion * const q,const LLQOptData * const llq)1107 mDNSlocal void SetLLQTimer(mDNS *const m, DNSQuestion *const q, const LLQOptData *const llq)
1108 {
1109     mDNSs32 lease = (mDNSs32)llq->llqlease * mDNSPlatformOneSecond;
1110     q->ReqLease      = llq->llqlease;
1111     q->LastQTime     = m->timenow;
1112     q->expire        = m->timenow + lease;
1113     q->ThisQInterval = lease/2 + mDNSRandom(lease/10);
1114     debugf("SetLLQTimer setting %##s (%s) to %d %d", q->qname.c, DNSTypeName(q->qtype), lease/mDNSPlatformOneSecond, q->ThisQInterval/mDNSPlatformOneSecond);
1115     SetNextQueryTime(m, q);
1116 }
1117 
recvSetupResponse(mDNS * const m,mDNSu8 rcode,DNSQuestion * const q,const LLQOptData * const llq)1118 mDNSlocal void recvSetupResponse(mDNS *const m, mDNSu8 rcode, DNSQuestion *const q, const LLQOptData *const llq)
1119 {
1120     if (rcode && rcode != kDNSFlag1_RC_NXDomain)
1121     { LogMsg("ERROR: recvSetupResponse %##s (%s) - rcode && rcode != kDNSFlag1_RC_NXDomain", q->qname.c, DNSTypeName(q->qtype)); return; }
1122 
1123     if (llq->llqOp != kLLQOp_Setup)
1124     { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad op %d", q->qname.c, DNSTypeName(q->qtype), llq->llqOp); return; }
1125 
1126     if (llq->vers != kLLQ_Vers)
1127     { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad vers %d", q->qname.c, DNSTypeName(q->qtype), llq->vers); return; }
1128 
1129     if (q->state == LLQ_InitialRequest)
1130     {
1131         //LogInfo("Got LLQ_InitialRequest");
1132 
1133         if (llq->err) { LogMsg("recvSetupResponse - received llq->err %d from server", llq->err); StartLLQPolling(m,q); return; }
1134 
1135         if (q->ReqLease != llq->llqlease)
1136             debugf("recvSetupResponse: requested lease %lu, granted lease %lu", q->ReqLease, llq->llqlease);
1137 
1138         // cache expiration in case we go to sleep before finishing setup
1139         q->ReqLease = llq->llqlease;
1140         q->expire = m->timenow + ((mDNSs32)llq->llqlease * mDNSPlatformOneSecond);
1141 
1142         // update state
1143         q->state  = LLQ_SecondaryRequest;
1144         q->id     = llq->id;
1145         q->ntries = 0; // first attempt to send response
1146         sendChallengeResponse(m, q, llq);
1147     }
1148     else if (q->state == LLQ_SecondaryRequest)
1149     {
1150         if (llq->err) { LogMsg("ERROR: recvSetupResponse %##s (%s) code %d from server", q->qname.c, DNSTypeName(q->qtype), llq->err); StartLLQPolling(m,q); return; }
1151         if (!mDNSSameOpaque64(&q->id, &llq->id))
1152         { LogMsg("recvSetupResponse - ID changed.  discarding"); return; }     // this can happen rarely (on packet loss + reordering)
1153         q->state         = LLQ_Established;
1154         q->ntries        = 0;
1155         SetLLQTimer(m, q, llq);
1156     }
1157 }
1158 
uDNS_recvLLQResponse(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * const end,const mDNSAddr * const srcaddr,const mDNSIPPort srcport,DNSQuestion ** matchQuestion)1159 mDNSexport uDNS_LLQType uDNS_recvLLQResponse(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
1160                                              const mDNSAddr *const srcaddr, const mDNSIPPort srcport, DNSQuestion **matchQuestion)
1161 {
1162     DNSQuestion pktQ, *q;
1163     if (msg->h.numQuestions && getQuestion(msg, msg->data, end, 0, &pktQ))
1164     {
1165         const rdataOPT *opt = GetLLQOptData(m, msg, end);
1166 
1167         for (q = m->Questions; q; q = q->next)
1168         {
1169             if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->qtype == pktQ.qtype && q->qnamehash == pktQ.qnamehash && SameDomainName(&q->qname, &pktQ.qname))
1170             {
1171                 debugf("uDNS_recvLLQResponse found %##s (%s) %d %#a %#a %X %X %X %X %d",
1172                        q->qname.c, DNSTypeName(q->qtype), q->state, srcaddr, &q->servAddr,
1173                        opt ? opt->u.llq.id.l[0] : 0, opt ? opt->u.llq.id.l[1] : 0, q->id.l[0], q->id.l[1], opt ? opt->u.llq.llqOp : 0);
1174                 if (q->state == LLQ_Poll) debugf("uDNS_LLQ_Events: q->state == LLQ_Poll msg->h.id %d q->TargetQID %d", mDNSVal16(msg->h.id), mDNSVal16(q->TargetQID));
1175                 if (q->state == LLQ_Poll && mDNSSameOpaque16(msg->h.id, q->TargetQID))
1176                 {
1177                     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
1178 
1179                     // Don't reset the state to IntialRequest as we may write that to the dynamic store
1180                     // and PrefPane might wrongly think that we are "Starting" instead of "Polling". If
1181                     // we are in polling state because of PCP/NAT-PMP disabled or DoubleNAT, next LLQNATCallback
1182                     // would kick us back to LLQInitialRequest. So, resetting the state here may not be useful.
1183                     //
1184                     // If we have a good NAT (neither PCP/NAT-PMP disabled nor Double-NAT), then we should not be
1185                     // possibly in polling state. To be safe, we want to retry from the start in that case
1186                     // as there may not be another LLQNATCallback
1187                     //
1188                     // NOTE: We can be in polling state if we cannot resolve the SOA record i.e, servAddr is set to
1189                     // all ones. In that case, we would set it in LLQ_InitialRequest as it overrides the PCP/NAT-PMP or
1190                     // Double-NAT state.
1191                     if (!mDNSAddressIsOnes(&q->servAddr) && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) &&
1192                         !m->LLQNAT.Result)
1193                     {
1194                         debugf("uDNS_recvLLQResponse got poll response; moving to LLQ_InitialRequest for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1195                         q->state         = LLQ_InitialRequest;
1196                     }
1197                     q->servPort      = zeroIPPort;      // Clear servPort so that startLLQHandshake will retry the GetZoneData processing
1198                     q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);    // Retry LLQ setup in approx 15 minutes
1199                     q->LastQTime     = m->timenow;
1200                     SetNextQueryTime(m, q);
1201                     *matchQuestion = q;
1202                     return uDNS_LLQ_Entire;     // uDNS_LLQ_Entire means flush stale records; assume a large effective TTL
1203                 }
1204                 // Note: In LLQ Event packets, the msg->h.id does not match our q->TargetQID, because in that case the msg->h.id nonce is selected by the server
1205                 else if (opt && q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Event && mDNSSameOpaque64(&opt->u.llq.id, &q->id))
1206                 {
1207                     mDNSu8 *ackEnd;
1208                     //debugf("Sending LLQ ack for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1209                     InitializeDNSMessage(&m->omsg.h, msg->h.id, ResponseFlags);
1210                     ackEnd = putLLQ(&m->omsg, m->omsg.data, q, &opt->u.llq);
1211                     if (ackEnd) mDNSSendDNSMessage(m, &m->omsg, ackEnd, mDNSInterface_Any, mDNSNULL, q->LocalSocket, srcaddr, srcport, mDNSNULL, mDNSfalse);
1212                     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
1213                     debugf("uDNS_LLQ_Events: q->state == LLQ_Established msg->h.id %d q->TargetQID %d", mDNSVal16(msg->h.id), mDNSVal16(q->TargetQID));
1214                     *matchQuestion = q;
1215                     return uDNS_LLQ_Events;
1216                 }
1217                 if (opt && mDNSSameOpaque16(msg->h.id, q->TargetQID))
1218                 {
1219                     if (q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Refresh && mDNSSameOpaque64(&opt->u.llq.id, &q->id) && msg->h.numAdditionals && !msg->h.numAnswers)
1220                     {
1221                         if (opt->u.llq.err != LLQErr_NoError) LogMsg("recvRefreshReply: received error %d from server", opt->u.llq.err);
1222                         else
1223                         {
1224                             //LogInfo("Received refresh confirmation ntries %d for %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
1225                             // If we're waiting to go to sleep, then this LLQ deletion may have been the thing
1226                             // we were waiting for, so schedule another check to see if we can sleep now.
1227                             if (opt->u.llq.llqlease == 0 && m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
1228                             GrantCacheExtensions(m, q, opt->u.llq.llqlease);
1229                             SetLLQTimer(m, q, &opt->u.llq);
1230                             q->ntries = 0;
1231                         }
1232                         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
1233                         *matchQuestion = q;
1234                         return uDNS_LLQ_Ignore;
1235                     }
1236                     if (q->state < LLQ_Established && mDNSSameAddress(srcaddr, &q->servAddr))
1237                     {
1238                         LLQ_State oldstate = q->state;
1239                         recvSetupResponse(m, msg->h.flags.b[1] & kDNSFlag1_RC_Mask, q, &opt->u.llq);
1240                         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
1241                         // We have a protocol anomaly here in the LLQ definition.
1242                         // Both the challenge packet from the server and the ack+answers packet have opt->u.llq.llqOp == kLLQOp_Setup.
1243                         // However, we need to treat them differently:
1244                         // The challenge packet has no answers in it, and tells us nothing about whether our cache entries
1245                         // are still valid, so this packet should not cause us to do anything that messes with our cache.
1246                         // The ack+answers packet gives us the whole truth, so we should handle it by updating our cache
1247                         // to match the answers in the packet, and only the answers in the packet.
1248                         *matchQuestion = q;
1249                         return (oldstate == LLQ_SecondaryRequest ? uDNS_LLQ_Entire : uDNS_LLQ_Ignore);
1250                     }
1251                 }
1252             }
1253         }
1254         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
1255     }
1256     *matchQuestion = mDNSNULL;
1257     return uDNS_LLQ_Not;
1258 }
1259 
1260 // Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
1261 struct TCPSocket_struct { mDNSIPPort port; TCPSocketFlags flags; /* ... */ };
1262 
1263 // tcpCallback is called to handle events (e.g. connection opening and data reception) on TCP connections for
1264 // Private DNS operations -- private queries, private LLQs, private record updates and private service updates
tcpCallback(TCPSocket * sock,void * context,mDNSBool ConnectionEstablished,mStatus err)1265 mDNSlocal void tcpCallback(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err)
1266 {
1267     tcpInfo_t *tcpInfo = (tcpInfo_t *)context;
1268     mDNSBool closed  = mDNSfalse;
1269     mDNS      *m       = tcpInfo->m;
1270     DNSQuestion *const q = tcpInfo->question;
1271     tcpInfo_t **backpointer =
1272         q                 ? &q->tcp :
1273         tcpInfo->rr       ? &tcpInfo->rr->tcp : mDNSNULL;
1274     if (backpointer && *backpointer != tcpInfo)
1275         LogMsg("tcpCallback: %d backpointer %p incorrect tcpInfo %p question %p rr %p",
1276                mDNSPlatformTCPGetFD(tcpInfo->sock), *backpointer, tcpInfo, q, tcpInfo->rr);
1277 
1278     if (err) goto exit;
1279 
1280     if (ConnectionEstablished)
1281     {
1282         mDNSu8    *end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
1283         DomainAuthInfo *AuthInfo;
1284 
1285         // Defensive coding for <rdar://problem/5546824> Crash in mDNSResponder at GetAuthInfoForName_internal + 366
1286         // Don't know yet what's causing this, but at least we can be cautious and try to avoid crashing if we find our pointers in an unexpected state
1287         if (tcpInfo->rr && tcpInfo->rr->resrec.name != &tcpInfo->rr->namestorage)
1288             LogMsg("tcpCallback: ERROR: tcpInfo->rr->resrec.name %p != &tcpInfo->rr->namestorage %p",
1289                    tcpInfo->rr->resrec.name, &tcpInfo->rr->namestorage);
1290         if (tcpInfo->rr  && tcpInfo->rr->resrec.name != &tcpInfo->rr->namestorage) return;
1291 
1292         AuthInfo =  tcpInfo->rr  ? GetAuthInfoForName(m, tcpInfo->rr->resrec.name)         : mDNSNULL;
1293 
1294         // connection is established - send the message
1295         if (q && q->LongLived && q->state == LLQ_Established)
1296         {
1297             // Lease renewal over TCP, resulting from opening a TCP connection in sendLLQRefresh
1298             end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
1299         }
1300         else if (q && q->LongLived && q->state != LLQ_Poll && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) && !mDNSIPPortIsZero(q->servPort))
1301         {
1302             // Notes:
1303             // If we have a NAT port mapping, ExternalPort is the external port
1304             // If we have a routable address so we don't need a port mapping, ExternalPort is the same as our own internal port
1305             // If we need a NAT port mapping but can't get one, then ExternalPort is zero
1306             LLQOptData llqData;         // set llq rdata
1307             llqData.vers  = kLLQ_Vers;
1308             llqData.llqOp = kLLQOp_Setup;
1309             llqData.err   = GetLLQEventPort(m, &tcpInfo->Addr); // We're using TCP; tell server what UDP port to send notifications to
1310             LogInfo("tcpCallback: eventPort %d", llqData.err);
1311             llqData.id    = zeroOpaque64;
1312             llqData.llqlease = kLLQ_DefLease;
1313             InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
1314             end = putLLQ(&tcpInfo->request, tcpInfo->request.data, q, &llqData);
1315             if (!end) { LogMsg("ERROR: tcpCallback - putLLQ"); err = mStatus_UnknownErr; goto exit; }
1316             AuthInfo = q->AuthInfo;     // Need to add TSIG to this message
1317             q->ntries = 0; // Reset ntries so that tcp/tls connection failures don't affect sendChallengeResponse failures
1318         }
1319         else if (q)
1320         {
1321             mDNSOpaque16 HeaderFlags = uQueryFlags;
1322 
1323             // LLQ Polling mode or non-LLQ uDNS over TCP
1324             InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, HeaderFlags);
1325             end = putQuestion(&tcpInfo->request, tcpInfo->request.data, tcpInfo->request.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
1326 
1327             AuthInfo = q->AuthInfo;     // Need to add TSIG to this message
1328         }
1329 
1330         err = mDNSSendDNSMessage(m, &tcpInfo->request, end, mDNSInterface_Any, sock, mDNSNULL, &tcpInfo->Addr, tcpInfo->Port, AuthInfo, mDNSfalse);
1331         if (err) { debugf("ERROR: tcpCallback: mDNSSendDNSMessage - %d", err); err = mStatus_UnknownErr; goto exit; }
1332 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
1333         if (mDNSSameIPPort(tcpInfo->Port, UnicastDNSPort))
1334         {
1335             MetricsUpdateDNSQuerySize((mDNSu32)(end - (mDNSu8 *)&tcpInfo->request));
1336         }
1337 #endif
1338 
1339         // Record time we sent this question
1340         if (q)
1341         {
1342             mDNS_Lock(m);
1343             q->LastQTime = m->timenow;
1344             if (q->ThisQInterval < (256 * mDNSPlatformOneSecond))   // Now we have a TCP connection open, make sure we wait at least 256 seconds before retrying
1345                 q->ThisQInterval = (256 * mDNSPlatformOneSecond);
1346             SetNextQueryTime(m, q);
1347             mDNS_Unlock(m);
1348         }
1349     }
1350     else
1351     {
1352         long n;
1353         const mDNSBool Read_replylen = (tcpInfo->nread < 2);  // Do we need to read the replylen field first?
1354         if (Read_replylen)         // First read the two-byte length preceeding the DNS message
1355         {
1356             mDNSu8 *lenptr = (mDNSu8 *)&tcpInfo->replylen;
1357             n = mDNSPlatformReadTCP(sock, lenptr + tcpInfo->nread, 2 - tcpInfo->nread, &closed);
1358             if (n < 0)
1359             {
1360                 LogMsg("ERROR: tcpCallback - attempt to read message length failed (%d)", n);
1361                 err = mStatus_ConnFailed;
1362                 goto exit;
1363             }
1364             else if (closed)
1365             {
1366                 // It's perfectly fine for this socket to close after the first reply. The server might
1367                 // be sending gratuitous replies using UDP and doesn't have a need to leave the TCP socket open.
1368                 // We'll only log this event if we've never received a reply before.
1369                 // BIND 9 appears to close an idle connection after 30 seconds.
1370                 if (tcpInfo->numReplies == 0)
1371                 {
1372                     LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
1373                     err = mStatus_ConnFailed;
1374                     goto exit;
1375                 }
1376                 else
1377                 {
1378                     // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1379                     // over this tcp connection.  That is, we only track whether we've received at least one response
1380                     // which may have been to a previous request sent over this tcp connection.
1381                     if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1382                     DisposeTCPConn(tcpInfo);
1383                     return;
1384                 }
1385             }
1386 
1387             tcpInfo->nread += n;
1388             if (tcpInfo->nread < 2) goto exit;
1389 
1390             tcpInfo->replylen = (mDNSu16)((mDNSu16)lenptr[0] << 8 | lenptr[1]);
1391             if (tcpInfo->replylen < sizeof(DNSMessageHeader))
1392             { LogMsg("ERROR: tcpCallback - length too short (%d bytes)", tcpInfo->replylen); err = mStatus_UnknownErr; goto exit; }
1393 
1394             tcpInfo->reply = (DNSMessage *) mDNSPlatformMemAllocate(tcpInfo->replylen);
1395             if (!tcpInfo->reply) { LogMsg("ERROR: tcpCallback - malloc failed"); err = mStatus_NoMemoryErr; goto exit; }
1396         }
1397 
1398         n = mDNSPlatformReadTCP(sock, ((char *)tcpInfo->reply) + (tcpInfo->nread - 2), tcpInfo->replylen - (tcpInfo->nread - 2), &closed);
1399 
1400         if (n < 0)
1401         {
1402             // If this is our only read for this invokation, and it fails, then that's bad.
1403             // But if we did successfully read some or all of the replylen field this time through,
1404             // and this is now our second read from the socket, then it's expected that sometimes
1405             // there may be no more data present, and that's perfectly okay.
1406             // Assuming failure of the second read is a problem is what caused this bug:
1407             // <rdar://problem/15043194> mDNSResponder fails to read DNS over TCP packet correctly
1408             if (!Read_replylen) { LogMsg("ERROR: tcpCallback - read returned %d", n); err = mStatus_ConnFailed; }
1409             goto exit;
1410         }
1411         else if (closed)
1412         {
1413             if (tcpInfo->numReplies == 0)
1414             {
1415                 LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
1416                 err = mStatus_ConnFailed;
1417                 goto exit;
1418             }
1419             else
1420             {
1421                 // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1422                 // over this tcp connection.  That is, we only track whether we've received at least one response
1423                 // which may have been to a previous request sent over this tcp connection.
1424                 if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1425                 DisposeTCPConn(tcpInfo);
1426                 return;
1427             }
1428         }
1429 
1430         tcpInfo->nread += n;
1431 
1432         if ((tcpInfo->nread - 2) == tcpInfo->replylen)
1433         {
1434             mDNSBool tls;
1435             DNSMessage *reply = tcpInfo->reply;
1436             mDNSu8     *end   = (mDNSu8 *)tcpInfo->reply + tcpInfo->replylen;
1437             mDNSAddr Addr  = tcpInfo->Addr;
1438             mDNSIPPort Port  = tcpInfo->Port;
1439             mDNSIPPort srcPort = zeroIPPort;
1440             tcpInfo->numReplies++;
1441             tcpInfo->reply    = mDNSNULL;   // Detach reply buffer from tcpInfo_t, to make sure client callback can't cause it to be disposed
1442             tcpInfo->nread    = 0;
1443             tcpInfo->replylen = 0;
1444 
1445             // If we're going to dispose this connection, do it FIRST, before calling client callback
1446             // Note: Sleep code depends on us clearing *backpointer here -- it uses the clearing of rr->tcp
1447             // as the signal that the DNS deregistration operation with the server has completed, and the machine may now sleep
1448             // If we clear the tcp pointer in the question, mDNSCoreReceiveResponse cannot find a matching question. Hence
1449             // we store the minimal information i.e., the source port of the connection in the question itself.
1450             // Dereference sock before it is disposed in DisposeTCPConn below.
1451 
1452             if (sock->flags & kTCPSocketFlags_UseTLS) tls = mDNStrue;
1453             else tls = mDNSfalse;
1454 
1455             if (q && q->tcp) {srcPort = q->tcp->SrcPort; q->tcpSrcPort = srcPort;}
1456 
1457             if (backpointer)
1458                 if (!q || !q->LongLived || m->SleepState)
1459                 { *backpointer = mDNSNULL; DisposeTCPConn(tcpInfo); }
1460 
1461             mDNSCoreReceive(m, reply, end, &Addr, Port, tls ? (mDNSAddr *)1 : mDNSNULL, srcPort, 0);
1462             // USE CAUTION HERE: Invoking mDNSCoreReceive may have caused the environment to change, including canceling this operation itself
1463 
1464             mDNSPlatformMemFree(reply);
1465             return;
1466         }
1467     }
1468 
1469 exit:
1470 
1471     if (err)
1472     {
1473         // Clear client backpointer FIRST -- that way if one of the callbacks cancels its operation
1474         // we won't end up double-disposing our tcpInfo_t
1475         if (backpointer) *backpointer = mDNSNULL;
1476 
1477         mDNS_Lock(m);       // Need to grab the lock to get m->timenow
1478 
1479         if (q)
1480         {
1481             if (q->ThisQInterval == 0)
1482             {
1483                 // We get here when we fail to establish a new TCP/TLS connection that would have been used for a new LLQ request or an LLQ renewal.
1484                 // Note that ThisQInterval is also zero when sendChallengeResponse resends the LLQ request on an extant TCP/TLS connection.
1485                 q->LastQTime = m->timenow;
1486                 if (q->LongLived)
1487                 {
1488                     // We didn't get the chance to send our request packet before the TCP/TLS connection failed.
1489                     // We want to retry quickly, but want to back off exponentially in case the server is having issues.
1490                     // Since ThisQInterval was 0, we can't just multiply by QuestionIntervalStep, we must track the number
1491                     // of TCP/TLS connection failures using ntries.
1492                     mDNSu32 count = q->ntries + 1; // want to wait at least 1 second before retrying
1493 
1494                     q->ThisQInterval = InitialQuestionInterval;
1495 
1496                     for (; count; count--)
1497                         q->ThisQInterval *= QuestionIntervalStep;
1498 
1499                     if (q->ThisQInterval > LLQ_POLL_INTERVAL)
1500                         q->ThisQInterval = LLQ_POLL_INTERVAL;
1501                     else
1502                         q->ntries++;
1503 
1504                     LogMsg("tcpCallback: stream connection for LLQ %##s (%s) failed %d times, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ntries, q->ThisQInterval);
1505                 }
1506                 else
1507                 {
1508                     q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
1509                     LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
1510                 }
1511                 SetNextQueryTime(m, q);
1512             }
1513             else if (NextQSendTime(q) - m->timenow > (q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL))
1514             {
1515                 // If we get an error and our next scheduled query for this question is more than the max interval from now,
1516                 // reset the next query to ensure we wait no longer the maximum interval from now before trying again.
1517                 q->LastQTime     = m->timenow;
1518                 q->ThisQInterval = q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL;
1519                 SetNextQueryTime(m, q);
1520                 LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
1521             }
1522 
1523             // We're about to dispose of the TCP connection, so we must reset the state to retry over TCP/TLS
1524             // because sendChallengeResponse will send the query via UDP if we don't have a tcp pointer.
1525             // Resetting to LLQ_InitialRequest will cause uDNS_CheckCurrentQuestion to call startLLQHandshake, which
1526             // will attempt to establish a new tcp connection.
1527             if (q->LongLived && q->state == LLQ_SecondaryRequest)
1528                 q->state = LLQ_InitialRequest;
1529 
1530             // ConnFailed may happen if the server sends a TCP reset or TLS fails, in which case we want to retry establishing the LLQ
1531             // quickly rather than switching to polling mode.  This case is handled by the above code to set q->ThisQInterval just above.
1532             // If the error isn't ConnFailed, then the LLQ is in bad shape, so we switch to polling mode.
1533             if (err != mStatus_ConnFailed)
1534             {
1535                 if (q->LongLived && q->state != LLQ_Poll) StartLLQPolling(m, q);
1536             }
1537         }
1538 
1539         mDNS_Unlock(m);
1540 
1541         DisposeTCPConn(tcpInfo);
1542     }
1543 }
1544 
MakeTCPConn(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * const end,TCPSocketFlags flags,const mDNSAddr * const Addr,const mDNSIPPort Port,domainname * hostname,DNSQuestion * const question,AuthRecord * const rr)1545 mDNSlocal tcpInfo_t *MakeTCPConn(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
1546                                  TCPSocketFlags flags, const mDNSAddr *const Addr, const mDNSIPPort Port, domainname *hostname,
1547                                  DNSQuestion *const question, AuthRecord *const rr)
1548 {
1549     mStatus err;
1550     mDNSIPPort srcport = zeroIPPort;
1551     tcpInfo_t *info;
1552     mDNSBool useBackgroundTrafficClass;
1553 
1554     useBackgroundTrafficClass = question ? question->UseBackgroundTraffic : mDNSfalse;
1555 
1556     if ((flags & kTCPSocketFlags_UseTLS) && (!hostname || !hostname->c[0]))
1557     { LogMsg("MakeTCPConn: TLS connection being setup with NULL hostname"); return mDNSNULL; }
1558 
1559     info = (tcpInfo_t *) mDNSPlatformMemAllocateClear(sizeof(*info));
1560     if (!info) { LogMsg("ERROR: MakeTCP - memallocate failed"); return(mDNSNULL); }
1561 
1562     if (msg)
1563     {
1564         const mDNSu8 *const start = (const mDNSu8 *)msg;
1565         if ((end < start) || ((end - start) > (int)sizeof(info->request)))
1566         {
1567             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
1568                 "MakeTCPConn: invalid DNS message pointers -- msg: %p, end: %p", msg, end);
1569             mDNSPlatformMemFree(info);
1570             return mDNSNULL;
1571         }
1572         info->requestLen = (int)(end - start);
1573         mDNSPlatformMemCopy(&info->request, msg, info->requestLen);
1574     }
1575 
1576     info->m          = m;
1577     info->sock       = mDNSPlatformTCPSocket(flags, Addr->type, &srcport, hostname, useBackgroundTrafficClass);
1578     info->question   = question;
1579     info->rr         = rr;
1580     info->Addr       = *Addr;
1581     info->Port       = Port;
1582     info->reply      = mDNSNULL;
1583     info->replylen   = 0;
1584     info->nread      = 0;
1585     info->numReplies = 0;
1586     info->SrcPort = srcport;
1587 
1588     if (!info->sock) { LogMsg("MakeTCPConn: unable to create TCP socket"); mDNSPlatformMemFree(info); return(mDNSNULL); }
1589     mDNSPlatformSetSocktOpt(info->sock, mDNSTransport_TCP, Addr->type, question);
1590     err = mDNSPlatformTCPConnect(info->sock, Addr, Port, (question ? question->InterfaceID : mDNSNULL), tcpCallback, info);
1591 
1592     // Probably suboptimal here.
1593     // Instead of returning mDNSNULL here on failure, we should probably invoke the callback with an error code.
1594     // That way clients can put all the error handling and retry/recovery code in one place,
1595     // instead of having to handle immediate errors in one place and async errors in another.
1596     // Also: "err == mStatus_ConnEstablished" probably never happens.
1597 
1598     // Don't need to log "connection failed" in customer builds -- it happens quite often during sleep, wake, configuration changes, etc.
1599     if      (err == mStatus_ConnEstablished) { tcpCallback(info->sock, info, mDNStrue, mStatus_NoError); }
1600     else if (err != mStatus_ConnPending    ) { LogInfo("MakeTCPConn: connection failed"); DisposeTCPConn(info); return(mDNSNULL); }
1601     return(info);
1602 }
1603 
DisposeTCPConn(struct tcpInfo_t * tcp)1604 mDNSexport void DisposeTCPConn(struct tcpInfo_t *tcp)
1605 {
1606     mDNSPlatformTCPCloseConnection(tcp->sock);
1607     if (tcp->reply) mDNSPlatformMemFree(tcp->reply);
1608     mDNSPlatformMemFree(tcp);
1609 }
1610 
1611 // Lock must be held
startLLQHandshake(mDNS * m,DNSQuestion * q)1612 mDNSexport void startLLQHandshake(mDNS *m, DNSQuestion *q)
1613 {
1614     // States prior to LLQ_InitialRequest should not react to NAT Mapping changes.
1615     // startLLQHandshake is never called with q->state < LLQ_InitialRequest except
1616     // from LLQNATCallback.   When we are actually trying to do LLQ, then q->state will
1617     // be equal to or greater than LLQ_InitialRequest when LLQNATCallback calls
1618     // startLLQHandshake.
1619     if (q->state < LLQ_InitialRequest)
1620     {
1621         return;
1622     }
1623 
1624     if (m->LLQNAT.clientContext != mDNSNULL) // LLQNAT just started, give it some time
1625     {
1626         LogInfo("startLLQHandshake: waiting for NAT status for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1627         q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);    // Retry in approx 15 minutes
1628         q->LastQTime = m->timenow;
1629         SetNextQueryTime(m, q);
1630         return;
1631     }
1632 
1633     // Either we don't have {PCP, NAT-PMP, UPnP/IGD} support (ExternalPort is zero) or behind a Double NAT that may or
1634     // may not have {PCP, NAT-PMP, UPnP/IGD} support (NATResult is non-zero)
1635     if (mDNSIPPortIsZero(m->LLQNAT.ExternalPort) || m->LLQNAT.Result)
1636     {
1637         LogInfo("startLLQHandshake: Cannot receive inbound packets; will poll for %##s (%s) External Port %d, NAT Result %d",
1638                 q->qname.c, DNSTypeName(q->qtype), mDNSVal16(m->LLQNAT.ExternalPort), m->LLQNAT.Result);
1639         StartLLQPolling(m, q);
1640         return;
1641     }
1642 
1643     if (mDNSIPPortIsZero(q->servPort))
1644     {
1645         debugf("startLLQHandshake: StartGetZoneData for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1646         q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10);    // Retry in approx 15 minutes
1647         q->LastQTime     = m->timenow;
1648         SetNextQueryTime(m, q);
1649         q->servAddr = zeroAddr;
1650         // We know q->servPort is zero because of check above
1651         if (q->nta) CancelGetZoneData(m, q->nta);
1652         q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
1653         return;
1654     }
1655 
1656     debugf("startLLQHandshake: m->AdvertisedV4 %#a%s Server %#a:%d%s %##s (%s)",
1657            &m->AdvertisedV4,                     mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) ? " (RFC 1918)" : "",
1658            &q->servAddr, mDNSVal16(q->servPort), mDNSAddrIsRFC1918(&q->servAddr)             ? " (RFC 1918)" : "",
1659            q->qname.c, DNSTypeName(q->qtype));
1660 
1661     if (q->ntries++ >= kLLQ_MAX_TRIES)
1662     {
1663         LogMsg("startLLQHandshake: %d failed attempts for LLQ %##s Polling.", kLLQ_MAX_TRIES, q->qname.c);
1664         StartLLQPolling(m, q);
1665     }
1666     else
1667     {
1668         mDNSu8 *end;
1669         LLQOptData llqData;
1670 
1671         // set llq rdata
1672         llqData.vers  = kLLQ_Vers;
1673         llqData.llqOp = kLLQOp_Setup;
1674         llqData.err   = LLQErr_NoError; // Don't need to tell server UDP notification port when sending over UDP
1675         llqData.id    = zeroOpaque64;
1676         llqData.llqlease = kLLQ_DefLease;
1677 
1678         InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
1679         end = putLLQ(&m->omsg, m->omsg.data, q, &llqData);
1680         if (!end) { LogMsg("ERROR: startLLQHandshake - putLLQ"); StartLLQPolling(m,q); return; }
1681 
1682         mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, mDNSNULL, q->LocalSocket, &q->servAddr, q->servPort , mDNSNULL, mDNSfalse);
1683 
1684         // update question state
1685         q->state         = LLQ_InitialRequest;
1686         q->ReqLease      = kLLQ_DefLease;
1687         q->ThisQInterval = (kLLQ_INIT_RESEND * mDNSPlatformOneSecond);
1688         q->LastQTime     = m->timenow;
1689         SetNextQueryTime(m, q);
1690     }
1691 }
1692 
1693 
1694 // forward declaration so GetServiceTarget can do reverse lookup if needed
1695 mDNSlocal void GetStaticHostname(mDNS *m);
1696 
GetServiceTarget(mDNS * m,AuthRecord * const rr)1697 mDNSexport const domainname *GetServiceTarget(mDNS *m, AuthRecord *const rr)
1698 {
1699     debugf("GetServiceTarget %##s", rr->resrec.name->c);
1700 
1701     if (!rr->AutoTarget)        // If not automatically tracking this host's current name, just return the existing target
1702         return(&rr->resrec.rdata->u.srv.target);
1703     else
1704     {
1705         {
1706             const int srvcount = CountLabels(rr->resrec.name);
1707             HostnameInfo *besthi = mDNSNULL, *hi;
1708             int best = 0;
1709             for (hi = m->Hostnames; hi; hi = hi->next)
1710                 if (hi->arv4.state == regState_Registered || hi->arv4.state == regState_Refresh ||
1711                     hi->arv6.state == regState_Registered || hi->arv6.state == regState_Refresh)
1712                 {
1713                     int x, hostcount = CountLabels(&hi->fqdn);
1714                     for (x = hostcount < srvcount ? hostcount : srvcount; x > 0 && x > best; x--)
1715                         if (SameDomainName(SkipLeadingLabels(rr->resrec.name, srvcount - x), SkipLeadingLabels(&hi->fqdn, hostcount - x)))
1716                         { best = x; besthi = hi; }
1717                 }
1718 
1719             if (besthi) return(&besthi->fqdn);
1720         }
1721         if (m->StaticHostname.c[0]) return(&m->StaticHostname);
1722         else GetStaticHostname(m); // asynchronously do reverse lookup for primary IPv4 address
1723         LogInfo("GetServiceTarget: Returning NULL for %s", ARDisplayString(m, rr));
1724         return(mDNSNULL);
1725     }
1726 }
1727 
1728 mDNSlocal const domainname *PUBLIC_UPDATE_SERVICE_TYPE         = (const domainname*)"\x0B_dns-update"     "\x04_udp";
1729 mDNSlocal const domainname *PUBLIC_LLQ_SERVICE_TYPE            = (const domainname*)"\x08_dns-llq"        "\x04_udp";
1730 
1731 mDNSlocal const domainname *PRIVATE_UPDATE_SERVICE_TYPE        = (const domainname*)"\x0F_dns-update-tls" "\x04_tcp";
1732 mDNSlocal const domainname *PRIVATE_QUERY_SERVICE_TYPE         = (const domainname*)"\x0E_dns-query-tls"  "\x04_tcp";
1733 mDNSlocal const domainname *PRIVATE_LLQ_SERVICE_TYPE           = (const domainname*)"\x0C_dns-llq-tls"    "\x04_tcp";
1734 mDNSlocal const domainname *DNS_PUSH_NOTIFICATION_SERVICE_TYPE = (const domainname*)"\x0D_dns-push-tls"   "\x04_tcp";
1735 
1736 #define ZoneDataSRV(X) ( \
1737         (X)->ZoneService == ZoneServiceUpdate  ? ((X)->ZonePrivate ? PRIVATE_UPDATE_SERVICE_TYPE : PUBLIC_UPDATE_SERVICE_TYPE) : \
1738         (X)->ZoneService == ZoneServiceQuery   ? ((X)->ZonePrivate ? PRIVATE_QUERY_SERVICE_TYPE  : (const domainname*)""     ) : \
1739         (X)->ZoneService == ZoneServiceLLQ     ? ((X)->ZonePrivate ? PRIVATE_LLQ_SERVICE_TYPE    : PUBLIC_LLQ_SERVICE_TYPE   ) : \
1740         (X)->ZoneService == ZoneServiceDNSPush ? DNS_PUSH_NOTIFICATION_SERVICE_TYPE : (const domainname*)"")
1741 
1742 // Forward reference: GetZoneData_StartQuery references GetZoneData_QuestionCallback, and
1743 // GetZoneData_QuestionCallback calls GetZoneData_StartQuery
1744 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype);
1745 
1746 // GetZoneData_QuestionCallback is called from normal client callback context (core API calls allowed)
GetZoneData_QuestionCallback(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)1747 mDNSlocal void GetZoneData_QuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
1748 {
1749     ZoneData *zd = (ZoneData*)question->QuestionContext;
1750 
1751     debugf("GetZoneData_QuestionCallback: %s %s", AddRecord ? "Add" : "Rmv", RRDisplayString(m, answer));
1752 
1753     if (!AddRecord) return;                                             // Don't care about REMOVE events
1754     if (AddRecord == QC_addnocache && answer->rdlength == 0) return;    // Don't care about transient failure indications
1755     if (answer->rrtype != question->qtype) return;                      // Don't care about CNAMEs
1756 
1757     if (answer->rrtype == kDNSType_SOA)
1758     {
1759         debugf("GetZoneData GOT SOA %s", RRDisplayString(m, answer));
1760         mDNS_StopQuery(m, question);
1761         if (question->ThisQInterval != -1)
1762             LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1763         if (answer->rdlength)
1764         {
1765             AssignDomainName(&zd->ZoneName, answer->name);
1766             zd->ZoneClass = answer->rrclass;
1767             GetZoneData_StartQuery(m, zd, kDNSType_SRV);
1768         }
1769         else if (zd->CurrentSOA->c[0])
1770         {
1771             zd->CurrentSOA = (domainname *)(zd->CurrentSOA->c + zd->CurrentSOA->c[0]+1);
1772             AssignDomainName(&zd->question.qname, zd->CurrentSOA);
1773             GetZoneData_StartQuery(m, zd, kDNSType_SOA);
1774         }
1775         else
1776         {
1777             LogInfo("GetZoneData recursed to root label of %##s without finding SOA", zd->ChildName.c);
1778             zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
1779         }
1780     }
1781     else if (answer->rrtype == kDNSType_SRV)
1782     {
1783         debugf("GetZoneData GOT SRV %s", RRDisplayString(m, answer));
1784         mDNS_StopQuery(m, question);
1785         if (question->ThisQInterval != -1)
1786             LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1787 // Right now we don't want to fail back to non-encrypted operations
1788 // If the AuthInfo has the AutoTunnel field set, then we want private or nothing
1789 // <rdar://problem/5687667> BTMM: Don't fallback to unencrypted operations when SRV lookup fails
1790 #if 0
1791         if (!answer->rdlength && zd->ZonePrivate && zd->ZoneService != ZoneServiceQuery)
1792         {
1793             zd->ZonePrivate = mDNSfalse;    // Causes ZoneDataSRV() to yield a different SRV name when building the query
1794             GetZoneData_StartQuery(m, zd, kDNSType_SRV);        // Try again, non-private this time
1795         }
1796         else
1797 #endif
1798         {
1799             if (answer->rdlength)
1800             {
1801                 AssignDomainName(&zd->Host, &answer->rdata->u.srv.target);
1802                 zd->Port = answer->rdata->u.srv.port;
1803                 // The MakeTCPConn path, which is used by everything but DNS Push, won't work at all for
1804                 // IPv6.  This should be fixed for all cases we care about, but for now we make an exception
1805                 // for Push notifications: we do not look up the a record here, but rather rely on the DSO
1806                 // infrastructure to do a GetAddrInfo call on the name and try each IP address in sequence
1807                 // until one connects.  We can't do this for the other use cases because this is in the DSO
1808                 // code, not in MakeTCPConn.  Ultimately the fix for this is to use Network Framework to do
1809                 // the connection establishment for all of these use cases.
1810                 //
1811                 // One implication of this is that if two different zones have DNS push server SRV records
1812                 // pointing to the same server using a different domain name, we will not see these as being
1813                 // the same server, and will not share the connection.   This isn't something we can easily
1814                 // fix, and so the advice if someone runs into this and considers it a problem should be to
1815                 // use the same name.
1816                 //
1817                 // Another issue with this code is that at present, we do not wait for more than one SRV
1818                 // record--we cancel the query as soon as the first one comes in.   This isn't ideal: it
1819                 // would be better to wait until we've gotten all our answers and then pick the one with
1820                 // the highest priority.   Of course, this is unlikely to cause an operational problem in
1821                 // practice, and as with the previous point, the fix is easy: figure out which server you
1822                 // want people to use and don't list any other servers.   Fully switching to Network
1823                 // Framework for this would (I think!) address this problem, or at least make it someone
1824                 // else's problem.
1825                 if (zd->ZoneService != ZoneServiceDNSPush)
1826                 {
1827                     AssignDomainName(&zd->question.qname, &zd->Host);
1828                     GetZoneData_StartQuery(m, zd, kDNSType_A);
1829                 }
1830                 else
1831                 {
1832                     zd->ZoneDataCallback(m, mStatus_NoError, zd);
1833                 }
1834             }
1835             else
1836             {
1837                 zd->ZonePrivate = mDNSfalse;
1838                 zd->Host.c[0] = 0;
1839                 zd->Port = zeroIPPort;
1840                 zd->Addr = zeroAddr;
1841                 zd->ZoneDataCallback(m, mStatus_NoError, zd);
1842             }
1843         }
1844     }
1845     else if (answer->rrtype == kDNSType_A)
1846     {
1847         debugf("GetZoneData GOT A %s", RRDisplayString(m, answer));
1848         mDNS_StopQuery(m, question);
1849         if (question->ThisQInterval != -1)
1850             LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1851         zd->Addr.type  = mDNSAddrType_IPv4;
1852 	if (answer->rdlength == 4)
1853             zd->Addr.ip.v4 = answer->rdata->u.ipv4;
1854 	else
1855             zd->Addr.ip.v4 = zerov4Addr;
1856         // In order to simulate firewalls blocking our outgoing TCP connections, returning immediate ICMP errors or TCP resets,
1857         // the code below will make us try to connect to loopback, resulting in an immediate "port unreachable" failure.
1858         // This helps us test to make sure we handle this case gracefully
1859         // <rdar://problem/5607082> BTMM: mDNSResponder taking 100 percent CPU after upgrading to 10.5.1
1860 #if 0
1861         zd->Addr.ip.v4.b[0] = 127;
1862         zd->Addr.ip.v4.b[1] = 0;
1863         zd->Addr.ip.v4.b[2] = 0;
1864         zd->Addr.ip.v4.b[3] = 1;
1865 #endif
1866         // The caller needs to free the memory when done with zone data
1867         zd->ZoneDataCallback(m, mStatus_NoError, zd);
1868     }
1869 }
1870 
1871 // GetZoneData_StartQuery is called from normal client context (lock not held, or client callback)
GetZoneData_StartQuery(mDNS * const m,ZoneData * zd,mDNSu16 qtype)1872 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype)
1873 {
1874     if (qtype == kDNSType_SRV)
1875     {
1876         AssignDomainName(&zd->question.qname, ZoneDataSRV(zd));
1877         AppendDomainName(&zd->question.qname, &zd->ZoneName);
1878         debugf("lookupDNSPort %##s", zd->question.qname.c);
1879     }
1880 
1881     // CancelGetZoneData can get called at any time. We should stop the question if it has not been
1882     // stopped already. A value of -1 for ThisQInterval indicates that the question is not active
1883     // yet.
1884     zd->question.ThisQInterval       = -1;
1885     zd->question.InterfaceID         = mDNSInterface_Any;
1886     zd->question.flags               = 0;
1887     //zd->question.qname.c[0]        = 0;           // Already set
1888     zd->question.qtype               = qtype;
1889     zd->question.qclass              = kDNSClass_IN;
1890     zd->question.LongLived           = mDNSfalse;
1891     zd->question.ExpectUnique        = mDNStrue;
1892     zd->question.ForceMCast          = mDNSfalse;
1893     zd->question.ReturnIntermed      = mDNStrue;
1894     zd->question.SuppressUnusable    = mDNSfalse;
1895     zd->question.AppendSearchDomains = 0;
1896     zd->question.TimeoutQuestion     = 0;
1897     zd->question.WakeOnResolve       = 0;
1898     zd->question.UseBackgroundTraffic = mDNSfalse;
1899     zd->question.ProxyQuestion      = 0;
1900     zd->question.pid                 = mDNSPlatformGetPID();
1901     zd->question.euid                = 0;
1902     zd->question.QuestionCallback    = GetZoneData_QuestionCallback;
1903     zd->question.QuestionContext     = zd;
1904 
1905     //LogMsg("GetZoneData_StartQuery %##s (%s) %p", zd->question.qname.c, DNSTypeName(zd->question.qtype), zd->question.Private);
1906     return(mDNS_StartQuery(m, &zd->question));
1907 }
1908 
1909 // StartGetZoneData is an internal routine (i.e. must be called with the lock already held)
StartGetZoneData(mDNS * const m,const domainname * const name,const ZoneService target,ZoneDataCallback callback,void * ZoneDataContext)1910 mDNSexport ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *ZoneDataContext)
1911 {
1912     ZoneData *zd = (ZoneData*) mDNSPlatformMemAllocateClear(sizeof(*zd));
1913     if (!zd) { LogMsg("ERROR: StartGetZoneData - mDNSPlatformMemAllocateClear failed"); return mDNSNULL; }
1914     AssignDomainName(&zd->ChildName, name);
1915     zd->ZoneService      = target;
1916     zd->CurrentSOA       = &zd->ChildName;
1917     zd->ZoneName.c[0]    = 0;
1918     zd->ZoneClass        = 0;
1919     zd->Host.c[0]        = 0;
1920     zd->Port             = zeroIPPort;
1921     zd->Addr             = zeroAddr;
1922     zd->ZonePrivate      = mDNSfalse;
1923     zd->ZoneDataCallback = callback;
1924     zd->ZoneDataContext  = ZoneDataContext;
1925 
1926     zd->question.QuestionContext = zd;
1927 
1928     mDNS_DropLockBeforeCallback();      // GetZoneData_StartQuery expects to be called from a normal callback, so we emulate that here
1929     AssignDomainName(&zd->question.qname, zd->CurrentSOA);
1930     GetZoneData_StartQuery(m, zd, kDNSType_SOA);
1931     mDNS_ReclaimLockAfterCallback();
1932 
1933     return zd;
1934 }
1935 
1936 // Returns if the question is a GetZoneData question. These questions are special in
1937 // that they are created internally while resolving a private query or LLQs.
IsGetZoneDataQuestion(DNSQuestion * q)1938 mDNSexport mDNSBool IsGetZoneDataQuestion(DNSQuestion *q)
1939 {
1940     if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNStrue);
1941     else return(mDNSfalse);
1942 }
1943 
1944 // GetZoneData queries are a special case -- even if we have a key for them, we don't do them privately,
1945 // because that would result in an infinite loop (i.e. to do a private query we first need to get
1946 // the _dns-query-tls SRV record for the zone, and we can't do *that* privately because to do so
1947 // we'd need to already know the _dns-query-tls SRV record.
1948 // Also, as a general rule, we never do SOA queries privately
GetAuthInfoForQuestion(mDNS * m,const DNSQuestion * const q)1949 mDNSexport DomainAuthInfo *GetAuthInfoForQuestion(mDNS *m, const DNSQuestion *const q)  // Must be called with lock held
1950 {
1951     if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNSNULL);
1952     if (q->qtype            == kDNSType_SOA                ) return(mDNSNULL);
1953     return(GetAuthInfoForName_internal(m, &q->qname));
1954 }
1955 
1956 // ***************************************************************************
1957 #if COMPILER_LIKES_PRAGMA_MARK
1958 #pragma mark - host name and interface management
1959 #endif
1960 
1961 mDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr);
1962 mDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr);
1963 mDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time);
1964 
1965 // When this function is called, service record is already deregistered. We just
1966 // have to deregister the PTR and TXT records.
UpdateAllServiceRecords(mDNS * const m,AuthRecord * rr,mDNSBool reg)1967 mDNSlocal void UpdateAllServiceRecords(mDNS *const m, AuthRecord *rr, mDNSBool reg)
1968 {
1969     AuthRecord *r, *srvRR;
1970 
1971     if (rr->resrec.rrtype != kDNSType_SRV) { LogMsg("UpdateAllServiceRecords:ERROR!! ResourceRecord not a service record %s", ARDisplayString(m, rr)); return; }
1972 
1973     if (reg && rr->state == regState_NoTarget) { LogMsg("UpdateAllServiceRecords:ERROR!! SRV record %s in noTarget state during registration", ARDisplayString(m, rr)); return; }
1974 
1975     LogInfo("UpdateAllServiceRecords: ResourceRecord %s", ARDisplayString(m, rr));
1976 
1977     for (r = m->ResourceRecords; r; r=r->next)
1978     {
1979         if (!AuthRecord_uDNS(r)) continue;
1980         srvRR = mDNSNULL;
1981         if (r->resrec.rrtype == kDNSType_PTR)
1982             srvRR = r->Additional1;
1983         else if (r->resrec.rrtype == kDNSType_TXT)
1984             srvRR = r->DependentOn;
1985         if (srvRR && srvRR->resrec.rrtype != kDNSType_SRV)
1986             LogMsg("UpdateAllServiceRecords: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1987         if (srvRR == rr)
1988         {
1989             if (!reg)
1990             {
1991                 LogInfo("UpdateAllServiceRecords: deregistering %s", ARDisplayString(m, r));
1992                 r->SRVChanged = mDNStrue;
1993                 r->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1994                 r->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1995                 r->state = regState_DeregPending;
1996             }
1997             else
1998             {
1999                 // Clearing SRVchanged is a safety measure. If our pevious dereg never
2000                 // came back and we had a target change, we are starting fresh
2001                 r->SRVChanged = mDNSfalse;
2002                 // if it is already registered or in the process of registering, then don't
2003                 // bother re-registering. This happens today for non-BTMM domains where the
2004                 // TXT and PTR get registered before SRV records because of the delay in
2005                 // getting the port mapping. There is no point in re-registering the TXT
2006                 // and PTR records.
2007                 if ((r->state == regState_Registered) ||
2008                     (r->state == regState_Pending && r->nta && !mDNSIPv4AddressIsZero(r->nta->Addr.ip.v4)))
2009                     LogInfo("UpdateAllServiceRecords: not registering %s, state %d", ARDisplayString(m, r), r->state);
2010                 else
2011                 {
2012                     LogInfo("UpdateAllServiceRecords: registering %s, state %d", ARDisplayString(m, r), r->state);
2013                     ActivateUnicastRegistration(m, r);
2014                 }
2015             }
2016         }
2017     }
2018 }
2019 
2020 // Called in normal client context (lock not held)
2021 // Currently only supports SRV records for nat mapping
CompleteRecordNatMap(mDNS * m,NATTraversalInfo * n)2022 mDNSlocal void CompleteRecordNatMap(mDNS *m, NATTraversalInfo *n)
2023 {
2024     const domainname *target;
2025     domainname *srvt;
2026     AuthRecord *rr = (AuthRecord *)n->clientContext;
2027     debugf("SRVNatMap complete %.4a IntPort %u ExternalPort %u NATLease %u", &n->ExternalAddress, mDNSVal16(n->IntPort), mDNSVal16(n->ExternalPort), n->NATLease);
2028 
2029     if (!rr) { LogMsg("CompleteRecordNatMap called with unknown AuthRecord object"); return; }
2030     if (!n->NATLease) { LogMsg("CompleteRecordNatMap No NATLease for %s", ARDisplayString(m, rr)); return; }
2031 
2032     if (rr->resrec.rrtype != kDNSType_SRV) {LogMsg("CompleteRecordNatMap: Not a service record %s", ARDisplayString(m, rr)); return; }
2033 
2034     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) { LogInfo("CompleteRecordNatMap called for %s, Service deregistering", ARDisplayString(m, rr)); return; }
2035 
2036     if (rr->state == regState_DeregPending) { LogInfo("CompleteRecordNatMap called for %s, record in DeregPending", ARDisplayString(m, rr)); return; }
2037 
2038     // As we free the zone info after registering/deregistering with the server (See hndlRecordUpdateReply),
2039     // we need to restart the get zone data and nat mapping request to get the latest mapping result as we can't handle it
2040     // at this moment. Restart from the beginning.
2041     if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
2042     {
2043         LogInfo("CompleteRecordNatMap called for %s but no zone information!", ARDisplayString(m, rr));
2044         // We need to clear out the NATinfo state so that it will result in re-acquiring the mapping
2045         // and hence this callback called again.
2046         if (rr->NATinfo.clientContext)
2047         {
2048             mDNS_StopNATOperation_internal(m, &rr->NATinfo);
2049             rr->NATinfo.clientContext = mDNSNULL;
2050         }
2051         rr->state = regState_Pending;
2052         rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
2053         rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
2054         return;
2055     }
2056 
2057     mDNS_Lock(m);
2058     // Reevaluate the target always as Target could have changed while
2059     // we were getting the port mapping (See UpdateOneSRVRecord)
2060     target = GetServiceTarget(m, rr);
2061     srvt = GetRRDomainNameTarget(&rr->resrec);
2062     if (!target || target->c[0] == 0 || mDNSIPPortIsZero(n->ExternalPort))
2063     {
2064         if (target && target->c[0])
2065             LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
2066         else
2067             LogInfo("CompleteRecordNatMap - no target for %##s, ExternalPort %d", rr->resrec.name->c, mDNSVal16(n->ExternalPort));
2068         if (srvt) srvt->c[0] = 0;
2069         rr->state = regState_NoTarget;
2070         rr->resrec.rdlength = rr->resrec.rdestimate = 0;
2071         mDNS_Unlock(m);
2072         UpdateAllServiceRecords(m, rr, mDNSfalse);
2073         return;
2074     }
2075     LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
2076     // This function might get called multiple times during a network transition event. Previosuly, we could
2077     // have put the SRV record in NoTarget state above and deregistered all the other records. When this
2078     // function gets called again with a non-zero ExternalPort, we need to set the target and register the
2079     // other records again.
2080     if (srvt && !SameDomainName(srvt, target))
2081     {
2082         AssignDomainName(srvt, target);
2083         SetNewRData(&rr->resrec, mDNSNULL, 0);      // Update rdlength, rdestimate, rdatahash
2084     }
2085 
2086     // SRVChanged is set when when the target of the SRV record changes (See UpdateOneSRVRecord).
2087     // As a result of the target change, we might register just that SRV Record if it was
2088     // previously registered and we have a new target OR deregister SRV (and the associated
2089     // PTR/TXT records) if we don't have a target anymore. When we get a response from the server,
2090     // SRVChanged state tells that we registered/deregistered because of a target change
2091     // and hence handle accordingly e.g., if we deregistered, put the records in NoTarget state OR
2092     // if we registered then put it in Registered state.
2093     //
2094     // Here, we are registering all the records again from the beginning. Treat this as first time
2095     // registration rather than a temporary target change.
2096     rr->SRVChanged = mDNSfalse;
2097 
2098     // We want IsRecordMergeable to check whether it is a record whose update can be
2099     // sent with others. We set the time before we call IsRecordMergeable, so that
2100     // it does not fail this record based on time. We are interested in other checks
2101     // at this time
2102     rr->state = regState_Pending;
2103     rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
2104     rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
2105     if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
2106         // Delay the record registration by MERGE_DELAY_TIME so that we can merge them
2107         // into one update
2108         rr->LastAPTime += MERGE_DELAY_TIME;
2109     mDNS_Unlock(m);
2110     // We call this always even though it may not be necessary always e.g., normal registration
2111     // process where TXT and PTR gets registered followed by the SRV record after it gets
2112     // the port mapping. In that case, UpdateAllServiceRecords handles the optimization. The
2113     // update of TXT and PTR record is required if we entered noTargetState before as explained
2114     // above.
2115     UpdateAllServiceRecords(m, rr, mDNStrue);
2116 }
2117 
StartRecordNatMap(mDNS * m,AuthRecord * rr)2118 mDNSlocal void StartRecordNatMap(mDNS *m, AuthRecord *rr)
2119 {
2120     const mDNSu8 *p;
2121     mDNSu8 protocol;
2122 
2123     if (rr->resrec.rrtype != kDNSType_SRV)
2124     {
2125         LogInfo("StartRecordNatMap: Resource Record %##s type %d, not supported", rr->resrec.name->c, rr->resrec.rrtype);
2126         return;
2127     }
2128     p = rr->resrec.name->c;
2129     //Assume <Service Instance>.<App Protocol>.<Transport protocol>.<Name>
2130     // Skip the first two labels to get to the transport protocol
2131     if (p[0]) p += 1 + p[0];
2132     if (p[0]) p += 1 + p[0];
2133     if      (SameDomainLabel(p, (mDNSu8 *)"\x4" "_tcp")) protocol = NATOp_MapTCP;
2134     else if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_udp")) protocol = NATOp_MapUDP;
2135     else { LogMsg("StartRecordNatMap: could not determine transport protocol of service %##s", rr->resrec.name->c); return; }
2136 
2137     //LogMsg("StartRecordNatMap: clientContext %p IntPort %d srv.port %d %s",
2138     //  rr->NATinfo.clientContext, mDNSVal16(rr->NATinfo.IntPort), mDNSVal16(rr->resrec.rdata->u.srv.port), ARDisplayString(m, rr));
2139     if (rr->NATinfo.clientContext) mDNS_StopNATOperation_internal(m, &rr->NATinfo);
2140     rr->NATinfo.Protocol       = protocol;
2141 
2142     // Shouldn't be trying to set IntPort here --
2143     // BuildUpdateMessage overwrites srs->RR_SRV.resrec.rdata->u.srv.port with external (mapped) port number
2144     rr->NATinfo.IntPort        = rr->resrec.rdata->u.srv.port;
2145     rr->NATinfo.RequestedPort  = rr->resrec.rdata->u.srv.port;
2146     rr->NATinfo.NATLease       = 0;     // Request default lease
2147     rr->NATinfo.clientCallback = CompleteRecordNatMap;
2148     rr->NATinfo.clientContext  = rr;
2149     mDNS_StartNATOperation_internal(m, &rr->NATinfo);
2150 }
2151 
2152 // Unlink an Auth Record from the m->ResourceRecords list.
2153 // When a resource record enters regState_NoTarget initially, mDNS_Register_internal
2154 // does not initialize completely e.g., it cannot check for duplicates etc. The resource
2155 // record is temporarily left in the ResourceRecords list so that we can initialize later
2156 // when the target is resolvable. Similarly, when host name changes, we enter regState_NoTarget
2157 // and we do the same.
2158 
2159 // This UnlinkResourceRecord routine is very worrying. It bypasses all the normal cleanup performed
2160 // by mDNS_Deregister_internal and just unceremoniously cuts the record from the active list.
2161 // This is why re-regsitering this record was producing syslog messages like this:
2162 // "Error! Tried to add a NAT traversal that's already in the active list"
2163 // Right now UnlinkResourceRecord is fortunately only called by RegisterAllServiceRecords,
2164 // which then immediately calls mDNS_Register_internal to re-register the record, which probably
2165 // masked more serious problems. Any other use of UnlinkResourceRecord is likely to lead to crashes.
2166 // For now we'll workaround that specific problem by explicitly calling mDNS_StopNATOperation_internal,
2167 // but long-term we should either stop cancelling the record registration and then re-registering it,
2168 // or if we really do need to do this for some reason it should be done via the usual
2169 // mDNS_Deregister_internal path instead of just cutting the record from the list.
2170 
UnlinkResourceRecord(mDNS * const m,AuthRecord * const rr)2171 mDNSlocal mStatus UnlinkResourceRecord(mDNS *const m, AuthRecord *const rr)
2172 {
2173     AuthRecord **list = &m->ResourceRecords;
2174     while (*list && *list != rr) list = &(*list)->next;
2175     if (*list)
2176     {
2177         *list = rr->next;
2178         rr->next = mDNSNULL;
2179 
2180         // Temporary workaround to cancel any active NAT mapping operation
2181         if (rr->NATinfo.clientContext)
2182         {
2183             mDNS_StopNATOperation_internal(m, &rr->NATinfo);
2184             rr->NATinfo.clientContext = mDNSNULL;
2185             if (rr->resrec.rrtype == kDNSType_SRV) rr->resrec.rdata->u.srv.port = rr->NATinfo.IntPort;
2186         }
2187 
2188         return(mStatus_NoError);
2189     }
2190     LogMsg("UnlinkResourceRecord:ERROR!! - no such active record %##s", rr->resrec.name->c);
2191     return(mStatus_NoSuchRecord);
2192 }
2193 
2194 // We need to go through mDNS_Register again as we did not complete the
2195 // full initialization last time e.g., duplicate checks.
2196 // After we register, we will be in regState_GetZoneData.
RegisterAllServiceRecords(mDNS * const m,AuthRecord * rr)2197 mDNSlocal void RegisterAllServiceRecords(mDNS *const m, AuthRecord *rr)
2198 {
2199     LogInfo("RegisterAllServiceRecords: Service Record %##s", rr->resrec.name->c);
2200     // First Register the service record, we do this differently from other records because
2201     // when it entered NoTarget state, it did not go through complete initialization
2202     rr->SRVChanged = mDNSfalse;
2203     UnlinkResourceRecord(m, rr);
2204     mDNS_Register_internal(m, rr);
2205     // Register the other records
2206     UpdateAllServiceRecords(m, rr, mDNStrue);
2207 }
2208 
2209 // Called with lock held
UpdateOneSRVRecord(mDNS * m,AuthRecord * rr)2210 mDNSlocal void UpdateOneSRVRecord(mDNS *m, AuthRecord *rr)
2211 {
2212     // Target change if:
2213     // We have a target and were previously waiting for one, or
2214     // We had a target and no longer do, or
2215     // The target has changed
2216 
2217     domainname *curtarget = &rr->resrec.rdata->u.srv.target;
2218     const domainname *const nt = GetServiceTarget(m, rr);
2219     const domainname *const newtarget = nt ? nt : (domainname*)"";
2220     mDNSBool TargetChanged = (newtarget->c[0] && rr->state == regState_NoTarget) || !SameDomainName(curtarget, newtarget);
2221     mDNSBool HaveZoneData  = rr->nta && !mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4);
2222 
2223     // Nat state change if:
2224     // We were behind a NAT, and now we are behind a new NAT, or
2225     // We're not behind a NAT but our port was previously mapped to a different external port
2226     // We were not behind a NAT and now we are
2227 
2228     mDNSIPPort port        = rr->resrec.rdata->u.srv.port;
2229     mDNSBool NowNeedNATMAP = (rr->AutoTarget == Target_AutoHostAndNATMAP && !mDNSIPPortIsZero(port) && mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && rr->nta && !mDNSAddrIsRFC1918(&rr->nta->Addr));
2230     mDNSBool WereBehindNAT = (rr->NATinfo.clientContext != mDNSNULL);
2231     mDNSBool PortWasMapped = (rr->NATinfo.clientContext && !mDNSSameIPPort(rr->NATinfo.RequestedPort, port));       // I think this is always false -- SC Sept 07
2232     mDNSBool NATChanged    = (!WereBehindNAT && NowNeedNATMAP) || (!NowNeedNATMAP && PortWasMapped);
2233 
2234     (void)HaveZoneData; //unused
2235 
2236     LogInfo("UpdateOneSRVRecord: Resource Record %s TargetChanged %d, NewTarget %##s", ARDisplayString(m, rr), TargetChanged, nt->c);
2237 
2238     debugf("UpdateOneSRVRecord: %##s newtarget %##s TargetChanged %d HaveZoneData %d port %d NowNeedNATMAP %d WereBehindNAT %d PortWasMapped %d NATChanged %d",
2239            rr->resrec.name->c, newtarget,
2240            TargetChanged, HaveZoneData, mDNSVal16(port), NowNeedNATMAP, WereBehindNAT, PortWasMapped, NATChanged);
2241 
2242     mDNS_CheckLock(m);
2243 
2244     if (!TargetChanged && !NATChanged) return;
2245 
2246     // If we are deregistering the record, then ignore any NAT/Target change.
2247     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2248     {
2249         LogInfo("UpdateOneSRVRecord: Deregistering record, Ignoring TargetChanged %d, NATChanged %d for %##s, state %d", TargetChanged, NATChanged,
2250                 rr->resrec.name->c, rr->state);
2251         return;
2252     }
2253 
2254     if (newtarget)
2255         LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, newtarget %##s", TargetChanged, NATChanged, rr->resrec.name->c, rr->state, newtarget->c);
2256     else
2257         LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, null newtarget", TargetChanged, NATChanged, rr->resrec.name->c, rr->state);
2258     switch(rr->state)
2259     {
2260     case regState_NATMap:
2261         // In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
2262         // or is in the process of, or has already been, deregistered. This assumes that whenever we transition out
2263         // of this state, we need to look at the target again.
2264         return;
2265 
2266     case regState_UpdatePending:
2267         // We are getting a Target change/NAT change while the SRV record is being updated ?
2268         // let us not do anything for now.
2269         return;
2270 
2271     case regState_NATError:
2272         if (!NATChanged) return;
2273     // if nat changed, register if we have a target (below)
2274 	/* FALLTHROUGH */
2275 
2276     case regState_NoTarget:
2277         if (!newtarget->c[0])
2278         {
2279             LogInfo("UpdateOneSRVRecord: No target yet for Resource Record %s", ARDisplayString(m, rr));
2280             return;
2281         }
2282         RegisterAllServiceRecords(m, rr);
2283         return;
2284     case regState_DeregPending:
2285     // We are in DeregPending either because the service was deregistered from above or we handled
2286     // a NAT/Target change before and sent the deregistration below. There are a few race conditions
2287     // possible
2288     //
2289     // 1. We are handling a second NAT/Target change while the first dereg is in progress. It is possible
2290     //    that first dereg never made it through because there was no network connectivity e.g., disconnecting
2291     //    from network triggers this function due to a target change and later connecting to the network
2292     //    retriggers this function but the deregistration never made it through yet. Just fall through.
2293     //    If there is a target register otherwise deregister.
2294     //
2295     // 2. While we sent the dereg during a previous NAT/Target change, uDNS_DeregisterRecord gets
2296     //    called as part of service deregistration. When the response comes back, we call
2297     //    CompleteDeregistration rather than handle NAT/Target change because the record is in
2298     //    kDNSRecordTypeDeregistering state.
2299     //
2300     // 3. If the upper layer deregisters the service, we check for kDNSRecordTypeDeregistering both
2301     //    here in this function to avoid handling NAT/Target change and in hndlRecordUpdateReply to call
2302     //    CompleteDeregistration instead of handling NAT/Target change. Hence, we are not concerned
2303     //    about that case here.
2304     //
2305     // We just handle case (1) by falling through
2306     case regState_Pending:
2307     case regState_Refresh:
2308     case regState_Registered:
2309         // target or nat changed.  deregister service.  upon completion, we'll look for a new target
2310         rr->SRVChanged = mDNStrue;
2311         rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
2312         rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
2313         if (newtarget->c[0])
2314         {
2315             LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s, registering with new target %##s",
2316                     rr->resrec.name->c, newtarget->c);
2317             rr->state = regState_Pending;
2318         }
2319         else
2320         {
2321             LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s de-registering", rr->resrec.name->c);
2322             rr->state = regState_DeregPending;
2323             UpdateAllServiceRecords(m, rr, mDNSfalse);
2324         }
2325         return;
2326     case regState_Unregistered:
2327     default: LogMsg("UpdateOneSRVRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
2328     }
2329 }
2330 
UpdateAllSRVRecords(mDNS * m)2331 mDNSexport void UpdateAllSRVRecords(mDNS *m)
2332 {
2333     m->NextSRVUpdate = 0;
2334     LogInfo("UpdateAllSRVRecords %d", m->SleepState);
2335 
2336     if (m->CurrentRecord)
2337         LogMsg("UpdateAllSRVRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2338     m->CurrentRecord = m->ResourceRecords;
2339     while (m->CurrentRecord)
2340     {
2341         AuthRecord *rptr = m->CurrentRecord;
2342         m->CurrentRecord = m->CurrentRecord->next;
2343         if (AuthRecord_uDNS(rptr) && rptr->resrec.rrtype == kDNSType_SRV)
2344             UpdateOneSRVRecord(m, rptr);
2345     }
2346 }
2347 
2348 // Forward reference: AdvertiseHostname references HostnameCallback, and HostnameCallback calls AdvertiseHostname
2349 mDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
2350 
2351 // Called in normal client context (lock not held)
hostnameGetPublicAddressCallback(mDNS * m,NATTraversalInfo * n)2352 mDNSlocal void hostnameGetPublicAddressCallback(mDNS *m, NATTraversalInfo *n)
2353 {
2354     HostnameInfo *h = (HostnameInfo *)n->clientContext;
2355 
2356     if (!h) { LogMsg("RegisterHostnameRecord: registration cancelled"); return; }
2357 
2358     if (!n->Result)
2359     {
2360         if (mDNSIPv4AddressIsZero(n->ExternalAddress) || mDNSv4AddrIsRFC1918(&n->ExternalAddress)) return;
2361 
2362         if (h->arv4.resrec.RecordType)
2363         {
2364             if (mDNSSameIPv4Address(h->arv4.resrec.rdata->u.ipv4, n->ExternalAddress)) return;  // If address unchanged, do nothing
2365             LogInfo("Updating hostname %p %##s IPv4 from %.4a to %.4a (NAT gateway's external address)",n,
2366                     h->arv4.resrec.name->c, &h->arv4.resrec.rdata->u.ipv4, &n->ExternalAddress);
2367             mDNS_Deregister(m, &h->arv4);   // mStatus_MemFree callback will re-register with new address
2368         }
2369         else
2370         {
2371             LogInfo("Advertising hostname %##s IPv4 %.4a (NAT gateway's external address)", h->arv4.resrec.name->c, &n->ExternalAddress);
2372             h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
2373             h->arv4.resrec.rdata->u.ipv4 = n->ExternalAddress;
2374             mDNS_Register(m, &h->arv4);
2375         }
2376     }
2377 }
2378 
2379 // register record or begin NAT traversal
AdvertiseHostname(mDNS * m,HostnameInfo * h)2380 mDNSlocal void AdvertiseHostname(mDNS *m, HostnameInfo *h)
2381 {
2382     if (!mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4) && h->arv4.resrec.RecordType == kDNSRecordTypeUnregistered)
2383     {
2384         mDNS_SetupResourceRecord(&h->arv4, mDNSNULL, mDNSInterface_Any, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnregistered, AuthRecordAny, HostnameCallback, h);
2385         AssignDomainName(&h->arv4.namestorage, &h->fqdn);
2386         h->arv4.resrec.rdata->u.ipv4 = m->AdvertisedV4.ip.v4;
2387         h->arv4.state = regState_Unregistered;
2388         if (mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4))
2389         {
2390             // If we already have a NAT query active, stop it and restart it to make sure we get another callback
2391             if (h->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &h->natinfo);
2392             h->natinfo.Protocol         = 0;
2393             h->natinfo.IntPort          = zeroIPPort;
2394             h->natinfo.RequestedPort    = zeroIPPort;
2395             h->natinfo.NATLease         = 0;
2396             h->natinfo.clientCallback   = hostnameGetPublicAddressCallback;
2397             h->natinfo.clientContext    = h;
2398             mDNS_StartNATOperation_internal(m, &h->natinfo);
2399         }
2400         else
2401         {
2402             LogInfo("Advertising hostname %##s IPv4 %.4a", h->arv4.resrec.name->c, &m->AdvertisedV4.ip.v4);
2403             h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
2404             mDNS_Register_internal(m, &h->arv4);
2405         }
2406     }
2407 
2408     if (!mDNSIPv6AddressIsZero(m->AdvertisedV6.ip.v6) && h->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
2409     {
2410         mDNS_SetupResourceRecord(&h->arv6, mDNSNULL, mDNSInterface_Any, kDNSType_AAAA, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, HostnameCallback, h);
2411         AssignDomainName(&h->arv6.namestorage, &h->fqdn);
2412         h->arv6.resrec.rdata->u.ipv6 = m->