1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2012 Apple Computer, Inc. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
23 #if APPLE_OSX_mDNSResponder
24 #include <TargetConditionals.h>
28 #if (defined(_MSC_VER))
29 // Disable "assignment within conditional expression".
30 // Other compilers understand the convention that if you place the assignment expression within an extra pair
31 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
32 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
33 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
34 #pragma warning(disable:4706)
37 // For domain enumeration and automatic browsing
38 // This is the user's DNS search list.
39 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
40 // to discover recommended domains for domain enumeration (browse, default browse, registration,
41 // default registration) and possibly one or more recommended automatic browsing domains.
42 mDNSexport SearchListElem
*SearchList
= mDNSNULL
;
44 // The value can be set to true by the Platform code e.g., MacOSX uses the plist mechanism
45 mDNSBool StrictUnicastOrdering
= mDNSfalse
;
47 // We keep track of the number of unicast DNS servers and log a message when we exceed 64.
48 // Currently the unicast queries maintain a 64 bit map to track the valid DNS servers for that
49 // question. Bit position is the index into the DNS server list. This is done so to try all
50 // the servers exactly once before giving up. If we could allocate memory in the core, then
51 // arbitrary limitation of 64 DNSServers can be removed.
52 mDNSu8 NumUnicastDNSServers
= 0;
53 #define MAX_UNICAST_DNS_SERVERS 64
55 #define SetNextuDNSEvent(m, rr) { \
56 if ((m)->NextuDNSEvent - ((rr)->LastAPTime + (rr)->ThisAPInterval) >= 0) \
57 (m)->NextuDNSEvent = ((rr)->LastAPTime + (rr)->ThisAPInterval); \
60 // ***************************************************************************
61 #if COMPILER_LIKES_PRAGMA_MARK
62 #pragma mark - General Utility Functions
65 // set retry timestamp for record with exponential backoff
66 mDNSlocal
void SetRecordRetry(mDNS
*const m
, AuthRecord
*rr
, mDNSu32 random
)
68 rr
->LastAPTime
= m
->timenow
;
70 if (rr
->expire
&& rr
->refreshCount
< MAX_UPDATE_REFRESH_COUNT
)
72 mDNSs32 remaining
= rr
->expire
- m
->timenow
;
74 if (remaining
> MIN_UPDATE_REFRESH_TIME
)
76 // Refresh at 70% + random (currently it is 0 to 10%)
77 rr
->ThisAPInterval
= 7 * (remaining
/10) + (random
? random
: mDNSRandom(remaining
/10));
78 // Don't update more often than 5 minutes
79 if (rr
->ThisAPInterval
< MIN_UPDATE_REFRESH_TIME
)
80 rr
->ThisAPInterval
= MIN_UPDATE_REFRESH_TIME
;
81 LogInfo("SetRecordRetry refresh in %d of %d for %s",
82 rr
->ThisAPInterval
/mDNSPlatformOneSecond
, (rr
->expire
- m
->timenow
)/mDNSPlatformOneSecond
, ARDisplayString(m
, rr
));
86 rr
->ThisAPInterval
= MIN_UPDATE_REFRESH_TIME
;
87 LogInfo("SetRecordRetry clamping to min refresh in %d of %d for %s",
88 rr
->ThisAPInterval
/mDNSPlatformOneSecond
, (rr
->expire
- m
->timenow
)/mDNSPlatformOneSecond
, ARDisplayString(m
, rr
));
95 rr
->ThisAPInterval
= rr
->ThisAPInterval
* QuestionIntervalStep
; // Same Retry logic as Unicast Queries
96 if (rr
->ThisAPInterval
< INIT_RECORD_REG_INTERVAL
)
97 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
98 if (rr
->ThisAPInterval
> MAX_RECORD_REG_INTERVAL
)
99 rr
->ThisAPInterval
= MAX_RECORD_REG_INTERVAL
;
101 LogInfo("SetRecordRetry retry in %d ms for %s", rr
->ThisAPInterval
, ARDisplayString(m
, rr
));
104 // ***************************************************************************
105 #if COMPILER_LIKES_PRAGMA_MARK
106 #pragma mark - Name Server List Management
109 mDNSexport DNSServer
*mDNS_AddDNSServer(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, const mDNSAddr
*addr
, const mDNSIPPort port
, mDNSBool scoped
, mDNSu32 timeout
, mDNSBool cellIntf
, mDNSu16 resGroupID
)
111 DNSServer
**p
= &m
->DNSServers
;
112 DNSServer
*tmp
= mDNSNULL
;
114 if ((NumUnicastDNSServers
+ 1) > MAX_UNICAST_DNS_SERVERS
)
116 LogMsg("mDNS_AddDNSServer: DNS server limit of %d reached, not adding this server", MAX_UNICAST_DNS_SERVERS
);
120 if (!d
) d
= (const domainname
*)"";
122 LogInfo("mDNS_AddDNSServer: Adding %#a for %##s, InterfaceID %p, scoped %d, resGroupID %d", addr
, d
->c
, interface
, scoped
, resGroupID
);
124 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
125 LogMsg("mDNS_AddDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
127 while (*p
) // Check if we already have this {interface,address,port,domain} tuple registered
129 if ((*p
)->scoped
== scoped
&& (*p
)->interface
== interface
&& (*p
)->teststate
!= DNSServer_Disabled
&&
130 mDNSSameAddress(&(*p
)->addr
, addr
) && mDNSSameIPPort((*p
)->port
, port
) && SameDomainName(&(*p
)->domain
, d
))
132 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
);
133 (*p
)->flags
&= ~DNSServer_FlagDelete
;
136 tmp
->next
= mDNSNULL
;
142 if (tmp
) *p
= tmp
; // move to end of list, to ensure ordering from platform layer
145 // allocate, add to list
146 *p
= mDNSPlatformMemAllocate(sizeof(**p
));
147 if (!*p
) LogMsg("Error: mDNS_AddDNSServer - malloc");
150 NumUnicastDNSServers
++;
151 (*p
)->scoped
= scoped
;
152 (*p
)->interface
= interface
;
155 (*p
)->flags
= DNSServer_FlagNew
;
156 (*p
)->teststate
= /* DNSServer_Untested */ DNSServer_Passed
;
157 (*p
)->lasttest
= m
->timenow
- INIT_UCAST_POLL_INTERVAL
;
158 (*p
)->timeout
= timeout
;
159 (*p
)->cellIntf
= cellIntf
;
160 AssignDomainName(&(*p
)->domain
, d
);
161 (*p
)->next
= mDNSNULL
;
164 (*p
)->penaltyTime
= 0;
165 // We always update the ID (not just when we allocate a new instance) because we could
166 // be adding a new non-scoped resolver with a new ID and we want all the non-scoped
167 // resolvers belong to the same group.
168 (*p
)->resGroupID
= resGroupID
;
172 // PenalizeDNSServer is called when the number of queries to the unicast
173 // DNS server exceeds MAX_UCAST_UNANSWERED_QUERIES or when we receive an
174 // error e.g., SERV_FAIL from DNS server.
175 mDNSexport
void PenalizeDNSServer(mDNS
*const m
, DNSQuestion
*q
)
178 DNSServer
*orig
= q
->qDNSServer
;
180 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
181 LogMsg("PenalizeDNSServer: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
183 LogInfo("PenalizeDNSServer: Penalizing DNS server %#a question for question %p %##s (%s) SuppressUnusable %d",
184 (q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
), q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->SuppressUnusable
);
186 // After we reset the qDNSServer to NULL, we could get more SERV_FAILS that might end up
188 if (!q
->qDNSServer
) goto end
;
190 // If strict ordering of unicast servers needs to be preserved, we just lookup
191 // the next best match server below
193 // If strict ordering is not required which is the default behavior, we penalize the server
194 // for DNSSERVER_PENALTY_TIME. We may also use additional logic e.g., don't penalize for PTR
197 if (!StrictUnicastOrdering
)
199 LogInfo("PenalizeDNSServer: Strict Unicast Ordering is FALSE");
200 // We penalize the server so that new queries don't pick this server for DNSSERVER_PENALTY_TIME
201 // XXX Include other logic here to see if this server should really be penalized
203 if (q
->qtype
== kDNSType_PTR
)
205 LogInfo("PenalizeDNSServer: Not Penalizing PTR question");
209 LogInfo("PenalizeDNSServer: Penalizing question type %d", q
->qtype
);
210 q
->qDNSServer
->penaltyTime
= NonZeroTime(m
->timenow
+ DNSSERVER_PENALTY_TIME
);
215 LogInfo("PenalizeDNSServer: Strict Unicast Ordering is TRUE");
219 new = GetServerForQuestion(m
, q
);
225 LogMsg("PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server %#a:%d", &new->addr
,
226 mDNSVal16(new->port
));
227 q
->ThisQInterval
= 0; // Inactivate this question so that we dont bombard the network
231 // When we have no more DNS servers, we might end up calling PenalizeDNSServer multiple
232 // times when we receive SERVFAIL from delayed packets in the network e.g., DNS server
233 // is slow in responding and we have sent three queries. When we repeatedly call, it is
234 // okay to receive the same NULL DNS server. Next time we try to send the query, we will
235 // realize and re-initialize the DNS servers.
236 LogInfo("PenalizeDNSServer: GetServerForQuestion returned the same server NULL");
241 // The new DNSServer is set in DNSServerChangeForQuestion
242 DNSServerChangeForQuestion(m
, q
, new);
246 LogInfo("PenalizeDNSServer: Server for %##s (%s) changed to %#a:%d (%##s)",
247 q
->qname
.c
, DNSTypeName(q
->qtype
), &q
->qDNSServer
->addr
, mDNSVal16(q
->qDNSServer
->port
), q
->qDNSServer
->domain
.c
);
248 // We want to try the next server immediately. As the question may already have backed off, reset
249 // the interval. We do this only the first time when we try all the DNS servers. Once we reached the end of
250 // list and retrying all the servers again e.g., at least one server failed to respond in the previous try, we
251 // use the normal backoff which is done in uDNS_CheckCurrentQuestion when we send the packet out.
252 if (!q
->triedAllServersOnce
)
254 q
->ThisQInterval
= InitialQuestionInterval
;
255 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
256 SetNextQueryTime(m
, q
);
261 // We don't have any more DNS servers for this question. If some server in the list did not return
262 // any response, we need to keep retrying till we get a response. uDNS_CheckCurrentQuestion handles
265 // If all servers responded with a negative response, We need to do two things. First, generate a
266 // negative response so that applications get a reply. We also need to reinitialize the DNS servers
267 // so that when the cache expires, we can restart the query. We defer this up until we generate
268 // a negative cache response in uDNS_CheckCurrentQuestion.
270 // Be careful not to touch the ThisQInterval here. For a normal question, when we answer the question
271 // in AnswerCurrentQuestionWithResourceRecord will set ThisQInterval to MaxQuestionInterval and hence
272 // the next query will not happen until cache expiry. If it is a long lived question,
273 // AnswerCurrentQuestionWithResourceRecord will not set it to MaxQuestionInterval. In that case,
274 // we want the normal backoff to work.
275 LogInfo("PenalizeDNSServer: Server for %p, %##s (%s) changed to NULL, Interval %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
);
277 q
->unansweredQueries
= 0;
282 // ***************************************************************************
283 #if COMPILER_LIKES_PRAGMA_MARK
284 #pragma mark - authorization management
287 mDNSlocal DomainAuthInfo
*GetAuthInfoForName_direct(mDNS
*m
, const domainname
*const name
)
289 const domainname
*n
= name
;
293 for (ptr
= m
->AuthInfoList
; ptr
; ptr
= ptr
->next
)
294 if (SameDomainName(&ptr
->domain
, n
))
296 debugf("GetAuthInfoForName %##s Matched %##s Key name %##s", name
->c
, ptr
->domain
.c
, ptr
->keyname
.c
);
299 n
= (const domainname
*)(n
->c
+ 1 + n
->c
[0]);
301 //LogInfo("GetAuthInfoForName none found for %##s", name->c);
305 // MUST be called with lock held
306 mDNSexport DomainAuthInfo
*GetAuthInfoForName_internal(mDNS
*m
, const domainname
*const name
)
308 DomainAuthInfo
**p
= &m
->AuthInfoList
;
310 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
311 LogMsg("GetAuthInfoForName_internal: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
313 // First purge any dead keys from the list
316 if ((*p
)->deltime
&& m
->timenow
- (*p
)->deltime
>= 0 && AutoTunnelUnregistered(*p
))
319 DomainAuthInfo
*info
= *p
;
320 LogInfo("GetAuthInfoForName_internal deleting expired key %##s %##s", info
->domain
.c
, info
->keyname
.c
);
321 *p
= info
->next
; // Cut DomainAuthInfo from list *before* scanning our question list updating AuthInfo pointers
322 for (q
= m
->Questions
; q
; q
=q
->next
)
323 if (q
->AuthInfo
== info
)
325 q
->AuthInfo
= GetAuthInfoForName_direct(m
, &q
->qname
);
326 debugf("GetAuthInfoForName_internal updated q->AuthInfo from %##s to %##s for %##s (%s)",
327 info
->domain
.c
, q
->AuthInfo
? q
->AuthInfo
->domain
.c
: mDNSNULL
, q
->qname
.c
, DNSTypeName(q
->qtype
));
330 // Probably not essential, but just to be safe, zero out the secret key data
331 // so we don't leave it hanging around in memory
332 // (where it could potentially get exposed via some other bug)
333 mDNSPlatformMemZero(info
, sizeof(*info
));
334 mDNSPlatformMemFree(info
);
340 return(GetAuthInfoForName_direct(m
, name
));
343 mDNSexport DomainAuthInfo
*GetAuthInfoForName(mDNS
*m
, const domainname
*const name
)
347 d
= GetAuthInfoForName_internal(m
, name
);
352 // MUST be called with the lock held
353 mDNSexport mStatus
mDNS_SetSecretForDomain(mDNS
*m
, DomainAuthInfo
*info
,
354 const domainname
*domain
, const domainname
*keyname
, const char *b64keydata
, const domainname
*hostname
, mDNSIPPort
*port
, mDNSBool autoTunnel
)
357 DomainAuthInfo
**p
= &m
->AuthInfoList
;
358 if (!info
|| !b64keydata
) { LogMsg("mDNS_SetSecretForDomain: ERROR: info %p b64keydata %p", info
, b64keydata
); return(mStatus_BadParamErr
); }
360 LogInfo("mDNS_SetSecretForDomain: domain %##s key %##s%s", domain
->c
, keyname
->c
, autoTunnel
? " AutoTunnel" : "");
362 info
->AutoTunnel
= autoTunnel
;
363 AssignDomainName(&info
->domain
, domain
);
364 AssignDomainName(&info
->keyname
, keyname
);
366 AssignDomainName(&info
->hostname
, hostname
);
368 info
->hostname
.c
[0] = 0;
372 info
->port
= zeroIPPort
;
373 mDNS_snprintf(info
->b64keydata
, sizeof(info
->b64keydata
), "%s", b64keydata
);
375 if (DNSDigest_ConstructHMACKeyfromBase64(info
, b64keydata
) < 0)
377 LogMsg("mDNS_SetSecretForDomain: ERROR: Could not convert shared secret from base64: domain %##s key %##s %s", domain
->c
, keyname
->c
, mDNS_LoggingEnabled
? b64keydata
: "");
378 return(mStatus_BadParamErr
);
381 // Don't clear deltime until after we've ascertained that b64keydata is valid
384 while (*p
&& (*p
) != info
) p
=&(*p
)->next
;
385 if (*p
) {LogInfo("mDNS_SetSecretForDomain: Domain %##s Already in list", (*p
)->domain
.c
); return(mStatus_AlreadyRegistered
);}
387 // Caution: Only zero AutoTunnelHostRecord.namestorage AFTER we've determined that this is a NEW DomainAuthInfo
388 // being added to the list. Otherwise we risk smashing our AutoTunnel host records that are already active and in use.
389 info
->AutoTunnelHostRecord
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
390 info
->AutoTunnelHostRecord
.namestorage
.c
[0] = 0;
391 info
->AutoTunnelTarget
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
392 info
->AutoTunnelDeviceInfo
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
393 info
->AutoTunnelService
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
394 info
->AutoTunnel6Record
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
395 info
->AutoTunnelServiceStarted
= mDNSfalse
;
396 info
->AutoTunnelInnerAddress
= zerov6Addr
;
397 info
->next
= mDNSNULL
;
400 // Check to see if adding this new DomainAuthInfo has changed the credentials for any of our questions
401 for (q
= m
->Questions
; q
; q
=q
->next
)
403 DomainAuthInfo
*newinfo
= GetAuthInfoForQuestion(m
, q
);
404 if (q
->AuthInfo
!= newinfo
)
406 debugf("mDNS_SetSecretForDomain updating q->AuthInfo from %##s to %##s for %##s (%s)",
407 q
->AuthInfo
? q
->AuthInfo
->domain
.c
: mDNSNULL
,
408 newinfo
? newinfo
->domain
.c
: mDNSNULL
, q
->qname
.c
, DNSTypeName(q
->qtype
));
409 q
->AuthInfo
= newinfo
;
413 return(mStatus_NoError
);
416 // ***************************************************************************
417 #if COMPILER_LIKES_PRAGMA_MARK
419 #pragma mark - NAT Traversal
422 mDNSlocal mStatus
uDNS_SendNATMsg(mDNS
*m
, NATTraversalInfo
*info
)
424 mStatus err
= mStatus_NoError
;
426 // send msg if we have a router and it is a private address
427 if (!mDNSIPv4AddressIsZero(m
->Router
.ip
.v4
) && mDNSv4AddrIsRFC1918(&m
->Router
.ip
.v4
))
429 union { NATAddrRequest NATAddrReq
; NATPortMapRequest NATPortReq
; } u
= { { NATMAP_VERS
, NATOp_AddrRequest
} } ;
430 const mDNSu8
*end
= (mDNSu8
*)&u
+ sizeof(NATAddrRequest
);
432 if (info
) // For NATOp_MapUDP and NATOp_MapTCP, fill in additional fields
434 mDNSu8
*p
= (mDNSu8
*)&u
.NATPortReq
.NATReq_lease
;
435 u
.NATPortReq
.opcode
= info
->Protocol
;
436 u
.NATPortReq
.unused
= zeroID
;
437 u
.NATPortReq
.intport
= info
->IntPort
;
438 u
.NATPortReq
.extport
= info
->RequestedPort
;
439 p
[0] = (mDNSu8
)((info
->NATLease
>> 24) & 0xFF);
440 p
[1] = (mDNSu8
)((info
->NATLease
>> 16) & 0xFF);
441 p
[2] = (mDNSu8
)((info
->NATLease
>> 8) & 0xFF);
442 p
[3] = (mDNSu8
)( info
->NATLease
& 0xFF);
443 end
= (mDNSu8
*)&u
+ sizeof(NATPortMapRequest
);
446 err
= mDNSPlatformSendUDP(m
, (mDNSu8
*)&u
, end
, 0, mDNSNULL
, &m
->Router
, NATPMPPort
, mDNSfalse
);
448 #ifdef _LEGACY_NAT_TRAVERSAL_
449 if (mDNSIPPortIsZero(m
->UPnPRouterPort
) || mDNSIPPortIsZero(m
->UPnPSOAPPort
)) LNT_SendDiscoveryMsg(m
);
450 else if (info
) err
= LNT_MapPort(m
, info
);
451 else err
= LNT_GetExternalAddress(m
);
452 #endif // _LEGACY_NAT_TRAVERSAL_
457 mDNSexport
void RecreateNATMappings(mDNS
*const m
)
460 for (n
= m
->NATTraversals
; n
; n
=n
->next
)
462 n
->ExpiryTime
= 0; // Mark this mapping as expired
463 n
->retryInterval
= NATMAP_INIT_RETRY
;
464 n
->retryPortMap
= m
->timenow
;
465 #ifdef _LEGACY_NAT_TRAVERSAL_
466 if (n
->tcpInfo
.sock
) { mDNSPlatformTCPCloseConnection(n
->tcpInfo
.sock
); n
->tcpInfo
.sock
= mDNSNULL
; }
467 #endif // _LEGACY_NAT_TRAVERSAL_
470 m
->NextScheduledNATOp
= m
->timenow
; // Need to send packets immediately
473 mDNSexport
void natTraversalHandleAddressReply(mDNS
*const m
, mDNSu16 err
, mDNSv4Addr ExtAddr
)
475 static mDNSu16 last_err
= 0;
479 if (err
!= last_err
) LogMsg("Error getting external address %d", err
);
480 ExtAddr
= zerov4Addr
;
484 LogInfo("Received external IP address %.4a from NAT", &ExtAddr
);
485 if (mDNSv4AddrIsRFC1918(&ExtAddr
))
486 LogMsg("Double NAT (external NAT gateway address %.4a is also a private RFC 1918 address)", &ExtAddr
);
487 if (mDNSIPv4AddressIsZero(ExtAddr
))
488 err
= NATErr_NetFail
; // fake error to handle routers that pathologically report success with the zero address
491 if (!mDNSSameIPv4Address(m
->ExternalAddress
, ExtAddr
))
493 m
->ExternalAddress
= ExtAddr
;
494 RecreateNATMappings(m
); // Also sets NextScheduledNATOp for us
497 if (!err
) // Success, back-off to maximum interval
498 m
->retryIntervalGetAddr
= NATMAP_MAX_RETRY_INTERVAL
;
499 else if (!last_err
) // Failure after success, retry quickly (then back-off exponentially)
500 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
501 // else back-off normally in case of pathological failures
503 m
->retryGetAddr
= m
->timenow
+ m
->retryIntervalGetAddr
;
504 if (m
->NextScheduledNATOp
- m
->retryIntervalGetAddr
> 0)
505 m
->NextScheduledNATOp
= m
->retryIntervalGetAddr
;
510 // Both places that call NATSetNextRenewalTime() update m->NextScheduledNATOp correctly afterwards
511 mDNSlocal
void NATSetNextRenewalTime(mDNS
*const m
, NATTraversalInfo
*n
)
513 n
->retryInterval
= (n
->ExpiryTime
- m
->timenow
)/2;
514 if (n
->retryInterval
< NATMAP_MIN_RETRY_INTERVAL
) // Min retry interval is 2 seconds
515 n
->retryInterval
= NATMAP_MIN_RETRY_INTERVAL
;
516 n
->retryPortMap
= m
->timenow
+ n
->retryInterval
;
519 // Note: When called from handleLNTPortMappingResponse() only pkt->err, pkt->extport and pkt->NATRep_lease fields are filled in
520 mDNSexport
void natTraversalHandlePortMapReply(mDNS
*const m
, NATTraversalInfo
*n
, const mDNSInterfaceID InterfaceID
, mDNSu16 err
, mDNSIPPort extport
, mDNSu32 lease
)
522 const char *prot
= n
->Protocol
== NATOp_MapUDP
? "UDP" : n
->Protocol
== NATOp_MapTCP
? "TCP" : "?";
525 if (err
|| lease
== 0 || mDNSIPPortIsZero(extport
))
527 LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d error %d",
528 n
, prot
, mDNSVal16(n
->IntPort
), mDNSVal16(extport
), lease
, err
);
529 n
->retryInterval
= NATMAP_MAX_RETRY_INTERVAL
;
530 n
->retryPortMap
= m
->timenow
+ NATMAP_MAX_RETRY_INTERVAL
;
531 // No need to set m->NextScheduledNATOp here, since we're only ever extending the m->retryPortMap time
532 if (err
== NATErr_Refused
) n
->NewResult
= mStatus_NATPortMappingDisabled
;
533 else if (err
> NATErr_None
&& err
<= NATErr_Opcode
) n
->NewResult
= mStatus_NATPortMappingUnsupported
;
537 if (lease
> 999999999UL / mDNSPlatformOneSecond
)
538 lease
= 999999999UL / mDNSPlatformOneSecond
;
539 n
->ExpiryTime
= NonZeroTime(m
->timenow
+ lease
* mDNSPlatformOneSecond
);
541 if (!mDNSSameIPPort(n
->RequestedPort
, extport
))
542 LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d changed to %5d",
543 n
, prot
, mDNSVal16(n
->IntPort
), mDNSVal16(n
->RequestedPort
), mDNSVal16(extport
));
545 n
->InterfaceID
= InterfaceID
;
546 n
->RequestedPort
= extport
;
548 LogInfo("natTraversalHandlePortMapReply: %p Response %s Port %5d External Port %5d lease %d",
549 n
, prot
, mDNSVal16(n
->IntPort
), mDNSVal16(extport
), lease
);
551 NATSetNextRenewalTime(m
, n
); // Got our port mapping; now set timer to renew it at halfway point
552 m
->NextScheduledNATOp
= m
->timenow
; // May need to invoke client callback immediately
556 // Must be called with the mDNS_Lock held
557 mDNSexport mStatus
mDNS_StartNATOperation_internal(mDNS
*const m
, NATTraversalInfo
*traversal
)
559 NATTraversalInfo
**n
;
561 LogInfo("mDNS_StartNATOperation_internal %p Protocol %d IntPort %d RequestedPort %d NATLease %d", traversal
,
562 traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), mDNSVal16(traversal
->RequestedPort
), traversal
->NATLease
);
564 // Note: It important that new traversal requests are appended at the *end* of the list, not prepended at the start
565 for (n
= &m
->NATTraversals
; *n
; n
=&(*n
)->next
)
569 LogMsg("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
570 traversal
, traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), traversal
->NATLease
);
574 return(mStatus_AlreadyRegistered
);
576 if (traversal
->Protocol
&& traversal
->Protocol
== (*n
)->Protocol
&& mDNSSameIPPort(traversal
->IntPort
, (*n
)->IntPort
) &&
577 !mDNSSameIPPort(traversal
->IntPort
, SSHPort
))
578 LogMsg("Warning: Created port mapping request %p Prot %d Int %d TTL %d "
579 "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
580 traversal
, traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), traversal
->NATLease
,
581 *n
, (*n
)->Protocol
, mDNSVal16((*n
)->IntPort
), (*n
)->NATLease
);
584 // Initialize necessary fields
585 traversal
->next
= mDNSNULL
;
586 traversal
->ExpiryTime
= 0;
587 traversal
->retryInterval
= NATMAP_INIT_RETRY
;
588 traversal
->retryPortMap
= m
->timenow
;
589 traversal
->NewResult
= mStatus_NoError
;
590 traversal
->ExternalAddress
= onesIPv4Addr
;
591 traversal
->ExternalPort
= zeroIPPort
;
592 traversal
->Lifetime
= 0;
593 traversal
->Result
= mStatus_NoError
;
595 // set default lease if necessary
596 if (!traversal
->NATLease
) traversal
->NATLease
= NATMAP_DEFAULT_LEASE
;
598 #ifdef _LEGACY_NAT_TRAVERSAL_
599 mDNSPlatformMemZero(&traversal
->tcpInfo
, sizeof(traversal
->tcpInfo
));
600 #endif // _LEGACY_NAT_TRAVERSAL_
602 if (!m
->NATTraversals
) // If this is our first NAT request, kick off an address request too
604 m
->retryGetAddr
= m
->timenow
;
605 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
608 m
->NextScheduledNATOp
= m
->timenow
; // This will always trigger sending the packet ASAP, and generate client callback if necessary
610 *n
= traversal
; // Append new NATTraversalInfo to the end of our list
612 return(mStatus_NoError
);
615 // Must be called with the mDNS_Lock held
616 mDNSexport mStatus
mDNS_StopNATOperation_internal(mDNS
*m
, NATTraversalInfo
*traversal
)
618 mDNSBool unmap
= mDNStrue
;
620 NATTraversalInfo
**ptr
= &m
->NATTraversals
;
622 while (*ptr
&& *ptr
!= traversal
) ptr
=&(*ptr
)->next
;
623 if (*ptr
) *ptr
= (*ptr
)->next
; // If we found it, cut this NATTraversalInfo struct from our list
626 LogMsg("mDNS_StopNATOperation_internal: NATTraversalInfo %p not found in list", traversal
);
627 return(mStatus_BadReferenceErr
);
630 LogInfo("mDNS_StopNATOperation_internal %p %d %d %d %d", traversal
,
631 traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), mDNSVal16(traversal
->RequestedPort
), traversal
->NATLease
);
633 if (m
->CurrentNATTraversal
== traversal
)
634 m
->CurrentNATTraversal
= m
->CurrentNATTraversal
->next
;
636 if (traversal
->Protocol
)
637 for (p
= m
->NATTraversals
; p
; p
=p
->next
)
638 if (traversal
->Protocol
== p
->Protocol
&& mDNSSameIPPort(traversal
->IntPort
, p
->IntPort
))
640 if (!mDNSSameIPPort(traversal
->IntPort
, SSHPort
))
641 LogMsg("Warning: Removed port mapping request %p Prot %d Int %d TTL %d "
642 "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
643 traversal
, traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), traversal
->NATLease
,
644 p
, p
->Protocol
, mDNSVal16(p
->IntPort
), p
->NATLease
);
648 if (traversal
->ExpiryTime
&& unmap
)
650 traversal
->NATLease
= 0;
651 traversal
->retryInterval
= 0;
652 uDNS_SendNATMsg(m
, traversal
);
655 // 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
656 #ifdef _LEGACY_NAT_TRAVERSAL_
658 mStatus err
= LNT_UnmapPort(m
, traversal
);
659 if (err
) LogMsg("Legacy NAT Traversal - unmap request failed with error %d", err
);
661 #endif // _LEGACY_NAT_TRAVERSAL_
663 return(mStatus_NoError
);
666 mDNSexport mStatus
mDNS_StartNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
)
670 status
= mDNS_StartNATOperation_internal(m
, traversal
);
675 mDNSexport mStatus
mDNS_StopNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
)
679 status
= mDNS_StopNATOperation_internal(m
, traversal
);
684 // ***************************************************************************
685 #if COMPILER_LIKES_PRAGMA_MARK
687 #pragma mark - Long-Lived Queries
690 // Lock must be held -- otherwise m->timenow is undefined
691 mDNSlocal
void StartLLQPolling(mDNS
*const m
, DNSQuestion
*q
)
693 debugf("StartLLQPolling: %##s", q
->qname
.c
);
695 q
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
;
696 // We want to send our poll query ASAP, but the "+ 1" is because if we set the time to now,
697 // we risk causing spurious "SendQueries didn't send all its queries" log messages
698 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ 1;
699 SetNextQueryTime(m
, q
);
700 #if APPLE_OSX_mDNSResponder
701 UpdateAutoTunnelDomainStatuses(m
);
705 mDNSlocal mDNSu8
*putLLQ(DNSMessage
*const msg
, mDNSu8
*ptr
, const DNSQuestion
*const question
, const LLQOptData
*const data
)
708 ResourceRecord
*opt
= &rr
.resrec
;
711 //!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
712 ptr
= putQuestion(msg
, ptr
, msg
->data
+ AbsoluteMaxDNSMessageData
, &question
->qname
, question
->qtype
, question
->qclass
);
713 if (!ptr
) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL
; }
715 // locate OptRR if it exists, set pointer to end
716 // !!!KRS implement me
718 // format opt rr (fields not specified are zero-valued)
719 mDNS_SetupResourceRecord(&rr
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
720 opt
->rrclass
= NormalMaxDNSMessageData
;
721 opt
->rdlength
= sizeof(rdataOPT
); // One option in this OPT record
722 opt
->rdestimate
= sizeof(rdataOPT
);
724 optRD
= &rr
.resrec
.rdata
->u
.opt
[0];
725 optRD
->opt
= kDNSOpt_LLQ
;
726 optRD
->u
.llq
= *data
;
727 ptr
= PutResourceRecordTTLJumbo(msg
, ptr
, &msg
->h
.numAdditionals
, opt
, 0);
728 if (!ptr
) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL
; }
733 // Normally we'd just request event packets be sent directly to m->LLQNAT.ExternalPort, except...
734 // with LLQs over TLS/TCP we're doing a weird thing where instead of requesting packets be sent to ExternalAddress:ExternalPort
735 // we're requesting that packets be sent to ExternalPort, but at the source address of our outgoing TCP connection.
736 // Normally, after going through the NAT gateway, the source address of our outgoing TCP connection is the same as ExternalAddress,
737 // so this is fine, except when the TCP connection ends up going over a VPN tunnel instead.
738 // 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
739 // LLQ server to send events to us directly at port 5353 on that address, instead of at our mapped external NAT port.
741 mDNSlocal mDNSu16
GetLLQEventPort(const mDNS
*const m
, const mDNSAddr
*const dst
)
744 mDNSPlatformSourceAddrForDest(&src
, dst
);
745 //LogMsg("GetLLQEventPort: src %#a for dst %#a (%d)", &src, dst, mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : 0);
746 return(mDNSv4AddrIsRFC1918(&src
.ip
.v4
) ? mDNSVal16(m
->LLQNAT
.ExternalPort
) : mDNSVal16(MulticastDNSPort
));
749 // Normally called with llq set.
750 // May be called with llq NULL, when retransmitting a lost Challenge Response
751 mDNSlocal
void sendChallengeResponse(mDNS
*const m
, DNSQuestion
*const q
, const LLQOptData
*llq
)
753 mDNSu8
*responsePtr
= m
->omsg
.data
;
756 if (q
->tcp
) { LogMsg("sendChallengeResponse: ERROR!!: question %##s (%s) tcp non-NULL", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
758 if (PrivateQuery(q
)) { LogMsg("sendChallengeResponse: ERROR!!: Private Query %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
760 if (q
->ntries
++ == kLLQ_MAX_TRIES
)
762 LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s", kLLQ_MAX_TRIES
, q
->qname
.c
);
763 StartLLQPolling(m
,q
);
767 if (!llq
) // Retransmission: need to make a new LLQOptData
769 llqBuf
.vers
= kLLQ_Vers
;
770 llqBuf
.llqOp
= kLLQOp_Setup
;
771 llqBuf
.err
= LLQErr_NoError
; // Don't need to tell server UDP notification port when sending over UDP
773 llqBuf
.llqlease
= q
->ReqLease
;
777 q
->LastQTime
= m
->timenow
;
778 q
->ThisQInterval
= q
->tcp
? 0 : (kLLQ_INIT_RESEND
* q
->ntries
* mDNSPlatformOneSecond
); // If using TCP, don't need to retransmit
779 SetNextQueryTime(m
, q
);
781 // To simulate loss of challenge response packet, uncomment line below
782 //if (q->ntries == 1) return;
784 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, uQueryFlags
);
785 responsePtr
= putLLQ(&m
->omsg
, responsePtr
, q
, llq
);
788 mStatus err
= mDNSSendDNSMessage(m
, &m
->omsg
, responsePtr
, mDNSInterface_Any
, q
->LocalSocket
, &q
->servAddr
, q
->servPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
789 if (err
) { LogMsg("sendChallengeResponse: mDNSSendDNSMessage%s failed: %d", q
->tcp
? " (TCP)" : "", err
); }
791 else StartLLQPolling(m
,q
);
794 mDNSlocal
void SetLLQTimer(mDNS
*const m
, DNSQuestion
*const q
, const LLQOptData
*const llq
)
796 mDNSs32 lease
= (mDNSs32
)llq
->llqlease
* mDNSPlatformOneSecond
;
797 q
->ReqLease
= llq
->llqlease
;
798 q
->LastQTime
= m
->timenow
;
799 q
->expire
= m
->timenow
+ lease
;
800 q
->ThisQInterval
= lease
/2 + mDNSRandom(lease
/10);
801 debugf("SetLLQTimer setting %##s (%s) to %d %d", q
->qname
.c
, DNSTypeName(q
->qtype
), lease
/mDNSPlatformOneSecond
, q
->ThisQInterval
/mDNSPlatformOneSecond
);
802 SetNextQueryTime(m
, q
);
805 mDNSlocal
void recvSetupResponse(mDNS
*const m
, mDNSu8 rcode
, DNSQuestion
*const q
, const LLQOptData
*const llq
)
807 if (rcode
&& rcode
!= kDNSFlag1_RC_NXDomain
)
808 { LogMsg("ERROR: recvSetupResponse %##s (%s) - rcode && rcode != kDNSFlag1_RC_NXDomain", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
810 if (llq
->llqOp
!= kLLQOp_Setup
)
811 { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad op %d", q
->qname
.c
, DNSTypeName(q
->qtype
), llq
->llqOp
); return; }
813 if (llq
->vers
!= kLLQ_Vers
)
814 { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad vers %d", q
->qname
.c
, DNSTypeName(q
->qtype
), llq
->vers
); return; }
816 if (q
->state
== LLQ_InitialRequest
)
818 //LogInfo("Got LLQ_InitialRequest");
820 if (llq
->err
) { LogMsg("recvSetupResponse - received llq->err %d from server", llq
->err
); StartLLQPolling(m
,q
); return; }
822 if (q
->ReqLease
!= llq
->llqlease
)
823 debugf("recvSetupResponse: requested lease %lu, granted lease %lu", q
->ReqLease
, llq
->llqlease
);
825 // cache expiration in case we go to sleep before finishing setup
826 q
->ReqLease
= llq
->llqlease
;
827 q
->expire
= m
->timenow
+ ((mDNSs32
)llq
->llqlease
* mDNSPlatformOneSecond
);
830 q
->state
= LLQ_SecondaryRequest
;
832 q
->ntries
= 0; // first attempt to send response
833 sendChallengeResponse(m
, q
, llq
);
835 else if (q
->state
== LLQ_SecondaryRequest
)
837 //LogInfo("Got LLQ_SecondaryRequest");
839 // Fix this immediately if not sooner. Copy the id from the LLQOptData into our DNSQuestion struct. This is only
840 // an issue for private LLQs, because we skip parts 2 and 3 of the handshake. This is related to a bigger
841 // problem of the current implementation of TCP LLQ setup: we're not handling state transitions correctly
842 // if the server sends back SERVFULL or STATIC.
845 LogInfo("Private LLQ_SecondaryRequest; copying id %08X%08X", llq
->id
.l
[0], llq
->id
.l
[1]);
849 if (llq
->err
) { LogMsg("ERROR: recvSetupResponse %##s (%s) code %d from server", q
->qname
.c
, DNSTypeName(q
->qtype
), llq
->err
); StartLLQPolling(m
,q
); return; }
850 if (!mDNSSameOpaque64(&q
->id
, &llq
->id
))
851 { LogMsg("recvSetupResponse - ID changed. discarding"); return; } // this can happen rarely (on packet loss + reordering)
852 q
->state
= LLQ_Established
;
854 SetLLQTimer(m
, q
, llq
);
855 #if APPLE_OSX_mDNSResponder
856 UpdateAutoTunnelDomainStatuses(m
);
861 mDNSexport uDNS_LLQType
uDNS_recvLLQResponse(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
862 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, DNSQuestion
**matchQuestion
)
864 DNSQuestion pktQ
, *q
;
865 if (msg
->h
.numQuestions
&& getQuestion(msg
, msg
->data
, end
, 0, &pktQ
))
867 const rdataOPT
*opt
= GetLLQOptData(m
, msg
, end
);
869 for (q
= m
->Questions
; q
; q
= q
->next
)
871 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->qtype
== pktQ
.qtype
&& q
->qnamehash
== pktQ
.qnamehash
&& SameDomainName(&q
->qname
, &pktQ
.qname
))
873 debugf("uDNS_recvLLQResponse found %##s (%s) %d %#a %#a %X %X %X %X %d",
874 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->state
, srcaddr
, &q
->servAddr
,
875 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);
876 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
));
877 if (q
->state
== LLQ_Poll
&& mDNSSameOpaque16(msg
->h
.id
, q
->TargetQID
))
879 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
881 // Don't reset the state to IntialRequest as we may write that to the dynamic store
882 // and PrefPane might wrongly think that we are "Starting" instead of "Polling". If
883 // we are in polling state because of NAT-PMP disabled or DoubleNAT, next LLQNATCallback
884 // would kick us back to LLQInitialRequest. So, resetting the state here may not be useful.
886 // If we have a good NAT (neither NAT-PMP disabled nor Double-NAT), then we should not be
887 // possibly in polling state. To be safe, we want to retry from the start in that case
888 // as there may not be another LLQNATCallback
890 // NOTE: We can be in polling state if we cannot resolve the SOA record i.e, servAddr is set to
891 // all ones. In that case, we would set it in LLQ_InitialRequest as it overrides the NAT-PMP or
893 if (!mDNSAddressIsOnes(&q
->servAddr
) && !mDNSIPPortIsZero(m
->LLQNAT
.ExternalPort
) &&
896 debugf("uDNS_recvLLQResponse got poll response; moving to LLQ_InitialRequest for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
897 q
->state
= LLQ_InitialRequest
;
899 q
->servPort
= zeroIPPort
; // Clear servPort so that startLLQHandshake will retry the GetZoneData processing
900 q
->ThisQInterval
= LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10); // Retry LLQ setup in approx 15 minutes
901 q
->LastQTime
= m
->timenow
;
902 SetNextQueryTime(m
, q
);
904 return uDNS_LLQ_Entire
; // uDNS_LLQ_Entire means flush stale records; assume a large effective TTL
906 // 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
907 else if (opt
&& q
->state
== LLQ_Established
&& opt
->u
.llq
.llqOp
== kLLQOp_Event
&& mDNSSameOpaque64(&opt
->u
.llq
.id
, &q
->id
))
910 //debugf("Sending LLQ ack for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
911 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, ResponseFlags
);
912 ackEnd
= putLLQ(&m
->omsg
, m
->omsg
.data
, q
, &opt
->u
.llq
);
913 if (ackEnd
) mDNSSendDNSMessage(m
, &m
->omsg
, ackEnd
, mDNSInterface_Any
, q
->LocalSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
914 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
915 debugf("uDNS_LLQ_Events: q->state == LLQ_Established msg->h.id %d q->TargetQID %d", mDNSVal16(msg
->h
.id
), mDNSVal16(q
->TargetQID
));
917 return uDNS_LLQ_Events
;
919 if (opt
&& mDNSSameOpaque16(msg
->h
.id
, q
->TargetQID
))
921 if (q
->state
== LLQ_Established
&& opt
->u
.llq
.llqOp
== kLLQOp_Refresh
&& mDNSSameOpaque64(&opt
->u
.llq
.id
, &q
->id
) && msg
->h
.numAdditionals
&& !msg
->h
.numAnswers
)
923 if (opt
->u
.llq
.err
!= LLQErr_NoError
) LogMsg("recvRefreshReply: received error %d from server", opt
->u
.llq
.err
);
926 //LogInfo("Received refresh confirmation ntries %d for %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
927 // If we're waiting to go to sleep, then this LLQ deletion may have been the thing
928 // we were waiting for, so schedule another check to see if we can sleep now.
929 if (opt
->u
.llq
.llqlease
== 0 && m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
930 GrantCacheExtensions(m
, q
, opt
->u
.llq
.llqlease
);
931 SetLLQTimer(m
, q
, &opt
->u
.llq
);
934 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
936 return uDNS_LLQ_Ignore
;
938 if (q
->state
< LLQ_Established
&& mDNSSameAddress(srcaddr
, &q
->servAddr
))
940 LLQ_State oldstate
= q
->state
;
941 recvSetupResponse(m
, msg
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
, q
, &opt
->u
.llq
);
942 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
943 // We have a protocol anomaly here in the LLQ definition.
944 // Both the challenge packet from the server and the ack+answers packet have opt->u.llq.llqOp == kLLQOp_Setup.
945 // However, we need to treat them differently:
946 // The challenge packet has no answers in it, and tells us nothing about whether our cache entries
947 // are still valid, so this packet should not cause us to do anything that messes with our cache.
948 // The ack+answers packet gives us the whole truth, so we should handle it by updating our cache
949 // to match the answers in the packet, and only the answers in the packet.
951 return (oldstate
== LLQ_SecondaryRequest
? uDNS_LLQ_Entire
: uDNS_LLQ_Ignore
);
956 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
958 *matchQuestion
= mDNSNULL
;
962 // Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
963 struct TCPSocket_struct
{ TCPSocketFlags flags
; /* ... */ };
965 // tcpCallback is called to handle events (e.g. connection opening and data reception) on TCP connections for
966 // Private DNS operations -- private queries, private LLQs, private record updates and private service updates
967 mDNSlocal
void tcpCallback(TCPSocket
*sock
, void *context
, mDNSBool ConnectionEstablished
, mStatus err
)
969 tcpInfo_t
*tcpInfo
= (tcpInfo_t
*)context
;
970 mDNSBool closed
= mDNSfalse
;
971 mDNS
*m
= tcpInfo
->m
;
972 DNSQuestion
*const q
= tcpInfo
->question
;
973 tcpInfo_t
**backpointer
=
975 tcpInfo
->rr
? &tcpInfo
->rr
->tcp
: mDNSNULL
;
976 if (backpointer
&& *backpointer
!= tcpInfo
)
977 LogMsg("tcpCallback: %d backpointer %p incorrect tcpInfo %p question %p rr %p",
978 mDNSPlatformTCPGetFD(tcpInfo
->sock
), *backpointer
, tcpInfo
, q
, tcpInfo
->rr
);
982 if (ConnectionEstablished
)
984 mDNSu8
*end
= ((mDNSu8
*) &tcpInfo
->request
) + tcpInfo
->requestLen
;
985 DomainAuthInfo
*AuthInfo
;
987 // Defensive coding for <rdar://problem/5546824> Crash in mDNSResponder at GetAuthInfoForName_internal + 366
988 // 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
989 if (tcpInfo
->rr
&& tcpInfo
->rr
->resrec
.name
!= &tcpInfo
->rr
->namestorage
)
990 LogMsg("tcpCallback: ERROR: tcpInfo->rr->resrec.name %p != &tcpInfo->rr->namestorage %p",
991 tcpInfo
->rr
->resrec
.name
, &tcpInfo
->rr
->namestorage
);
992 if (tcpInfo
->rr
&& tcpInfo
->rr
->resrec
.name
!= &tcpInfo
->rr
->namestorage
) return;
994 AuthInfo
= tcpInfo
->rr
? GetAuthInfoForName(m
, tcpInfo
->rr
->resrec
.name
) : mDNSNULL
;
996 // connection is established - send the message
997 if (q
&& q
->LongLived
&& q
->state
== LLQ_Established
)
999 // Lease renewal over TCP, resulting from opening a TCP connection in sendLLQRefresh
1000 end
= ((mDNSu8
*) &tcpInfo
->request
) + tcpInfo
->requestLen
;
1002 else if (q
&& q
->LongLived
&& q
->state
!= LLQ_Poll
&& !mDNSIPPortIsZero(m
->LLQNAT
.ExternalPort
) && !mDNSIPPortIsZero(q
->servPort
))
1005 // If we have a NAT port mapping, ExternalPort is the external port
1006 // If we have a routable address so we don't need a port mapping, ExternalPort is the same as our own internal port
1007 // If we need a NAT port mapping but can't get one, then ExternalPort is zero
1008 LLQOptData llqData
; // set llq rdata
1009 llqData
.vers
= kLLQ_Vers
;
1010 llqData
.llqOp
= kLLQOp_Setup
;
1011 llqData
.err
= GetLLQEventPort(m
, &tcpInfo
->Addr
); // We're using TCP; tell server what UDP port to send notifications to
1012 LogInfo("tcpCallback: eventPort %d", llqData
.err
);
1013 llqData
.id
= zeroOpaque64
;
1014 llqData
.llqlease
= kLLQ_DefLease
;
1015 InitializeDNSMessage(&tcpInfo
->request
.h
, q
->TargetQID
, uQueryFlags
);
1016 end
= putLLQ(&tcpInfo
->request
, tcpInfo
->request
.data
, q
, &llqData
);
1017 if (!end
) { LogMsg("ERROR: tcpCallback - putLLQ"); err
= mStatus_UnknownErr
; goto exit
; }
1018 AuthInfo
= q
->AuthInfo
; // Need to add TSIG to this message
1019 q
->ntries
= 0; // Reset ntries so that tcp/tls connection failures don't affect sendChallengeResponse failures
1023 // LLQ Polling mode or non-LLQ uDNS over TCP
1024 InitializeDNSMessage(&tcpInfo
->request
.h
, q
->TargetQID
, (DNSSECQuestion(q
) ? DNSSecQFlags
: uQueryFlags
));
1025 end
= putQuestion(&tcpInfo
->request
, tcpInfo
->request
.data
, tcpInfo
->request
.data
+ AbsoluteMaxDNSMessageData
, &q
->qname
, q
->qtype
, q
->qclass
);
1026 if (DNSSECQuestion(q
) && q
->qDNSServer
&& !q
->qDNSServer
->cellIntf
)
1027 end
= putDNSSECOption(&tcpInfo
->request
, end
, tcpInfo
->request
.data
+ AbsoluteMaxDNSMessageData
);
1029 AuthInfo
= q
->AuthInfo
; // Need to add TSIG to this message
1032 err
= mDNSSendDNSMessage(m
, &tcpInfo
->request
, end
, mDNSInterface_Any
, mDNSNULL
, &tcpInfo
->Addr
, tcpInfo
->Port
, sock
, AuthInfo
, mDNSfalse
);
1033 if (err
) { debugf("ERROR: tcpCallback: mDNSSendDNSMessage - %d", err
); err
= mStatus_UnknownErr
; goto exit
; }
1035 // Record time we sent this question
1039 q
->LastQTime
= m
->timenow
;
1040 if (q
->ThisQInterval
< (256 * mDNSPlatformOneSecond
)) // Now we have a TCP connection open, make sure we wait at least 256 seconds before retrying
1041 q
->ThisQInterval
= (256 * mDNSPlatformOneSecond
);
1042 SetNextQueryTime(m
, q
);
1049 if (tcpInfo
->nread
< 2) // First read the two-byte length preceeding the DNS message
1051 mDNSu8
*lenptr
= (mDNSu8
*)&tcpInfo
->replylen
;
1052 n
= mDNSPlatformReadTCP(sock
, lenptr
+ tcpInfo
->nread
, 2 - tcpInfo
->nread
, &closed
);
1055 LogMsg("ERROR: tcpCallback - attempt to read message length failed (%d)", n
);
1056 err
= mStatus_ConnFailed
;
1061 // It's perfectly fine for this socket to close after the first reply. The server might
1062 // be sending gratuitous replies using UDP and doesn't have a need to leave the TCP socket open.
1063 // We'll only log this event if we've never received a reply before.
1064 // BIND 9 appears to close an idle connection after 30 seconds.
1065 if (tcpInfo
->numReplies
== 0)
1067 LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo
->nread
);
1068 err
= mStatus_ConnFailed
;
1073 // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1074 // over this tcp connection. That is, we only track whether we've received at least one response
1075 // which may have been to a previous request sent over this tcp connection.
1076 if (backpointer
) *backpointer
= mDNSNULL
; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1077 DisposeTCPConn(tcpInfo
);
1082 tcpInfo
->nread
+= n
;
1083 if (tcpInfo
->nread
< 2) goto exit
;
1085 tcpInfo
->replylen
= (mDNSu16
)((mDNSu16
)lenptr
[0] << 8 | lenptr
[1]);
1086 if (tcpInfo
->replylen
< sizeof(DNSMessageHeader
))
1087 { LogMsg("ERROR: tcpCallback - length too short (%d bytes)", tcpInfo
->replylen
); err
= mStatus_UnknownErr
; goto exit
; }
1089 tcpInfo
->reply
= mDNSPlatformMemAllocate(tcpInfo
->replylen
);
1090 if (!tcpInfo
->reply
) { LogMsg("ERROR: tcpCallback - malloc failed"); err
= mStatus_NoMemoryErr
; goto exit
; }
1093 n
= mDNSPlatformReadTCP(sock
, ((char *)tcpInfo
->reply
) + (tcpInfo
->nread
- 2), tcpInfo
->replylen
- (tcpInfo
->nread
- 2), &closed
);
1097 LogMsg("ERROR: tcpCallback - read returned %d", n
);
1098 err
= mStatus_ConnFailed
;
1103 if (tcpInfo
->numReplies
== 0)
1105 LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo
->nread
);
1106 err
= mStatus_ConnFailed
;
1111 // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1112 // over this tcp connection. That is, we only track whether we've received at least one response
1113 // which may have been to a previous request sent over this tcp connection.
1114 if (backpointer
) *backpointer
= mDNSNULL
; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1115 DisposeTCPConn(tcpInfo
);
1120 tcpInfo
->nread
+= n
;
1122 if ((tcpInfo
->nread
- 2) == tcpInfo
->replylen
)
1125 DNSMessage
*reply
= tcpInfo
->reply
;
1126 mDNSu8
*end
= (mDNSu8
*)tcpInfo
->reply
+ tcpInfo
->replylen
;
1127 mDNSAddr Addr
= tcpInfo
->Addr
;
1128 mDNSIPPort Port
= tcpInfo
->Port
;
1129 mDNSIPPort srcPort
= zeroIPPort
;
1130 tcpInfo
->numReplies
++;
1131 tcpInfo
->reply
= mDNSNULL
; // Detach reply buffer from tcpInfo_t, to make sure client callback can't cause it to be disposed
1133 tcpInfo
->replylen
= 0;
1135 // If we're going to dispose this connection, do it FIRST, before calling client callback
1136 // Note: Sleep code depends on us clearing *backpointer here -- it uses the clearing of rr->tcp
1137 // as the signal that the DNS deregistration operation with the server has completed, and the machine may now sleep
1138 // If we clear the tcp pointer in the question, mDNSCoreReceiveResponse cannot find a matching question. Hence
1139 // we store the minimal information i.e., the source port of the connection in the question itself.
1140 // Dereference sock before it is disposed in DisposeTCPConn below.
1142 if (sock
->flags
& kTCPSocketFlags_UseTLS
) tls
= mDNStrue
;
1143 else tls
= mDNSfalse
;
1145 if (q
&& q
->tcp
) {srcPort
= q
->tcp
->SrcPort
; q
->tcpSrcPort
= srcPort
;}
1148 if (!q
|| !q
->LongLived
|| m
->SleepState
)
1149 { *backpointer
= mDNSNULL
; DisposeTCPConn(tcpInfo
); }
1151 mDNSCoreReceive(m
, reply
, end
, &Addr
, Port
, tls
? (mDNSAddr
*)1 : mDNSNULL
, srcPort
, 0);
1152 // USE CAUTION HERE: Invoking mDNSCoreReceive may have caused the environment to change, including canceling this operation itself
1154 mDNSPlatformMemFree(reply
);
1163 // Clear client backpointer FIRST -- that way if one of the callbacks cancels its operation
1164 // we won't end up double-disposing our tcpInfo_t
1165 if (backpointer
) *backpointer
= mDNSNULL
;
1167 mDNS_Lock(m
); // Need to grab the lock to get m->timenow
1171 if (q
->ThisQInterval
== 0)
1173 // 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.
1174 // Note that ThisQInterval is also zero when sendChallengeResponse resends the LLQ request on an extant TCP/TLS connection.
1175 q
->LastQTime
= m
->timenow
;
1178 // We didn't get the chance to send our request packet before the TCP/TLS connection failed.
1179 // We want to retry quickly, but want to back off exponentially in case the server is having issues.
1180 // Since ThisQInterval was 0, we can't just multiply by QuestionIntervalStep, we must track the number
1181 // of TCP/TLS connection failures using ntries.
1182 mDNSu32 count
= q
->ntries
+ 1; // want to wait at least 1 second before retrying
1184 q
->ThisQInterval
= InitialQuestionInterval
;
1186 for (; count
; count
--)
1187 q
->ThisQInterval
*= QuestionIntervalStep
;
1189 if (q
->ThisQInterval
> LLQ_POLL_INTERVAL
)
1190 q
->ThisQInterval
= LLQ_POLL_INTERVAL
;
1194 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
);
1198 q
->ThisQInterval
= MAX_UCAST_POLL_INTERVAL
;
1199 LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
);
1201 SetNextQueryTime(m
, q
);
1203 else if (NextQSendTime(q
) - m
->timenow
> (q
->LongLived
? LLQ_POLL_INTERVAL
: MAX_UCAST_POLL_INTERVAL
))
1205 // If we get an error and our next scheduled query for this question is more than the max interval from now,
1206 // reset the next query to ensure we wait no longer the maximum interval from now before trying again.
1207 q
->LastQTime
= m
->timenow
;
1208 q
->ThisQInterval
= q
->LongLived
? LLQ_POLL_INTERVAL
: MAX_UCAST_POLL_INTERVAL
;
1209 SetNextQueryTime(m
, q
);
1210 LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
);
1213 // We're about to dispose of the TCP connection, so we must reset the state to retry over TCP/TLS
1214 // because sendChallengeResponse will send the query via UDP if we don't have a tcp pointer.
1215 // Resetting to LLQ_InitialRequest will cause uDNS_CheckCurrentQuestion to call startLLQHandshake, which
1216 // will attempt to establish a new tcp connection.
1217 if (q
->LongLived
&& q
->state
== LLQ_SecondaryRequest
)
1218 q
->state
= LLQ_InitialRequest
;
1220 // ConnFailed may happen if the server sends a TCP reset or TLS fails, in which case we want to retry establishing the LLQ
1221 // quickly rather than switching to polling mode. This case is handled by the above code to set q->ThisQInterval just above.
1222 // If the error isn't ConnFailed, then the LLQ is in bad shape, so we switch to polling mode.
1223 if (err
!= mStatus_ConnFailed
)
1225 if (q
->LongLived
&& q
->state
!= LLQ_Poll
) StartLLQPolling(m
, q
);
1231 DisposeTCPConn(tcpInfo
);
1235 mDNSlocal tcpInfo_t
*MakeTCPConn(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
1236 TCPSocketFlags flags
, const mDNSAddr
*const Addr
, const mDNSIPPort Port
, domainname
*hostname
,
1237 DNSQuestion
*const question
, AuthRecord
*const rr
)
1240 mDNSIPPort srcport
= zeroIPPort
;
1242 mDNSBool useBackgroundTrafficClass
;
1244 useBackgroundTrafficClass
= question
? question
->UseBrackgroundTrafficClass
: mDNSfalse
;
1246 if ((flags
& kTCPSocketFlags_UseTLS
) && (!hostname
|| !hostname
->c
[0]))
1247 { LogMsg("MakeTCPConn: TLS connection being setup with NULL hostname"); return mDNSNULL
; }
1249 info
= (tcpInfo_t
*)mDNSPlatformMemAllocate(sizeof(tcpInfo_t
));
1250 if (!info
) { LogMsg("ERROR: MakeTCP - memallocate failed"); return(mDNSNULL
); }
1251 mDNSPlatformMemZero(info
, sizeof(tcpInfo_t
));
1254 info
->sock
= mDNSPlatformTCPSocket(m
, flags
, &srcport
, useBackgroundTrafficClass
);
1255 info
->requestLen
= 0;
1256 info
->question
= question
;
1260 info
->reply
= mDNSNULL
;
1263 info
->numReplies
= 0;
1264 info
->SrcPort
= srcport
;
1268 info
->requestLen
= (int) (end
- ((mDNSu8
*)msg
));
1269 mDNSPlatformMemCopy(&info
->request
, msg
, info
->requestLen
);
1272 if (!info
->sock
) { LogMsg("MakeTCPConn: unable to create TCP socket"); mDNSPlatformMemFree(info
); return(mDNSNULL
); }
1273 err
= mDNSPlatformTCPConnect(info
->sock
, Addr
, Port
, hostname
, (question
? question
->InterfaceID
: mDNSNULL
), tcpCallback
, info
);
1275 // Probably suboptimal here.
1276 // Instead of returning mDNSNULL here on failure, we should probably invoke the callback with an error code.
1277 // That way clients can put all the error handling and retry/recovery code in one place,
1278 // instead of having to handle immediate errors in one place and async errors in another.
1279 // Also: "err == mStatus_ConnEstablished" probably never happens.
1281 // Don't need to log "connection failed" in customer builds -- it happens quite often during sleep, wake, configuration changes, etc.
1282 if (err
== mStatus_ConnEstablished
) { tcpCallback(info
->sock
, info
, mDNStrue
, mStatus_NoError
); }
1283 else if (err
!= mStatus_ConnPending
) { LogInfo("MakeTCPConn: connection failed"); DisposeTCPConn(info
); return(mDNSNULL
); }
1287 mDNSexport
void DisposeTCPConn(struct tcpInfo_t
*tcp
)
1289 mDNSPlatformTCPCloseConnection(tcp
->sock
);
1290 if (tcp
->reply
) mDNSPlatformMemFree(tcp
->reply
);
1291 mDNSPlatformMemFree(tcp
);
1294 // Lock must be held
1295 mDNSexport
void startLLQHandshake(mDNS
*m
, DNSQuestion
*q
)
1297 if (mDNSIPv4AddressIsOnes(m
->LLQNAT
.ExternalAddress
))
1299 LogInfo("startLLQHandshake: waiting for NAT status for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
1300 q
->ThisQInterval
= LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10); // Retry in approx 15 minutes
1301 q
->LastQTime
= m
->timenow
;
1302 SetNextQueryTime(m
, q
);
1306 // Either we don't have NAT-PMP support (ExternalPort is zero) or behind a Double NAT that may or
1307 // may not have NAT-PMP support (NATResult is non-zero)
1308 if (mDNSIPPortIsZero(m
->LLQNAT
.ExternalPort
) || m
->LLQNAT
.Result
)
1310 LogInfo("startLLQHandshake: Cannot receive inbound packets; will poll for %##s (%s) External Port %d, NAT Result %d",
1311 q
->qname
.c
, DNSTypeName(q
->qtype
), mDNSVal16(m
->LLQNAT
.ExternalPort
), m
->LLQNAT
.Result
);
1312 StartLLQPolling(m
, q
);
1316 if (mDNSIPPortIsZero(q
->servPort
))
1318 debugf("startLLQHandshake: StartGetZoneData for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
1319 q
->ThisQInterval
= LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10); // Retry in approx 15 minutes
1320 q
->LastQTime
= m
->timenow
;
1321 SetNextQueryTime(m
, q
);
1322 q
->servAddr
= zeroAddr
;
1323 // We know q->servPort is zero because of check above
1324 if (q
->nta
) CancelGetZoneData(m
, q
->nta
);
1325 q
->nta
= StartGetZoneData(m
, &q
->qname
, ZoneServiceLLQ
, LLQGotZoneData
, q
);
1329 if (PrivateQuery(q
))
1331 if (q
->tcp
) LogInfo("startLLQHandshake: Disposing existing TCP connection for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
1332 if (q
->tcp
) { DisposeTCPConn(q
->tcp
); q
->tcp
= mDNSNULL
; }
1335 // Normally we lookup the zone data and then call this function. And we never free the zone data
1336 // for "PrivateQuery". But sometimes this can happen due to some race conditions. When we
1337 // switch networks, we might end up "Polling" the network e.g., we are behind a Double NAT.
1338 // When we poll, we free the zone information as we send the query to the server (See
1339 // PrivateQueryGotZoneData). The NAT callback (LLQNATCallback) may happen soon after that. If we
1340 // are still behind Double NAT, we would have returned early in this function. But we could
1341 // have switched to a network with no NATs and we should get the zone data again.
1342 LogInfo("startLLQHandshake: nta is NULL for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
1343 q
->nta
= StartGetZoneData(m
, &q
->qname
, ZoneServiceLLQ
, LLQGotZoneData
, q
);
1346 else if (!q
->nta
->Host
.c
[0])
1348 // This should not happen. If it happens, we print a log and MakeTCPConn will fail if it can't find a hostname
1349 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
);
1351 q
->tcp
= MakeTCPConn(m
, mDNSNULL
, mDNSNULL
, kTCPSocketFlags_UseTLS
, &q
->servAddr
, q
->servPort
, &q
->nta
->Host
, q
, mDNSNULL
);
1353 q
->ThisQInterval
= mDNSPlatformOneSecond
* 5; // If TCP failed (transient networking glitch) try again in five seconds
1356 q
->state
= LLQ_SecondaryRequest
; // Right now, for private DNS, we skip the four-way LLQ handshake
1357 q
->ReqLease
= kLLQ_DefLease
;
1358 q
->ThisQInterval
= 0;
1360 q
->LastQTime
= m
->timenow
;
1361 SetNextQueryTime(m
, q
);
1365 debugf("startLLQHandshake: m->AdvertisedV4 %#a%s Server %#a:%d%s %##s (%s)",
1366 &m
->AdvertisedV4
, mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
) ? " (RFC 1918)" : "",
1367 &q
->servAddr
, mDNSVal16(q
->servPort
), mDNSAddrIsRFC1918(&q
->servAddr
) ? " (RFC 1918)" : "",
1368 q
->qname
.c
, DNSTypeName(q
->qtype
));
1370 if (q
->ntries
++ >= kLLQ_MAX_TRIES
)
1372 LogMsg("startLLQHandshake: %d failed attempts for LLQ %##s Polling.", kLLQ_MAX_TRIES
, q
->qname
.c
);
1373 StartLLQPolling(m
, q
);
1381 llqData
.vers
= kLLQ_Vers
;
1382 llqData
.llqOp
= kLLQOp_Setup
;
1383 llqData
.err
= LLQErr_NoError
; // Don't need to tell server UDP notification port when sending over UDP
1384 llqData
.id
= zeroOpaque64
;
1385 llqData
.llqlease
= kLLQ_DefLease
;
1387 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, uQueryFlags
);
1388 end
= putLLQ(&m
->omsg
, m
->omsg
.data
, q
, &llqData
);
1389 if (!end
) { LogMsg("ERROR: startLLQHandshake - putLLQ"); StartLLQPolling(m
,q
); return; }
1391 mDNSSendDNSMessage(m
, &m
->omsg
, end
, mDNSInterface_Any
, q
->LocalSocket
, &q
->servAddr
, q
->servPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
1393 // update question state
1394 q
->state
= LLQ_InitialRequest
;
1395 q
->ReqLease
= kLLQ_DefLease
;
1396 q
->ThisQInterval
= (kLLQ_INIT_RESEND
* mDNSPlatformOneSecond
);
1397 q
->LastQTime
= m
->timenow
;
1398 SetNextQueryTime(m
, q
);
1403 // forward declaration so GetServiceTarget can do reverse lookup if needed
1404 mDNSlocal
void GetStaticHostname(mDNS
*m
);
1406 mDNSexport
const domainname
*GetServiceTarget(mDNS
*m
, AuthRecord
*const rr
)
1408 debugf("GetServiceTarget %##s", rr
->resrec
.name
->c
);
1410 if (!rr
->AutoTarget
) // If not automatically tracking this host's current name, just return the existing target
1411 return(&rr
->resrec
.rdata
->u
.srv
.target
);
1414 #if APPLE_OSX_mDNSResponder
1415 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
1416 if (AuthInfo
&& AuthInfo
->AutoTunnel
)
1418 StartServerTunnel(m
, AuthInfo
);
1419 if (AuthInfo
->AutoTunnelHostRecord
.namestorage
.c
[0] == 0) return(mDNSNULL
);
1420 debugf("GetServiceTarget: Returning %##s", AuthInfo
->AutoTunnelHostRecord
.namestorage
.c
);
1421 return(&AuthInfo
->AutoTunnelHostRecord
.namestorage
);
1424 #endif // APPLE_OSX_mDNSResponder
1426 const int srvcount
= CountLabels(rr
->resrec
.name
);
1427 HostnameInfo
*besthi
= mDNSNULL
, *hi
;
1429 for (hi
= m
->Hostnames
; hi
; hi
= hi
->next
)
1430 if (hi
->arv4
.state
== regState_Registered
|| hi
->arv4
.state
== regState_Refresh
||
1431 hi
->arv6
.state
== regState_Registered
|| hi
->arv6
.state
== regState_Refresh
)
1433 int x
, hostcount
= CountLabels(&hi
->fqdn
);
1434 for (x
= hostcount
< srvcount
? hostcount
: srvcount
; x
> 0 && x
> best
; x
--)
1435 if (SameDomainName(SkipLeadingLabels(rr
->resrec
.name
, srvcount
- x
), SkipLeadingLabels(&hi
->fqdn
, hostcount
- x
)))
1436 { best
= x
; besthi
= hi
; }
1439 if (besthi
) return(&besthi
->fqdn
);
1441 if (m
->StaticHostname
.c
[0]) return(&m
->StaticHostname
);
1442 else GetStaticHostname(m
); // asynchronously do reverse lookup for primary IPv4 address
1443 LogInfo("GetServiceTarget: Returning NULL for %s", ARDisplayString(m
, rr
));
1448 mDNSlocal
const domainname
*PUBLIC_UPDATE_SERVICE_TYPE
= (const domainname
*)"\x0B_dns-update" "\x04_udp";
1449 mDNSlocal
const domainname
*PUBLIC_LLQ_SERVICE_TYPE
= (const domainname
*)"\x08_dns-llq" "\x04_udp";
1451 mDNSlocal
const domainname
*PRIVATE_UPDATE_SERVICE_TYPE
= (const domainname
*)"\x0F_dns-update-tls" "\x04_tcp";
1452 mDNSlocal
const domainname
*PRIVATE_QUERY_SERVICE_TYPE
= (const domainname
*)"\x0E_dns-query-tls" "\x04_tcp";
1453 mDNSlocal
const domainname
*PRIVATE_LLQ_SERVICE_TYPE
= (const domainname
*)"\x0C_dns-llq-tls" "\x04_tcp";
1455 #define ZoneDataSRV(X) ( \
1456 (X)->ZoneService == ZoneServiceUpdate ? ((X)->ZonePrivate ? PRIVATE_UPDATE_SERVICE_TYPE : PUBLIC_UPDATE_SERVICE_TYPE) : \
1457 (X)->ZoneService == ZoneServiceQuery ? ((X)->ZonePrivate ? PRIVATE_QUERY_SERVICE_TYPE : (const domainname*)"" ) : \
1458 (X)->ZoneService == ZoneServiceLLQ ? ((X)->ZonePrivate ? PRIVATE_LLQ_SERVICE_TYPE : PUBLIC_LLQ_SERVICE_TYPE ) : (const domainname*)"")
1460 // Forward reference: GetZoneData_StartQuery references GetZoneData_QuestionCallback, and
1461 // GetZoneData_QuestionCallback calls GetZoneData_StartQuery
1462 mDNSlocal mStatus
GetZoneData_StartQuery(mDNS
*const m
, ZoneData
*zd
, mDNSu16 qtype
);
1464 // GetZoneData_QuestionCallback is called from normal client callback context (core API calls allowed)
1465 mDNSlocal
void GetZoneData_QuestionCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
1467 ZoneData
*zd
= (ZoneData
*)question
->QuestionContext
;
1469 debugf("GetZoneData_QuestionCallback: %s %s", AddRecord
? "Add" : "Rmv", RRDisplayString(m
, answer
));
1471 if (!AddRecord
) return; // Don't care about REMOVE events
1472 if (AddRecord
== QC_addnocache
&& answer
->rdlength
== 0) return; // Don't care about transient failure indications
1473 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
1475 if (answer
->rrtype
== kDNSType_SOA
)
1477 debugf("GetZoneData GOT SOA %s", RRDisplayString(m
, answer
));
1478 mDNS_StopQuery(m
, question
);
1479 if (question
->ThisQInterval
!= -1)
1480 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->ThisQInterval
);
1481 if (answer
->rdlength
)
1483 AssignDomainName(&zd
->ZoneName
, answer
->name
);
1484 zd
->ZoneClass
= answer
->rrclass
;
1485 AssignDomainName(&zd
->question
.qname
, &zd
->ZoneName
);
1486 GetZoneData_StartQuery(m
, zd
, kDNSType_SRV
);
1488 else if (zd
->CurrentSOA
->c
[0])
1490 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName(m
, zd
->CurrentSOA
);
1491 if (AuthInfo
&& AuthInfo
->AutoTunnel
)
1493 // To keep the load on the server down, we don't chop down on
1494 // SOA lookups for AutoTunnels
1495 LogInfo("GetZoneData_QuestionCallback: not chopping labels for %##s", zd
->CurrentSOA
->c
);
1496 zd
->ZoneDataCallback(m
, mStatus_NoSuchNameErr
, zd
);
1500 zd
->CurrentSOA
= (domainname
*)(zd
->CurrentSOA
->c
+ zd
->CurrentSOA
->c
[0]+1);
1501 AssignDomainName(&zd
->question
.qname
, zd
->CurrentSOA
);
1502 GetZoneData_StartQuery(m
, zd
, kDNSType_SOA
);
1507 LogInfo("GetZoneData recursed to root label of %##s without finding SOA", zd
->ChildName
.c
);
1508 zd
->ZoneDataCallback(m
, mStatus_NoSuchNameErr
, zd
);
1511 else if (answer
->rrtype
== kDNSType_SRV
)
1513 debugf("GetZoneData GOT SRV %s", RRDisplayString(m
, answer
));
1514 mDNS_StopQuery(m
, question
);
1515 if (question
->ThisQInterval
!= -1)
1516 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->ThisQInterval
);
1517 // Right now we don't want to fail back to non-encrypted operations
1518 // If the AuthInfo has the AutoTunnel field set, then we want private or nothing
1519 // <rdar://problem/5687667> BTMM: Don't fallback to unencrypted operations when SRV lookup fails
1521 if (!answer
->rdlength
&& zd
->ZonePrivate
&& zd
->ZoneService
!= ZoneServiceQuery
)
1523 zd
->ZonePrivate
= mDNSfalse
; // Causes ZoneDataSRV() to yield a different SRV name when building the query
1524 GetZoneData_StartQuery(m
, zd
, kDNSType_SRV
); // Try again, non-private this time
1529 if (answer
->rdlength
)
1531 AssignDomainName(&zd
->Host
, &answer
->rdata
->u
.srv
.target
);
1532 zd
->Port
= answer
->rdata
->u
.srv
.port
;
1533 AssignDomainName(&zd
->question
.qname
, &zd
->Host
);
1534 GetZoneData_StartQuery(m
, zd
, kDNSType_A
);
1538 zd
->ZonePrivate
= mDNSfalse
;
1540 zd
->Port
= zeroIPPort
;
1541 zd
->Addr
= zeroAddr
;
1542 zd
->ZoneDataCallback(m
, mStatus_NoError
, zd
);
1546 else if (answer
->rrtype
== kDNSType_A
)
1548 debugf("GetZoneData GOT A %s", RRDisplayString(m
, answer
));
1549 mDNS_StopQuery(m
, question
);
1550 if (question
->ThisQInterval
!= -1)
1551 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->ThisQInterval
);
1552 zd
->Addr
.type
= mDNSAddrType_IPv4
;
1553 zd
->Addr
.ip
.v4
= (answer
->rdlength
== 4) ? answer
->rdata
->u
.ipv4
: zerov4Addr
;
1554 // In order to simulate firewalls blocking our outgoing TCP connections, returning immediate ICMP errors or TCP resets,
1555 // the code below will make us try to connect to loopback, resulting in an immediate "port unreachable" failure.
1556 // This helps us test to make sure we handle this case gracefully
1557 // <rdar://problem/5607082> BTMM: mDNSResponder taking 100 percent CPU after upgrading to 10.5.1
1559 zd
->Addr
.ip
.v4
.b
[0] = 127;
1560 zd
->Addr
.ip
.v4
.b
[1] = 0;
1561 zd
->Addr
.ip
.v4
.b
[2] = 0;
1562 zd
->Addr
.ip
.v4
.b
[3] = 1;
1564 // The caller needs to free the memory when done with zone data
1565 zd
->ZoneDataCallback(m
, mStatus_NoError
, zd
);
1569 // GetZoneData_StartQuery is called from normal client context (lock not held, or client callback)
1570 mDNSlocal mStatus
GetZoneData_StartQuery(mDNS
*const m
, ZoneData
*zd
, mDNSu16 qtype
)
1572 if (qtype
== kDNSType_SRV
)
1574 AssignDomainName(&zd
->question
.qname
, ZoneDataSRV(zd
));
1575 AppendDomainName(&zd
->question
.qname
, &zd
->ZoneName
);
1576 debugf("lookupDNSPort %##s", zd
->question
.qname
.c
);
1579 // CancelGetZoneData can get called at any time. We should stop the question if it has not been
1580 // stopped already. A value of -1 for ThisQInterval indicates that the question is not active
1582 zd
->question
.ThisQInterval
= -1;
1583 zd
->question
.InterfaceID
= mDNSInterface_Any
;
1584 zd
->question
.flags
= 0;
1585 zd
->question
.Target
= zeroAddr
;
1586 //zd->question.qname.c[0] = 0; // Already set
1587 zd
->question
.qtype
= qtype
;
1588 zd
->question
.qclass
= kDNSClass_IN
;
1589 zd
->question
.LongLived
= mDNSfalse
;
1590 zd
->question
.ExpectUnique
= mDNStrue
;
1591 zd
->question
.ForceMCast
= mDNSfalse
;
1592 zd
->question
.ReturnIntermed
= mDNStrue
;
1593 zd
->question
.SuppressUnusable
= mDNSfalse
;
1594 zd
->question
.SearchListIndex
= 0;
1595 zd
->question
.AppendSearchDomains
= 0;
1596 zd
->question
.RetryWithSearchDomains
= mDNSfalse
;
1597 zd
->question
.TimeoutQuestion
= 0;
1598 zd
->question
.WakeOnResolve
= 0;
1599 zd
->question
.UseBrackgroundTrafficClass
= mDNSfalse
;
1600 zd
->question
.ValidationRequired
= 0;
1601 zd
->question
.ValidatingResponse
= 0;
1602 zd
->question
.qnameOrig
= mDNSNULL
;
1603 zd
->question
.QuestionCallback
= GetZoneData_QuestionCallback
;
1604 zd
->question
.QuestionContext
= zd
;
1606 //LogMsg("GetZoneData_StartQuery %##s (%s) %p", zd->question.qname.c, DNSTypeName(zd->question.qtype), zd->question.Private);
1607 return(mDNS_StartQuery(m
, &zd
->question
));
1610 // StartGetZoneData is an internal routine (i.e. must be called with the lock already held)
1611 mDNSexport ZoneData
*StartGetZoneData(mDNS
*const m
, const domainname
*const name
, const ZoneService target
, ZoneDataCallback callback
, void *ZoneDataContext
)
1613 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName_internal(m
, name
);
1614 int initialskip
= (AuthInfo
&& AuthInfo
->AutoTunnel
) ? DomainNameLength(name
) - DomainNameLength(&AuthInfo
->domain
) : 0;
1615 ZoneData
*zd
= (ZoneData
*)mDNSPlatformMemAllocate(sizeof(ZoneData
));
1616 if (!zd
) { LogMsg("ERROR: StartGetZoneData - mDNSPlatformMemAllocate failed"); return mDNSNULL
; }
1617 mDNSPlatformMemZero(zd
, sizeof(ZoneData
));
1618 AssignDomainName(&zd
->ChildName
, name
);
1619 zd
->ZoneService
= target
;
1620 zd
->CurrentSOA
= (domainname
*)(&zd
->ChildName
.c
[initialskip
]);
1621 zd
->ZoneName
.c
[0] = 0;
1624 zd
->Port
= zeroIPPort
;
1625 zd
->Addr
= zeroAddr
;
1626 zd
->ZonePrivate
= AuthInfo
&& AuthInfo
->AutoTunnel
? mDNStrue
: mDNSfalse
;
1627 zd
->ZoneDataCallback
= callback
;
1628 zd
->ZoneDataContext
= ZoneDataContext
;
1630 zd
->question
.QuestionContext
= zd
;
1632 mDNS_DropLockBeforeCallback(); // GetZoneData_StartQuery expects to be called from a normal callback, so we emulate that here
1633 if (AuthInfo
&& AuthInfo
->AutoTunnel
&& !mDNSIPPortIsZero(AuthInfo
->port
))
1635 LogInfo("StartGetZoneData: Bypassing SOA, SRV query for %##s", AuthInfo
->domain
.c
);
1636 // We bypass SOA and SRV queries if we know the hostname and port already from the configuration.
1637 // Today this is only true for AutoTunnel. As we bypass, we need to infer a few things:
1639 // 1. Zone name is the same as the AuthInfo domain
1640 // 2. ZoneClass is kDNSClass_IN which should be a safe assumption
1642 // If we want to make this bypass mechanism work for non-AutoTunnels also, (1) has to hold
1643 // good. Otherwise, it has to be configured also.
1645 AssignDomainName(&zd
->ZoneName
, &AuthInfo
->domain
);
1646 zd
->ZoneClass
= kDNSClass_IN
;
1647 AssignDomainName(&zd
->Host
, &AuthInfo
->hostname
);
1648 zd
->Port
= AuthInfo
->port
;
1649 AssignDomainName(&zd
->question
.qname
, &zd
->Host
);
1650 GetZoneData_StartQuery(m
, zd
, kDNSType_A
);
1654 if (AuthInfo
&& AuthInfo
->AutoTunnel
) LogInfo("StartGetZoneData: Not Bypassing SOA, SRV query for %##s", AuthInfo
->domain
.c
);
1655 AssignDomainName(&zd
->question
.qname
, zd
->CurrentSOA
);
1656 GetZoneData_StartQuery(m
, zd
, kDNSType_SOA
);
1658 mDNS_ReclaimLockAfterCallback();
1663 // Returns if the question is a GetZoneData question. These questions are special in
1664 // that they are created internally while resolving a private query or LLQs.
1665 mDNSexport mDNSBool
IsGetZoneDataQuestion(DNSQuestion
*q
)
1667 if (q
->QuestionCallback
== GetZoneData_QuestionCallback
) return(mDNStrue
);
1668 else return(mDNSfalse
);
1671 // GetZoneData queries are a special case -- even if we have a key for them, we don't do them privately,
1672 // because that would result in an infinite loop (i.e. to do a private query we first need to get
1673 // the _dns-query-tls SRV record for the zone, and we can't do *that* privately because to do so
1674 // we'd need to already know the _dns-query-tls SRV record.
1675 // Also, as a general rule, we never do SOA queries privately
1676 mDNSexport DomainAuthInfo
*GetAuthInfoForQuestion(mDNS
*m
, const DNSQuestion
*const q
) // Must be called with lock held
1678 if (q
->QuestionCallback
== GetZoneData_QuestionCallback
) return(mDNSNULL
);
1679 if (q
->qtype
== kDNSType_SOA
) return(mDNSNULL
);
1680 return(GetAuthInfoForName_internal(m
, &q
->qname
));
1683 // ***************************************************************************
1684 #if COMPILER_LIKES_PRAGMA_MARK
1685 #pragma mark - host name and interface management
1688 mDNSlocal
void SendRecordRegistration(mDNS
*const m
, AuthRecord
*rr
);
1689 mDNSlocal
void SendRecordDeregistration(mDNS
*m
, AuthRecord
*rr
);
1690 mDNSlocal mDNSBool
IsRecordMergeable(mDNS
*const m
, AuthRecord
*rr
, mDNSs32 time
);
1692 // When this function is called, service record is already deregistered. We just
1693 // have to deregister the PTR and TXT records.
1694 mDNSlocal
void UpdateAllServiceRecords(mDNS
*const m
, AuthRecord
*rr
, mDNSBool reg
)
1696 AuthRecord
*r
, *srvRR
;
1698 if (rr
->resrec
.rrtype
!= kDNSType_SRV
) { LogMsg("UpdateAllServiceRecords:ERROR!! ResourceRecord not a service record %s", ARDisplayString(m
, rr
)); return; }
1700 if (reg
&& rr
->state
== regState_NoTarget
) { LogMsg("UpdateAllServiceRecords:ERROR!! SRV record %s in noTarget state during registration", ARDisplayString(m
, rr
)); return; }
1702 LogInfo("UpdateAllServiceRecords: ResourceRecord %s", ARDisplayString(m
, rr
));
1704 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
1706 if (!AuthRecord_uDNS(r
)) continue;
1708 if (r
->resrec
.rrtype
== kDNSType_PTR
)
1709 srvRR
= r
->Additional1
;
1710 else if (r
->resrec
.rrtype
== kDNSType_TXT
)
1711 srvRR
= r
->DependentOn
;
1712 if (srvRR
&& srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
1713 LogMsg("UpdateAllServiceRecords: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
1718 LogInfo("UpdateAllServiceRecords: deregistering %s", ARDisplayString(m
, r
));
1719 r
->SRVChanged
= mDNStrue
;
1720 r
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1721 r
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
1722 r
->state
= regState_DeregPending
;
1726 // Clearing SRVchanged is a safety measure. If our pevious dereg never
1727 // came back and we had a target change, we are starting fresh
1728 r
->SRVChanged
= mDNSfalse
;
1729 // if it is already registered or in the process of registering, then don't
1730 // bother re-registering. This happens today for non-BTMM domains where the
1731 // TXT and PTR get registered before SRV records because of the delay in
1732 // getting the port mapping. There is no point in re-registering the TXT
1734 if ((r
->state
== regState_Registered
) ||
1735 (r
->state
== regState_Pending
&& r
->nta
&& !mDNSIPv4AddressIsZero(r
->nta
->Addr
.ip
.v4
)))
1736 LogInfo("UpdateAllServiceRecords: not registering %s, state %d", ARDisplayString(m
, r
), r
->state
);
1739 LogInfo("UpdateAllServiceRecords: registering %s, state %d", ARDisplayString(m
, r
), r
->state
);
1740 ActivateUnicastRegistration(m
, r
);
1747 // Called in normal client context (lock not held)
1748 // Currently only supports SRV records for nat mapping
1749 mDNSlocal
void CompleteRecordNatMap(mDNS
*m
, NATTraversalInfo
*n
)
1751 const domainname
*target
;
1753 AuthRecord
*rr
= (AuthRecord
*)n
->clientContext
;
1754 debugf("SRVNatMap complete %.4a IntPort %u ExternalPort %u NATLease %u", &n
->ExternalAddress
, mDNSVal16(n
->IntPort
), mDNSVal16(n
->ExternalPort
), n
->NATLease
);
1756 if (!rr
) { LogMsg("CompleteRecordNatMap called with unknown AuthRecord object"); return; }
1757 if (!n
->NATLease
) { LogMsg("CompleteRecordNatMap No NATLease for %s", ARDisplayString(m
, rr
)); return; }
1759 if (rr
->resrec
.rrtype
!= kDNSType_SRV
) {LogMsg("CompleteRecordNatMap: Not a service record %s", ARDisplayString(m
, rr
)); return; }
1761 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) { LogInfo("CompleteRecordNatMap called for %s, Service deregistering", ARDisplayString(m
, rr
)); return; }
1763 if (rr
->state
== regState_DeregPending
) { LogInfo("CompleteRecordNatMap called for %s, record in DeregPending", ARDisplayString(m
, rr
)); return; }
1765 // As we free the zone info after registering/deregistering with the server (See hndlRecordUpdateReply),
1766 // we need to restart the get zone data and nat mapping request to get the latest mapping result as we can't handle it
1767 // at this moment. Restart from the beginning.
1768 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
1770 LogInfo("CompleteRecordNatMap called for %s but no zone information!", ARDisplayString(m
, rr
));
1771 // We need to clear out the NATinfo state so that it will result in re-acquiring the mapping
1772 // and hence this callback called again.
1773 if (rr
->NATinfo
.clientContext
)
1775 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1776 rr
->NATinfo
.clientContext
= mDNSNULL
;
1778 rr
->state
= regState_Pending
;
1779 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1780 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
1785 // Reevaluate the target always as Target could have changed while
1786 // we were getting the port mapping (See UpdateOneSRVRecord)
1787 target
= GetServiceTarget(m
, rr
);
1788 srvt
= GetRRDomainNameTarget(&rr
->resrec
);
1789 if (!target
|| target
->c
[0] == 0 || mDNSIPPortIsZero(n
->ExternalPort
))
1791 if (target
&& target
->c
[0])
1792 LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target
->c
, rr
->resrec
.name
->c
, mDNSVal16(n
->ExternalPort
));
1794 LogInfo("CompleteRecordNatMap - no target for %##s, ExternalPort %d", rr
->resrec
.name
->c
, mDNSVal16(n
->ExternalPort
));
1795 if (srvt
) srvt
->c
[0] = 0;
1796 rr
->state
= regState_NoTarget
;
1797 rr
->resrec
.rdlength
= rr
->resrec
.rdestimate
= 0;
1799 UpdateAllServiceRecords(m
, rr
, mDNSfalse
);
1802 LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target
->c
, rr
->resrec
.name
->c
, mDNSVal16(n
->ExternalPort
));
1803 // This function might get called multiple times during a network transition event. Previosuly, we could
1804 // have put the SRV record in NoTarget state above and deregistered all the other records. When this
1805 // function gets called again with a non-zero ExternalPort, we need to set the target and register the
1806 // other records again.
1807 if (srvt
&& !SameDomainName(srvt
, target
))
1809 AssignDomainName(srvt
, target
);
1810 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
1813 // SRVChanged is set when when the target of the SRV record changes (See UpdateOneSRVRecord).
1814 // As a result of the target change, we might register just that SRV Record if it was
1815 // previously registered and we have a new target OR deregister SRV (and the associated
1816 // PTR/TXT records) if we don't have a target anymore. When we get a response from the server,
1817 // SRVChanged state tells that we registered/deregistered because of a target change
1818 // and hence handle accordingly e.g., if we deregistered, put the records in NoTarget state OR
1819 // if we registered then put it in Registered state.
1821 // Here, we are registering all the records again from the beginning. Treat this as first time
1822 // registration rather than a temporary target change.
1823 rr
->SRVChanged
= mDNSfalse
;
1825 // We want IsRecordMergeable to check whether it is a record whose update can be
1826 // sent with others. We set the time before we call IsRecordMergeable, so that
1827 // it does not fail this record based on time. We are interested in other checks
1829 rr
->state
= regState_Pending
;
1830 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1831 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
1832 if (IsRecordMergeable(m
, rr
, m
->timenow
+ MERGE_DELAY_TIME
))
1833 // Delay the record registration by MERGE_DELAY_TIME so that we can merge them
1835 rr
->LastAPTime
+= MERGE_DELAY_TIME
;
1837 // We call this always even though it may not be necessary always e.g., normal registration
1838 // process where TXT and PTR gets registered followed by the SRV record after it gets
1839 // the port mapping. In that case, UpdateAllServiceRecords handles the optimization. The
1840 // update of TXT and PTR record is required if we entered noTargetState before as explained
1842 UpdateAllServiceRecords(m
, rr
, mDNStrue
);
1845 mDNSlocal
void StartRecordNatMap(mDNS
*m
, AuthRecord
*rr
)
1850 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
1852 LogInfo("StartRecordNatMap: Resource Record %##s type %d, not supported", rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
1855 p
= rr
->resrec
.name
->c
;
1856 //Assume <Service Instance>.<App Protocol>.<Transport protocol>.<Name>
1857 // Skip the first two labels to get to the transport protocol
1858 if (p
[0]) p
+= 1 + p
[0];
1859 if (p
[0]) p
+= 1 + p
[0];
1860 if (SameDomainLabel(p
, (mDNSu8
*)"\x4" "_tcp")) protocol
= NATOp_MapTCP
;
1861 else if (SameDomainLabel(p
, (mDNSu8
*)"\x4" "_udp")) protocol
= NATOp_MapUDP
;
1862 else { LogMsg("StartRecordNatMap: could not determine transport protocol of service %##s", rr
->resrec
.name
->c
); return; }
1864 //LogMsg("StartRecordNatMap: clientContext %p IntPort %d srv.port %d %s",
1865 // rr->NATinfo.clientContext, mDNSVal16(rr->NATinfo.IntPort), mDNSVal16(rr->resrec.rdata->u.srv.port), ARDisplayString(m, rr));
1866 if (rr
->NATinfo
.clientContext
) mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1867 rr
->NATinfo
.Protocol
= protocol
;
1869 // Shouldn't be trying to set IntPort here --
1870 // BuildUpdateMessage overwrites srs->RR_SRV.resrec.rdata->u.srv.port with external (mapped) port number
1871 rr
->NATinfo
.IntPort
= rr
->resrec
.rdata
->u
.srv
.port
;
1872 rr
->NATinfo
.RequestedPort
= rr
->resrec
.rdata
->u
.srv
.port
;
1873 rr
->NATinfo
.NATLease
= 0; // Request default lease
1874 rr
->NATinfo
.clientCallback
= CompleteRecordNatMap
;
1875 rr
->NATinfo
.clientContext
= rr
;
1876 mDNS_StartNATOperation_internal(m
, &rr
->NATinfo
);
1879 // Unlink an Auth Record from the m->ResourceRecords list.
1880 // When a resource record enters regState_NoTarget initially, mDNS_Register_internal
1881 // does not initialize completely e.g., it cannot check for duplicates etc. The resource
1882 // record is temporarily left in the ResourceRecords list so that we can initialize later
1883 // when the target is resolvable. Similarly, when host name changes, we enter regState_NoTarget
1884 // and we do the same.
1886 // This UnlinkResourceRecord routine is very worrying. It bypasses all the normal cleanup performed
1887 // by mDNS_Deregister_internal and just unceremoniously cuts the record from the active list.
1888 // This is why re-regsitering this record was producing syslog messages like this:
1889 // "Error! Tried to add a NAT traversal that's already in the active list"
1890 // Right now UnlinkResourceRecord is fortunately only called by RegisterAllServiceRecords,
1891 // which then immediately calls mDNS_Register_internal to re-register the record, which probably
1892 // masked more serious problems. Any other use of UnlinkResourceRecord is likely to lead to crashes.
1893 // For now we'll workaround that specific problem by explicitly calling mDNS_StopNATOperation_internal,
1894 // but long-term we should either stop cancelling the record registration and then re-registering it,
1895 // or if we really do need to do this for some reason it should be done via the usual
1896 // mDNS_Deregister_internal path instead of just cutting the record from the list.
1898 mDNSlocal mStatus
UnlinkResourceRecord(mDNS
*const m
, AuthRecord
*const rr
)
1900 AuthRecord
**list
= &m
->ResourceRecords
;
1901 while (*list
&& *list
!= rr
) list
= &(*list
)->next
;
1905 rr
->next
= mDNSNULL
;
1907 // Temporary workaround to cancel any active NAT mapping operation
1908 if (rr
->NATinfo
.clientContext
)
1910 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1911 rr
->NATinfo
.clientContext
= mDNSNULL
;
1912 if (rr
->resrec
.rrtype
== kDNSType_SRV
) rr
->resrec
.rdata
->u
.srv
.port
= rr
->NATinfo
.IntPort
;
1915 return(mStatus_NoError
);
1917 LogMsg("UnlinkResourceRecord:ERROR!! - no such active record %##s", rr
->resrec
.name
->c
);
1918 return(mStatus_NoSuchRecord
);
1921 // We need to go through mDNS_Register again as we did not complete the
1922 // full initialization last time e.g., duplicate checks.
1923 // After we register, we will be in regState_GetZoneData.
1924 mDNSlocal
void RegisterAllServiceRecords(mDNS
*const m
, AuthRecord
*rr
)
1926 LogInfo("RegisterAllServiceRecords: Service Record %##s", rr
->resrec
.name
->c
);
1927 // First Register the service record, we do this differently from other records because
1928 // when it entered NoTarget state, it did not go through complete initialization
1929 rr
->SRVChanged
= mDNSfalse
;
1930 UnlinkResourceRecord(m
, rr
);
1931 mDNS_Register_internal(m
, rr
);
1932 // Register the other records
1933 UpdateAllServiceRecords(m
, rr
, mDNStrue
);
1936 // Called with lock held
1937 mDNSlocal
void UpdateOneSRVRecord(mDNS
*m
, AuthRecord
*rr
)
1939 // Target change if:
1940 // We have a target and were previously waiting for one, or
1941 // We had a target and no longer do, or
1942 // The target has changed
1944 domainname
*curtarget
= &rr
->resrec
.rdata
->u
.srv
.target
;
1945 const domainname
*const nt
= GetServiceTarget(m
, rr
);
1946 const domainname
*const newtarget
= nt
? nt
: (domainname
*)"";
1947 mDNSBool TargetChanged
= (newtarget
->c
[0] && rr
->state
== regState_NoTarget
) || !SameDomainName(curtarget
, newtarget
);
1948 mDNSBool HaveZoneData
= rr
->nta
&& !mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
);
1950 // Nat state change if:
1951 // We were behind a NAT, and now we are behind a new NAT, or
1952 // We're not behind a NAT but our port was previously mapped to a different external port
1953 // We were not behind a NAT and now we are
1955 mDNSIPPort port
= rr
->resrec
.rdata
->u
.srv
.port
;
1956 mDNSBool NowNeedNATMAP
= (rr
->AutoTarget
== Target_AutoHostAndNATMAP
&& !mDNSIPPortIsZero(port
) && mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
) && rr
->nta
&& !mDNSAddrIsRFC1918(&rr
->nta
->Addr
));
1957 mDNSBool WereBehindNAT
= (rr
->NATinfo
.clientContext
!= mDNSNULL
);
1958 mDNSBool PortWasMapped
= (rr
->NATinfo
.clientContext
&& !mDNSSameIPPort(rr
->NATinfo
.RequestedPort
, port
)); // I think this is always false -- SC Sept 07
1959 mDNSBool NATChanged
= (!WereBehindNAT
&& NowNeedNATMAP
) || (!NowNeedNATMAP
&& PortWasMapped
);
1961 (void)HaveZoneData
; //unused
1963 LogInfo("UpdateOneSRVRecord: Resource Record %s TargetChanged %d, NewTarget %##s", ARDisplayString(m
, rr
), TargetChanged
, nt
->c
);
1965 debugf("UpdateOneSRVRecord: %##s newtarget %##s TargetChanged %d HaveZoneData %d port %d NowNeedNATMAP %d WereBehindNAT %d PortWasMapped %d NATChanged %d",
1966 rr
->resrec
.name
->c
, newtarget
,
1967 TargetChanged
, HaveZoneData
, mDNSVal16(port
), NowNeedNATMAP
, WereBehindNAT
, PortWasMapped
, NATChanged
);
1969 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
1970 LogMsg("UpdateOneSRVRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
1972 if (!TargetChanged
&& !NATChanged
) return;
1974 // If we are deregistering the record, then ignore any NAT/Target change.
1975 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1977 LogInfo("UpdateOneSRVRecord: Deregistering record, Ignoring TargetChanged %d, NATChanged %d for %##s, state %d", TargetChanged
, NATChanged
,
1978 rr
->resrec
.name
->c
, rr
->state
);
1983 LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, newtarget %##s", TargetChanged
, NATChanged
, rr
->resrec
.name
->c
, rr
->state
, newtarget
->c
);
1985 LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, null newtarget", TargetChanged
, NATChanged
, rr
->resrec
.name
->c
, rr
->state
);
1988 case regState_NATMap
:
1989 // In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
1990 // or is in the process of, or has already been, deregistered. This assumes that whenever we transition out
1991 // of this state, we need to look at the target again.
1994 case regState_UpdatePending
:
1995 // We are getting a Target change/NAT change while the SRV record is being updated ?
1996 // let us not do anything for now.
1999 case regState_NATError
:
2000 if (!NATChanged
) return;
2001 // if nat changed, register if we have a target (below)
2003 case regState_NoTarget
:
2004 if (!newtarget
->c
[0])
2006 LogInfo("UpdateOneSRVRecord: No target yet for Resource Record %s", ARDisplayString(m
, rr
));
2009 RegisterAllServiceRecords(m
, rr
);
2011 case regState_DeregPending
:
2012 // We are in DeregPending either because the service was deregistered from above or we handled
2013 // a NAT/Target change before and sent the deregistration below. There are a few race conditions
2016 // 1. We are handling a second NAT/Target change while the first dereg is in progress. It is possible
2017 // that first dereg never made it through because there was no network connectivity e.g., disconnecting
2018 // from network triggers this function due to a target change and later connecting to the network
2019 // retriggers this function but the deregistration never made it through yet. Just fall through.
2020 // If there is a target register otherwise deregister.
2022 // 2. While we sent the dereg during a previous NAT/Target change, uDNS_DeregisterRecord gets
2023 // called as part of service deregistration. When the response comes back, we call
2024 // CompleteDeregistration rather than handle NAT/Target change because the record is in
2025 // kDNSRecordTypeDeregistering state.
2027 // 3. If the upper layer deregisters the service, we check for kDNSRecordTypeDeregistering both
2028 // here in this function to avoid handling NAT/Target change and in hndlRecordUpdateReply to call
2029 // CompleteDeregistration instead of handling NAT/Target change. Hence, we are not concerned
2030 // about that case here.
2032 // We just handle case (1) by falling through
2033 case regState_Pending
:
2034 case regState_Refresh
:
2035 case regState_Registered
:
2036 // target or nat changed. deregister service. upon completion, we'll look for a new target
2037 rr
->SRVChanged
= mDNStrue
;
2038 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
2039 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
2040 if (newtarget
->c
[0])
2042 LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s, registering with new target %##s",
2043 rr
->resrec
.name
->c
, newtarget
->c
);
2044 rr
->state
= regState_Pending
;
2048 LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s de-registering", rr
->resrec
.name
->c
);
2049 rr
->state
= regState_DeregPending
;
2050 UpdateAllServiceRecords(m
, rr
, mDNSfalse
);
2053 case regState_Unregistered
:
2054 default: LogMsg("UpdateOneSRVRecord: Unknown state %d for %##s", rr
->state
, rr
->resrec
.name
->c
);
2058 mDNSexport
void UpdateAllSRVRecords(mDNS
*m
)
2060 m
->NextSRVUpdate
= 0;
2061 LogInfo("UpdateAllSRVRecords %d", m
->SleepState
);
2063 if (m
->CurrentRecord
)
2064 LogMsg("UpdateAllSRVRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2065 m
->CurrentRecord
= m
->ResourceRecords
;
2066 while (m
->CurrentRecord
)
2068 AuthRecord
*rptr
= m
->CurrentRecord
;
2069 m
->CurrentRecord
= m
->CurrentRecord
->next
;
2070 if (AuthRecord_uDNS(rptr
) && rptr
->resrec
.rrtype
== kDNSType_SRV
)
2071 UpdateOneSRVRecord(m
, rptr
);
2075 // Forward reference: AdvertiseHostname references HostnameCallback, and HostnameCallback calls AdvertiseHostname
2076 mDNSlocal
void HostnameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
2078 // Called in normal client context (lock not held)
2079 mDNSlocal
void hostnameGetPublicAddressCallback(mDNS
*m
, NATTraversalInfo
*n
)
2081 HostnameInfo
*h
= (HostnameInfo
*)n
->clientContext
;
2083 if (!h
) { LogMsg("RegisterHostnameRecord: registration cancelled"); return; }
2087 if (mDNSIPv4AddressIsZero(n
->ExternalAddress
) || mDNSv4AddrIsRFC1918(&n
->ExternalAddress
)) return;
2089 if (h
->arv4
.resrec
.RecordType
)
2091 if (mDNSSameIPv4Address(h
->arv4
.resrec
.rdata
->u
.ipv4
, n
->ExternalAddress
)) return; // If address unchanged, do nothing
2092 LogInfo("Updating hostname %p %##s IPv4 from %.4a to %.4a (NAT gateway's external address)",n
,
2093 h
->arv4
.resrec
.name
->c
, &h
->arv4
.resrec
.rdata
->u
.ipv4
, &n
->ExternalAddress
);
2094 mDNS_Deregister(m
, &h
->arv4
); // mStatus_MemFree callback will re-register with new address
2098 LogInfo("Advertising hostname %##s IPv4 %.4a (NAT gateway's external address)", h
->arv4
.resrec
.name
->c
, &n
->ExternalAddress
);
2099 h
->arv4
.resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
2100 h
->arv4
.resrec
.rdata
->u
.ipv4
= n
->ExternalAddress
;
2101 mDNS_Register(m
, &h
->arv4
);
2106 // register record or begin NAT traversal
2107 mDNSlocal
void AdvertiseHostname(mDNS
*m
, HostnameInfo
*h
)
2109 if (!mDNSIPv4AddressIsZero(m
->AdvertisedV4
.ip
.v4
) && h
->arv4
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2111 mDNS_SetupResourceRecord(&h
->arv4
, mDNSNULL
, mDNSInterface_Any
, kDNSType_A
, kHostNameTTL
, kDNSRecordTypeUnregistered
, AuthRecordAny
, HostnameCallback
, h
);
2112 AssignDomainName(&h
->arv4
.namestorage
, &h
->fqdn
);
2113 h
->arv4
.resrec
.rdata
->u
.ipv4
= m
->AdvertisedV4
.ip
.v4
;
2114 h
->arv4
.state
= regState_Unregistered
;
2115 if (mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
))
2117 // If we already have a NAT query active, stop it and restart it to make sure we get another callback
2118 if (h
->natinfo
.clientContext
) mDNS_StopNATOperation_internal(m
, &h
->natinfo
);
2119 h
->natinfo
.Protocol
= 0;
2120 h
->natinfo
.IntPort
= zeroIPPort
;
2121 h
->natinfo
.RequestedPort
= zeroIPPort
;
2122 h
->natinfo
.NATLease
= 0;
2123 h
->natinfo
.clientCallback
= hostnameGetPublicAddressCallback
;
2124 h
->natinfo
.clientContext
= h
;
2125 mDNS_StartNATOperation_internal(m
, &h
->natinfo
);
2129 LogInfo("Advertising hostname %##s IPv4 %.4a", h
->arv4
.resrec
.name
->c
, &m
->AdvertisedV4
.ip
.v4
);
2130 h
->arv4
.resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
2131 mDNS_Register_internal(m
, &h
->arv4
);
2135 if (!mDNSIPv6AddressIsZero(m
->AdvertisedV6
.ip
.v6
) && h
->arv6
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2137 mDNS_SetupResourceRecord(&h
->arv6
, mDNSNULL
, mDNSInterface_Any
, kDNSType_AAAA
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, HostnameCallback
, h
);
2138 AssignDomainName(&h
->arv6
.namestorage
, &h
->fqdn
);
2139 h
->arv6
.resrec
.rdata
->u
.ipv6
= m
->AdvertisedV6
.ip
.v6
;
2140 h
->arv6
.state
= regState_Unregistered
;
2141 LogInfo("Advertising hostname %##s IPv6 %.16a", h
->arv6
.resrec
.name
->c
, &m
->AdvertisedV6
.ip
.v6
);
2142 mDNS_Register_internal(m
, &h
->arv6
);
2146 mDNSlocal
void HostnameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
2148 HostnameInfo
*hi
= (HostnameInfo
*)rr
->RecordContext
;
2150 if (result
== mStatus_MemFree
)
2154 // If we're still in the Hostnames list, update to new address
2156 LogInfo("HostnameCallback: Got mStatus_MemFree for %p %p %s", hi
, rr
, ARDisplayString(m
, rr
));
2157 for (i
= m
->Hostnames
; i
; i
= i
->next
)
2158 if (rr
== &i
->arv4
|| rr
== &i
->arv6
)
2159 { mDNS_Lock(m
); AdvertiseHostname(m
, i
); mDNS_Unlock(m
); return; }
2161 // Else, we're not still in the Hostnames list, so free the memory
2162 if (hi
->arv4
.resrec
.RecordType
== kDNSRecordTypeUnregistered
&&
2163 hi
->arv6
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2165 if (hi
->natinfo
.clientContext
) mDNS_StopNATOperation_internal(m
, &hi
->natinfo
);
2166 hi
->natinfo
.clientContext
= mDNSNULL
;
2167 mDNSPlatformMemFree(hi
); // free hi when both v4 and v6 AuthRecs deallocated
2175 // don't unlink or free - we can retry when we get a new address/router
2176 if (rr
->resrec
.rrtype
== kDNSType_A
)
2177 LogMsg("HostnameCallback: Error %d for registration of %##s IP %.4a", result
, rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv4
);
2179 LogMsg("HostnameCallback: Error %d for registration of %##s IP %.16a", result
, rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv6
);
2180 if (!hi
) { mDNSPlatformMemFree(rr
); return; }
2181 if (rr
->state
!= regState_Unregistered
) LogMsg("Error: HostnameCallback invoked with error code for record not in regState_Unregistered!");
2183 if (hi
->arv4
.state
== regState_Unregistered
&&
2184 hi
->arv6
.state
== regState_Unregistered
)
2186 // only deliver status if both v4 and v6 fail
2187 rr
->RecordContext
= (void *)hi
->StatusContext
;
2188 if (hi
->StatusCallback
)
2189 hi
->StatusCallback(m
, rr
, result
); // client may NOT make API calls here
2190 rr
->RecordContext
= (void *)hi
;
2195 // register any pending services that require a target
2197 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2200 // Deliver success to client
2201 if (!hi
) { LogMsg("HostnameCallback invoked with orphaned address record"); return; }
2202 if (rr
->resrec
.rrtype
== kDNSType_A
)
2203 LogInfo("Registered hostname %##s IP %.4a", rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv4
);
2205 LogInfo("Registered hostname %##s IP %.16a", rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv6
);
2207 rr
->RecordContext
= (void *)hi
->StatusContext
;
2208 if (hi
->StatusCallback
)
2209 hi
->StatusCallback(m
, rr
, result
); // client may NOT make API calls here
2210 rr
->RecordContext
= (void *)hi
;
2213 mDNSlocal
void FoundStaticHostname(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2215 const domainname
*pktname
= &answer
->rdata
->u
.name
;
2216 domainname
*storedname
= &m
->StaticHostname
;
2217 HostnameInfo
*h
= m
->Hostnames
;
2221 if (answer
->rdlength
!= 0)
2222 LogInfo("FoundStaticHostname: question %##s -> answer %##s (%s)", question
->qname
.c
, answer
->rdata
->u
.name
.c
, AddRecord
? "ADD" : "RMV");
2224 LogInfo("FoundStaticHostname: question %##s -> answer NULL (%s)", question
->qname
.c
, AddRecord
? "ADD" : "RMV");
2226 if (AddRecord
&& answer
->rdlength
!= 0 && !SameDomainName(pktname
, storedname
))
2228 AssignDomainName(storedname
, pktname
);
2231 if (h
->arv4
.state
== regState_Pending
|| h
->arv4
.state
== regState_NATMap
|| h
->arv6
.state
== regState_Pending
)
2233 // 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
2234 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ 5 * mDNSPlatformOneSecond
);
2235 debugf("FoundStaticHostname: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
2241 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2244 else if (!AddRecord
&& SameDomainName(pktname
, storedname
))
2247 storedname
->c
[0] = 0;
2248 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2253 // Called with lock held
2254 mDNSlocal
void GetStaticHostname(mDNS
*m
)
2256 char buf
[MAX_REVERSE_MAPPING_NAME_V4
];
2257 DNSQuestion
*q
= &m
->ReverseMap
;
2258 mDNSu8
*ip
= m
->AdvertisedV4
.ip
.v4
.b
;
2261 if (m
->ReverseMap
.ThisQInterval
!= -1) return; // already running
2262 if (mDNSIPv4AddressIsZero(m
->AdvertisedV4
.ip
.v4
)) return;
2264 mDNSPlatformMemZero(q
, sizeof(*q
));
2265 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
2266 mDNS_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa.", ip
[3], ip
[2], ip
[1], ip
[0]);
2267 if (!MakeDomainNameFromDNSNameString(&q
->qname
, buf
)) { LogMsg("Error: GetStaticHostname - bad name %s", buf
); return; }
2269 q
->InterfaceID
= mDNSInterface_Any
;
2271 q
->Target
= zeroAddr
;
2272 q
->qtype
= kDNSType_PTR
;
2273 q
->qclass
= kDNSClass_IN
;
2274 q
->LongLived
= mDNSfalse
;
2275 q
->ExpectUnique
= mDNSfalse
;
2276 q
->ForceMCast
= mDNSfalse
;
2277 q
->ReturnIntermed
= mDNStrue
;
2278 q
->SuppressUnusable
= mDNSfalse
;
2279 q
->SearchListIndex
= 0;
2280 q
->AppendSearchDomains
= 0;
2281 q
->RetryWithSearchDomains
= mDNSfalse
;
2282 q
->TimeoutQuestion
= 0;
2283 q
->WakeOnResolve
= 0;
2284 q
->UseBrackgroundTrafficClass
= mDNSfalse
;
2285 q
->ValidationRequired
= 0;
2286 q
->ValidatingResponse
= 0;
2287 q
->qnameOrig
= mDNSNULL
;
2288 q
->QuestionCallback
= FoundStaticHostname
;
2289 q
->QuestionContext
= mDNSNULL
;
2291 LogInfo("GetStaticHostname: %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
2292 err
= mDNS_StartQuery_internal(m
, q
);
2293 if (err
) LogMsg("Error: GetStaticHostname - StartQuery returned error %d", err
);
2296 mDNSexport
void mDNS_AddDynDNSHostName(mDNS
*m
, const domainname
*fqdn
, mDNSRecordCallback
*StatusCallback
, const void *StatusContext
)
2298 HostnameInfo
**ptr
= &m
->Hostnames
;
2300 LogInfo("mDNS_AddDynDNSHostName %##s", fqdn
);
2302 while (*ptr
&& !SameDomainName(fqdn
, &(*ptr
)->fqdn
)) ptr
= &(*ptr
)->next
;
2303 if (*ptr
) { LogMsg("DynDNSHostName %##s already in list", fqdn
->c
); return; }
2305 // allocate and format new address record
2306 *ptr
= mDNSPlatformMemAllocate(sizeof(**ptr
));
2307 if (!*ptr
) { LogMsg("ERROR: mDNS_AddDynDNSHostName - malloc"); return; }
2309 mDNSPlatformMemZero(*ptr
, sizeof(**ptr
));
2310 AssignDomainName(&(*ptr
)->fqdn
, fqdn
);
2311 (*ptr
)->arv4
.state
= regState_Unregistered
;
2312 (*ptr
)->arv6
.state
= regState_Unregistered
;
2313 (*ptr
)->StatusCallback
= StatusCallback
;
2314 (*ptr
)->StatusContext
= StatusContext
;
2316 AdvertiseHostname(m
, *ptr
);
2319 mDNSexport
void mDNS_RemoveDynDNSHostName(mDNS
*m
, const domainname
*fqdn
)
2321 HostnameInfo
**ptr
= &m
->Hostnames
;
2323 LogInfo("mDNS_RemoveDynDNSHostName %##s", fqdn
);
2325 while (*ptr
&& !SameDomainName(fqdn
, &(*ptr
)->fqdn
)) ptr
= &(*ptr
)->next
;
2326 if (!*ptr
) LogMsg("mDNS_RemoveDynDNSHostName: no such domainname %##s", fqdn
->c
);
2329 HostnameInfo
*hi
= *ptr
;
2330 // We do it this way because, if we have no active v6 record, the "mDNS_Deregister_internal(m, &hi->arv4);"
2331 // below could free the memory, and we have to make sure we don't touch hi fields after that.
2332 mDNSBool f4
= hi
->arv4
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
&& hi
->arv4
.state
!= regState_Unregistered
;
2333 mDNSBool f6
= hi
->arv6
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
&& hi
->arv6
.state
!= regState_Unregistered
;
2334 if (f4
) LogInfo("mDNS_RemoveDynDNSHostName removing v4 %##s", fqdn
);
2335 if (f6
) LogInfo("mDNS_RemoveDynDNSHostName removing v6 %##s", fqdn
);
2336 *ptr
= (*ptr
)->next
; // unlink
2337 if (f4
) mDNS_Deregister_internal(m
, &hi
->arv4
, mDNS_Dereg_normal
);
2338 if (f6
) mDNS_Deregister_internal(m
, &hi
->arv6
, mDNS_Dereg_normal
);
2339 // When both deregistrations complete we'll free the memory in the mStatus_MemFree callback
2341 if (!m
->mDNS_busy
) LogMsg("mDNS_RemoveDynDNSHostName: ERROR: Lock not held");
2342 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2345 // Currently called without holding the lock
2346 // Maybe we should change that?
2347 mDNSexport
void mDNS_SetPrimaryInterfaceInfo(mDNS
*m
, const mDNSAddr
*v4addr
, const mDNSAddr
*v6addr
, const mDNSAddr
*router
)
2349 mDNSBool v4Changed
, v6Changed
, RouterChanged
;
2351 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
2352 LogMsg("mDNS_SetPrimaryInterfaceInfo: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
2354 if (v4addr
&& v4addr
->type
!= mDNSAddrType_IPv4
) { LogMsg("mDNS_SetPrimaryInterfaceInfo v4 address - incorrect type. Discarding. %#a", v4addr
); return; }
2355 if (v6addr
&& v6addr
->type
!= mDNSAddrType_IPv6
) { LogMsg("mDNS_SetPrimaryInterfaceInfo v6 address - incorrect type. Discarding. %#a", v6addr
); return; }
2356 if (router
&& router
->type
!= mDNSAddrType_IPv4
) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-v4 router. Discarding. %#a", router
); return; }
2360 v4Changed
= !mDNSSameIPv4Address(m
->AdvertisedV4
.ip
.v4
, v4addr
? v4addr
->ip
.v4
: zerov4Addr
);
2361 v6Changed
= !mDNSSameIPv6Address(m
->AdvertisedV6
.ip
.v6
, v6addr
? v6addr
->ip
.v6
: zerov6Addr
);
2362 RouterChanged
= !mDNSSameIPv4Address(m
->Router
.ip
.v4
, router
? router
->ip
.v4
: zerov4Addr
);
2364 if (v4addr
&& (v4Changed
|| RouterChanged
))
2365 debugf("mDNS_SetPrimaryInterfaceInfo: address changed from %#a to %#a", &m
->AdvertisedV4
, v4addr
);
2367 if (v4addr
) m
->AdvertisedV4
= *v4addr
;else m
->AdvertisedV4
.ip
.v4
= zerov4Addr
;
2368 if (v6addr
) m
->AdvertisedV6
= *v6addr
;else m
->AdvertisedV6
.ip
.v6
= zerov6Addr
;
2369 if (router
) m
->Router
= *router
;else m
->Router
.ip
.v4
= zerov4Addr
;
2370 // setting router to zero indicates that nat mappings must be reestablished when router is reset
2372 if (v4Changed
|| RouterChanged
|| v6Changed
)
2375 LogInfo("mDNS_SetPrimaryInterfaceInfo: %s%s%s%#a %#a %#a",
2376 v4Changed
? "v4Changed " : "",
2377 RouterChanged
? "RouterChanged " : "",
2378 v6Changed
? "v6Changed " : "", v4addr
, v6addr
, router
);
2380 for (i
= m
->Hostnames
; i
; i
= i
->next
)
2382 LogInfo("mDNS_SetPrimaryInterfaceInfo updating host name registrations for %##s", i
->fqdn
.c
);
2384 if (i
->arv4
.resrec
.RecordType
> kDNSRecordTypeDeregistering
&&
2385 !mDNSSameIPv4Address(i
->arv4
.resrec
.rdata
->u
.ipv4
, m
->AdvertisedV4
.ip
.v4
))
2387 LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m
, &i
->arv4
));
2388 mDNS_Deregister_internal(m
, &i
->arv4
, mDNS_Dereg_normal
);
2391 if (i
->arv6
.resrec
.RecordType
> kDNSRecordTypeDeregistering
&&
2392 !mDNSSameIPv6Address(i
->arv6
.resrec
.rdata
->u
.ipv6
, m
->AdvertisedV6
.ip
.v6
))
2394 LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m
, &i
->arv6
));
2395 mDNS_Deregister_internal(m
, &i
->arv6
, mDNS_Dereg_normal
);
2398 // AdvertiseHostname will only register new address records.
2399 // For records still in the process of deregistering it will ignore them, and let the mStatus_MemFree callback handle them.
2400 AdvertiseHostname(m
, i
);
2403 if (v4Changed
|| RouterChanged
)
2405 // If we have a non-zero IPv4 address, we should try immediately to see if we have a NAT gateway
2406 // If we have no IPv4 address, we don't want to be in quite such a hurry to report failures to our clients
2407 // <rdar://problem/6935929> Sleeping server sometimes briefly disappears over Back to My Mac after it wakes up
2408 m
->ExternalAddress
= zerov4Addr
;
2409 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
2410 m
->retryGetAddr
= m
->timenow
+ (v4addr
? 0 : mDNSPlatformOneSecond
* 5);
2411 m
->NextScheduledNATOp
= m
->timenow
;
2412 m
->LastNATMapResultCode
= NATErr_None
;
2413 #ifdef _LEGACY_NAT_TRAVERSAL_
2415 #endif // _LEGACY_NAT_TRAVERSAL_
2416 LogInfo("mDNS_SetPrimaryInterfaceInfo:%s%s: retryGetAddr in %d %d",
2417 v4Changed
? " v4Changed" : "",
2418 RouterChanged
? " RouterChanged" : "",
2419 m
->retryGetAddr
- m
->timenow
, m
->timenow
);
2422 if (m
->ReverseMap
.ThisQInterval
!= -1) mDNS_StopQuery_internal(m
, &m
->ReverseMap
);
2423 m
->StaticHostname
.c
[0] = 0;
2425 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2427 #if APPLE_OSX_mDNSResponder
2428 if (RouterChanged
) uuid_generate(m
->asl_uuid
);
2429 UpdateAutoTunnelDomainStatuses(m
);
2436 // ***************************************************************************
2437 #if COMPILER_LIKES_PRAGMA_MARK
2438 #pragma mark - Incoming Message Processing
2441 mDNSlocal mStatus
ParseTSIGError(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
, const domainname
*const displayname
)
2444 mStatus err
= mStatus_NoError
;
2447 ptr
= LocateAdditionals(msg
, end
);
2448 if (!ptr
) goto finish
;
2450 for (i
= 0; i
< msg
->h
.numAdditionals
; i
++)
2452 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
2453 if (!ptr
) goto finish
;
2454 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
)
2457 mDNSu8
*rd
= m
->rec
.r
.resrec
.rdata
->u
.data
;
2458 mDNSu8
*rdend
= rd
+ m
->rec
.r
.resrec
.rdlength
;
2459 int alglen
= DomainNameLengthLimit(&m
->rec
.r
.resrec
.rdata
->u
.name
, rdend
);
2460 if (alglen
> MAX_DOMAIN_NAME
) goto finish
;
2461 rd
+= alglen
; // algorithm name
2462 if (rd
+ 6 > rdend
) goto finish
;
2463 rd
+= 6; // 48-bit timestamp
2464 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2465 rd
+= sizeof(mDNSOpaque16
); // fudge
2466 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2467 macsize
= mDNSVal16(*(mDNSOpaque16
*)rd
);
2468 rd
+= sizeof(mDNSOpaque16
); // MAC size
2469 if (rd
+ macsize
> rdend
) goto finish
;
2471 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2472 rd
+= sizeof(mDNSOpaque16
); // orig id
2473 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2474 err
= mDNSVal16(*(mDNSOpaque16
*)rd
); // error code
2476 if (err
== TSIG_ErrBadSig
) { LogMsg("%##s: bad signature", displayname
->c
); err
= mStatus_BadSig
; }
2477 else if (err
== TSIG_ErrBadKey
) { LogMsg("%##s: bad key", displayname
->c
); err
= mStatus_BadKey
; }
2478 else if (err
== TSIG_ErrBadTime
) { LogMsg("%##s: bad time", displayname
->c
); err
= mStatus_BadTime
; }
2479 else if (err
) { LogMsg("%##s: unknown tsig error %d", displayname
->c
, err
); err
= mStatus_UnknownErr
; }
2482 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
2486 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
2490 mDNSlocal mStatus
checkUpdateResult(mDNS
*const m
, const domainname
*const displayname
, const mDNSu8 rcode
, const DNSMessage
*const msg
, const mDNSu8
*const end
)
2492 (void)msg
; // currently unused, needed for TSIG errors
2493 if (!rcode
) return mStatus_NoError
;
2494 else if (rcode
== kDNSFlag1_RC_YXDomain
)
2496 debugf("name in use: %##s", displayname
->c
);
2497 return mStatus_NameConflict
;
2499 else if (rcode
== kDNSFlag1_RC_Refused
)
2501 LogMsg("Update %##s refused", displayname
->c
);
2502 return mStatus_Refused
;
2504 else if (rcode
== kDNSFlag1_RC_NXRRSet
)
2506 LogMsg("Reregister refused (NXRRSET): %##s", displayname
->c
);
2507 return mStatus_NoSuchRecord
;
2509 else if (rcode
== kDNSFlag1_RC_NotAuth
)
2511 // TSIG errors should come with FormErr as per RFC 2845, but BIND 9 sends them with NotAuth so we look here too
2512 mStatus tsigerr
= ParseTSIGError(m
, msg
, end
, displayname
);
2515 LogMsg("Permission denied (NOAUTH): %##s", displayname
->c
);
2516 return mStatus_UnknownErr
;
2518 else return tsigerr
;
2520 else if (rcode
== kDNSFlag1_RC_FormErr
)
2522 mStatus tsigerr
= ParseTSIGError(m
, msg
, end
, displayname
);
2525 LogMsg("Format Error: %##s", displayname
->c
);
2526 return mStatus_UnknownErr
;
2528 else return tsigerr
;
2532 LogMsg("Update %##s failed with rcode %d", displayname
->c
, rcode
);
2533 return mStatus_UnknownErr
;
2537 // We add three Additional Records for unicast resource record registrations
2538 // which is a function of AuthInfo and AutoTunnel properties
2539 mDNSlocal mDNSu32
RRAdditionalSize(mDNS
*const m
, DomainAuthInfo
*AuthInfo
)
2541 mDNSu32 leaseSize
, hinfoSize
, tsigSize
;
2542 mDNSu32 rr_base_size
= 10; // type (2) class (2) TTL (4) rdlength (2)
2544 // OPT RR : Emptyname(.) + base size + rdataOPT
2545 leaseSize
= 1 + rr_base_size
+ sizeof(rdataOPT
);
2547 // HINFO: Resource Record Name + base size + RDATA
2548 // HINFO is added only for autotunnels
2550 if (AuthInfo
&& AuthInfo
->AutoTunnel
)
2551 hinfoSize
= (m
->hostlabel
.c
[0] + 1) + DomainNameLength(&AuthInfo
->domain
) +
2552 rr_base_size
+ (2 + m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0]);
2554 //TSIG: Resource Record Name + base size + RDATA
2556 // Algorithm name: hmac-md5.sig-alg.reg.int (8+7+3+3 + 5 bytes for length = 26 bytes)
2559 // Mac Size: 2 bytes
2566 if (AuthInfo
) tsigSize
= DomainNameLength(&AuthInfo
->keyname
) + rr_base_size
+ 58;
2568 return (leaseSize
+ hinfoSize
+ tsigSize
);
2571 //Note: Make sure that RREstimatedSize is updated accordingly if anything that is done here
2572 //would modify rdlength/rdestimate
2573 mDNSlocal mDNSu8
* BuildUpdateMessage(mDNS
*const m
, mDNSu8
*ptr
, AuthRecord
*rr
, mDNSu8
*limit
)
2575 //If this record is deregistering, then just send the deletion record
2576 if (rr
->state
== regState_DeregPending
)
2578 rr
->expire
= 0; // Indicate that we have no active registration any more
2579 ptr
= putDeletionRecordWithLimit(&m
->omsg
, ptr
, &rr
->resrec
, limit
);
2580 if (!ptr
) goto exit
;
2584 // This is a common function to both sending an update in a group or individual
2585 // records separately. Hence, we change the state here.
2586 if (rr
->state
== regState_Registered
) rr
->state
= regState_Refresh
;
2587 if (rr
->state
!= regState_Refresh
&& rr
->state
!= regState_UpdatePending
)
2588 rr
->state
= regState_Pending
;
2590 // For Advisory records like e.g., _services._dns-sd, which is shared, don't send goodbyes as multiple
2591 // host might be registering records and deregistering from one does not make sense
2592 if (rr
->resrec
.RecordType
!= kDNSRecordTypeAdvisory
) rr
->RequireGoodbye
= mDNStrue
;
2594 if ((rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHostAndNATMAP
) &&
2595 !mDNSIPPortIsZero(rr
->NATinfo
.ExternalPort
))
2597 rr
->resrec
.rdata
->u
.srv
.port
= rr
->NATinfo
.ExternalPort
;
2600 if (rr
->state
== regState_UpdatePending
)
2603 SetNewRData(&rr
->resrec
, rr
->OrigRData
, rr
->OrigRDLen
);
2604 if (!(ptr
= putDeletionRecordWithLimit(&m
->omsg
, ptr
, &rr
->resrec
, limit
))) goto exit
; // delete old rdata
2607 SetNewRData(&rr
->resrec
, rr
->InFlightRData
, rr
->InFlightRDLen
);
2608 if (!(ptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, ptr
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
))) goto exit
;
2612 if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
|| rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
2614 // KnownUnique : Delete any previous value
2615 // For Unicast registrations, we don't verify that it is unique, but set to verified and hence we want to
2616 // delete any previous value
2617 ptr
= putDeleteRRSetWithLimit(&m
->omsg
, ptr
, rr
->resrec
.name
, rr
->resrec
.rrtype
, limit
);
2618 if (!ptr
) goto exit
;
2620 else if (rr
->resrec
.RecordType
!= kDNSRecordTypeShared
)
2622 // For now don't do this, until we have the logic for intelligent grouping of individual records into logical service record sets
2623 //ptr = putPrereqNameNotInUse(rr->resrec.name, &m->omsg, ptr, end);
2624 if (!ptr
) goto exit
;
2627 ptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, ptr
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
2628 if (!ptr
) goto exit
;
2633 LogMsg("BuildUpdateMessage: Error formatting message for %s", ARDisplayString(m
, rr
));
2637 // Called with lock held
2638 mDNSlocal
void SendRecordRegistration(mDNS
*const m
, AuthRecord
*rr
)
2640 mDNSu8
*ptr
= m
->omsg
.data
;
2641 mStatus err
= mStatus_UnknownErr
;
2643 DomainAuthInfo
*AuthInfo
;
2645 // For the ability to register large TXT records, we limit the single record registrations
2646 // to AbsoluteMaxDNSMessageData
2647 limit
= ptr
+ AbsoluteMaxDNSMessageData
;
2649 AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
2650 limit
-= RRAdditionalSize(m
, AuthInfo
);
2652 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
2653 LogMsg("SendRecordRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
2655 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
2657 // We never call this function when there is no zone information . Log a message if it ever happens.
2658 LogMsg("SendRecordRegistration: No Zone information, should not happen %s", ARDisplayString(m
, rr
));
2662 rr
->updateid
= mDNS_NewMessageID(m
);
2663 InitializeDNSMessage(&m
->omsg
.h
, rr
->updateid
, UpdateReqFlags
);
2666 ptr
= putZone(&m
->omsg
, ptr
, limit
, rr
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
2667 if (!ptr
) goto exit
;
2669 if (!(ptr
= BuildUpdateMessage(m
, ptr
, rr
, limit
))) goto exit
;
2673 ptr
= putUpdateLeaseWithLimit(&m
->omsg
, ptr
, DEFAULT_UPDATE_LEASE
, limit
);
2674 if (!ptr
) goto exit
;
2678 LogInfo("SendRecordRegistration TCP %p %s", rr
->tcp
, ARDisplayString(m
, rr
));
2679 if (rr
->tcp
) LogInfo("SendRecordRegistration: Disposing existing TCP connection for %s", ARDisplayString(m
, rr
));
2680 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2681 if (!rr
->nta
) { LogMsg("SendRecordRegistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
2682 rr
->tcp
= MakeTCPConn(m
, &m
->omsg
, ptr
, kTCPSocketFlags_UseTLS
, &rr
->nta
->Addr
, rr
->nta
->Port
, &rr
->nta
->Host
, mDNSNULL
, rr
);
2686 LogInfo("SendRecordRegistration UDP %s", ARDisplayString(m
, rr
));
2687 if (!rr
->nta
) { LogMsg("SendRecordRegistration:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
2688 err
= mDNSSendDNSMessage(m
, &m
->omsg
, ptr
, mDNSInterface_Any
, mDNSNULL
, &rr
->nta
->Addr
, rr
->nta
->Port
, mDNSNULL
, GetAuthInfoForName_internal(m
, rr
->resrec
.name
), mDNSfalse
);
2689 if (err
) debugf("ERROR: SendRecordRegistration - mDNSSendDNSMessage - %d", err
);
2692 SetRecordRetry(m
, rr
, 0);
2695 LogMsg("SendRecordRegistration: Error formatting message for %s, disabling further updates", ARDisplayString(m
, rr
));
2696 // Disable this record from future updates
2697 rr
->state
= regState_NoTarget
;
2700 // Is the given record "rr" eligible for merging ?
2701 mDNSlocal mDNSBool
IsRecordMergeable(mDNS
*const m
, AuthRecord
*rr
, mDNSs32 time
)
2703 DomainAuthInfo
*info
;
2705 // A record is eligible for merge, if the following properties are met.
2707 // 1. uDNS Resource Record
2708 // 2. It is time to send them now
2709 // 3. It is in proper state
2710 // 4. Update zone has been resolved
2711 // 5. if DomainAuthInfo exists for the zone, it should not be soon deleted
2712 // 6. Zone information is present
2713 // 7. Update server is not zero
2714 // 8. It has a non-null zone
2715 // 9. It uses a lease option
2716 // 10. DontMerge is not set
2718 // Following code is implemented as separate "if" statements instead of one "if" statement
2719 // is for better debugging purposes e.g., we know exactly what failed if debugging turned on.
2721 if (!AuthRecord_uDNS(rr
)) return mDNSfalse
;
2723 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- time
> 0)
2724 { debugf("IsRecordMergeable: Time %d not reached for %s", rr
->LastAPTime
+ rr
->ThisAPInterval
- m
->timenow
, ARDisplayString(m
, rr
)); return mDNSfalse
; }
2726 if (!rr
->zone
) return mDNSfalse
;
2728 info
= GetAuthInfoForName_internal(m
, rr
->zone
);
2730 if (info
&& info
->deltime
&& m
->timenow
- info
->deltime
>= 0) {debugf("IsRecordMergeable: Domain %##s will be deleted soon", info
->domain
.c
); return mDNSfalse
;}
2732 if (rr
->state
!= regState_DeregPending
&& rr
->state
!= regState_Pending
&& rr
->state
!= regState_Registered
&& rr
->state
!= regState_Refresh
&& rr
->state
!= regState_UpdatePending
)
2733 { debugf("IsRecordMergeable: state %d not right %s", rr
->state
, ARDisplayString(m
, rr
)); return mDNSfalse
; }
2735 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
)) return mDNSfalse
;
2737 if (!rr
->uselease
) return mDNSfalse
;
2739 if (rr
->mState
== mergeState_DontMerge
) {debugf("IsRecordMergeable Dontmerge true %s", ARDisplayString(m
, rr
)); return mDNSfalse
;}
2740 debugf("IsRecordMergeable: Returning true for %s", ARDisplayString(m
, rr
));
2744 // Is the resource record "rr" eligible to merge to with "currentRR" ?
2745 mDNSlocal mDNSBool
AreRecordsMergeable(mDNS
*const m
, AuthRecord
*currentRR
, AuthRecord
*rr
, mDNSs32 time
)
2747 // A record is eligible to merge with another record as long it is eligible for merge in itself
2748 // and it has the same zone information as the other record
2749 if (!IsRecordMergeable(m
, rr
, time
)) return mDNSfalse
;
2751 if (!SameDomainName(currentRR
->zone
, rr
->zone
))
2752 { debugf("AreRecordMergeable zone mismatch current rr Zone %##s, rr zone %##s", currentRR
->zone
->c
, rr
->zone
->c
); return mDNSfalse
; }
2754 if (!mDNSSameIPv4Address(currentRR
->nta
->Addr
.ip
.v4
, rr
->nta
->Addr
.ip
.v4
)) return mDNSfalse
;
2756 if (!mDNSSameIPPort(currentRR
->nta
->Port
, rr
->nta
->Port
)) return mDNSfalse
;
2758 debugf("AreRecordsMergeable: Returning true for %s", ARDisplayString(m
, rr
));
2762 // If we can't build the message successfully because of problems in pre-computing
2763 // the space, we disable merging for all the current records
2764 mDNSlocal
void RRMergeFailure(mDNS
*const m
)
2767 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
2769 rr
->mState
= mergeState_DontMerge
;
2770 rr
->SendRNow
= mDNSNULL
;
2771 // Restarting the registration is much simpler than saving and restoring
2773 ActivateUnicastRegistration(m
, rr
);
2777 mDNSlocal
void SendGroupRRMessage(mDNS
*const m
, AuthRecord
*anchorRR
, mDNSu8
*ptr
, DomainAuthInfo
*info
)
2780 if (!anchorRR
) {debugf("SendGroupRRMessage: Could not merge records"); return;}
2782 if (info
&& info
->AutoTunnel
) limit
= m
->omsg
.data
+ AbsoluteMaxDNSMessageData
;
2783 else limit
= m
->omsg
.data
+ NormalMaxDNSMessageData
;
2785 // This has to go in the additional section and hence need to be done last
2786 ptr
= putUpdateLeaseWithLimit(&m
->omsg
, ptr
, DEFAULT_UPDATE_LEASE
, limit
);
2789 LogMsg("SendGroupRRMessage: ERROR: Could not put lease option, failing the group registration");
2790 // if we can't put the lease, we need to undo the merge
2794 if (anchorRR
->Private
)
2796 if (anchorRR
->tcp
) debugf("SendGroupRRMessage: Disposing existing TCP connection for %s", ARDisplayString(m
, anchorRR
));
2797 if (anchorRR
->tcp
) { DisposeTCPConn(anchorRR
->tcp
); anchorRR
->tcp
= mDNSNULL
; }
2798 if (!anchorRR
->nta
) { LogMsg("SendGroupRRMessage:ERROR!! nta is NULL for %s", ARDisplayString(m
, anchorRR
)); return; }
2799 anchorRR
->tcp
= MakeTCPConn(m
, &m
->omsg
, ptr
, kTCPSocketFlags_UseTLS
, &anchorRR
->nta
->Addr
, anchorRR
->nta
->Port
, &anchorRR
->nta
->Host
, mDNSNULL
, anchorRR
);
2800 if (!anchorRR
->tcp
) LogInfo("SendGroupRRMessage: Cannot establish TCP connection for %s", ARDisplayString(m
, anchorRR
));
2801 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
);
2805 mStatus err
= mDNSSendDNSMessage(m
, &m
->omsg
, ptr
, mDNSInterface_Any
, mDNSNULL
, &anchorRR
->nta
->Addr
, anchorRR
->nta
->Port
, mDNSNULL
, info
, mDNSfalse
);
2806 if (err
) LogInfo("SendGroupRRMessage: Cannot send UDP message for %s", ARDisplayString(m
, anchorRR
));
2807 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
);
2812 // As we always include the zone information and the resource records contain zone name
2813 // at the end, it will get compressed. Hence, we subtract zoneSize and add two bytes for
2814 // the compression pointer
2815 mDNSlocal mDNSu32
RREstimatedSize(AuthRecord
*rr
, int zoneSize
)
2819 // Note: Estimation of the record size has to mirror the logic in BuildUpdateMessage, otherwise estimation
2820 // would be wrong. Currently BuildUpdateMessage calls SetNewRData in UpdatePending case. Hence, we need
2821 // to account for that here. Otherwise, we might under estimate the size.
2822 if (rr
->state
== regState_UpdatePending
)
2823 // old RData that will be deleted
2824 // new RData that will be added
2825 rdlength
= rr
->OrigRDLen
+ rr
->InFlightRDLen
;
2827 rdlength
= rr
->resrec
.rdestimate
;
2829 if (rr
->state
== regState_DeregPending
)
2831 debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
2832 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), DomainNameLength(rr
->resrec
.name
), zoneSize
, rdlength
);
2833 return DomainNameLength(rr
->resrec
.name
) - zoneSize
+ 2 + 10 + rdlength
;
2836 // For SRV, TXT, AAAA etc. that are Unique/Verified, we also send a Deletion Record
2837 if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
|| rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
2839 // Deletion Record: Resource Record Name + Base size (10) + 0
2840 // Record: Resource Record Name (Compressed = 2) + Base size (10) + rdestimate
2842 debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
2843 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), DomainNameLength(rr
->resrec
.name
), zoneSize
, rdlength
);
2844 return DomainNameLength(rr
->resrec
.name
) - zoneSize
+ 2 + 10 + 2 + 10 + rdlength
;
2848 return DomainNameLength(rr
->resrec
.name
) - zoneSize
+ 2 + 10 + rdlength
;
2852 mDNSlocal AuthRecord
*MarkRRForSending(mDNS
*const m
)
2855 AuthRecord
*firstRR
= mDNSNULL
;
2857 // Look for records that needs to be sent in the next two seconds (MERGE_DELAY_TIME is set to 1 second).
2858 // The logic is as follows.
2860 // 1. Record 1 finishes getting zone data and its registration gets delayed by 1 second
2861 // 2. Record 2 comes 0.1 second later, finishes getting its zone data and its registration is also delayed by
2862 // 1 second which is now scheduled at 1.1 second
2864 // By looking for 1 second into the future (m->timenow + MERGE_DELAY_TIME below does that) we have merged both
2865 // of the above records. Note that we can't look for records too much into the future as this will affect the
2866 // retry logic. The first retry is scheduled at 3 seconds. Hence, we should always look smaller than that.
2867 // Anything more than one second will affect the first retry to happen sooner.
2869 // Note: As a side effect of looking one second into the future to facilitate merging, the retries happen
2870 // one second sooner.
2871 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
2875 if (!IsRecordMergeable(m
, rr
, m
->timenow
+ MERGE_DELAY_TIME
)) continue;
2878 else if (!AreRecordsMergeable(m
, firstRR
, rr
, m
->timenow
+ MERGE_DELAY_TIME
)) continue;
2880 if (rr
->SendRNow
) LogMsg("MarkRRForSending: Resourcerecord %s already marked for sending", ARDisplayString(m
, rr
));
2881 rr
->SendRNow
= mDNSInterfaceMark
;
2884 // We parsed through all records and found something to send. The services/records might
2885 // get registered at different times but we want the refreshes to be all merged and sent
2886 // as one update. Hence, we accelerate some of the records so that they will sync up in
2887 // the future. Look at the records excluding the ones that we have already sent in the
2888 // previous pass. If it half way through its scheduled refresh/retransmit, merge them
2889 // into this packet.
2891 // Note that we only look at Registered/Refresh state to keep it simple. As we don't know
2892 // whether the current update will fit into one or more packets, merging a resource record
2893 // (which is in a different state) that has been scheduled for retransmit would trigger
2894 // sending more packets.
2898 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
2900 if ((rr
->state
!= regState_Registered
&& rr
->state
!= regState_Refresh
) ||
2901 (rr
->SendRNow
== mDNSInterfaceMark
) ||
2902 (!AreRecordsMergeable(m
, firstRR
, rr
, m
->timenow
+ rr
->ThisAPInterval
/2)))
2904 rr
->SendRNow
= mDNSInterfaceMark
;
2907 if (acc
) LogInfo("MarkRRForSending: Accelereated %d records", acc
);
2912 mDNSlocal mDNSBool
SendGroupUpdates(mDNS
*const m
)
2915 mDNSs32 spaceleft
= 0;
2916 mDNSs32 zoneSize
, rrSize
;
2917 mDNSu8
*oldnext
; // for debugging
2918 mDNSu8
*next
= m
->omsg
.data
;
2920 AuthRecord
*anchorRR
= mDNSNULL
;
2922 AuthRecord
*startRR
= m
->ResourceRecords
;
2923 mDNSu8
*limit
= mDNSNULL
;
2924 DomainAuthInfo
*AuthInfo
= mDNSNULL
;
2925 mDNSBool sentallRecords
= mDNStrue
;
2928 // We try to fit as many ResourceRecords as possible in AbsoluteNormal/MaxDNSMessageData. Before we start
2929 // putting in resource records, we need to reserve space for a few things. Every group/packet should
2930 // have the following.
2932 // 1) Needs space for the Zone information (which needs to be at the beginning)
2933 // 2) Additional section MUST have space for lease option, HINFO and TSIG option (which needs to
2934 // to be at the end)
2936 // In future we need to reserve space for the pre-requisites which also goes at the beginning.
2937 // To accomodate pre-requisites in the future, first we walk the whole list marking records
2938 // that can be sent in this packet and computing the space needed for these records.
2939 // For TXT and SRV records, we delete the previous record if any by sending the same
2940 // resource record with ANY RDATA and zero rdlen. Hence, we need to have space for both of them.
2944 AuthInfo
= mDNSNULL
;
2945 anchorRR
= mDNSNULL
;
2948 for (rr
= startRR
; rr
; rr
= rr
->next
)
2950 if (rr
->SendRNow
!= mDNSInterfaceMark
) continue;
2952 rr
->SendRNow
= mDNSNULL
;
2956 AuthInfo
= GetAuthInfoForName_internal(m
, rr
->zone
);
2958 // Though we allow single record registrations for UDP to be AbsoluteMaxDNSMessageData (See
2959 // SendRecordRegistration) to handle large TXT records, to avoid fragmentation we limit UDP
2960 // message to NormalMaxDNSMessageData
2961 if (AuthInfo
&& AuthInfo
->AutoTunnel
) spaceleft
= AbsoluteMaxDNSMessageData
;
2962 else spaceleft
= NormalMaxDNSMessageData
;
2964 next
= m
->omsg
.data
;
2965 spaceleft
-= RRAdditionalSize(m
, AuthInfo
);
2968 LogMsg("SendGroupUpdates: ERROR!!: spaceleft is zero at the beginning");
2972 limit
= next
+ spaceleft
;
2974 // Build the initial part of message before putting in the other records
2975 msgid
= mDNS_NewMessageID(m
);
2976 InitializeDNSMessage(&m
->omsg
.h
, msgid
, UpdateReqFlags
);
2978 // We need zone information at the beginning of the packet. Length: ZNAME, ZTYPE(2), ZCLASS(2)
2979 // zone has to be non-NULL for a record to be mergeable, hence it is safe to set/ examine zone
2980 //without checking for NULL.
2981 zoneSize
= DomainNameLength(rr
->zone
) + 4;
2982 spaceleft
-= zoneSize
;
2985 LogMsg("SendGroupUpdates: ERROR no space for zone information, disabling merge");
2989 next
= putZone(&m
->omsg
, next
, limit
, rr
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
2992 LogMsg("SendGroupUpdates: ERROR! Cannot put zone, disabling merge");
2999 rrSize
= RREstimatedSize(rr
, zoneSize
- 4);
3001 if ((spaceleft
- rrSize
) < 0)
3003 // If we can't fit even a single message, skip it, it will be sent separately
3004 // in CheckRecordUpdates
3007 LogInfo("SendGroupUpdates: Skipping message %s, spaceleft %d, rrSize %d", ARDisplayString(m
, rr
), spaceleft
, rrSize
);
3008 // Mark this as not sent so that the caller knows about it
3009 rr
->SendRNow
= mDNSInterfaceMark
;
3010 // We need to remove the merge delay so that we can send it immediately
3011 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3012 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3014 anchorRR
= mDNSNULL
;
3015 sentallRecords
= mDNSfalse
;
3019 LogInfo("SendGroupUpdates:1: Parsed %d records and sending using %s, spaceleft %d, rrSize %d", nrecords
, ARDisplayString(m
, anchorRR
), spaceleft
, rrSize
);
3020 SendGroupRRMessage(m
, anchorRR
, next
, AuthInfo
);
3022 break; // breaks out of for loop
3024 spaceleft
-= rrSize
;
3026 LogInfo("SendGroupUpdates: Building a message with resource record %s, next %p, state %d, ttl %d", ARDisplayString(m
, rr
), next
, rr
->state
, rr
->resrec
.rroriginalttl
);
3027 if (!(next
= BuildUpdateMessage(m
, next
, rr
, limit
)))
3029 // We calculated the space and if we can't fit in, we had some bug in the calculation,
3030 // disable merge completely.
3031 LogMsg("SendGroupUpdates: ptr NULL while building message with %s", ARDisplayString(m
, rr
));
3035 // If our estimate was higher, adjust to the actual size
3036 if ((next
- oldnext
) > rrSize
)
3037 LogMsg("SendGroupUpdates: ERROR!! Record size estimation is wrong for %s, Estimate %d, Actual %d, state %d", ARDisplayString(m
, rr
), rrSize
, next
- oldnext
, rr
->state
);
3038 else { spaceleft
+= rrSize
; spaceleft
-= (next
- oldnext
); }
3041 // We could have sent an update earlier with this "rr" as anchorRR for which we never got a response.
3042 // To preserve ordering, we blow away the previous connection before sending this.
3043 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
;}
3044 rr
->updateid
= msgid
;
3046 // By setting the retry time interval here, we will not be looking at these records
3047 // again when we return to CheckGroupRecordUpdates.
3048 SetRecordRetry(m
, rr
, 0);
3050 // Either we have parsed all the records or stopped at "rr" above due to lack of space
3056 LogInfo("SendGroupUpdates: Parsed %d records and sending using %s", nrecords
, ARDisplayString(m
, anchorRR
));
3057 SendGroupRRMessage(m
, anchorRR
, next
, AuthInfo
);
3059 return sentallRecords
;
3062 // Merge the record registrations and send them as a group only if they
3063 // have same DomainAuthInfo and hence the same key to put the TSIG
3064 mDNSlocal
void CheckGroupRecordUpdates(mDNS
*const m
)
3066 AuthRecord
*rr
, *nextRR
;
3067 // Keep sending as long as there is at least one record to be sent
3068 while (MarkRRForSending(m
))
3070 if (!SendGroupUpdates(m
))
3072 // if everything that was marked was not sent, send them out individually
3073 for (rr
= m
->ResourceRecords
; rr
; rr
= nextRR
)
3075 // SendRecordRegistrtion might delete the rr from list, hence
3076 // dereference nextRR before calling the function
3078 if (rr
->SendRNow
== mDNSInterfaceMark
)
3080 // Any records marked for sending should be eligible to be sent out
3081 // immediately. Just being cautious
3082 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- m
->timenow
> 0)
3083 { LogMsg("CheckGroupRecordUpdates: ERROR!! Resourcerecord %s not ready", ARDisplayString(m
, rr
)); continue; }
3084 rr
->SendRNow
= mDNSNULL
;
3085 SendRecordRegistration(m
, rr
);
3091 debugf("CheckGroupRecordUpdates: No work, returning");
3095 mDNSlocal
void hndlSRVChanged(mDNS
*const m
, AuthRecord
*rr
)
3097 // Reevaluate the target always as NAT/Target could have changed while
3098 // we were registering/deeregistering
3100 const domainname
*target
= GetServiceTarget(m
, rr
);
3101 if (!target
|| target
->c
[0] == 0)
3103 // we don't have a target, if we just derregistered, then we don't have to do anything
3104 if (rr
->state
== regState_DeregPending
)
3106 LogInfo("hndlSRVChanged: SRVChanged, No Target, SRV Deregistered for %##s, state %d", rr
->resrec
.name
->c
,
3108 rr
->SRVChanged
= mDNSfalse
;
3109 dt
= GetRRDomainNameTarget(&rr
->resrec
);
3110 if (dt
) dt
->c
[0] = 0;
3111 rr
->state
= regState_NoTarget
; // Wait for the next target change
3112 rr
->resrec
.rdlength
= rr
->resrec
.rdestimate
= 0;
3116 // we don't have a target, if we just registered, we need to deregister
3117 if (rr
->state
== regState_Pending
)
3119 LogInfo("hndlSRVChanged: SRVChanged, No Target, Deregistering again %##s, state %d", rr
->resrec
.name
->c
, rr
->state
);
3120 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3121 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3122 rr
->state
= regState_DeregPending
;
3125 LogInfo("hndlSRVChanged: Not in DeregPending or RegPending state %##s, state %d", rr
->resrec
.name
->c
, rr
->state
);
3129 // If we were in registered state and SRV changed to NULL, we deregister and come back here
3130 // if we have a target, we need to register again.
3132 // if we just registered check to see if it is same. If it is different just re-register the
3133 // SRV and its assoicated records
3135 // UpdateOneSRVRecord takes care of re-registering all service records
3136 if ((rr
->state
== regState_DeregPending
) ||
3137 (rr
->state
== regState_Pending
&& !SameDomainName(target
, &rr
->resrec
.rdata
->u
.srv
.target
)))
3139 dt
= GetRRDomainNameTarget(&rr
->resrec
);
3140 if (dt
) dt
->c
[0] = 0;
3141 rr
->state
= regState_NoTarget
; // NoTarget will allow us to pick up new target OR nat traversal state
3142 rr
->resrec
.rdlength
= rr
->resrec
.rdestimate
= 0;
3143 LogInfo("hndlSRVChanged: SRVChanged, Valid Target %##s, Registering all records for %##s, state %d",
3144 target
->c
, rr
->resrec
.name
->c
, rr
->state
);
3145 rr
->SRVChanged
= mDNSfalse
;
3146 UpdateOneSRVRecord(m
, rr
);
3149 // Target did not change while this record was registering. Hence, we go to
3150 // Registered state - the state we started from.
3151 if (rr
->state
== regState_Pending
) rr
->state
= regState_Registered
;
3154 rr
->SRVChanged
= mDNSfalse
;
3157 // Called with lock held
3158 mDNSlocal
void hndlRecordUpdateReply(mDNS
*m
, AuthRecord
*rr
, mStatus err
, mDNSu32 random
)
3160 mDNSBool InvokeCallback
= mDNStrue
;
3161 mDNSIPPort UpdatePort
= zeroIPPort
;
3163 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
3164 LogMsg("hndlRecordUpdateReply: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
3166 LogInfo("hndlRecordUpdateReply: err %d ID %d state %d %s(%p)", err
, mDNSVal16(rr
->updateid
), rr
->state
, ARDisplayString(m
, rr
), rr
);
3168 rr
->updateError
= err
;
3169 #if APPLE_OSX_mDNSResponder
3170 if (err
== mStatus_BadSig
|| err
== mStatus_BadKey
) UpdateAutoTunnelDomainStatuses(m
);
3173 SetRecordRetry(m
, rr
, random
);
3175 rr
->updateid
= zeroID
; // Make sure that this is not considered as part of a group anymore
3176 // Later when need to send an update, we will get the zone data again. Thus we avoid
3177 // using stale information.
3179 // Note: By clearing out the zone info here, it also helps better merging of records
3180 // in some cases. For example, when we get out regState_NoTarget state e.g., move out
3181 // of Double NAT, we want all the records to be in one update. Some BTMM records like
3182 // _autotunnel6 and host records are registered/deregistered when NAT state changes.
3183 // As they are re-registered the zone information is cleared out. To merge with other
3184 // records that might be possibly going out, clearing out the information here helps
3185 // as all of them try to get the zone data.
3188 // We always expect the question to be stopped when we get a valid response from the server.
3189 // If the zone info tries to change during this time, updateid would be different and hence
3190 // this response should not have been accepted.
3191 if (rr
->nta
->question
.ThisQInterval
!= -1)
3192 LogMsg("hndlRecordUpdateReply: ResourceRecord %s, zone info question %##s (%s) interval %d not -1",
3193 ARDisplayString(m
, rr
), rr
->nta
->question
.qname
.c
, DNSTypeName(rr
->nta
->question
.qtype
), rr
->nta
->question
.ThisQInterval
);
3194 UpdatePort
= rr
->nta
->Port
;
3195 CancelGetZoneData(m
, rr
->nta
);
3199 // If we are deregistering the record, then complete the deregistration. Ignore any NAT/SRV change
3200 // that could have happened during that time.
3201 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->state
== regState_DeregPending
)
3203 debugf("hndlRecordUpdateReply: Received reply for deregister record %##s type %d", rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
3204 if (err
) LogMsg("ERROR: Deregistration of record %##s type %d failed with error %d",
3205 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, err
);
3206 rr
->state
= regState_Unregistered
;
3207 CompleteDeregistration(m
, rr
);
3211 // We are returning early without updating the state. When we come back from sleep we will re-register after
3212 // re-initializing all the state as though it is a first registration. If the record can't be registered e.g.,
3213 // no target, it will be deregistered. Hence, the updating to the right state should not matter when going
3217 // Need to set it to NoTarget state so that RecordReadyForSleep knows that
3219 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& rr
->state
== regState_DeregPending
)
3220 rr
->state
= regState_NoTarget
;
3224 if (rr
->state
== regState_UpdatePending
)
3226 if (err
) LogMsg("Update record failed for %##s (err %d)", rr
->resrec
.name
->c
, err
);
3227 rr
->state
= regState_Registered
;
3228 // deallocate old RData
3229 if (rr
->UpdateCallback
) rr
->UpdateCallback(m
, rr
, rr
->OrigRData
, rr
->OrigRDLen
);
3230 SetNewRData(&rr
->resrec
, rr
->InFlightRData
, rr
->InFlightRDLen
);
3231 rr
->OrigRData
= mDNSNULL
;
3232 rr
->InFlightRData
= mDNSNULL
;
3237 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
3238 hndlSRVChanged(m
, rr
);
3241 LogInfo("hndlRecordUpdateReply: Deregistered %##s (%s), state %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->state
);
3242 rr
->SRVChanged
= mDNSfalse
;
3243 if (rr
->state
!= regState_DeregPending
) LogMsg("hndlRecordUpdateReply: ResourceRecord %s not in DeregPending state %d", ARDisplayString(m
, rr
), rr
->state
);
3244 rr
->state
= regState_NoTarget
; // Wait for the next target change
3249 if (rr
->state
== regState_Pending
|| rr
->state
== regState_Refresh
)
3253 if (rr
->state
== regState_Refresh
) InvokeCallback
= mDNSfalse
;
3254 rr
->state
= regState_Registered
;
3258 // Retry without lease only for non-Private domains
3259 LogMsg("hndlRecordUpdateReply: Registration of record %##s type %d failed with error %d", rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, err
);
3260 if (!rr
->Private
&& rr
->uselease
&& err
== mStatus_UnknownErr
&& mDNSSameIPPort(UpdatePort
, UnicastDNSPort
))
3262 LogMsg("hndlRecordUpdateReply: Will retry update of record %##s without lease option", rr
->resrec
.name
->c
);
3263 rr
->uselease
= mDNSfalse
;
3264 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3265 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3266 SetNextuDNSEvent(m
, rr
);
3269 // Communicate the error to the application in the callback below
3273 if (rr
->QueuedRData
&& rr
->state
== regState_Registered
)
3275 rr
->state
= regState_UpdatePending
;
3276 rr
->InFlightRData
= rr
->QueuedRData
;
3277 rr
->InFlightRDLen
= rr
->QueuedRDLen
;
3278 rr
->OrigRData
= rr
->resrec
.rdata
;
3279 rr
->OrigRDLen
= rr
->resrec
.rdlength
;
3280 rr
->QueuedRData
= mDNSNULL
;
3281 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3282 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3283 SetNextuDNSEvent(m
, rr
);
3287 // Don't invoke the callback on error as this may not be useful to the client.
3288 // The client may potentially delete the resource record on error which we normally
3289 // delete during deregistration
3290 if (!err
&& InvokeCallback
&& rr
->RecordCallback
)
3292 LogInfo("hndlRecordUpdateReply: Calling record callback on %##s", rr
->resrec
.name
->c
);
3293 mDNS_DropLockBeforeCallback();
3294 rr
->RecordCallback(m
, rr
, err
);
3295 mDNS_ReclaimLockAfterCallback();
3297 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
3298 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
3301 mDNSexport
void uDNS_ReceiveNATPMPPacket(mDNS
*m
, const mDNSInterfaceID InterfaceID
, mDNSu8
*pkt
, mDNSu16 len
)
3303 NATTraversalInfo
*ptr
;
3304 NATAddrReply
*AddrReply
= (NATAddrReply
*)pkt
;
3305 NATPortMapReply
*PortMapReply
= (NATPortMapReply
*)pkt
;
3306 mDNSu32 nat_elapsed
, our_elapsed
;
3308 // Minimum packet is vers (1) opcode (1) err (2) upseconds (4) = 8 bytes
3309 if (!AddrReply
->err
&& len
< 8) { LogMsg("NAT Traversal message too short (%d bytes)", len
); return; }
3310 if (AddrReply
->vers
!= NATMAP_VERS
) { LogMsg("Received NAT Traversal response with version %d (expected %d)", pkt
[0], NATMAP_VERS
); return; }
3312 // Read multi-byte numeric values (fields are identical in a NATPortMapReply)
3313 AddrReply
->err
= (mDNSu16
) ( (mDNSu16
)pkt
[2] << 8 | pkt
[3]);
3314 AddrReply
->upseconds
= (mDNSs32
) ((mDNSs32
)pkt
[4] << 24 | (mDNSs32
)pkt
[5] << 16 | (mDNSs32
)pkt
[6] << 8 | pkt
[7]);
3316 nat_elapsed
= AddrReply
->upseconds
- m
->LastNATupseconds
;
3317 our_elapsed
= (m
->timenow
- m
->LastNATReplyLocalTime
) / mDNSPlatformOneSecond
;
3318 debugf("uDNS_ReceiveNATPMPPacket %X upseconds %u nat_elapsed %d our_elapsed %d", AddrReply
->opcode
, AddrReply
->upseconds
, nat_elapsed
, our_elapsed
);
3320 // We compute a conservative estimate of how much the NAT gateways's clock should have advanced
3321 // 1. We subtract 12.5% from our own measured elapsed time, to allow for NAT gateways that have an inacurate clock that runs slowly
3322 // 2. We add a two-second safety margin to allow for rounding errors: e.g.
3323 // -- if NAT gateway sends a packet at t=2.000 seconds, then one at t=7.999, that's approximately 6 real seconds,
3324 // but based on the values in the packet (2,7) the apparent difference according to the packet is only 5 seconds
3325 // -- if we're slow handling packets and/or we have coarse clock granularity,
3326 // we could receive the t=2 packet at our t=1.999 seconds, which we round down to 1
3327 // and the t=7.999 packet at our t=8.000 seconds, which we record as 8,
3328 // giving an apparent local time difference of 7 seconds
3329 // The two-second safety margin coves this possible calculation discrepancy
3330 if (AddrReply
->upseconds
< m
->LastNATupseconds
|| nat_elapsed
+ 2 < our_elapsed
- our_elapsed
/8)
3331 { LogMsg("NAT gateway %#a rebooted", &m
->Router
); RecreateNATMappings(m
); }
3333 m
->LastNATupseconds
= AddrReply
->upseconds
;
3334 m
->LastNATReplyLocalTime
= m
->timenow
;
3335 #ifdef _LEGACY_NAT_TRAVERSAL_
3337 #endif // _LEGACY_NAT_TRAVERSAL_
3339 if (AddrReply
->opcode
== NATOp_AddrResponse
)
3341 #if APPLE_OSX_mDNSResponder
3342 static char msgbuf
[16];
3343 mDNS_snprintf(msgbuf
, sizeof(msgbuf
), "%d", AddrReply
->err
);
3344 mDNSASLLog((uuid_t
*)&m
->asl_uuid
, "natt.natpmp.AddressRequest", AddrReply
->err
? "failure" : "success", msgbuf
, "");
3346 if (!AddrReply
->err
&& len
< sizeof(NATAddrReply
)) { LogMsg("NAT Traversal AddrResponse message too short (%d bytes)", len
); return; }
3347 natTraversalHandleAddressReply(m
, AddrReply
->err
, AddrReply
->ExtAddr
);
3349 else if (AddrReply
->opcode
== NATOp_MapUDPResponse
|| AddrReply
->opcode
== NATOp_MapTCPResponse
)
3351 mDNSu8 Protocol
= AddrReply
->opcode
& 0x7F;
3352 #if APPLE_OSX_mDNSResponder
3353 static char msgbuf
[16];
3354 mDNS_snprintf(msgbuf
, sizeof(msgbuf
), "%s - %d", AddrReply
->opcode
== NATOp_MapUDPResponse
? "UDP" : "TCP", PortMapReply
->err
);
3355 mDNSASLLog((uuid_t
*)&m
->asl_uuid
, "natt.natpmp.PortMapRequest", PortMapReply
->err
? "failure" : "success", msgbuf
, "");
3357 if (!PortMapReply
->err
)
3359 if (len
< sizeof(NATPortMapReply
)) { LogMsg("NAT Traversal PortMapReply message too short (%d bytes)", len
); return; }
3360 PortMapReply
->NATRep_lease
= (mDNSu32
) ((mDNSu32
)pkt
[12] << 24 | (mDNSu32
)pkt
[13] << 16 | (mDNSu32
)pkt
[14] << 8 | pkt
[15]);
3363 // Since some NAT-PMP server implementations don't return the requested internal port in
3364 // the reply, we can't associate this reply with a particular NATTraversalInfo structure.
3365 // We globally keep track of the most recent error code for mappings.
3366 m
->LastNATMapResultCode
= PortMapReply
->err
;
3368 for (ptr
= m
->NATTraversals
; ptr
; ptr
=ptr
->next
)
3369 if (ptr
->Protocol
== Protocol
&& mDNSSameIPPort(ptr
->IntPort
, PortMapReply
->intport
))
3370 natTraversalHandlePortMapReply(m
, ptr
, InterfaceID
, PortMapReply
->err
, PortMapReply
->extport
, PortMapReply
->NATRep_lease
);
3372 else { LogMsg("Received NAT Traversal response with version unknown opcode 0x%X", AddrReply
->opcode
); return; }
3374 // Don't need an SSDP socket if we get a NAT-PMP packet
3375 if (m
->SSDPSocket
) { debugf("uDNS_ReceiveNATPMPPacket destroying SSDPSocket %p", &m
->SSDPSocket
); mDNSPlatformUDPClose(m
->SSDPSocket
); m
->SSDPSocket
= mDNSNULL
; }
3378 // <rdar://problem/3925163> Shorten DNS-SD queries to avoid NAT bugs
3379 // <rdar://problem/4288449> Add check to avoid crashing NAT gateways that have buggy DNS relay code
3381 // We know of bugs in home NAT gateways that cause them to crash if they receive certain DNS queries.
3382 // The DNS queries that make them crash are perfectly legal DNS queries, but even if they weren't,
3383 // the gateway shouldn't crash -- in today's world of viruses and network attacks, software has to
3384 // be written assuming that a malicious attacker could send them any packet, properly-formed or not.
3385 // Still, we don't want to be crashing people's home gateways, so we go out of our way to avoid
3386 // the queries that crash them.
3390 // 1. Any query where the name ends in ".in-addr.arpa." and the text before this is 32 or more bytes.
3391 // The query type does not need to be PTR -- the gateway will crash for any query type.
3392 // e.g. "ping long-name-crashes-the-buggy-router.in-addr.arpa" will crash one of these.
3394 // 2. Any query that results in a large response with the TC bit set.
3396 // 3. Any PTR query that doesn't begin with four decimal numbers.
3397 // These gateways appear to assume that the only possible PTR query is a reverse-mapping query
3398 // (e.g. "1.0.168.192.in-addr.arpa") and if they ever get a PTR query where the first four
3399 // labels are not all decimal numbers in the range 0-255, they handle that by crashing.
3400 // These gateways also ignore the remainder of the name following the four decimal numbers
3401 // -- whether or not it actually says in-addr.arpa, they just make up an answer anyway.
3403 // The challenge therefore is to craft a query that will discern whether the DNS server
3404 // is one of these buggy ones, without crashing it. Furthermore we don't want our test
3405 // queries making it all the way to the root name servers, putting extra load on those
3406 // name servers and giving Apple a bad reputation. To this end we send this query:
3407 // dig -t ptr 1.0.0.127.dnsbugtest.1.0.0.127.in-addr.arpa.
3409 // The text preceding the ".in-addr.arpa." is under 32 bytes, so it won't cause crash (1).
3410 // It will not yield a large response with the TC bit set, so it won't cause crash (2).
3411 // It starts with four decimal numbers, so it won't cause crash (3).
3412 // The name falls within the "1.0.0.127.in-addr.arpa." domain, the reverse-mapping name for the local
3413 // loopback address, and therefore the query will black-hole at the first properly-configured DNS server
3414 // it reaches, making it highly unlikely that this query will make it all the way to the root.
3416 // Finally, the correct response to this query is NXDOMAIN or a similar error, but the
3417 // gateways that ignore the remainder of the name following the four decimal numbers
3418 // give themselves away by actually returning a result for this nonsense query.
3420 mDNSlocal
const domainname
*DNSRelayTestQuestion
= (const domainname
*)
3421 "\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\xa" "dnsbugtest"
3422 "\x1" "1" "\x1" "0" "\x1" "0" "\x3" "127" "\x7" "in-addr" "\x4" "arpa";
3424 // See comments above for DNSRelayTestQuestion
3425 // If this is the kind of query that has the risk of crashing buggy DNS servers, we do a test question first
3426 mDNSlocal mDNSBool
NoTestQuery(DNSQuestion
*q
)
3429 mDNSu8
*p
= q
->qname
.c
;
3430 if (q
->AuthInfo
) return(mDNStrue
); // Don't need a test query for private queries sent directly to authoritative server over TLS/TCP
3431 if (q
->qtype
!= kDNSType_PTR
) return(mDNStrue
); // Don't need a test query for any non-PTR queries
3432 for (i
=0; i
<4; i
++) // If qname does not begin with num.num.num.num, can't skip the test query
3434 if (p
[0] < 1 || p
[0] > 3) return(mDNSfalse
);
3435 if ( p
[1] < '0' || p
[1] > '9' ) return(mDNSfalse
);
3436 if (p
[0] >= 2 && (p
[2] < '0' || p
[2] > '9')) return(mDNSfalse
);
3437 if (p
[0] >= 3 && (p
[3] < '0' || p
[3] > '9')) return(mDNSfalse
);
3440 // If remainder of qname is ".in-addr.arpa.", this is a vanilla reverse-mapping query and
3441 // we can safely do it without needing a test query first, otherwise we need the test query.
3442 return(SameDomainName((domainname
*)p
, (const domainname
*)"\x7" "in-addr" "\x4" "arpa"));
3445 // Returns mDNStrue if response was handled
3446 mDNSlocal mDNSBool
uDNS_ReceiveTestQuestionResponse(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
3447 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
)
3449 const mDNSu8
*ptr
= msg
->data
;
3454 // 1. Find out if this is an answer to one of our test questions
3455 if (msg
->h
.numQuestions
!= 1) return(mDNSfalse
);
3456 ptr
= getQuestion(msg
, ptr
, end
, mDNSInterface_Any
, &pktq
);
3457 if (!ptr
) return(mDNSfalse
);
3458 if (pktq
.qtype
!= kDNSType_PTR
|| pktq
.qclass
!= kDNSClass_IN
) return(mDNSfalse
);
3459 if (!SameDomainName(&pktq
.qname
, DNSRelayTestQuestion
)) return(mDNSfalse
);
3461 // 2. If the DNS relay gave us a positive response, then it's got buggy firmware
3462 // else, if the DNS relay gave us an error or no-answer response, it passed our test
3463 if ((msg
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
) == kDNSFlag1_RC_NoErr
&& msg
->h
.numAnswers
> 0)
3464 result
= DNSServer_Failed
;
3466 result
= DNSServer_Passed
;
3468 // 3. Find occurrences of this server in our list, and mark them appropriately
3469 for (s
= m
->DNSServers
; s
; s
= s
->next
)
3471 mDNSBool matchaddr
= (s
->teststate
!= result
&& mDNSSameAddress(srcaddr
, &s
->addr
) && mDNSSameIPPort(srcport
, s
->port
));
3472 mDNSBool matchid
= (s
->teststate
== DNSServer_Untested
&& mDNSSameOpaque16(msg
->h
.id
, s
->testid
));
3473 if (matchaddr
|| matchid
)
3476 s
->teststate
= result
;
3477 if (result
== DNSServer_Passed
)
3479 LogInfo("DNS Server %#a:%d (%#a:%d) %d passed%s",
3480 &s
->addr
, mDNSVal16(s
->port
), srcaddr
, mDNSVal16(srcport
), mDNSVal16(s
->testid
),
3481 matchaddr
? "" : " NOTE: Reply did not come from address to which query was sent");
3485 LogMsg("NOTE: Wide-Area Service Discovery disabled to avoid crashing defective DNS relay %#a:%d (%#a:%d) %d%s",
3486 &s
->addr
, mDNSVal16(s
->port
), srcaddr
, mDNSVal16(srcport
), mDNSVal16(s
->testid
),
3487 matchaddr
? "" : " NOTE: Reply did not come from address to which query was sent");
3490 // If this server has just changed state from DNSServer_Untested to DNSServer_Passed, then retrigger any waiting questions.
3491 // We use the NoTestQuery() test so that we only retrigger questions that were actually blocked waiting for this test to complete.
3492 if (result
== DNSServer_Passed
) // Unblock any questions that were waiting for this result
3493 for (q
= m
->Questions
; q
; q
=q
->next
)
3494 if (q
->qDNSServer
== s
&& !NoTestQuery(q
))
3496 q
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
/ QuestionIntervalStep
;
3497 q
->unansweredQueries
= 0;
3498 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3499 m
->NextScheduledQuery
= m
->timenow
;
3504 return(mDNStrue
); // Return mDNStrue to tell uDNS_ReceiveMsg it doesn't need to process this packet further
3507 // Called from mDNSCoreReceive with the lock held
3508 mDNSexport
void uDNS_ReceiveMsg(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
, const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
)
3511 mStatus err
= mStatus_NoError
;
3513 mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
3514 mDNSu8 UpdateR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
3515 mDNSu8 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
3516 mDNSu8 rcode
= (mDNSu8
)(msg
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
3518 (void)srcport
; // Unused
3520 debugf("uDNS_ReceiveMsg from %#-15a with "
3521 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
3523 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
3524 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
3525 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
3526 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? "" : "s", end
- msg
->data
);
3530 //if (srcaddr && recvLLQResponse(m, msg, end, srcaddr, srcport)) return;
3531 if (uDNS_ReceiveTestQuestionResponse(m
, msg
, end
, srcaddr
, srcport
)) return;
3532 for (qptr
= m
->Questions
; qptr
; qptr
= qptr
->next
)
3533 if (msg
->h
.flags
.b
[0] & kDNSFlag0_TC
&& mDNSSameOpaque16(qptr
->TargetQID
, msg
->h
.id
) && m
->timenow
- qptr
->LastQTime
< RESPONSE_WINDOW
)
3535 if (!srcaddr
) LogMsg("uDNS_ReceiveMsg: TCP DNS response had TC bit set: ignoring");
3538 // Don't reuse TCP connections. We might have failed over to a different DNS server
3539 // while the first TCP connection is in progress. We need a new TCP connection to the
3540 // new DNS server. So, always try to establish a new connection.
3541 if (qptr
->tcp
) { DisposeTCPConn(qptr
->tcp
); qptr
->tcp
= mDNSNULL
; }
3542 qptr
->tcp
= MakeTCPConn(m
, mDNSNULL
, mDNSNULL
, kTCPSocketFlags_Zero
, srcaddr
, srcport
, mDNSNULL
, qptr
, mDNSNULL
);
3547 if (QR_OP
== UpdateR
)
3549 mDNSu32 lease
= GetPktLease(m
, msg
, end
);
3550 mDNSs32 expire
= m
->timenow
+ (mDNSs32
)lease
* mDNSPlatformOneSecond
;
3551 mDNSu32 random
= mDNSRandom((mDNSs32
)lease
* mDNSPlatformOneSecond
/10);
3553 //rcode = kDNSFlag1_RC_ServFail; // Simulate server failure (rcode 2)
3555 // Walk through all the records that matches the messageID. There could be multiple
3556 // records if we had sent them in a group
3557 if (m
->CurrentRecord
)
3558 LogMsg("uDNS_ReceiveMsg ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3559 m
->CurrentRecord
= m
->ResourceRecords
;
3560 while (m
->CurrentRecord
)
3562 AuthRecord
*rptr
= m
->CurrentRecord
;
3563 m
->CurrentRecord
= m
->CurrentRecord
->next
;
3564 if (AuthRecord_uDNS(rptr
) && mDNSSameOpaque16(rptr
->updateid
, msg
->h
.id
))
3566 err
= checkUpdateResult(m
, rptr
->resrec
.name
, rcode
, msg
, end
);
3567 if (!err
&& rptr
->uselease
&& lease
)
3568 if (rptr
->expire
- expire
>= 0 || rptr
->state
!= regState_UpdatePending
)
3570 rptr
->expire
= expire
;
3571 rptr
->refreshCount
= 0;
3573 // We pass the random value to make sure that if we update multiple
3574 // records, they all get the same random value
3575 hndlRecordUpdateReply(m
, rptr
, err
, random
);
3579 debugf("Received unexpected response: ID %d matches no active records", mDNSVal16(msg
->h
.id
));
3582 // ***************************************************************************
3583 #if COMPILER_LIKES_PRAGMA_MARK
3584 #pragma mark - Query Routines
3587 mDNSexport
void sendLLQRefresh(mDNS
*m
, DNSQuestion
*q
)
3591 mDNSu8
*limit
= m
->omsg
.data
+ AbsoluteMaxDNSMessageData
;
3594 if ((q
->state
== LLQ_Established
&& q
->ntries
>= kLLQ_MAX_TRIES
) || q
->expire
- m
->timenow
< 0)
3596 LogMsg("Unable to refresh LLQ %##s (%s) - will retry in %d seconds", q
->qname
.c
, DNSTypeName(q
->qtype
), LLQ_POLL_INTERVAL
/ mDNSPlatformOneSecond
);
3597 StartLLQPolling(m
,q
);
3601 llq
.vers
= kLLQ_Vers
;
3602 llq
.llqOp
= kLLQOp_Refresh
;
3603 llq
.err
= q
->tcp
? GetLLQEventPort(m
, &q
->servAddr
) : LLQErr_NoError
; // If using TCP tell server what UDP port to send notifications to
3605 llq
.llqlease
= q
->ReqLease
;
3607 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, uQueryFlags
);
3608 end
= putLLQ(&m
->omsg
, m
->omsg
.data
, q
, &llq
);
3609 if (!end
) { LogMsg("sendLLQRefresh: putLLQ failed %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
3611 // Note that we (conditionally) add HINFO and TSIG here, since the question might be going away,
3612 // so we may not be able to reference it (most importantly it's AuthInfo) when we actually send the message
3613 end
= putHINFO(m
, &m
->omsg
, end
, q
->AuthInfo
, limit
);
3614 if (!end
) { LogMsg("sendLLQRefresh: putHINFO failed %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
3616 if (PrivateQuery(q
))
3618 DNSDigest_SignMessageHostByteOrder(&m
->omsg
, &end
, q
->AuthInfo
);
3619 if (!end
) { LogMsg("sendLLQRefresh: DNSDigest_SignMessage failed %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
3622 if (PrivateQuery(q
) && !q
->tcp
)
3624 LogInfo("sendLLQRefresh setting up new TLS session %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3625 if (!q
->nta
) { LogMsg("sendLLQRefresh:ERROR!! q->nta is NULL for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
3626 q
->tcp
= MakeTCPConn(m
, &m
->omsg
, end
, kTCPSocketFlags_UseTLS
, &q
->servAddr
, q
->servPort
, &q
->nta
->Host
, q
, mDNSNULL
);
3632 // if AuthInfo and AuthInfo->AutoTunnel is set, we use the TCP socket but don't need to pass the AuthInfo as
3633 // we already protected the message above.
3634 LogInfo("sendLLQRefresh: using existing %s session %##s (%s)", PrivateQuery(q
) ? "TLS" : "UDP",
3635 q
->qname
.c
, DNSTypeName(q
->qtype
));
3637 err
= mDNSSendDNSMessage(m
, &m
->omsg
, end
, mDNSInterface_Any
, q
->LocalSocket
, &q
->servAddr
, q
->servPort
, q
->tcp
? q
->tcp
->sock
: mDNSNULL
, mDNSNULL
, mDNSfalse
);
3640 LogMsg("sendLLQRefresh: mDNSSendDNSMessage%s failed: %d", q
->tcp
? " (TCP)" : "", err
);
3641 if (q
->tcp
) { DisposeTCPConn(q
->tcp
); q
->tcp
= mDNSNULL
; }
3647 debugf("sendLLQRefresh ntries %d %##s (%s)", q
->ntries
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3649 q
->LastQTime
= m
->timenow
;
3650 SetNextQueryTime(m
, q
);
3653 mDNSexport
void LLQGotZoneData(mDNS
*const m
, mStatus err
, const ZoneData
*zoneInfo
)
3655 DNSQuestion
*q
= (DNSQuestion
*)zoneInfo
->ZoneDataContext
;
3659 // If we get here it means that the GetZoneData operation has completed.
3660 // We hold on to the zone data if it is AutoTunnel as we use the hostname
3661 // in zoneInfo during the TLS connection setup.
3662 q
->servAddr
= zeroAddr
;
3663 q
->servPort
= zeroIPPort
;
3665 if (!err
&& zoneInfo
&& !mDNSIPPortIsZero(zoneInfo
->Port
) && !mDNSAddressIsZero(&zoneInfo
->Addr
) && zoneInfo
->Host
.c
[0])
3667 q
->servAddr
= zoneInfo
->Addr
;
3668 q
->servPort
= zoneInfo
->Port
;
3669 if (!PrivateQuery(q
))
3671 // We don't need the zone data as we use it only for the Host information which we
3672 // don't need if we are not going to use TLS connections.
3675 if (q
->nta
!= zoneInfo
) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p) %##s (%s)", q
->nta
, zoneInfo
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3676 CancelGetZoneData(m
, q
->nta
);
3681 debugf("LLQGotZoneData %#a:%d", &q
->servAddr
, mDNSVal16(q
->servPort
));
3682 startLLQHandshake(m
, q
);
3688 if (q
->nta
!= zoneInfo
) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p) %##s (%s)", q
->nta
, zoneInfo
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3689 CancelGetZoneData(m
, q
->nta
);
3692 StartLLQPolling(m
,q
);
3693 if (err
== mStatus_NoSuchNameErr
)
3695 // this actually failed, so mark it by setting address to all ones
3696 q
->servAddr
.type
= mDNSAddrType_IPv4
;
3697 q
->servAddr
.ip
.v4
= onesIPv4Addr
;
3704 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
3705 mDNSlocal
void PrivateQueryGotZoneData(mDNS
*const m
, mStatus err
, const ZoneData
*zoneInfo
)
3707 DNSQuestion
*q
= (DNSQuestion
*) zoneInfo
->ZoneDataContext
;
3709 LogInfo("PrivateQueryGotZoneData %##s (%s) err %d Zone %##s Private %d", q
->qname
.c
, DNSTypeName(q
->qtype
), err
, zoneInfo
->ZoneName
.c
, zoneInfo
->ZonePrivate
);
3711 if (q
->nta
!= zoneInfo
) LogMsg("PrivateQueryGotZoneData:ERROR!!: nta (%p) != zoneInfo (%p) %##s (%s)", q
->nta
, zoneInfo
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3713 if (err
|| !zoneInfo
|| mDNSAddressIsZero(&zoneInfo
->Addr
) || mDNSIPPortIsZero(zoneInfo
->Port
) || !zoneInfo
->Host
.c
[0])
3715 LogInfo("PrivateQueryGotZoneData: ERROR!! %##s (%s) invoked with error code %d %p %#a:%d",
3716 q
->qname
.c
, DNSTypeName(q
->qtype
), err
, zoneInfo
,
3717 zoneInfo
? &zoneInfo
->Addr
: mDNSNULL
,
3718 zoneInfo
? mDNSVal16(zoneInfo
->Port
) : 0);
3719 CancelGetZoneData(m
, q
->nta
);
3724 if (!zoneInfo
->ZonePrivate
)
3726 debugf("Private port lookup failed -- retrying without TLS -- %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3727 q
->AuthInfo
= mDNSNULL
; // Clear AuthInfo so we try again non-private
3728 q
->ThisQInterval
= InitialQuestionInterval
;
3729 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3730 CancelGetZoneData(m
, q
->nta
);
3733 SetNextQueryTime(m
, q
);
3736 // Next call to uDNS_CheckCurrentQuestion() will do this as a non-private query
3739 if (!PrivateQuery(q
))
3741 LogMsg("PrivateQueryGotZoneData: ERROR!! Not a private query %##s (%s) AuthInfo %p", q
->qname
.c
, DNSTypeName(q
->qtype
), q
->AuthInfo
);
3742 CancelGetZoneData(m
, q
->nta
);
3747 q
->TargetQID
= mDNS_NewMessageID(m
);
3748 if (q
->tcp
) { DisposeTCPConn(q
->tcp
); q
->tcp
= mDNSNULL
; }
3749 if (!q
->nta
) { LogMsg("PrivateQueryGotZoneData:ERROR!! nta is NULL for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
3750 q
->tcp
= MakeTCPConn(m
, mDNSNULL
, mDNSNULL
, kTCPSocketFlags_UseTLS
, &zoneInfo
->Addr
, zoneInfo
->Port
, &q
->nta
->Host
, q
, mDNSNULL
);
3751 if (q
->nta
) { CancelGetZoneData(m
, q
->nta
); q
->nta
= mDNSNULL
; }
3754 // ***************************************************************************
3755 #if COMPILER_LIKES_PRAGMA_MARK
3756 #pragma mark - Dynamic Updates
3759 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
3760 mDNSexport
void RecordRegistrationGotZoneData(mDNS
*const m
, mStatus err
, const ZoneData
*zoneData
)
3762 AuthRecord
*newRR
= (AuthRecord
*)zoneData
->ZoneDataContext
;
3766 if (newRR
->nta
!= zoneData
)
3767 LogMsg("RecordRegistrationGotZoneData: nta (%p) != zoneData (%p) %##s (%s)", newRR
->nta
, zoneData
, newRR
->resrec
.name
->c
, DNSTypeName(newRR
->resrec
.rrtype
));
3769 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
3770 LogMsg("RecordRegistrationGotZoneData: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
3772 // make sure record is still in list (!!!)
3773 for (ptr
= m
->ResourceRecords
; ptr
; ptr
= ptr
->next
) if (ptr
== newRR
) break;
3776 LogMsg("RecordRegistrationGotZoneData - RR no longer in list. Discarding.");
3777 CancelGetZoneData(m
, newRR
->nta
);
3778 newRR
->nta
= mDNSNULL
;
3782 // check error/result
3785 if (err
!= mStatus_NoSuchNameErr
) LogMsg("RecordRegistrationGotZoneData: error %d", err
);
3786 CancelGetZoneData(m
, newRR
->nta
);
3787 newRR
->nta
= mDNSNULL
;
3791 if (!zoneData
) { LogMsg("ERROR: RecordRegistrationGotZoneData invoked with NULL result and no error"); return; }
3793 if (newRR
->resrec
.rrclass
!= zoneData
->ZoneClass
)
3795 LogMsg("ERROR: New resource record's class (%d) does not match zone class (%d)", newRR
->resrec
.rrclass
, zoneData
->ZoneClass
);
3796 CancelGetZoneData(m
, newRR
->nta
);
3797 newRR
->nta
= mDNSNULL
;
3801 // Don't try to do updates to the root name server.
3802 // We might be tempted also to block updates to any single-label name server (e.g. com, edu, net, etc.) but some
3803 // organizations use their own private pseudo-TLD, like ".home", etc, and we don't want to block that.
3804 if (zoneData
->ZoneName
.c
[0] == 0)
3806 LogInfo("RecordRegistrationGotZoneData: No name server found claiming responsibility for \"%##s\"!", newRR
->resrec
.name
->c
);
3807 CancelGetZoneData(m
, newRR
->nta
);
3808 newRR
->nta
= mDNSNULL
;
3812 // Store discovered zone data
3813 c1
= CountLabels(newRR
->resrec
.name
);
3814 c2
= CountLabels(&zoneData
->ZoneName
);
3817 LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" is longer than \"%##s\"", zoneData
->ZoneName
.c
, newRR
->resrec
.name
->c
);
3818 CancelGetZoneData(m
, newRR
->nta
);
3819 newRR
->nta
= mDNSNULL
;
3822 newRR
->zone
= SkipLeadingLabels(newRR
->resrec
.name
, c1
-c2
);
3823 if (!SameDomainName(newRR
->zone
, &zoneData
->ZoneName
))
3825 LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" does not match \"%##s\" for \"%##s\"", newRR
->zone
->c
, zoneData
->ZoneName
.c
, newRR
->resrec
.name
->c
);
3826 CancelGetZoneData(m
, newRR
->nta
);
3827 newRR
->nta
= mDNSNULL
;
3831 if (mDNSIPPortIsZero(zoneData
->Port
) || mDNSAddressIsZero(&zoneData
->Addr
) || !zoneData
->Host
.c
[0])
3833 LogInfo("RecordRegistrationGotZoneData: No _dns-update._udp service found for \"%##s\"!", newRR
->resrec
.name
->c
);
3834 CancelGetZoneData(m
, newRR
->nta
);
3835 newRR
->nta
= mDNSNULL
;
3839 newRR
->Private
= zoneData
->ZonePrivate
;
3840 debugf("RecordRegistrationGotZoneData: Set zone information for %##s %##s to %#a:%d",
3841 newRR
->resrec
.name
->c
, zoneData
->ZoneName
.c
, &zoneData
->Addr
, mDNSVal16(zoneData
->Port
));
3843 // If we are deregistering, uDNS_DeregisterRecord will do that as it has the zone data now.
3844 if (newRR
->state
== regState_DeregPending
)
3847 uDNS_DeregisterRecord(m
, newRR
);
3852 if (newRR
->resrec
.rrtype
== kDNSType_SRV
)
3854 const domainname
*target
;
3855 // Reevaluate the target always as NAT/Target could have changed while
3856 // we were fetching zone data.
3858 target
= GetServiceTarget(m
, newRR
);
3860 if (!target
|| target
->c
[0] == 0)
3862 domainname
*t
= GetRRDomainNameTarget(&newRR
->resrec
);
3863 LogInfo("RecordRegistrationGotZoneData - no target for %##s", newRR
->resrec
.name
->c
);
3865 newRR
->resrec
.rdlength
= newRR
->resrec
.rdestimate
= 0;
3866 newRR
->state
= regState_NoTarget
;
3867 CancelGetZoneData(m
, newRR
->nta
);
3868 newRR
->nta
= mDNSNULL
;
3872 // If we have non-zero service port (always?)
3873 // and a private address, and update server is non-private
3874 // and this service is AutoTarget
3875 // then initiate a NAT mapping request. On completion it will do SendRecordRegistration() for us
3876 if (newRR
->resrec
.rrtype
== kDNSType_SRV
&& !mDNSIPPortIsZero(newRR
->resrec
.rdata
->u
.srv
.port
) &&
3877 mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
) && newRR
->nta
&& !mDNSAddrIsRFC1918(&newRR
->nta
->Addr
) &&
3878 newRR
->AutoTarget
== Target_AutoHostAndNATMAP
)
3880 DomainAuthInfo
*AuthInfo
;
3881 AuthInfo
= GetAuthInfoForName(m
, newRR
->resrec
.name
);
3882 if (AuthInfo
&& AuthInfo
->AutoTunnel
)
3884 domainname
*t
= GetRRDomainNameTarget(&newRR
->resrec
);
3885 LogMsg("RecordRegistrationGotZoneData: ERROR!! AutoTunnel has Target_AutoHostAndNATMAP for %s", ARDisplayString(m
, newRR
));
3887 newRR
->resrec
.rdlength
= newRR
->resrec
.rdestimate
= 0;
3888 newRR
->state
= regState_NoTarget
;
3889 CancelGetZoneData(m
, newRR
->nta
);
3890 newRR
->nta
= mDNSNULL
;
3893 // During network transitions, we are called multiple times in different states. Setup NAT
3894 // state just once for this record.
3895 if (!newRR
->NATinfo
.clientContext
)
3897 LogInfo("RecordRegistrationGotZoneData StartRecordNatMap %s", ARDisplayString(m
, newRR
));
3898 newRR
->state
= regState_NATMap
;
3899 StartRecordNatMap(m
, newRR
);
3902 else LogInfo("RecordRegistrationGotZoneData: StartRecordNatMap for %s, state %d, context %p", ARDisplayString(m
, newRR
), newRR
->state
, newRR
->NATinfo
.clientContext
);
3905 // We want IsRecordMergeable to check whether it is a record whose update can be
3906 // sent with others. We set the time before we call IsRecordMergeable, so that
3907 // it does not fail this record based on time. We are interested in other checks
3908 // at this time. If a previous update resulted in error, then don't reset the
3909 // interval. Preserve the back-off so that we don't keep retrying aggressively.
3910 if (newRR
->updateError
== mStatus_NoError
)
3912 newRR
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3913 newRR
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3915 if (IsRecordMergeable(m
, newRR
, m
->timenow
+ MERGE_DELAY_TIME
))
3917 // Delay the record registration by MERGE_DELAY_TIME so that we can merge them
3919 LogInfo("RecordRegistrationGotZoneData: Delayed registration for %s", ARDisplayString(m
, newRR
));
3920 newRR
->LastAPTime
+= MERGE_DELAY_TIME
;
3925 mDNSlocal
void SendRecordDeregistration(mDNS
*m
, AuthRecord
*rr
)
3927 mDNSu8
*ptr
= m
->omsg
.data
;
3929 DomainAuthInfo
*AuthInfo
;
3931 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
3932 LogMsg("SendRecordDeRegistration: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
3934 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
3936 LogMsg("SendRecordDeRegistration: No zone info for Resource record %s RecordType %d", ARDisplayString(m
, rr
), rr
->resrec
.RecordType
);
3940 limit
= ptr
+ AbsoluteMaxDNSMessageData
;
3941 AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
3942 limit
-= RRAdditionalSize(m
, AuthInfo
);
3944 rr
->updateid
= mDNS_NewMessageID(m
);
3945 InitializeDNSMessage(&m
->omsg
.h
, rr
->updateid
, UpdateReqFlags
);
3948 ptr
= putZone(&m
->omsg
, ptr
, limit
, rr
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
3949 if (!ptr
) goto exit
;
3951 ptr
= BuildUpdateMessage(m
, ptr
, rr
, limit
);
3953 if (!ptr
) goto exit
;
3957 LogInfo("SendRecordDeregistration TCP %p %s", rr
->tcp
, ARDisplayString(m
, rr
));
3958 if (rr
->tcp
) LogInfo("SendRecordDeregistration: Disposing existing TCP connection for %s", ARDisplayString(m
, rr
));
3959 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
3960 if (!rr
->nta
) { LogMsg("SendRecordDeregistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
3961 rr
->tcp
= MakeTCPConn(m
, &m
->omsg
, ptr
, kTCPSocketFlags_UseTLS
, &rr
->nta
->Addr
, rr
->nta
->Port
, &rr
->nta
->Host
, mDNSNULL
, rr
);
3966 LogInfo("SendRecordDeregistration UDP %s", ARDisplayString(m
, rr
));
3967 if (!rr
->nta
) { LogMsg("SendRecordDeregistration:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
3968 err
= mDNSSendDNSMessage(m
, &m
->omsg
, ptr
, mDNSInterface_Any
, mDNSNULL
, &rr
->nta
->Addr
, rr
->nta
->Port
, mDNSNULL
, GetAuthInfoForName_internal(m
, rr
->resrec
.name
), mDNSfalse
);
3969 if (err
) debugf("ERROR: SendRecordDeregistration - mDNSSendDNSMessage - %d", err
);
3970 //if (rr->state == regState_DeregPending) CompleteDeregistration(m, rr); // Don't touch rr after this
3972 SetRecordRetry(m
, rr
, 0);
3975 LogMsg("SendRecordDeregistration: Error formatting message for %s", ARDisplayString(m
, rr
));
3978 mDNSexport mStatus
uDNS_DeregisterRecord(mDNS
*const m
, AuthRecord
*const rr
)
3980 DomainAuthInfo
*info
;
3982 LogInfo("uDNS_DeregisterRecord: Resource Record %s, state %d", ARDisplayString(m
, rr
), rr
->state
);
3986 case regState_Refresh
:
3987 case regState_Pending
:
3988 case regState_UpdatePending
:
3989 case regState_Registered
: break;
3990 case regState_DeregPending
: break;
3992 case regState_NATError
:
3993 case regState_NATMap
:
3994 // A record could be in NoTarget to start with if the corresponding SRV record could not find a target.
3995 // It is also possible to reenter the NoTarget state when we move to a network with a NAT that has
3996 // no NAT-PMP/UPnP support. In that case before we entered NoTarget, we already deregistered with
3998 case regState_NoTarget
:
3999 case regState_Unregistered
:
4002 LogInfo("uDNS_DeregisterRecord: State %d for %##s type %s", rr
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
4003 // This function may be called during sleep when there are no sleep proxy servers
4004 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) CompleteDeregistration(m
, rr
);
4005 return mStatus_NoError
;
4008 // if unsent rdata is queued, free it.
4010 // The data may be queued in QueuedRData or InFlightRData.
4012 // 1) If the record is in Registered state, we store it in InFlightRData and copy the same in "rdata"
4013 // *just* before sending the update to the server. Till we get the response, InFlightRData and "rdata"
4014 // in the resource record are same. We don't want to free in that case. It will be freed when "rdata"
4015 // is freed. If they are not same, the update has not been sent and we should free it here.
4017 // 2) If the record is in UpdatePending state, we queue the update in QueuedRData. When the previous update
4018 // comes back from the server, we copy it from QueuedRData to InFlightRData and repeat (1). This implies
4019 // that QueuedRData can never be same as "rdata" in the resource record. As long as we have something
4020 // left in QueuedRData, we should free it here.
4022 if (rr
->InFlightRData
&& rr
->UpdateCallback
)
4024 if (rr
->InFlightRData
!= rr
->resrec
.rdata
)
4026 LogInfo("uDNS_DeregisterRecord: Freeing InFlightRData for %s", ARDisplayString(m
, rr
));
4027 rr
->UpdateCallback(m
, rr
, rr
->InFlightRData
, rr
->InFlightRDLen
);
4028 rr
->InFlightRData
= mDNSNULL
;
4031 LogInfo("uDNS_DeregisterRecord: InFlightRData same as rdata for %s", ARDisplayString(m
, rr
));
4034 if (rr
->QueuedRData
&& rr
->UpdateCallback
)
4036 if (rr
->QueuedRData
== rr
->resrec
.rdata
)
4037 LogMsg("uDNS_DeregisterRecord: ERROR!! QueuedRData same as rdata for %s", ARDisplayString(m
, rr
));
4040 LogInfo("uDNS_DeregisterRecord: Freeing QueuedRData for %s", ARDisplayString(m
, rr
));
4041 rr
->UpdateCallback(m
, rr
, rr
->QueuedRData
, rr
->QueuedRDLen
);
4042 rr
->QueuedRData
= mDNSNULL
;
4046 // If a current group registration is pending, we can't send this deregisration till that registration
4047 // has reached the server i.e., the ordering is important. Previously, if we did not send this
4048 // registration in a group, then the previous connection will be torn down as part of sending the
4049 // deregistration. If we send this in a group, we need to locate the resource record that was used
4050 // to send this registration and terminate that connection. This means all the updates on that might
4051 // be lost (assuming the response is not waiting for us at the socket) and the retry will send the
4052 // update again sometime in the near future.
4054 // NOTE: SSL handshake failures normally free the TCP connection immediately. Hence, you may not
4055 // find the TCP below there. This case can happen only when tcp is trying to actively retransmit
4056 // the request or SSL negotiation taking time i.e resource record is actively trying to get the
4057 // message to the server. During that time a deregister has to happen.
4059 if (!mDNSOpaque16IsZero(rr
->updateid
))
4061 AuthRecord
*anchorRR
;
4062 mDNSBool found
= mDNSfalse
;
4063 for (anchorRR
= m
->ResourceRecords
; anchorRR
; anchorRR
= anchorRR
->next
)
4065 if (AuthRecord_uDNS(rr
) && mDNSSameOpaque16(anchorRR
->updateid
, rr
->updateid
) && anchorRR
->tcp
)
4067 LogInfo("uDNS_DeregisterRecord: Found Anchor RR %s terminated", ARDisplayString(m
, anchorRR
));
4069 LogMsg("uDNS_DeregisterRecord: ERROR: Another anchorRR %s found", ARDisplayString(m
, anchorRR
));
4070 DisposeTCPConn(anchorRR
->tcp
);
4071 anchorRR
->tcp
= mDNSNULL
;
4075 if (!found
) LogInfo("uDNSDeregisterRecord: Cannot find the anchor Resource Record for %s, not an error", ARDisplayString(m
, rr
));
4078 // Retry logic for deregistration should be no different from sending registration the first time.
4079 // Currently ThisAPInterval most likely is set to the refresh interval
4080 rr
->state
= regState_DeregPending
;
4081 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
4082 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
4083 info
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
4084 if (IsRecordMergeable(m
, rr
, m
->timenow
+ MERGE_DELAY_TIME
))
4086 // Delay the record deregistration by MERGE_DELAY_TIME so that we can merge them
4087 // into one update. If the domain is being deleted, delay by 2 * MERGE_DELAY_TIME
4088 // so that we can merge all the AutoTunnel records and the service records in
4089 // one update (they get deregistered a little apart)
4090 if (info
&& info
->deltime
) rr
->LastAPTime
+= (2 * MERGE_DELAY_TIME
);
4091 else rr
->LastAPTime
+= MERGE_DELAY_TIME
;
4093 // IsRecordMergeable could have returned false for several reasons e.g., DontMerge is set or
4094 // no zone information. Most likely it is the latter, CheckRecordUpdates will fetch the zone
4095 // data when it encounters this record.
4097 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
4098 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
4100 return mStatus_NoError
;
4103 mDNSexport mStatus
uDNS_UpdateRecord(mDNS
*m
, AuthRecord
*rr
)
4105 LogInfo("uDNS_UpdateRecord: Resource Record %##s, state %d", rr
->resrec
.name
->c
, rr
->state
);
4108 case regState_DeregPending
:
4109 case regState_Unregistered
:
4110 // not actively registered
4113 case regState_NATMap
:
4114 case regState_NoTarget
:
4115 // change rdata directly since it hasn't been sent yet
4116 if (rr
->UpdateCallback
) rr
->UpdateCallback(m
, rr
, rr
->resrec
.rdata
, rr
->resrec
.rdlength
);
4117 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
4118 rr
->NewRData
= mDNSNULL
;
4119 return mStatus_NoError
;
4121 case regState_Pending
:
4122 case regState_Refresh
:
4123 case regState_UpdatePending
:
4124 // registration in-flight. queue rdata and return
4125 if (rr
->QueuedRData
&& rr
->UpdateCallback
)
4126 // if unsent rdata is already queued, free it before we replace it
4127 rr
->UpdateCallback(m
, rr
, rr
->QueuedRData
, rr
->QueuedRDLen
);
4128 rr
->QueuedRData
= rr
->NewRData
;
4129 rr
->QueuedRDLen
= rr
->newrdlength
;
4130 rr
->NewRData
= mDNSNULL
;
4131 return mStatus_NoError
;
4133 case regState_Registered
:
4134 rr
->OrigRData
= rr
->resrec
.rdata
;
4135 rr
->OrigRDLen
= rr
->resrec
.rdlength
;
4136 rr
->InFlightRData
= rr
->NewRData
;
4137 rr
->InFlightRDLen
= rr
->newrdlength
;
4138 rr
->NewRData
= mDNSNULL
;
4139 rr
->state
= regState_UpdatePending
;
4140 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
4141 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
4142 SetNextuDNSEvent(m
, rr
);
4143 return mStatus_NoError
;
4145 case regState_NATError
:
4146 LogMsg("ERROR: uDNS_UpdateRecord called for record %##s with bad state regState_NATError", rr
->resrec
.name
->c
);
4147 return mStatus_UnknownErr
; // states for service records only
4149 default: LogMsg("uDNS_UpdateRecord: Unknown state %d for %##s", rr
->state
, rr
->resrec
.name
->c
);
4153 LogMsg("uDNS_UpdateRecord: Requested update of record %##s type %d, in erroneous state %d",
4154 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, rr
->state
);
4155 return mStatus_Invalid
;
4158 // ***************************************************************************
4159 #if COMPILER_LIKES_PRAGMA_MARK
4160 #pragma mark - Periodic Execution Routines
4163 // The question to be checked is not passed in as an explicit parameter;
4164 // instead it is implicit that the question to be checked is m->CurrentQuestion.
4165 mDNSexport
void uDNS_CheckCurrentQuestion(mDNS
*const m
)
4167 DNSQuestion
*q
= m
->CurrentQuestion
;
4168 if (m
->timenow
- NextQSendTime(q
) < 0) return;
4174 case LLQ_InitialRequest
: startLLQHandshake(m
, q
); break;
4175 case LLQ_SecondaryRequest
:
4176 // For PrivateQueries, we need to start the handshake again as we don't do the Challenge/Response step
4177 if (PrivateQuery(q
))
4178 startLLQHandshake(m
, q
);
4180 sendChallengeResponse(m
, q
, mDNSNULL
);
4182 case LLQ_Established
: sendLLQRefresh(m
, q
); break;
4183 case LLQ_Poll
: break; // Do nothing (handled below)
4187 // We repeat the check above (rather than just making this the "else" case) because startLLQHandshake can change q->state to LLQ_Poll
4188 if (!(q
->LongLived
&& q
->state
!= LLQ_Poll
))
4190 if (q
->unansweredQueries
>= MAX_UCAST_UNANSWERED_QUERIES
)
4192 DNSServer
*orig
= q
->qDNSServer
;
4194 LogInfo("uDNS_CheckCurrentQuestion: Sent %d unanswered queries for %##s (%s) to %#a:%d (%##s)",
4195 q
->unansweredQueries
, q
->qname
.c
, DNSTypeName(q
->qtype
), &orig
->addr
, mDNSVal16(orig
->port
), orig
->domain
.c
);
4197 PenalizeDNSServer(m
, q
);
4198 q
->noServerResponse
= 1;
4200 // There are two cases here.
4202 // 1. We have only one DNS server for this question. It is not responding even after we sent MAX_UCAST_UNANSWERED_QUERIES.
4203 // In that case, we need to keep retrying till we get a response. But we need to backoff as we retry. We set
4204 // noServerResponse in the block above and below we do not touch the question interval. When we come here, we
4205 // already waited for the response. We need to send another query right at this moment. We do that below by
4206 // reinitializing dns servers and reissuing the query.
4208 // 2. We have more than one DNS server. If at least one server did not respond, we would have set noServerResponse
4209 // either now (the last server in the list) or before (non-last server in the list). In either case, if we have
4210 // reached the end of DNS server list, we need to try again from the beginning. Ideally we should try just the
4211 // servers that did not respond, but for simplicity we try all the servers. Once we reached the end of list, we
4212 // set triedAllServersOnce so that we don't try all the servers aggressively. See PenalizeDNSServer.
4213 if (!q
->qDNSServer
&& q
->noServerResponse
)
4217 q
->triedAllServersOnce
= 1;
4218 // Re-initialize all DNS servers for this question. If we have a DNSServer, DNSServerChangeForQuestion will
4219 // handle all the work including setting the new DNS server.
4220 SetValidDNSServers(m
, q
);
4221 new = GetServerForQuestion(m
, q
);
4224 LogInfo("uDNS_checkCurrentQuestion: Retrying question %p %##s (%s) DNS Server %#a:%d ThisQInterval %d",
4225 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), new ? &new->addr
: mDNSNULL
, mDNSVal16(new ? new->port
: zeroIPPort
), q
->ThisQInterval
);
4226 DNSServerChangeForQuestion(m
, q
, new);
4228 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
4229 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
4231 if (q
->qDNSServer
&& q
->qDNSServer
->teststate
!= DNSServer_Disabled
)
4233 mDNSu8
*end
= m
->omsg
.data
;
4234 mStatus err
= mStatus_NoError
;
4235 mDNSBool
private = mDNSfalse
;
4237 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, (DNSSECQuestion(q
) ? DNSSecQFlags
: uQueryFlags
));
4239 if (q
->qDNSServer
->teststate
!= DNSServer_Untested
|| NoTestQuery(q
))
4241 end
= putQuestion(&m
->omsg
, m
->omsg
.data
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
, &q
->qname
, q
->qtype
, q
->qclass
);
4242 if (DNSSECQuestion(q
) && !q
->qDNSServer
->cellIntf
)
4243 end
= putDNSSECOption(&m
->omsg
, end
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
4244 private = PrivateQuery(q
);
4246 else if (m
->timenow
- q
->qDNSServer
->lasttest
>= INIT_UCAST_POLL_INTERVAL
) // Make sure at least three seconds has elapsed since last test query
4248 LogInfo("Sending DNS test query to %#a:%d", &q
->qDNSServer
->addr
, mDNSVal16(q
->qDNSServer
->port
));
4249 q
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
/ QuestionIntervalStep
;
4250 q
->qDNSServer
->lasttest
= m
->timenow
;
4251 end
= putQuestion(&m
->omsg
, m
->omsg
.data
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
, DNSRelayTestQuestion
, kDNSType_PTR
, kDNSClass_IN
);
4252 q
->qDNSServer
->testid
= m
->omsg
.h
.id
;
4255 if (end
> m
->omsg
.data
&& (q
->qDNSServer
->teststate
!= DNSServer_Failed
|| NoTestQuery(q
)))
4257 //LogMsg("uDNS_CheckCurrentQuestion %p %d %p %##s (%s)", q, NextQSendTime(q) - m->timenow, private, q->qname.c, DNSTypeName(q->qtype));
4260 if (q
->nta
) CancelGetZoneData(m
, q
->nta
);
4261 q
->nta
= StartGetZoneData(m
, &q
->qname
, q
->LongLived
? ZoneServiceLLQ
: ZoneServiceQuery
, PrivateQueryGotZoneData
, q
);
4262 if (q
->state
== LLQ_Poll
) q
->ThisQInterval
= (LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10)) / QuestionIntervalStep
;
4266 debugf("uDNS_CheckCurrentQuestion sending %p %##s (%s) %#a:%d UnansweredQueries %d",
4267 q
, q
->qname
.c
, DNSTypeName(q
->qtype
),
4268 q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
, mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
), q
->unansweredQueries
);
4269 if (!q
->LocalSocket
) q
->LocalSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
4270 if (!q
->LocalSocket
) err
= mStatus_NoMemoryErr
; // If failed to make socket (should be very rare), we'll try again next time
4271 else err
= mDNSSendDNSMessage(m
, &m
->omsg
, end
, q
->qDNSServer
->interface
, q
->LocalSocket
, &q
->qDNSServer
->addr
, q
->qDNSServer
->port
, mDNSNULL
, mDNSNULL
, q
->UseBrackgroundTrafficClass
);
4275 if (err
!= mStatus_TransientErr
) // if it is not a transient error backoff and DO NOT flood queries unnecessarily
4277 q
->ThisQInterval
= q
->ThisQInterval
* QuestionIntervalStep
; // Only increase interval if send succeeded
4278 q
->unansweredQueries
++;
4279 if (q
->ThisQInterval
> MAX_UCAST_POLL_INTERVAL
)
4280 q
->ThisQInterval
= MAX_UCAST_POLL_INTERVAL
;
4281 if (private && q
->state
!= LLQ_Poll
)
4283 // We don't want to retransmit too soon. Hence, we always schedule our first
4284 // retransmisson at 3 seconds rather than one second
4285 if (q
->ThisQInterval
< (3 * mDNSPlatformOneSecond
))
4286 q
->ThisQInterval
= q
->ThisQInterval
* QuestionIntervalStep
;
4287 if (q
->ThisQInterval
> LLQ_POLL_INTERVAL
)
4288 q
->ThisQInterval
= LLQ_POLL_INTERVAL
;
4289 LogInfo("uDNS_CheckCurrentQuestion: private non polling question for %##s (%s) will be retried in %d ms", q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
);
4291 if (q
->qDNSServer
->cellIntf
)
4293 // We don't want to retransmit too soon. Schedule our first retransmisson at
4294 // MIN_UCAST_RETRANS_TIMEOUT seconds.
4295 if (q
->ThisQInterval
< MIN_UCAST_RETRANS_TIMEOUT
)
4296 q
->ThisQInterval
= MIN_UCAST_RETRANS_TIMEOUT
;
4298 debugf("uDNS_CheckCurrentQuestion: Increased ThisQInterval to %d for %##s (%s), cell %d", q
->ThisQInterval
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
->cellIntf
);
4300 q
->LastQTime
= m
->timenow
;
4301 SetNextQueryTime(m
, q
);
4305 // If we have no server for this query, or the only server is a disabled one, then we deliver
4306 // a transient failure indication to the client. This is important for things like iPhone
4307 // where we want to return timely feedback to the user when no network is available.
4308 // After calling MakeNegativeCacheRecord() we store the resulting record in the
4309 // cache so that it will be visible to other clients asking the same question.
4310 // (When we have a group of identical questions, only the active representative of the group gets
4311 // passed to uDNS_CheckCurrentQuestion -- we only want one set of query packets hitting the wire --
4312 // but we want *all* of the questions to get answer callbacks.)
4315 const mDNSu32 slot
= HashSlot(&q
->qname
);
4316 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
4318 for (rr
= cg
->members
; rr
; rr
=rr
->next
)
4319 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
)) mDNS_PurgeCacheResourceRecord(m
, rr
);
4323 if (!mDNSOpaque64IsZero(&q
->validDNSServers
))
4324 LogMsg("uDNS_CheckCurrentQuestion: ERROR!!: valid DNSServer bits not zero 0x%x, 0x%x for question %##s (%s)",
4325 q
->validDNSServers
.l
[1], q
->validDNSServers
.l
[0], q
->qname
.c
, DNSTypeName(q
->qtype
));
4326 // If we reached the end of list while picking DNS servers, then we don't want to deactivate the
4327 // question. Try after 60 seconds. We find this by looking for valid DNSServers for this question,
4328 // if we find any, then we must have tried them before we came here. This avoids maintaining
4329 // another state variable to see if we had valid DNS servers for this question.
4330 SetValidDNSServers(m
, q
);
4331 if (mDNSOpaque64IsZero(&q
->validDNSServers
))
4333 LogInfo("uDNS_CheckCurrentQuestion: no DNS server for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4334 q
->ThisQInterval
= 0;
4339 // Pretend that we sent this question. As this is an ActiveQuestion, the NextScheduledQuery should
4340 // be set properly. Also, we need to properly backoff in cases where we don't set the question to
4341 // MaxQuestionInterval when we answer the question e.g., LongLived, we need to keep backing off
4342 q
->ThisQInterval
= q
->ThisQInterval
* QuestionIntervalStep
;
4343 q
->LastQTime
= m
->timenow
;
4344 SetNextQueryTime(m
, q
);
4345 // Pick a new DNS server now. Otherwise, when the cache is 80% of its expiry, we will try
4346 // to send a query and come back to the same place here and log the above message.
4347 q
->qDNSServer
= GetServerForQuestion(m
, q
);
4348 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
4349 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
4350 LogInfo("uDNS_checkCurrentQuestion: Tried all DNS servers, retry question %p SuppressUnusable %d %##s (%s) with DNS Server %#a:%d after 60 seconds, ThisQInterval %d",
4351 q
, q
->SuppressUnusable
, q
->qname
.c
, DNSTypeName(q
->qtype
),
4352 q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
, mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
), q
->ThisQInterval
);
4357 q
->ThisQInterval
= 0;
4358 LogMsg("uDNS_CheckCurrentQuestion DNS server %#a:%d for %##s is disabled", &q
->qDNSServer
->addr
, mDNSVal16(q
->qDNSServer
->port
), q
->qname
.c
);
4361 // For some of the WAB queries that we generate form within the mDNSResponder, most of the home routers
4362 // don't understand and return ServFail/NXDomain. In those cases, we don't want to try too often. We try
4363 // every fifteen minutes in that case
4364 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, (DomainEnumQuery(&q
->qname
) ? 60 * 15 : 60), mDNSInterface_Any
, q
->qDNSServer
);
4365 q
->unansweredQueries
= 0;
4366 // We're already using the m->CurrentQuestion pointer, so CacheRecordAdd can't use it to walk the question list.
4367 // To solve this problem we set rr->DelayDelivery to a nonzero value (which happens to be 'now') so that we
4368 // momentarily defer generating answer callbacks until mDNS_Execute time.
4369 CreateNewCacheEntry(m
, slot
, cg
, NonZeroTime(m
->timenow
), mDNStrue
, mDNSNULL
);
4370 ScheduleNextCacheCheckTime(m
, slot
, NonZeroTime(m
->timenow
));
4371 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4372 // MUST NOT touch m->CurrentQuestion (or q) after this -- client callback could have deleted it
4377 mDNSexport
void CheckNATMappings(mDNS
*m
)
4379 mStatus err
= mStatus_NoError
;
4380 mDNSBool rfc1918
= mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
);
4381 mDNSBool HaveRoutable
= !rfc1918
&& !mDNSIPv4AddressIsZero(m
->AdvertisedV4
.ip
.v4
);
4382 m
->NextScheduledNATOp
= m
->timenow
+ 0x3FFFFFFF;
4384 if (HaveRoutable
) m
->ExternalAddress
= m
->AdvertisedV4
.ip
.v4
;
4386 if (m
->NATTraversals
&& rfc1918
) // Do we need to open NAT-PMP socket to receive multicast announcements from router?
4388 if (m
->NATMcastRecvskt
== mDNSNULL
) // If we are behind a NAT and the socket hasn't been opened yet, open it
4390 // we need to log a message if we can't get our socket, but only the first time (after success)
4391 static mDNSBool needLog
= mDNStrue
;
4392 m
->NATMcastRecvskt
= mDNSPlatformUDPSocket(m
, NATPMPAnnouncementPort
);
4393 if (!m
->NATMcastRecvskt
)
4397 LogMsg("CheckNATMappings: Failed to allocate port 5350 UDP multicast socket for NAT-PMP announcements");
4398 needLog
= mDNSfalse
;
4405 else // else, we don't want to listen for announcements, so close them if they're open
4407 if (m
->NATMcastRecvskt
) { mDNSPlatformUDPClose(m
->NATMcastRecvskt
); m
->NATMcastRecvskt
= mDNSNULL
; }
4408 if (m
->SSDPSocket
) { debugf("CheckNATMappings destroying SSDPSocket %p", &m
->SSDPSocket
); mDNSPlatformUDPClose(m
->SSDPSocket
); m
->SSDPSocket
= mDNSNULL
; }
4411 if (!m
->NATTraversals
)
4412 m
->retryGetAddr
= m
->timenow
+ 0x78000000;
4415 if (m
->timenow
- m
->retryGetAddr
>= 0)
4417 err
= uDNS_SendNATMsg(m
, mDNSNULL
); // Will also do UPnP discovery for us, if necessary
4420 if (m
->retryIntervalGetAddr
< NATMAP_INIT_RETRY
) m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
4421 else if (m
->retryIntervalGetAddr
< NATMAP_MAX_RETRY_INTERVAL
/ 2) m
->retryIntervalGetAddr
*= 2;
4422 else m
->retryIntervalGetAddr
= NATMAP_MAX_RETRY_INTERVAL
;
4424 LogInfo("CheckNATMappings retryGetAddr sent address request err %d interval %d", err
, m
->retryIntervalGetAddr
);
4426 // Always update m->retryGetAddr, even if we fail to send the packet. Otherwise in cases where we can't send the packet
4427 // (like when we have no active interfaces) we'll spin in an infinite loop repeatedly failing to send the packet
4428 m
->retryGetAddr
= m
->timenow
+ m
->retryIntervalGetAddr
;
4430 // Even when we didn't send the GetAddr packet, still need to make sure NextScheduledNATOp is set correctly
4431 if (m
->NextScheduledNATOp
- m
->retryGetAddr
> 0)
4432 m
->NextScheduledNATOp
= m
->retryGetAddr
;
4435 if (m
->CurrentNATTraversal
) LogMsg("WARNING m->CurrentNATTraversal already in use");
4436 m
->CurrentNATTraversal
= m
->NATTraversals
;
4438 while (m
->CurrentNATTraversal
)
4440 NATTraversalInfo
*cur
= m
->CurrentNATTraversal
;
4441 m
->CurrentNATTraversal
= m
->CurrentNATTraversal
->next
;
4443 if (HaveRoutable
) // If not RFC 1918 address, our own address and port are effectively our external address and port
4445 cur
->ExpiryTime
= 0;
4446 cur
->NewResult
= mStatus_NoError
;
4448 else if (cur
->Protocol
) // Check if it's time to send port mapping packets
4450 if (m
->timenow
- cur
->retryPortMap
>= 0) // Time to do something with this mapping
4452 if (cur
->ExpiryTime
&& cur
->ExpiryTime
- m
->timenow
< 0) // Mapping has expired
4454 cur
->ExpiryTime
= 0;
4455 cur
->retryInterval
= NATMAP_INIT_RETRY
;
4458 //LogMsg("uDNS_SendNATMsg");
4459 err
= uDNS_SendNATMsg(m
, cur
);
4461 if (cur
->ExpiryTime
) // If have active mapping then set next renewal time halfway to expiry
4462 NATSetNextRenewalTime(m
, cur
);
4463 else // else no mapping; use exponential backoff sequence
4465 if (cur
->retryInterval
< NATMAP_INIT_RETRY
) cur
->retryInterval
= NATMAP_INIT_RETRY
;
4466 else if (cur
->retryInterval
< NATMAP_MAX_RETRY_INTERVAL
/ 2) cur
->retryInterval
*= 2;
4467 else cur
->retryInterval
= NATMAP_MAX_RETRY_INTERVAL
;
4468 cur
->retryPortMap
= m
->timenow
+ cur
->retryInterval
;
4472 if (m
->NextScheduledNATOp
- cur
->retryPortMap
> 0)
4473 m
->NextScheduledNATOp
= cur
->retryPortMap
;
4476 // Notify the client if necessary. We invoke the callback if:
4477 // (1) we have an ExternalAddress, or we've tried and failed a couple of times to discover it
4478 // 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
4479 // and (3) we have new data to give the client that's changed since the last callback
4480 // Time line is: Send, Wait 500ms, Send, Wait 1sec, Send, Wait 2sec, Send
4481 // At this point we've sent three requests without an answer, we've just sent our fourth request,
4482 // retryIntervalGetAddr is now 4 seconds, which is greater than NATMAP_INIT_RETRY * 8 (2 seconds),
4483 // so we return an error result to the caller.
4484 if (!mDNSIPv4AddressIsZero(m
->ExternalAddress
) || m
->retryIntervalGetAddr
> NATMAP_INIT_RETRY
* 8)
4486 const mStatus EffectiveResult
= cur
->NewResult
? cur
->NewResult
: mDNSv4AddrIsRFC1918(&m
->ExternalAddress
) ? mStatus_DoubleNAT
: mStatus_NoError
;
4487 const mDNSIPPort ExternalPort
= HaveRoutable
? cur
->IntPort
:
4488 !mDNSIPv4AddressIsZero(m
->ExternalAddress
) && cur
->ExpiryTime
? cur
->RequestedPort
: zeroIPPort
;
4489 if (!cur
->Protocol
|| HaveRoutable
|| cur
->ExpiryTime
|| cur
->retryInterval
> NATMAP_INIT_RETRY
* 8)
4490 if (!mDNSSameIPv4Address(cur
->ExternalAddress
, m
->ExternalAddress
) ||
4491 !mDNSSameIPPort (cur
->ExternalPort
, ExternalPort
) ||
4492 cur
->Result
!= EffectiveResult
)
4494 //LogMsg("NAT callback %d %d %d", cur->Protocol, cur->ExpiryTime, cur->retryInterval);
4495 if (cur
->Protocol
&& mDNSIPPortIsZero(ExternalPort
) && !mDNSIPv4AddressIsZero(m
->Router
.ip
.v4
))
4497 if (!EffectiveResult
)
4498 LogInfo("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4499 cur
, &m
->Router
, &m
->ExternalAddress
, mDNSVal16(cur
->IntPort
), cur
->retryInterval
, EffectiveResult
);
4501 LogMsg("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4502 cur
, &m
->Router
, &m
->ExternalAddress
, mDNSVal16(cur
->IntPort
), cur
->retryInterval
, EffectiveResult
);
4505 cur
->ExternalAddress
= m
->ExternalAddress
;
4506 cur
->ExternalPort
= ExternalPort
;
4507 cur
->Lifetime
= cur
->ExpiryTime
&& !mDNSIPPortIsZero(ExternalPort
) ?
4508 (cur
->ExpiryTime
- m
->timenow
+ mDNSPlatformOneSecond
/2) / mDNSPlatformOneSecond
: 0;
4509 cur
->Result
= EffectiveResult
;
4510 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
4511 if (cur
->clientCallback
)
4512 cur
->clientCallback(m
, cur
);
4513 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4514 // MUST NOT touch cur after invoking the callback
4520 mDNSlocal mDNSs32
CheckRecordUpdates(mDNS
*m
)
4523 mDNSs32 nextevent
= m
->timenow
+ 0x3FFFFFFF;
4525 CheckGroupRecordUpdates(m
);
4527 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4529 if (!AuthRecord_uDNS(rr
)) continue;
4530 if (rr
->state
== regState_NoTarget
) {debugf("CheckRecordUpdates: Record %##s in NoTarget", rr
->resrec
.name
->c
); continue;}
4531 // While we are waiting for the port mapping, we have nothing to do. The port mapping callback
4532 // will take care of this
4533 if (rr
->state
== regState_NATMap
) {debugf("CheckRecordUpdates: Record %##s in NATMap", rr
->resrec
.name
->c
); continue;}
4534 if (rr
->state
== regState_Pending
|| rr
->state
== regState_DeregPending
|| rr
->state
== regState_UpdatePending
||
4535 rr
->state
== regState_Refresh
|| rr
->state
== regState_Registered
)
4537 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- m
->timenow
<= 0)
4539 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
4540 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
4542 // Zero out the updateid so that if we have a pending response from the server, it won't
4543 // be accepted as a valid response. If we accept the response, we might free the new "nta"
4544 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
4545 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
4547 // We have just started the GetZoneData. We need to wait for it to finish. SetRecordRetry here
4548 // schedules the update timer to fire in the future.
4550 // There are three cases.
4552 // 1) When the updates are sent the first time, the first retry is intended to be at three seconds
4553 // in the future. But by calling SetRecordRetry here we set it to nine seconds. But it does not
4554 // matter because when the answer comes back, RecordRegistrationGotZoneData resets the interval
4555 // back to INIT_RECORD_REG_INTERVAL. This also gives enough time for the query.
4557 // 2) In the case of update errors (updateError), this causes further backoff as
4558 // RecordRegistrationGotZoneData does not reset the timer. This is intentional as in the case of
4559 // errors, we don't want to update aggressively.
4561 // 3) We might be refreshing the update. This is very similar to case (1). RecordRegistrationGotZoneData
4562 // resets it back to INIT_RECORD_REG_INTERVAL.
4564 SetRecordRetry(m
, rr
, 0);
4566 else if (rr
->state
== regState_DeregPending
) SendRecordDeregistration(m
, rr
);
4567 else SendRecordRegistration(m
, rr
);
4570 if (nextevent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) > 0)
4571 nextevent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
4576 mDNSexport
void uDNS_Tasks(mDNS
*const m
)
4581 m
->NextuDNSEvent
= m
->timenow
+ 0x3FFFFFFF;
4583 nexte
= CheckRecordUpdates(m
);
4584 if (m
->NextuDNSEvent
- nexte
> 0)
4585 m
->NextuDNSEvent
= nexte
;
4587 for (d
= m
->DNSServers
; d
; d
=d
->next
)
4590 if (m
->timenow
- d
->penaltyTime
>= 0)
4592 LogInfo("DNS server %#a:%d out of penalty box", &d
->addr
, mDNSVal16(d
->port
));
4596 if (m
->NextuDNSEvent
- d
->penaltyTime
> 0)
4597 m
->NextuDNSEvent
= d
->penaltyTime
;
4600 if (m
->CurrentQuestion
)
4601 LogMsg("uDNS_Tasks ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4602 m
->CurrentQuestion
= m
->Questions
;
4603 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4605 DNSQuestion
*const q
= m
->CurrentQuestion
;
4606 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
))
4608 uDNS_CheckCurrentQuestion(m
);
4609 if (q
== m
->CurrentQuestion
)
4610 if (m
->NextuDNSEvent
- NextQSendTime(q
) > 0)
4611 m
->NextuDNSEvent
= NextQSendTime(q
);
4613 // If m->CurrentQuestion wasn't modified out from under us, advance it now
4614 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion()
4615 // depends on having m->CurrentQuestion point to the right question
4616 if (m
->CurrentQuestion
== q
)
4617 m
->CurrentQuestion
= q
->next
;
4619 m
->CurrentQuestion
= mDNSNULL
;
4622 // ***************************************************************************
4623 #if COMPILER_LIKES_PRAGMA_MARK
4624 #pragma mark - Startup, Shutdown, and Sleep
4627 mDNSexport
void SleepRecordRegistrations(mDNS
*m
)
4630 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4632 if (AuthRecord_uDNS(rr
))
4634 // Zero out the updateid so that if we have a pending response from the server, it won't
4635 // be accepted as a valid response.
4636 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
4638 if (rr
->NATinfo
.clientContext
)
4640 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
4641 rr
->NATinfo
.clientContext
= mDNSNULL
;
4643 // We are waiting to update the resource record. The original data of the record is
4644 // in OrigRData and the updated value is in InFlightRData. Free the old and the new
4645 // one will be registered when we come back.
4646 if (rr
->state
== regState_UpdatePending
)
4648 // act as if the update succeeded, since we're about to delete the name anyway
4649 rr
->state
= regState_Registered
;
4650 // deallocate old RData
4651 if (rr
->UpdateCallback
) rr
->UpdateCallback(m
, rr
, rr
->OrigRData
, rr
->OrigRDLen
);
4652 SetNewRData(&rr
->resrec
, rr
->InFlightRData
, rr
->InFlightRDLen
);
4653 rr
->OrigRData
= mDNSNULL
;
4654 rr
->InFlightRData
= mDNSNULL
;
4657 // If we have not begun the registration process i.e., never sent a registration packet,
4658 // then uDNS_DeregisterRecord will not send a deregistration
4659 uDNS_DeregisterRecord(m
, rr
);
4661 // When we wake, we call ActivateUnicastRegistration which starts at StartGetZoneData
4666 mDNSexport
void mDNS_AddSearchDomain(const domainname
*const domain
, mDNSInterfaceID InterfaceID
)
4669 SearchListElem
*tmp
= mDNSNULL
;
4671 // Check to see if we already have this domain in our list
4672 for (p
= &SearchList
; *p
; p
= &(*p
)->next
)
4673 if (((*p
)->InterfaceID
== InterfaceID
) && SameDomainName(&(*p
)->domain
, domain
))
4675 // If domain is already in list, and marked for deletion, unmark the delete
4676 // Be careful not to touch the other flags that may be present
4677 LogInfo("mDNS_AddSearchDomain already in list %##s", domain
->c
);
4678 if ((*p
)->flag
& SLE_DELETE
) (*p
)->flag
&= ~SLE_DELETE
;
4681 tmp
->next
= mDNSNULL
;
4686 // move to end of list so that we maintain the same order
4687 while (*p
) p
= &(*p
)->next
;
4692 // if domain not in list, add to list, mark as add (1)
4693 *p
= mDNSPlatformMemAllocate(sizeof(SearchListElem
));
4694 if (!*p
) { LogMsg("ERROR: mDNS_AddSearchDomain - malloc"); return; }
4695 mDNSPlatformMemZero(*p
, sizeof(SearchListElem
));
4696 AssignDomainName(&(*p
)->domain
, domain
);
4697 (*p
)->next
= mDNSNULL
;
4698 (*p
)->InterfaceID
= InterfaceID
;
4699 LogInfo("mDNS_AddSearchDomain created new %##s, InterfaceID %p", domain
->c
, InterfaceID
);
4703 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
4706 if (result
== mStatus_MemFree
) mDNSPlatformMemFree(rr
->RecordContext
);
4709 mDNSlocal
void FoundDomain(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
4711 SearchListElem
*slElem
= question
->QuestionContext
;
4715 if (answer
->rrtype
!= kDNSType_PTR
) return;
4716 if (answer
->RecordType
== kDNSRecordTypePacketNegative
) return;
4717 if (answer
->InterfaceID
== mDNSInterface_LocalOnly
) return;
4719 if (question
== &slElem
->BrowseQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowse
];
4720 else if (question
== &slElem
->DefBrowseQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowseDefault
];
4721 else if (question
== &slElem
->AutomaticBrowseQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowseAutomatic
];
4722 else if (question
== &slElem
->RegisterQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeRegistration
];
4723 else if (question
== &slElem
->DefRegisterQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeRegistrationDefault
];
4724 else { LogMsg("FoundDomain - unknown question"); return; }
4726 LogInfo("FoundDomain: %p %s %s Q %##s A %s", answer
->InterfaceID
, AddRecord
? "Add" : "Rmv", name
, question
->qname
.c
, RRDisplayString(m
, answer
));
4730 ARListElem
*arElem
= mDNSPlatformMemAllocate(sizeof(ARListElem
));
4731 if (!arElem
) { LogMsg("ERROR: FoundDomain out of memory"); return; }
4732 mDNS_SetupResourceRecord(&arElem
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, AuthRecordLocalOnly
, FreeARElemCallback
, arElem
);
4733 MakeDomainNameFromDNSNameString(&arElem
->ar
.namestorage
, name
);
4734 AppendDNSNameString (&arElem
->ar
.namestorage
, "local");
4735 AssignDomainName(&arElem
->ar
.resrec
.rdata
->u
.name
, &answer
->rdata
->u
.name
);
4736 LogInfo("FoundDomain: Registering %s", ARDisplayString(m
, &arElem
->ar
));
4737 err
= mDNS_Register(m
, &arElem
->ar
);
4738 if (err
) { LogMsg("ERROR: FoundDomain - mDNS_Register returned %d", err
); mDNSPlatformMemFree(arElem
); return; }
4739 arElem
->next
= slElem
->AuthRecs
;
4740 slElem
->AuthRecs
= arElem
;
4744 ARListElem
**ptr
= &slElem
->AuthRecs
;
4747 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, &answer
->rdata
->u
.name
))
4749 ARListElem
*dereg
= *ptr
;
4750 *ptr
= (*ptr
)->next
;
4751 LogInfo("FoundDomain: Deregistering %s", ARDisplayString(m
, &dereg
->ar
));
4752 err
= mDNS_Deregister(m
, &dereg
->ar
);
4753 if (err
) LogMsg("ERROR: FoundDomain - mDNS_Deregister returned %d", err
);
4754 // Memory will be freed in the FreeARElemCallback
4757 ptr
= &(*ptr
)->next
;
4762 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4763 mDNSexport
void udns_validatelists(void *const v
)
4767 NATTraversalInfo
*n
;
4768 for (n
= m
->NATTraversals
; n
; n
=n
->next
)
4769 if (n
->next
== (NATTraversalInfo
*)~0 || n
->clientCallback
== (NATTraversalClientCallback
) ~0)
4770 LogMemCorruption("m->NATTraversals: %p is garbage", n
);
4773 for (d
= m
->DNSServers
; d
; d
=d
->next
)
4774 if (d
->next
== (DNSServer
*)~0 || d
->teststate
> DNSServer_Disabled
)
4775 LogMemCorruption("m->DNSServers: %p is garbage (%d)", d
, d
->teststate
);
4777 DomainAuthInfo
*info
;
4778 for (info
= m
->AuthInfoList
; info
; info
= info
->next
)
4779 if (info
->next
== (DomainAuthInfo
*)~0 || info
->AutoTunnel
== (const char*)~0)
4780 LogMemCorruption("m->AuthInfoList: %p is garbage (%X)", info
, info
->AutoTunnel
);
4783 for (hi
= m
->Hostnames
; hi
; hi
= hi
->next
)
4784 if (hi
->next
== (HostnameInfo
*)~0 || hi
->StatusCallback
== (mDNSRecordCallback
*)~0)
4785 LogMemCorruption("m->Hostnames: %p is garbage", n
);
4787 SearchListElem
*ptr
;
4788 for (ptr
= SearchList
; ptr
; ptr
= ptr
->next
)
4789 if (ptr
->next
== (SearchListElem
*)~0 || ptr
->AuthRecs
== (void*)~0)
4790 LogMemCorruption("SearchList: %p is garbage (%X)", ptr
, ptr
->AuthRecs
);
4794 // This should probably move to the UDS daemon -- the concept of legacy clients and automatic registration / automatic browsing
4795 // is really a UDS API issue, not something intrinsic to uDNS
4797 mDNSexport mStatus
uDNS_SetupSearchDomains(mDNS
*const m
, int action
)
4799 SearchListElem
**p
= &SearchList
, *ptr
;
4802 // step 1: mark each element for removal
4803 for (ptr
= SearchList
; ptr
; ptr
= ptr
->next
) ptr
->flag
|= SLE_DELETE
;
4805 // Make sure we have the search domains from the platform layer so that if we start the WAB
4806 // queries below, we have the latest information
4808 mDNSPlatformSetDNSConfig(m
, mDNSfalse
, mDNStrue
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
4811 if (action
& UDNS_START_WAB_QUERY
)
4812 m
->StartWABQueries
= mDNStrue
;
4814 // delete elems marked for removal, do queries for elems marked add
4818 LogInfo("uDNS_SetupSearchDomains:action %d: Flags %d, AuthRecs %p, InterfaceID %p %##s", action
, ptr
->flag
, ptr
->AuthRecs
, ptr
->InterfaceID
, ptr
->domain
.c
);
4819 if (ptr
->flag
& SLE_DELETE
)
4821 ARListElem
*arList
= ptr
->AuthRecs
;
4822 ptr
->AuthRecs
= mDNSNULL
;
4825 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries
4826 // We suppressed the domain enumeration for scoped search domains below. When we enable that
4828 if ((ptr
->flag
& SLE_WAB_QUERY_STARTED
) &&
4829 !SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
4831 mDNS_StopGetDomains(m
, &ptr
->BrowseQ
);
4832 mDNS_StopGetDomains(m
, &ptr
->RegisterQ
);
4833 mDNS_StopGetDomains(m
, &ptr
->DefBrowseQ
);
4834 mDNS_StopGetDomains(m
, &ptr
->DefRegisterQ
);
4835 mDNS_StopGetDomains(m
, &ptr
->AutomaticBrowseQ
);
4838 mDNSPlatformMemFree(ptr
);
4840 // deregister records generated from answers to the query
4843 ARListElem
*dereg
= arList
;
4844 arList
= arList
->next
;
4845 debugf("Deregistering PTR %##s -> %##s", dereg
->ar
.resrec
.name
->c
, dereg
->ar
.resrec
.rdata
->u
.name
.c
);
4846 err
= mDNS_Deregister(m
, &dereg
->ar
);
4847 if (err
) LogMsg("uDNS_SetupSearchDomains:: ERROR!! mDNS_Deregister returned %d", err
);
4848 // Memory will be freed in the FreeARElemCallback
4853 if ((action
& UDNS_START_WAB_QUERY
) && !(ptr
->flag
& SLE_WAB_QUERY_STARTED
))
4855 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries.
4856 // Also, suppress the domain enumeration for scoped search domains for now until there is a need.
4857 if (!SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
4859 mStatus err1
, err2
, err3
, err4
, err5
;
4860 err1
= mDNS_GetDomains(m
, &ptr
->BrowseQ
, mDNS_DomainTypeBrowse
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
4861 err2
= mDNS_GetDomains(m
, &ptr
->DefBrowseQ
, mDNS_DomainTypeBrowseDefault
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
4862 err3
= mDNS_GetDomains(m
, &ptr
->RegisterQ
, mDNS_DomainTypeRegistration
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
4863 err4
= mDNS_GetDomains(m
, &ptr
->DefRegisterQ
, mDNS_DomainTypeRegistrationDefault
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
4864 err5
= mDNS_GetDomains(m
, &ptr
->AutomaticBrowseQ
, mDNS_DomainTypeBrowseAutomatic
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
4865 if (err1
|| err2
|| err3
|| err4
|| err5
)
4866 LogMsg("uDNS_SetupSearchDomains: GetDomains for domain %##s returned error(s):\n"
4867 "%d (mDNS_DomainTypeBrowse)\n"
4868 "%d (mDNS_DomainTypeBrowseDefault)\n"
4869 "%d (mDNS_DomainTypeRegistration)\n"
4870 "%d (mDNS_DomainTypeRegistrationDefault)"
4871 "%d (mDNS_DomainTypeBrowseAutomatic)\n",
4872 ptr
->domain
.c
, err1
, err2
, err3
, err4
, err5
);
4873 ptr
->flag
|= SLE_WAB_QUERY_STARTED
;
4879 return mStatus_NoError
;
4882 mDNSexport domainname
*uDNS_GetNextSearchDomain(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSs8
*searchIndex
, mDNSBool ignoreDotLocal
)
4884 SearchListElem
*p
= SearchList
;
4885 int count
= *searchIndex
;
4888 if (count
< 0) { LogMsg("uDNS_GetNextSearchDomain: count %d less than zero", count
); return mDNSNULL
; }
4890 // Skip the domains that we already looked at before. Guard against "p"
4891 // being NULL. When search domains change we may not set the SearchListIndex
4892 // of the question to zero immediately e.g., domain enumeration query calls
4893 // uDNS_SetupSearchDomain which reads in the new search domain but does not
4894 // restart the questions immediately. Questions are restarted as part of
4895 // network change and hence temporarily SearchListIndex may be out of range.
4897 for (; count
&& p
; count
--)
4902 int labels
= CountLabels(&p
->domain
);
4905 const domainname
*d
= SkipLeadingLabels(&p
->domain
, labels
- 1);
4906 if (SameDomainLabel(d
->c
, (const mDNSu8
*)"\x4" "arpa"))
4908 LogInfo("uDNS_GetNextSearchDomain: skipping search domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
4913 if (ignoreDotLocal
&& SameDomainLabel(d
->c
, (const mDNSu8
*)"\x5" "local"))
4915 LogInfo("uDNS_GetNextSearchDomain: skipping local domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
4921 // Point to the next one in the list which we will look at next time.
4923 // When we are appending search domains in a ActiveDirectory domain, the question's InterfaceID
4924 // set to mDNSInterface_Unicast. Match the unscoped entries in that case.
4925 if (((InterfaceID
== mDNSInterface_Unicast
) && (p
->InterfaceID
== mDNSInterface_Any
)) ||
4926 p
->InterfaceID
== InterfaceID
)
4928 LogInfo("uDNS_GetNextSearchDomain returning domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
4931 LogInfo("uDNS_GetNextSearchDomain skipping domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
4937 mDNSlocal
void FlushAddressCacheRecords(mDNS
*const m
)
4942 FORALL_CACHERECORDS(slot
, cg
, cr
)
4944 if (cr
->resrec
.InterfaceID
) continue;
4946 // If a resource record can answer A or AAAA, they need to be flushed so that we will
4947 // deliver an ADD or RMV
4948 if (RRTypeAnswersQuestionType(&cr
->resrec
, kDNSType_A
) ||
4949 RRTypeAnswersQuestionType(&cr
->resrec
, kDNSType_AAAA
))
4951 LogInfo("FlushAddressCacheRecords: Purging Resourcerecord %s", CRDisplayString(m
, cr
));
4952 mDNS_PurgeCacheResourceRecord(m
, cr
);
4957 // Retry questions which has seach domains appended
4958 mDNSexport
void RetrySearchDomainQuestions(mDNS
*const m
)
4960 // Purge all the A/AAAA cache records and restart the queries. mDNSCoreRestartAddressQueries
4961 // does this. When we restart the question, we first want to try the new search domains rather
4962 // than use the entries that is already in the cache. When we appended search domains, we might
4963 // have created cache entries which is no longer valid as there are new search domains now
4965 LogInfo("RetrySearchDomainQuestions: Calling mDNSCoreRestartAddressQueries");
4966 mDNSCoreRestartAddressQueries(m
, mDNStrue
, FlushAddressCacheRecords
, mDNSNULL
, mDNSNULL
);
4969 // Construction of Default Browse domain list (i.e. when clients pass NULL) is as follows:
4970 // 1) query for b._dns-sd._udp.local on LocalOnly interface
4971 // (.local manually generated via explicit callback)
4972 // 2) for each search domain (from prefs pane), query for b._dns-sd._udp.<searchdomain>.
4973 // 3) for each result from (2), register LocalOnly PTR record b._dns-sd._udp.local. -> <result>
4974 // 4) result above should generate a callback from question in (1). result added to global list
4975 // 5) global list delivered to client via GetSearchDomainList()
4976 // 6) client calls to enumerate domains now go over LocalOnly interface
4977 // (!!!KRS may add outgoing interface in addition)
4979 struct CompileTimeAssertionChecks_uDNS
4981 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4982 // other overly-large structures instead of having a pointer to them, can inadvertently
4983 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
4984 char sizecheck_tcpInfo_t
[(sizeof(tcpInfo_t
) <= 9056) ? 1 : -1];
4985 char sizecheck_SearchListElem
[(sizeof(SearchListElem
) <= 5000) ? 1 : -1];