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