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