]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/uDNS.c
mDNSResponder-258.21.tar.gz
[apple/mdnsresponder.git] / mDNSCore / uDNS.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2006 Apple Computer, 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 #include "uDNS.h"
24
25 #if(defined(_MSC_VER))
26 // Disable "assignment within conditional expression".
27 // Other compilers understand the convention that if you place the assignment expression within an extra pair
28 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
29 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
30 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
31 #pragma warning(disable:4706)
32 #endif
33
34 // For domain enumeration and automatic browsing
35 // This is the user's DNS search list.
36 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
37 // to discover recommended domains for domain enumeration (browse, default browse, registration,
38 // default registration) and possibly one or more recommended automatic browsing domains.
39 mDNSexport SearchListElem *SearchList = mDNSNULL;
40
41 // The value can be set to true by the Platform code e.g., MacOSX uses the plist mechanism
42 mDNSBool StrictUnicastOrdering = mDNSfalse;
43
44 // We keep track of the number of unicast DNS servers and log a message when we exceed 64.
45 // Currently the unicast queries maintain a 64 bit map to track the valid DNS servers for that
46 // question. Bit position is the index into the DNS server list. This is done so to try all
47 // the servers exactly once before giving up. If we could allocate memory in the core, then
48 // arbitrary limitation of 64 DNSServers can be removed.
49 mDNSu8 NumUnicastDNSServers = 0;
50 #define MAX_UNICAST_DNS_SERVERS 64
51
52 // ***************************************************************************
53 #if COMPILER_LIKES_PRAGMA_MARK
54 #pragma mark - General Utility Functions
55 #endif
56
57 // set retry timestamp for record with exponential backoff
58 mDNSlocal void SetRecordRetry(mDNS *const m, AuthRecord *rr, mDNSu32 random)
59 {
60 rr->LastAPTime = m->timenow;
61
62 if (rr->expire && rr->refreshCount < MAX_UPDATE_REFRESH_COUNT)
63 {
64 mDNSs32 remaining = rr->expire - m->timenow;
65 rr->refreshCount++;
66 if (remaining > MIN_UPDATE_REFRESH_TIME)
67 {
68 // Refresh at 70% + random (currently it is 0 to 10%)
69 rr->ThisAPInterval = 7 * (remaining/10) + (random ? random : mDNSRandom(remaining/10));
70 // Don't update more often than 5 minutes
71 if (rr->ThisAPInterval < MIN_UPDATE_REFRESH_TIME)
72 rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
73 LogInfo("SetRecordRetry refresh in %d of %d for %s",
74 rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
75 }
76 else
77 {
78 rr->ThisAPInterval = MIN_UPDATE_REFRESH_TIME;
79 LogInfo("SetRecordRetry clamping to min refresh in %d of %d for %s",
80 rr->ThisAPInterval/mDNSPlatformOneSecond, (rr->expire - m->timenow)/mDNSPlatformOneSecond, ARDisplayString(m, rr));
81 }
82 return;
83 }
84
85 rr->expire = 0;
86
87 rr->ThisAPInterval = rr->ThisAPInterval * QuestionIntervalStep; // Same Retry logic as Unicast Queries
88 if (rr->ThisAPInterval < INIT_RECORD_REG_INTERVAL)
89 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
90 if (rr->ThisAPInterval > MAX_RECORD_REG_INTERVAL)
91 rr->ThisAPInterval = MAX_RECORD_REG_INTERVAL;
92
93 LogInfo("SetRecordRetry retry in %d ms for %s", rr->ThisAPInterval, ARDisplayString(m, rr));
94 }
95
96 // ***************************************************************************
97 #if COMPILER_LIKES_PRAGMA_MARK
98 #pragma mark - Name Server List Management
99 #endif
100
101 mDNSexport DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, const mDNSAddr *addr, const mDNSIPPort port, mDNSBool scoped)
102 {
103 DNSServer **p = &m->DNSServers;
104 DNSServer *tmp = mDNSNULL;
105
106 if ((NumUnicastDNSServers + 1) > MAX_UNICAST_DNS_SERVERS)
107 {
108 LogMsg("mDNS_AddDNSServer: DNS server limit of %d reached, not adding this server", MAX_UNICAST_DNS_SERVERS);
109 return mDNSNULL;
110 }
111
112 if (!d) d = (const domainname *)"";
113
114 LogInfo("mDNS_AddDNSServer: Adding %#a for %##s, InterfaceID %p, scoped %d", addr, d->c, interface, scoped);
115 if (m->mDNS_busy != m->mDNS_reentrancy+1)
116 LogMsg("mDNS_AddDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
117
118 while (*p) // Check if we already have this {interface,address,port,domain} tuple registered
119 {
120 if ((*p)->scoped == scoped && (*p)->interface == interface && (*p)->teststate != DNSServer_Disabled &&
121 mDNSSameAddress(&(*p)->addr, addr) && mDNSSameIPPort((*p)->port, port) && SameDomainName(&(*p)->domain, d))
122 {
123 if (!((*p)->flags & DNSServer_FlagDelete)) debugf("Note: DNS Server %#a:%d for domain %##s (%p) registered more than once", addr, mDNSVal16(port), d->c, interface);
124 (*p)->flags &= ~DNSServer_FlagDelete;
125 tmp = *p;
126 *p = tmp->next;
127 tmp->next = mDNSNULL;
128 }
129 else
130 p=&(*p)->next;
131 }
132
133 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
134 else
135 {
136 // allocate, add to list
137 *p = mDNSPlatformMemAllocate(sizeof(**p));
138 if (!*p) LogMsg("Error: mDNS_AddDNSServer - malloc");
139 else
140 {
141 NumUnicastDNSServers++;
142 (*p)->scoped = scoped;
143 (*p)->interface = interface;
144 (*p)->addr = *addr;
145 (*p)->port = port;
146 (*p)->flags = DNSServer_FlagNew;
147 (*p)->teststate = /* DNSServer_Untested */ DNSServer_Passed;
148 (*p)->lasttest = m->timenow - INIT_UCAST_POLL_INTERVAL;
149 AssignDomainName(&(*p)->domain, d);
150 (*p)->next = mDNSNULL;
151 }
152 }
153 (*p)->penaltyTime = 0;
154 return(*p);
155 }
156
157 // PenalizeDNSServer is called when the number of queries to the unicast
158 // DNS server exceeds MAX_UCAST_UNANSWERED_QUERIES or when we receive an
159 // error e.g., SERV_FAIL from DNS server.
160 mDNSexport void PenalizeDNSServer(mDNS *const m, DNSQuestion *q)
161 {
162 DNSServer *new;
163 DNSServer *orig = q->qDNSServer;
164
165 if (m->mDNS_busy != m->mDNS_reentrancy+1)
166 LogMsg("PenalizeDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
167
168 // This should never happen. Whenever we change DNS server, we change the ID on the question and hence
169 // we should never accept a response after we penalize a DNS server e.g., send two queries, no response,
170 // penalize DNS server and no new servers to pick for the question and hence qDNSServer is NULL. If we
171 // receive a response now, the DNS server can be NULL. But we won't because the ID already has been
172 // changed.
173 if (!q->qDNSServer)
174 {
175 LogMsg("PenalizeDNSServer: ERROR!! Null DNS server for %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), q->unansweredQueries);
176 goto end;
177 }
178
179 LogInfo("PenalizeDNSServer: Penalizing DNS server %#a:%d question (%##s) for question %p %##s (%s) SuppressUnusable %d",
180 &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c, q, q->qname.c, DNSTypeName(q->qtype),
181 q->SuppressUnusable);
182
183 // If strict ordering of unicast servers needs to be preserved, we just lookup
184 // the next best match server below
185 //
186 // If strict ordering is not required which is the default behavior, we penalize the server
187 // for DNSSERVER_PENALTY_TIME. We may also use additional logic e.g., don't penalize for PTR
188 // in the future.
189
190 if (!StrictUnicastOrdering)
191 {
192 LogInfo("PenalizeDNSServer: Strict Unicast Ordering is FALSE");
193 // We penalize the server so that new queries don't pick this server for DNSSERVER_PENALTY_TIME
194 // XXX Include other logic here to see if this server should really be penalized
195 //
196 if (q->qtype == kDNSType_PTR)
197 {
198 LogInfo("PenalizeDNSServer: Not Penalizing PTR question");
199 }
200 else
201 {
202 LogInfo("PenalizeDNSServer: Penalizing question type %d", q->qtype);
203 q->qDNSServer->penaltyTime = NonZeroTime(m->timenow + DNSSERVER_PENALTY_TIME);
204 }
205 }
206 else
207 {
208 LogInfo("PenalizeDNSServer: Strict Unicast Ordering is TRUE");
209 }
210
211 end:
212 new = GetServerForQuestion(m, q);
213
214
215 if (new == orig)
216 {
217 if (new)
218 LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server %#a:%d", &new->addr,
219 mDNSVal16(new->port));
220 else
221 LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server NULL");
222 q->ThisQInterval = 0; // Inactivate this question so that we dont bombard the network
223 }
224 else
225 {
226 // The new DNSServer is set in DNSServerChangeForQuestion
227 DNSServerChangeForQuestion(m, q, new);
228
229 if (new)
230 {
231 LogInfo("PenalizeDNSServer: Server for %##s (%s) changed to %#a:%d (%##s)",
232 q->qname.c, DNSTypeName(q->qtype), &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qDNSServer->domain.c);
233 // We want to try the next server immediately. As the question may already have backed off, reset
234 // the interval. We do this only the first time when we try all the DNS servers. Once we reached the end of
235 // list and retrying all the servers again e.g., at least one server failed to respond in the previous try, we
236 // use the normal backoff which is done in uDNS_CheckCurrentQuestion when we send the packet out.
237 if (!q->triedAllServersOnce)
238 {
239 q->ThisQInterval = InitialQuestionInterval;
240 q->LastQTime = m->timenow - q->ThisQInterval;
241 SetNextQueryTime(m, q);
242 }
243 }
244 else
245 {
246 // We don't have any more DNS servers for this question. If some server in the list did not return
247 // any response, we need to keep retrying till we get a response. uDNS_CheckCurrentQuestion handles
248 // this case.
249 //
250 // If all servers responded with a negative response, We need to do two things. First, generate a
251 // negative response so that applications get a reply. We also need to reinitialize the DNS servers
252 // so that when the cache expires, we can restart the query.
253 //
254 // Negative response may be generated in two ways.
255 //
256 // 1. AnswerQuestionForDNSServerChanges (called from DNSServerChangedForQuestion) might find some
257 // cache entries and answer this question.
258 // 2. uDNS_CheckCurrentQuestion will create a new cache entry and answer this question
259 //
260 // For (1), it might be okay to reinitialize the DNS servers here. But for (2), we can't do it here
261 // because uDNS_CheckCurrentQuestion will try resending the queries. Hence, to be consistent, we
262 // defer reintializing the DNS servers up until generating a negative cache response.
263 //
264 // Be careful not to touch the ThisQInterval here. For a normal question, when we answer the question
265 // in AnswerCurrentQuestionWithResourceRecord will set ThisQInterval to MaxQuestionInterval and hence
266 // the next query will not happen until cache expiry. If it is a long lived question,
267 // AnswerCurrentQuestionWithResourceRecord will not set it to MaxQuestionInterval. In that case,
268 // we want the normal backoff to work.
269 LogInfo("PenalizeDNSServer: Server for %p, %##s (%s) changed to NULL, Interval %d", q, q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
270 }
271 q->unansweredQueries = 0;
272
273 }
274 }
275
276 // ***************************************************************************
277 #if COMPILER_LIKES_PRAGMA_MARK
278 #pragma mark - authorization management
279 #endif
280
281 mDNSlocal DomainAuthInfo *GetAuthInfoForName_direct(mDNS *m, const domainname *const name)
282 {
283 const domainname *n = name;
284 while (n->c[0])
285 {
286 DomainAuthInfo *ptr;
287 for (ptr = m->AuthInfoList; ptr; ptr = ptr->next)
288 if (SameDomainName(&ptr->domain, n))
289 {
290 debugf("GetAuthInfoForName %##s Matched %##s Key name %##s", name->c, ptr->domain.c, ptr->keyname.c);
291 return(ptr);
292 }
293 n = (const domainname *)(n->c + 1 + n->c[0]);
294 }
295 //LogInfo("GetAuthInfoForName none found for %##s", name->c);
296 return mDNSNULL;
297 }
298
299 // MUST be called with lock held
300 mDNSexport DomainAuthInfo *GetAuthInfoForName_internal(mDNS *m, const domainname *const name)
301 {
302 DomainAuthInfo **p = &m->AuthInfoList;
303
304 if (m->mDNS_busy != m->mDNS_reentrancy+1)
305 LogMsg("GetAuthInfoForName_internal: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
306
307 // First purge any dead keys from the list
308 while (*p)
309 {
310 if ((*p)->deltime && m->timenow - (*p)->deltime >= 0 && AutoTunnelUnregistered(*p))
311 {
312 DNSQuestion *q;
313 DomainAuthInfo *info = *p;
314 LogInfo("GetAuthInfoForName_internal deleting expired key %##s %##s", info->domain.c, info->keyname.c);
315 *p = info->next; // Cut DomainAuthInfo from list *before* scanning our question list updating AuthInfo pointers
316 for (q = m->Questions; q; q=q->next)
317 if (q->AuthInfo == info)
318 {
319 q->AuthInfo = GetAuthInfoForName_direct(m, &q->qname);
320 debugf("GetAuthInfoForName_internal updated q->AuthInfo from %##s to %##s for %##s (%s)",
321 info->domain.c, q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
322 }
323
324 // Probably not essential, but just to be safe, zero out the secret key data
325 // so we don't leave it hanging around in memory
326 // (where it could potentially get exposed via some other bug)
327 mDNSPlatformMemZero(info, sizeof(*info));
328 mDNSPlatformMemFree(info);
329 }
330 else
331 p = &(*p)->next;
332 }
333
334 return(GetAuthInfoForName_direct(m, name));
335 }
336
337 mDNSexport DomainAuthInfo *GetAuthInfoForName(mDNS *m, const domainname *const name)
338 {
339 DomainAuthInfo *d;
340 mDNS_Lock(m);
341 d = GetAuthInfoForName_internal(m, name);
342 mDNS_Unlock(m);
343 return(d);
344 }
345
346 // MUST be called with the lock held
347 mDNSexport mStatus mDNS_SetSecretForDomain(mDNS *m, DomainAuthInfo *info,
348 const domainname *domain, const domainname *keyname, const char *b64keydata, mDNSBool AutoTunnel)
349 {
350 DNSQuestion *q;
351 DomainAuthInfo **p = &m->AuthInfoList;
352 if (!info || !b64keydata) { LogMsg("mDNS_SetSecretForDomain: ERROR: info %p b64keydata %p", info, b64keydata); return(mStatus_BadParamErr); }
353
354 LogInfo("mDNS_SetSecretForDomain: domain %##s key %##s%s", domain->c, keyname->c, AutoTunnel ? " AutoTunnel" : "");
355
356 info->AutoTunnel = AutoTunnel;
357 AssignDomainName(&info->domain, domain);
358 AssignDomainName(&info->keyname, keyname);
359 mDNS_snprintf(info->b64keydata, sizeof(info->b64keydata), "%s", b64keydata);
360
361 if (DNSDigest_ConstructHMACKeyfromBase64(info, b64keydata) < 0)
362 {
363 LogMsg("mDNS_SetSecretForDomain: ERROR: Could not convert shared secret from base64: domain %##s key %##s %s", domain->c, keyname->c, mDNS_LoggingEnabled ? b64keydata : "");
364 return(mStatus_BadParamErr);
365 }
366
367 // Don't clear deltime until after we've ascertained that b64keydata is valid
368 info->deltime = 0;
369
370 while (*p && (*p) != info) p=&(*p)->next;
371 if (*p) {LogInfo("mDNS_SetSecretForDomain: Domain %##s Already in list", (*p)->domain.c); return(mStatus_AlreadyRegistered);}
372
373 // Caution: Only zero AutoTunnelHostRecord.namestorage and AutoTunnelNAT.clientContext AFTER we've determined that this is a NEW DomainAuthInfo
374 // being added to the list. Otherwise we risk smashing our AutoTunnel host records and NATOperation that are already active and in use.
375 info->AutoTunnelHostRecord.resrec.RecordType = kDNSRecordTypeUnregistered;
376 info->AutoTunnelHostRecord.namestorage.c[0] = 0;
377 info->AutoTunnelTarget .resrec.RecordType = kDNSRecordTypeUnregistered;
378 info->AutoTunnelDeviceInfo.resrec.RecordType = kDNSRecordTypeUnregistered;
379 info->AutoTunnelService .resrec.RecordType = kDNSRecordTypeUnregistered;
380 info->AutoTunnel6Record .resrec.RecordType = kDNSRecordTypeUnregistered;
381 info->AutoTunnelNAT.clientContext = mDNSNULL;
382 info->next = mDNSNULL;
383 *p = info;
384
385 // Check to see if adding this new DomainAuthInfo has changed the credentials for any of our questions
386 for (q = m->Questions; q; q=q->next)
387 {
388 DomainAuthInfo *newinfo = GetAuthInfoForQuestion(m, q);
389 if (q->AuthInfo != newinfo)
390 {
391 debugf("mDNS_SetSecretForDomain updating q->AuthInfo from %##s to %##s for %##s (%s)",
392 q->AuthInfo ? q->AuthInfo->domain.c : mDNSNULL,
393 newinfo ? newinfo ->domain.c : mDNSNULL, q->qname.c, DNSTypeName(q->qtype));
394 q->AuthInfo = newinfo;
395 }
396 }
397
398 return(mStatus_NoError);
399 }
400
401 // ***************************************************************************
402 #if COMPILER_LIKES_PRAGMA_MARK
403 #pragma mark -
404 #pragma mark - NAT Traversal
405 #endif
406
407 mDNSlocal mStatus uDNS_SendNATMsg(mDNS *m, NATTraversalInfo *info)
408 {
409 mStatus err = mStatus_NoError;
410
411 // send msg if we have a router and it is a private address
412 if (!mDNSIPv4AddressIsZero(m->Router.ip.v4) && mDNSv4AddrIsRFC1918(&m->Router.ip.v4))
413 {
414 union { NATAddrRequest NATAddrReq; NATPortMapRequest NATPortReq; } u = { { NATMAP_VERS, NATOp_AddrRequest } } ;
415 const mDNSu8 *end = (mDNSu8 *)&u + sizeof(NATAddrRequest);
416
417 if (info) // For NATOp_MapUDP and NATOp_MapTCP, fill in additional fields
418 {
419 mDNSu8 *p = (mDNSu8 *)&u.NATPortReq.NATReq_lease;
420 u.NATPortReq.opcode = info->Protocol;
421 u.NATPortReq.unused = zeroID;
422 u.NATPortReq.intport = info->IntPort;
423 u.NATPortReq.extport = info->RequestedPort;
424 p[0] = (mDNSu8)((info->NATLease >> 24) & 0xFF);
425 p[1] = (mDNSu8)((info->NATLease >> 16) & 0xFF);
426 p[2] = (mDNSu8)((info->NATLease >> 8) & 0xFF);
427 p[3] = (mDNSu8)( info->NATLease & 0xFF);
428 end = (mDNSu8 *)&u + sizeof(NATPortMapRequest);
429 }
430
431 err = mDNSPlatformSendUDP(m, (mDNSu8 *)&u, end, 0, mDNSNULL, &m->Router, NATPMPPort);
432
433 #ifdef _LEGACY_NAT_TRAVERSAL_
434 if (mDNSIPPortIsZero(m->UPnPRouterPort) || mDNSIPPortIsZero(m->UPnPSOAPPort)) LNT_SendDiscoveryMsg(m);
435 else if (info) err = LNT_MapPort(m, info);
436 else err = LNT_GetExternalAddress(m);
437 #endif // _LEGACY_NAT_TRAVERSAL_
438 }
439 return(err);
440 }
441
442 mDNSexport void RecreateNATMappings(mDNS *const m)
443 {
444 NATTraversalInfo *n;
445 for (n = m->NATTraversals; n; n=n->next)
446 {
447 n->ExpiryTime = 0; // Mark this mapping as expired
448 n->retryInterval = NATMAP_INIT_RETRY;
449 n->retryPortMap = m->timenow;
450 #ifdef _LEGACY_NAT_TRAVERSAL_
451 if (n->tcpInfo.sock) { mDNSPlatformTCPCloseConnection(n->tcpInfo.sock); n->tcpInfo.sock = mDNSNULL; }
452 #endif // _LEGACY_NAT_TRAVERSAL_
453 }
454
455 m->NextScheduledNATOp = m->timenow; // Need to send packets immediately
456 }
457
458 mDNSexport void natTraversalHandleAddressReply(mDNS *const m, mDNSu16 err, mDNSv4Addr ExtAddr)
459 {
460 static mDNSu16 last_err = 0;
461
462 if (err)
463 {
464 if (err != last_err) LogMsg("Error getting external address %d", err);
465 ExtAddr = zerov4Addr;
466 }
467 else
468 {
469 LogInfo("Received external IP address %.4a from NAT", &ExtAddr);
470 if (mDNSv4AddrIsRFC1918(&ExtAddr))
471 LogMsg("Double NAT (external NAT gateway address %.4a is also a private RFC 1918 address)", &ExtAddr);
472 if (mDNSIPv4AddressIsZero(ExtAddr))
473 err = NATErr_NetFail; // fake error to handle routers that pathologically report success with the zero address
474 }
475
476 if (!mDNSSameIPv4Address(m->ExternalAddress, ExtAddr))
477 {
478 m->ExternalAddress = ExtAddr;
479 RecreateNATMappings(m); // Also sets NextScheduledNATOp for us
480 }
481
482 if (!err) // Success, back-off to maximum interval
483 m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
484 else if (!last_err) // Failure after success, retry quickly (then back-off exponentially)
485 m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
486 // else back-off normally in case of pathological failures
487
488 m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
489 if (m->NextScheduledNATOp - m->retryIntervalGetAddr > 0)
490 m->NextScheduledNATOp = m->retryIntervalGetAddr;
491
492 last_err = err;
493 }
494
495 // Both places that call NATSetNextRenewalTime() update m->NextScheduledNATOp correctly afterwards
496 mDNSlocal void NATSetNextRenewalTime(mDNS *const m, NATTraversalInfo *n)
497 {
498 n->retryInterval = (n->ExpiryTime - m->timenow)/2;
499 if (n->retryInterval < NATMAP_MIN_RETRY_INTERVAL) // Min retry interval is 2 seconds
500 n->retryInterval = NATMAP_MIN_RETRY_INTERVAL;
501 n->retryPortMap = m->timenow + n->retryInterval;
502 }
503
504 // Note: When called from handleLNTPortMappingResponse() only pkt->err, pkt->extport and pkt->NATRep_lease fields are filled in
505 mDNSexport void natTraversalHandlePortMapReply(mDNS *const m, NATTraversalInfo *n, const mDNSInterfaceID InterfaceID, mDNSu16 err, mDNSIPPort extport, mDNSu32 lease)
506 {
507 const char *prot = n->Protocol == NATOp_MapUDP ? "UDP" : n->Protocol == NATOp_MapTCP ? "TCP" : "?";
508 (void)prot;
509 n->NewResult = err;
510 if (err || lease == 0 || mDNSIPPortIsZero(extport))
511 {
512 LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d error %d",
513 n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease, err);
514 n->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
515 n->retryPortMap = m->timenow + NATMAP_MAX_RETRY_INTERVAL;
516 // No need to set m->NextScheduledNATOp here, since we're only ever extending the m->retryPortMap time
517 if (err == NATErr_Refused) n->NewResult = mStatus_NATPortMappingDisabled;
518 else if (err > NATErr_None && err <= NATErr_Opcode) n->NewResult = mStatus_NATPortMappingUnsupported;
519 }
520 else
521 {
522 if (lease > 999999999UL / mDNSPlatformOneSecond)
523 lease = 999999999UL / mDNSPlatformOneSecond;
524 n->ExpiryTime = NonZeroTime(m->timenow + lease * mDNSPlatformOneSecond);
525
526 if (!mDNSSameIPPort(n->RequestedPort, extport))
527 LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d changed to %5d",
528 n, prot, mDNSVal16(n->IntPort), mDNSVal16(n->RequestedPort), mDNSVal16(extport));
529
530 n->InterfaceID = InterfaceID;
531 n->RequestedPort = extport;
532
533 LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d",
534 n, prot, mDNSVal16(n->IntPort), mDNSVal16(extport), lease);
535
536 NATSetNextRenewalTime(m, n); // Got our port mapping; now set timer to renew it at halfway point
537 m->NextScheduledNATOp = m->timenow; // May need to invoke client callback immediately
538 }
539 }
540
541 // Must be called with the mDNS_Lock held
542 mDNSexport mStatus mDNS_StartNATOperation_internal(mDNS *const m, NATTraversalInfo *traversal)
543 {
544 NATTraversalInfo **n;
545
546 LogInfo("mDNS_StartNATOperation_internal %p Protocol %d IntPort %d RequestedPort %d NATLease %d", traversal,
547 traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
548
549 // Note: It important that new traversal requests are appended at the *end* of the list, not prepended at the start
550 for (n = &m->NATTraversals; *n; n=&(*n)->next)
551 {
552 if (traversal == *n)
553 {
554 LogMsg("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
555 traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease);
556 #if ForceAlerts
557 *(long*)0 = 0;
558 #endif
559 return(mStatus_AlreadyRegistered);
560 }
561 if (traversal->Protocol && traversal->Protocol == (*n)->Protocol && mDNSSameIPPort(traversal->IntPort, (*n)->IntPort) &&
562 !mDNSSameIPPort(traversal->IntPort, SSHPort))
563 LogMsg("Warning: Created port mapping request %p Prot %d Int %d TTL %d "
564 "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
565 traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
566 *n, (*n) ->Protocol, mDNSVal16((*n) ->IntPort), (*n) ->NATLease);
567 }
568
569 // Initialize necessary fields
570 traversal->next = mDNSNULL;
571 traversal->ExpiryTime = 0;
572 traversal->retryInterval = NATMAP_INIT_RETRY;
573 traversal->retryPortMap = m->timenow;
574 traversal->NewResult = mStatus_NoError;
575 traversal->ExternalAddress = onesIPv4Addr;
576 traversal->ExternalPort = zeroIPPort;
577 traversal->Lifetime = 0;
578 traversal->Result = mStatus_NoError;
579
580 // set default lease if necessary
581 if (!traversal->NATLease) traversal->NATLease = NATMAP_DEFAULT_LEASE;
582
583 #ifdef _LEGACY_NAT_TRAVERSAL_
584 mDNSPlatformMemZero(&traversal->tcpInfo, sizeof(traversal->tcpInfo));
585 #endif // _LEGACY_NAT_TRAVERSAL_
586
587 if (!m->NATTraversals) // If this is our first NAT request, kick off an address request too
588 {
589 m->retryGetAddr = m->timenow;
590 m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
591 }
592
593 m->NextScheduledNATOp = m->timenow; // This will always trigger sending the packet ASAP, and generate client callback if necessary
594
595 *n = traversal; // Append new NATTraversalInfo to the end of our list
596
597 return(mStatus_NoError);
598 }
599
600 // Must be called with the mDNS_Lock held
601 mDNSexport mStatus mDNS_StopNATOperation_internal(mDNS *m, NATTraversalInfo *traversal)
602 {
603 mDNSBool unmap = mDNStrue;
604 NATTraversalInfo *p;
605 NATTraversalInfo **ptr = &m->NATTraversals;
606
607 while (*ptr && *ptr != traversal) ptr=&(*ptr)->next;
608 if (*ptr) *ptr = (*ptr)->next; // If we found it, cut this NATTraversalInfo struct from our list
609 else
610 {
611 LogMsg("mDNS_StopNATOperation_internal: NATTraversalInfo %p not found in list", traversal);
612 return(mStatus_BadReferenceErr);
613 }
614
615 LogInfo("mDNS_StopNATOperation_internal %p %d %d %d %d", traversal,
616 traversal->Protocol, mDNSVal16(traversal->IntPort), mDNSVal16(traversal->RequestedPort), traversal->NATLease);
617
618 if (m->CurrentNATTraversal == traversal)
619 m->CurrentNATTraversal = m->CurrentNATTraversal->next;
620
621 if (traversal->Protocol)
622 for (p = m->NATTraversals; p; p=p->next)
623 if (traversal->Protocol == p->Protocol && mDNSSameIPPort(traversal->IntPort, p->IntPort))
624 {
625 if (!mDNSSameIPPort(traversal->IntPort, SSHPort))
626 LogMsg("Warning: Removed port mapping request %p Prot %d Int %d TTL %d "
627 "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
628 traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease,
629 p, p ->Protocol, mDNSVal16(p ->IntPort), p ->NATLease);
630 unmap = mDNSfalse;
631 }
632
633 if (traversal->ExpiryTime && unmap)
634 {
635 traversal->NATLease = 0;
636 traversal->retryInterval = 0;
637 uDNS_SendNATMsg(m, traversal);
638 }
639
640 // 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
641 #ifdef _LEGACY_NAT_TRAVERSAL_
642 {
643 mStatus err = LNT_UnmapPort(m, traversal);
644 if (err) LogMsg("Legacy NAT Traversal - unmap request failed with error %d", err);
645 }
646 #endif // _LEGACY_NAT_TRAVERSAL_
647
648 return(mStatus_NoError);
649 }
650
651 mDNSexport mStatus mDNS_StartNATOperation(mDNS *const m, NATTraversalInfo *traversal)
652 {
653 mStatus status;
654 mDNS_Lock(m);
655 status = mDNS_StartNATOperation_internal(m, traversal);
656 mDNS_Unlock(m);
657 return(status);
658 }
659
660 mDNSexport mStatus mDNS_StopNATOperation(mDNS *const m, NATTraversalInfo *traversal)
661 {
662 mStatus status;
663 mDNS_Lock(m);
664 status = mDNS_StopNATOperation_internal(m, traversal);
665 mDNS_Unlock(m);
666 return(status);
667 }
668
669 // ***************************************************************************
670 #if COMPILER_LIKES_PRAGMA_MARK
671 #pragma mark -
672 #pragma mark - Long-Lived Queries
673 #endif
674
675 // Lock must be held -- otherwise m->timenow is undefined
676 mDNSlocal void StartLLQPolling(mDNS *const m, DNSQuestion *q)
677 {
678 debugf("StartLLQPolling: %##s", q->qname.c);
679 q->state = LLQ_Poll;
680 q->ThisQInterval = INIT_UCAST_POLL_INTERVAL;
681 // We want to send our poll query ASAP, but the "+ 1" is because if we set the time to now,
682 // we risk causing spurious "SendQueries didn't send all its queries" log messages
683 q->LastQTime = m->timenow - q->ThisQInterval + 1;
684 SetNextQueryTime(m, q);
685 #if APPLE_OSX_mDNSResponder
686 UpdateAutoTunnelDomainStatuses(m);
687 #endif
688 }
689
690 mDNSlocal mDNSu8 *putLLQ(DNSMessage *const msg, mDNSu8 *ptr, const DNSQuestion *const question, const LLQOptData *const data)
691 {
692 AuthRecord rr;
693 ResourceRecord *opt = &rr.resrec;
694 rdataOPT *optRD;
695
696 //!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
697 ptr = putQuestion(msg, ptr, msg->data + AbsoluteMaxDNSMessageData, &question->qname, question->qtype, question->qclass);
698 if (!ptr) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL; }
699
700 // locate OptRR if it exists, set pointer to end
701 // !!!KRS implement me
702
703 // format opt rr (fields not specified are zero-valued)
704 mDNS_SetupResourceRecord(&rr, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
705 opt->rrclass = NormalMaxDNSMessageData;
706 opt->rdlength = sizeof(rdataOPT); // One option in this OPT record
707 opt->rdestimate = sizeof(rdataOPT);
708
709 optRD = &rr.resrec.rdata->u.opt[0];
710 optRD->opt = kDNSOpt_LLQ;
711 optRD->u.llq = *data;
712 ptr = PutResourceRecordTTLJumbo(msg, ptr, &msg->h.numAdditionals, opt, 0);
713 if (!ptr) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL; }
714
715 return ptr;
716 }
717
718 // Normally we'd just request event packets be sent directly to m->LLQNAT.ExternalPort, except...
719 // with LLQs over TLS/TCP we're doing a weird thing where instead of requesting packets be sent to ExternalAddress:ExternalPort
720 // we're requesting that packets be sent to ExternalPort, but at the source address of our outgoing TCP connection.
721 // Normally, after going through the NAT gateway, the source address of our outgoing TCP connection is the same as ExternalAddress,
722 // so this is fine, except when the TCP connection ends up going over a VPN tunnel instead.
723 // 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
724 // LLQ server to send events to us directly at port 5353 on that address, instead of at our mapped external NAT port.
725
726 mDNSlocal mDNSu16 GetLLQEventPort(const mDNS *const m, const mDNSAddr *const dst)
727 {
728 mDNSAddr src;
729 mDNSPlatformSourceAddrForDest(&src, dst);
730 //LogMsg("GetLLQEventPort: src %#a for dst %#a (%d)", &src, dst, mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : 0);
731 return(mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : mDNSVal16(MulticastDNSPort));
732 }
733
734 // Normally called with llq set.
735 // May be called with llq NULL, when retransmitting a lost Challenge Response
736 mDNSlocal void sendChallengeResponse(mDNS *const m, DNSQuestion *const q, const LLQOptData *llq)
737 {
738 mDNSu8 *responsePtr = m->omsg.data;
739 LLQOptData llqBuf;
740
741 if (q->tcp) { LogMsg("sendChallengeResponse: ERROR!!: question %##s (%s) tcp non-NULL", q->qname.c, DNSTypeName(q->qtype)); return; }
742
743 if (PrivateQuery(q)) { LogMsg("sendChallengeResponse: ERROR!!: Private Query %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
744
745 if (q->ntries++ == kLLQ_MAX_TRIES)
746 {
747 LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s", kLLQ_MAX_TRIES, q->qname.c);
748 StartLLQPolling(m,q);
749 return;
750 }
751
752 if (!llq) // Retransmission: need to make a new LLQOptData
753 {
754 llqBuf.vers = kLLQ_Vers;
755 llqBuf.llqOp = kLLQOp_Setup;
756 llqBuf.err = LLQErr_NoError; // Don't need to tell server UDP notification port when sending over UDP
757 llqBuf.id = q->id;
758 llqBuf.llqlease = q->ReqLease;
759 llq = &llqBuf;
760 }
761
762 q->LastQTime = m->timenow;
763 q->ThisQInterval = q->tcp ? 0 : (kLLQ_INIT_RESEND * q->ntries * mDNSPlatformOneSecond); // If using TCP, don't need to retransmit
764 SetNextQueryTime(m, q);
765
766 // To simulate loss of challenge response packet, uncomment line below
767 //if (q->ntries == 1) return;
768
769 InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
770 responsePtr = putLLQ(&m->omsg, responsePtr, q, llq);
771 if (responsePtr)
772 {
773 mStatus err = mDNSSendDNSMessage(m, &m->omsg, responsePtr, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
774 if (err) { LogMsg("sendChallengeResponse: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err); }
775 }
776 else StartLLQPolling(m,q);
777 }
778
779 mDNSlocal void SetLLQTimer(mDNS *const m, DNSQuestion *const q, const LLQOptData *const llq)
780 {
781 mDNSs32 lease = (mDNSs32)llq->llqlease * mDNSPlatformOneSecond;
782 q->ReqLease = llq->llqlease;
783 q->LastQTime = m->timenow;
784 q->expire = m->timenow + lease;
785 q->ThisQInterval = lease/2 + mDNSRandom(lease/10);
786 debugf("SetLLQTimer setting %##s (%s) to %d %d", q->qname.c, DNSTypeName(q->qtype), lease/mDNSPlatformOneSecond, q->ThisQInterval/mDNSPlatformOneSecond);
787 SetNextQueryTime(m, q);
788 }
789
790 mDNSlocal void recvSetupResponse(mDNS *const m, mDNSu8 rcode, DNSQuestion *const q, const LLQOptData *const llq)
791 {
792 if (rcode && rcode != kDNSFlag1_RC_NXDomain)
793 { LogMsg("ERROR: recvSetupResponse %##s (%s) - rcode && rcode != kDNSFlag1_RC_NXDomain", q->qname.c, DNSTypeName(q->qtype)); return; }
794
795 if (llq->llqOp != kLLQOp_Setup)
796 { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad op %d", q->qname.c, DNSTypeName(q->qtype), llq->llqOp); return; }
797
798 if (llq->vers != kLLQ_Vers)
799 { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad vers %d", q->qname.c, DNSTypeName(q->qtype), llq->vers); return; }
800
801 if (q->state == LLQ_InitialRequest)
802 {
803 //LogInfo("Got LLQ_InitialRequest");
804
805 if (llq->err) { LogMsg("recvSetupResponse - received llq->err %d from server", llq->err); StartLLQPolling(m,q); return; }
806
807 if (q->ReqLease != llq->llqlease)
808 debugf("recvSetupResponse: requested lease %lu, granted lease %lu", q->ReqLease, llq->llqlease);
809
810 // cache expiration in case we go to sleep before finishing setup
811 q->ReqLease = llq->llqlease;
812 q->expire = m->timenow + ((mDNSs32)llq->llqlease * mDNSPlatformOneSecond);
813
814 // update state
815 q->state = LLQ_SecondaryRequest;
816 q->id = llq->id;
817 q->ntries = 0; // first attempt to send response
818 sendChallengeResponse(m, q, llq);
819 }
820 else if (q->state == LLQ_SecondaryRequest)
821 {
822 //LogInfo("Got LLQ_SecondaryRequest");
823
824 // Fix this immediately if not sooner. Copy the id from the LLQOptData into our DNSQuestion struct. This is only
825 // an issue for private LLQs, because we skip parts 2 and 3 of the handshake. This is related to a bigger
826 // problem of the current implementation of TCP LLQ setup: we're not handling state transitions correctly
827 // if the server sends back SERVFULL or STATIC.
828 if (PrivateQuery(q))
829 {
830 LogInfo("Private LLQ_SecondaryRequest; copying id %08X%08X", llq->id.l[0], llq->id.l[1]);
831 q->id = llq->id;
832 }
833
834 if (llq->err) { LogMsg("ERROR: recvSetupResponse %##s (%s) code %d from server", q->qname.c, DNSTypeName(q->qtype), llq->err); StartLLQPolling(m,q); return; }
835 if (!mDNSSameOpaque64(&q->id, &llq->id))
836 { LogMsg("recvSetupResponse - ID changed. discarding"); return; } // this can happen rarely (on packet loss + reordering)
837 q->state = LLQ_Established;
838 q->ntries = 0;
839 SetLLQTimer(m, q, llq);
840 #if APPLE_OSX_mDNSResponder
841 UpdateAutoTunnelDomainStatuses(m);
842 #endif
843 }
844 }
845
846 mDNSexport uDNS_LLQType uDNS_recvLLQResponse(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
847 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, DNSQuestion **matchQuestion)
848 {
849 DNSQuestion pktQ, *q;
850 if (msg->h.numQuestions && getQuestion(msg, msg->data, end, 0, &pktQ))
851 {
852 const rdataOPT *opt = GetLLQOptData(m, msg, end);
853
854 for (q = m->Questions; q; q = q->next)
855 {
856 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->qtype == pktQ.qtype && q->qnamehash == pktQ.qnamehash && SameDomainName(&q->qname, &pktQ.qname))
857 {
858 debugf("uDNS_recvLLQResponse found %##s (%s) %d %#a %#a %X %X %X %X %d",
859 q->qname.c, DNSTypeName(q->qtype), q->state, srcaddr, &q->servAddr,
860 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);
861 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));
862 if (q->state == LLQ_Poll && mDNSSameOpaque16(msg->h.id, q->TargetQID))
863 {
864 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
865
866 // Don't reset the state to IntialRequest as we may write that to the dynamic store
867 // and PrefPane might wrongly think that we are "Starting" instead of "Polling". If
868 // we are in polling state because of NAT-PMP disabled or DoubleNAT, next LLQNATCallback
869 // would kick us back to LLQInitialRequest. So, resetting the state here may not be useful.
870 //
871 // If we have a good NAT (neither NAT-PMP disabled nor Double-NAT), then we should not be
872 // possibly in polling state. To be safe, we want to retry from the start in that case
873 // as there may not be another LLQNATCallback
874 //
875 // NOTE: We can be in polling state if we cannot resolve the SOA record i.e, servAddr is set to
876 // all ones. In that case, we would set it in LLQ_InitialRequest as it overrides the NAT-PMP or
877 // Double-NAT state.
878 if (!mDNSAddressIsOnes(&q->servAddr) && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) &&
879 !m->LLQNAT.Result)
880 {
881 debugf("uDNS_recvLLQResponse got poll response; moving to LLQ_InitialRequest for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
882 q->state = LLQ_InitialRequest;
883 }
884 q->servPort = zeroIPPort; // Clear servPort so that startLLQHandshake will retry the GetZoneData processing
885 q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10); // Retry LLQ setup in approx 15 minutes
886 q->LastQTime = m->timenow;
887 SetNextQueryTime(m, q);
888 *matchQuestion = q;
889 return uDNS_LLQ_Entire; // uDNS_LLQ_Entire means flush stale records; assume a large effective TTL
890 }
891 // 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
892 else if (opt && q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Event && mDNSSameOpaque64(&opt->u.llq.id, &q->id))
893 {
894 mDNSu8 *ackEnd;
895 //debugf("Sending LLQ ack for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
896 InitializeDNSMessage(&m->omsg.h, msg->h.id, ResponseFlags);
897 ackEnd = putLLQ(&m->omsg, m->omsg.data, q, &opt->u.llq);
898 if (ackEnd) mDNSSendDNSMessage(m, &m->omsg, ackEnd, mDNSInterface_Any, q->LocalSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
899 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
900 debugf("uDNS_LLQ_Events: q->state == LLQ_Established msg->h.id %d q->TargetQID %d", mDNSVal16(msg->h.id), mDNSVal16(q->TargetQID));
901 *matchQuestion = q;
902 return uDNS_LLQ_Events;
903 }
904 if (opt && mDNSSameOpaque16(msg->h.id, q->TargetQID))
905 {
906 if (q->state == LLQ_Established && opt->u.llq.llqOp == kLLQOp_Refresh && mDNSSameOpaque64(&opt->u.llq.id, &q->id) && msg->h.numAdditionals && !msg->h.numAnswers)
907 {
908 if (opt->u.llq.err != LLQErr_NoError) LogMsg("recvRefreshReply: received error %d from server", opt->u.llq.err);
909 else
910 {
911 //LogInfo("Received refresh confirmation ntries %d for %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
912 // If we're waiting to go to sleep, then this LLQ deletion may have been the thing
913 // we were waiting for, so schedule another check to see if we can sleep now.
914 if (opt->u.llq.llqlease == 0 && m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
915 GrantCacheExtensions(m, q, opt->u.llq.llqlease);
916 SetLLQTimer(m, q, &opt->u.llq);
917 q->ntries = 0;
918 }
919 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
920 *matchQuestion = q;
921 return uDNS_LLQ_Ignore;
922 }
923 if (q->state < LLQ_Established && mDNSSameAddress(srcaddr, &q->servAddr))
924 {
925 LLQ_State oldstate = q->state;
926 recvSetupResponse(m, msg->h.flags.b[1] & kDNSFlag1_RC_Mask, q, &opt->u.llq);
927 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
928 // We have a protocol anomaly here in the LLQ definition.
929 // Both the challenge packet from the server and the ack+answers packet have opt->u.llq.llqOp == kLLQOp_Setup.
930 // However, we need to treat them differently:
931 // The challenge packet has no answers in it, and tells us nothing about whether our cache entries
932 // are still valid, so this packet should not cause us to do anything that messes with our cache.
933 // The ack+answers packet gives us the whole truth, so we should handle it by updating our cache
934 // to match the answers in the packet, and only the answers in the packet.
935 *matchQuestion = q;
936 return (oldstate == LLQ_SecondaryRequest ? uDNS_LLQ_Entire : uDNS_LLQ_Ignore);
937 }
938 }
939 }
940 }
941 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
942 }
943 *matchQuestion = mDNSNULL;
944 return uDNS_LLQ_Not;
945 }
946
947 // Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
948 struct TCPSocket_struct { TCPSocketFlags flags; /* ... */ };
949
950 // tcpCallback is called to handle events (e.g. connection opening and data reception) on TCP connections for
951 // Private DNS operations -- private queries, private LLQs, private record updates and private service updates
952 mDNSlocal void tcpCallback(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err)
953 {
954 tcpInfo_t *tcpInfo = (tcpInfo_t *)context;
955 mDNSBool closed = mDNSfalse;
956 mDNS *m = tcpInfo->m;
957 DNSQuestion *const q = tcpInfo->question;
958 tcpInfo_t **backpointer =
959 q ? &q ->tcp :
960 tcpInfo->rr ? &tcpInfo->rr ->tcp : mDNSNULL;
961 if (backpointer && *backpointer != tcpInfo)
962 LogMsg("tcpCallback: %d backpointer %p incorrect tcpInfo %p question %p rr %p",
963 mDNSPlatformTCPGetFD(tcpInfo->sock), *backpointer, tcpInfo, q, tcpInfo->rr);
964
965 if (err) goto exit;
966
967 if (ConnectionEstablished)
968 {
969 mDNSu8 *end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
970 DomainAuthInfo *AuthInfo;
971
972 // Defensive coding for <rdar://problem/5546824> Crash in mDNSResponder at GetAuthInfoForName_internal + 366
973 // 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
974 if (tcpInfo->rr && tcpInfo->rr->resrec.name != &tcpInfo->rr->namestorage)
975 LogMsg("tcpCallback: ERROR: tcpInfo->rr->resrec.name %p != &tcpInfo->rr->namestorage %p",
976 tcpInfo->rr->resrec.name, &tcpInfo->rr->namestorage);
977 if (tcpInfo->rr && tcpInfo->rr-> resrec.name != &tcpInfo->rr-> namestorage) return;
978
979 AuthInfo = tcpInfo->rr ? GetAuthInfoForName(m, tcpInfo->rr->resrec.name) : mDNSNULL;
980
981 // connection is established - send the message
982 if (q && q->LongLived && q->state == LLQ_Established)
983 {
984 // Lease renewal over TCP, resulting from opening a TCP connection in sendLLQRefresh
985 end = ((mDNSu8*) &tcpInfo->request) + tcpInfo->requestLen;
986 }
987 else if (q && q->LongLived && q->state != LLQ_Poll && !mDNSIPPortIsZero(m->LLQNAT.ExternalPort) && !mDNSIPPortIsZero(q->servPort))
988 {
989 // Notes:
990 // If we have a NAT port mapping, ExternalPort is the external port
991 // If we have a routable address so we don't need a port mapping, ExternalPort is the same as our own internal port
992 // If we need a NAT port mapping but can't get one, then ExternalPort is zero
993 LLQOptData llqData; // set llq rdata
994 llqData.vers = kLLQ_Vers;
995 llqData.llqOp = kLLQOp_Setup;
996 llqData.err = GetLLQEventPort(m, &tcpInfo->Addr); // We're using TCP; tell server what UDP port to send notifications to
997 LogInfo("tcpCallback: eventPort %d", llqData.err);
998 llqData.id = zeroOpaque64;
999 llqData.llqlease = kLLQ_DefLease;
1000 InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
1001 end = putLLQ(&tcpInfo->request, tcpInfo->request.data, q, &llqData);
1002 if (!end) { LogMsg("ERROR: tcpCallback - putLLQ"); err = mStatus_UnknownErr; goto exit; }
1003 AuthInfo = q->AuthInfo; // Need to add TSIG to this message
1004 q->ntries = 0; // Reset ntries so that tcp/tls connection failures don't affect sendChallengeResponse failures
1005 }
1006 else if (q)
1007 {
1008 // LLQ Polling mode or non-LLQ uDNS over TCP
1009 InitializeDNSMessage(&tcpInfo->request.h, q->TargetQID, uQueryFlags);
1010 end = putQuestion(&tcpInfo->request, tcpInfo->request.data, tcpInfo->request.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
1011 AuthInfo = q->AuthInfo; // Need to add TSIG to this message
1012 }
1013
1014 err = mDNSSendDNSMessage(m, &tcpInfo->request, end, mDNSInterface_Any, mDNSNULL, &tcpInfo->Addr, tcpInfo->Port, sock, AuthInfo);
1015 if (err) { debugf("ERROR: tcpCallback: mDNSSendDNSMessage - %d", err); err = mStatus_UnknownErr; goto exit; }
1016
1017 // Record time we sent this question
1018 if (q)
1019 {
1020 mDNS_Lock(m);
1021 q->LastQTime = m->timenow;
1022 if (q->ThisQInterval < (256 * mDNSPlatformOneSecond)) // Now we have a TCP connection open, make sure we wait at least 256 seconds before retrying
1023 q->ThisQInterval = (256 * mDNSPlatformOneSecond);
1024 SetNextQueryTime(m, q);
1025 mDNS_Unlock(m);
1026 }
1027 }
1028 else
1029 {
1030 long n;
1031 if (tcpInfo->nread < 2) // First read the two-byte length preceeding the DNS message
1032 {
1033 mDNSu8 *lenptr = (mDNSu8 *)&tcpInfo->replylen;
1034 n = mDNSPlatformReadTCP(sock, lenptr + tcpInfo->nread, 2 - tcpInfo->nread, &closed);
1035 if (n < 0)
1036 {
1037 LogMsg("ERROR: tcpCallback - attempt to read message length failed (%d)", n);
1038 err = mStatus_ConnFailed;
1039 goto exit;
1040 }
1041 else if (closed)
1042 {
1043 // It's perfectly fine for this socket to close after the first reply. The server might
1044 // be sending gratuitous replies using UDP and doesn't have a need to leave the TCP socket open.
1045 // We'll only log this event if we've never received a reply before.
1046 // BIND 9 appears to close an idle connection after 30 seconds.
1047 if (tcpInfo->numReplies == 0)
1048 {
1049 LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
1050 err = mStatus_ConnFailed;
1051 goto exit;
1052 }
1053 else
1054 {
1055 // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1056 // over this tcp connection. That is, we only track whether we've received at least one response
1057 // which may have been to a previous request sent over this tcp connection.
1058 if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1059 DisposeTCPConn(tcpInfo);
1060 return;
1061 }
1062 }
1063
1064 tcpInfo->nread += n;
1065 if (tcpInfo->nread < 2) goto exit;
1066
1067 tcpInfo->replylen = (mDNSu16)((mDNSu16)lenptr[0] << 8 | lenptr[1]);
1068 if (tcpInfo->replylen < sizeof(DNSMessageHeader))
1069 { LogMsg("ERROR: tcpCallback - length too short (%d bytes)", tcpInfo->replylen); err = mStatus_UnknownErr; goto exit; }
1070
1071 tcpInfo->reply = mDNSPlatformMemAllocate(tcpInfo->replylen);
1072 if (!tcpInfo->reply) { LogMsg("ERROR: tcpCallback - malloc failed"); err = mStatus_NoMemoryErr; goto exit; }
1073 }
1074
1075 n = mDNSPlatformReadTCP(sock, ((char *)tcpInfo->reply) + (tcpInfo->nread - 2), tcpInfo->replylen - (tcpInfo->nread - 2), &closed);
1076
1077 if (n < 0)
1078 {
1079 LogMsg("ERROR: tcpCallback - read returned %d", n);
1080 err = mStatus_ConnFailed;
1081 goto exit;
1082 }
1083 else if (closed)
1084 {
1085 if (tcpInfo->numReplies == 0)
1086 {
1087 LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo->nread);
1088 err = mStatus_ConnFailed;
1089 goto exit;
1090 }
1091 else
1092 {
1093 // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1094 // over this tcp connection. That is, we only track whether we've received at least one response
1095 // which may have been to a previous request sent over this tcp connection.
1096 if (backpointer) *backpointer = mDNSNULL; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1097 DisposeTCPConn(tcpInfo);
1098 return;
1099 }
1100 }
1101
1102 tcpInfo->nread += n;
1103
1104 if ((tcpInfo->nread - 2) == tcpInfo->replylen)
1105 {
1106 mDNSBool tls;
1107 DNSMessage *reply = tcpInfo->reply;
1108 mDNSu8 *end = (mDNSu8 *)tcpInfo->reply + tcpInfo->replylen;
1109 mDNSAddr Addr = tcpInfo->Addr;
1110 mDNSIPPort Port = tcpInfo->Port;
1111 mDNSIPPort srcPort = zeroIPPort;
1112 tcpInfo->numReplies++;
1113 tcpInfo->reply = mDNSNULL; // Detach reply buffer from tcpInfo_t, to make sure client callback can't cause it to be disposed
1114 tcpInfo->nread = 0;
1115 tcpInfo->replylen = 0;
1116
1117 // If we're going to dispose this connection, do it FIRST, before calling client callback
1118 // Note: Sleep code depends on us clearing *backpointer here -- it uses the clearing of rr->tcp
1119 // as the signal that the DNS deregistration operation with the server has completed, and the machine may now sleep
1120 // If we clear the tcp pointer in the question, mDNSCoreReceiveResponse cannot find a matching question. Hence
1121 // we store the minimal information i.e., the source port of the connection in the question itself.
1122 // Dereference sock before it is disposed in DisposeTCPConn below.
1123
1124 if (sock->flags & kTCPSocketFlags_UseTLS) tls = mDNStrue;
1125 else tls = mDNSfalse;
1126
1127 if (q && q->tcp) {srcPort = q->tcp->SrcPort; q->tcpSrcPort = srcPort;}
1128
1129 if (backpointer)
1130 if (!q || !q->LongLived || m->SleepState)
1131 { *backpointer = mDNSNULL; DisposeTCPConn(tcpInfo); }
1132
1133 mDNSCoreReceive(m, reply, end, &Addr, Port, tls ? (mDNSAddr *)1 : mDNSNULL, srcPort, 0);
1134 // USE CAUTION HERE: Invoking mDNSCoreReceive may have caused the environment to change, including canceling this operation itself
1135
1136 mDNSPlatformMemFree(reply);
1137 return;
1138 }
1139 }
1140
1141 exit:
1142
1143 if (err)
1144 {
1145 // Clear client backpointer FIRST -- that way if one of the callbacks cancels its operation
1146 // we won't end up double-disposing our tcpInfo_t
1147 if (backpointer) *backpointer = mDNSNULL;
1148
1149 mDNS_Lock(m); // Need to grab the lock to get m->timenow
1150
1151 if (q)
1152 {
1153 if (q->ThisQInterval == 0)
1154 {
1155 // 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.
1156 // Note that ThisQInterval is also zero when sendChallengeResponse resends the LLQ request on an extant TCP/TLS connection.
1157 q->LastQTime = m->timenow;
1158 if (q->LongLived)
1159 {
1160 // We didn't get the chance to send our request packet before the TCP/TLS connection failed.
1161 // We want to retry quickly, but want to back off exponentially in case the server is having issues.
1162 // Since ThisQInterval was 0, we can't just multiply by QuestionIntervalStep, we must track the number
1163 // of TCP/TLS connection failures using ntries.
1164 mDNSu32 count = q->ntries + 1; // want to wait at least 1 second before retrying
1165
1166 q->ThisQInterval = InitialQuestionInterval;
1167
1168 for (;count;count--)
1169 q->ThisQInterval *= QuestionIntervalStep;
1170
1171 if (q->ThisQInterval > LLQ_POLL_INTERVAL)
1172 q->ThisQInterval = LLQ_POLL_INTERVAL;
1173 else
1174 q->ntries++;
1175
1176 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);
1177 }
1178 else
1179 {
1180 q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
1181 LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
1182 }
1183 SetNextQueryTime(m, q);
1184 }
1185 else if (NextQSendTime(q) - m->timenow > (q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL))
1186 {
1187 // If we get an error and our next scheduled query for this question is more than the max interval from now,
1188 // reset the next query to ensure we wait no longer the maximum interval from now before trying again.
1189 q->LastQTime = m->timenow;
1190 q->ThisQInterval = q->LongLived ? LLQ_POLL_INTERVAL : MAX_UCAST_POLL_INTERVAL;
1191 SetNextQueryTime(m, q);
1192 LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
1193 }
1194
1195 // We're about to dispose of the TCP connection, so we must reset the state to retry over TCP/TLS
1196 // because sendChallengeResponse will send the query via UDP if we don't have a tcp pointer.
1197 // Resetting to LLQ_InitialRequest will cause uDNS_CheckCurrentQuestion to call startLLQHandshake, which
1198 // will attempt to establish a new tcp connection.
1199 if (q->LongLived && q->state == LLQ_SecondaryRequest)
1200 q->state = LLQ_InitialRequest;
1201
1202 // ConnFailed may happen if the server sends a TCP reset or TLS fails, in which case we want to retry establishing the LLQ
1203 // quickly rather than switching to polling mode. This case is handled by the above code to set q->ThisQInterval just above.
1204 // If the error isn't ConnFailed, then the LLQ is in bad shape, so we switch to polling mode.
1205 if (err != mStatus_ConnFailed)
1206 {
1207 if (q->LongLived && q->state != LLQ_Poll) StartLLQPolling(m, q);
1208 }
1209 }
1210
1211 mDNS_Unlock(m);
1212
1213 DisposeTCPConn(tcpInfo);
1214 }
1215 }
1216
1217 mDNSlocal tcpInfo_t *MakeTCPConn(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
1218 TCPSocketFlags flags, const mDNSAddr *const Addr, const mDNSIPPort Port, domainname *hostname,
1219 DNSQuestion *const question, AuthRecord *const rr)
1220 {
1221 mStatus err;
1222 mDNSIPPort srcport = zeroIPPort;
1223 tcpInfo_t *info;
1224
1225 if ((flags & kTCPSocketFlags_UseTLS) && (!hostname || !hostname->c[0]))
1226 { LogMsg("MakeTCPConn: TLS connection being setup with NULL hostname"); return mDNSNULL; }
1227
1228 info = (tcpInfo_t *)mDNSPlatformMemAllocate(sizeof(tcpInfo_t));
1229 if (!info) { LogMsg("ERROR: MakeTCP - memallocate failed"); return(mDNSNULL); }
1230 mDNSPlatformMemZero(info, sizeof(tcpInfo_t));
1231
1232 info->m = m;
1233 info->sock = mDNSPlatformTCPSocket(m, flags, &srcport);
1234 info->requestLen = 0;
1235 info->question = question;
1236 info->rr = rr;
1237 info->Addr = *Addr;
1238 info->Port = Port;
1239 info->reply = mDNSNULL;
1240 info->replylen = 0;
1241 info->nread = 0;
1242 info->numReplies = 0;
1243 info->SrcPort = srcport;
1244
1245 if (msg)
1246 {
1247 info->requestLen = (int) (end - ((mDNSu8*)msg));
1248 mDNSPlatformMemCopy(&info->request, msg, info->requestLen);
1249 }
1250
1251 if (!info->sock) { LogMsg("MakeTCPConn: unable to create TCP socket"); mDNSPlatformMemFree(info); return(mDNSNULL); }
1252 err = mDNSPlatformTCPConnect(info->sock, Addr, Port, hostname, (question ? question->InterfaceID : mDNSNULL), tcpCallback, info);
1253
1254 // Probably suboptimal here.
1255 // Instead of returning mDNSNULL here on failure, we should probably invoke the callback with an error code.
1256 // That way clients can put all the error handling and retry/recovery code in one place,
1257 // instead of having to handle immediate errors in one place and async errors in another.
1258 // Also: "err == mStatus_ConnEstablished" probably never happens.
1259
1260 // Don't need to log "connection failed" in customer builds -- it happens quite often during sleep, wake, configuration changes, etc.
1261 if (err == mStatus_ConnEstablished) { tcpCallback(info->sock, info, mDNStrue, mStatus_NoError); }
1262 else if (err != mStatus_ConnPending ) { LogInfo("MakeTCPConn: connection failed"); DisposeTCPConn(info); return(mDNSNULL); }
1263 return(info);
1264 }
1265
1266 mDNSexport void DisposeTCPConn(struct tcpInfo_t *tcp)
1267 {
1268 mDNSPlatformTCPCloseConnection(tcp->sock);
1269 if (tcp->reply) mDNSPlatformMemFree(tcp->reply);
1270 mDNSPlatformMemFree(tcp);
1271 }
1272
1273 // Lock must be held
1274 mDNSexport void startLLQHandshake(mDNS *m, DNSQuestion *q)
1275 {
1276 if (mDNSIPv4AddressIsOnes(m->LLQNAT.ExternalAddress))
1277 {
1278 LogInfo("startLLQHandshake: waiting for NAT status for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1279 q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10); // Retry in approx 15 minutes
1280 q->LastQTime = m->timenow;
1281 SetNextQueryTime(m, q);
1282 return;
1283 }
1284
1285 // Either we don't have NAT-PMP support (ExternalPort is zero) or behind a Double NAT that may or
1286 // may not have NAT-PMP support (NATResult is non-zero)
1287 if (mDNSIPPortIsZero(m->LLQNAT.ExternalPort) || m->LLQNAT.Result)
1288 {
1289 LogInfo("startLLQHandshake: Cannot receive inbound packets; will poll for %##s (%s) External Port %d, NAT Result %d",
1290 q->qname.c, DNSTypeName(q->qtype), mDNSVal16(m->LLQNAT.ExternalPort), m->LLQNAT.Result);
1291 StartLLQPolling(m, q);
1292 return;
1293 }
1294
1295 if (mDNSIPPortIsZero(q->servPort))
1296 {
1297 debugf("startLLQHandshake: StartGetZoneData for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1298 q->ThisQInterval = LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10); // Retry in approx 15 minutes
1299 q->LastQTime = m->timenow;
1300 SetNextQueryTime(m, q);
1301 q->servAddr = zeroAddr;
1302 // We know q->servPort is zero because of check above
1303 if (q->nta) CancelGetZoneData(m, q->nta);
1304 q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
1305 return;
1306 }
1307
1308 if (PrivateQuery(q))
1309 {
1310 if (q->tcp) LogInfo("startLLQHandshake: Disposing existing TCP connection for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1311 if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
1312 if (!q->nta)
1313 {
1314 // Normally we lookup the zone data and then call this function. And we never free the zone data
1315 // for "PrivateQuery". But sometimes this can happen due to some race conditions. When we
1316 // switch networks, we might end up "Polling" the network e.g., we are behind a Double NAT.
1317 // When we poll, we free the zone information as we send the query to the server (See
1318 // PrivateQueryGotZoneData). The NAT callback (LLQNATCallback) may happen soon after that. If we
1319 // are still behind Double NAT, we would have returned early in this function. But we could
1320 // have switched to a network with no NATs and we should get the zone data again.
1321 LogInfo("startLLQHandshake: nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1322 q->nta = StartGetZoneData(m, &q->qname, ZoneServiceLLQ, LLQGotZoneData, q);
1323 return;
1324 }
1325 else if (!q->nta->Host.c[0])
1326 {
1327 // This should not happen. If it happens, we print a log and MakeTCPConn will fail if it can't find a hostname
1328 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);
1329 }
1330 q->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
1331 if (!q->tcp)
1332 q->ThisQInterval = mDNSPlatformOneSecond * 5; // If TCP failed (transient networking glitch) try again in five seconds
1333 else
1334 {
1335 q->state = LLQ_SecondaryRequest; // Right now, for private DNS, we skip the four-way LLQ handshake
1336 q->ReqLease = kLLQ_DefLease;
1337 q->ThisQInterval = 0;
1338 }
1339 q->LastQTime = m->timenow;
1340 SetNextQueryTime(m, q);
1341 }
1342 else
1343 {
1344 debugf("startLLQHandshake: m->AdvertisedV4 %#a%s Server %#a:%d%s %##s (%s)",
1345 &m->AdvertisedV4, mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) ? " (RFC 1918)" : "",
1346 &q->servAddr, mDNSVal16(q->servPort), mDNSAddrIsRFC1918(&q->servAddr) ? " (RFC 1918)" : "",
1347 q->qname.c, DNSTypeName(q->qtype));
1348
1349 if (q->ntries++ >= kLLQ_MAX_TRIES)
1350 {
1351 LogMsg("startLLQHandshake: %d failed attempts for LLQ %##s Polling.", kLLQ_MAX_TRIES, q->qname.c);
1352 StartLLQPolling(m, q);
1353 }
1354 else
1355 {
1356 mDNSu8 *end;
1357 LLQOptData llqData;
1358
1359 // set llq rdata
1360 llqData.vers = kLLQ_Vers;
1361 llqData.llqOp = kLLQOp_Setup;
1362 llqData.err = LLQErr_NoError; // Don't need to tell server UDP notification port when sending over UDP
1363 llqData.id = zeroOpaque64;
1364 llqData.llqlease = kLLQ_DefLease;
1365
1366 InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
1367 end = putLLQ(&m->omsg, m->omsg.data, q, &llqData);
1368 if (!end) { LogMsg("ERROR: startLLQHandshake - putLLQ"); StartLLQPolling(m,q); return; }
1369
1370 mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, mDNSNULL, mDNSNULL);
1371
1372 // update question state
1373 q->state = LLQ_InitialRequest;
1374 q->ReqLease = kLLQ_DefLease;
1375 q->ThisQInterval = (kLLQ_INIT_RESEND * mDNSPlatformOneSecond);
1376 q->LastQTime = m->timenow;
1377 SetNextQueryTime(m, q);
1378 }
1379 }
1380 }
1381
1382 // forward declaration so GetServiceTarget can do reverse lookup if needed
1383 mDNSlocal void GetStaticHostname(mDNS *m);
1384
1385 mDNSexport const domainname *GetServiceTarget(mDNS *m, AuthRecord *const rr)
1386 {
1387 debugf("GetServiceTarget %##s", rr->resrec.name->c);
1388
1389 if (!rr->AutoTarget) // If not automatically tracking this host's current name, just return the existing target
1390 return(&rr->resrec.rdata->u.srv.target);
1391 else
1392 {
1393 #if APPLE_OSX_mDNSResponder
1394 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
1395 if (AuthInfo && AuthInfo->AutoTunnel)
1396 {
1397 // If this AutoTunnel is not yet active, start it now (which entails activating its NAT Traversal request,
1398 // which will subsequently advertise the appropriate records when the NAT Traversal returns a result)
1399 if (!AuthInfo->AutoTunnelNAT.clientContext && m->AutoTunnelHostAddr.b[0])
1400 {
1401 LogInfo("GetServiceTarget: Calling SetupLocalAutoTunnelInterface_internal");
1402 SetupLocalAutoTunnelInterface_internal(m, mDNStrue);
1403 }
1404 if (AuthInfo->AutoTunnelHostRecord.namestorage.c[0] == 0) return(mDNSNULL);
1405 debugf("GetServiceTarget: Returning %##s", AuthInfo->AutoTunnelHostRecord.namestorage.c);
1406 return(&AuthInfo->AutoTunnelHostRecord.namestorage);
1407 }
1408 else
1409 #endif // APPLE_OSX_mDNSResponder
1410 {
1411 const int srvcount = CountLabels(rr->resrec.name);
1412 HostnameInfo *besthi = mDNSNULL, *hi;
1413 int best = 0;
1414 for (hi = m->Hostnames; hi; hi = hi->next)
1415 if (hi->arv4.state == regState_Registered || hi->arv4.state == regState_Refresh ||
1416 hi->arv6.state == regState_Registered || hi->arv6.state == regState_Refresh)
1417 {
1418 int x, hostcount = CountLabels(&hi->fqdn);
1419 for (x = hostcount < srvcount ? hostcount : srvcount; x > 0 && x > best; x--)
1420 if (SameDomainName(SkipLeadingLabels(rr->resrec.name, srvcount - x), SkipLeadingLabels(&hi->fqdn, hostcount - x)))
1421 { best = x; besthi = hi; }
1422 }
1423
1424 if (besthi) return(&besthi->fqdn);
1425 }
1426 if (m->StaticHostname.c[0]) return(&m->StaticHostname);
1427 else GetStaticHostname(m); // asynchronously do reverse lookup for primary IPv4 address
1428 LogInfo("GetServiceTarget: Returning NULL for %s", ARDisplayString(m, rr));
1429 return(mDNSNULL);
1430 }
1431 }
1432
1433 mDNSlocal const domainname *PUBLIC_UPDATE_SERVICE_TYPE = (const domainname*)"\x0B_dns-update" "\x04_udp";
1434 mDNSlocal const domainname *PUBLIC_LLQ_SERVICE_TYPE = (const domainname*)"\x08_dns-llq" "\x04_udp";
1435
1436 mDNSlocal const domainname *PRIVATE_UPDATE_SERVICE_TYPE = (const domainname*)"\x0F_dns-update-tls" "\x04_tcp";
1437 mDNSlocal const domainname *PRIVATE_QUERY_SERVICE_TYPE = (const domainname*)"\x0E_dns-query-tls" "\x04_tcp";
1438 mDNSlocal const domainname *PRIVATE_LLQ_SERVICE_TYPE = (const domainname*)"\x0C_dns-llq-tls" "\x04_tcp";
1439
1440 #define ZoneDataSRV(X) (\
1441 (X)->ZoneService == ZoneServiceUpdate ? ((X)->ZonePrivate ? PRIVATE_UPDATE_SERVICE_TYPE : PUBLIC_UPDATE_SERVICE_TYPE) : \
1442 (X)->ZoneService == ZoneServiceQuery ? ((X)->ZonePrivate ? PRIVATE_QUERY_SERVICE_TYPE : (const domainname*)"" ) : \
1443 (X)->ZoneService == ZoneServiceLLQ ? ((X)->ZonePrivate ? PRIVATE_LLQ_SERVICE_TYPE : PUBLIC_LLQ_SERVICE_TYPE ) : (const domainname*)"")
1444
1445 // Forward reference: GetZoneData_StartQuery references GetZoneData_QuestionCallback, and
1446 // GetZoneData_QuestionCallback calls GetZoneData_StartQuery
1447 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype);
1448
1449 // GetZoneData_QuestionCallback is called from normal client callback context (core API calls allowed)
1450 mDNSlocal void GetZoneData_QuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
1451 {
1452 ZoneData *zd = (ZoneData*)question->QuestionContext;
1453
1454 debugf("GetZoneData_QuestionCallback: %s %s", AddRecord ? "Add" : "Rmv", RRDisplayString(m, answer));
1455
1456 if (!AddRecord) return; // Don't care about REMOVE events
1457 if (AddRecord == QC_addnocache && answer->rdlength == 0) return; // Don't care about transient failure indications
1458 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
1459
1460 if (answer->rrtype == kDNSType_SOA)
1461 {
1462 debugf("GetZoneData GOT SOA %s", RRDisplayString(m, answer));
1463 mDNS_StopQuery(m, question);
1464 if (question->ThisQInterval != -1)
1465 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1466 if (answer->rdlength)
1467 {
1468 AssignDomainName(&zd->ZoneName, answer->name);
1469 zd->ZoneClass = answer->rrclass;
1470 AssignDomainName(&zd->question.qname, &zd->ZoneName);
1471 GetZoneData_StartQuery(m, zd, kDNSType_SRV);
1472 }
1473 else if (zd->CurrentSOA->c[0])
1474 {
1475 DomainAuthInfo *AuthInfo = GetAuthInfoForName(m, zd->CurrentSOA);
1476 if (AuthInfo && AuthInfo->AutoTunnel)
1477 {
1478 // To keep the load on the server down, we don't chop down on
1479 // SOA lookups for AutoTunnels
1480 LogInfo("GetZoneData_QuestionCallback: not chopping labels for %##s", zd->CurrentSOA->c);
1481 zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
1482 }
1483 else
1484 {
1485 zd->CurrentSOA = (domainname *)(zd->CurrentSOA->c + zd->CurrentSOA->c[0]+1);
1486 AssignDomainName(&zd->question.qname, zd->CurrentSOA);
1487 GetZoneData_StartQuery(m, zd, kDNSType_SOA);
1488 }
1489 }
1490 else
1491 {
1492 LogInfo("GetZoneData recursed to root label of %##s without finding SOA", zd->ChildName.c);
1493 zd->ZoneDataCallback(m, mStatus_NoSuchNameErr, zd);
1494 }
1495 }
1496 else if (answer->rrtype == kDNSType_SRV)
1497 {
1498 debugf("GetZoneData GOT SRV %s", RRDisplayString(m, answer));
1499 mDNS_StopQuery(m, question);
1500 if (question->ThisQInterval != -1)
1501 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1502 // Right now we don't want to fail back to non-encrypted operations
1503 // If the AuthInfo has the AutoTunnel field set, then we want private or nothing
1504 // <rdar://problem/5687667> BTMM: Don't fallback to unencrypted operations when SRV lookup fails
1505 #if 0
1506 if (!answer->rdlength && zd->ZonePrivate && zd->ZoneService != ZoneServiceQuery)
1507 {
1508 zd->ZonePrivate = mDNSfalse; // Causes ZoneDataSRV() to yield a different SRV name when building the query
1509 GetZoneData_StartQuery(m, zd, kDNSType_SRV); // Try again, non-private this time
1510 }
1511 else
1512 #endif
1513 {
1514 if (answer->rdlength)
1515 {
1516 AssignDomainName(&zd->Host, &answer->rdata->u.srv.target);
1517 zd->Port = answer->rdata->u.srv.port;
1518 AssignDomainName(&zd->question.qname, &zd->Host);
1519 GetZoneData_StartQuery(m, zd, kDNSType_A);
1520 }
1521 else
1522 {
1523 zd->ZonePrivate = mDNSfalse;
1524 zd->Host.c[0] = 0;
1525 zd->Port = zeroIPPort;
1526 zd->Addr = zeroAddr;
1527 zd->ZoneDataCallback(m, mStatus_NoError, zd);
1528 }
1529 }
1530 }
1531 else if (answer->rrtype == kDNSType_A)
1532 {
1533 debugf("GetZoneData GOT A %s", RRDisplayString(m, answer));
1534 mDNS_StopQuery(m, question);
1535 if (question->ThisQInterval != -1)
1536 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question->qname.c, DNSTypeName(question->qtype), question->ThisQInterval);
1537 zd->Addr.type = mDNSAddrType_IPv4;
1538 zd->Addr.ip.v4 = (answer->rdlength == 4) ? answer->rdata->u.ipv4 : zerov4Addr;
1539 // In order to simulate firewalls blocking our outgoing TCP connections, returning immediate ICMP errors or TCP resets,
1540 // the code below will make us try to connect to loopback, resulting in an immediate "port unreachable" failure.
1541 // This helps us test to make sure we handle this case gracefully
1542 // <rdar://problem/5607082> BTMM: mDNSResponder taking 100 percent CPU after upgrading to 10.5.1
1543 #if 0
1544 zd->Addr.ip.v4.b[0] = 127;
1545 zd->Addr.ip.v4.b[1] = 0;
1546 zd->Addr.ip.v4.b[2] = 0;
1547 zd->Addr.ip.v4.b[3] = 1;
1548 #endif
1549 // The caller needs to free the memory when done with zone data
1550 zd->ZoneDataCallback(m, mStatus_NoError, zd);
1551 }
1552 }
1553
1554 // GetZoneData_StartQuery is called from normal client context (lock not held, or client callback)
1555 mDNSlocal mStatus GetZoneData_StartQuery(mDNS *const m, ZoneData *zd, mDNSu16 qtype)
1556 {
1557 if (qtype == kDNSType_SRV)
1558 {
1559 AssignDomainName(&zd->question.qname, ZoneDataSRV(zd));
1560 AppendDomainName(&zd->question.qname, &zd->ZoneName);
1561 debugf("lookupDNSPort %##s", zd->question.qname.c);
1562 }
1563
1564 // CancelGetZoneData can get called at any time. We should stop the question if it has not been
1565 // stopped already. A value of -1 for ThisQInterval indicates that the question is not active
1566 // yet.
1567 zd->question.ThisQInterval = -1;
1568 zd->question.InterfaceID = mDNSInterface_Any;
1569 zd->question.Target = zeroAddr;
1570 //zd->question.qname.c[0] = 0; // Already set
1571 zd->question.qtype = qtype;
1572 zd->question.qclass = kDNSClass_IN;
1573 zd->question.LongLived = mDNSfalse;
1574 zd->question.ExpectUnique = mDNStrue;
1575 zd->question.ForceMCast = mDNSfalse;
1576 zd->question.ReturnIntermed = mDNStrue;
1577 zd->question.SuppressUnusable = mDNSfalse;
1578 zd->question.WakeOnResolve = mDNSfalse;
1579 zd->question.QuestionCallback = GetZoneData_QuestionCallback;
1580 zd->question.QuestionContext = zd;
1581
1582 //LogMsg("GetZoneData_StartQuery %##s (%s) %p", zd->question.qname.c, DNSTypeName(zd->question.qtype), zd->question.Private);
1583 return(mDNS_StartQuery(m, &zd->question));
1584 }
1585
1586 // StartGetZoneData is an internal routine (i.e. must be called with the lock already held)
1587 mDNSexport ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *ZoneDataContext)
1588 {
1589 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, name);
1590 int initialskip = (AuthInfo && AuthInfo->AutoTunnel) ? DomainNameLength(name) - DomainNameLength(&AuthInfo->domain) : 0;
1591 ZoneData *zd = (ZoneData*)mDNSPlatformMemAllocate(sizeof(ZoneData));
1592 if (!zd) { LogMsg("ERROR: StartGetZoneData - mDNSPlatformMemAllocate failed"); return mDNSNULL; }
1593 mDNSPlatformMemZero(zd, sizeof(ZoneData));
1594 AssignDomainName(&zd->ChildName, name);
1595 zd->ZoneService = target;
1596 zd->CurrentSOA = (domainname *)(&zd->ChildName.c[initialskip]);
1597 zd->ZoneName.c[0] = 0;
1598 zd->ZoneClass = 0;
1599 zd->Host.c[0] = 0;
1600 zd->Port = zeroIPPort;
1601 zd->Addr = zeroAddr;
1602 zd->ZonePrivate = AuthInfo && AuthInfo->AutoTunnel ? mDNStrue : mDNSfalse;
1603 zd->ZoneDataCallback = callback;
1604 zd->ZoneDataContext = ZoneDataContext;
1605
1606 zd->question.QuestionContext = zd;
1607 AssignDomainName(&zd->question.qname, zd->CurrentSOA);
1608
1609 mDNS_DropLockBeforeCallback(); // GetZoneData_StartQuery expects to be called from a normal callback, so we emulate that here
1610 GetZoneData_StartQuery(m, zd, kDNSType_SOA);
1611 mDNS_ReclaimLockAfterCallback();
1612
1613 return zd;
1614 }
1615
1616 // GetZoneData queries are a special case -- even if we have a key for them, we don't do them privately,
1617 // because that would result in an infinite loop (i.e. to do a private query we first need to get
1618 // the _dns-query-tls SRV record for the zone, and we can't do *that* privately because to do so
1619 // we'd need to already know the _dns-query-tls SRV record.
1620 // Also, as a general rule, we never do SOA queries privately
1621 mDNSexport DomainAuthInfo *GetAuthInfoForQuestion(mDNS *m, const DNSQuestion *const q) // Must be called with lock held
1622 {
1623 if (q->QuestionCallback == GetZoneData_QuestionCallback) return(mDNSNULL);
1624 if (q->qtype == kDNSType_SOA ) return(mDNSNULL);
1625 return(GetAuthInfoForName_internal(m, &q->qname));
1626 }
1627
1628 // ***************************************************************************
1629 #if COMPILER_LIKES_PRAGMA_MARK
1630 #pragma mark - host name and interface management
1631 #endif
1632
1633 mDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr);
1634 mDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr);
1635 mDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time);
1636
1637 // When this function is called, service record is already deregistered. We just
1638 // have to deregister the PTR and TXT records.
1639 mDNSlocal void UpdateAllServiceRecords(mDNS *const m, AuthRecord *rr, mDNSBool reg)
1640 {
1641 AuthRecord *r, *srvRR;
1642
1643 if (rr->resrec.rrtype != kDNSType_SRV) { LogMsg("UpdateAllServiceRecords:ERROR!! ResourceRecord not a service record %s", ARDisplayString(m, rr)); return; }
1644
1645 if (reg && rr->state == regState_NoTarget) { LogMsg("UpdateAllServiceRecords:ERROR!! SRV record %s in noTarget state during registration", ARDisplayString(m, rr)); return; }
1646
1647 LogInfo("UpdateAllServiceRecords: ResourceRecord %s", ARDisplayString(m, rr));
1648
1649 for (r = m->ResourceRecords; r; r=r->next)
1650 {
1651 if (!AuthRecord_uDNS(r)) continue;
1652 srvRR = mDNSNULL;
1653 if (r->resrec.rrtype == kDNSType_PTR)
1654 srvRR = r->Additional1;
1655 else if (r->resrec.rrtype == kDNSType_TXT)
1656 srvRR = r->DependentOn;
1657 if (srvRR && srvRR->resrec.rrtype != kDNSType_SRV)
1658 LogMsg("UpdateAllServiceRecords: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1659 if (srvRR == rr)
1660 {
1661 if (!reg)
1662 {
1663 LogInfo("UpdateAllServiceRecords: deregistering %s", ARDisplayString(m, r));
1664 r->SRVChanged = mDNStrue;
1665 r->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1666 r->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1667 r->state = regState_DeregPending;
1668 }
1669 else
1670 {
1671 // Clearing SRVchanged is a safety measure. If our pewvious dereg never
1672 // came back and we had a target change, we are starting fresh
1673 r->SRVChanged = mDNSfalse;
1674 // if it is already registered or in the process of registering, then don't
1675 // bother re-registering. This happens today for non-BTMM domains where the
1676 // TXT and PTR get registered before SRV records because of the delay in
1677 // getting the port mapping. There is no point in re-registering the TXT
1678 // and PTR records.
1679 if ((r->state == regState_Registered) ||
1680 (r->state == regState_Pending && r->nta && !mDNSIPv4AddressIsZero(r->nta->Addr.ip.v4)))
1681 LogInfo("UpdateAllServiceRecords: not registering %s, state %d", ARDisplayString(m, r), r->state);
1682 else
1683 {
1684 LogInfo("UpdateAllServiceRecords: registering %s, state %d", ARDisplayString(m, r), r->state);
1685 ActivateUnicastRegistration(m, r);
1686 }
1687 }
1688 }
1689 }
1690 }
1691
1692 // Called in normal client context (lock not held)
1693 // Currently only supports SRV records for nat mapping
1694 mDNSlocal void CompleteRecordNatMap(mDNS *m, NATTraversalInfo *n)
1695 {
1696 const domainname *target;
1697 domainname *srvt;
1698 AuthRecord *rr = (AuthRecord *)n->clientContext;
1699 debugf("SRVNatMap complete %.4a IntPort %u ExternalPort %u NATLease %u", &n->ExternalAddress, mDNSVal16(n->IntPort), mDNSVal16(n->ExternalPort), n->NATLease);
1700
1701 if (!rr) { LogMsg("CompleteRecordNatMap called with unknown AuthRecord object"); return; }
1702 if (!n->NATLease) { LogMsg("CompleteRecordNatMap No NATLease for %s", ARDisplayString(m, rr)); return; }
1703
1704 if (rr->resrec.rrtype != kDNSType_SRV) {LogMsg("CompleteRecordNatMap: Not a service record %s", ARDisplayString(m, rr)); return; }
1705
1706 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) { LogInfo("CompleteRecordNatMap called for %s, Service deregistering", ARDisplayString(m, rr)); return; }
1707
1708 if (rr->state == regState_DeregPending) { LogInfo("CompleteRecordNatMap called for %s, record in DeregPending", ARDisplayString(m, rr)); return; }
1709
1710 // As we free the zone info after registering/deregistering with the server (See hndlRecordUpdateReply),
1711 // we need to restart the get zone data and nat mapping request to get the latest mapping result as we can't handle it
1712 // at this moment. Restart from the beginning.
1713 if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
1714 {
1715 LogInfo("CompleteRecordNatMap called for %s but no zone information!", ARDisplayString(m, rr));
1716 // We need to clear out the NATinfo state so that it will result in re-acquiring the mapping
1717 // and hence this callback called again.
1718 if (rr->NATinfo.clientContext)
1719 {
1720 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1721 rr->NATinfo.clientContext = mDNSNULL;
1722 }
1723 rr->state = regState_Pending;
1724 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1725 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1726 return;
1727 }
1728
1729 mDNS_Lock(m);
1730 // Reevaluate the target always as Target could have changed while
1731 // we were getting the port mapping (See UpdateOneSRVRecord)
1732 target = GetServiceTarget(m, rr);
1733 srvt = GetRRDomainNameTarget(&rr->resrec);
1734 if (!target || target->c[0] == 0 || mDNSIPPortIsZero(n->ExternalPort))
1735 {
1736 if (target && target->c[0])
1737 LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
1738 else
1739 LogInfo("CompleteRecordNatMap - no target for %##s, ExternalPort %d", rr->resrec.name->c, mDNSVal16(n->ExternalPort));
1740 if (srvt) srvt->c[0] = 0;
1741 rr->state = regState_NoTarget;
1742 rr->resrec.rdlength = rr->resrec.rdestimate = 0;
1743 mDNS_Unlock(m);
1744 UpdateAllServiceRecords(m, rr, mDNSfalse);
1745 return;
1746 }
1747 LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target->c, rr->resrec.name->c, mDNSVal16(n->ExternalPort));
1748 // This function might get called multiple times during a network transition event. Previosuly, we could
1749 // have put the SRV record in NoTarget state above and deregistered all the other records. When this
1750 // function gets called again with a non-zero ExternalPort, we need to set the target and register the
1751 // other records again.
1752 if (srvt && !SameDomainName(srvt, target))
1753 {
1754 AssignDomainName(srvt, target);
1755 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
1756 }
1757
1758 // SRVChanged is set when when the target of the SRV record changes (See UpdateOneSRVRecord).
1759 // As a result of the target change, we might register just that SRV Record if it was
1760 // previously registered and we have a new target OR deregister SRV (and the associated
1761 // PTR/TXT records) if we don't have a target anymore. When we get a response from the server,
1762 // SRVChanged state tells that we registered/deregistered because of a target change
1763 // and hence handle accordingly e.g., if we deregistered, put the records in NoTarget state OR
1764 // if we registered then put it in Registered state.
1765 //
1766 // Here, we are registering all the records again from the beginning. Treat this as first time
1767 // registration rather than a temporary target change.
1768 rr->SRVChanged = mDNSfalse;
1769
1770 // We want IsRecordMergeable to check whether it is a record whose update can be
1771 // sent with others. We set the time before we call IsRecordMergeable, so that
1772 // it does not fail this record based on time. We are interested in other checks
1773 // at this time
1774 rr->state = regState_Pending;
1775 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1776 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1777 if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
1778 // Delay the record registration by MERGE_DELAY_TIME so that we can merge them
1779 // into one update
1780 rr->LastAPTime += MERGE_DELAY_TIME;
1781 mDNS_Unlock(m);
1782 // We call this always even though it may not be necessary always e.g., normal registration
1783 // process where TXT and PTR gets registered followed by the SRV record after it gets
1784 // the port mapping. In that case, UpdateAllServiceRecords handles the optimization. The
1785 // update of TXT and PTR record is required if we entered noTargetState before as explained
1786 // above.
1787 UpdateAllServiceRecords(m, rr, mDNStrue);
1788 }
1789
1790 mDNSlocal void StartRecordNatMap(mDNS *m, AuthRecord *rr)
1791 {
1792 const mDNSu8 *p;
1793 mDNSu8 protocol;
1794
1795 if (rr->resrec.rrtype != kDNSType_SRV)
1796 {
1797 LogInfo("StartRecordNatMap: Resource Record %##s type %d, not supported", rr->resrec.name->c, rr->resrec.rrtype);
1798 return;
1799 }
1800 p = rr->resrec.name->c;
1801 //Assume <Service Instance>.<App Protocol>.<Transport protocol>.<Name>
1802 // Skip the first two labels to get to the transport protocol
1803 if (p[0]) p += 1 + p[0];
1804 if (p[0]) p += 1 + p[0];
1805 if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_tcp")) protocol = NATOp_MapTCP;
1806 else if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_udp")) protocol = NATOp_MapUDP;
1807 else { LogMsg("StartRecordNatMap: could not determine transport protocol of service %##s", rr->resrec.name->c); return; }
1808
1809 //LogMsg("StartRecordNatMap: clientContext %p IntPort %d srv.port %d %s",
1810 // rr->NATinfo.clientContext, mDNSVal16(rr->NATinfo.IntPort), mDNSVal16(rr->resrec.rdata->u.srv.port), ARDisplayString(m, rr));
1811 if (rr->NATinfo.clientContext) mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1812 rr->NATinfo.Protocol = protocol;
1813
1814 // Shouldn't be trying to set IntPort here --
1815 // BuildUpdateMessage overwrites srs->RR_SRV.resrec.rdata->u.srv.port with external (mapped) port number
1816 rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1817 rr->NATinfo.RequestedPort = rr->resrec.rdata->u.srv.port;
1818 rr->NATinfo.NATLease = 0; // Request default lease
1819 rr->NATinfo.clientCallback = CompleteRecordNatMap;
1820 rr->NATinfo.clientContext = rr;
1821 mDNS_StartNATOperation_internal(m, &rr->NATinfo);
1822 }
1823
1824 // Unlink an Auth Record from the m->ResourceRecords list.
1825 // When a resource record enters regState_NoTarget initially, mDNS_Register_internal
1826 // does not initialize completely e.g., it cannot check for duplicates etc. The resource
1827 // record is temporarily left in the ResourceRecords list so that we can initialize later
1828 // when the target is resolvable. Similarly, when host name changes, we enter regState_NoTarget
1829 // and we do the same.
1830
1831 // This UnlinkResourceRecord routine is very worrying. It bypasses all the normal cleanup performed
1832 // by mDNS_Deregister_internal and just unceremoniously cuts the record from the active list.
1833 // This is why re-regsitering this record was producing syslog messages like this:
1834 // "Error! Tried to add a NAT traversal that's already in the active list"
1835 // Right now UnlinkResourceRecord is fortunately only called by RegisterAllServiceRecords,
1836 // which then immediately calls mDNS_Register_internal to re-register the record, which probably
1837 // masked more serious problems. Any other use of UnlinkResourceRecord is likely to lead to crashes.
1838 // For now we'll workaround that specific problem by explicitly calling mDNS_StopNATOperation_internal,
1839 // but long-term we should either stop cancelling the record registration and then re-registering it,
1840 // or if we really do need to do this for some reason it should be done via the usual
1841 // mDNS_Deregister_internal path instead of just cutting the record from the list.
1842
1843 mDNSlocal mStatus UnlinkResourceRecord(mDNS *const m, AuthRecord *const rr)
1844 {
1845 AuthRecord **list = &m->ResourceRecords;
1846 while (*list && *list != rr) list = &(*list)->next;
1847 if (*list)
1848 {
1849 *list = rr->next;
1850 rr->next = mDNSNULL;
1851
1852 // Temporary workaround to cancel any active NAT mapping operation
1853 if (rr->NATinfo.clientContext)
1854 {
1855 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1856 rr->NATinfo.clientContext = mDNSNULL;
1857 if (rr->resrec.rrtype == kDNSType_SRV) rr->resrec.rdata->u.srv.port = rr->NATinfo.IntPort;
1858 }
1859
1860 return(mStatus_NoError);
1861 }
1862 LogMsg("UnlinkResourceRecord:ERROR!! - no such active record %##s", rr->resrec.name->c);
1863 return(mStatus_NoSuchRecord);
1864 }
1865
1866 // We need to go through mDNS_Register again as we did not complete the
1867 // full initialization last time e.g., duplicate checks.
1868 // After we register, we will be in regState_GetZoneData.
1869 mDNSlocal void RegisterAllServiceRecords(mDNS *const m, AuthRecord *rr)
1870 {
1871 LogInfo("RegisterAllServiceRecords: Service Record %##s", rr->resrec.name->c);
1872 // First Register the service record, we do this differently from other records because
1873 // when it entered NoTarget state, it did not go through complete initialization
1874 rr->SRVChanged = mDNSfalse;
1875 UnlinkResourceRecord(m, rr);
1876 mDNS_Register_internal(m, rr);
1877 // Register the other records
1878 UpdateAllServiceRecords(m, rr, mDNStrue);
1879 }
1880
1881 // Called with lock held
1882 mDNSlocal void UpdateOneSRVRecord(mDNS *m, AuthRecord *rr)
1883 {
1884 // Target change if:
1885 // We have a target and were previously waiting for one, or
1886 // We had a target and no longer do, or
1887 // The target has changed
1888
1889 domainname *curtarget = &rr->resrec.rdata->u.srv.target;
1890 const domainname *const nt = GetServiceTarget(m, rr);
1891 const domainname *const newtarget = nt ? nt : (domainname*)"";
1892 mDNSBool TargetChanged = (newtarget->c[0] && rr->state == regState_NoTarget) || !SameDomainName(curtarget, newtarget);
1893 mDNSBool HaveZoneData = rr->nta && !mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4);
1894
1895 // Nat state change if:
1896 // We were behind a NAT, and now we are behind a new NAT, or
1897 // We're not behind a NAT but our port was previously mapped to a different external port
1898 // We were not behind a NAT and now we are
1899
1900 mDNSIPPort port = rr->resrec.rdata->u.srv.port;
1901 mDNSBool NowNeedNATMAP = (rr->AutoTarget == Target_AutoHostAndNATMAP && !mDNSIPPortIsZero(port) && mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && rr->nta && !mDNSAddrIsRFC1918(&rr->nta->Addr));
1902 mDNSBool WereBehindNAT = (rr->NATinfo.clientContext != mDNSNULL);
1903 mDNSBool PortWasMapped = (rr->NATinfo.clientContext && !mDNSSameIPPort(rr->NATinfo.RequestedPort, port)); // I think this is always false -- SC Sept 07
1904 mDNSBool NATChanged = (!WereBehindNAT && NowNeedNATMAP) || (!NowNeedNATMAP && PortWasMapped);
1905
1906 (void)HaveZoneData; //unused
1907
1908 LogInfo("UpdateOneSRVRecord: Resource Record %s TargetChanged %d, NewTarget %##s", ARDisplayString(m, rr), TargetChanged, nt->c);
1909
1910 debugf("UpdateOneSRVRecord: %##s newtarget %##s TargetChanged %d HaveZoneData %d port %d NowNeedNATMAP %d WereBehindNAT %d PortWasMapped %d NATChanged %d",
1911 rr->resrec.name->c, newtarget,
1912 TargetChanged, HaveZoneData, mDNSVal16(port), NowNeedNATMAP, WereBehindNAT, PortWasMapped, NATChanged);
1913
1914 if (m->mDNS_busy != m->mDNS_reentrancy+1)
1915 LogMsg("UpdateOneSRVRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
1916
1917 if (!TargetChanged && !NATChanged) return;
1918
1919 // If we are deregistering the record, then ignore any NAT/Target change.
1920 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1921 {
1922 LogInfo("UpdateOneSRVRecord: Deregistering record, Ignoring TargetChanged %d, NATChanged %d for %##s, state %d", TargetChanged, NATChanged,
1923 rr->resrec.name->c, rr->state);
1924 return;
1925 }
1926
1927 if (newtarget)
1928 LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, newtarget %##s", TargetChanged, NATChanged, rr->resrec.name->c, rr->state, newtarget->c);
1929 else
1930 LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, null newtarget", TargetChanged, NATChanged, rr->resrec.name->c, rr->state);
1931 switch(rr->state)
1932 {
1933 case regState_NATMap:
1934 // In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
1935 // or is in the process of, or has already been, deregistered. This assumes that whenever we transition out
1936 // of this state, we need to look at the target again.
1937 return;
1938
1939 case regState_UpdatePending:
1940 // We are getting a Target change/NAT change while the SRV record is being updated ?
1941 // let us not do anything for now.
1942 return;
1943
1944 case regState_NATError:
1945 if (!NATChanged) return;
1946 // if nat changed, register if we have a target (below)
1947
1948 case regState_NoTarget:
1949 if (!newtarget->c[0])
1950 {
1951 LogInfo("UpdateOneSRVRecord: No target yet for Resource Record %s", ARDisplayString(m, rr));
1952 return;
1953 }
1954 RegisterAllServiceRecords(m , rr);
1955 return;
1956 case regState_DeregPending:
1957 // We are in DeregPending either because the service was deregistered from above or we handled
1958 // a NAT/Target change before and sent the deregistration below. There are a few race conditions
1959 // possible
1960 //
1961 // 1. We are handling a second NAT/Target change while the first dereg is in progress. It is possible
1962 // that first dereg never made it through because there was no network connectivity e.g., disconnecting
1963 // from network triggers this function due to a target change and later connecting to the network
1964 // retriggers this function but the deregistration never made it through yet. Just fall through.
1965 // If there is a target register otherwise deregister.
1966 //
1967 // 2. While we sent the dereg during a previous NAT/Target change, uDNS_DeregisterRecord gets
1968 // called as part of service deregistration. When the response comes back, we call
1969 // CompleteDeregistration rather than handle NAT/Target change because the record is in
1970 // kDNSRecordTypeDeregistering state.
1971 //
1972 // 3. If the upper layer deregisters the service, we check for kDNSRecordTypeDeregistering both
1973 // here in this function to avoid handling NAT/Target change and in hndlRecordUpdateReply to call
1974 // CompleteDeregistration instead of handling NAT/Target change. Hence, we are not concerned
1975 // about that case here.
1976 //
1977 // We just handle case (1) by falling through
1978 case regState_Pending:
1979 case regState_Refresh:
1980 case regState_Registered:
1981 // target or nat changed. deregister service. upon completion, we'll look for a new target
1982 rr->SRVChanged = mDNStrue;
1983 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1984 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
1985 if (newtarget->c[0])
1986 {
1987 LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s, registering with new target %##s",
1988 rr->resrec.name->c, newtarget->c);
1989 rr->state = regState_Pending;
1990 }
1991 else
1992 {
1993 LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s de-registering", rr->resrec.name->c);
1994 rr->state = regState_DeregPending;
1995 UpdateAllServiceRecords(m, rr, mDNSfalse);
1996 }
1997 return;
1998 case regState_Unregistered:
1999 default: LogMsg("UpdateOneSRVRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
2000 }
2001 }
2002
2003 mDNSexport void UpdateAllSRVRecords(mDNS *m)
2004 {
2005 m->NextSRVUpdate = 0;
2006 LogInfo("UpdateAllSRVRecords %d", m->SleepState);
2007
2008 if (m->CurrentRecord)
2009 LogMsg("UpdateAllSRVRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2010 m->CurrentRecord = m->ResourceRecords;
2011 while (m->CurrentRecord)
2012 {
2013 AuthRecord *rptr = m->CurrentRecord;
2014 m->CurrentRecord = m->CurrentRecord->next;
2015 if (AuthRecord_uDNS(rptr) && rptr->resrec.rrtype == kDNSType_SRV)
2016 UpdateOneSRVRecord(m, rptr);
2017 }
2018 }
2019
2020 // Forward reference: AdvertiseHostname references HostnameCallback, and HostnameCallback calls AdvertiseHostname
2021 mDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
2022
2023 // Called in normal client context (lock not held)
2024 mDNSlocal void hostnameGetPublicAddressCallback(mDNS *m, NATTraversalInfo *n)
2025 {
2026 HostnameInfo *h = (HostnameInfo *)n->clientContext;
2027
2028 if (!h) { LogMsg("RegisterHostnameRecord: registration cancelled"); return; }
2029
2030 if (!n->Result)
2031 {
2032 if (mDNSIPv4AddressIsZero(n->ExternalAddress) || mDNSv4AddrIsRFC1918(&n->ExternalAddress)) return;
2033
2034 if (h->arv4.resrec.RecordType)
2035 {
2036 if (mDNSSameIPv4Address(h->arv4.resrec.rdata->u.ipv4, n->ExternalAddress)) return; // If address unchanged, do nothing
2037 LogInfo("Updating hostname %p %##s IPv4 from %.4a to %.4a (NAT gateway's external address)",n,
2038 h->arv4.resrec.name->c, &h->arv4.resrec.rdata->u.ipv4, &n->ExternalAddress);
2039 mDNS_Deregister(m, &h->arv4); // mStatus_MemFree callback will re-register with new address
2040 }
2041 else
2042 {
2043 LogInfo("Advertising hostname %##s IPv4 %.4a (NAT gateway's external address)", h->arv4.resrec.name->c, &n->ExternalAddress);
2044 h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
2045 h->arv4.resrec.rdata->u.ipv4 = n->ExternalAddress;
2046 mDNS_Register(m, &h->arv4);
2047 }
2048 }
2049 }
2050
2051 // register record or begin NAT traversal
2052 mDNSlocal void AdvertiseHostname(mDNS *m, HostnameInfo *h)
2053 {
2054 if (!mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4) && h->arv4.resrec.RecordType == kDNSRecordTypeUnregistered)
2055 {
2056 mDNS_SetupResourceRecord(&h->arv4, mDNSNULL, mDNSInterface_Any, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnregistered, HostnameCallback, h);
2057 AssignDomainName(&h->arv4.namestorage, &h->fqdn);
2058 h->arv4.resrec.rdata->u.ipv4 = m->AdvertisedV4.ip.v4;
2059 h->arv4.state = regState_Unregistered;
2060 if (mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4))
2061 {
2062 // If we already have a NAT query active, stop it and restart it to make sure we get another callback
2063 if (h->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &h->natinfo);
2064 h->natinfo.Protocol = 0;
2065 h->natinfo.IntPort = zeroIPPort;
2066 h->natinfo.RequestedPort = zeroIPPort;
2067 h->natinfo.NATLease = 0;
2068 h->natinfo.clientCallback = hostnameGetPublicAddressCallback;
2069 h->natinfo.clientContext = h;
2070 mDNS_StartNATOperation_internal(m, &h->natinfo);
2071 }
2072 else
2073 {
2074 LogInfo("Advertising hostname %##s IPv4 %.4a", h->arv4.resrec.name->c, &m->AdvertisedV4.ip.v4);
2075 h->arv4.resrec.RecordType = kDNSRecordTypeKnownUnique;
2076 mDNS_Register_internal(m, &h->arv4);
2077 }
2078 }
2079
2080 if (!mDNSIPv6AddressIsZero(m->AdvertisedV6.ip.v6) && h->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
2081 {
2082 mDNS_SetupResourceRecord(&h->arv6, mDNSNULL, mDNSInterface_Any, kDNSType_AAAA, kHostNameTTL, kDNSRecordTypeKnownUnique, HostnameCallback, h);
2083 AssignDomainName(&h->arv6.namestorage, &h->fqdn);
2084 h->arv6.resrec.rdata->u.ipv6 = m->AdvertisedV6.ip.v6;
2085 h->arv6.state = regState_Unregistered;
2086 LogInfo("Advertising hostname %##s IPv6 %.16a", h->arv6.resrec.name->c, &m->AdvertisedV6.ip.v6);
2087 mDNS_Register_internal(m, &h->arv6);
2088 }
2089 }
2090
2091 mDNSlocal void HostnameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
2092 {
2093 HostnameInfo *hi = (HostnameInfo *)rr->RecordContext;
2094
2095 if (result == mStatus_MemFree)
2096 {
2097 if (hi)
2098 {
2099 // If we're still in the Hostnames list, update to new address
2100 HostnameInfo *i;
2101 LogInfo("HostnameCallback: Got mStatus_MemFree for %p %p %s", hi, rr, ARDisplayString(m, rr));
2102 for (i = m->Hostnames; i; i = i->next)
2103 if (rr == &i->arv4 || rr == &i->arv6)
2104 { mDNS_Lock(m); AdvertiseHostname(m, i); mDNS_Unlock(m); return; }
2105
2106 // Else, we're not still in the Hostnames list, so free the memory
2107 if (hi->arv4.resrec.RecordType == kDNSRecordTypeUnregistered &&
2108 hi->arv6.resrec.RecordType == kDNSRecordTypeUnregistered)
2109 {
2110 if (hi->natinfo.clientContext) mDNS_StopNATOperation_internal(m, &hi->natinfo);
2111 hi->natinfo.clientContext = mDNSNULL;
2112 mDNSPlatformMemFree(hi); // free hi when both v4 and v6 AuthRecs deallocated
2113 }
2114 }
2115 return;
2116 }
2117
2118 if (result)
2119 {
2120 // don't unlink or free - we can retry when we get a new address/router
2121 if (rr->resrec.rrtype == kDNSType_A)
2122 LogMsg("HostnameCallback: Error %d for registration of %##s IP %.4a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
2123 else
2124 LogMsg("HostnameCallback: Error %d for registration of %##s IP %.16a", result, rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
2125 if (!hi) { mDNSPlatformMemFree(rr); return; }
2126 if (rr->state != regState_Unregistered) LogMsg("Error: HostnameCallback invoked with error code for record not in regState_Unregistered!");
2127
2128 if (hi->arv4.state == regState_Unregistered &&
2129 hi->arv6.state == regState_Unregistered)
2130 {
2131 // only deliver status if both v4 and v6 fail
2132 rr->RecordContext = (void *)hi->StatusContext;
2133 if (hi->StatusCallback)
2134 hi->StatusCallback(m, rr, result); // client may NOT make API calls here
2135 rr->RecordContext = (void *)hi;
2136 }
2137 return;
2138 }
2139
2140 // register any pending services that require a target
2141 mDNS_Lock(m);
2142 m->NextSRVUpdate = NonZeroTime(m->timenow);
2143 mDNS_Unlock(m);
2144
2145 // Deliver success to client
2146 if (!hi) { LogMsg("HostnameCallback invoked with orphaned address record"); return; }
2147 if (rr->resrec.rrtype == kDNSType_A)
2148 LogInfo("Registered hostname %##s IP %.4a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv4);
2149 else
2150 LogInfo("Registered hostname %##s IP %.16a", rr->resrec.name->c, &rr->resrec.rdata->u.ipv6);
2151
2152 rr->RecordContext = (void *)hi->StatusContext;
2153 if (hi->StatusCallback)
2154 hi->StatusCallback(m, rr, result); // client may NOT make API calls here
2155 rr->RecordContext = (void *)hi;
2156 }
2157
2158 mDNSlocal void FoundStaticHostname(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2159 {
2160 const domainname *pktname = &answer->rdata->u.name;
2161 domainname *storedname = &m->StaticHostname;
2162 HostnameInfo *h = m->Hostnames;
2163
2164 (void)question;
2165
2166 if (answer->rdlength != 0)
2167 LogInfo("FoundStaticHostname: question %##s -> answer %##s (%s)", question->qname.c, answer->rdata->u.name.c, AddRecord ? "ADD" : "RMV");
2168 else
2169 LogInfo("FoundStaticHostname: question %##s -> answer NULL (%s)", question->qname.c, AddRecord ? "ADD" : "RMV");
2170
2171 if (AddRecord && answer->rdlength != 0 && !SameDomainName(pktname, storedname))
2172 {
2173 AssignDomainName(storedname, pktname);
2174 while (h)
2175 {
2176 if (h->arv4.state == regState_Pending || h->arv4.state == regState_NATMap || h->arv6.state == regState_Pending)
2177 {
2178 // 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
2179 m->NextSRVUpdate = NonZeroTime(m->timenow + 5 * mDNSPlatformOneSecond);
2180 debugf("FoundStaticHostname: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
2181 return;
2182 }
2183 h = h->next;
2184 }
2185 mDNS_Lock(m);
2186 m->NextSRVUpdate = NonZeroTime(m->timenow);
2187 mDNS_Unlock(m);
2188 }
2189 else if (!AddRecord && SameDomainName(pktname, storedname))
2190 {
2191 mDNS_Lock(m);
2192 storedname->c[0] = 0;
2193 m->NextSRVUpdate = NonZeroTime(m->timenow);
2194 mDNS_Unlock(m);
2195 }
2196 }
2197
2198 // Called with lock held
2199 mDNSlocal void GetStaticHostname(mDNS *m)
2200 {
2201 char buf[MAX_REVERSE_MAPPING_NAME_V4];
2202 DNSQuestion *q = &m->ReverseMap;
2203 mDNSu8 *ip = m->AdvertisedV4.ip.v4.b;
2204 mStatus err;
2205
2206 if (m->ReverseMap.ThisQInterval != -1) return; // already running
2207 if (mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4)) return;
2208
2209 mDNSPlatformMemZero(q, sizeof(*q));
2210 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
2211 mDNS_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa.", ip[3], ip[2], ip[1], ip[0]);
2212 if (!MakeDomainNameFromDNSNameString(&q->qname, buf)) { LogMsg("Error: GetStaticHostname - bad name %s", buf); return; }
2213
2214 q->InterfaceID = mDNSInterface_Any;
2215 q->Target = zeroAddr;
2216 q->qtype = kDNSType_PTR;
2217 q->qclass = kDNSClass_IN;
2218 q->LongLived = mDNSfalse;
2219 q->ExpectUnique = mDNSfalse;
2220 q->ForceMCast = mDNSfalse;
2221 q->ReturnIntermed = mDNStrue;
2222 q->SuppressUnusable = mDNSfalse;
2223 q->WakeOnResolve = mDNSfalse;
2224 q->QuestionCallback = FoundStaticHostname;
2225 q->QuestionContext = mDNSNULL;
2226
2227 LogInfo("GetStaticHostname: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2228 err = mDNS_StartQuery_internal(m, q);
2229 if (err) LogMsg("Error: GetStaticHostname - StartQuery returned error %d", err);
2230 }
2231
2232 mDNSexport void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext)
2233 {
2234 HostnameInfo **ptr = &m->Hostnames;
2235
2236 LogInfo("mDNS_AddDynDNSHostName %##s", fqdn);
2237
2238 while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
2239 if (*ptr) { LogMsg("DynDNSHostName %##s already in list", fqdn->c); return; }
2240
2241 // allocate and format new address record
2242 *ptr = mDNSPlatformMemAllocate(sizeof(**ptr));
2243 if (!*ptr) { LogMsg("ERROR: mDNS_AddDynDNSHostName - malloc"); return; }
2244
2245 mDNSPlatformMemZero(*ptr, sizeof(**ptr));
2246 AssignDomainName(&(*ptr)->fqdn, fqdn);
2247 (*ptr)->arv4.state = regState_Unregistered;
2248 (*ptr)->arv6.state = regState_Unregistered;
2249 (*ptr)->StatusCallback = StatusCallback;
2250 (*ptr)->StatusContext = StatusContext;
2251
2252 AdvertiseHostname(m, *ptr);
2253 }
2254
2255 mDNSexport void mDNS_RemoveDynDNSHostName(mDNS *m, const domainname *fqdn)
2256 {
2257 HostnameInfo **ptr = &m->Hostnames;
2258
2259 LogInfo("mDNS_RemoveDynDNSHostName %##s", fqdn);
2260
2261 while (*ptr && !SameDomainName(fqdn, &(*ptr)->fqdn)) ptr = &(*ptr)->next;
2262 if (!*ptr) LogMsg("mDNS_RemoveDynDNSHostName: no such domainname %##s", fqdn->c);
2263 else
2264 {
2265 HostnameInfo *hi = *ptr;
2266 // We do it this way because, if we have no active v6 record, the "mDNS_Deregister_internal(m, &hi->arv4);"
2267 // below could free the memory, and we have to make sure we don't touch hi fields after that.
2268 mDNSBool f4 = hi->arv4.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv4.state != regState_Unregistered;
2269 mDNSBool f6 = hi->arv6.resrec.RecordType != kDNSRecordTypeUnregistered && hi->arv6.state != regState_Unregistered;
2270 if (f4) LogInfo("mDNS_RemoveDynDNSHostName removing v4 %##s", fqdn);
2271 if (f6) LogInfo("mDNS_RemoveDynDNSHostName removing v6 %##s", fqdn);
2272 *ptr = (*ptr)->next; // unlink
2273 if (f4) mDNS_Deregister_internal(m, &hi->arv4, mDNS_Dereg_normal);
2274 if (f6) mDNS_Deregister_internal(m, &hi->arv6, mDNS_Dereg_normal);
2275 // When both deregistrations complete we'll free the memory in the mStatus_MemFree callback
2276 }
2277 if (!m->mDNS_busy) LogMsg("mDNS_RemoveDynDNSHostName: ERROR: Lock not held");
2278 m->NextSRVUpdate = NonZeroTime(m->timenow);
2279 }
2280
2281 // Currently called without holding the lock
2282 // Maybe we should change that?
2283 mDNSexport void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *v4addr, const mDNSAddr *v6addr, const mDNSAddr *router)
2284 {
2285 mDNSBool v4Changed, v6Changed, RouterChanged;
2286
2287 if (m->mDNS_busy != m->mDNS_reentrancy)
2288 LogMsg("mDNS_SetPrimaryInterfaceInfo: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
2289
2290 if (v4addr && v4addr->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo v4 address - incorrect type. Discarding. %#a", v4addr); return; }
2291 if (v6addr && v6addr->type != mDNSAddrType_IPv6) { LogMsg("mDNS_SetPrimaryInterfaceInfo v6 address - incorrect type. Discarding. %#a", v6addr); return; }
2292 if (router && router->type != mDNSAddrType_IPv4) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-v4 router. Discarding. %#a", router); return; }
2293
2294 mDNS_Lock(m);
2295
2296 v4Changed = !mDNSSameIPv4Address(m->AdvertisedV4.ip.v4, v4addr ? v4addr->ip.v4 : zerov4Addr);
2297 v6Changed = !mDNSSameIPv6Address(m->AdvertisedV6.ip.v6, v6addr ? v6addr->ip.v6 : zerov6Addr);
2298 RouterChanged = !mDNSSameIPv4Address(m->Router.ip.v4, router ? router->ip.v4 : zerov4Addr);
2299
2300 if (v4addr && (v4Changed || RouterChanged))
2301 debugf("mDNS_SetPrimaryInterfaceInfo: address changed from %#a to %#a", &m->AdvertisedV4, v4addr);
2302
2303 if (v4addr) m->AdvertisedV4 = *v4addr; else m->AdvertisedV4.ip.v4 = zerov4Addr;
2304 if (v6addr) m->AdvertisedV6 = *v6addr; else m->AdvertisedV6.ip.v6 = zerov6Addr;
2305 if (router) m->Router = *router; else m->Router .ip.v4 = zerov4Addr;
2306 // setting router to zero indicates that nat mappings must be reestablished when router is reset
2307
2308 if (v4Changed || RouterChanged || v6Changed)
2309 {
2310 HostnameInfo *i;
2311 LogInfo("mDNS_SetPrimaryInterfaceInfo: %s%s%s%#a %#a %#a",
2312 v4Changed ? "v4Changed " : "",
2313 RouterChanged ? "RouterChanged " : "",
2314 v6Changed ? "v6Changed " : "", v4addr, v6addr, router);
2315
2316 for (i = m->Hostnames; i; i = i->next)
2317 {
2318 LogInfo("mDNS_SetPrimaryInterfaceInfo updating host name registrations for %##s", i->fqdn.c);
2319
2320 if (i->arv4.resrec.RecordType > kDNSRecordTypeDeregistering &&
2321 !mDNSSameIPv4Address(i->arv4.resrec.rdata->u.ipv4, m->AdvertisedV4.ip.v4))
2322 {
2323 LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv4));
2324 mDNS_Deregister_internal(m, &i->arv4, mDNS_Dereg_normal);
2325 }
2326
2327 if (i->arv6.resrec.RecordType > kDNSRecordTypeDeregistering &&
2328 !mDNSSameIPv6Address(i->arv6.resrec.rdata->u.ipv6, m->AdvertisedV6.ip.v6))
2329 {
2330 LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m, &i->arv6));
2331 mDNS_Deregister_internal(m, &i->arv6, mDNS_Dereg_normal);
2332 }
2333
2334 // AdvertiseHostname will only register new address records.
2335 // For records still in the process of deregistering it will ignore them, and let the mStatus_MemFree callback handle them.
2336 AdvertiseHostname(m, i);
2337 }
2338
2339 if (v4Changed || RouterChanged)
2340 {
2341 // If we have a non-zero IPv4 address, we should try immediately to see if we have a NAT gateway
2342 // If we have no IPv4 address, we don't want to be in quite such a hurry to report failures to our clients
2343 // <rdar://problem/6935929> Sleeping server sometimes briefly disappears over Back to My Mac after it wakes up
2344 m->ExternalAddress = zerov4Addr;
2345 m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
2346 m->retryGetAddr = m->timenow + (v4addr ? 0 : mDNSPlatformOneSecond * 5);
2347 m->NextScheduledNATOp = m->timenow;
2348 m->LastNATMapResultCode = NATErr_None;
2349 #ifdef _LEGACY_NAT_TRAVERSAL_
2350 LNT_ClearState(m);
2351 #endif // _LEGACY_NAT_TRAVERSAL_
2352 LogInfo("mDNS_SetPrimaryInterfaceInfo:%s%s: retryGetAddr in %d %d",
2353 v4Changed ? " v4Changed" : "",
2354 RouterChanged ? " RouterChanged" : "",
2355 m->retryGetAddr - m->timenow, m->timenow);
2356 }
2357
2358 if (m->ReverseMap.ThisQInterval != -1) mDNS_StopQuery_internal(m, &m->ReverseMap);
2359 m->StaticHostname.c[0] = 0;
2360
2361 m->NextSRVUpdate = NonZeroTime(m->timenow);
2362
2363 #if APPLE_OSX_mDNSResponder
2364 if (RouterChanged) uuid_generate(m->asl_uuid);
2365 UpdateAutoTunnelDomainStatuses(m);
2366 #endif
2367 }
2368
2369 mDNS_Unlock(m);
2370 }
2371
2372 // ***************************************************************************
2373 #if COMPILER_LIKES_PRAGMA_MARK
2374 #pragma mark - Incoming Message Processing
2375 #endif
2376
2377 mDNSlocal mStatus ParseTSIGError(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end, const domainname *const displayname)
2378 {
2379 const mDNSu8 *ptr;
2380 mStatus err = mStatus_NoError;
2381 int i;
2382
2383 ptr = LocateAdditionals(msg, end);
2384 if (!ptr) goto finish;
2385
2386 for (i = 0; i < msg->h.numAdditionals; i++)
2387 {
2388 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
2389 if (!ptr) goto finish;
2390 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_TSIG)
2391 {
2392 mDNSu32 macsize;
2393 mDNSu8 *rd = m->rec.r.resrec.rdata->u.data;
2394 mDNSu8 *rdend = rd + m->rec.r.resrec.rdlength;
2395 int alglen = DomainNameLengthLimit(&m->rec.r.resrec.rdata->u.name, rdend);
2396 if (alglen > MAX_DOMAIN_NAME) goto finish;
2397 rd += alglen; // algorithm name
2398 if (rd + 6 > rdend) goto finish;
2399 rd += 6; // 48-bit timestamp
2400 if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2401 rd += sizeof(mDNSOpaque16); // fudge
2402 if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2403 macsize = mDNSVal16(*(mDNSOpaque16 *)rd);
2404 rd += sizeof(mDNSOpaque16); // MAC size
2405 if (rd + macsize > rdend) goto finish;
2406 rd += macsize;
2407 if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2408 rd += sizeof(mDNSOpaque16); // orig id
2409 if (rd + sizeof(mDNSOpaque16) > rdend) goto finish;
2410 err = mDNSVal16(*(mDNSOpaque16 *)rd); // error code
2411
2412 if (err == TSIG_ErrBadSig) { LogMsg("%##s: bad signature", displayname->c); err = mStatus_BadSig; }
2413 else if (err == TSIG_ErrBadKey) { LogMsg("%##s: bad key", displayname->c); err = mStatus_BadKey; }
2414 else if (err == TSIG_ErrBadTime) { LogMsg("%##s: bad time", displayname->c); err = mStatus_BadTime; }
2415 else if (err) { LogMsg("%##s: unknown tsig error %d", displayname->c, err); err = mStatus_UnknownErr; }
2416 goto finish;
2417 }
2418 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
2419 }
2420
2421 finish:
2422 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
2423 return err;
2424 }
2425
2426 mDNSlocal mStatus checkUpdateResult(mDNS *const m, const domainname *const displayname, const mDNSu8 rcode, const DNSMessage *const msg, const mDNSu8 *const end)
2427 {
2428 (void)msg; // currently unused, needed for TSIG errors
2429 if (!rcode) return mStatus_NoError;
2430 else if (rcode == kDNSFlag1_RC_YXDomain)
2431 {
2432 debugf("name in use: %##s", displayname->c);
2433 return mStatus_NameConflict;
2434 }
2435 else if (rcode == kDNSFlag1_RC_Refused)
2436 {
2437 LogMsg("Update %##s refused", displayname->c);
2438 return mStatus_Refused;
2439 }
2440 else if (rcode == kDNSFlag1_RC_NXRRSet)
2441 {
2442 LogMsg("Reregister refused (NXRRSET): %##s", displayname->c);
2443 return mStatus_NoSuchRecord;
2444 }
2445 else if (rcode == kDNSFlag1_RC_NotAuth)
2446 {
2447 // TSIG errors should come with FormErr as per RFC 2845, but BIND 9 sends them with NotAuth so we look here too
2448 mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
2449 if (!tsigerr)
2450 {
2451 LogMsg("Permission denied (NOAUTH): %##s", displayname->c);
2452 return mStatus_UnknownErr;
2453 }
2454 else return tsigerr;
2455 }
2456 else if (rcode == kDNSFlag1_RC_FormErr)
2457 {
2458 mStatus tsigerr = ParseTSIGError(m, msg, end, displayname);
2459 if (!tsigerr)
2460 {
2461 LogMsg("Format Error: %##s", displayname->c);
2462 return mStatus_UnknownErr;
2463 }
2464 else return tsigerr;
2465 }
2466 else
2467 {
2468 LogMsg("Update %##s failed with rcode %d", displayname->c, rcode);
2469 return mStatus_UnknownErr;
2470 }
2471 }
2472
2473 // We add three Additional Records for unicast resource record registrations
2474 // which is a function of AuthInfo and AutoTunnel properties
2475 mDNSlocal mDNSu32 RRAdditionalSize(mDNS *const m, DomainAuthInfo *AuthInfo)
2476 {
2477 mDNSu32 leaseSize, hinfoSize, tsigSize;
2478 mDNSu32 rr_base_size = 10; // type (2) class (2) TTL (4) rdlength (2)
2479
2480 // OPT RR : Emptyname(.) + base size + rdataOPT
2481 leaseSize = 1 + rr_base_size + sizeof(rdataOPT);
2482
2483 // HINFO: Resource Record Name + base size + RDATA
2484 // HINFO is added only for autotunnels
2485 hinfoSize = 0;
2486 if (AuthInfo && AuthInfo->AutoTunnel)
2487 hinfoSize = (m->hostlabel.c[0] + 1) + DomainNameLength(&AuthInfo->domain) +
2488 rr_base_size + (2 + m->HIHardware.c[0] + m->HISoftware.c[0]);
2489
2490 //TSIG: Resource Record Name + base size + RDATA
2491 // RDATA:
2492 // Algorithm name: hmac-md5.sig-alg.reg.int (8+7+3+3 + 5 bytes for length = 26 bytes)
2493 // Time: 6 bytes
2494 // Fudge: 2 bytes
2495 // Mac Size: 2 bytes
2496 // Mac: 16 bytes
2497 // ID: 2 bytes
2498 // Error: 2 bytes
2499 // Len: 2 bytes
2500 // Total: 58 bytes
2501 tsigSize = 0;
2502 if (AuthInfo) tsigSize = DomainNameLength(&AuthInfo->keyname) + rr_base_size + 58;
2503
2504 return (leaseSize + hinfoSize + tsigSize);
2505 }
2506
2507 //Note: Make sure that RREstimatedSize is updated accordingly if anything that is done here
2508 //would modify rdlength/rdestimate
2509 mDNSlocal mDNSu8* BuildUpdateMessage(mDNS *const m, mDNSu8 *ptr, AuthRecord *rr, mDNSu8 *limit)
2510 {
2511 //If this record is deregistering, then just send the deletion record
2512 if (rr->state == regState_DeregPending)
2513 {
2514 rr->expire = 0; // Indicate that we have no active registration any more
2515 ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit);
2516 if (!ptr) goto exit;
2517 return ptr;
2518 }
2519
2520 // This is a common function to both sending an update in a group or individual
2521 // records separately. Hence, we change the state here.
2522 if (rr->state == regState_Registered) rr->state = regState_Refresh;
2523 if (rr->state != regState_Refresh && rr->state != regState_UpdatePending)
2524 rr->state = regState_Pending;
2525
2526 // For Advisory records like e.g., _services._dns-sd, which is shared, don't send goodbyes as multiple
2527 // host might be registering records and deregistering from one does not make sense
2528 if (rr->resrec.RecordType != kDNSRecordTypeAdvisory) rr->RequireGoodbye = mDNStrue;
2529
2530 if ((rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHostAndNATMAP) &&
2531 !mDNSIPPortIsZero(rr->NATinfo.ExternalPort))
2532 {
2533 rr->resrec.rdata->u.srv.port = rr->NATinfo.ExternalPort;
2534 }
2535
2536 if (rr->state == regState_UpdatePending)
2537 {
2538 // delete old RData
2539 SetNewRData(&rr->resrec, rr->OrigRData, rr->OrigRDLen);
2540 if (!(ptr = putDeletionRecordWithLimit(&m->omsg, ptr, &rr->resrec, limit))) goto exit; // delete old rdata
2541
2542 // add new RData
2543 SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
2544 if (!(ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit))) goto exit;
2545 }
2546 else
2547 {
2548 if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
2549 {
2550 // KnownUnique : Delete any previous value
2551 // For Unicast registrations, we don't verify that it is unique, but set to verified and hence we want to
2552 // delete any previous value
2553 ptr = putDeleteRRSetWithLimit(&m->omsg, ptr, rr->resrec.name, rr->resrec.rrtype, limit);
2554 if (!ptr) goto exit;
2555 }
2556 else if (rr->resrec.RecordType != kDNSRecordTypeShared)
2557 {
2558 // For now don't do this, until we have the logic for intelligent grouping of individual records into logical service record sets
2559 //ptr = putPrereqNameNotInUse(rr->resrec.name, &m->omsg, ptr, end);
2560 if (!ptr) goto exit;
2561 }
2562
2563 ptr = PutResourceRecordTTLWithLimit(&m->omsg, ptr, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
2564 if (!ptr) goto exit;
2565 }
2566
2567 return ptr;
2568 exit:
2569 LogMsg("BuildUpdateMessage: Error formatting message for %s", ARDisplayString(m, rr));
2570 return mDNSNULL;
2571 }
2572
2573 // Called with lock held
2574 mDNSlocal void SendRecordRegistration(mDNS *const m, AuthRecord *rr)
2575 {
2576 mDNSu8 *ptr = m->omsg.data;
2577 mStatus err = mStatus_UnknownErr;
2578 mDNSu8 *limit;
2579 DomainAuthInfo *AuthInfo;
2580
2581 // For the ability to register large TXT records, we limit the single record registrations
2582 // to AbsoluteMaxDNSMessageData
2583 limit = ptr + AbsoluteMaxDNSMessageData;
2584
2585 AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
2586 limit -= RRAdditionalSize(m, AuthInfo);
2587
2588 if (m->mDNS_busy != m->mDNS_reentrancy+1)
2589 LogMsg("SendRecordRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
2590
2591 if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
2592 {
2593 // We never call this function when there is no zone information . Log a message if it ever happens.
2594 LogMsg("SendRecordRegistration: No Zone information, should not happen %s", ARDisplayString(m, rr));
2595 return;
2596 }
2597
2598 rr->updateid = mDNS_NewMessageID(m);
2599 InitializeDNSMessage(&m->omsg.h, rr->updateid, UpdateReqFlags);
2600
2601 // set zone
2602 ptr = putZone(&m->omsg, ptr, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
2603 if (!ptr) goto exit;
2604
2605 if (!(ptr = BuildUpdateMessage(m, ptr, rr, limit))) goto exit;
2606
2607 if (rr->uselease)
2608 {
2609 ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
2610 if (!ptr) goto exit;
2611 }
2612 if (rr->Private)
2613 {
2614 LogInfo("SendRecordRegistration TCP %p %s", rr->tcp, ARDisplayString(m, rr));
2615 if (rr->tcp) LogInfo("SendRecordRegistration: Disposing existing TCP connection for %s", ARDisplayString(m, rr));
2616 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2617 if (!rr->nta) { LogMsg("SendRecordRegistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
2618 rr->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &rr->nta->Addr, rr->nta->Port, &rr->nta->Host, mDNSNULL, rr);
2619 }
2620 else
2621 {
2622 LogInfo("SendRecordRegistration UDP %s", ARDisplayString(m, rr));
2623 if (!rr->nta) { LogMsg("SendRecordRegistration:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
2624 err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &rr->nta->Addr, rr->nta->Port, mDNSNULL, GetAuthInfoForName_internal(m, rr->resrec.name));
2625 if (err) debugf("ERROR: SendRecordRegistration - mDNSSendDNSMessage - %d", err);
2626 }
2627
2628 SetRecordRetry(m, rr, 0);
2629 return;
2630 exit:
2631 LogMsg("SendRecordRegistration: Error formatting message for %s, disabling further updates", ARDisplayString(m, rr));
2632 // Disable this record from future updates
2633 rr->state = regState_NoTarget;
2634 }
2635
2636 // Is the given record "rr" eligible for merging ?
2637 mDNSlocal mDNSBool IsRecordMergeable(mDNS *const m, AuthRecord *rr, mDNSs32 time)
2638 {
2639 DomainAuthInfo *info;
2640 (void) m; //unused
2641 // A record is eligible for merge, if the following properties are met.
2642 //
2643 // 1. uDNS Resource Record
2644 // 2. It is time to send them now
2645 // 3. It is in proper state
2646 // 4. Update zone has been resolved
2647 // 5. if DomainAuthInfo exists for the zone, it should not be soon deleted
2648 // 6. Zone information is present
2649 // 7. Update server is not zero
2650 // 8. It has a non-null zone
2651 // 9. It uses a lease option
2652 // 10. DontMerge is not set
2653 //
2654 // Following code is implemented as separate "if" statements instead of one "if" statement
2655 // is for better debugging purposes e.g., we know exactly what failed if debugging turned on.
2656
2657 if (!AuthRecord_uDNS(rr)) return mDNSfalse;
2658
2659 if (rr->LastAPTime + rr->ThisAPInterval - time > 0)
2660 { debugf("IsRecordMergeable: Time %d not reached for %s", rr->LastAPTime + rr->ThisAPInterval - m->timenow, ARDisplayString(m, rr)); return mDNSfalse; }
2661
2662 if (!rr->zone) return mDNSfalse;
2663
2664 info = GetAuthInfoForName_internal(m, rr->zone);
2665
2666 if (info && info->deltime && m->timenow - info->deltime >= 0) {debugf("IsRecordMergeable: Domain %##s will be deleted soon", info->domain.c); return mDNSfalse;}
2667
2668 if (rr->state != regState_DeregPending && rr->state != regState_Pending && rr->state != regState_Registered && rr->state != regState_Refresh && rr->state != regState_UpdatePending)
2669 { debugf("IsRecordMergeable: state %d not right %s", rr->state, ARDisplayString(m, rr)); return mDNSfalse; }
2670
2671 if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4)) return mDNSfalse;
2672
2673 if (!rr->uselease) return mDNSfalse;
2674
2675 if (rr->mState == mergeState_DontMerge) {debugf("IsRecordMergeable Dontmerge true %s", ARDisplayString(m, rr));return mDNSfalse;}
2676 debugf("IsRecordMergeable: Returning true for %s", ARDisplayString(m, rr));
2677 return mDNStrue;
2678 }
2679
2680 // Is the resource record "rr" eligible to merge to with "currentRR" ?
2681 mDNSlocal mDNSBool AreRecordsMergeable(mDNS *const m, AuthRecord *currentRR, AuthRecord *rr, mDNSs32 time)
2682 {
2683 // A record is eligible to merge with another record as long it is eligible for merge in itself
2684 // and it has the same zone information as the other record
2685 if (!IsRecordMergeable(m, rr, time)) return mDNSfalse;
2686
2687 if (!SameDomainName(currentRR->zone, rr->zone))
2688 { debugf("AreRecordMergeable zone mismatch current rr Zone %##s, rr zone %##s", currentRR->zone->c, rr->zone->c); return mDNSfalse; }
2689
2690 if (!mDNSSameIPv4Address(currentRR->nta->Addr.ip.v4, rr->nta->Addr.ip.v4)) return mDNSfalse;
2691
2692 if (!mDNSSameIPPort(currentRR->nta->Port, rr->nta->Port)) return mDNSfalse;
2693
2694 debugf("AreRecordsMergeable: Returning true for %s", ARDisplayString(m, rr));
2695 return mDNStrue;
2696 }
2697
2698 // If we can't build the message successfully because of problems in pre-computing
2699 // the space, we disable merging for all the current records
2700 mDNSlocal void RRMergeFailure(mDNS *const m)
2701 {
2702 AuthRecord *rr;
2703 for (rr = m->ResourceRecords; rr; rr = rr->next)
2704 {
2705 rr->mState = mergeState_DontMerge;
2706 rr->SendRNow = mDNSNULL;
2707 // Restarting the registration is much simpler than saving and restoring
2708 // the exact time
2709 ActivateUnicastRegistration(m, rr);
2710 }
2711 }
2712
2713 mDNSlocal void SendGroupRRMessage(mDNS *const m, AuthRecord *anchorRR, mDNSu8 *ptr, DomainAuthInfo *info)
2714 {
2715 mDNSu8 *limit;
2716 if (!anchorRR) {debugf("SendGroupRRMessage: Could not merge records"); return;}
2717
2718 if (info && info->AutoTunnel) limit = m->omsg.data + AbsoluteMaxDNSMessageData;
2719 else limit = m->omsg.data + NormalMaxDNSMessageData;
2720
2721 // This has to go in the additional section and hence need to be done last
2722 ptr = putUpdateLeaseWithLimit(&m->omsg, ptr, DEFAULT_UPDATE_LEASE, limit);
2723 if (!ptr)
2724 {
2725 LogMsg("SendGroupRRMessage: ERROR: Could not put lease option, failing the group registration");
2726 // if we can't put the lease, we need to undo the merge
2727 RRMergeFailure(m);
2728 return;
2729 }
2730 if (anchorRR->Private)
2731 {
2732 if (anchorRR->tcp) debugf("SendGroupRRMessage: Disposing existing TCP connection for %s", ARDisplayString(m, anchorRR));
2733 if (anchorRR->tcp) { DisposeTCPConn(anchorRR->tcp); anchorRR->tcp = mDNSNULL; }
2734 if (!anchorRR->nta) { LogMsg("SendGroupRRMessage:ERROR!! nta is NULL for %s", ARDisplayString(m, anchorRR)); return; }
2735 anchorRR->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &anchorRR->nta->Addr, anchorRR->nta->Port, &anchorRR->nta->Host, mDNSNULL, anchorRR);
2736 if (!anchorRR->tcp) LogInfo("SendGroupRRMessage: Cannot establish TCP connection for %s", ARDisplayString(m, anchorRR));
2737 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);
2738 }
2739 else
2740 {
2741 mStatus err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &anchorRR->nta->Addr, anchorRR->nta->Port, mDNSNULL, info);
2742 if (err) LogInfo("SendGroupRRMessage: Cannot send UDP message for %s", ARDisplayString(m, anchorRR));
2743 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);
2744 }
2745 return;
2746 }
2747
2748 // As we always include the zone information and the resource records contain zone name
2749 // at the end, it will get compressed. Hence, we subtract zoneSize and add two bytes for
2750 // the compression pointer
2751 mDNSlocal mDNSu32 RREstimatedSize(AuthRecord *rr, int zoneSize)
2752 {
2753 int rdlength;
2754
2755 // Note: Estimation of the record size has to mirror the logic in BuildUpdateMessage, otherwise estimation
2756 // would be wrong. Currently BuildUpdateMessage calls SetNewRData in UpdatePending case. Hence, we need
2757 // to account for that here. Otherwise, we might under estimate the size.
2758 if (rr->state == regState_UpdatePending)
2759 // old RData that will be deleted
2760 // new RData that will be added
2761 rdlength = rr->OrigRDLen + rr->InFlightRDLen;
2762 else
2763 rdlength = rr->resrec.rdestimate;
2764
2765 if (rr->state == regState_DeregPending)
2766 {
2767 debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
2768 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
2769 return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
2770 }
2771
2772 // For SRV, TXT, AAAA etc. that are Unique/Verified, we also send a Deletion Record
2773 if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique || rr->resrec.RecordType == kDNSRecordTypeVerified)
2774 {
2775 // Deletion Record: Resource Record Name + Base size (10) + 0
2776 // Record: Resource Record Name (Compressed = 2) + Base size (10) + rdestimate
2777
2778 debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
2779 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), DomainNameLength(rr->resrec.name), zoneSize, rdlength);
2780 return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + 2 + 10 + rdlength;
2781 }
2782 else
2783 {
2784 return DomainNameLength(rr->resrec.name) - zoneSize + 2 + 10 + rdlength;
2785 }
2786 }
2787
2788 mDNSlocal AuthRecord *MarkRRForSending(mDNS *const m)
2789 {
2790 AuthRecord *rr;
2791 AuthRecord *firstRR = mDNSNULL;
2792
2793 // Look for records that needs to be sent in the next two seconds (MERGE_DELAY_TIME is set to 1 second).
2794 // The logic is as follows.
2795 //
2796 // 1. Record 1 finishes getting zone data and its registration gets delayed by 1 second
2797 // 2. Record 2 comes 0.1 second later, finishes getting its zone data and its registration is also delayed by
2798 // 1 second which is now scheduled at 1.1 second
2799 //
2800 // By looking for 1 second into the future (m->timenow + MERGE_DELAY_TIME below does that) we have merged both
2801 // of the above records. Note that we can't look for records too much into the future as this will affect the
2802 // retry logic. The first retry is scheduled at 3 seconds. Hence, we should always look smaller than that.
2803 // Anything more than one second will affect the first retry to happen sooner.
2804 //
2805 // Note: As a side effect of looking one second into the future to facilitate merging, the retries happen
2806 // one second sooner.
2807 for (rr = m->ResourceRecords; rr; rr = rr->next)
2808 {
2809 if (!firstRR)
2810 {
2811 if (!IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME)) continue;
2812 firstRR = rr;
2813 }
2814 else if (!AreRecordsMergeable(m, firstRR, rr, m->timenow + MERGE_DELAY_TIME)) continue;
2815
2816 if (rr->SendRNow) LogMsg("MarkRRForSending: Resourcerecord %s already marked for sending", ARDisplayString(m, rr));
2817 rr->SendRNow = mDNSInterfaceMark;
2818 }
2819
2820 // We parsed through all records and found something to send. The services/records might
2821 // get registered at different times but we want the refreshes to be all merged and sent
2822 // as one update. Hence, we accelerate some of the records so that they will sync up in
2823 // the future. Look at the records excluding the ones that we have already sent in the
2824 // previous pass. If it half way through its scheduled refresh/retransmit, merge them
2825 // into this packet.
2826 //
2827 // Note that we only look at Registered/Refresh state to keep it simple. As we don't know
2828 // whether the current update will fit into one or more packets, merging a resource record
2829 // (which is in a different state) that has been scheduled for retransmit would trigger
2830 // sending more packets.
2831 if (firstRR)
2832 {
2833 int acc = 0;
2834 for (rr = m->ResourceRecords; rr; rr = rr->next)
2835 {
2836 if ((rr->state != regState_Registered && rr->state != regState_Refresh) ||
2837 (rr->SendRNow == mDNSInterfaceMark) ||
2838 (!AreRecordsMergeable(m, firstRR, rr, m->timenow + rr->ThisAPInterval/2)))
2839 continue;
2840 rr->SendRNow = mDNSInterfaceMark;
2841 acc++;
2842 }
2843 if (acc) LogInfo("MarkRRForSending: Accelereated %d records", acc);
2844 }
2845 return firstRR;
2846 }
2847
2848 mDNSlocal mDNSBool SendGroupUpdates(mDNS *const m)
2849 {
2850 mDNSOpaque16 msgid;
2851 mDNSs32 spaceleft = 0;
2852 mDNSs32 zoneSize, rrSize;
2853 mDNSu8 *oldnext; // for debugging
2854 mDNSu8 *next = m->omsg.data;
2855 AuthRecord *rr;
2856 AuthRecord *anchorRR = mDNSNULL;
2857 int nrecords = 0;
2858 AuthRecord *startRR = m->ResourceRecords;
2859 mDNSu8 *limit = mDNSNULL;
2860 DomainAuthInfo *AuthInfo = mDNSNULL;
2861 mDNSBool sentallRecords = mDNStrue;
2862
2863
2864 // We try to fit as many ResourceRecords as possible in AbsoluteNormal/MaxDNSMessageData. Before we start
2865 // putting in resource records, we need to reserve space for a few things. Every group/packet should
2866 // have the following.
2867 //
2868 // 1) Needs space for the Zone information (which needs to be at the beginning)
2869 // 2) Additional section MUST have space for lease option, HINFO and TSIG option (which needs to
2870 // to be at the end)
2871 //
2872 // In future we need to reserve space for the pre-requisites which also goes at the beginning.
2873 // To accomodate pre-requisites in the future, first we walk the whole list marking records
2874 // that can be sent in this packet and computing the space needed for these records.
2875 // For TXT and SRV records, we delete the previous record if any by sending the same
2876 // resource record with ANY RDATA and zero rdlen. Hence, we need to have space for both of them.
2877
2878 while (startRR)
2879 {
2880 AuthInfo = mDNSNULL;
2881 anchorRR = mDNSNULL;
2882 nrecords = 0;
2883 zoneSize = 0;
2884 for (rr = startRR; rr; rr = rr->next)
2885 {
2886 if (rr->SendRNow != mDNSInterfaceMark) continue;
2887
2888 rr->SendRNow = mDNSNULL;
2889
2890 if (!anchorRR)
2891 {
2892 AuthInfo = GetAuthInfoForName_internal(m, rr->zone);
2893
2894 // Though we allow single record registrations for UDP to be AbsoluteMaxDNSMessageData (See
2895 // SendRecordRegistration) to handle large TXT records, to avoid fragmentation we limit UDP
2896 // message to NormalMaxDNSMessageData
2897 if (AuthInfo && AuthInfo->AutoTunnel) spaceleft = AbsoluteMaxDNSMessageData;
2898 else spaceleft = NormalMaxDNSMessageData;
2899
2900 next = m->omsg.data;
2901 spaceleft -= RRAdditionalSize(m, AuthInfo);
2902 if (spaceleft <= 0)
2903 {
2904 LogMsg("SendGroupUpdates: ERROR!!: spaceleft is zero at the beginning");
2905 RRMergeFailure(m);
2906 return mDNSfalse;
2907 }
2908 limit = next + spaceleft;
2909
2910 // Build the initial part of message before putting in the other records
2911 msgid = mDNS_NewMessageID(m);
2912 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
2913
2914 // We need zone information at the beginning of the packet. Length: ZNAME, ZTYPE(2), ZCLASS(2)
2915 // zone has to be non-NULL for a record to be mergeable, hence it is safe to set/ examine zone
2916 //without checking for NULL.
2917 zoneSize = DomainNameLength(rr->zone) + 4;
2918 spaceleft -= zoneSize;
2919 if (spaceleft <= 0)
2920 {
2921 LogMsg("SendGroupUpdates: ERROR no space for zone information, disabling merge");
2922 RRMergeFailure(m);
2923 return mDNSfalse;
2924 }
2925 next = putZone(&m->omsg, next, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
2926 if (!next)
2927 {
2928 LogMsg("SendGroupUpdates: ERROR! Cannot put zone, disabling merge");
2929 RRMergeFailure(m);
2930 return mDNSfalse;
2931 }
2932 anchorRR = rr;
2933 }
2934
2935 rrSize = RREstimatedSize(rr, zoneSize - 4);
2936
2937 if ((spaceleft - rrSize) < 0)
2938 {
2939 // If we can't fit even a single message, skip it, it will be sent separately
2940 // in CheckRecordUpdates
2941 if (!nrecords)
2942 {
2943 LogInfo("SendGroupUpdates: Skipping message %s, spaceleft %d, rrSize %d", ARDisplayString(m, rr), spaceleft, rrSize);
2944 // Mark this as not sent so that the caller knows about it
2945 rr->SendRNow = mDNSInterfaceMark;
2946 // We need to remove the merge delay so that we can send it immediately
2947 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
2948 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
2949 rr = rr->next;
2950 anchorRR = mDNSNULL;
2951 sentallRecords = mDNSfalse;
2952 }
2953 else
2954 {
2955 LogInfo("SendGroupUpdates:1: Parsed %d records and sending using %s, spaceleft %d, rrSize %d", nrecords, ARDisplayString(m, anchorRR), spaceleft, rrSize);
2956 SendGroupRRMessage(m, anchorRR, next, AuthInfo);
2957 }
2958 break; // breaks out of for loop
2959 }
2960 spaceleft -= rrSize;
2961 oldnext = next;
2962 LogInfo("SendGroupUpdates: Building a message with resource record %s, next %p, state %d", ARDisplayString(m, rr), next, rr->state);
2963 if (!(next = BuildUpdateMessage(m, next, rr, limit)))
2964 {
2965 // We calculated the space and if we can't fit in, we had some bug in the calculation,
2966 // disable merge completely.
2967 LogMsg("SendGroupUpdates: ptr NULL while building message with %s", ARDisplayString(m, rr));
2968 RRMergeFailure(m);
2969 return mDNSfalse;
2970 }
2971 // If our estimate was higher, adjust to the actual size
2972 if ((next - oldnext) > rrSize)
2973 LogMsg("SendGroupUpdates: ERROR!! Record size estimation is wrong for %s, Estimate %d, Actual %d, state %d", ARDisplayString(m, rr), rrSize, next - oldnext, rr->state);
2974 else { spaceleft += rrSize; spaceleft -= (next - oldnext); }
2975
2976 nrecords++;
2977 // We could have sent an update earlier with this "rr" as anchorRR for which we never got a response.
2978 // To preserve ordering, we blow away the previous connection before sending this.
2979 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL;}
2980 rr->updateid = msgid;
2981
2982 // By setting the retry time interval here, we will not be looking at these records
2983 // again when we return to CheckGroupRecordUpdates.
2984 SetRecordRetry(m, rr, 0);
2985 }
2986 // Either we have parsed all the records or stopped at "rr" above due to lack of space
2987 startRR = rr;
2988 }
2989
2990 if (anchorRR)
2991 {
2992 LogInfo("SendGroupUpdates: Parsed %d records and sending using %s", nrecords, ARDisplayString(m, anchorRR));
2993 SendGroupRRMessage(m, anchorRR, next, AuthInfo);
2994 }
2995 return sentallRecords;
2996 }
2997
2998 // Merge the record registrations and send them as a group only if they
2999 // have same DomainAuthInfo and hence the same key to put the TSIG
3000 mDNSlocal void CheckGroupRecordUpdates(mDNS *const m)
3001 {
3002 AuthRecord *rr, *nextRR;
3003 // Keep sending as long as there is at least one record to be sent
3004 while (MarkRRForSending(m))
3005 {
3006 if (!SendGroupUpdates(m))
3007 {
3008 // if everything that was marked was not sent, send them out individually
3009 for (rr = m->ResourceRecords; rr; rr = nextRR)
3010 {
3011 // SendRecordRegistrtion might delete the rr from list, hence
3012 // dereference nextRR before calling the function
3013 nextRR = rr->next;
3014 if (rr->SendRNow == mDNSInterfaceMark)
3015 {
3016 // Any records marked for sending should be eligible to be sent out
3017 // immediately. Just being cautious
3018 if (rr->LastAPTime + rr->ThisAPInterval - m->timenow > 0)
3019 { LogMsg("CheckGroupRecordUpdates: ERROR!! Resourcerecord %s not ready", ARDisplayString(m, rr)); continue; }
3020 rr->SendRNow = mDNSNULL;
3021 SendRecordRegistration(m, rr);
3022 }
3023 }
3024 }
3025 }
3026
3027 debugf("CheckGroupRecordUpdates: No work, returning");
3028 return;
3029 }
3030
3031 mDNSlocal void hndlSRVChanged(mDNS *const m, AuthRecord *rr)
3032 {
3033 // Reevaluate the target always as NAT/Target could have changed while
3034 // we were registering/deeregistering
3035 domainname *dt;
3036 const domainname *target = GetServiceTarget(m, rr);
3037 if (!target || target->c[0] == 0)
3038 {
3039 // we don't have a target, if we just derregistered, then we don't have to do anything
3040 if (rr->state == regState_DeregPending)
3041 {
3042 LogInfo("hndlSRVChanged: SRVChanged, No Target, SRV Deregistered for %##s, state %d", rr->resrec.name->c,
3043 rr->state);
3044 rr->SRVChanged = mDNSfalse;
3045 dt = GetRRDomainNameTarget(&rr->resrec);
3046 if (dt) dt->c[0] = 0;
3047 rr->state = regState_NoTarget; // Wait for the next target change
3048 rr->resrec.rdlength = rr->resrec.rdestimate = 0;
3049 return;
3050 }
3051
3052 // we don't have a target, if we just registered, we need to deregister
3053 if (rr->state == regState_Pending)
3054 {
3055 LogInfo("hndlSRVChanged: SRVChanged, No Target, Deregistering again %##s, state %d", rr->resrec.name->c, rr->state);
3056 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3057 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3058 rr->state = regState_DeregPending;
3059 return;
3060 }
3061 LogInfo("hndlSRVChanged: Not in DeregPending or RegPending state %##s, state %d", rr->resrec.name->c, rr->state);
3062 }
3063 else
3064 {
3065 // If we were in registered state and SRV changed to NULL, we deregister and come back here
3066 // if we have a target, we need to register again.
3067 //
3068 // if we just registered check to see if it is same. If it is different just re-register the
3069 // SRV and its assoicated records
3070 //
3071 // UpdateOneSRVRecord takes care of re-registering all service records
3072 if ((rr->state == regState_DeregPending) ||
3073 (rr->state == regState_Pending && !SameDomainName(target, &rr->resrec.rdata->u.srv.target)))
3074 {
3075 dt = GetRRDomainNameTarget(&rr->resrec);
3076 if (dt) dt->c[0] = 0;
3077 rr->state = regState_NoTarget; // NoTarget will allow us to pick up new target OR nat traversal state
3078 rr->resrec.rdlength = rr->resrec.rdestimate = 0;
3079 LogInfo("hndlSRVChanged: SRVChanged, Valid Target %##s, Registering all records for %##s, state %d",
3080 target->c, rr->resrec.name->c, rr->state);
3081 rr->SRVChanged = mDNSfalse;
3082 UpdateOneSRVRecord(m, rr);
3083 return;
3084 }
3085 // Target did not change while this record was registering. Hence, we go to
3086 // Registered state - the state we started from.
3087 if (rr->state == regState_Pending) rr->state = regState_Registered;
3088 }
3089
3090 rr->SRVChanged = mDNSfalse;
3091 }
3092
3093 // Called with lock held
3094 mDNSlocal void hndlRecordUpdateReply(mDNS *m, AuthRecord *rr, mStatus err, mDNSu32 random)
3095 {
3096 mDNSBool InvokeCallback = mDNStrue;
3097 mDNSIPPort UpdatePort = zeroIPPort;
3098
3099 if (m->mDNS_busy != m->mDNS_reentrancy+1)
3100 LogMsg("hndlRecordUpdateReply: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
3101
3102 LogInfo("hndlRecordUpdateReply: err %d ID %d state %d %s(%p)", err, mDNSVal16(rr->updateid), rr->state, ARDisplayString(m, rr), rr);
3103
3104 rr->updateError = err;
3105 #if APPLE_OSX_mDNSResponder
3106 if (err == mStatus_BadSig) UpdateAutoTunnelDomainStatuses(m);
3107 #endif
3108
3109 SetRecordRetry(m, rr, random);
3110
3111 rr->updateid = zeroID; // Make sure that this is not considered as part of a group anymore
3112 // Later when need to send an update, we will get the zone data again. Thus we avoid
3113 // using stale information.
3114 //
3115 // Note: By clearing out the zone info here, it also helps better merging of records
3116 // in some cases. For example, when we get out regState_NoTarget state e.g., move out
3117 // of Double NAT, we want all the records to be in one update. Some BTMM records like
3118 // _autotunnel6 and host records are registered/deregistered when NAT state changes.
3119 // As they are re-registered the zone information is cleared out. To merge with other
3120 // records that might be possibly going out, clearing out the information here helps
3121 // as all of them try to get the zone data.
3122 if (rr->nta)
3123 {
3124 // We always expect the question to be stopped when we get a valid response from the server.
3125 // If the zone info tries to change during this time, updateid would be different and hence
3126 // this response should not have been accepted.
3127 if (rr->nta->question.ThisQInterval != -1)
3128 LogMsg("hndlRecordUpdateReply: ResourceRecord %s, zone info question %##s (%s) interval %d not -1",
3129 ARDisplayString(m, rr), rr->nta->question.qname.c, DNSTypeName(rr->nta->question.qtype), rr->nta->question.ThisQInterval);
3130 UpdatePort = rr->nta->Port;
3131 CancelGetZoneData(m, rr->nta);
3132 rr->nta = mDNSNULL;
3133 }
3134
3135 // If we are deregistering the record, then complete the deregistration. Ignore any NAT/SRV change
3136 // that could have happened during that time.
3137 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->state == regState_DeregPending)
3138 {
3139 debugf("hndlRecordUpdateReply: Received reply for deregister record %##s type %d", rr->resrec.name->c, rr->resrec.rrtype);
3140 if (err) LogMsg("ERROR: Deregistration of record %##s type %d failed with error %d",
3141 rr->resrec.name->c, rr->resrec.rrtype, err);
3142 rr->state = regState_Unregistered;
3143 CompleteDeregistration(m, rr);
3144 return;
3145 }
3146
3147 // We are returning early without updating the state. When we come back from sleep we will re-register after
3148 // re-initializing all the state as though it is a first registration. If the record can't be registered e.g.,
3149 // no target, it will be deregistered. Hence, the updating to the right state should not matter when going
3150 // to sleep.
3151 if (m->SleepState)
3152 {
3153 // Need to set it to NoTarget state so that RecordReadyForSleep knows that
3154 // we are done
3155 if (rr->resrec.rrtype == kDNSType_SRV && rr->state == regState_DeregPending)
3156 rr->state = regState_NoTarget;
3157 return;
3158 }
3159
3160 if (rr->state == regState_UpdatePending)
3161 {
3162 if (err) LogMsg("Update record failed for %##s (err %d)", rr->resrec.name->c, err);
3163 rr->state = regState_Registered;
3164 // deallocate old RData
3165 if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->OrigRData, rr->OrigRDLen);
3166 SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
3167 rr->OrigRData = mDNSNULL;
3168 rr->InFlightRData = mDNSNULL;
3169 }
3170
3171 if (rr->SRVChanged)
3172 {
3173 if (rr->resrec.rrtype == kDNSType_SRV)
3174 hndlSRVChanged(m, rr);
3175 else
3176 {
3177 LogInfo("hndlRecordUpdateReply: Deregistered %##s (%s), state %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->state);
3178 rr->SRVChanged = mDNSfalse;
3179 if (rr->state != regState_DeregPending) LogMsg("hndlRecordUpdateReply: ResourceRecord %s not in DeregPending state %d", ARDisplayString(m, rr), rr->state);
3180 rr->state = regState_NoTarget; // Wait for the next target change
3181 }
3182 return;
3183 }
3184
3185 if (rr->state == regState_Pending || rr->state == regState_Refresh)
3186 {
3187 if (!err)
3188 {
3189 if (rr->state == regState_Refresh) InvokeCallback = mDNSfalse;
3190 rr->state = regState_Registered;
3191 }
3192 else
3193 {
3194 // Retry without lease only for non-Private domains
3195 LogMsg("hndlRecordUpdateReply: Registration of record %##s type %d failed with error %d", rr->resrec.name->c, rr->resrec.rrtype, err);
3196 if (!rr->Private && rr->uselease && err == mStatus_UnknownErr && mDNSSameIPPort(UpdatePort, UnicastDNSPort))
3197 {
3198 LogMsg("hndlRecordUpdateReply: Will retry update of record %##s without lease option", rr->resrec.name->c);
3199 rr->uselease = mDNSfalse;
3200 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3201 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3202 return;
3203 }
3204 // Communicate the error to the application in the callback below
3205 }
3206 }
3207
3208 if (rr->QueuedRData && rr->state == regState_Registered)
3209 {
3210 rr->state = regState_UpdatePending;
3211 rr->InFlightRData = rr->QueuedRData;
3212 rr->InFlightRDLen = rr->QueuedRDLen;
3213 rr->OrigRData = rr->resrec.rdata;
3214 rr->OrigRDLen = rr->resrec.rdlength;
3215 rr->QueuedRData = mDNSNULL;
3216 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3217 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3218 return;
3219 }
3220
3221 // Don't invoke the callback on error as this may not be useful to the client.
3222 // The client may potentially delete the resource record on error which we normally
3223 // delete during deregistration
3224 if (!err && InvokeCallback && rr->RecordCallback)
3225 {
3226 LogInfo("hndlRecordUpdateReply: Calling record callback on %##s", rr->resrec.name->c);
3227 mDNS_DropLockBeforeCallback();
3228 rr->RecordCallback(m, rr, err);
3229 mDNS_ReclaimLockAfterCallback();
3230 }
3231 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
3232 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
3233 }
3234
3235 mDNSexport void uDNS_ReceiveNATPMPPacket(mDNS *m, const mDNSInterfaceID InterfaceID, mDNSu8 *pkt, mDNSu16 len)
3236 {
3237 NATTraversalInfo *ptr;
3238 NATAddrReply *AddrReply = (NATAddrReply *)pkt;
3239 NATPortMapReply *PortMapReply = (NATPortMapReply *)pkt;
3240 mDNSu32 nat_elapsed, our_elapsed;
3241
3242 // Minimum packet is vers (1) opcode (1) err (2) upseconds (4) = 8 bytes
3243 if (!AddrReply->err && len < 8) { LogMsg("NAT Traversal message too short (%d bytes)", len); return; }
3244 if (AddrReply->vers != NATMAP_VERS) { LogMsg("Received NAT Traversal response with version %d (expected %d)", pkt[0], NATMAP_VERS); return; }
3245
3246 // Read multi-byte numeric values (fields are identical in a NATPortMapReply)
3247 AddrReply->err = (mDNSu16) ( (mDNSu16)pkt[2] << 8 | pkt[3]);
3248 AddrReply->upseconds = (mDNSs32) ((mDNSs32)pkt[4] << 24 | (mDNSs32)pkt[5] << 16 | (mDNSs32)pkt[6] << 8 | pkt[7]);
3249
3250 nat_elapsed = AddrReply->upseconds - m->LastNATupseconds;
3251 our_elapsed = (m->timenow - m->LastNATReplyLocalTime) / mDNSPlatformOneSecond;
3252 debugf("uDNS_ReceiveNATPMPPacket %X upseconds %u nat_elapsed %d our_elapsed %d", AddrReply->opcode, AddrReply->upseconds, nat_elapsed, our_elapsed);
3253
3254 // We compute a conservative estimate of how much the NAT gateways's clock should have advanced
3255 // 1. We subtract 12.5% from our own measured elapsed time, to allow for NAT gateways that have an inacurate clock that runs slowly
3256 // 2. We add a two-second safety margin to allow for rounding errors: e.g.
3257 // -- if NAT gateway sends a packet at t=2.000 seconds, then one at t=7.999, that's approximately 6 real seconds,
3258 // but based on the values in the packet (2,7) the apparent difference according to the packet is only 5 seconds
3259 // -- if we're slow handling packets and/or we have coarse clock granularity,
3260 // we could receive the t=2 packet at our t=1.999 seconds, which we round down to 1
3261 // and the t=7.999 packet at our t=8.000 seconds, which we record as 8,
3262 // giving an apparent local time difference of 7 seconds
3263 // The two-second safety margin coves this possible calculation discrepancy
3264 if (AddrReply->upseconds < m->LastNATupseconds || nat_elapsed + 2 < our_elapsed - our_elapsed/8)
3265 { LogMsg("NAT gateway %#a rebooted", &m->Router); RecreateNATMappings(m); }
3266
3267 m->LastNATupseconds = AddrReply->upseconds;
3268 m->LastNATReplyLocalTime = m->timenow;
3269 #ifdef _LEGACY_NAT_TRAVERSAL_
3270 LNT_ClearState(m);
3271 #endif // _LEGACY_NAT_TRAVERSAL_
3272
3273 if (AddrReply->opcode == NATOp_AddrResponse)
3274 {
3275 #if APPLE_OSX_mDNSResponder
3276 static char msgbuf[16];
3277 mDNS_snprintf(msgbuf, sizeof(msgbuf), "%d", AddrReply->err);
3278 mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.AddressRequest", AddrReply->err ? "failure" : "success", msgbuf, "");
3279 #endif
3280 if (!AddrReply->err && len < sizeof(NATAddrReply)) { LogMsg("NAT Traversal AddrResponse message too short (%d bytes)", len); return; }
3281 natTraversalHandleAddressReply(m, AddrReply->err, AddrReply->ExtAddr);
3282 }
3283 else if (AddrReply->opcode == NATOp_MapUDPResponse || AddrReply->opcode == NATOp_MapTCPResponse)
3284 {
3285 mDNSu8 Protocol = AddrReply->opcode & 0x7F;
3286 #if APPLE_OSX_mDNSResponder
3287 static char msgbuf[16];
3288 mDNS_snprintf(msgbuf, sizeof(msgbuf), "%s - %d", AddrReply->opcode == NATOp_MapUDPResponse ? "UDP" : "TCP", PortMapReply->err);
3289 mDNSASLLog((uuid_t *)&m->asl_uuid, "natt.natpmp.PortMapRequest", PortMapReply->err ? "failure" : "success", msgbuf, "");
3290 #endif
3291 if (!PortMapReply->err)
3292 {
3293 if (len < sizeof(NATPortMapReply)) { LogMsg("NAT Traversal PortMapReply message too short (%d bytes)", len); return; }
3294 PortMapReply->NATRep_lease = (mDNSu32) ((mDNSu32)pkt[12] << 24 | (mDNSu32)pkt[13] << 16 | (mDNSu32)pkt[14] << 8 | pkt[15]);
3295 }
3296
3297 // Since some NAT-PMP server implementations don't return the requested internal port in
3298 // the reply, we can't associate this reply with a particular NATTraversalInfo structure.
3299 // We globally keep track of the most recent error code for mappings.
3300 m->LastNATMapResultCode = PortMapReply->err;
3301
3302 for (ptr = m->NATTraversals; ptr; ptr=ptr->next)
3303 if (ptr->Protocol == Protocol && mDNSSameIPPort(ptr->IntPort, PortMapReply->intport))
3304 natTraversalHandlePortMapReply(m, ptr, InterfaceID, PortMapReply->err, PortMapReply->extport, PortMapReply->NATRep_lease);
3305 }
3306 else { LogMsg("Received NAT Traversal response with version unknown opcode 0x%X", AddrReply->opcode); return; }
3307
3308 // Don't need an SSDP socket if we get a NAT-PMP packet
3309 if (m->SSDPSocket) { debugf("uDNS_ReceiveNATPMPPacket destroying SSDPSocket %p", &m->SSDPSocket); mDNSPlatformUDPClose(m->SSDPSocket); m->SSDPSocket = mDNSNULL; }
3310 }
3311
3312 // <rdar://problem/3925163> Shorten DNS-SD queries to avoid NAT bugs
3313 // <rdar://problem/4288449> Add check to avoid crashing NAT gateways that have buggy DNS relay code
3314 //
3315 // We know of bugs in home NAT gateways that cause them to crash if they receive certain DNS queries.
3316 // The DNS queries that make them crash are perfectly legal DNS queries, but even if they weren't,
3317 // the gateway shouldn't crash -- in today's world of viruses and network attacks, software has to
3318 // be written assuming that a malicious attacker could send them any packet, properly-formed or not.
3319 // Still, we don't want to be crashing people's home gateways, so we go out of our way to avoid
3320 // the queries that crash them.
3321 //
3322 // Some examples:
3323 //
3324 // 1. Any query where the name ends in ".in-addr.arpa." and the text before this is 32 or more bytes.
3325 // The query type does not need to be PTR -- the gateway will crash for any query type.
3326 // e.g. "ping long-name-crashes-the-buggy-router.in-addr.arpa" will crash one of these.
3327 //
3328 // 2. Any query that results in a large response with the TC bit set.
3329 //
3330 // 3. Any PTR query that doesn't begin with four decimal numbers.
3331 // These gateways appear to assume that the only possible PTR query is a reverse-mapping query
3332 // (e.g. "1.0.168.192.in-addr.arpa") and if they ever get a PTR query where the first four
3333 // labels are not all decimal numbers in the range 0-255, they handle that by crashing.
3334 // These gateways also ignore the remainder of the name following the four decimal numbers
3335 // -- whether or not it actually says in-addr.arpa, they just make up an answer anyway.
3336 //
3337 // The challenge therefore is to craft a query that will discern whether the DNS server
3338 // is one of these buggy ones, without crashing it. Furthermore we don't want our test
3339 // queries making it all the way to the root name servers, putting extra load on those
3340 // name servers and giving Apple a bad reputation. To this end we send this query:
3341 // dig -t ptr 1.0.0.127.dnsbugtest.1.0.0.127.in-addr.arpa.
3342 //
3343 // The text preceding the ".in-addr.arpa." is under 32 bytes, so it won't cause crash (1).
3344 // It will not yield a large response with the TC bit set, so it won't cause crash (2).
3345 // It starts with four decimal numbers, so it won't cause crash (3).
3346 // The name falls within the "1.0.0.127.in-addr.arpa." domain, the reverse-mapping name for the local
3347 // loopback address, and therefore the query will black-hole at the first properly-configured DNS server
3348 // it reaches, making it highly unlikely that this query will make it all the way to the root.
3349 //
3350 // Finally, the correct response to this query is NXDOMAIN or a similar error, but the
3351 // gateways that ignore the remainder of the name following the four decimal numbers
3352 // give themselves away by actually returning a result for this nonsense query.
3353
3354 mDNSlocal const domainname *DNSRelayTestQuestion = (const domainname*)
3355 "\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\xa" "dnsbugtest"
3356 "\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\x7" "in-addr" "\x4" "arpa";
3357
3358 // See comments above for DNSRelayTestQuestion
3359 // If this is the kind of query that has the risk of crashing buggy DNS servers, we do a test question first
3360 mDNSlocal mDNSBool NoTestQuery(DNSQuestion *q)
3361 {
3362 int i;
3363 mDNSu8 *p = q->qname.c;
3364 if (q->AuthInfo) return(mDNStrue); // Don't need a test query for private queries sent directly to authoritative server over TLS/TCP
3365 if (q->qtype != kDNSType_PTR) return(mDNStrue); // Don't need a test query for any non-PTR queries
3366 for (i=0; i<4; i++) // If qname does not begin with num.num.num.num, can't skip the test query
3367 {
3368 if (p[0] < 1 || p[0] > 3) return(mDNSfalse);
3369 if ( p[1] < '0' || p[1] > '9' ) return(mDNSfalse);
3370 if (p[0] >= 2 && (p[2] < '0' || p[2] > '9')) return(mDNSfalse);
3371 if (p[0] >= 3 && (p[3] < '0' || p[3] > '9')) return(mDNSfalse);
3372 p += 1 + p[0];
3373 }
3374 // If remainder of qname is ".in-addr.arpa.", this is a vanilla reverse-mapping query and
3375 // we can safely do it without needing a test query first, otherwise we need the test query.
3376 return(SameDomainName((domainname*)p, (const domainname*)"\x7" "in-addr" "\x4" "arpa"));
3377 }
3378
3379 // Returns mDNStrue if response was handled
3380 mDNSlocal mDNSBool uDNS_ReceiveTestQuestionResponse(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
3381 const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
3382 {
3383 const mDNSu8 *ptr = msg->data;
3384 DNSQuestion pktq;
3385 DNSServer *s;
3386 mDNSu32 result = 0;
3387
3388 // 1. Find out if this is an answer to one of our test questions
3389 if (msg->h.numQuestions != 1) return(mDNSfalse);
3390 ptr = getQuestion(msg, ptr, end, mDNSInterface_Any, &pktq);
3391 if (!ptr) return(mDNSfalse);
3392 if (pktq.qtype != kDNSType_PTR || pktq.qclass != kDNSClass_IN) return(mDNSfalse);
3393 if (!SameDomainName(&pktq.qname, DNSRelayTestQuestion)) return(mDNSfalse);
3394
3395 // 2. If the DNS relay gave us a positive response, then it's got buggy firmware
3396 // else, if the DNS relay gave us an error or no-answer response, it passed our test
3397 if ((msg->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr && msg->h.numAnswers > 0)
3398 result = DNSServer_Failed;
3399 else
3400 result = DNSServer_Passed;
3401
3402 // 3. Find occurrences of this server in our list, and mark them appropriately
3403 for (s = m->DNSServers; s; s = s->next)
3404 {
3405 mDNSBool matchaddr = (s->teststate != result && mDNSSameAddress(srcaddr, &s->addr) && mDNSSameIPPort(srcport, s->port));
3406 mDNSBool matchid = (s->teststate == DNSServer_Untested && mDNSSameOpaque16(msg->h.id, s->testid));
3407 if (matchaddr || matchid)
3408 {
3409 DNSQuestion *q;
3410 s->teststate = result;
3411 if (result == DNSServer_Passed)
3412 {
3413 LogInfo("DNS Server %#a:%d (%#a:%d) %d passed%s",
3414 &s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
3415 matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
3416 }
3417 else
3418 {
3419 LogMsg("NOTE: Wide-Area Service Discovery disabled to avoid crashing defective DNS relay %#a:%d (%#a:%d) %d%s",
3420 &s->addr, mDNSVal16(s->port), srcaddr, mDNSVal16(srcport), mDNSVal16(s->testid),
3421 matchaddr ? "" : " NOTE: Reply did not come from address to which query was sent");
3422 }
3423
3424 // If this server has just changed state from DNSServer_Untested to DNSServer_Passed, then retrigger any waiting questions.
3425 // We use the NoTestQuery() test so that we only retrigger questions that were actually blocked waiting for this test to complete.
3426 if (result == DNSServer_Passed) // Unblock any questions that were waiting for this result
3427 for (q = m->Questions; q; q=q->next)
3428 if (q->qDNSServer == s && !NoTestQuery(q))
3429 {
3430 q->ThisQInterval = INIT_UCAST_POLL_INTERVAL / QuestionIntervalStep;
3431 q->unansweredQueries = 0;
3432 q->LastQTime = m->timenow - q->ThisQInterval;
3433 m->NextScheduledQuery = m->timenow;
3434 }
3435 }
3436 }
3437
3438 return(mDNStrue); // Return mDNStrue to tell uDNS_ReceiveMsg it doesn't need to process this packet further
3439 }
3440
3441 // Called from mDNSCoreReceive with the lock held
3442 mDNSexport void uDNS_ReceiveMsg(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end, const mDNSAddr *const srcaddr, const mDNSIPPort srcport)
3443 {
3444 DNSQuestion *qptr;
3445 mStatus err = mStatus_NoError;
3446
3447 mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
3448 mDNSu8 UpdateR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
3449 mDNSu8 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
3450 mDNSu8 rcode = (mDNSu8)(msg->h.flags.b[1] & kDNSFlag1_RC_Mask);
3451
3452 (void)srcport; // Unused
3453
3454 debugf("uDNS_ReceiveMsg from %#-15a with "
3455 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
3456 srcaddr,
3457 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
3458 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
3459 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
3460 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? "" : "s", end - msg->data);
3461
3462 if (QR_OP == StdR)
3463 {
3464 //if (srcaddr && recvLLQResponse(m, msg, end, srcaddr, srcport)) return;
3465 if (uDNS_ReceiveTestQuestionResponse(m, msg, end, srcaddr, srcport)) return;
3466 for (qptr = m->Questions; qptr; qptr = qptr->next)
3467 if (msg->h.flags.b[0] & kDNSFlag0_TC && mDNSSameOpaque16(qptr->TargetQID, msg->h.id) && m->timenow - qptr->LastQTime < RESPONSE_WINDOW)
3468 {
3469 if (!srcaddr) LogMsg("uDNS_ReceiveMsg: TCP DNS response had TC bit set: ignoring");
3470 else
3471 {
3472 // Don't reuse TCP connections. We might have failed over to a different DNS server
3473 // while the first TCP connection is in progress. We need a new TCP connection to the
3474 // new DNS server. So, always try to establish a new connection.
3475 if (qptr->tcp) { DisposeTCPConn(qptr->tcp); qptr->tcp = mDNSNULL; }
3476 qptr->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_Zero, srcaddr, srcport, mDNSNULL, qptr, mDNSNULL);
3477 }
3478 }
3479 }
3480
3481 if (QR_OP == UpdateR)
3482 {
3483 mDNSu32 lease = GetPktLease(m, msg, end);
3484 mDNSs32 expire = m->timenow + (mDNSs32)lease * mDNSPlatformOneSecond;
3485 mDNSu32 random = mDNSRandom((mDNSs32)lease * mDNSPlatformOneSecond/10);
3486
3487 //rcode = kDNSFlag1_RC_ServFail; // Simulate server failure (rcode 2)
3488
3489 // Walk through all the records that matches the messageID. There could be multiple
3490 // records if we had sent them in a group
3491 if (m->CurrentRecord)
3492 LogMsg("uDNS_ReceiveMsg ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3493 m->CurrentRecord = m->ResourceRecords;
3494 while (m->CurrentRecord)
3495 {
3496 AuthRecord *rptr = m->CurrentRecord;
3497 m->CurrentRecord = m->CurrentRecord->next;
3498 if (AuthRecord_uDNS(rptr) && mDNSSameOpaque16(rptr->updateid, msg->h.id))
3499 {
3500 err = checkUpdateResult(m, rptr->resrec.name, rcode, msg, end);
3501 if (!err && rptr->uselease && lease)
3502 if (rptr->expire - expire >= 0 || rptr->state != regState_UpdatePending)
3503 {
3504 rptr->expire = expire;
3505 rptr->refreshCount = 0;
3506 }
3507 // We pass the random value to make sure that if we update multiple
3508 // records, they all get the same random value
3509 hndlRecordUpdateReply(m, rptr, err, random);
3510 }
3511 }
3512 }
3513 debugf("Received unexpected response: ID %d matches no active records", mDNSVal16(msg->h.id));
3514 }
3515
3516 // ***************************************************************************
3517 #if COMPILER_LIKES_PRAGMA_MARK
3518 #pragma mark - Query Routines
3519 #endif
3520
3521 mDNSexport void sendLLQRefresh(mDNS *m, DNSQuestion *q)
3522 {
3523 mDNSu8 *end;
3524 LLQOptData llq;
3525 mDNSu8 *limit = m->omsg.data + AbsoluteMaxDNSMessageData;
3526
3527 if (q->ReqLease)
3528 if ((q->state == LLQ_Established && q->ntries >= kLLQ_MAX_TRIES) || q->expire - m->timenow < 0)
3529 {
3530 LogMsg("Unable to refresh LLQ %##s (%s) - will retry in %d seconds", q->qname.c, DNSTypeName(q->qtype), LLQ_POLL_INTERVAL / mDNSPlatformOneSecond);
3531 StartLLQPolling(m,q);
3532 return;
3533 }
3534
3535 llq.vers = kLLQ_Vers;
3536 llq.llqOp = kLLQOp_Refresh;
3537 llq.err = q->tcp ? GetLLQEventPort(m, &q->servAddr) : LLQErr_NoError; // If using TCP tell server what UDP port to send notifications to
3538 llq.id = q->id;
3539 llq.llqlease = q->ReqLease;
3540
3541 InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
3542 end = putLLQ(&m->omsg, m->omsg.data, q, &llq);
3543 if (!end) { LogMsg("sendLLQRefresh: putLLQ failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3544
3545 // Note that we (conditionally) add HINFO and TSIG here, since the question might be going away,
3546 // so we may not be able to reference it (most importantly it's AuthInfo) when we actually send the message
3547 end = putHINFO(m, &m->omsg, end, q->AuthInfo, limit);
3548 if (!end) { LogMsg("sendLLQRefresh: putHINFO failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3549
3550 if (PrivateQuery(q))
3551 {
3552 DNSDigest_SignMessageHostByteOrder(&m->omsg, &end, q->AuthInfo);
3553 if (!end) { LogMsg("sendLLQRefresh: DNSDigest_SignMessage failed %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3554 }
3555
3556 if (PrivateQuery(q) && !q->tcp)
3557 {
3558 LogInfo("sendLLQRefresh setting up new TLS session %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3559 if (!q->nta) { LogMsg("sendLLQRefresh:ERROR!! q->nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3560 q->tcp = MakeTCPConn(m, &m->omsg, end, kTCPSocketFlags_UseTLS, &q->servAddr, q->servPort, &q->nta->Host, q, mDNSNULL);
3561 }
3562 else
3563 {
3564 mStatus err;
3565
3566 // if AuthInfo and AuthInfo->AutoTunnel is set, we use the TCP socket but don't need to pass the AuthInfo as
3567 // we already protected the message above.
3568 LogInfo("sendLLQRefresh: using existing %s session %##s (%s)", PrivateQuery(q) ? "TLS" : "UDP",
3569 q->qname.c, DNSTypeName(q->qtype));
3570
3571 err = mDNSSendDNSMessage(m, &m->omsg, end, mDNSInterface_Any, q->LocalSocket, &q->servAddr, q->servPort, q->tcp ? q->tcp->sock : mDNSNULL, mDNSNULL);
3572 if (err)
3573 {
3574 LogMsg("sendLLQRefresh: mDNSSendDNSMessage%s failed: %d", q->tcp ? " (TCP)" : "", err);
3575 if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
3576 }
3577 }
3578
3579 q->ntries++;
3580
3581 debugf("sendLLQRefresh ntries %d %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
3582
3583 q->LastQTime = m->timenow;
3584 SetNextQueryTime(m, q);
3585 }
3586
3587 mDNSexport void LLQGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
3588 {
3589 DNSQuestion *q = (DNSQuestion *)zoneInfo->ZoneDataContext;
3590
3591 mDNS_Lock(m);
3592
3593 // If we get here it means that the GetZoneData operation has completed.
3594 // We hold on to the zone data if it is AutoTunnel as we use the hostname
3595 // in zoneInfo during the TLS connection setup.
3596 q->servAddr = zeroAddr;
3597 q->servPort = zeroIPPort;
3598
3599 if (!err && zoneInfo && !mDNSIPPortIsZero(zoneInfo->Port) && !mDNSAddressIsZero(&zoneInfo->Addr) && zoneInfo->Host.c[0])
3600 {
3601 q->servAddr = zoneInfo->Addr;
3602 q->servPort = zoneInfo->Port;
3603 if (!PrivateQuery(q))
3604 {
3605 // We don't need the zone data as we use it only for the Host information which we
3606 // don't need if we are not going to use TLS connections.
3607 if (q->nta)
3608 {
3609 if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p) %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
3610 CancelGetZoneData(m, q->nta);
3611 q->nta = mDNSNULL;
3612 }
3613 }
3614 q->ntries = 0;
3615 debugf("LLQGotZoneData %#a:%d", &q->servAddr, mDNSVal16(q->servPort));
3616 startLLQHandshake(m, q);
3617 }
3618 else
3619 {
3620 if (q->nta)
3621 {
3622 if (q->nta != zoneInfo) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p) %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
3623 CancelGetZoneData(m, q->nta);
3624 q->nta = mDNSNULL;
3625 }
3626 StartLLQPolling(m,q);
3627 if (err == mStatus_NoSuchNameErr)
3628 {
3629 // this actually failed, so mark it by setting address to all ones
3630 q->servAddr.type = mDNSAddrType_IPv4;
3631 q->servAddr.ip.v4 = onesIPv4Addr;
3632 }
3633 }
3634
3635 mDNS_Unlock(m);
3636 }
3637
3638 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
3639 mDNSlocal void PrivateQueryGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneInfo)
3640 {
3641 DNSQuestion *q = (DNSQuestion *) zoneInfo->ZoneDataContext;
3642
3643 LogInfo("PrivateQueryGotZoneData %##s (%s) err %d Zone %##s Private %d", q->qname.c, DNSTypeName(q->qtype), err, zoneInfo->ZoneName.c, zoneInfo->ZonePrivate);
3644
3645 if (q->nta != zoneInfo) LogMsg("PrivateQueryGotZoneData:ERROR!!: nta (%p) != zoneInfo (%p) %##s (%s)", q->nta, zoneInfo, q->qname.c, DNSTypeName(q->qtype));
3646
3647 if (err || !zoneInfo || mDNSAddressIsZero(&zoneInfo->Addr) || mDNSIPPortIsZero(zoneInfo->Port) || !zoneInfo->Host.c[0])
3648 {
3649 LogInfo("PrivateQueryGotZoneData: ERROR!! %##s (%s) invoked with error code %d %p %#a:%d",
3650 q->qname.c, DNSTypeName(q->qtype), err, zoneInfo,
3651 zoneInfo ? &zoneInfo->Addr : mDNSNULL,
3652 zoneInfo ? mDNSVal16(zoneInfo->Port) : 0);
3653 CancelGetZoneData(m, q->nta);
3654 q->nta = mDNSNULL;
3655 return;
3656 }
3657
3658 if (!zoneInfo->ZonePrivate)
3659 {
3660 debugf("Private port lookup failed -- retrying without TLS -- %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3661 q->AuthInfo = mDNSNULL; // Clear AuthInfo so we try again non-private
3662 q->ThisQInterval = InitialQuestionInterval;
3663 q->LastQTime = m->timenow - q->ThisQInterval;
3664 CancelGetZoneData(m, q->nta);
3665 q->nta = mDNSNULL;
3666 mDNS_Lock(m);
3667 SetNextQueryTime(m, q);
3668 mDNS_Unlock(m);
3669 return;
3670 // Next call to uDNS_CheckCurrentQuestion() will do this as a non-private query
3671 }
3672
3673 if (!PrivateQuery(q))
3674 {
3675 LogMsg("PrivateQueryGotZoneData: ERROR!! Not a private query %##s (%s) AuthInfo %p", q->qname.c, DNSTypeName(q->qtype), q->AuthInfo);
3676 CancelGetZoneData(m, q->nta);
3677 q->nta = mDNSNULL;
3678 return;
3679 }
3680
3681 q->TargetQID = mDNS_NewMessageID(m);
3682 if (q->tcp) { DisposeTCPConn(q->tcp); q->tcp = mDNSNULL; }
3683 if (!q->nta) { LogMsg("PrivateQueryGotZoneData:ERROR!! nta is NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); return; }
3684 q->tcp = MakeTCPConn(m, mDNSNULL, mDNSNULL, kTCPSocketFlags_UseTLS, &zoneInfo->Addr, zoneInfo->Port, &q->nta->Host, q, mDNSNULL);
3685 if (q->nta) { CancelGetZoneData(m, q->nta); q->nta = mDNSNULL; }
3686 }
3687
3688 // ***************************************************************************
3689 #if COMPILER_LIKES_PRAGMA_MARK
3690 #pragma mark - Dynamic Updates
3691 #endif
3692
3693 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
3694 mDNSexport void RecordRegistrationGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneData)
3695 {
3696 AuthRecord *newRR = (AuthRecord*)zoneData->ZoneDataContext;
3697 AuthRecord *ptr;
3698 int c1, c2;
3699
3700 if (newRR->nta != zoneData)
3701 LogMsg("RecordRegistrationGotZoneData: nta (%p) != zoneData (%p) %##s (%s)", newRR->nta, zoneData, newRR->resrec.name->c, DNSTypeName(newRR->resrec.rrtype));
3702
3703 if (m->mDNS_busy != m->mDNS_reentrancy)
3704 LogMsg("RecordRegistrationGotZoneData: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
3705
3706 // make sure record is still in list (!!!)
3707 for (ptr = m->ResourceRecords; ptr; ptr = ptr->next) if (ptr == newRR) break;
3708 if (!ptr)
3709 {
3710 LogMsg("RecordRegistrationGotZoneData - RR no longer in list. Discarding.");
3711 CancelGetZoneData(m, newRR->nta);
3712 newRR->nta = mDNSNULL;
3713 return;
3714 }
3715
3716 // check error/result
3717 if (err)
3718 {
3719 if (err != mStatus_NoSuchNameErr) LogMsg("RecordRegistrationGotZoneData: error %d", err);
3720 CancelGetZoneData(m, newRR->nta);
3721 newRR->nta = mDNSNULL;
3722 return;
3723 }
3724
3725 if (!zoneData) { LogMsg("ERROR: RecordRegistrationGotZoneData invoked with NULL result and no error"); return; }
3726
3727 if (newRR->resrec.rrclass != zoneData->ZoneClass)
3728 {
3729 LogMsg("ERROR: New resource record's class (%d) does not match zone class (%d)", newRR->resrec.rrclass, zoneData->ZoneClass);
3730 CancelGetZoneData(m, newRR->nta);
3731 newRR->nta = mDNSNULL;
3732 return;
3733 }
3734
3735 // Don't try to do updates to the root name server.
3736 // We might be tempted also to block updates to any single-label name server (e.g. com, edu, net, etc.) but some
3737 // organizations use their own private pseudo-TLD, like ".home", etc, and we don't want to block that.
3738 if (zoneData->ZoneName.c[0] == 0)
3739 {
3740 LogInfo("RecordRegistrationGotZoneData: No name server found claiming responsibility for \"%##s\"!", newRR->resrec.name->c);
3741 CancelGetZoneData(m, newRR->nta);
3742 newRR->nta = mDNSNULL;
3743 return;
3744 }
3745
3746 // Store discovered zone data
3747 c1 = CountLabels(newRR->resrec.name);
3748 c2 = CountLabels(&zoneData->ZoneName);
3749 if (c2 > c1)
3750 {
3751 LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" is longer than \"%##s\"", zoneData->ZoneName.c, newRR->resrec.name->c);
3752 CancelGetZoneData(m, newRR->nta);
3753 newRR->nta = mDNSNULL;
3754 return;
3755 }
3756 newRR->zone = SkipLeadingLabels(newRR->resrec.name, c1-c2);
3757 if (!SameDomainName(newRR->zone, &zoneData->ZoneName))
3758 {
3759 LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" does not match \"%##s\" for \"%##s\"", newRR->zone->c, zoneData->ZoneName.c, newRR->resrec.name->c);
3760 CancelGetZoneData(m, newRR->nta);
3761 newRR->nta = mDNSNULL;
3762 return;
3763 }
3764
3765 if (mDNSIPPortIsZero(zoneData->Port) || mDNSAddressIsZero(&zoneData->Addr) || !zoneData->Host.c[0])
3766 {
3767 LogInfo("RecordRegistrationGotZoneData: No _dns-update._udp service found for \"%##s\"!", newRR->resrec.name->c);
3768 CancelGetZoneData(m, newRR->nta);
3769 newRR->nta = mDNSNULL;
3770 return;
3771 }
3772
3773 newRR->Private = zoneData->ZonePrivate;
3774 debugf("RecordRegistrationGotZoneData: Set zone information for %##s %##s to %#a:%d",
3775 newRR->resrec.name->c, zoneData->ZoneName.c, &zoneData->Addr, mDNSVal16(zoneData->Port));
3776
3777 // If we are deregistering, uDNS_DeregisterRecord will do that as it has the zone data now.
3778 if (newRR->state == regState_DeregPending)
3779 {
3780 mDNS_Lock(m);
3781 uDNS_DeregisterRecord(m, newRR);
3782 mDNS_Unlock(m);
3783 return;
3784 }
3785
3786 if (newRR->resrec.rrtype == kDNSType_SRV)
3787 {
3788 const domainname *target;
3789 // Reevaluate the target always as NAT/Target could have changed while
3790 // we were fetching zone data.
3791 mDNS_Lock(m);
3792 target = GetServiceTarget(m, newRR);
3793 mDNS_Unlock(m);
3794 if (!target || target->c[0] == 0)
3795 {
3796 domainname *t = GetRRDomainNameTarget(&newRR->resrec);
3797 LogInfo("RecordRegistrationGotZoneData - no target for %##s", newRR->resrec.name->c);
3798 if (t) t->c[0] = 0;
3799 newRR->resrec.rdlength = newRR->resrec.rdestimate = 0;
3800 newRR->state = regState_NoTarget;
3801 CancelGetZoneData(m, newRR->nta);
3802 newRR->nta = mDNSNULL;
3803 return;
3804 }
3805 }
3806 // If we have non-zero service port (always?)
3807 // and a private address, and update server is non-private
3808 // and this service is AutoTarget
3809 // then initiate a NAT mapping request. On completion it will do SendRecordRegistration() for us
3810 if (newRR->resrec.rrtype == kDNSType_SRV && !mDNSIPPortIsZero(newRR->resrec.rdata->u.srv.port) &&
3811 mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4) && newRR->nta && !mDNSAddrIsRFC1918(&newRR->nta->Addr) &&
3812 newRR->AutoTarget == Target_AutoHostAndNATMAP)
3813 {
3814 DomainAuthInfo *AuthInfo;
3815 AuthInfo = GetAuthInfoForName(m, newRR->resrec.name);
3816 if (AuthInfo && AuthInfo->AutoTunnel)
3817 {
3818 domainname *t = GetRRDomainNameTarget(&newRR->resrec);
3819 LogMsg("RecordRegistrationGotZoneData: ERROR!! AutoTunnel has Target_AutoHostAndNATMAP for %s", ARDisplayString(m, newRR));
3820 if (t) t->c[0] = 0;
3821 newRR->resrec.rdlength = newRR->resrec.rdestimate = 0;
3822 newRR->state = regState_NoTarget;
3823 CancelGetZoneData(m, newRR->nta);
3824 newRR->nta = mDNSNULL;
3825 return;
3826 }
3827 // During network transitions, we are called multiple times in different states. Setup NAT
3828 // state just once for this record.
3829 if (!newRR->NATinfo.clientContext)
3830 {
3831 LogInfo("RecordRegistrationGotZoneData StartRecordNatMap %s", ARDisplayString(m, newRR));
3832 newRR->state = regState_NATMap;
3833 StartRecordNatMap(m, newRR);
3834 return;
3835 }
3836 else LogInfo("RecordRegistrationGotZoneData: StartRecordNatMap for %s, state %d, context %p", ARDisplayString(m, newRR), newRR->state, newRR->NATinfo.clientContext);
3837 }
3838 mDNS_Lock(m);
3839 // We want IsRecordMergeable to check whether it is a record whose update can be
3840 // sent with others. We set the time before we call IsRecordMergeable, so that
3841 // it does not fail this record based on time. We are interested in other checks
3842 // at this time. If a previous update resulted in error, then don't reset the
3843 // interval. Preserve the back-off so that we don't keep retrying aggressively.
3844 if (newRR->updateError == mStatus_NoError)
3845 {
3846 newRR->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3847 newRR->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3848 }
3849 if (IsRecordMergeable(m, newRR, m->timenow + MERGE_DELAY_TIME))
3850 {
3851 // Delay the record registration by MERGE_DELAY_TIME so that we can merge them
3852 // into one update
3853 LogInfo("RecordRegistrationGotZoneData: Delayed registration for %s", ARDisplayString(m, newRR));
3854 newRR->LastAPTime += MERGE_DELAY_TIME;
3855 }
3856 mDNS_Unlock(m);
3857 }
3858
3859 mDNSlocal void SendRecordDeregistration(mDNS *m, AuthRecord *rr)
3860 {
3861 mDNSu8 *ptr = m->omsg.data;
3862 mDNSu8 *limit;
3863 DomainAuthInfo *AuthInfo;
3864
3865 if (m->mDNS_busy != m->mDNS_reentrancy+1)
3866 LogMsg("SendRecordDeRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
3867
3868 if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
3869 {
3870 LogMsg("SendRecordDeRegistration: No zone info for Resource record %s RecordType %d", ARDisplayString(m, rr), rr->resrec.RecordType);
3871 return;
3872 }
3873
3874 limit = ptr + AbsoluteMaxDNSMessageData;
3875 AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
3876 limit -= RRAdditionalSize(m, AuthInfo);
3877
3878 rr->updateid = mDNS_NewMessageID(m);
3879 InitializeDNSMessage(&m->omsg.h, rr->updateid, UpdateReqFlags);
3880
3881 // set zone
3882 ptr = putZone(&m->omsg, ptr, limit, rr->zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass));
3883 if (!ptr) goto exit;
3884
3885 ptr = BuildUpdateMessage(m, ptr, rr, limit);
3886
3887 if (!ptr) goto exit;
3888
3889 if (rr->Private)
3890 {
3891 LogInfo("SendRecordDeregistration TCP %p %s", rr->tcp, ARDisplayString(m, rr));
3892 if (rr->tcp) LogInfo("SendRecordDeregistration: Disposing existing TCP connection for %s", ARDisplayString(m, rr));
3893 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
3894 if (!rr->nta) { LogMsg("SendRecordDeregistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
3895 rr->tcp = MakeTCPConn(m, &m->omsg, ptr, kTCPSocketFlags_UseTLS, &rr->nta->Addr, rr->nta->Port, &rr->nta->Host, mDNSNULL, rr);
3896 }
3897 else
3898 {
3899 mStatus err;
3900 LogInfo("SendRecordDeregistration UDP %s", ARDisplayString(m, rr));
3901 if (!rr->nta) { LogMsg("SendRecordDeregistration:ERROR!! nta is NULL for %s", ARDisplayString(m, rr)); return; }
3902 err = mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &rr->nta->Addr, rr->nta->Port, mDNSNULL, GetAuthInfoForName_internal(m, rr->resrec.name));
3903 if (err) debugf("ERROR: SendRecordDeregistration - mDNSSendDNSMessage - %d", err);
3904 //if (rr->state == regState_DeregPending) CompleteDeregistration(m, rr); // Don't touch rr after this
3905 }
3906 SetRecordRetry(m, rr, 0);
3907 return;
3908 exit:
3909 LogMsg("SendRecordDeregistration: Error formatting message for %s", ARDisplayString(m, rr));
3910 }
3911
3912 mDNSexport mStatus uDNS_DeregisterRecord(mDNS *const m, AuthRecord *const rr)
3913 {
3914 DomainAuthInfo *info;
3915
3916 LogInfo("uDNS_DeregisterRecord: Resource Record %s, state %d", ARDisplayString(m, rr), rr->state);
3917
3918 switch (rr->state)
3919 {
3920 case regState_Refresh:
3921 case regState_Pending:
3922 case regState_UpdatePending:
3923 case regState_Registered: break;
3924 case regState_DeregPending: break;
3925
3926 case regState_NATError:
3927 case regState_NATMap:
3928 // A record could be in NoTarget to start with if the corresponding SRV record could not find a target.
3929 // It is also possible to reenter the NoTarget state when we move to a network with a NAT that has
3930 // no NAT-PMP/UPnP support. In that case before we entered NoTarget, we already deregistered with
3931 // the server.
3932 case regState_NoTarget:
3933 case regState_Unregistered:
3934 case regState_Zero:
3935 default:
3936 LogInfo("uDNS_DeregisterRecord: State %d for %##s type %s", rr->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
3937 // This function may be called during sleep when there are no sleep proxy servers
3938 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) CompleteDeregistration(m, rr);
3939 return mStatus_NoError;
3940 }
3941
3942 // If a current group registration is pending, we can't send this deregisration till that registration
3943 // has reached the server i.e., the ordering is important. Previously, if we did not send this
3944 // registration in a group, then the previous connection will be torn down as part of sending the
3945 // deregistration. If we send this in a group, we need to locate the resource record that was used
3946 // to send this registration and terminate that connection. This means all the updates on that might
3947 // be lost (assuming the response is not waiting for us at the socket) and the retry will send the
3948 // update again sometime in the near future.
3949 //
3950 // NOTE: SSL handshake failures normally free the TCP connection immediately. Hence, you may not
3951 // find the TCP below there. This case can happen only when tcp is trying to actively retransmit
3952 // the request or SSL negotiation taking time i.e resource record is actively trying to get the
3953 // message to the server. During that time a deregister has to happen.
3954
3955 if (!mDNSOpaque16IsZero(rr->updateid))
3956 {
3957 AuthRecord *anchorRR;
3958 mDNSBool found = mDNSfalse;
3959 for (anchorRR = m->ResourceRecords; anchorRR; anchorRR = anchorRR->next)
3960 {
3961 if (AuthRecord_uDNS(rr) && mDNSSameOpaque16(anchorRR->updateid, rr->updateid) && anchorRR->tcp)
3962 {
3963 LogInfo("uDNS_DeregisterRecord: Found Anchor RR %s terminated", ARDisplayString(m, anchorRR));
3964 if (found)
3965 LogMsg("uDNS_DeregisterRecord: ERROR: Another anchorRR %s found", ARDisplayString(m, anchorRR));
3966 DisposeTCPConn(anchorRR->tcp);
3967 anchorRR->tcp = mDNSNULL;
3968 found = mDNStrue;
3969 }
3970 }
3971 if (!found) LogInfo("uDNSDeregisterRecord: Cannot find the anchor Resource Record for %s, not an error", ARDisplayString(m, rr));
3972 }
3973
3974 // Retry logic for deregistration should be no different from sending registration the first time.
3975 // Currently ThisAPInterval most likely is set to the refresh interval
3976 rr->state = regState_DeregPending;
3977 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
3978 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
3979 info = GetAuthInfoForName_internal(m, rr->resrec.name);
3980 if (IsRecordMergeable(m, rr, m->timenow + MERGE_DELAY_TIME))
3981 {
3982 // Delay the record deregistration by MERGE_DELAY_TIME so that we can merge them
3983 // into one update. If the domain is being deleted, delay by 2 * MERGE_DELAY_TIME
3984 // so that we can merge all the AutoTunnel records and the service records in
3985 // one update (they get deregistered a little apart)
3986 if (info && info->deltime) rr->LastAPTime += (2 * MERGE_DELAY_TIME);
3987 else rr->LastAPTime += MERGE_DELAY_TIME;
3988 }
3989 // IsRecordMergeable could have returned false for several reasons e.g., DontMerge is set or
3990 // no zone information. Most likely it is the latter, CheckRecordUpdates will fetch the zone
3991 // data when it encounters this record.
3992
3993 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
3994 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
3995
3996 return mStatus_NoError;
3997 }
3998
3999 mDNSexport mStatus uDNS_UpdateRecord(mDNS *m, AuthRecord *rr)
4000 {
4001 LogInfo("uDNS_UpdateRecord: Resource Record %##s, state %d", rr->resrec.name->c, rr->state);
4002 switch(rr->state)
4003 {
4004 case regState_DeregPending:
4005 case regState_Unregistered:
4006 // not actively registered
4007 goto unreg_error;
4008
4009 case regState_NATMap:
4010 case regState_NoTarget:
4011 // change rdata directly since it hasn't been sent yet
4012 if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->resrec.rdata, rr->resrec.rdlength);
4013 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
4014 rr->NewRData = mDNSNULL;
4015 return mStatus_NoError;
4016
4017 case regState_Pending:
4018 case regState_Refresh:
4019 case regState_UpdatePending:
4020 // registration in-flight. queue rdata and return
4021 if (rr->QueuedRData && rr->UpdateCallback)
4022 // if unsent rdata is already queued, free it before we replace it
4023 rr->UpdateCallback(m, rr, rr->QueuedRData, rr->QueuedRDLen);
4024 rr->QueuedRData = rr->NewRData;
4025 rr->QueuedRDLen = rr->newrdlength;
4026 rr->NewRData = mDNSNULL;
4027 return mStatus_NoError;
4028
4029 case regState_Registered:
4030 rr->OrigRData = rr->resrec.rdata;
4031 rr->OrigRDLen = rr->resrec.rdlength;
4032 rr->InFlightRData = rr->NewRData;
4033 rr->InFlightRDLen = rr->newrdlength;
4034 rr->NewRData = mDNSNULL;
4035 rr->state = regState_UpdatePending;
4036 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
4037 rr->LastAPTime = m->timenow - INIT_RECORD_REG_INTERVAL;
4038 return mStatus_NoError;
4039
4040 case regState_NATError:
4041 LogMsg("ERROR: uDNS_UpdateRecord called for record %##s with bad state regState_NATError", rr->resrec.name->c);
4042 return mStatus_UnknownErr; // states for service records only
4043
4044 default: LogMsg("uDNS_UpdateRecord: Unknown state %d for %##s", rr->state, rr->resrec.name->c);
4045 }
4046
4047 unreg_error:
4048 LogMsg("uDNS_UpdateRecord: Requested update of record %##s type %d, in erroneous state %d",
4049 rr->resrec.name->c, rr->resrec.rrtype, rr->state);
4050 return mStatus_Invalid;
4051 }
4052
4053 // ***************************************************************************
4054 #if COMPILER_LIKES_PRAGMA_MARK
4055 #pragma mark - Periodic Execution Routines
4056 #endif
4057
4058 mDNSlocal const mDNSu8 *mDNS_WABLabels[] =
4059 {
4060 (const mDNSu8 *)"\001b",
4061 (const mDNSu8 *)"\002db",
4062 (const mDNSu8 *)"\002lb",
4063 (const mDNSu8 *)"\001r",
4064 (const mDNSu8 *)"\002dr",
4065 (const mDNSu8 *)"\002cf",
4066 (const mDNSu8 *)mDNSNULL,
4067 };
4068
4069 // Returns true if it is a WAB question
4070 mDNSlocal mDNSBool WABQuestion(const domainname *qname)
4071 {
4072 const mDNSu8 *sd = (const mDNSu8 *)"\007_dns-sd";
4073 const mDNSu8 *prot = (const mDNSu8 *)"\004_udp";
4074 const domainname *d = qname;
4075 const mDNSu8 *label;
4076 int i = 0;
4077
4078 // We need at least 3 labels (WAB prefix) + one more label to make
4079 // a meaningful WAB query
4080 if (CountLabels(qname) < 4) { debugf("WABQuestion: question %##s, not enough labels", qname->c); return mDNSfalse; }
4081
4082 label = (const mDNSu8 *)d;
4083 while (mDNS_WABLabels[i] != (const mDNSu8 *)mDNSNULL)
4084 {
4085 if (SameDomainLabel(mDNS_WABLabels[i], label)) {debugf("WABquestion: WAB question %##s, label1 match", qname->c); break;}
4086 i++;
4087 }
4088 if (mDNS_WABLabels[i] == (const mDNSu8 *)mDNSNULL)
4089 {
4090 debugf("WABquestion: Not a WAB question %##s, label1 mismatch", qname->c);
4091 return mDNSfalse;
4092 }
4093 // CountLabels already verified the number of labels
4094 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label
4095 label = (const mDNSu8 *)d;
4096 if (!SameDomainLabel(label, sd)){ debugf("WABquestion: Not a WAB question %##s, label2 mismatch", qname->c);return(mDNSfalse); }
4097 debugf("WABquestion: WAB question %##s, label2 match", qname->c);
4098
4099 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label
4100 label = (const mDNSu8 *)d;
4101 if (!SameDomainLabel(label, prot)){ debugf("WABquestion: Not a WAB question %##s, label3 mismatch", qname->c);return(mDNSfalse); }
4102 debugf("WABquestion: WAB question %##s, label3 match", qname->c);
4103
4104 LogInfo("WABquestion: Question %##s is a WAB question", qname->c);
4105
4106 return mDNStrue;
4107 }
4108
4109 // The question to be checked is not passed in as an explicit parameter;
4110 // instead it is implicit that the question to be checked is m->CurrentQuestion.
4111 mDNSexport void uDNS_CheckCurrentQuestion(mDNS *const m)
4112 {
4113 DNSQuestion *q = m->CurrentQuestion;
4114 if (m->timenow - NextQSendTime(q) < 0) return;
4115
4116 if (q->LongLived)
4117 {
4118 switch (q->state)
4119 {
4120 case LLQ_InitialRequest: startLLQHandshake(m, q); break;
4121 case LLQ_SecondaryRequest:
4122 // For PrivateQueries, we need to start the handshake again as we don't do the Challenge/Response step
4123 if (PrivateQuery(q))
4124 startLLQHandshake(m, q);
4125 else
4126 sendChallengeResponse(m, q, mDNSNULL);
4127 break;
4128 case LLQ_Established: sendLLQRefresh(m, q); break;
4129 case LLQ_Poll: break; // Do nothing (handled below)
4130 }
4131 }
4132
4133 // We repeat the check above (rather than just making this the "else" case) because startLLQHandshake can change q->state to LLQ_Poll
4134 if (!(q->LongLived && q->state != LLQ_Poll))
4135 {
4136 if (q->unansweredQueries >= MAX_UCAST_UNANSWERED_QUERIES)
4137 {
4138 DNSServer *orig = q->qDNSServer;
4139 if (orig)
4140 LogInfo("uDNS_CheckCurrentQuestion: Sent %d unanswered queries for %##s (%s) to %#a:%d (%##s)",
4141 q->unansweredQueries, q->qname.c, DNSTypeName(q->qtype), &orig->addr, mDNSVal16(orig->port), orig->domain.c);
4142
4143 PenalizeDNSServer(m, q);
4144 q->noServerResponse = 1;
4145 }
4146 // There are two cases here.
4147 //
4148 // 1. We have only one DNS server for this question. It is not responding even after we sent MAX_UCAST_UNANSWERED_QUERIES.
4149 // In that case, we need to keep retrying till we get a response. But we need to backoff as we retry. We set
4150 // noServerResponse in the block above and below we do not touch the question interval. When we come here, we
4151 // already waited for the response. We need to send another query right at this moment. We do that below by
4152 // reinitializing dns servers and reissuing the query.
4153 //
4154 // 2. We have more than one DNS server. If at least one server did not respond, we would have set noServerResponse
4155 // either now (the last server in the list) or before (non-last server in the list). In either case, if we have
4156 // reached the end of DNS server list, we need to try again from the beginning. Ideally we should try just the
4157 // servers that did not respond, but for simplicity we try all the servers. Once we reached the end of list, we
4158 // set triedAllServersOnce so that we don't try all the servers aggressively. See PenalizeDNSServer.
4159 if (!q->qDNSServer && q->noServerResponse)
4160 {
4161 DNSServer *new;
4162 DNSQuestion *qptr;
4163 q->triedAllServersOnce = 1;
4164 // Re-initialize all DNS servers for this question. If we have a DNSServer, DNSServerChangeForQuestion will
4165 // handle all the work including setting the new DNS server.
4166 SetValidDNSServers(m, q);
4167 new = GetServerForQuestion(m, q);
4168 if (new)
4169 {
4170 LogInfo("uDNS_checkCurrentQuestion: Retrying question %p %##s (%s) DNS Server %#a:%d ThisQInterval %d",
4171 q, q->qname.c, DNSTypeName(q->qtype), new ? &new->addr : mDNSNULL, mDNSVal16(new ? new->port : zeroIPPort), q->ThisQInterval);
4172 DNSServerChangeForQuestion(m, q, new);
4173 }
4174 for (qptr = q->next ; qptr; qptr = qptr->next)
4175 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
4176 }
4177 if (q->qDNSServer && q->qDNSServer->teststate != DNSServer_Disabled)
4178 {
4179 mDNSu8 *end = m->omsg.data;
4180 mStatus err = mStatus_NoError;
4181 mDNSBool private = mDNSfalse;
4182
4183 InitializeDNSMessage(&m->omsg.h, q->TargetQID, uQueryFlags);
4184
4185 if (q->qDNSServer->teststate != DNSServer_Untested || NoTestQuery(q))
4186 {
4187 end = putQuestion(&m->omsg, m->omsg.data, m->omsg.data + AbsoluteMaxDNSMessageData, &q->qname, q->qtype, q->qclass);
4188 private = PrivateQuery(q);
4189 }
4190 else if (m->timenow - q->qDNSServer->lasttest >= INIT_UCAST_POLL_INTERVAL) // Make sure at least three seconds has elapsed since last test query
4191 {
4192 LogInfo("Sending DNS test query to %#a:%d", &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port));
4193 q->ThisQInterval = INIT_UCAST_POLL_INTERVAL / QuestionIntervalStep;
4194 q->qDNSServer->lasttest = m->timenow;
4195 end = putQuestion(&m->omsg, m->omsg.data, m->omsg.data + AbsoluteMaxDNSMessageData, DNSRelayTestQuestion, kDNSType_PTR, kDNSClass_IN);
4196 q->qDNSServer->testid = m->omsg.h.id;
4197 }
4198
4199 if (end > m->omsg.data && (q->qDNSServer->teststate != DNSServer_Failed || NoTestQuery(q)))
4200 {
4201 //LogMsg("uDNS_CheckCurrentQuestion %p %d %p %##s (%s)", q, NextQSendTime(q) - m->timenow, private, q->qname.c, DNSTypeName(q->qtype));
4202 if (private)
4203 {
4204 if (q->nta) CancelGetZoneData(m, q->nta);
4205 q->nta = StartGetZoneData(m, &q->qname, q->LongLived ? ZoneServiceLLQ : ZoneServiceQuery, PrivateQueryGotZoneData, q);
4206 if (q->state == LLQ_Poll) q->ThisQInterval = (LLQ_POLL_INTERVAL + mDNSRandom(LLQ_POLL_INTERVAL/10)) / QuestionIntervalStep;
4207 }
4208 else
4209 {
4210 debugf("uDNS_CheckCurrentQuestion sending %p %##s (%s) %#a:%d UnansweredQueries %d",
4211 q, q->qname.c, DNSTypeName(q->qtype),
4212 q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL, mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort), q->unansweredQueries);
4213 if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
4214 if (!q->LocalSocket) err = mStatus_NoMemoryErr; // If failed to make socket (should be very rare), we'll try again next time
4215 else err = mDNSSendDNSMessage(m, &m->omsg, end, q->qDNSServer->interface, q->LocalSocket, &q->qDNSServer->addr, q->qDNSServer->port, mDNSNULL, mDNSNULL);
4216 }
4217 }
4218
4219 if (err) debugf("ERROR: uDNS_idle - mDNSSendDNSMessage - %d", err); // surpress syslog messages if we have no network
4220 else
4221 {
4222 q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep; // Only increase interval if send succeeded
4223 q->unansweredQueries++;
4224 if (q->ThisQInterval > MAX_UCAST_POLL_INTERVAL)
4225 q->ThisQInterval = MAX_UCAST_POLL_INTERVAL;
4226 if (private && q->state != LLQ_Poll)
4227 {
4228 // We don't want to retransmit too soon. Hence, we always schedule our first
4229 // retransmisson at 3 seconds rather than one second
4230 if (q->ThisQInterval < (3 * mDNSPlatformOneSecond))
4231 q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;
4232 if (q->ThisQInterval > LLQ_POLL_INTERVAL)
4233 q->ThisQInterval = LLQ_POLL_INTERVAL;
4234 LogInfo("uDNS_CheckCurrentQuestion: private non polling question for %##s (%s) will be retried in %d ms", q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval);
4235 }
4236 debugf("Increased ThisQInterval to %d for %##s (%s)", q->ThisQInterval, q->qname.c, DNSTypeName(q->qtype));
4237 }
4238 q->LastQTime = m->timenow;
4239 SetNextQueryTime(m, q);
4240 }
4241 else
4242 {
4243 // If we have no server for this query, or the only server is a disabled one, then we deliver
4244 // a transient failure indication to the client. This is important for things like iPhone
4245 // where we want to return timely feedback to the user when no network is available.
4246 // After calling MakeNegativeCacheRecord() we store the resulting record in the
4247 // cache so that it will be visible to other clients asking the same question.
4248 // (When we have a group of identical questions, only the active representative of the group gets
4249 // passed to uDNS_CheckCurrentQuestion -- we only want one set of query packets hitting the wire --
4250 // but we want *all* of the questions to get answer callbacks.)
4251
4252 CacheRecord *rr;
4253 const mDNSu32 slot = HashSlot(&q->qname);
4254 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
4255 if (cg)
4256 for (rr = cg->members; rr; rr=rr->next)
4257 if (SameNameRecordAnswersQuestion(&rr->resrec, q)) mDNS_PurgeCacheResourceRecord(m, rr);
4258
4259 if (!q->qDNSServer)
4260 {
4261 if (!mDNSOpaque64IsZero(&q->validDNSServers))
4262 LogMsg("uDNS_CheckCurrentQuestion: ERROR!!: valid DNSServer bits not zero 0x%x, 0x%x for question %##s (%s)",
4263 q->validDNSServers.l[1], q->validDNSServers.l[0], q->qname.c, DNSTypeName(q->qtype));
4264 // If we reached the end of list while picking DNS servers, then we don't want to deactivate the
4265 // question. Try after 60 seconds. We find this by looking for valid DNSServers for this question,
4266 // if we find any, then we must have tried them before we came here. This avoids maintaining
4267 // another state variable to see if we had valid DNS servers for this question.
4268 SetValidDNSServers(m, q);
4269 if (mDNSOpaque64IsZero(&q->validDNSServers))
4270 {
4271 LogInfo("uDNS_CheckCurrentQuestion: no DNS server for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4272 q->ThisQInterval = 0;
4273 }
4274 else
4275 {
4276 DNSQuestion *qptr;
4277 // Pretend that we sent this question. As this is an ActiveQuestion, the NextScheduledQuery should
4278 // be set properly. Also, we need to properly backoff in cases where we don't set the question to
4279 // MaxQuestionInterval when we answer the question e.g., LongLived, we need to keep backing off
4280 q->ThisQInterval = q->ThisQInterval * QuestionIntervalStep;
4281 q->LastQTime = m->timenow;
4282 SetNextQueryTime(m, q);
4283 // Pick a new DNS server now. Otherwise, when the cache is 80% of its expiry, we will try
4284 // to send a query and come back to the same place here and log the above message.
4285 q->qDNSServer = GetServerForQuestion(m, q);
4286 for (qptr = q->next ; qptr; qptr = qptr->next)
4287 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
4288 LogInfo("uDNS_checkCurrentQuestion: Tried all DNS servers, retry question %p SuppressUnusable %d %##s (%s) with DNS Server %#a:%d after 60 seconds, ThisQInterval %d",
4289 q, q->SuppressUnusable, q->qname.c, DNSTypeName(q->qtype),
4290 q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL, mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort), q->ThisQInterval);
4291 }
4292 }
4293 else
4294 {
4295 q->ThisQInterval = 0;
4296 LogMsg("uDNS_CheckCurrentQuestion DNS server %#a:%d for %##s is disabled", &q->qDNSServer->addr, mDNSVal16(q->qDNSServer->port), q->qname.c);
4297 }
4298
4299 // For some of the WAB queries that we generate form within the mDNSResponder, most of the home routers
4300 // don't understand and return ServFail/NXDomain. In those cases, we don't want to try too often. We try
4301 // every fifteen minutes in that case
4302 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, (WABQuestion(&q->qname) ? 60 * 15 : 60), mDNSInterface_Any, q->qDNSServer);
4303 q->unansweredQueries = 0;
4304 // We're already using the m->CurrentQuestion pointer, so CacheRecordAdd can't use it to walk the question list.
4305 // To solve this problem we set rr->DelayDelivery to a nonzero value (which happens to be 'now') so that we
4306 // momentarily defer generating answer callbacks until mDNS_Execute time.
4307 CreateNewCacheEntry(m, slot, cg, NonZeroTime(m->timenow));
4308 ScheduleNextCacheCheckTime(m, slot, NonZeroTime(m->timenow));
4309 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
4310 // MUST NOT touch m->CurrentQuestion (or q) after this -- client callback could have deleted it
4311 }
4312 }
4313 }
4314
4315 mDNSexport void CheckNATMappings(mDNS *m)
4316 {
4317 mStatus err = mStatus_NoError;
4318 mDNSBool rfc1918 = mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4);
4319 mDNSBool HaveRoutable = !rfc1918 && !mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4);
4320 m->NextScheduledNATOp = m->timenow + 0x3FFFFFFF;
4321
4322 if (HaveRoutable) m->ExternalAddress = m->AdvertisedV4.ip.v4;
4323
4324 if (m->NATTraversals && rfc1918) // Do we need to open NAT-PMP socket to receive multicast announcements from router?
4325 {
4326 if (m->NATMcastRecvskt == mDNSNULL) // If we are behind a NAT and the socket hasn't been opened yet, open it
4327 {
4328 // we need to log a message if we can't get our socket, but only the first time (after success)
4329 static mDNSBool needLog = mDNStrue;
4330 m->NATMcastRecvskt = mDNSPlatformUDPSocket(m, NATPMPAnnouncementPort);
4331 if (!m->NATMcastRecvskt)
4332 {
4333 if (needLog)
4334 {
4335 LogMsg("CheckNATMappings: Failed to allocate port 5350 UDP multicast socket for NAT-PMP announcements");
4336 needLog = mDNSfalse;
4337 }
4338 }
4339 else
4340 needLog = mDNStrue;
4341 }
4342 }
4343 else // else, we don't want to listen for announcements, so close them if they're open
4344 {
4345 if (m->NATMcastRecvskt) { mDNSPlatformUDPClose(m->NATMcastRecvskt); m->NATMcastRecvskt = mDNSNULL; }
4346 if (m->SSDPSocket) { debugf("CheckNATMappings destroying SSDPSocket %p", &m->SSDPSocket); mDNSPlatformUDPClose(m->SSDPSocket); m->SSDPSocket = mDNSNULL; }
4347 }
4348
4349 if (!m->NATTraversals)
4350 m->retryGetAddr = m->timenow + 0x78000000;
4351 else
4352 {
4353 if (m->timenow - m->retryGetAddr >= 0)
4354 {
4355 err = uDNS_SendNATMsg(m, mDNSNULL); // Will also do UPnP discovery for us, if necessary
4356 if (!err)
4357 {
4358 if (m->retryIntervalGetAddr < NATMAP_INIT_RETRY) m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
4359 else if (m->retryIntervalGetAddr < NATMAP_MAX_RETRY_INTERVAL / 2) m->retryIntervalGetAddr *= 2;
4360 else m->retryIntervalGetAddr = NATMAP_MAX_RETRY_INTERVAL;
4361 }
4362 LogInfo("CheckNATMappings retryGetAddr sent address request err %d interval %d", err, m->retryIntervalGetAddr);
4363
4364 // Always update m->retryGetAddr, even if we fail to send the packet. Otherwise in cases where we can't send the packet
4365 // (like when we have no active interfaces) we'll spin in an infinite loop repeatedly failing to send the packet
4366 m->retryGetAddr = m->timenow + m->retryIntervalGetAddr;
4367 }
4368 // Even when we didn't send the GetAddr packet, still need to make sure NextScheduledNATOp is set correctly
4369 if (m->NextScheduledNATOp - m->retryGetAddr > 0)
4370 m->NextScheduledNATOp = m->retryGetAddr;
4371 }
4372
4373 if (m->CurrentNATTraversal) LogMsg("WARNING m->CurrentNATTraversal already in use");
4374 m->CurrentNATTraversal = m->NATTraversals;
4375
4376 while (m->CurrentNATTraversal)
4377 {
4378 NATTraversalInfo *cur = m->CurrentNATTraversal;
4379 m->CurrentNATTraversal = m->CurrentNATTraversal->next;
4380
4381 if (HaveRoutable) // If not RFC 1918 address, our own address and port are effectively our external address and port
4382 {
4383 cur->ExpiryTime = 0;
4384 cur->NewResult = mStatus_NoError;
4385 }
4386 else if (cur->Protocol) // Check if it's time to send port mapping packets
4387 {
4388 if (m->timenow - cur->retryPortMap >= 0) // Time to do something with this mapping
4389 {
4390 if (cur->ExpiryTime && cur->ExpiryTime - m->timenow < 0) // Mapping has expired
4391 {
4392 cur->ExpiryTime = 0;
4393 cur->retryInterval = NATMAP_INIT_RETRY;
4394 }
4395
4396 //LogMsg("uDNS_SendNATMsg");
4397 err = uDNS_SendNATMsg(m, cur);
4398
4399 if (cur->ExpiryTime) // If have active mapping then set next renewal time halfway to expiry
4400 NATSetNextRenewalTime(m, cur);
4401 else // else no mapping; use exponential backoff sequence
4402 {
4403 if (cur->retryInterval < NATMAP_INIT_RETRY ) cur->retryInterval = NATMAP_INIT_RETRY;
4404 else if (cur->retryInterval < NATMAP_MAX_RETRY_INTERVAL / 2) cur->retryInterval *= 2;
4405 else cur->retryInterval = NATMAP_MAX_RETRY_INTERVAL;
4406 cur->retryPortMap = m->timenow + cur->retryInterval;
4407 }
4408 }
4409
4410 if (m->NextScheduledNATOp - cur->retryPortMap > 0)
4411 m->NextScheduledNATOp = cur->retryPortMap;
4412 }
4413
4414 // Notify the client if necessary. We invoke the callback if:
4415 // (1) we have an ExternalAddress, or we've tried and failed a couple of times to discover it
4416 // and (2) the client doesn't want a mapping, or the client won't need a mapping, or the client has a successful mapping, or we've tried and failed a couple of times
4417 // and (3) we have new data to give the client that's changed since the last callback
4418 // Time line is: Send, Wait 500ms, Send, Wait 1sec, Send, Wait 2sec, Send
4419 // At this point we've sent three requests without an answer, we've just sent our fourth request,
4420 // retryIntervalGetAddr is now 4 seconds, which is greater than NATMAP_INIT_RETRY * 8 (2 seconds),
4421 // so we return an error result to the caller.
4422 if (!mDNSIPv4AddressIsZero(m->ExternalAddress) || m->retryIntervalGetAddr > NATMAP_INIT_RETRY * 8)
4423 {
4424 const mStatus EffectiveResult = cur->NewResult ? cur->NewResult : mDNSv4AddrIsRFC1918(&m->ExternalAddress) ? mStatus_DoubleNAT : mStatus_NoError;
4425 const mDNSIPPort ExternalPort = HaveRoutable ? cur->IntPort :
4426 !mDNSIPv4AddressIsZero(m->ExternalAddress) && cur->ExpiryTime ? cur->RequestedPort : zeroIPPort;
4427 if (!cur->Protocol || HaveRoutable || cur->ExpiryTime || cur->retryInterval > NATMAP_INIT_RETRY * 8)
4428 if (!mDNSSameIPv4Address(cur->ExternalAddress, m->ExternalAddress) ||
4429 !mDNSSameIPPort (cur->ExternalPort, ExternalPort) ||
4430 cur->Result != EffectiveResult)
4431 {
4432 //LogMsg("NAT callback %d %d %d", cur->Protocol, cur->ExpiryTime, cur->retryInterval);
4433 if (cur->Protocol && mDNSIPPortIsZero(ExternalPort) && !mDNSIPv4AddressIsZero(m->Router.ip.v4))
4434 {
4435 if (!EffectiveResult)
4436 LogInfo("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4437 cur, &m->Router, &m->ExternalAddress, mDNSVal16(cur->IntPort), cur->retryInterval, EffectiveResult);
4438 else
4439 LogMsg("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4440 cur, &m->Router, &m->ExternalAddress, mDNSVal16(cur->IntPort), cur->retryInterval, EffectiveResult);
4441 }
4442
4443 cur->ExternalAddress = m->ExternalAddress;
4444 cur->ExternalPort = ExternalPort;
4445 cur->Lifetime = cur->ExpiryTime && !mDNSIPPortIsZero(ExternalPort) ?
4446 (cur->ExpiryTime - m->timenow + mDNSPlatformOneSecond/2) / mDNSPlatformOneSecond : 0;
4447 cur->Result = EffectiveResult;
4448 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
4449 if (cur->clientCallback)
4450 cur->clientCallback(m, cur);
4451 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4452 // MUST NOT touch cur after invoking the callback
4453 }
4454 }
4455 }
4456 }
4457
4458 mDNSlocal mDNSs32 CheckRecordUpdates(mDNS *m)
4459 {
4460 AuthRecord *rr;
4461 mDNSs32 nextevent = m->timenow + 0x3FFFFFFF;
4462
4463 CheckGroupRecordUpdates(m);
4464
4465 for (rr = m->ResourceRecords; rr; rr = rr->next)
4466 {
4467 if (!AuthRecord_uDNS(rr)) continue;
4468 if (rr->state == regState_NoTarget) {debugf("CheckRecordUpdates: Record %##s in NoTarget", rr->resrec.name->c); continue;}
4469 // While we are waiting for the port mapping, we have nothing to do. The port mapping callback
4470 // will take care of this
4471 if (rr->state == regState_NATMap) {debugf("CheckRecordUpdates: Record %##s in NATMap", rr->resrec.name->c); continue;}
4472 if (rr->state == regState_Pending || rr->state == regState_DeregPending || rr->state == regState_UpdatePending ||
4473 rr->state == regState_Refresh || rr->state == regState_Registered)
4474 {
4475 if (rr->LastAPTime + rr->ThisAPInterval - m->timenow <= 0)
4476 {
4477 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
4478 if (!rr->nta || mDNSIPv4AddressIsZero(rr->nta->Addr.ip.v4))
4479 {
4480 // Zero out the updateid so that if we have a pending response from the server, it won't
4481 // be accepted as a valid response. If we accept the response, we might free the new "nta"
4482 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
4483 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
4484
4485 // We have just started the GetZoneData. We need to wait for it to finish. SetRecordRetry here
4486 // schedules the update timer to fire in the future.
4487 //
4488 // There are three cases.
4489 //
4490 // 1) When the updates are sent the first time, the first retry is intended to be at three seconds
4491 // in the future. But by calling SetRecordRetry here we set it to nine seconds. But it does not
4492 // matter because when the answer comes back, RecordRegistrationGotZoneData resets the interval
4493 // back to INIT_RECORD_REG_INTERVAL. This also gives enough time for the query.
4494 //
4495 // 2) In the case of update errors (updateError), this causes further backoff as
4496 // RecordRegistrationGotZoneData does not reset the timer. This is intentional as in the case of
4497 // errors, we don't want to update aggressively.
4498 //
4499 // 3) We might be refreshing the update. This is very similar to case (1). RecordRegistrationGotZoneData
4500 // resets it back to INIT_RECORD_REG_INTERVAL.
4501 //
4502 SetRecordRetry(m, rr, 0);
4503 }
4504 else if (rr->state == regState_DeregPending) SendRecordDeregistration(m, rr);
4505 else SendRecordRegistration(m, rr);
4506 }
4507 }
4508 if (nextevent - (rr->LastAPTime + rr->ThisAPInterval) > 0)
4509 nextevent = (rr->LastAPTime + rr->ThisAPInterval);
4510 }
4511 return nextevent;
4512 }
4513
4514 mDNSexport void uDNS_Tasks(mDNS *const m)
4515 {
4516 mDNSs32 nexte;
4517 DNSServer *d;
4518
4519 m->NextuDNSEvent = m->timenow + 0x3FFFFFFF;
4520
4521 nexte = CheckRecordUpdates(m);
4522 if (m->NextuDNSEvent - nexte > 0)
4523 m->NextuDNSEvent = nexte;
4524
4525 for (d = m->DNSServers; d; d=d->next)
4526 if (d->penaltyTime)
4527 {
4528 if (m->timenow - d->penaltyTime >= 0)
4529 {
4530 LogInfo("DNS server %#a:%d out of penalty box", &d->addr, mDNSVal16(d->port));
4531 d->penaltyTime = 0;
4532 }
4533 else
4534 if (m->NextuDNSEvent - d->penaltyTime > 0)
4535 m->NextuDNSEvent = d->penaltyTime;
4536 }
4537
4538 if (m->CurrentQuestion)
4539 LogMsg("uDNS_Tasks ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4540 m->CurrentQuestion = m->Questions;
4541 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4542 {
4543 DNSQuestion *const q = m->CurrentQuestion;
4544 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID))
4545 {
4546 uDNS_CheckCurrentQuestion(m);
4547 if (q == m->CurrentQuestion)
4548 if (m->NextuDNSEvent - NextQSendTime(q) > 0)
4549 m->NextuDNSEvent = NextQSendTime(q);
4550 }
4551 // If m->CurrentQuestion wasn't modified out from under us, advance it now
4552 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion()
4553 // depends on having m->CurrentQuestion point to the right question
4554 if (m->CurrentQuestion == q)
4555 m->CurrentQuestion = q->next;
4556 }
4557 m->CurrentQuestion = mDNSNULL;
4558 }
4559
4560 // ***************************************************************************
4561 #if COMPILER_LIKES_PRAGMA_MARK
4562 #pragma mark - Startup, Shutdown, and Sleep
4563 #endif
4564
4565 mDNSexport void SleepRecordRegistrations(mDNS *m)
4566 {
4567 AuthRecord *rr;
4568 for (rr = m->ResourceRecords; rr; rr=rr->next)
4569 {
4570 if (AuthRecord_uDNS(rr))
4571 {
4572 // Zero out the updateid so that if we have a pending response from the server, it won't
4573 // be accepted as a valid response.
4574 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
4575
4576 if (rr->NATinfo.clientContext)
4577 {
4578 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
4579 rr->NATinfo.clientContext = mDNSNULL;
4580 }
4581 // We are waiting to update the resource record. The original data of the record is
4582 // in OrigRData and the updated value is in InFlightRData. Free the old and the new
4583 // one will be registered when we come back.
4584 if (rr->state == regState_UpdatePending)
4585 {
4586 // act as if the update succeeded, since we're about to delete the name anyway
4587 rr->state = regState_Registered;
4588 // deallocate old RData
4589 if (rr->UpdateCallback) rr->UpdateCallback(m, rr, rr->OrigRData, rr->OrigRDLen);
4590 SetNewRData(&rr->resrec, rr->InFlightRData, rr->InFlightRDLen);
4591 rr->OrigRData = mDNSNULL;
4592 rr->InFlightRData = mDNSNULL;
4593 }
4594
4595 // If we have not begun the registration process i.e., never sent a registration packet,
4596 // then uDNS_DeregisterRecord will not send a deregistration
4597 uDNS_DeregisterRecord(m, rr);
4598
4599 // When we wake, we call ActivateUnicastRegistration which starts at StartGetZoneData
4600 }
4601 }
4602 }
4603
4604 mDNSexport void mDNS_AddSearchDomain(const domainname *const domain)
4605 {
4606 SearchListElem **p;
4607
4608 // Check to see if we already have this domain in our list
4609 for (p = &SearchList; *p; p = &(*p)->next)
4610 if (SameDomainName(&(*p)->domain, domain))
4611 {
4612 // If domain is already in list, and marked for deletion, unmark the delete
4613 // Be careful not to touch the other flags that may be present
4614 if ((*p)->flag & SLE_DELETE) (*p)->flag &= ~SLE_DELETE;
4615 LogInfo("mDNS_AddSearchDomain already in list %##s", domain->c);
4616 return;
4617 }
4618
4619 // if domain not in list, add to list, mark as add (1)
4620 *p = mDNSPlatformMemAllocate(sizeof(SearchListElem));
4621 if (!*p) { LogMsg("ERROR: mDNS_AddSearchDomain - malloc"); return; }
4622 mDNSPlatformMemZero(*p, sizeof(SearchListElem));
4623 AssignDomainName(&(*p)->domain, domain);
4624 (*p)->next = mDNSNULL;
4625 LogInfo("mDNS_AddSearchDomain created new %##s", domain->c);
4626 }
4627
4628 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
4629 {
4630 (void)m; // unused
4631 if (result == mStatus_MemFree) mDNSPlatformMemFree(rr->RecordContext);
4632 }
4633
4634 #if APPLE_OSX_mDNSResponder
4635 mDNSlocal void CheckAutoTunnel6Registration(mDNS *const m, mDNSBool RegisterAutoTunnel6)
4636 {
4637 LogInfo("CheckAutoTunnel6Registration: Current value RegisterAutoTunnel6 %d, New value %d", m->RegisterAutoTunnel6, RegisterAutoTunnel6);
4638 if (!RegisterAutoTunnel6)
4639 {
4640 // We are not supposed to register autotunnel6. If we had previously registered
4641 // autotunnel6, deregister it now.
4642 if (m->RegisterAutoTunnel6)
4643 {
4644 m->RegisterAutoTunnel6 = mDNSfalse;
4645 LogInfo("CheckAutoTunnel6Registration: Removing AutoTunnel6");
4646 RemoveAutoTunnel6Record(m);
4647 }
4648 else LogInfo("CheckAutoTunnel6Registration: Already Removed AutoTunnel6");
4649 }
4650 else
4651 {
4652 // We are supposed to register autotunnel6. If we had previously de-registered
4653 // autotunnel6, re-register it now.
4654 if (!m->RegisterAutoTunnel6)
4655 {
4656 m->RegisterAutoTunnel6 = mDNStrue;
4657 LogInfo("CheckAutoTunnel6Registration: Adding AutoTunnel6");
4658 SetupConndConfigChanges(m);
4659 }
4660 else LogInfo("CheckAutoTunnel6Registration: already Added AutoTunnel6");
4661 }
4662 }
4663 #endif
4664
4665 mDNSlocal void FoundCFDomain(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
4666 {
4667 SearchListElem *slElem = question->QuestionContext;
4668 mDNSBool RegisterAutoTunnel6 = mDNStrue;
4669 char *res = "DisableInboundRelay";
4670
4671 LogInfo("FoundCFDomain: InterfaceID %p %s Question %##s Answer %s", answer->InterfaceID, AddRecord ? "Add" : "Rmv", question->qname.c, RRDisplayString(m, answer));
4672 if (answer->rrtype != kDNSType_TXT)
4673 {
4674 LogMsg("FoundCFDomain: answer type is not TXT %s for question %##s", DNSTypeName(answer->rrtype), question->qname.c);
4675 return;
4676 }
4677 if (answer->RecordType == kDNSRecordTypePacketNegative)
4678 {
4679 LogInfo("FoundCFDomain: Negative answer for %##s", question->qname.c);
4680 return;
4681 }
4682 if (answer->InterfaceID == mDNSInterface_LocalOnly)
4683 {
4684 LogInfo("FoundCFDomain: LocalOnly interfaceID for %##s", question->qname.c);
4685 return;
4686 }
4687
4688 // TXT record is encoded as <len><data>
4689 if (answer->rdlength != mDNSPlatformStrLen(res) + 1)
4690 {
4691 LogInfo("FoundCFDomain: Invalid TXT record to disable %##s, length %d", question->qname.c, answer->rdlength);
4692 return;
4693 }
4694
4695 // Compare the data (excluding the len byte)
4696 if (!mDNSPlatformMemSame(&answer->rdata->u.txt.c[1], res, answer->rdlength - 1))
4697 {
4698 LogInfo("FoundCFDomain: Invalid TXT record to disable %##s", question->qname.c);
4699 return;
4700 }
4701
4702 // It is sufficient for one answer to disable registration of autotunnel6. But we should
4703 // have zero answers across all domains to register autotunnel6.
4704 if (AddRecord)
4705 {
4706 slElem->numCfAnswers++;
4707 RegisterAutoTunnel6 = mDNSfalse;
4708 }
4709 else
4710 {
4711 const SearchListElem *s;
4712 slElem->numCfAnswers--;
4713 if (slElem->numCfAnswers < 0) LogMsg("FoundCFDomain: numCfAnswers less than zero %d", slElem->numCfAnswers);
4714 // See if any domain (including the slElem) has any answers
4715 for (s=SearchList; s; s=s->next)
4716 if (s->numCfAnswers) { RegisterAutoTunnel6 = mDNSfalse; break; }
4717 }
4718 #if APPLE_OSX_mDNSResponder
4719 CheckAutoTunnel6Registration(m, RegisterAutoTunnel6);
4720 #endif
4721 }
4722
4723 mDNSlocal void FoundDomain(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
4724 {
4725 SearchListElem *slElem = question->QuestionContext;
4726 mStatus err;
4727 const char *name;
4728
4729 if (answer->rrtype != kDNSType_PTR) return;
4730 if (answer->RecordType == kDNSRecordTypePacketNegative) return;
4731 if (answer->InterfaceID == mDNSInterface_LocalOnly) return;
4732
4733 if (question == &slElem->BrowseQ) name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowse];
4734 else if (question == &slElem->DefBrowseQ) name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowseDefault];
4735 else if (question == &slElem->AutomaticBrowseQ) name = mDNS_DomainTypeNames[mDNS_DomainTypeBrowseAutomatic];
4736 else if (question == &slElem->RegisterQ) name = mDNS_DomainTypeNames[mDNS_DomainTypeRegistration];
4737 else if (question == &slElem->DefRegisterQ) name = mDNS_DomainTypeNames[mDNS_DomainTypeRegistrationDefault];
4738 else { LogMsg("FoundDomain - unknown question"); return; }
4739
4740 LogInfo("FoundDomain: %p %s %s Q %##s A %s", answer->InterfaceID, AddRecord ? "Add" : "Rmv", name, question->qname.c, RRDisplayString(m, answer));
4741
4742 if (AddRecord)
4743 {
4744 ARListElem *arElem = mDNSPlatformMemAllocate(sizeof(ARListElem));
4745 if (!arElem) { LogMsg("ERROR: FoundDomain out of memory"); return; }
4746 mDNS_SetupResourceRecord(&arElem->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, FreeARElemCallback, arElem);
4747 MakeDomainNameFromDNSNameString(&arElem->ar.namestorage, name);
4748 AppendDNSNameString (&arElem->ar.namestorage, "local");
4749 AssignDomainName(&arElem->ar.resrec.rdata->u.name, &answer->rdata->u.name);
4750 LogInfo("FoundDomain: Registering %s", ARDisplayString(m, &arElem->ar));
4751 err = mDNS_Register(m, &arElem->ar);
4752 if (err) { LogMsg("ERROR: FoundDomain - mDNS_Register returned %d", err); mDNSPlatformMemFree(arElem); return; }
4753 arElem->next = slElem->AuthRecs;
4754 slElem->AuthRecs = arElem;
4755 }
4756 else
4757 {
4758 ARListElem **ptr = &slElem->AuthRecs;
4759 while (*ptr)
4760 {
4761 if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, &answer->rdata->u.name))
4762 {
4763 ARListElem *dereg = *ptr;
4764 *ptr = (*ptr)->next;
4765 LogInfo("FoundDomain: Deregistering %s", ARDisplayString(m, &dereg->ar));
4766 err = mDNS_Deregister(m, &dereg->ar);
4767 if (err) LogMsg("ERROR: FoundDomain - mDNS_Deregister returned %d", err);
4768 // Memory will be freed in the FreeARElemCallback
4769 }
4770 else
4771 ptr = &(*ptr)->next;
4772 }
4773 }
4774 }
4775
4776 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4777 mDNSexport void udns_validatelists(void *const v)
4778 {
4779 mDNS *const m = v;
4780
4781 NATTraversalInfo *n;
4782 for (n = m->NATTraversals; n; n=n->next)
4783 if (n->next == (NATTraversalInfo *)~0 || n->clientCallback == (NATTraversalClientCallback)~0)
4784 LogMemCorruption("m->NATTraversals: %p is garbage", n);
4785
4786 DNSServer *d;
4787 for (d = m->DNSServers; d; d=d->next)
4788 if (d->next == (DNSServer *)~0 || d->teststate > DNSServer_Disabled)
4789 LogMemCorruption("m->DNSServers: %p is garbage (%d)", d, d->teststate);
4790
4791 DomainAuthInfo *info;
4792 for (info = m->AuthInfoList; info; info = info->next)
4793 if (info->next == (DomainAuthInfo *)~0 || info->AutoTunnel == (mDNSBool)~0)
4794 LogMemCorruption("m->AuthInfoList: %p is garbage (%X)", info, info->AutoTunnel);
4795
4796 HostnameInfo *hi;
4797 for (hi = m->Hostnames; hi; hi = hi->next)
4798 if (hi->next == (HostnameInfo *)~0 || hi->StatusCallback == (mDNSRecordCallback*)~0)
4799 LogMemCorruption("m->Hostnames: %p is garbage", n);
4800
4801 SearchListElem *ptr;
4802 for (ptr = SearchList; ptr; ptr = ptr->next)
4803 if (ptr->next == (SearchListElem *)~0 || ptr->AuthRecs == (void*)~0)
4804 LogMemCorruption("SearchList: %p is garbage (%X)", ptr, ptr->AuthRecs);
4805 }
4806 #endif
4807
4808 mDNSlocal void mDNS_StartCFQuestion(mDNS *const m, DNSQuestion *question, domainname *domain, void *context)
4809 {
4810 AssignDomainName (&question->qname, (const domainname*)"\002cf" "\007_dns-sd" "\x04_udp");
4811 AppendDomainName (&question->qname, domain);
4812 question->InterfaceID = mDNSInterface_Any;
4813 question->Target = zeroAddr;
4814 question->qtype = kDNSType_TXT;
4815 question->qclass = kDNSClass_IN;
4816 question->LongLived = mDNSfalse;
4817 question->ExpectUnique = mDNStrue;
4818 question->ForceMCast = mDNSfalse;
4819 question->ReturnIntermed = mDNSfalse;
4820 question->SuppressUnusable = mDNSfalse;
4821 question->WakeOnResolve = mDNSfalse;
4822 question->QuestionCallback = FoundCFDomain;
4823 question->QuestionContext = context;
4824 LogInfo("mDNS_StartCFQuestion: Start CF domain question %##s", question->qname.c);
4825 if (mDNS_StartQuery(m, question))
4826 LogMsg("mDNS_StartCFQuestion: ERROR!! cannot start cf._dns-sd query");
4827 }
4828
4829 // This should probably move to the UDS daemon -- the concept of legacy clients and automatic registration / automatic browsing
4830 // is really a UDS API issue, not something intrinsic to uDNS
4831 mDNSexport mStatus uDNS_SetupSearchDomains(mDNS *const m, int action)
4832 {
4833 SearchListElem **p = &SearchList, *ptr;
4834 const SearchListElem *s;
4835 mDNSBool RegisterAutoTunnel6 = mDNStrue;
4836 mStatus err;
4837
4838 // step 1: mark each element for removal
4839 for (ptr = SearchList; ptr; ptr = ptr->next) ptr->flag |= SLE_DELETE;
4840
4841 // Client has requested domain enumeration or automatic browse -- time to make sure we have the search domains from the platform layer
4842 mDNS_Lock(m);
4843 mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNStrue, mDNSNULL, mDNSNULL, mDNSNULL);
4844 mDNS_Unlock(m);
4845
4846 if (action & UDNS_START_WAB_QUERY)
4847 m->StartWABQueries = mDNStrue;
4848
4849 // delete elems marked for removal, do queries for elems marked add
4850 while (*p)
4851 {
4852 ptr = *p;
4853 LogInfo("uDNS_SetupSearchDomains:action %d: Flags %d, AuthRecs %p, %##s", action, ptr->flag, ptr->AuthRecs, ptr->domain.c);
4854 if (ptr->flag & SLE_DELETE)
4855 {
4856 ARListElem *arList = ptr->AuthRecs;
4857 ptr->AuthRecs = mDNSNULL;
4858 *p = ptr->next;
4859
4860 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries
4861 // Note: Stopping a question will not generate the RMV events for the question (handled in FoundCFDomain)
4862 // and hence we need to recheck all the domains to see if we need to register/deregister _autotunnel6.
4863 // This is done at the end.
4864 if ((ptr->flag & SLE_WAB_QUERY_STARTED) && !SameDomainName(&ptr->domain, &localdomain))
4865 {
4866 mDNS_StopGetDomains(m, &ptr->BrowseQ);
4867 mDNS_StopGetDomains(m, &ptr->RegisterQ);
4868 mDNS_StopGetDomains(m, &ptr->DefBrowseQ);
4869 mDNS_StopGetDomains(m, &ptr->DefRegisterQ);
4870 mDNS_StopGetDomains(m, &ptr->AutomaticBrowseQ);
4871 }
4872 #if !TARGET_OS_EMBEDDED
4873 if ((ptr->flag & SLE_CF_QUERY_STARTED) && !SameDomainName(&ptr->domain, &localdomain))
4874 {
4875 mDNS_StopGetDomains(m, &ptr->CfQ);
4876 }
4877 #endif
4878 mDNSPlatformMemFree(ptr);
4879
4880 // deregister records generated from answers to the query
4881 while (arList)
4882 {
4883 ARListElem *dereg = arList;
4884 arList = arList->next;
4885 debugf("Deregistering PTR %##s -> %##s", dereg->ar.resrec.name->c, dereg->ar.resrec.rdata->u.name.c);
4886 err = mDNS_Deregister(m, &dereg->ar);
4887 if (err) LogMsg("uDNS_SetupSearchDomains:: ERROR!! mDNS_Deregister returned %d", err);
4888 // Memory will be freed in the FreeARElemCallback
4889 }
4890 continue;
4891 }
4892
4893 if ((action & UDNS_START_WAB_QUERY) && !(ptr->flag & SLE_WAB_QUERY_STARTED))
4894 {
4895 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries.
4896 if (!SameDomainName(&ptr->domain, &localdomain))
4897 {
4898 mStatus err1, err2, err3, err4, err5;
4899 err1 = mDNS_GetDomains(m, &ptr->BrowseQ, mDNS_DomainTypeBrowse, &ptr->domain, mDNSInterface_Any, FoundDomain, ptr);
4900 err2 = mDNS_GetDomains(m, &ptr->DefBrowseQ, mDNS_DomainTypeBrowseDefault, &ptr->domain, mDNSInterface_Any, FoundDomain, ptr);
4901 err3 = mDNS_GetDomains(m, &ptr->RegisterQ, mDNS_DomainTypeRegistration, &ptr->domain, mDNSInterface_Any, FoundDomain, ptr);
4902 err4 = mDNS_GetDomains(m, &ptr->DefRegisterQ, mDNS_DomainTypeRegistrationDefault, &ptr->domain, mDNSInterface_Any, FoundDomain, ptr);
4903 err5 = mDNS_GetDomains(m, &ptr->AutomaticBrowseQ, mDNS_DomainTypeBrowseAutomatic, &ptr->domain, mDNSInterface_Any, FoundDomain, ptr);
4904 if (err1 || err2 || err3 || err4 || err5)
4905 LogMsg("uDNS_SetupSearchDomains: GetDomains for domain %##s returned error(s):\n"
4906 "%d (mDNS_DomainTypeBrowse)\n"
4907 "%d (mDNS_DomainTypeBrowseDefault)\n"
4908 "%d (mDNS_DomainTypeRegistration)\n"
4909 "%d (mDNS_DomainTypeRegistrationDefault)"
4910 "%d (mDNS_DomainTypeBrowseAutomatic)\n",
4911 ptr->domain.c, err1, err2, err3, err4, err5);
4912 ptr->flag |= SLE_WAB_QUERY_STARTED;
4913 }
4914 }
4915 #if !TARGET_OS_EMBEDDED
4916 if ((action & UDNS_START_CF_QUERY) && !(ptr->flag & SLE_CF_QUERY_STARTED))
4917 {
4918 if (!SameDomainName(&ptr->domain, &localdomain))
4919 {
4920 mDNS_StartCFQuestion(m, &ptr->CfQ, &ptr->domain, ptr);
4921 ptr->flag |= SLE_CF_QUERY_STARTED;
4922 }
4923 }
4924 #endif
4925
4926 p = &ptr->next;
4927 }
4928 #if !TARGET_OS_EMBEDDED
4929 // if there is any domain has answers, need to deregister autotunnel6
4930 for (s=SearchList; s; s=s->next)
4931 if (s->numCfAnswers) { RegisterAutoTunnel6 = mDNSfalse; break; }
4932 #if APPLE_OSX_mDNSResponder
4933 CheckAutoTunnel6Registration(m, RegisterAutoTunnel6);
4934 #endif
4935 #endif
4936 return mStatus_NoError;
4937 }
4938
4939 // Construction of Default Browse domain list (i.e. when clients pass NULL) is as follows:
4940 // 1) query for b._dns-sd._udp.local on LocalOnly interface
4941 // (.local manually generated via explicit callback)
4942 // 2) for each search domain (from prefs pane), query for b._dns-sd._udp.<searchdomain>.
4943 // 3) for each result from (2), register LocalOnly PTR record b._dns-sd._udp.local. -> <result>
4944 // 4) result above should generate a callback from question in (1). result added to global list
4945 // 5) global list delivered to client via GetSearchDomainList()
4946 // 6) client calls to enumerate domains now go over LocalOnly interface
4947 // (!!!KRS may add outgoing interface in addition)
4948
4949 struct CompileTimeAssertionChecks_uDNS
4950 {
4951 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4952 // other overly-large structures instead of having a pointer to them, can inadvertently
4953 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
4954 char sizecheck_tcpInfo_t [(sizeof(tcpInfo_t) <= 9056) ? 1 : -1];
4955 char sizecheck_SearchListElem[(sizeof(SearchListElem) <= 4860) ? 1 : -1];
4956 };