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