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