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