2 * Copyright (c) 2002-2020 Apple Inc. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 * Elimate all mDNSPlatformMemAllocate/mDNSPlatformMemFree from this code -- the core code
18 * is supposed to be malloc-free so that it runs in constant memory determined at compile-time.
19 * Any dynamic run-time requirements should be handled by the platform layer below or client layer above
24 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
28 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
29 #include "SymptomReporter.h"
32 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
33 #include "QuerierSupport.h"
36 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
37 #include "dnssec_v2.h"
38 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
40 #if (defined(_MSC_VER))
41 // Disable "assignment within conditional expression".
42 // Other compilers understand the convention that if you place the assignment expression within an extra pair
43 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
44 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
45 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
46 #pragma warning(disable:4706)
49 // For domain enumeration and automatic browsing
50 // This is the user's DNS search list.
51 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
52 // to discover recommended domains for domain enumeration (browse, default browse, registration,
53 // default registration) and possibly one or more recommended automatic browsing domains.
54 mDNSexport SearchListElem
*SearchList
= mDNSNULL
;
56 // The value can be set to true by the Platform code e.g., MacOSX uses the plist mechanism
57 mDNSBool StrictUnicastOrdering
= mDNSfalse
;
59 extern mDNS mDNSStorage
;
61 // We keep track of the number of unicast DNS servers and log a message when we exceed 64.
62 // Currently the unicast queries maintain a 128 bit map to track the valid DNS servers for that
63 // question. Bit position is the index into the DNS server list. This is done so to try all
64 // the servers exactly once before giving up. If we could allocate memory in the core, then
65 // arbitrary limitation of 128 DNSServers can be removed.
66 #define MAX_UNICAST_DNS_SERVERS 128
68 #define SetNextuDNSEvent(m, rr) { \
69 if ((m)->NextuDNSEvent - ((rr)->LastAPTime + (rr)->ThisAPInterval) >= 0) \
70 (m)->NextuDNSEvent = ((rr)->LastAPTime + (rr)->ThisAPInterval); \
73 #ifndef UNICAST_DISABLED
75 // ***************************************************************************
76 #if COMPILER_LIKES_PRAGMA_MARK
77 #pragma mark - General Utility Functions
80 // set retry timestamp for record with exponential backoff
81 mDNSlocal
void SetRecordRetry(mDNS
*const m
, AuthRecord
*rr
, mDNSu32 random
)
83 rr
->LastAPTime
= m
->timenow
;
85 if (rr
->expire
&& rr
->refreshCount
< MAX_UPDATE_REFRESH_COUNT
)
87 mDNSs32 remaining
= rr
->expire
- m
->timenow
;
89 if (remaining
> MIN_UPDATE_REFRESH_TIME
)
91 // Refresh at 70% + random (currently it is 0 to 10%)
92 rr
->ThisAPInterval
= 7 * (remaining
/10) + (random
? random
: mDNSRandom(remaining
/10));
93 // Don't update more often than 5 minutes
94 if (rr
->ThisAPInterval
< MIN_UPDATE_REFRESH_TIME
)
95 rr
->ThisAPInterval
= MIN_UPDATE_REFRESH_TIME
;
96 LogInfo("SetRecordRetry refresh in %d of %d for %s",
97 rr
->ThisAPInterval
/mDNSPlatformOneSecond
, (rr
->expire
- m
->timenow
)/mDNSPlatformOneSecond
, ARDisplayString(m
, rr
));
101 rr
->ThisAPInterval
= MIN_UPDATE_REFRESH_TIME
;
102 LogInfo("SetRecordRetry clamping to min refresh in %d of %d for %s",
103 rr
->ThisAPInterval
/mDNSPlatformOneSecond
, (rr
->expire
- m
->timenow
)/mDNSPlatformOneSecond
, ARDisplayString(m
, rr
));
110 rr
->ThisAPInterval
= rr
->ThisAPInterval
* QuestionIntervalStep
; // Same Retry logic as Unicast Queries
111 if (rr
->ThisAPInterval
< INIT_RECORD_REG_INTERVAL
)
112 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
113 if (rr
->ThisAPInterval
> MAX_RECORD_REG_INTERVAL
)
114 rr
->ThisAPInterval
= MAX_RECORD_REG_INTERVAL
;
116 LogInfo("SetRecordRetry retry in %d ms for %s", rr
->ThisAPInterval
, ARDisplayString(m
, rr
));
119 // ***************************************************************************
120 #if COMPILER_LIKES_PRAGMA_MARK
121 #pragma mark - Name Server List Management
124 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
125 mDNSexport DNSServer
*mDNS_AddDNSServer(mDNS
*const m
, const domainname
*domain
, const mDNSInterfaceID interface
,
126 const mDNSs32 serviceID
, const mDNSAddr
*addr
, const mDNSIPPort port
, ScopeType scopeType
, mDNSu32 timeout
,
127 mDNSBool isCell
, mDNSBool isExpensive
, mDNSBool isConstrained
, mDNSBool isCLAT46
, mDNSu32 resGroupID
,
128 mDNSBool usableA
, mDNSBool usableAAAA
, mDNSBool reqDO
)
132 int dnsCount
= CountOfUnicastDNSServers(m
);
133 if (dnsCount
>= MAX_UNICAST_DNS_SERVERS
)
135 LogMsg("mDNS_AddDNSServer: DNS server count of %d reached, not adding this server", dnsCount
);
139 if (!domain
) domain
= (const domainname
*)"";
141 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
142 "mDNS_AddDNSServer(%d): Adding " PRI_IP_ADDR
" for " PRI_DM_NAME
" interface " PUB_S
" (%p), serviceID %u, "
143 "scopeType %d, resGroupID %u" PUB_S PUB_S PUB_S PUB_S PUB_S PUB_S PUB_S
,
144 dnsCount
+ 1, addr
, DM_NAME_PARAM(domain
), InterfaceNameForID(&mDNSStorage
, interface
), interface
, serviceID
,
145 (int)scopeType
, resGroupID
,
146 usableA
? ", usableA" : "",
147 usableAAAA
? ", usableAAAA" : "",
148 isCell
? ", cell" : "",
149 isExpensive
? ", expensive" : "",
150 isConstrained
? ", constrained" : "",
151 isCLAT46
? ", CLAT46" : "",
152 reqDO
? ", reqDO" : "");
156 // Scan our existing list to see if we already have a matching record for this DNS resolver
157 for (p
= &m
->DNSServers
; (server
= *p
) != mDNSNULL
; p
= &server
->next
)
159 if (server
->interface
!= interface
) continue;
160 if (server
->serviceID
!= serviceID
) continue;
161 if (!mDNSSameAddress(&server
->addr
, addr
)) continue;
162 if (!mDNSSameIPPort(server
->port
, port
)) continue;
163 if (!SameDomainName(&server
->domain
, domain
)) continue;
164 if (server
->scopeType
!= scopeType
) continue;
165 if (server
->timeout
!= timeout
) continue;
166 if (!server
->usableA
!= !usableA
) continue;
167 if (!server
->usableAAAA
!= !usableAAAA
) continue;
168 if (!server
->isCell
!= !isCell
) continue;
169 if (!(server
->flags
& DNSServerFlag_Delete
))
171 debugf("Note: DNS Server %#a:%d for domain %##s (%p) registered more than once",
172 addr
, mDNSVal16(port
), domain
->c
, interface
);
174 // If we found a matching record, cut it from the list
175 // (and if we’re *not* resurrecting a record that was marked for deletion, it’s a duplicate,
176 // and the debugf message signifies that we’re collapsing duplicate entries into one)
178 server
->next
= mDNSNULL
;
182 // If we broke out because we found an existing matching record, advance our pointer to the end of the list
190 if (server
->flags
& DNSServerFlag_Delete
)
192 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
193 server
->flags
&= ~DNSServerFlag_Unreachable
;
195 server
->flags
&= ~DNSServerFlag_Delete
;
197 server
->isExpensive
= isExpensive
;
198 server
->isConstrained
= isConstrained
;
199 server
->isCLAT46
= isCLAT46
;
200 *p
= server
; // Append resurrected record at end of list
204 server
= (DNSServer
*) mDNSPlatformMemAllocateClear(sizeof(*server
));
207 LogMsg("Error: mDNS_AddDNSServer - malloc");
211 server
->interface
= interface
;
212 server
->serviceID
= serviceID
;
213 server
->addr
= *addr
;
215 server
->scopeType
= scopeType
;
216 server
->timeout
= timeout
;
217 server
->usableA
= usableA
;
218 server
->usableAAAA
= usableAAAA
;
219 server
->isCell
= isCell
;
220 server
->isExpensive
= isExpensive
;
221 server
->isConstrained
= isConstrained
;
222 server
->isCLAT46
= isCLAT46
;
223 AssignDomainName(&server
->domain
, domain
);
224 *p
= server
; // Append new record at end of list
229 server
->penaltyTime
= 0;
230 // We always update the ID (not just when we allocate a new instance) because we want
231 // all the resGroupIDs for a particular domain to match.
232 server
->resGroupID
= resGroupID
;
237 // PenalizeDNSServer is called when the number of queries to the unicast
238 // DNS server exceeds MAX_UCAST_UNANSWERED_QUERIES or when we receive an
239 // error e.g., SERV_FAIL from DNS server.
240 mDNSexport
void PenalizeDNSServer(mDNS
*const m
, DNSQuestion
*q
, mDNSOpaque16 responseFlags
)
243 DNSServer
*orig
= q
->qDNSServer
;
248 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
249 "PenalizeDNSServer: Penalizing DNS server " PRI_IP_ADDR
" question for question %p " PRI_DM_NAME
" (" PUB_S
") SuppressUnusable %d",
250 (q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), q
->SuppressUnusable
);
252 // If we get error from any DNS server, remember the error. If all of the servers,
253 // return the error, then return the first error.
254 if (mDNSOpaque16IsZero(q
->responseFlags
))
255 q
->responseFlags
= responseFlags
;
257 rcode
= (mDNSu8
)(responseFlags
.b
[1] & kDNSFlag1_RC_Mask
);
259 // After we reset the qDNSServer to NULL, we could get more SERV_FAILS that might end up
264 // If strict ordering of unicast servers needs to be preserved, we just lookup
265 // the next best match server below
267 // If strict ordering is not required which is the default behavior, we penalize the server
268 // for DNSSERVER_PENALTY_TIME. We may also use additional logic e.g., don't penalize for PTR
271 if (!StrictUnicastOrdering
)
273 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "PenalizeDNSServer: Strict Unicast Ordering is FALSE");
274 // We penalize the server so that new queries don't pick this server for DNSSERVER_PENALTY_TIME
275 // XXX Include other logic here to see if this server should really be penalized
277 if (q
->qtype
== kDNSType_PTR
)
279 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "PenalizeDNSServer: Not Penalizing PTR question");
281 else if ((rcode
== kDNSFlag1_RC_FormErr
) || (rcode
== kDNSFlag1_RC_ServFail
) || (rcode
== kDNSFlag1_RC_NotImpl
))
283 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
284 "PenalizeDNSServer: Not Penalizing DNS Server since it at least responded with rcode %d", rcode
);
288 const char *reason
= "";
289 if (rcode
== kDNSFlag1_RC_Refused
)
291 reason
= " because server refused to answer";
293 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "PenalizeDNSServer: Penalizing question type %d" PUB_S
,
295 q
->qDNSServer
->penaltyTime
= NonZeroTime(m
->timenow
+ DNSSERVER_PENALTY_TIME
);
300 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "PenalizeDNSServer: Strict Unicast Ordering is TRUE");
304 new = GetServerForQuestion(m
, q
);
310 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
311 "PenalizeDNSServer: ERROR!! GetServerForQuestion returned the same server " PRI_IP_ADDR
":%d",
312 &new->addr
, mDNSVal16(new->port
));
313 q
->ThisQInterval
= 0; // Inactivate this question so that we dont bombard the network
317 // When we have no more DNS servers, we might end up calling PenalizeDNSServer multiple
318 // times when we receive SERVFAIL from delayed packets in the network e.g., DNS server
319 // is slow in responding and we have sent three queries. When we repeatedly call, it is
320 // okay to receive the same NULL DNS server. Next time we try to send the query, we will
321 // realize and re-initialize the DNS servers.
322 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "PenalizeDNSServer: GetServerForQuestion returned the same server NULL");
327 // The new DNSServer is set in DNSServerChangeForQuestion
328 DNSServerChangeForQuestion(m
, q
, new);
332 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
333 "PenalizeDNSServer: Server for " PRI_DM_NAME
" (" PUB_S
") changed to " PRI_IP_ADDR
":%d (" PRI_DM_NAME
")",
334 DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), &q
->qDNSServer
->addr
, mDNSVal16(q
->qDNSServer
->port
), DM_NAME_PARAM(&q
->qDNSServer
->domain
));
335 // We want to try the next server immediately. As the question may already have backed off, reset
336 // the interval. We do this only the first time when we try all the DNS servers. Once we reached the end of
337 // list and retrying all the servers again e.g., at least one server failed to respond in the previous try, we
338 // use the normal backoff which is done in uDNS_CheckCurrentQuestion when we send the packet out.
339 if (!q
->triedAllServersOnce
)
341 q
->ThisQInterval
= InitialQuestionInterval
;
342 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
343 SetNextQueryTime(m
, q
);
348 // We don't have any more DNS servers for this question. If some server in the list did not return
349 // any response, we need to keep retrying till we get a response. uDNS_CheckCurrentQuestion handles
352 // If all servers responded with a negative response, We need to do two things. First, generate a
353 // negative response so that applications get a reply. We also need to reinitialize the DNS servers
354 // so that when the cache expires, we can restart the query. We defer this up until we generate
355 // a negative cache response in uDNS_CheckCurrentQuestion.
357 // Be careful not to touch the ThisQInterval here. For a normal question, when we answer the question
358 // in AnswerCurrentQuestionWithResourceRecord will set ThisQInterval to MaxQuestionInterval and hence
359 // the next query will not happen until cache expiry. If it is a long lived question,
360 // AnswerCurrentQuestionWithResourceRecord will not set it to MaxQuestionInterval. In that case,
361 // we want the normal backoff to work.
362 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
363 "PenalizeDNSServer: Server for %p, " PRI_DM_NAME
" (" PUB_S
") changed to NULL, Interval %d",
364 q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), q
->ThisQInterval
);
366 q
->unansweredQueries
= 0;
370 #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
372 // ***************************************************************************
373 #if COMPILER_LIKES_PRAGMA_MARK
374 #pragma mark - authorization management
377 mDNSlocal DomainAuthInfo
*GetAuthInfoForName_direct(mDNS
*m
, const domainname
*const name
)
379 const domainname
*n
= name
;
383 for (ptr
= m
->AuthInfoList
; ptr
; ptr
= ptr
->next
)
384 if (SameDomainName(&ptr
->domain
, n
))
386 debugf("GetAuthInfoForName %##s Matched %##s Key name %##s", name
->c
, ptr
->domain
.c
, ptr
->keyname
.c
);
389 n
= (const domainname
*)(n
->c
+ 1 + n
->c
[0]);
391 //LogInfo("GetAuthInfoForName none found for %##s", name->c);
395 // MUST be called with lock held
396 mDNSexport DomainAuthInfo
*GetAuthInfoForName_internal(mDNS
*m
, const domainname
*const name
)
398 DomainAuthInfo
**p
= &m
->AuthInfoList
;
402 // First purge any dead keys from the list
405 if ((*p
)->deltime
&& m
->timenow
- (*p
)->deltime
>= 0)
408 DomainAuthInfo
*info
= *p
;
409 LogInfo("GetAuthInfoForName_internal deleting expired key %##s %##s", info
->domain
.c
, info
->keyname
.c
);
410 *p
= info
->next
; // Cut DomainAuthInfo from list *before* scanning our question list updating AuthInfo pointers
411 for (q
= m
->Questions
; q
; q
=q
->next
)
412 if (q
->AuthInfo
== info
)
414 q
->AuthInfo
= GetAuthInfoForName_direct(m
, &q
->qname
);
415 debugf("GetAuthInfoForName_internal updated q->AuthInfo from %##s to %##s for %##s (%s)",
416 info
->domain
.c
, q
->AuthInfo
? q
->AuthInfo
->domain
.c
: mDNSNULL
, q
->qname
.c
, DNSTypeName(q
->qtype
));
419 // Probably not essential, but just to be safe, zero out the secret key data
420 // so we don't leave it hanging around in memory
421 // (where it could potentially get exposed via some other bug)
422 mDNSPlatformMemZero(info
, sizeof(*info
));
423 mDNSPlatformMemFree(info
);
429 return(GetAuthInfoForName_direct(m
, name
));
432 mDNSexport DomainAuthInfo
*GetAuthInfoForName(mDNS
*m
, const domainname
*const name
)
436 d
= GetAuthInfoForName_internal(m
, name
);
441 // MUST be called with the lock held
442 mDNSexport mStatus
mDNS_SetSecretForDomain(mDNS
*m
, DomainAuthInfo
*info
,
443 const domainname
*domain
, const domainname
*keyname
, const char *b64keydata
, const domainname
*hostname
, mDNSIPPort
*port
)
446 DomainAuthInfo
**p
= &m
->AuthInfoList
;
447 if (!info
|| !b64keydata
) { LogMsg("mDNS_SetSecretForDomain: ERROR: info %p b64keydata %p", info
, b64keydata
); return(mStatus_BadParamErr
); }
449 LogInfo("mDNS_SetSecretForDomain: domain %##s key %##s", domain
->c
, keyname
->c
);
451 AssignDomainName(&info
->domain
, domain
);
452 AssignDomainName(&info
->keyname
, keyname
);
454 AssignDomainName(&info
->hostname
, hostname
);
456 info
->hostname
.c
[0] = 0;
460 info
->port
= zeroIPPort
;
461 mDNS_snprintf(info
->b64keydata
, sizeof(info
->b64keydata
), "%s", b64keydata
);
463 if (DNSDigest_ConstructHMACKeyfromBase64(info
, b64keydata
) < 0)
465 LogMsg("mDNS_SetSecretForDomain: ERROR: Could not convert shared secret from base64: domain %##s key %##s %s", domain
->c
, keyname
->c
, mDNS_LoggingEnabled
? b64keydata
: "");
466 return(mStatus_BadParamErr
);
469 // Don't clear deltime until after we've ascertained that b64keydata is valid
472 while (*p
&& (*p
) != info
) p
=&(*p
)->next
;
473 if (*p
) {LogInfo("mDNS_SetSecretForDomain: Domain %##s Already in list", (*p
)->domain
.c
); return(mStatus_AlreadyRegistered
);}
475 info
->next
= mDNSNULL
;
478 // Check to see if adding this new DomainAuthInfo has changed the credentials for any of our questions
479 for (q
= m
->Questions
; q
; q
=q
->next
)
481 DomainAuthInfo
*newinfo
= GetAuthInfoForQuestion(m
, q
);
482 if (q
->AuthInfo
!= newinfo
)
484 debugf("mDNS_SetSecretForDomain updating q->AuthInfo from %##s to %##s for %##s (%s)",
485 q
->AuthInfo
? q
->AuthInfo
->domain
.c
: mDNSNULL
,
486 newinfo
? newinfo
->domain
.c
: mDNSNULL
, q
->qname
.c
, DNSTypeName(q
->qtype
));
487 q
->AuthInfo
= newinfo
;
491 return(mStatus_NoError
);
494 // ***************************************************************************
495 #if COMPILER_LIKES_PRAGMA_MARK
497 #pragma mark - NAT Traversal
500 // Keep track of when to request/refresh the external address using NAT-PMP or UPnP/IGD,
501 // and do so when necessary
502 mDNSlocal mStatus
uDNS_RequestAddress(mDNS
*m
)
504 mStatus err
= mStatus_NoError
;
506 if (!m
->NATTraversals
)
508 m
->retryGetAddr
= NonZeroTime(m
->timenow
+ FutureTime
);
509 LogInfo("uDNS_RequestAddress: Setting retryGetAddr to future");
511 else if (m
->timenow
- m
->retryGetAddr
>= 0)
513 if (mDNSv4AddrIsRFC1918(&m
->Router
.ip
.v4
))
515 static NATAddrRequest req
= {NATMAP_VERS
, NATOp_AddrRequest
};
516 static mDNSu8
* start
= (mDNSu8
*)&req
;
517 mDNSu8
* end
= start
+ sizeof(NATAddrRequest
);
518 err
= mDNSPlatformSendUDP(m
, start
, end
, 0, mDNSNULL
, &m
->Router
, NATPMPPort
, mDNSfalse
);
519 debugf("uDNS_RequestAddress: Sent NAT-PMP external address request %d", err
);
521 #ifdef _LEGACY_NAT_TRAVERSAL_
522 if (mDNSIPPortIsZero(m
->UPnPRouterPort
) || mDNSIPPortIsZero(m
->UPnPSOAPPort
))
524 LNT_SendDiscoveryMsg(m
);
525 debugf("uDNS_RequestAddress: LNT_SendDiscoveryMsg");
529 mStatus lnterr
= LNT_GetExternalAddress(m
);
531 LogMsg("uDNS_RequestAddress: LNT_GetExternalAddress returned error %d", lnterr
);
533 err
= err
? err
: lnterr
; // NAT-PMP error takes precedence
535 #endif // _LEGACY_NAT_TRAVERSAL_
538 // Always update the interval and retry time, so that even if we fail to send the
539 // packet, we won't spin in an infinite loop repeatedly failing to send the packet
540 if (m
->retryIntervalGetAddr
< NATMAP_INIT_RETRY
)
542 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
544 else if (m
->retryIntervalGetAddr
< NATMAP_MAX_RETRY_INTERVAL
/ 2)
546 m
->retryIntervalGetAddr
*= 2;
550 m
->retryIntervalGetAddr
= NATMAP_MAX_RETRY_INTERVAL
;
553 m
->retryGetAddr
= NonZeroTime(m
->timenow
+ m
->retryIntervalGetAddr
);
557 debugf("uDNS_RequestAddress: Not time to send address request");
560 // Always update NextScheduledNATOp, even if we didn't change retryGetAddr, so we'll
561 // be called when we need to send the request(s)
562 if (m
->NextScheduledNATOp
- m
->retryGetAddr
> 0)
563 m
->NextScheduledNATOp
= m
->retryGetAddr
;
568 mDNSlocal mStatus
uDNS_SendNATMsg(mDNS
*m
, NATTraversalInfo
*info
, mDNSBool usePCP
, mDNSBool unmapping
)
570 mStatus err
= mStatus_NoError
;
574 LogMsg("uDNS_SendNATMsg called unexpectedly with NULL info");
575 return mStatus_BadParamErr
;
578 // send msg if the router's address is private (which means it's non-zero)
579 if (mDNSv4AddrIsRFC1918(&m
->Router
.ip
.v4
))
583 if (!info
->sentNATPMP
)
587 static NATPortMapRequest NATPortReq
;
588 static const mDNSu8
* end
= (mDNSu8
*)&NATPortReq
+ sizeof(NATPortMapRequest
);
589 mDNSu8
*p
= (mDNSu8
*)&NATPortReq
.NATReq_lease
;
591 NATPortReq
.vers
= NATMAP_VERS
;
592 NATPortReq
.opcode
= info
->Protocol
;
593 NATPortReq
.unused
= zeroID
;
594 NATPortReq
.intport
= info
->IntPort
;
595 NATPortReq
.extport
= info
->RequestedPort
;
596 p
[0] = (mDNSu8
)((info
->NATLease
>> 24) & 0xFF);
597 p
[1] = (mDNSu8
)((info
->NATLease
>> 16) & 0xFF);
598 p
[2] = (mDNSu8
)((info
->NATLease
>> 8) & 0xFF);
599 p
[3] = (mDNSu8
)( info
->NATLease
& 0xFF);
601 err
= mDNSPlatformSendUDP(m
, (mDNSu8
*)&NATPortReq
, end
, 0, mDNSNULL
, &m
->Router
, NATPMPPort
, mDNSfalse
);
602 debugf("uDNS_SendNATMsg: Sent NAT-PMP mapping request %d", err
);
605 // In case the address request already went out for another NAT-T,
606 // set the NewAddress to the currently known global external address, so
607 // Address-only operations will get the callback immediately
608 info
->NewAddress
= m
->ExtAddress
;
610 // Remember that we just sent a NAT-PMP packet, so we won't resend one later.
611 // We do this because the NAT-PMP "Unsupported Version" response has no
612 // information about the (PCP) request that triggered it, so we must send
613 // NAT-PMP requests for all operations. Without this, we'll send n PCP
614 // requests for n operations, receive n NAT-PMP "Unsupported Version"
615 // responses, and send n NAT-PMP requests for each of those responses,
616 // resulting in (n + n^2) packets sent. We only want to send 2n packets:
617 // n PCP requests followed by n NAT-PMP requests.
618 info
->sentNATPMP
= mDNStrue
;
624 mDNSu8
* start
= (mDNSu8
*)&req
;
625 mDNSu8
* end
= start
+ sizeof(req
);
626 mDNSu8
* p
= (mDNSu8
*)&req
.lifetime
;
628 req
.version
= PCP_VERS
;
629 req
.opCode
= PCPOp_Map
;
630 req
.reserved
= zeroID
;
632 p
[0] = (mDNSu8
)((info
->NATLease
>> 24) & 0xFF);
633 p
[1] = (mDNSu8
)((info
->NATLease
>> 16) & 0xFF);
634 p
[2] = (mDNSu8
)((info
->NATLease
>> 8) & 0xFF);
635 p
[3] = (mDNSu8
)( info
->NATLease
& 0xFF);
637 mDNSAddrMapIPv4toIPv6(&m
->AdvertisedV4
.ip
.v4
, &req
.clientAddr
);
639 req
.nonce
[0] = m
->PCPNonce
[0];
640 req
.nonce
[1] = m
->PCPNonce
[1];
641 req
.nonce
[2] = m
->PCPNonce
[2];
643 req
.protocol
= (info
->Protocol
== NATOp_MapUDP
? PCPProto_UDP
: PCPProto_TCP
);
645 req
.reservedMapOp
[0] = 0;
646 req
.reservedMapOp
[1] = 0;
647 req
.reservedMapOp
[2] = 0;
649 req
.intPort
= info
->Protocol
? info
->IntPort
: DiscardPort
;
650 req
.extPort
= info
->RequestedPort
;
652 // Since we only support IPv4, even if using the all-zeros address, map it, so
653 // the PCP gateway will give us an IPv4 address & not an IPv6 address.
654 mDNSAddrMapIPv4toIPv6(&info
->NewAddress
, &req
.extAddress
);
656 err
= mDNSPlatformSendUDP(m
, start
, end
, 0, mDNSNULL
, &m
->Router
, NATPMPPort
, mDNSfalse
);
657 debugf("uDNS_SendNATMsg: Sent PCP Mapping request %d", err
);
659 // Unset the sentNATPMP flag, so that we'll send a NAT-PMP packet if we
660 // receive a NAT-PMP "Unsupported Version" packet. This will result in every
661 // renewal, retransmission, etc. being tried first as PCP, then if a NAT-PMP
662 // "Unsupported Version" response is received, fall-back & send the request
664 info
->sentNATPMP
= mDNSfalse
;
666 #ifdef _LEGACY_NAT_TRAVERSAL_
667 // If an unmapping is being performed, then don't send an LNT discovery message or an LNT port map request.
670 if (mDNSIPPortIsZero(m
->UPnPRouterPort
) || mDNSIPPortIsZero(m
->UPnPSOAPPort
))
672 LNT_SendDiscoveryMsg(m
);
673 debugf("uDNS_SendNATMsg: LNT_SendDiscoveryMsg");
677 mStatus lnterr
= LNT_MapPort(m
, info
);
679 LogMsg("uDNS_SendNATMsg: LNT_MapPort returned error %d", lnterr
);
681 err
= err
? err
: lnterr
; // PCP error takes precedence
685 (void)unmapping
; // Unused
686 #endif // _LEGACY_NAT_TRAVERSAL_
693 mDNSexport
void RecreateNATMappings(mDNS
*const m
, const mDNSu32 waitTicks
)
695 mDNSu32 when
= NonZeroTime(m
->timenow
+ waitTicks
);
697 for (n
= m
->NATTraversals
; n
; n
=n
->next
)
699 n
->ExpiryTime
= 0; // Mark this mapping as expired
700 n
->retryInterval
= NATMAP_INIT_RETRY
;
701 n
->retryPortMap
= when
;
702 n
->lastSuccessfulProtocol
= NATTProtocolNone
;
703 if (!n
->Protocol
) n
->NewResult
= mStatus_NoError
;
704 #ifdef _LEGACY_NAT_TRAVERSAL_
705 if (n
->tcpInfo
.sock
) { mDNSPlatformTCPCloseConnection(n
->tcpInfo
.sock
); n
->tcpInfo
.sock
= mDNSNULL
; }
706 #endif // _LEGACY_NAT_TRAVERSAL_
709 m
->PCPNonce
[0] = mDNSRandom(-1);
710 m
->PCPNonce
[1] = mDNSRandom(-1);
711 m
->PCPNonce
[2] = mDNSRandom(-1);
712 m
->retryIntervalGetAddr
= 0;
713 m
->retryGetAddr
= when
;
715 #ifdef _LEGACY_NAT_TRAVERSAL_
717 #endif // _LEGACY_NAT_TRAVERSAL_
719 m
->NextScheduledNATOp
= m
->timenow
; // Need to send packets immediately
722 mDNSexport
void natTraversalHandleAddressReply(mDNS
*const m
, mDNSu16 err
, mDNSv4Addr ExtAddr
)
724 static mDNSu16 last_err
= 0;
729 if (err
!= last_err
) LogMsg("Error getting external address %d", err
);
730 ExtAddr
= zerov4Addr
;
734 LogInfo("Received external IP address %.4a from NAT", &ExtAddr
);
735 if (mDNSv4AddrIsRFC1918(&ExtAddr
))
736 LogMsg("Double NAT (external NAT gateway address %.4a is also a private RFC 1918 address)", &ExtAddr
);
737 if (mDNSIPv4AddressIsZero(ExtAddr
))
738 err
= NATErr_NetFail
; // fake error to handle routers that pathologically report success with the zero address
741 // Globally remember the most recently discovered address, so it can be used in each
742 // new NATTraversal structure
743 m
->ExtAddress
= ExtAddr
;
745 if (!err
) // Success, back-off to maximum interval
746 m
->retryIntervalGetAddr
= NATMAP_MAX_RETRY_INTERVAL
;
747 else if (!last_err
) // Failure after success, retry quickly (then back-off exponentially)
748 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
749 // else back-off normally in case of pathological failures
751 m
->retryGetAddr
= m
->timenow
+ m
->retryIntervalGetAddr
;
752 if (m
->NextScheduledNATOp
- m
->retryGetAddr
> 0)
753 m
->NextScheduledNATOp
= m
->retryGetAddr
;
757 for (n
= m
->NATTraversals
; n
; n
=n
->next
)
759 // We should change n->NewAddress only when n is one of:
760 // 1) a mapping operation that most recently succeeded using NAT-PMP or UPnP/IGD,
761 // because such an operation needs the update now. If the lastSuccessfulProtocol
762 // is currently none, then natTraversalHandlePortMapReplyWithAddress() will be
763 // called should NAT-PMP or UPnP/IGD succeed in the future.
764 // 2) an address-only operation that did not succeed via PCP, because when such an
765 // operation succeeds via PCP, it's for the TCP discard port just to learn the
766 // address. And that address may be different than the external address
767 // discovered via NAT-PMP or UPnP/IGD. If the lastSuccessfulProtocol
768 // is currently none, we must update the NewAddress as PCP may not succeed.
769 if (!mDNSSameIPv4Address(n
->NewAddress
, ExtAddr
) &&
771 (n
->lastSuccessfulProtocol
== NATTProtocolNATPMP
|| n
->lastSuccessfulProtocol
== NATTProtocolUPNPIGD
) :
772 (n
->lastSuccessfulProtocol
!= NATTProtocolPCP
)))
774 // Needs an update immediately
775 n
->NewAddress
= ExtAddr
;
777 n
->retryInterval
= NATMAP_INIT_RETRY
;
778 n
->retryPortMap
= m
->timenow
;
779 #ifdef _LEGACY_NAT_TRAVERSAL_
780 if (n
->tcpInfo
.sock
) { mDNSPlatformTCPCloseConnection(n
->tcpInfo
.sock
); n
->tcpInfo
.sock
= mDNSNULL
; }
781 #endif // _LEGACY_NAT_TRAVERSAL_
783 m
->NextScheduledNATOp
= m
->timenow
; // Need to send packets immediately
788 // Both places that call NATSetNextRenewalTime() update m->NextScheduledNATOp correctly afterwards
789 mDNSlocal
void NATSetNextRenewalTime(mDNS
*const m
, NATTraversalInfo
*n
)
791 n
->retryInterval
= (n
->ExpiryTime
- m
->timenow
)/2;
792 if (n
->retryInterval
< NATMAP_MIN_RETRY_INTERVAL
) // Min retry interval is 2 seconds
793 n
->retryInterval
= NATMAP_MIN_RETRY_INTERVAL
;
794 n
->retryPortMap
= m
->timenow
+ n
->retryInterval
;
797 mDNSlocal
void natTraversalHandlePortMapReplyWithAddress(mDNS
*const m
, NATTraversalInfo
*n
, const mDNSInterfaceID InterfaceID
, mDNSu16 err
, mDNSv4Addr extaddr
, mDNSIPPort extport
, mDNSu32 lease
, NATTProtocol protocol
)
799 const char *prot
= n
->Protocol
== 0 ? "Add" : n
->Protocol
== NATOp_MapUDP
? "UDP" : n
->Protocol
== NATOp_MapTCP
? "TCP" : "???";
802 if (err
|| lease
== 0 || mDNSIPPortIsZero(extport
))
804 LogInfo("natTraversalHandlePortMapReplyWithAddress: %p Response %s Port %5d External %.4a:%d lease %d error %d",
805 n
, prot
, mDNSVal16(n
->IntPort
), &extaddr
, mDNSVal16(extport
), lease
, err
);
806 n
->retryInterval
= NATMAP_MAX_RETRY_INTERVAL
;
807 n
->retryPortMap
= m
->timenow
+ NATMAP_MAX_RETRY_INTERVAL
;
808 // No need to set m->NextScheduledNATOp here, since we're only ever extending the m->retryPortMap time
809 if (err
== NATErr_Refused
) n
->NewResult
= mStatus_NATPortMappingDisabled
;
810 else if (err
> NATErr_None
&& err
<= NATErr_Opcode
) n
->NewResult
= mStatus_NATPortMappingUnsupported
;
814 if (lease
> 999999999UL / mDNSPlatformOneSecond
)
815 lease
= 999999999UL / mDNSPlatformOneSecond
;
816 n
->ExpiryTime
= NonZeroTime(m
->timenow
+ lease
* mDNSPlatformOneSecond
);
818 if (!mDNSSameIPv4Address(n
->NewAddress
, extaddr
) || !mDNSSameIPPort(n
->RequestedPort
, extport
))
819 LogInfo("natTraversalHandlePortMapReplyWithAddress: %p %s Response %s Port %5d External %.4a:%d changed to %.4a:%d lease %d",
821 (n
->lastSuccessfulProtocol
== NATTProtocolNone
? "None " :
822 n
->lastSuccessfulProtocol
== NATTProtocolNATPMP
? "NAT-PMP " :
823 n
->lastSuccessfulProtocol
== NATTProtocolUPNPIGD
? "UPnP/IGD" :
824 n
->lastSuccessfulProtocol
== NATTProtocolPCP
? "PCP " :
825 /* else */ "Unknown " ),
826 prot
, mDNSVal16(n
->IntPort
), &n
->NewAddress
, mDNSVal16(n
->RequestedPort
),
827 &extaddr
, mDNSVal16(extport
), lease
);
829 n
->InterfaceID
= InterfaceID
;
830 n
->NewAddress
= extaddr
;
831 if (n
->Protocol
) n
->RequestedPort
= extport
; // Don't report the (PCP) external port to address-only operations
832 n
->lastSuccessfulProtocol
= protocol
;
834 NATSetNextRenewalTime(m
, n
); // Got our port mapping; now set timer to renew it at halfway point
835 m
->NextScheduledNATOp
= m
->timenow
; // May need to invoke client callback immediately
839 // To be called for NAT-PMP or UPnP/IGD mappings, to use currently discovered (global) address
840 mDNSexport
void natTraversalHandlePortMapReply(mDNS
*const m
, NATTraversalInfo
*n
, const mDNSInterfaceID InterfaceID
, mDNSu16 err
, mDNSIPPort extport
, mDNSu32 lease
, NATTProtocol protocol
)
842 natTraversalHandlePortMapReplyWithAddress(m
, n
, InterfaceID
, err
, m
->ExtAddress
, extport
, lease
, protocol
);
845 // Must be called with the mDNS_Lock held
846 mDNSexport mStatus
mDNS_StartNATOperation_internal(mDNS
*const m
, NATTraversalInfo
*traversal
)
848 NATTraversalInfo
**n
;
850 LogInfo("mDNS_StartNATOperation_internal %p Protocol %d IntPort %d RequestedPort %d NATLease %d", traversal
,
851 traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), mDNSVal16(traversal
->RequestedPort
), traversal
->NATLease
);
853 // Note: It important that new traversal requests are appended at the *end* of the list, not prepended at the start
854 for (n
= &m
->NATTraversals
; *n
; n
=&(*n
)->next
)
858 LogFatalError("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
859 traversal
, traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), traversal
->NATLease
);
860 return(mStatus_AlreadyRegistered
);
862 if (traversal
->Protocol
&& traversal
->Protocol
== (*n
)->Protocol
&& mDNSSameIPPort(traversal
->IntPort
, (*n
)->IntPort
) &&
863 !mDNSSameIPPort(traversal
->IntPort
, SSHPort
))
864 LogMsg("Warning: Created port mapping request %p Prot %d Int %d TTL %d "
865 "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
866 traversal
, traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), traversal
->NATLease
,
867 *n
, (*n
)->Protocol
, mDNSVal16((*n
)->IntPort
), (*n
)->NATLease
);
870 // Initialize necessary fields
871 traversal
->next
= mDNSNULL
;
872 traversal
->ExpiryTime
= 0;
873 traversal
->retryInterval
= NATMAP_INIT_RETRY
;
874 traversal
->retryPortMap
= m
->timenow
;
875 traversal
->NewResult
= mStatus_NoError
;
876 traversal
->lastSuccessfulProtocol
= NATTProtocolNone
;
877 traversal
->sentNATPMP
= mDNSfalse
;
878 traversal
->ExternalAddress
= onesIPv4Addr
;
879 traversal
->NewAddress
= zerov4Addr
;
880 traversal
->ExternalPort
= zeroIPPort
;
881 traversal
->Lifetime
= 0;
882 traversal
->Result
= mStatus_NoError
;
884 // set default lease if necessary
885 if (!traversal
->NATLease
) traversal
->NATLease
= NATMAP_DEFAULT_LEASE
;
887 #ifdef _LEGACY_NAT_TRAVERSAL_
888 mDNSPlatformMemZero(&traversal
->tcpInfo
, sizeof(traversal
->tcpInfo
));
889 #endif // _LEGACY_NAT_TRAVERSAL_
891 if (!m
->NATTraversals
) // If this is our first NAT request, kick off an address request too
893 m
->retryGetAddr
= m
->timenow
;
894 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
897 // If this is an address-only operation, initialize to the current global address,
898 // or (in non-PCP environments) we won't know the address until the next external
899 // address request/response.
900 if (!traversal
->Protocol
)
902 traversal
->NewAddress
= m
->ExtAddress
;
905 m
->NextScheduledNATOp
= m
->timenow
; // This will always trigger sending the packet ASAP, and generate client callback if necessary
907 *n
= traversal
; // Append new NATTraversalInfo to the end of our list
909 return(mStatus_NoError
);
912 // Must be called with the mDNS_Lock held
913 mDNSexport mStatus
mDNS_StopNATOperation_internal(mDNS
*m
, NATTraversalInfo
*traversal
)
915 mDNSBool unmap
= mDNStrue
;
917 NATTraversalInfo
**ptr
= &m
->NATTraversals
;
919 while (*ptr
&& *ptr
!= traversal
) ptr
=&(*ptr
)->next
;
920 if (*ptr
) *ptr
= (*ptr
)->next
; // If we found it, cut this NATTraversalInfo struct from our list
923 LogMsg("mDNS_StopNATOperation_internal: NATTraversalInfo %p not found in list", traversal
);
924 return(mStatus_BadReferenceErr
);
927 LogInfo("mDNS_StopNATOperation_internal %p %d %d %d %d", traversal
,
928 traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), mDNSVal16(traversal
->RequestedPort
), traversal
->NATLease
);
930 if (m
->CurrentNATTraversal
== traversal
)
931 m
->CurrentNATTraversal
= m
->CurrentNATTraversal
->next
;
933 // If there is a match for the operation being stopped, don't send a deletion request (unmap)
934 for (p
= m
->NATTraversals
; p
; p
=p
->next
)
936 if (traversal
->Protocol
?
937 ((traversal
->Protocol
== p
->Protocol
&& mDNSSameIPPort(traversal
->IntPort
, p
->IntPort
)) ||
938 (!p
->Protocol
&& traversal
->Protocol
== NATOp_MapTCP
&& mDNSSameIPPort(traversal
->IntPort
, DiscardPort
))) :
939 (!p
->Protocol
|| (p
->Protocol
== NATOp_MapTCP
&& mDNSSameIPPort(p
->IntPort
, DiscardPort
))))
941 LogInfo("Warning: Removed port mapping request %p Prot %d Int %d TTL %d "
942 "duplicates existing port mapping request %p Prot %d Int %d TTL %d",
943 traversal
, traversal
->Protocol
, mDNSVal16(traversal
->IntPort
), traversal
->NATLease
,
944 p
, p
->Protocol
, mDNSVal16( p
->IntPort
), p
->NATLease
);
949 // Even if we DIDN'T make a successful UPnP mapping yet, we might still have a partially-open TCP connection we need to clean up
950 // Before zeroing traversal->RequestedPort below, perform the LNT unmapping, which requires the mapping's external port,
951 // held by the traversal->RequestedPort variable.
952 #ifdef _LEGACY_NAT_TRAVERSAL_
954 mStatus err
= LNT_UnmapPort(m
, traversal
);
955 if (err
) LogMsg("Legacy NAT Traversal - unmap request failed with error %d", err
);
957 #endif // _LEGACY_NAT_TRAVERSAL_
959 if (traversal
->ExpiryTime
&& unmap
)
961 traversal
->NATLease
= 0;
962 traversal
->retryInterval
= 0;
964 // In case we most recently sent NAT-PMP, we need to set sentNATPMP to false so
965 // that we'll send a NAT-PMP request to destroy the mapping. We do this because
966 // the NATTraversal struct has already been cut from the list, and the client
967 // layer will destroy the memory upon returning from this function, so we can't
968 // try PCP first and then fall-back to NAT-PMP. That is, if we most recently
969 // created/renewed the mapping using NAT-PMP, we need to destroy it using NAT-PMP
970 // now, because we won't get a chance later.
971 traversal
->sentNATPMP
= mDNSfalse
;
973 // Both NAT-PMP & PCP RFCs state that the suggested port in deletion requests
974 // should be zero. And for PCP, the suggested external address should also be
975 // zero, specifically, the all-zeros IPv4-mapped address, since we would only
976 // would have requested an IPv4 address.
977 traversal
->RequestedPort
= zeroIPPort
;
978 traversal
->NewAddress
= zerov4Addr
;
980 uDNS_SendNATMsg(m
, traversal
, traversal
->lastSuccessfulProtocol
!= NATTProtocolNATPMP
, mDNStrue
);
983 return(mStatus_NoError
);
986 mDNSexport mStatus
mDNS_StartNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
)
990 status
= mDNS_StartNATOperation_internal(m
, traversal
);
995 mDNSexport mStatus
mDNS_StopNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
)
999 status
= mDNS_StopNATOperation_internal(m
, traversal
);
1004 // ***************************************************************************
1005 #if COMPILER_LIKES_PRAGMA_MARK
1007 #pragma mark - Long-Lived Queries
1010 // Lock must be held -- otherwise m->timenow is undefined
1011 mDNSlocal
void StartLLQPolling(mDNS
*const m
, DNSQuestion
*q
)
1013 debugf("StartLLQPolling: %##s", q
->qname
.c
);
1014 q
->state
= LLQ_Poll
;
1015 q
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
;
1016 // We want to send our poll query ASAP, but the "+ 1" is because if we set the time to now,
1017 // we risk causing spurious "SendQueries didn't send all its queries" log messages
1018 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ 1;
1019 SetNextQueryTime(m
, q
);
1022 mDNSlocal mDNSu8
*putLLQ(DNSMessage
*const msg
, mDNSu8
*ptr
, const DNSQuestion
*const question
, const LLQOptData
*const data
)
1025 ResourceRecord
*opt
= &rr
.resrec
;
1028 //!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
1029 ptr
= putQuestion(msg
, ptr
, msg
->data
+ AbsoluteMaxDNSMessageData
, &question
->qname
, question
->qtype
, question
->qclass
);
1030 if (!ptr
) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL
; }
1032 // locate OptRR if it exists, set pointer to end
1033 // !!!KRS implement me
1035 // format opt rr (fields not specified are zero-valued)
1036 mDNS_SetupResourceRecord(&rr
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
1037 opt
->rrclass
= NormalMaxDNSMessageData
;
1038 opt
->rdlength
= sizeof(rdataOPT
); // One option in this OPT record
1039 opt
->rdestimate
= sizeof(rdataOPT
);
1041 optRD
= &rr
.resrec
.rdata
->u
.opt
[0];
1042 optRD
->opt
= kDNSOpt_LLQ
;
1043 optRD
->u
.llq
= *data
;
1044 ptr
= PutResourceRecordTTLJumbo(msg
, ptr
, &msg
->h
.numAdditionals
, opt
, 0);
1045 if (!ptr
) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL
; }
1050 // Normally we'd just request event packets be sent directly to m->LLQNAT.ExternalPort, except...
1051 // with LLQs over TLS/TCP we're doing a weird thing where instead of requesting packets be sent to ExternalAddress:ExternalPort
1052 // we're requesting that packets be sent to ExternalPort, but at the source address of our outgoing TCP connection.
1053 // Normally, after going through the NAT gateway, the source address of our outgoing TCP connection is the same as ExternalAddress,
1054 // so this is fine, except when the TCP connection ends up going over a VPN tunnel instead.
1055 // To work around this, if we find that the source address for our TCP connection is not a private address, we tell the Dot Mac
1056 // LLQ server to send events to us directly at port 5353 on that address, instead of at our mapped external NAT port.
1058 mDNSlocal mDNSu16
GetLLQEventPort(const mDNS
*const m
, const mDNSAddr
*const dst
)
1061 mDNSPlatformSourceAddrForDest(&src
, dst
);
1062 //LogMsg("GetLLQEventPort: src %#a for dst %#a (%d)", &src, dst, mDNSv4AddrIsRFC1918(&src.ip.v4) ? mDNSVal16(m->LLQNAT.ExternalPort) : 0);
1063 return(mDNSv4AddrIsRFC1918(&src
.ip
.v4
) ? mDNSVal16(m
->LLQNAT
.ExternalPort
) : mDNSVal16(MulticastDNSPort
));
1066 // Normally called with llq set.
1067 // May be called with llq NULL, when retransmitting a lost Challenge Response
1068 mDNSlocal
void sendChallengeResponse(mDNS
*const m
, DNSQuestion
*const q
, const LLQOptData
*llq
)
1070 mDNSu8
*responsePtr
= m
->omsg
.data
;
1073 if (q
->tcp
) { LogMsg("sendChallengeResponse: ERROR!!: question %##s (%s) tcp non-NULL", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
1075 if (q
->ntries
++ == kLLQ_MAX_TRIES
)
1077 LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s", kLLQ_MAX_TRIES
, q
->qname
.c
);
1078 StartLLQPolling(m
,q
);
1082 if (!llq
) // Retransmission: need to make a new LLQOptData
1084 llqBuf
.vers
= kLLQ_Vers
;
1085 llqBuf
.llqOp
= kLLQOp_Setup
;
1086 llqBuf
.err
= LLQErr_NoError
; // Don't need to tell server UDP notification port when sending over UDP
1088 llqBuf
.llqlease
= q
->ReqLease
;
1092 q
->LastQTime
= m
->timenow
;
1093 q
->ThisQInterval
= q
->tcp
? 0 : (kLLQ_INIT_RESEND
* q
->ntries
* mDNSPlatformOneSecond
); // If using TCP, don't need to retransmit
1094 SetNextQueryTime(m
, q
);
1096 // To simulate loss of challenge response packet, uncomment line below
1097 //if (q->ntries == 1) return;
1099 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, uQueryFlags
);
1100 responsePtr
= putLLQ(&m
->omsg
, responsePtr
, q
, llq
);
1103 mStatus err
= mDNSSendDNSMessage(m
, &m
->omsg
, responsePtr
, mDNSInterface_Any
, mDNSNULL
, q
->LocalSocket
, &q
->servAddr
, q
->servPort
, mDNSNULL
, mDNSfalse
);
1104 if (err
) { LogMsg("sendChallengeResponse: mDNSSendDNSMessage%s failed: %d", q
->tcp
? " (TCP)" : "", err
); }
1106 else StartLLQPolling(m
,q
);
1109 mDNSlocal
void SetLLQTimer(mDNS
*const m
, DNSQuestion
*const q
, const LLQOptData
*const llq
)
1111 mDNSs32 lease
= (mDNSs32
)llq
->llqlease
* mDNSPlatformOneSecond
;
1112 q
->ReqLease
= llq
->llqlease
;
1113 q
->LastQTime
= m
->timenow
;
1114 q
->expire
= m
->timenow
+ lease
;
1115 q
->ThisQInterval
= lease
/2 + mDNSRandom(lease
/10);
1116 debugf("SetLLQTimer setting %##s (%s) to %d %d", q
->qname
.c
, DNSTypeName(q
->qtype
), lease
/mDNSPlatformOneSecond
, q
->ThisQInterval
/mDNSPlatformOneSecond
);
1117 SetNextQueryTime(m
, q
);
1120 mDNSlocal
void recvSetupResponse(mDNS
*const m
, mDNSu8 rcode
, DNSQuestion
*const q
, const LLQOptData
*const llq
)
1122 if (rcode
&& rcode
!= kDNSFlag1_RC_NXDomain
)
1123 { LogMsg("ERROR: recvSetupResponse %##s (%s) - rcode && rcode != kDNSFlag1_RC_NXDomain", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
1125 if (llq
->llqOp
!= kLLQOp_Setup
)
1126 { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad op %d", q
->qname
.c
, DNSTypeName(q
->qtype
), llq
->llqOp
); return; }
1128 if (llq
->vers
!= kLLQ_Vers
)
1129 { LogMsg("ERROR: recvSetupResponse %##s (%s) - bad vers %d", q
->qname
.c
, DNSTypeName(q
->qtype
), llq
->vers
); return; }
1131 if (q
->state
== LLQ_InitialRequest
)
1133 //LogInfo("Got LLQ_InitialRequest");
1135 if (llq
->err
) { LogMsg("recvSetupResponse - received llq->err %d from server", llq
->err
); StartLLQPolling(m
,q
); return; }
1137 if (q
->ReqLease
!= llq
->llqlease
)
1138 debugf("recvSetupResponse: requested lease %lu, granted lease %lu", q
->ReqLease
, llq
->llqlease
);
1140 // cache expiration in case we go to sleep before finishing setup
1141 q
->ReqLease
= llq
->llqlease
;
1142 q
->expire
= m
->timenow
+ ((mDNSs32
)llq
->llqlease
* mDNSPlatformOneSecond
);
1145 q
->state
= LLQ_SecondaryRequest
;
1147 q
->ntries
= 0; // first attempt to send response
1148 sendChallengeResponse(m
, q
, llq
);
1150 else if (q
->state
== LLQ_SecondaryRequest
)
1152 if (llq
->err
) { LogMsg("ERROR: recvSetupResponse %##s (%s) code %d from server", q
->qname
.c
, DNSTypeName(q
->qtype
), llq
->err
); StartLLQPolling(m
,q
); return; }
1153 if (!mDNSSameOpaque64(&q
->id
, &llq
->id
))
1154 { LogMsg("recvSetupResponse - ID changed. discarding"); return; } // this can happen rarely (on packet loss + reordering)
1155 q
->state
= LLQ_Established
;
1157 SetLLQTimer(m
, q
, llq
);
1161 mDNSexport uDNS_LLQType
uDNS_recvLLQResponse(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
1162 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, DNSQuestion
**matchQuestion
)
1164 DNSQuestion pktQ
, *q
;
1165 if (msg
->h
.numQuestions
&& getQuestion(msg
, msg
->data
, end
, 0, &pktQ
))
1167 const rdataOPT
*opt
= GetLLQOptData(m
, msg
, end
);
1169 for (q
= m
->Questions
; q
; q
= q
->next
)
1171 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->qtype
== pktQ
.qtype
&& q
->qnamehash
== pktQ
.qnamehash
&& SameDomainName(&q
->qname
, &pktQ
.qname
))
1173 debugf("uDNS_recvLLQResponse found %##s (%s) %d %#a %#a %X %X %X %X %d",
1174 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->state
, srcaddr
, &q
->servAddr
,
1175 opt
? opt
->u
.llq
.id
.l
[0] : 0, opt
? opt
->u
.llq
.id
.l
[1] : 0, q
->id
.l
[0], q
->id
.l
[1], opt
? opt
->u
.llq
.llqOp
: 0);
1176 if (q
->state
== LLQ_Poll
) debugf("uDNS_LLQ_Events: q->state == LLQ_Poll msg->h.id %d q->TargetQID %d", mDNSVal16(msg
->h
.id
), mDNSVal16(q
->TargetQID
));
1177 if (q
->state
== LLQ_Poll
&& mDNSSameOpaque16(msg
->h
.id
, q
->TargetQID
))
1179 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
1181 // Don't reset the state to IntialRequest as we may write that to the dynamic store
1182 // and PrefPane might wrongly think that we are "Starting" instead of "Polling". If
1183 // we are in polling state because of PCP/NAT-PMP disabled or DoubleNAT, next LLQNATCallback
1184 // would kick us back to LLQInitialRequest. So, resetting the state here may not be useful.
1186 // If we have a good NAT (neither PCP/NAT-PMP disabled nor Double-NAT), then we should not be
1187 // possibly in polling state. To be safe, we want to retry from the start in that case
1188 // as there may not be another LLQNATCallback
1190 // NOTE: We can be in polling state if we cannot resolve the SOA record i.e, servAddr is set to
1191 // all ones. In that case, we would set it in LLQ_InitialRequest as it overrides the PCP/NAT-PMP or
1192 // Double-NAT state.
1193 if (!mDNSAddressIsOnes(&q
->servAddr
) && !mDNSIPPortIsZero(m
->LLQNAT
.ExternalPort
) &&
1196 debugf("uDNS_recvLLQResponse got poll response; moving to LLQ_InitialRequest for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
1197 q
->state
= LLQ_InitialRequest
;
1199 q
->servPort
= zeroIPPort
; // Clear servPort so that startLLQHandshake will retry the GetZoneData processing
1200 q
->ThisQInterval
= LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10); // Retry LLQ setup in approx 15 minutes
1201 q
->LastQTime
= m
->timenow
;
1202 SetNextQueryTime(m
, q
);
1204 return uDNS_LLQ_Entire
; // uDNS_LLQ_Entire means flush stale records; assume a large effective TTL
1206 // Note: In LLQ Event packets, the msg->h.id does not match our q->TargetQID, because in that case the msg->h.id nonce is selected by the server
1207 else if (opt
&& q
->state
== LLQ_Established
&& opt
->u
.llq
.llqOp
== kLLQOp_Event
&& mDNSSameOpaque64(&opt
->u
.llq
.id
, &q
->id
))
1210 //debugf("Sending LLQ ack for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
1211 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, ResponseFlags
);
1212 ackEnd
= putLLQ(&m
->omsg
, m
->omsg
.data
, q
, &opt
->u
.llq
);
1213 if (ackEnd
) mDNSSendDNSMessage(m
, &m
->omsg
, ackEnd
, mDNSInterface_Any
, mDNSNULL
, q
->LocalSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSfalse
);
1214 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
1215 debugf("uDNS_LLQ_Events: q->state == LLQ_Established msg->h.id %d q->TargetQID %d", mDNSVal16(msg
->h
.id
), mDNSVal16(q
->TargetQID
));
1217 return uDNS_LLQ_Events
;
1219 if (opt
&& mDNSSameOpaque16(msg
->h
.id
, q
->TargetQID
))
1221 if (q
->state
== LLQ_Established
&& opt
->u
.llq
.llqOp
== kLLQOp_Refresh
&& mDNSSameOpaque64(&opt
->u
.llq
.id
, &q
->id
) && msg
->h
.numAdditionals
&& !msg
->h
.numAnswers
)
1223 if (opt
->u
.llq
.err
!= LLQErr_NoError
) LogMsg("recvRefreshReply: received error %d from server", opt
->u
.llq
.err
);
1226 //LogInfo("Received refresh confirmation ntries %d for %##s (%s)", q->ntries, q->qname.c, DNSTypeName(q->qtype));
1227 // If we're waiting to go to sleep, then this LLQ deletion may have been the thing
1228 // we were waiting for, so schedule another check to see if we can sleep now.
1229 if (opt
->u
.llq
.llqlease
== 0 && m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
1230 GrantCacheExtensions(m
, q
, opt
->u
.llq
.llqlease
);
1231 SetLLQTimer(m
, q
, &opt
->u
.llq
);
1234 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
1236 return uDNS_LLQ_Ignore
;
1238 if (q
->state
< LLQ_Established
&& mDNSSameAddress(srcaddr
, &q
->servAddr
))
1240 LLQ_State oldstate
= q
->state
;
1241 recvSetupResponse(m
, msg
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
, q
, &opt
->u
.llq
);
1242 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
1243 // We have a protocol anomaly here in the LLQ definition.
1244 // Both the challenge packet from the server and the ack+answers packet have opt->u.llq.llqOp == kLLQOp_Setup.
1245 // However, we need to treat them differently:
1246 // The challenge packet has no answers in it, and tells us nothing about whether our cache entries
1247 // are still valid, so this packet should not cause us to do anything that messes with our cache.
1248 // The ack+answers packet gives us the whole truth, so we should handle it by updating our cache
1249 // to match the answers in the packet, and only the answers in the packet.
1251 return (oldstate
== LLQ_SecondaryRequest
? uDNS_LLQ_Entire
: uDNS_LLQ_Ignore
);
1256 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
1258 *matchQuestion
= mDNSNULL
;
1259 return uDNS_LLQ_Not
;
1262 // Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
1263 struct TCPSocket_struct
{ mDNSIPPort port
; TCPSocketFlags flags
; /* ... */ };
1265 // tcpCallback is called to handle events (e.g. connection opening and data reception) on TCP connections for
1266 // Private DNS operations -- private queries, private LLQs, private record updates and private service updates
1267 mDNSlocal
void tcpCallback(TCPSocket
*sock
, void *context
, mDNSBool ConnectionEstablished
, mStatus err
)
1269 tcpInfo_t
*tcpInfo
= (tcpInfo_t
*)context
;
1270 mDNSBool closed
= mDNSfalse
;
1271 mDNS
*m
= tcpInfo
->m
;
1272 DNSQuestion
*const q
= tcpInfo
->question
;
1273 tcpInfo_t
**backpointer
=
1275 tcpInfo
->rr
? &tcpInfo
->rr
->tcp
: mDNSNULL
;
1276 if (backpointer
&& *backpointer
!= tcpInfo
)
1277 LogMsg("tcpCallback: %d backpointer %p incorrect tcpInfo %p question %p rr %p",
1278 mDNSPlatformTCPGetFD(tcpInfo
->sock
), *backpointer
, tcpInfo
, q
, tcpInfo
->rr
);
1282 if (ConnectionEstablished
)
1284 mDNSu8
*end
= ((mDNSu8
*) &tcpInfo
->request
) + tcpInfo
->requestLen
;
1285 DomainAuthInfo
*AuthInfo
;
1287 // Defensive coding for <rdar://problem/5546824> Crash in mDNSResponder at GetAuthInfoForName_internal + 366
1288 // Don't know yet what's causing this, but at least we can be cautious and try to avoid crashing if we find our pointers in an unexpected state
1289 if (tcpInfo
->rr
&& tcpInfo
->rr
->resrec
.name
!= &tcpInfo
->rr
->namestorage
)
1290 LogMsg("tcpCallback: ERROR: tcpInfo->rr->resrec.name %p != &tcpInfo->rr->namestorage %p",
1291 tcpInfo
->rr
->resrec
.name
, &tcpInfo
->rr
->namestorage
);
1292 if (tcpInfo
->rr
&& tcpInfo
->rr
->resrec
.name
!= &tcpInfo
->rr
->namestorage
) return;
1294 AuthInfo
= tcpInfo
->rr
? GetAuthInfoForName(m
, tcpInfo
->rr
->resrec
.name
) : mDNSNULL
;
1296 // connection is established - send the message
1297 if (q
&& q
->LongLived
&& q
->state
== LLQ_Established
)
1299 // Lease renewal over TCP, resulting from opening a TCP connection in sendLLQRefresh
1300 end
= ((mDNSu8
*) &tcpInfo
->request
) + tcpInfo
->requestLen
;
1302 else if (q
&& q
->LongLived
&& q
->state
!= LLQ_Poll
&& !mDNSIPPortIsZero(m
->LLQNAT
.ExternalPort
) && !mDNSIPPortIsZero(q
->servPort
))
1305 // If we have a NAT port mapping, ExternalPort is the external port
1306 // If we have a routable address so we don't need a port mapping, ExternalPort is the same as our own internal port
1307 // If we need a NAT port mapping but can't get one, then ExternalPort is zero
1308 LLQOptData llqData
; // set llq rdata
1309 llqData
.vers
= kLLQ_Vers
;
1310 llqData
.llqOp
= kLLQOp_Setup
;
1311 llqData
.err
= GetLLQEventPort(m
, &tcpInfo
->Addr
); // We're using TCP; tell server what UDP port to send notifications to
1312 LogInfo("tcpCallback: eventPort %d", llqData
.err
);
1313 llqData
.id
= zeroOpaque64
;
1314 llqData
.llqlease
= kLLQ_DefLease
;
1315 InitializeDNSMessage(&tcpInfo
->request
.h
, q
->TargetQID
, uQueryFlags
);
1316 end
= putLLQ(&tcpInfo
->request
, tcpInfo
->request
.data
, q
, &llqData
);
1317 if (!end
) { LogMsg("ERROR: tcpCallback - putLLQ"); err
= mStatus_UnknownErr
; goto exit
; }
1318 AuthInfo
= q
->AuthInfo
; // Need to add TSIG to this message
1319 q
->ntries
= 0; // Reset ntries so that tcp/tls connection failures don't affect sendChallengeResponse failures
1323 mDNSOpaque16 HeaderFlags
= uQueryFlags
;
1325 // LLQ Polling mode or non-LLQ uDNS over TCP
1326 InitializeDNSMessage(&tcpInfo
->request
.h
, q
->TargetQID
, HeaderFlags
);
1327 end
= putQuestion(&tcpInfo
->request
, tcpInfo
->request
.data
, tcpInfo
->request
.data
+ AbsoluteMaxDNSMessageData
, &q
->qname
, q
->qtype
, q
->qclass
);
1329 AuthInfo
= q
->AuthInfo
; // Need to add TSIG to this message
1332 err
= mDNSSendDNSMessage(m
, &tcpInfo
->request
, end
, mDNSInterface_Any
, sock
, mDNSNULL
, &tcpInfo
->Addr
, tcpInfo
->Port
, AuthInfo
, mDNSfalse
);
1333 if (err
) { debugf("ERROR: tcpCallback: mDNSSendDNSMessage - %d", err
); err
= mStatus_UnknownErr
; goto exit
; }
1334 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
1335 if (mDNSSameIPPort(tcpInfo
->Port
, UnicastDNSPort
))
1337 MetricsUpdateDNSQuerySize((mDNSu32
)(end
- (mDNSu8
*)&tcpInfo
->request
));
1341 // Record time we sent this question
1345 q
->LastQTime
= m
->timenow
;
1346 if (q
->ThisQInterval
< (256 * mDNSPlatformOneSecond
)) // Now we have a TCP connection open, make sure we wait at least 256 seconds before retrying
1347 q
->ThisQInterval
= (256 * mDNSPlatformOneSecond
);
1348 SetNextQueryTime(m
, q
);
1355 const mDNSBool Read_replylen
= (tcpInfo
->nread
< 2); // Do we need to read the replylen field first?
1356 if (Read_replylen
) // First read the two-byte length preceeding the DNS message
1358 mDNSu8
*lenptr
= (mDNSu8
*)&tcpInfo
->replylen
;
1359 n
= mDNSPlatformReadTCP(sock
, lenptr
+ tcpInfo
->nread
, 2 - tcpInfo
->nread
, &closed
);
1362 LogMsg("ERROR: tcpCallback - attempt to read message length failed (%d)", n
);
1363 err
= mStatus_ConnFailed
;
1368 // It's perfectly fine for this socket to close after the first reply. The server might
1369 // be sending gratuitous replies using UDP and doesn't have a need to leave the TCP socket open.
1370 // We'll only log this event if we've never received a reply before.
1371 // BIND 9 appears to close an idle connection after 30 seconds.
1372 if (tcpInfo
->numReplies
== 0)
1374 LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo
->nread
);
1375 err
= mStatus_ConnFailed
;
1380 // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1381 // over this tcp connection. That is, we only track whether we've received at least one response
1382 // which may have been to a previous request sent over this tcp connection.
1383 if (backpointer
) *backpointer
= mDNSNULL
; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1384 DisposeTCPConn(tcpInfo
);
1389 tcpInfo
->nread
+= n
;
1390 if (tcpInfo
->nread
< 2) goto exit
;
1392 tcpInfo
->replylen
= (mDNSu16
)((mDNSu16
)lenptr
[0] << 8 | lenptr
[1]);
1393 if (tcpInfo
->replylen
< sizeof(DNSMessageHeader
))
1394 { LogMsg("ERROR: tcpCallback - length too short (%d bytes)", tcpInfo
->replylen
); err
= mStatus_UnknownErr
; goto exit
; }
1396 tcpInfo
->reply
= (DNSMessage
*) mDNSPlatformMemAllocate(tcpInfo
->replylen
);
1397 if (!tcpInfo
->reply
) { LogMsg("ERROR: tcpCallback - malloc failed"); err
= mStatus_NoMemoryErr
; goto exit
; }
1400 n
= mDNSPlatformReadTCP(sock
, ((char *)tcpInfo
->reply
) + (tcpInfo
->nread
- 2), tcpInfo
->replylen
- (tcpInfo
->nread
- 2), &closed
);
1404 // If this is our only read for this invokation, and it fails, then that's bad.
1405 // But if we did successfully read some or all of the replylen field this time through,
1406 // and this is now our second read from the socket, then it's expected that sometimes
1407 // there may be no more data present, and that's perfectly okay.
1408 // Assuming failure of the second read is a problem is what caused this bug:
1409 // <rdar://problem/15043194> mDNSResponder fails to read DNS over TCP packet correctly
1410 if (!Read_replylen
) { LogMsg("ERROR: tcpCallback - read returned %d", n
); err
= mStatus_ConnFailed
; }
1415 if (tcpInfo
->numReplies
== 0)
1417 LogMsg("ERROR: socket closed prematurely tcpInfo->nread = %d", tcpInfo
->nread
);
1418 err
= mStatus_ConnFailed
;
1423 // Note that we may not be doing the best thing if an error occurs after we've sent a second request
1424 // over this tcp connection. That is, we only track whether we've received at least one response
1425 // which may have been to a previous request sent over this tcp connection.
1426 if (backpointer
) *backpointer
= mDNSNULL
; // Clear client backpointer FIRST so we don't risk double-disposing our tcpInfo_t
1427 DisposeTCPConn(tcpInfo
);
1432 tcpInfo
->nread
+= n
;
1434 if ((tcpInfo
->nread
- 2) == tcpInfo
->replylen
)
1437 DNSMessage
*reply
= tcpInfo
->reply
;
1438 mDNSu8
*end
= (mDNSu8
*)tcpInfo
->reply
+ tcpInfo
->replylen
;
1439 mDNSAddr Addr
= tcpInfo
->Addr
;
1440 mDNSIPPort Port
= tcpInfo
->Port
;
1441 mDNSIPPort srcPort
= zeroIPPort
;
1442 tcpInfo
->numReplies
++;
1443 tcpInfo
->reply
= mDNSNULL
; // Detach reply buffer from tcpInfo_t, to make sure client callback can't cause it to be disposed
1445 tcpInfo
->replylen
= 0;
1447 // If we're going to dispose this connection, do it FIRST, before calling client callback
1448 // Note: Sleep code depends on us clearing *backpointer here -- it uses the clearing of rr->tcp
1449 // as the signal that the DNS deregistration operation with the server has completed, and the machine may now sleep
1450 // If we clear the tcp pointer in the question, mDNSCoreReceiveResponse cannot find a matching question. Hence
1451 // we store the minimal information i.e., the source port of the connection in the question itself.
1452 // Dereference sock before it is disposed in DisposeTCPConn below.
1454 if (sock
->flags
& kTCPSocketFlags_UseTLS
) tls
= mDNStrue
;
1455 else tls
= mDNSfalse
;
1457 if (q
&& q
->tcp
) {srcPort
= q
->tcp
->SrcPort
; q
->tcpSrcPort
= srcPort
;}
1460 if (!q
|| !q
->LongLived
|| m
->SleepState
)
1461 { *backpointer
= mDNSNULL
; DisposeTCPConn(tcpInfo
); }
1463 mDNSCoreReceive(m
, reply
, end
, &Addr
, Port
, tls
? (mDNSAddr
*)1 : mDNSNULL
, srcPort
, 0);
1464 // USE CAUTION HERE: Invoking mDNSCoreReceive may have caused the environment to change, including canceling this operation itself
1466 mDNSPlatformMemFree(reply
);
1475 // Clear client backpointer FIRST -- that way if one of the callbacks cancels its operation
1476 // we won't end up double-disposing our tcpInfo_t
1477 if (backpointer
) *backpointer
= mDNSNULL
;
1479 mDNS_Lock(m
); // Need to grab the lock to get m->timenow
1483 if (q
->ThisQInterval
== 0)
1485 // We get here when we fail to establish a new TCP/TLS connection that would have been used for a new LLQ request or an LLQ renewal.
1486 // Note that ThisQInterval is also zero when sendChallengeResponse resends the LLQ request on an extant TCP/TLS connection.
1487 q
->LastQTime
= m
->timenow
;
1490 // We didn't get the chance to send our request packet before the TCP/TLS connection failed.
1491 // We want to retry quickly, but want to back off exponentially in case the server is having issues.
1492 // Since ThisQInterval was 0, we can't just multiply by QuestionIntervalStep, we must track the number
1493 // of TCP/TLS connection failures using ntries.
1494 mDNSu32 count
= q
->ntries
+ 1; // want to wait at least 1 second before retrying
1496 q
->ThisQInterval
= InitialQuestionInterval
;
1498 for (; count
; count
--)
1499 q
->ThisQInterval
*= QuestionIntervalStep
;
1501 if (q
->ThisQInterval
> LLQ_POLL_INTERVAL
)
1502 q
->ThisQInterval
= LLQ_POLL_INTERVAL
;
1506 LogMsg("tcpCallback: stream connection for LLQ %##s (%s) failed %d times, retrying in %d ms", q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ntries
, q
->ThisQInterval
);
1510 q
->ThisQInterval
= MAX_UCAST_POLL_INTERVAL
;
1511 LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
);
1513 SetNextQueryTime(m
, q
);
1515 else if (NextQSendTime(q
) - m
->timenow
> (q
->LongLived
? LLQ_POLL_INTERVAL
: MAX_UCAST_POLL_INTERVAL
))
1517 // If we get an error and our next scheduled query for this question is more than the max interval from now,
1518 // reset the next query to ensure we wait no longer the maximum interval from now before trying again.
1519 q
->LastQTime
= m
->timenow
;
1520 q
->ThisQInterval
= q
->LongLived
? LLQ_POLL_INTERVAL
: MAX_UCAST_POLL_INTERVAL
;
1521 SetNextQueryTime(m
, q
);
1522 LogMsg("tcpCallback: stream connection for %##s (%s) failed, retrying in %d ms", q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
);
1525 // We're about to dispose of the TCP connection, so we must reset the state to retry over TCP/TLS
1526 // because sendChallengeResponse will send the query via UDP if we don't have a tcp pointer.
1527 // Resetting to LLQ_InitialRequest will cause uDNS_CheckCurrentQuestion to call startLLQHandshake, which
1528 // will attempt to establish a new tcp connection.
1529 if (q
->LongLived
&& q
->state
== LLQ_SecondaryRequest
)
1530 q
->state
= LLQ_InitialRequest
;
1532 // ConnFailed may happen if the server sends a TCP reset or TLS fails, in which case we want to retry establishing the LLQ
1533 // quickly rather than switching to polling mode. This case is handled by the above code to set q->ThisQInterval just above.
1534 // If the error isn't ConnFailed, then the LLQ is in bad shape, so we switch to polling mode.
1535 if (err
!= mStatus_ConnFailed
)
1537 if (q
->LongLived
&& q
->state
!= LLQ_Poll
) StartLLQPolling(m
, q
);
1543 DisposeTCPConn(tcpInfo
);
1547 mDNSlocal tcpInfo_t
*MakeTCPConn(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
1548 TCPSocketFlags flags
, const mDNSAddr
*const Addr
, const mDNSIPPort Port
, domainname
*hostname
,
1549 DNSQuestion
*const question
, AuthRecord
*const rr
)
1552 mDNSIPPort srcport
= zeroIPPort
;
1554 mDNSBool useBackgroundTrafficClass
;
1556 useBackgroundTrafficClass
= question
? question
->UseBackgroundTraffic
: mDNSfalse
;
1558 if ((flags
& kTCPSocketFlags_UseTLS
) && (!hostname
|| !hostname
->c
[0]))
1559 { LogMsg("MakeTCPConn: TLS connection being setup with NULL hostname"); return mDNSNULL
; }
1561 info
= (tcpInfo_t
*) mDNSPlatformMemAllocateClear(sizeof(*info
));
1562 if (!info
) { LogMsg("ERROR: MakeTCP - memallocate failed"); return(mDNSNULL
); }
1566 const mDNSu8
*const start
= (const mDNSu8
*)msg
;
1567 if ((end
< start
) || ((end
- start
) > (int)sizeof(info
->request
)))
1569 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
1570 "MakeTCPConn: invalid DNS message pointers -- msg: %p, end: %p", msg
, end
);
1571 mDNSPlatformMemFree(info
);
1574 info
->requestLen
= (int)(end
- start
);
1575 mDNSPlatformMemCopy(&info
->request
, msg
, info
->requestLen
);
1579 info
->sock
= mDNSPlatformTCPSocket(flags
, Addr
->type
, &srcport
, hostname
, useBackgroundTrafficClass
);
1580 info
->question
= question
;
1584 info
->reply
= mDNSNULL
;
1587 info
->numReplies
= 0;
1588 info
->SrcPort
= srcport
;
1590 if (!info
->sock
) { LogMsg("MakeTCPConn: unable to create TCP socket"); mDNSPlatformMemFree(info
); return(mDNSNULL
); }
1591 mDNSPlatformSetSocktOpt(info
->sock
, mDNSTransport_TCP
, Addr
->type
, question
);
1592 err
= mDNSPlatformTCPConnect(info
->sock
, Addr
, Port
, (question
? question
->InterfaceID
: mDNSNULL
), tcpCallback
, info
);
1594 // Probably suboptimal here.
1595 // Instead of returning mDNSNULL here on failure, we should probably invoke the callback with an error code.
1596 // That way clients can put all the error handling and retry/recovery code in one place,
1597 // instead of having to handle immediate errors in one place and async errors in another.
1598 // Also: "err == mStatus_ConnEstablished" probably never happens.
1600 // Don't need to log "connection failed" in customer builds -- it happens quite often during sleep, wake, configuration changes, etc.
1601 if (err
== mStatus_ConnEstablished
) { tcpCallback(info
->sock
, info
, mDNStrue
, mStatus_NoError
); }
1602 else if (err
!= mStatus_ConnPending
) { LogInfo("MakeTCPConn: connection failed"); DisposeTCPConn(info
); return(mDNSNULL
); }
1606 mDNSexport
void DisposeTCPConn(struct tcpInfo_t
*tcp
)
1608 mDNSPlatformTCPCloseConnection(tcp
->sock
);
1609 if (tcp
->reply
) mDNSPlatformMemFree(tcp
->reply
);
1610 mDNSPlatformMemFree(tcp
);
1613 // Lock must be held
1614 mDNSexport
void startLLQHandshake(mDNS
*m
, DNSQuestion
*q
)
1616 // States prior to LLQ_InitialRequest should not react to NAT Mapping changes.
1617 // startLLQHandshake is never called with q->state < LLQ_InitialRequest except
1618 // from LLQNATCallback. When we are actually trying to do LLQ, then q->state will
1619 // be equal to or greater than LLQ_InitialRequest when LLQNATCallback calls
1620 // startLLQHandshake.
1621 if (q
->state
< LLQ_InitialRequest
)
1626 if (m
->LLQNAT
.clientContext
!= mDNSNULL
) // LLQNAT just started, give it some time
1628 LogInfo("startLLQHandshake: waiting for NAT status for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
1629 q
->ThisQInterval
= LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10); // Retry in approx 15 minutes
1630 q
->LastQTime
= m
->timenow
;
1631 SetNextQueryTime(m
, q
);
1635 // Either we don't have {PCP, NAT-PMP, UPnP/IGD} support (ExternalPort is zero) or behind a Double NAT that may or
1636 // may not have {PCP, NAT-PMP, UPnP/IGD} support (NATResult is non-zero)
1637 if (mDNSIPPortIsZero(m
->LLQNAT
.ExternalPort
) || m
->LLQNAT
.Result
)
1639 LogInfo("startLLQHandshake: Cannot receive inbound packets; will poll for %##s (%s) External Port %d, NAT Result %d",
1640 q
->qname
.c
, DNSTypeName(q
->qtype
), mDNSVal16(m
->LLQNAT
.ExternalPort
), m
->LLQNAT
.Result
);
1641 StartLLQPolling(m
, q
);
1645 if (mDNSIPPortIsZero(q
->servPort
))
1647 debugf("startLLQHandshake: StartGetZoneData for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
1648 q
->ThisQInterval
= LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10); // Retry in approx 15 minutes
1649 q
->LastQTime
= m
->timenow
;
1650 SetNextQueryTime(m
, q
);
1651 q
->servAddr
= zeroAddr
;
1652 // We know q->servPort is zero because of check above
1653 if (q
->nta
) CancelGetZoneData(m
, q
->nta
);
1654 q
->nta
= StartGetZoneData(m
, &q
->qname
, ZoneServiceLLQ
, LLQGotZoneData
, q
);
1658 debugf("startLLQHandshake: m->AdvertisedV4 %#a%s Server %#a:%d%s %##s (%s)",
1659 &m
->AdvertisedV4
, mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
) ? " (RFC 1918)" : "",
1660 &q
->servAddr
, mDNSVal16(q
->servPort
), mDNSAddrIsRFC1918(&q
->servAddr
) ? " (RFC 1918)" : "",
1661 q
->qname
.c
, DNSTypeName(q
->qtype
));
1663 if (q
->ntries
++ >= kLLQ_MAX_TRIES
)
1665 LogMsg("startLLQHandshake: %d failed attempts for LLQ %##s Polling.", kLLQ_MAX_TRIES
, q
->qname
.c
);
1666 StartLLQPolling(m
, q
);
1674 llqData
.vers
= kLLQ_Vers
;
1675 llqData
.llqOp
= kLLQOp_Setup
;
1676 llqData
.err
= LLQErr_NoError
; // Don't need to tell server UDP notification port when sending over UDP
1677 llqData
.id
= zeroOpaque64
;
1678 llqData
.llqlease
= kLLQ_DefLease
;
1680 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, uQueryFlags
);
1681 end
= putLLQ(&m
->omsg
, m
->omsg
.data
, q
, &llqData
);
1682 if (!end
) { LogMsg("ERROR: startLLQHandshake - putLLQ"); StartLLQPolling(m
,q
); return; }
1684 mDNSSendDNSMessage(m
, &m
->omsg
, end
, mDNSInterface_Any
, mDNSNULL
, q
->LocalSocket
, &q
->servAddr
, q
->servPort
, mDNSNULL
, mDNSfalse
);
1686 // update question state
1687 q
->state
= LLQ_InitialRequest
;
1688 q
->ReqLease
= kLLQ_DefLease
;
1689 q
->ThisQInterval
= (kLLQ_INIT_RESEND
* mDNSPlatformOneSecond
);
1690 q
->LastQTime
= m
->timenow
;
1691 SetNextQueryTime(m
, q
);
1696 // forward declaration so GetServiceTarget can do reverse lookup if needed
1697 mDNSlocal
void GetStaticHostname(mDNS
*m
);
1699 mDNSexport
const domainname
*GetServiceTarget(mDNS
*m
, AuthRecord
*const rr
)
1701 debugf("GetServiceTarget %##s", rr
->resrec
.name
->c
);
1703 if (!rr
->AutoTarget
) // If not automatically tracking this host's current name, just return the existing target
1704 return(&rr
->resrec
.rdata
->u
.srv
.target
);
1708 const int srvcount
= CountLabels(rr
->resrec
.name
);
1709 HostnameInfo
*besthi
= mDNSNULL
, *hi
;
1711 for (hi
= m
->Hostnames
; hi
; hi
= hi
->next
)
1712 if (hi
->arv4
.state
== regState_Registered
|| hi
->arv4
.state
== regState_Refresh
||
1713 hi
->arv6
.state
== regState_Registered
|| hi
->arv6
.state
== regState_Refresh
)
1715 int x
, hostcount
= CountLabels(&hi
->fqdn
);
1716 for (x
= hostcount
< srvcount
? hostcount
: srvcount
; x
> 0 && x
> best
; x
--)
1717 if (SameDomainName(SkipLeadingLabels(rr
->resrec
.name
, srvcount
- x
), SkipLeadingLabels(&hi
->fqdn
, hostcount
- x
)))
1718 { best
= x
; besthi
= hi
; }
1721 if (besthi
) return(&besthi
->fqdn
);
1723 if (m
->StaticHostname
.c
[0]) return(&m
->StaticHostname
);
1724 else GetStaticHostname(m
); // asynchronously do reverse lookup for primary IPv4 address
1725 LogInfo("GetServiceTarget: Returning NULL for %s", ARDisplayString(m
, rr
));
1730 mDNSlocal
const domainname
*PUBLIC_UPDATE_SERVICE_TYPE
= (const domainname
*)"\x0B_dns-update" "\x04_udp";
1731 mDNSlocal
const domainname
*PUBLIC_LLQ_SERVICE_TYPE
= (const domainname
*)"\x08_dns-llq" "\x04_udp";
1733 mDNSlocal
const domainname
*PRIVATE_UPDATE_SERVICE_TYPE
= (const domainname
*)"\x0F_dns-update-tls" "\x04_tcp";
1734 mDNSlocal
const domainname
*PRIVATE_QUERY_SERVICE_TYPE
= (const domainname
*)"\x0E_dns-query-tls" "\x04_tcp";
1735 mDNSlocal
const domainname
*PRIVATE_LLQ_SERVICE_TYPE
= (const domainname
*)"\x0C_dns-llq-tls" "\x04_tcp";
1736 mDNSlocal
const domainname
*DNS_PUSH_NOTIFICATION_SERVICE_TYPE
= (const domainname
*)"\x0D_dns-push-tls" "\x04_tcp";
1738 #define ZoneDataSRV(X) ( \
1739 (X)->ZoneService == ZoneServiceUpdate ? ((X)->ZonePrivate ? PRIVATE_UPDATE_SERVICE_TYPE : PUBLIC_UPDATE_SERVICE_TYPE) : \
1740 (X)->ZoneService == ZoneServiceQuery ? ((X)->ZonePrivate ? PRIVATE_QUERY_SERVICE_TYPE : (const domainname*)"" ) : \
1741 (X)->ZoneService == ZoneServiceLLQ ? ((X)->ZonePrivate ? PRIVATE_LLQ_SERVICE_TYPE : PUBLIC_LLQ_SERVICE_TYPE ) : \
1742 (X)->ZoneService == ZoneServiceDNSPush ? DNS_PUSH_NOTIFICATION_SERVICE_TYPE : (const domainname*)"")
1744 // Forward reference: GetZoneData_StartQuery references GetZoneData_QuestionCallback, and
1745 // GetZoneData_QuestionCallback calls GetZoneData_StartQuery
1746 mDNSlocal mStatus
GetZoneData_StartQuery(mDNS
*const m
, ZoneData
*zd
, mDNSu16 qtype
);
1748 // GetZoneData_QuestionCallback is called from normal client callback context (core API calls allowed)
1749 mDNSlocal
void GetZoneData_QuestionCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
1751 ZoneData
*zd
= (ZoneData
*)question
->QuestionContext
;
1753 debugf("GetZoneData_QuestionCallback: %s %s", AddRecord
? "Add" : "Rmv", RRDisplayString(m
, answer
));
1755 if (!AddRecord
) return; // Don't care about REMOVE events
1756 if (AddRecord
== QC_addnocache
&& answer
->rdlength
== 0) return; // Don't care about transient failure indications
1757 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
1759 if (answer
->rrtype
== kDNSType_SOA
)
1761 debugf("GetZoneData GOT SOA %s", RRDisplayString(m
, answer
));
1762 mDNS_StopQuery(m
, question
);
1763 if (question
->ThisQInterval
!= -1)
1764 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->ThisQInterval
);
1765 if (answer
->rdlength
)
1767 AssignDomainName(&zd
->ZoneName
, answer
->name
);
1768 zd
->ZoneClass
= answer
->rrclass
;
1769 GetZoneData_StartQuery(m
, zd
, kDNSType_SRV
);
1771 else if (zd
->CurrentSOA
->c
[0])
1773 zd
->CurrentSOA
= (domainname
*)(zd
->CurrentSOA
->c
+ zd
->CurrentSOA
->c
[0]+1);
1774 AssignDomainName(&zd
->question
.qname
, zd
->CurrentSOA
);
1775 GetZoneData_StartQuery(m
, zd
, kDNSType_SOA
);
1779 LogInfo("GetZoneData recursed to root label of %##s without finding SOA", zd
->ChildName
.c
);
1780 zd
->ZoneDataCallback(m
, mStatus_NoSuchNameErr
, zd
);
1783 else if (answer
->rrtype
== kDNSType_SRV
)
1785 debugf("GetZoneData GOT SRV %s", RRDisplayString(m
, answer
));
1786 mDNS_StopQuery(m
, question
);
1787 if (question
->ThisQInterval
!= -1)
1788 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->ThisQInterval
);
1789 // Right now we don't want to fail back to non-encrypted operations
1790 // If the AuthInfo has the AutoTunnel field set, then we want private or nothing
1791 // <rdar://problem/5687667> BTMM: Don't fallback to unencrypted operations when SRV lookup fails
1793 if (!answer
->rdlength
&& zd
->ZonePrivate
&& zd
->ZoneService
!= ZoneServiceQuery
)
1795 zd
->ZonePrivate
= mDNSfalse
; // Causes ZoneDataSRV() to yield a different SRV name when building the query
1796 GetZoneData_StartQuery(m
, zd
, kDNSType_SRV
); // Try again, non-private this time
1801 if (answer
->rdlength
)
1803 AssignDomainName(&zd
->Host
, &answer
->rdata
->u
.srv
.target
);
1804 zd
->Port
= answer
->rdata
->u
.srv
.port
;
1805 // The MakeTCPConn path, which is used by everything but DNS Push, won't work at all for
1806 // IPv6. This should be fixed for all cases we care about, but for now we make an exception
1807 // for Push notifications: we do not look up the a record here, but rather rely on the DSO
1808 // infrastructure to do a GetAddrInfo call on the name and try each IP address in sequence
1809 // until one connects. We can't do this for the other use cases because this is in the DSO
1810 // code, not in MakeTCPConn. Ultimately the fix for this is to use Network Framework to do
1811 // the connection establishment for all of these use cases.
1813 // One implication of this is that if two different zones have DNS push server SRV records
1814 // pointing to the same server using a different domain name, we will not see these as being
1815 // the same server, and will not share the connection. This isn't something we can easily
1816 // fix, and so the advice if someone runs into this and considers it a problem should be to
1817 // use the same name.
1819 // Another issue with this code is that at present, we do not wait for more than one SRV
1820 // record--we cancel the query as soon as the first one comes in. This isn't ideal: it
1821 // would be better to wait until we've gotten all our answers and then pick the one with
1822 // the highest priority. Of course, this is unlikely to cause an operational problem in
1823 // practice, and as with the previous point, the fix is easy: figure out which server you
1824 // want people to use and don't list any other servers. Fully switching to Network
1825 // Framework for this would (I think!) address this problem, or at least make it someone
1827 if (zd
->ZoneService
!= ZoneServiceDNSPush
)
1829 AssignDomainName(&zd
->question
.qname
, &zd
->Host
);
1830 GetZoneData_StartQuery(m
, zd
, kDNSType_A
);
1834 zd
->ZoneDataCallback(m
, mStatus_NoError
, zd
);
1839 zd
->ZonePrivate
= mDNSfalse
;
1841 zd
->Port
= zeroIPPort
;
1842 zd
->Addr
= zeroAddr
;
1843 zd
->ZoneDataCallback(m
, mStatus_NoError
, zd
);
1847 else if (answer
->rrtype
== kDNSType_A
)
1849 debugf("GetZoneData GOT A %s", RRDisplayString(m
, answer
));
1850 mDNS_StopQuery(m
, question
);
1851 if (question
->ThisQInterval
!= -1)
1852 LogMsg("GetZoneData_QuestionCallback: Question %##s (%s) ThisQInterval %d not -1", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->ThisQInterval
);
1853 zd
->Addr
.type
= mDNSAddrType_IPv4
;
1854 zd
->Addr
.ip
.v4
= (answer
->rdlength
== 4) ? answer
->rdata
->u
.ipv4
: zerov4Addr
;
1855 // In order to simulate firewalls blocking our outgoing TCP connections, returning immediate ICMP errors or TCP resets,
1856 // the code below will make us try to connect to loopback, resulting in an immediate "port unreachable" failure.
1857 // This helps us test to make sure we handle this case gracefully
1858 // <rdar://problem/5607082> BTMM: mDNSResponder taking 100 percent CPU after upgrading to 10.5.1
1860 zd
->Addr
.ip
.v4
.b
[0] = 127;
1861 zd
->Addr
.ip
.v4
.b
[1] = 0;
1862 zd
->Addr
.ip
.v4
.b
[2] = 0;
1863 zd
->Addr
.ip
.v4
.b
[3] = 1;
1865 // The caller needs to free the memory when done with zone data
1866 zd
->ZoneDataCallback(m
, mStatus_NoError
, zd
);
1870 // GetZoneData_StartQuery is called from normal client context (lock not held, or client callback)
1871 mDNSlocal mStatus
GetZoneData_StartQuery(mDNS
*const m
, ZoneData
*zd
, mDNSu16 qtype
)
1873 if (qtype
== kDNSType_SRV
)
1875 AssignDomainName(&zd
->question
.qname
, ZoneDataSRV(zd
));
1876 AppendDomainName(&zd
->question
.qname
, &zd
->ZoneName
);
1877 debugf("lookupDNSPort %##s", zd
->question
.qname
.c
);
1880 // CancelGetZoneData can get called at any time. We should stop the question if it has not been
1881 // stopped already. A value of -1 for ThisQInterval indicates that the question is not active
1883 zd
->question
.ThisQInterval
= -1;
1884 zd
->question
.InterfaceID
= mDNSInterface_Any
;
1885 zd
->question
.flags
= 0;
1886 //zd->question.qname.c[0] = 0; // Already set
1887 zd
->question
.qtype
= qtype
;
1888 zd
->question
.qclass
= kDNSClass_IN
;
1889 zd
->question
.LongLived
= mDNSfalse
;
1890 zd
->question
.ExpectUnique
= mDNStrue
;
1891 zd
->question
.ForceMCast
= mDNSfalse
;
1892 zd
->question
.ReturnIntermed
= mDNStrue
;
1893 zd
->question
.SuppressUnusable
= mDNSfalse
;
1894 zd
->question
.AppendSearchDomains
= 0;
1895 zd
->question
.TimeoutQuestion
= 0;
1896 zd
->question
.WakeOnResolve
= 0;
1897 zd
->question
.UseBackgroundTraffic
= mDNSfalse
;
1898 zd
->question
.ProxyQuestion
= 0;
1899 zd
->question
.pid
= mDNSPlatformGetPID();
1900 zd
->question
.euid
= 0;
1901 zd
->question
.QuestionCallback
= GetZoneData_QuestionCallback
;
1902 zd
->question
.QuestionContext
= zd
;
1904 //LogMsg("GetZoneData_StartQuery %##s (%s) %p", zd->question.qname.c, DNSTypeName(zd->question.qtype), zd->question.Private);
1905 return(mDNS_StartQuery(m
, &zd
->question
));
1908 // StartGetZoneData is an internal routine (i.e. must be called with the lock already held)
1909 mDNSexport ZoneData
*StartGetZoneData(mDNS
*const m
, const domainname
*const name
, const ZoneService target
, ZoneDataCallback callback
, void *ZoneDataContext
)
1911 ZoneData
*zd
= (ZoneData
*) mDNSPlatformMemAllocateClear(sizeof(*zd
));
1912 if (!zd
) { LogMsg("ERROR: StartGetZoneData - mDNSPlatformMemAllocateClear failed"); return mDNSNULL
; }
1913 AssignDomainName(&zd
->ChildName
, name
);
1914 zd
->ZoneService
= target
;
1915 zd
->CurrentSOA
= &zd
->ChildName
;
1916 zd
->ZoneName
.c
[0] = 0;
1919 zd
->Port
= zeroIPPort
;
1920 zd
->Addr
= zeroAddr
;
1921 zd
->ZonePrivate
= mDNSfalse
;
1922 zd
->ZoneDataCallback
= callback
;
1923 zd
->ZoneDataContext
= ZoneDataContext
;
1925 zd
->question
.QuestionContext
= zd
;
1927 mDNS_DropLockBeforeCallback(); // GetZoneData_StartQuery expects to be called from a normal callback, so we emulate that here
1928 AssignDomainName(&zd
->question
.qname
, zd
->CurrentSOA
);
1929 GetZoneData_StartQuery(m
, zd
, kDNSType_SOA
);
1930 mDNS_ReclaimLockAfterCallback();
1935 // Returns if the question is a GetZoneData question. These questions are special in
1936 // that they are created internally while resolving a private query or LLQs.
1937 mDNSexport mDNSBool
IsGetZoneDataQuestion(DNSQuestion
*q
)
1939 if (q
->QuestionCallback
== GetZoneData_QuestionCallback
) return(mDNStrue
);
1940 else return(mDNSfalse
);
1943 // GetZoneData queries are a special case -- even if we have a key for them, we don't do them privately,
1944 // because that would result in an infinite loop (i.e. to do a private query we first need to get
1945 // the _dns-query-tls SRV record for the zone, and we can't do *that* privately because to do so
1946 // we'd need to already know the _dns-query-tls SRV record.
1947 // Also, as a general rule, we never do SOA queries privately
1948 mDNSexport DomainAuthInfo
*GetAuthInfoForQuestion(mDNS
*m
, const DNSQuestion
*const q
) // Must be called with lock held
1950 if (q
->QuestionCallback
== GetZoneData_QuestionCallback
) return(mDNSNULL
);
1951 if (q
->qtype
== kDNSType_SOA
) return(mDNSNULL
);
1952 return(GetAuthInfoForName_internal(m
, &q
->qname
));
1955 // ***************************************************************************
1956 #if COMPILER_LIKES_PRAGMA_MARK
1957 #pragma mark - host name and interface management
1960 mDNSlocal
void SendRecordRegistration(mDNS
*const m
, AuthRecord
*rr
);
1961 mDNSlocal
void SendRecordDeregistration(mDNS
*m
, AuthRecord
*rr
);
1962 mDNSlocal mDNSBool
IsRecordMergeable(mDNS
*const m
, AuthRecord
*rr
, mDNSs32 time
);
1964 // When this function is called, service record is already deregistered. We just
1965 // have to deregister the PTR and TXT records.
1966 mDNSlocal
void UpdateAllServiceRecords(mDNS
*const m
, AuthRecord
*rr
, mDNSBool reg
)
1968 AuthRecord
*r
, *srvRR
;
1970 if (rr
->resrec
.rrtype
!= kDNSType_SRV
) { LogMsg("UpdateAllServiceRecords:ERROR!! ResourceRecord not a service record %s", ARDisplayString(m
, rr
)); return; }
1972 if (reg
&& rr
->state
== regState_NoTarget
) { LogMsg("UpdateAllServiceRecords:ERROR!! SRV record %s in noTarget state during registration", ARDisplayString(m
, rr
)); return; }
1974 LogInfo("UpdateAllServiceRecords: ResourceRecord %s", ARDisplayString(m
, rr
));
1976 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
1978 if (!AuthRecord_uDNS(r
)) continue;
1980 if (r
->resrec
.rrtype
== kDNSType_PTR
)
1981 srvRR
= r
->Additional1
;
1982 else if (r
->resrec
.rrtype
== kDNSType_TXT
)
1983 srvRR
= r
->DependentOn
;
1984 if (srvRR
&& srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
1985 LogMsg("UpdateAllServiceRecords: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
1990 LogInfo("UpdateAllServiceRecords: deregistering %s", ARDisplayString(m
, r
));
1991 r
->SRVChanged
= mDNStrue
;
1992 r
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1993 r
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
1994 r
->state
= regState_DeregPending
;
1998 // Clearing SRVchanged is a safety measure. If our pevious dereg never
1999 // came back and we had a target change, we are starting fresh
2000 r
->SRVChanged
= mDNSfalse
;
2001 // if it is already registered or in the process of registering, then don't
2002 // bother re-registering. This happens today for non-BTMM domains where the
2003 // TXT and PTR get registered before SRV records because of the delay in
2004 // getting the port mapping. There is no point in re-registering the TXT
2006 if ((r
->state
== regState_Registered
) ||
2007 (r
->state
== regState_Pending
&& r
->nta
&& !mDNSIPv4AddressIsZero(r
->nta
->Addr
.ip
.v4
)))
2008 LogInfo("UpdateAllServiceRecords: not registering %s, state %d", ARDisplayString(m
, r
), r
->state
);
2011 LogInfo("UpdateAllServiceRecords: registering %s, state %d", ARDisplayString(m
, r
), r
->state
);
2012 ActivateUnicastRegistration(m
, r
);
2019 // Called in normal client context (lock not held)
2020 // Currently only supports SRV records for nat mapping
2021 mDNSlocal
void CompleteRecordNatMap(mDNS
*m
, NATTraversalInfo
*n
)
2023 const domainname
*target
;
2025 AuthRecord
*rr
= (AuthRecord
*)n
->clientContext
;
2026 debugf("SRVNatMap complete %.4a IntPort %u ExternalPort %u NATLease %u", &n
->ExternalAddress
, mDNSVal16(n
->IntPort
), mDNSVal16(n
->ExternalPort
), n
->NATLease
);
2028 if (!rr
) { LogMsg("CompleteRecordNatMap called with unknown AuthRecord object"); return; }
2029 if (!n
->NATLease
) { LogMsg("CompleteRecordNatMap No NATLease for %s", ARDisplayString(m
, rr
)); return; }
2031 if (rr
->resrec
.rrtype
!= kDNSType_SRV
) {LogMsg("CompleteRecordNatMap: Not a service record %s", ARDisplayString(m
, rr
)); return; }
2033 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) { LogInfo("CompleteRecordNatMap called for %s, Service deregistering", ARDisplayString(m
, rr
)); return; }
2035 if (rr
->state
== regState_DeregPending
) { LogInfo("CompleteRecordNatMap called for %s, record in DeregPending", ARDisplayString(m
, rr
)); return; }
2037 // As we free the zone info after registering/deregistering with the server (See hndlRecordUpdateReply),
2038 // we need to restart the get zone data and nat mapping request to get the latest mapping result as we can't handle it
2039 // at this moment. Restart from the beginning.
2040 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
2042 LogInfo("CompleteRecordNatMap called for %s but no zone information!", ARDisplayString(m
, rr
));
2043 // We need to clear out the NATinfo state so that it will result in re-acquiring the mapping
2044 // and hence this callback called again.
2045 if (rr
->NATinfo
.clientContext
)
2047 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
2048 rr
->NATinfo
.clientContext
= mDNSNULL
;
2050 rr
->state
= regState_Pending
;
2051 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
2052 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
2057 // Reevaluate the target always as Target could have changed while
2058 // we were getting the port mapping (See UpdateOneSRVRecord)
2059 target
= GetServiceTarget(m
, rr
);
2060 srvt
= GetRRDomainNameTarget(&rr
->resrec
);
2061 if (!target
|| target
->c
[0] == 0 || mDNSIPPortIsZero(n
->ExternalPort
))
2063 if (target
&& target
->c
[0])
2064 LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target
->c
, rr
->resrec
.name
->c
, mDNSVal16(n
->ExternalPort
));
2066 LogInfo("CompleteRecordNatMap - no target for %##s, ExternalPort %d", rr
->resrec
.name
->c
, mDNSVal16(n
->ExternalPort
));
2067 if (srvt
) srvt
->c
[0] = 0;
2068 rr
->state
= regState_NoTarget
;
2069 rr
->resrec
.rdlength
= rr
->resrec
.rdestimate
= 0;
2071 UpdateAllServiceRecords(m
, rr
, mDNSfalse
);
2074 LogInfo("CompleteRecordNatMap - Target %##s for ResourceRecord %##s, ExternalPort %d", target
->c
, rr
->resrec
.name
->c
, mDNSVal16(n
->ExternalPort
));
2075 // This function might get called multiple times during a network transition event. Previosuly, we could
2076 // have put the SRV record in NoTarget state above and deregistered all the other records. When this
2077 // function gets called again with a non-zero ExternalPort, we need to set the target and register the
2078 // other records again.
2079 if (srvt
&& !SameDomainName(srvt
, target
))
2081 AssignDomainName(srvt
, target
);
2082 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
2085 // SRVChanged is set when when the target of the SRV record changes (See UpdateOneSRVRecord).
2086 // As a result of the target change, we might register just that SRV Record if it was
2087 // previously registered and we have a new target OR deregister SRV (and the associated
2088 // PTR/TXT records) if we don't have a target anymore. When we get a response from the server,
2089 // SRVChanged state tells that we registered/deregistered because of a target change
2090 // and hence handle accordingly e.g., if we deregistered, put the records in NoTarget state OR
2091 // if we registered then put it in Registered state.
2093 // Here, we are registering all the records again from the beginning. Treat this as first time
2094 // registration rather than a temporary target change.
2095 rr
->SRVChanged
= mDNSfalse
;
2097 // We want IsRecordMergeable to check whether it is a record whose update can be
2098 // sent with others. We set the time before we call IsRecordMergeable, so that
2099 // it does not fail this record based on time. We are interested in other checks
2101 rr
->state
= regState_Pending
;
2102 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
2103 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
2104 if (IsRecordMergeable(m
, rr
, m
->timenow
+ MERGE_DELAY_TIME
))
2105 // Delay the record registration by MERGE_DELAY_TIME so that we can merge them
2107 rr
->LastAPTime
+= MERGE_DELAY_TIME
;
2109 // We call this always even though it may not be necessary always e.g., normal registration
2110 // process where TXT and PTR gets registered followed by the SRV record after it gets
2111 // the port mapping. In that case, UpdateAllServiceRecords handles the optimization. The
2112 // update of TXT and PTR record is required if we entered noTargetState before as explained
2114 UpdateAllServiceRecords(m
, rr
, mDNStrue
);
2117 mDNSlocal
void StartRecordNatMap(mDNS
*m
, AuthRecord
*rr
)
2122 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
2124 LogInfo("StartRecordNatMap: Resource Record %##s type %d, not supported", rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
2127 p
= rr
->resrec
.name
->c
;
2128 //Assume <Service Instance>.<App Protocol>.<Transport protocol>.<Name>
2129 // Skip the first two labels to get to the transport protocol
2130 if (p
[0]) p
+= 1 + p
[0];
2131 if (p
[0]) p
+= 1 + p
[0];
2132 if (SameDomainLabel(p
, (mDNSu8
*)"\x4" "_tcp")) protocol
= NATOp_MapTCP
;
2133 else if (SameDomainLabel(p
, (mDNSu8
*)"\x4" "_udp")) protocol
= NATOp_MapUDP
;
2134 else { LogMsg("StartRecordNatMap: could not determine transport protocol of service %##s", rr
->resrec
.name
->c
); return; }
2136 //LogMsg("StartRecordNatMap: clientContext %p IntPort %d srv.port %d %s",
2137 // rr->NATinfo.clientContext, mDNSVal16(rr->NATinfo.IntPort), mDNSVal16(rr->resrec.rdata->u.srv.port), ARDisplayString(m, rr));
2138 if (rr
->NATinfo
.clientContext
) mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
2139 rr
->NATinfo
.Protocol
= protocol
;
2141 // Shouldn't be trying to set IntPort here --
2142 // BuildUpdateMessage overwrites srs->RR_SRV.resrec.rdata->u.srv.port with external (mapped) port number
2143 rr
->NATinfo
.IntPort
= rr
->resrec
.rdata
->u
.srv
.port
;
2144 rr
->NATinfo
.RequestedPort
= rr
->resrec
.rdata
->u
.srv
.port
;
2145 rr
->NATinfo
.NATLease
= 0; // Request default lease
2146 rr
->NATinfo
.clientCallback
= CompleteRecordNatMap
;
2147 rr
->NATinfo
.clientContext
= rr
;
2148 mDNS_StartNATOperation_internal(m
, &rr
->NATinfo
);
2151 // Unlink an Auth Record from the m->ResourceRecords list.
2152 // When a resource record enters regState_NoTarget initially, mDNS_Register_internal
2153 // does not initialize completely e.g., it cannot check for duplicates etc. The resource
2154 // record is temporarily left in the ResourceRecords list so that we can initialize later
2155 // when the target is resolvable. Similarly, when host name changes, we enter regState_NoTarget
2156 // and we do the same.
2158 // This UnlinkResourceRecord routine is very worrying. It bypasses all the normal cleanup performed
2159 // by mDNS_Deregister_internal and just unceremoniously cuts the record from the active list.
2160 // This is why re-regsitering this record was producing syslog messages like this:
2161 // "Error! Tried to add a NAT traversal that's already in the active list"
2162 // Right now UnlinkResourceRecord is fortunately only called by RegisterAllServiceRecords,
2163 // which then immediately calls mDNS_Register_internal to re-register the record, which probably
2164 // masked more serious problems. Any other use of UnlinkResourceRecord is likely to lead to crashes.
2165 // For now we'll workaround that specific problem by explicitly calling mDNS_StopNATOperation_internal,
2166 // but long-term we should either stop cancelling the record registration and then re-registering it,
2167 // or if we really do need to do this for some reason it should be done via the usual
2168 // mDNS_Deregister_internal path instead of just cutting the record from the list.
2170 mDNSlocal mStatus
UnlinkResourceRecord(mDNS
*const m
, AuthRecord
*const rr
)
2172 AuthRecord
**list
= &m
->ResourceRecords
;
2173 while (*list
&& *list
!= rr
) list
= &(*list
)->next
;
2177 rr
->next
= mDNSNULL
;
2179 // Temporary workaround to cancel any active NAT mapping operation
2180 if (rr
->NATinfo
.clientContext
)
2182 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
2183 rr
->NATinfo
.clientContext
= mDNSNULL
;
2184 if (rr
->resrec
.rrtype
== kDNSType_SRV
) rr
->resrec
.rdata
->u
.srv
.port
= rr
->NATinfo
.IntPort
;
2187 return(mStatus_NoError
);
2189 LogMsg("UnlinkResourceRecord:ERROR!! - no such active record %##s", rr
->resrec
.name
->c
);
2190 return(mStatus_NoSuchRecord
);
2193 // We need to go through mDNS_Register again as we did not complete the
2194 // full initialization last time e.g., duplicate checks.
2195 // After we register, we will be in regState_GetZoneData.
2196 mDNSlocal
void RegisterAllServiceRecords(mDNS
*const m
, AuthRecord
*rr
)
2198 LogInfo("RegisterAllServiceRecords: Service Record %##s", rr
->resrec
.name
->c
);
2199 // First Register the service record, we do this differently from other records because
2200 // when it entered NoTarget state, it did not go through complete initialization
2201 rr
->SRVChanged
= mDNSfalse
;
2202 UnlinkResourceRecord(m
, rr
);
2203 mDNS_Register_internal(m
, rr
);
2204 // Register the other records
2205 UpdateAllServiceRecords(m
, rr
, mDNStrue
);
2208 // Called with lock held
2209 mDNSlocal
void UpdateOneSRVRecord(mDNS
*m
, AuthRecord
*rr
)
2211 // Target change if:
2212 // We have a target and were previously waiting for one, or
2213 // We had a target and no longer do, or
2214 // The target has changed
2216 domainname
*curtarget
= &rr
->resrec
.rdata
->u
.srv
.target
;
2217 const domainname
*const nt
= GetServiceTarget(m
, rr
);
2218 const domainname
*const newtarget
= nt
? nt
: (domainname
*)"";
2219 mDNSBool TargetChanged
= (newtarget
->c
[0] && rr
->state
== regState_NoTarget
) || !SameDomainName(curtarget
, newtarget
);
2220 mDNSBool HaveZoneData
= rr
->nta
&& !mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
);
2222 // Nat state change if:
2223 // We were behind a NAT, and now we are behind a new NAT, or
2224 // We're not behind a NAT but our port was previously mapped to a different external port
2225 // We were not behind a NAT and now we are
2227 mDNSIPPort port
= rr
->resrec
.rdata
->u
.srv
.port
;
2228 mDNSBool NowNeedNATMAP
= (rr
->AutoTarget
== Target_AutoHostAndNATMAP
&& !mDNSIPPortIsZero(port
) && mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
) && rr
->nta
&& !mDNSAddrIsRFC1918(&rr
->nta
->Addr
));
2229 mDNSBool WereBehindNAT
= (rr
->NATinfo
.clientContext
!= mDNSNULL
);
2230 mDNSBool PortWasMapped
= (rr
->NATinfo
.clientContext
&& !mDNSSameIPPort(rr
->NATinfo
.RequestedPort
, port
)); // I think this is always false -- SC Sept 07
2231 mDNSBool NATChanged
= (!WereBehindNAT
&& NowNeedNATMAP
) || (!NowNeedNATMAP
&& PortWasMapped
);
2233 (void)HaveZoneData
; //unused
2235 LogInfo("UpdateOneSRVRecord: Resource Record %s TargetChanged %d, NewTarget %##s", ARDisplayString(m
, rr
), TargetChanged
, nt
->c
);
2237 debugf("UpdateOneSRVRecord: %##s newtarget %##s TargetChanged %d HaveZoneData %d port %d NowNeedNATMAP %d WereBehindNAT %d PortWasMapped %d NATChanged %d",
2238 rr
->resrec
.name
->c
, newtarget
,
2239 TargetChanged
, HaveZoneData
, mDNSVal16(port
), NowNeedNATMAP
, WereBehindNAT
, PortWasMapped
, NATChanged
);
2243 if (!TargetChanged
&& !NATChanged
) return;
2245 // If we are deregistering the record, then ignore any NAT/Target change.
2246 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2248 LogInfo("UpdateOneSRVRecord: Deregistering record, Ignoring TargetChanged %d, NATChanged %d for %##s, state %d", TargetChanged
, NATChanged
,
2249 rr
->resrec
.name
->c
, rr
->state
);
2254 LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, newtarget %##s", TargetChanged
, NATChanged
, rr
->resrec
.name
->c
, rr
->state
, newtarget
->c
);
2256 LogInfo("UpdateOneSRVRecord: TargetChanged %d, NATChanged %d for %##s, state %d, null newtarget", TargetChanged
, NATChanged
, rr
->resrec
.name
->c
, rr
->state
);
2259 case regState_NATMap
:
2260 // In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
2261 // or is in the process of, or has already been, deregistered. This assumes that whenever we transition out
2262 // of this state, we need to look at the target again.
2265 case regState_UpdatePending
:
2266 // We are getting a Target change/NAT change while the SRV record is being updated ?
2267 // let us not do anything for now.
2270 case regState_NATError
:
2271 if (!NATChanged
) return;
2273 // if nat changed, register if we have a target (below)
2275 case regState_NoTarget
:
2276 if (!newtarget
->c
[0])
2278 LogInfo("UpdateOneSRVRecord: No target yet for Resource Record %s", ARDisplayString(m
, rr
));
2281 RegisterAllServiceRecords(m
, rr
);
2283 case regState_DeregPending
:
2284 // We are in DeregPending either because the service was deregistered from above or we handled
2285 // a NAT/Target change before and sent the deregistration below. There are a few race conditions
2288 // 1. We are handling a second NAT/Target change while the first dereg is in progress. It is possible
2289 // that first dereg never made it through because there was no network connectivity e.g., disconnecting
2290 // from network triggers this function due to a target change and later connecting to the network
2291 // retriggers this function but the deregistration never made it through yet. Just fall through.
2292 // If there is a target register otherwise deregister.
2294 // 2. While we sent the dereg during a previous NAT/Target change, uDNS_DeregisterRecord gets
2295 // called as part of service deregistration. When the response comes back, we call
2296 // CompleteDeregistration rather than handle NAT/Target change because the record is in
2297 // kDNSRecordTypeDeregistering state.
2299 // 3. If the upper layer deregisters the service, we check for kDNSRecordTypeDeregistering both
2300 // here in this function to avoid handling NAT/Target change and in hndlRecordUpdateReply to call
2301 // CompleteDeregistration instead of handling NAT/Target change. Hence, we are not concerned
2302 // about that case here.
2304 // We just handle case (1) by falling through
2305 case regState_Pending
:
2306 case regState_Refresh
:
2307 case regState_Registered
:
2308 // target or nat changed. deregister service. upon completion, we'll look for a new target
2309 rr
->SRVChanged
= mDNStrue
;
2310 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
2311 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
2312 if (newtarget
->c
[0])
2314 LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s, registering with new target %##s",
2315 rr
->resrec
.name
->c
, newtarget
->c
);
2316 rr
->state
= regState_Pending
;
2320 LogInfo("UpdateOneSRVRecord: SRV record changed for service %##s de-registering", rr
->resrec
.name
->c
);
2321 rr
->state
= regState_DeregPending
;
2322 UpdateAllServiceRecords(m
, rr
, mDNSfalse
);
2325 case regState_Unregistered
:
2326 default: LogMsg("UpdateOneSRVRecord: Unknown state %d for %##s", rr
->state
, rr
->resrec
.name
->c
);
2330 mDNSexport
void UpdateAllSRVRecords(mDNS
*m
)
2332 m
->NextSRVUpdate
= 0;
2333 LogInfo("UpdateAllSRVRecords %d", m
->SleepState
);
2335 if (m
->CurrentRecord
)
2336 LogMsg("UpdateAllSRVRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2337 m
->CurrentRecord
= m
->ResourceRecords
;
2338 while (m
->CurrentRecord
)
2340 AuthRecord
*rptr
= m
->CurrentRecord
;
2341 m
->CurrentRecord
= m
->CurrentRecord
->next
;
2342 if (AuthRecord_uDNS(rptr
) && rptr
->resrec
.rrtype
== kDNSType_SRV
)
2343 UpdateOneSRVRecord(m
, rptr
);
2347 // Forward reference: AdvertiseHostname references HostnameCallback, and HostnameCallback calls AdvertiseHostname
2348 mDNSlocal
void HostnameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
2350 // Called in normal client context (lock not held)
2351 mDNSlocal
void hostnameGetPublicAddressCallback(mDNS
*m
, NATTraversalInfo
*n
)
2353 HostnameInfo
*h
= (HostnameInfo
*)n
->clientContext
;
2355 if (!h
) { LogMsg("RegisterHostnameRecord: registration cancelled"); return; }
2359 if (mDNSIPv4AddressIsZero(n
->ExternalAddress
) || mDNSv4AddrIsRFC1918(&n
->ExternalAddress
)) return;
2361 if (h
->arv4
.resrec
.RecordType
)
2363 if (mDNSSameIPv4Address(h
->arv4
.resrec
.rdata
->u
.ipv4
, n
->ExternalAddress
)) return; // If address unchanged, do nothing
2364 LogInfo("Updating hostname %p %##s IPv4 from %.4a to %.4a (NAT gateway's external address)",n
,
2365 h
->arv4
.resrec
.name
->c
, &h
->arv4
.resrec
.rdata
->u
.ipv4
, &n
->ExternalAddress
);
2366 mDNS_Deregister(m
, &h
->arv4
); // mStatus_MemFree callback will re-register with new address
2370 LogInfo("Advertising hostname %##s IPv4 %.4a (NAT gateway's external address)", h
->arv4
.resrec
.name
->c
, &n
->ExternalAddress
);
2371 h
->arv4
.resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
2372 h
->arv4
.resrec
.rdata
->u
.ipv4
= n
->ExternalAddress
;
2373 mDNS_Register(m
, &h
->arv4
);
2378 // register record or begin NAT traversal
2379 mDNSlocal
void AdvertiseHostname(mDNS
*m
, HostnameInfo
*h
)
2381 if (!mDNSIPv4AddressIsZero(m
->AdvertisedV4
.ip
.v4
) && h
->arv4
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2383 mDNS_SetupResourceRecord(&h
->arv4
, mDNSNULL
, mDNSInterface_Any
, kDNSType_A
, kHostNameTTL
, kDNSRecordTypeUnregistered
, AuthRecordAny
, HostnameCallback
, h
);
2384 AssignDomainName(&h
->arv4
.namestorage
, &h
->fqdn
);
2385 h
->arv4
.resrec
.rdata
->u
.ipv4
= m
->AdvertisedV4
.ip
.v4
;
2386 h
->arv4
.state
= regState_Unregistered
;
2387 if (mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
))
2389 // If we already have a NAT query active, stop it and restart it to make sure we get another callback
2390 if (h
->natinfo
.clientContext
) mDNS_StopNATOperation_internal(m
, &h
->natinfo
);
2391 h
->natinfo
.Protocol
= 0;
2392 h
->natinfo
.IntPort
= zeroIPPort
;
2393 h
->natinfo
.RequestedPort
= zeroIPPort
;
2394 h
->natinfo
.NATLease
= 0;
2395 h
->natinfo
.clientCallback
= hostnameGetPublicAddressCallback
;
2396 h
->natinfo
.clientContext
= h
;
2397 mDNS_StartNATOperation_internal(m
, &h
->natinfo
);
2401 LogInfo("Advertising hostname %##s IPv4 %.4a", h
->arv4
.resrec
.name
->c
, &m
->AdvertisedV4
.ip
.v4
);
2402 h
->arv4
.resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
2403 mDNS_Register_internal(m
, &h
->arv4
);
2407 if (!mDNSIPv6AddressIsZero(m
->AdvertisedV6
.ip
.v6
) && h
->arv6
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2409 mDNS_SetupResourceRecord(&h
->arv6
, mDNSNULL
, mDNSInterface_Any
, kDNSType_AAAA
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, HostnameCallback
, h
);
2410 AssignDomainName(&h
->arv6
.namestorage
, &h
->fqdn
);
2411 h
->arv6
.resrec
.rdata
->u
.ipv6
= m
->AdvertisedV6
.ip
.v6
;
2412 h
->arv6
.state
= regState_Unregistered
;
2413 LogInfo("Advertising hostname %##s IPv6 %.16a", h
->arv6
.resrec
.name
->c
, &m
->AdvertisedV6
.ip
.v6
);
2414 mDNS_Register_internal(m
, &h
->arv6
);
2418 mDNSlocal
void HostnameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
2420 HostnameInfo
*hi
= (HostnameInfo
*)rr
->RecordContext
;
2422 if (result
== mStatus_MemFree
)
2426 // If we're still in the Hostnames list, update to new address
2428 LogInfo("HostnameCallback: Got mStatus_MemFree for %p %p %s", hi
, rr
, ARDisplayString(m
, rr
));
2429 for (i
= m
->Hostnames
; i
; i
= i
->next
)
2430 if (rr
== &i
->arv4
|| rr
== &i
->arv6
)
2431 { mDNS_Lock(m
); AdvertiseHostname(m
, i
); mDNS_Unlock(m
); return; }
2433 // Else, we're not still in the Hostnames list, so free the memory
2434 if (hi
->arv4
.resrec
.RecordType
== kDNSRecordTypeUnregistered
&&
2435 hi
->arv6
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2437 if (hi
->natinfo
.clientContext
) mDNS_StopNATOperation_internal(m
, &hi
->natinfo
);
2438 hi
->natinfo
.clientContext
= mDNSNULL
;
2439 mDNSPlatformMemFree(hi
); // free hi when both v4 and v6 AuthRecs deallocated
2447 // don't unlink or free - we can retry when we get a new address/router
2448 if (rr
->resrec
.rrtype
== kDNSType_A
)
2449 LogMsg("HostnameCallback: Error %d for registration of %##s IP %.4a", result
, rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv4
);
2451 LogMsg("HostnameCallback: Error %d for registration of %##s IP %.16a", result
, rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv6
);
2452 if (!hi
) { mDNSPlatformMemFree(rr
); return; }
2453 if (rr
->state
!= regState_Unregistered
) LogMsg("Error: HostnameCallback invoked with error code for record not in regState_Unregistered!");
2455 if (hi
->arv4
.state
== regState_Unregistered
&&
2456 hi
->arv6
.state
== regState_Unregistered
)
2458 // only deliver status if both v4 and v6 fail
2459 rr
->RecordContext
= (void *)hi
->StatusContext
;
2460 if (hi
->StatusCallback
)
2461 hi
->StatusCallback(m
, rr
, result
); // client may NOT make API calls here
2462 rr
->RecordContext
= (void *)hi
;
2467 // register any pending services that require a target
2469 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2472 // Deliver success to client
2473 if (!hi
) { LogMsg("HostnameCallback invoked with orphaned address record"); return; }
2474 if (rr
->resrec
.rrtype
== kDNSType_A
)
2475 LogInfo("Registered hostname %##s IP %.4a", rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv4
);
2477 LogInfo("Registered hostname %##s IP %.16a", rr
->resrec
.name
->c
, &rr
->resrec
.rdata
->u
.ipv6
);
2479 rr
->RecordContext
= (void *)hi
->StatusContext
;
2480 if (hi
->StatusCallback
)
2481 hi
->StatusCallback(m
, rr
, result
); // client may NOT make API calls here
2482 rr
->RecordContext
= (void *)hi
;
2485 mDNSlocal
void FoundStaticHostname(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2487 const domainname
*pktname
= &answer
->rdata
->u
.name
;
2488 domainname
*storedname
= &m
->StaticHostname
;
2489 HostnameInfo
*h
= m
->Hostnames
;
2493 if (answer
->rdlength
!= 0)
2494 LogInfo("FoundStaticHostname: question %##s -> answer %##s (%s)", question
->qname
.c
, answer
->rdata
->u
.name
.c
, AddRecord
? "ADD" : "RMV");
2496 LogInfo("FoundStaticHostname: question %##s -> answer NULL (%s)", question
->qname
.c
, AddRecord
? "ADD" : "RMV");
2498 if (AddRecord
&& answer
->rdlength
!= 0 && !SameDomainName(pktname
, storedname
))
2500 AssignDomainName(storedname
, pktname
);
2503 if (h
->arv4
.state
== regState_Pending
|| h
->arv4
.state
== regState_NATMap
|| h
->arv6
.state
== regState_Pending
)
2505 // if we're in the process of registering a dynamic hostname, delay SRV update so we don't have to reregister services if the dynamic name succeeds
2506 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ 5 * mDNSPlatformOneSecond
);
2507 debugf("FoundStaticHostname: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
2513 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2516 else if (!AddRecord
&& SameDomainName(pktname
, storedname
))
2519 storedname
->c
[0] = 0;
2520 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2525 // Called with lock held
2526 mDNSlocal
void GetStaticHostname(mDNS
*m
)
2528 char buf
[MAX_REVERSE_MAPPING_NAME_V4
];
2529 DNSQuestion
*q
= &m
->ReverseMap
;
2530 mDNSu8
*ip
= m
->AdvertisedV4
.ip
.v4
.b
;
2533 if (m
->ReverseMap
.ThisQInterval
!= -1) return; // already running
2534 if (mDNSIPv4AddressIsZero(m
->AdvertisedV4
.ip
.v4
)) return;
2536 mDNSPlatformMemZero(q
, sizeof(*q
));
2537 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
2538 mDNS_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa.", ip
[3], ip
[2], ip
[1], ip
[0]);
2539 if (!MakeDomainNameFromDNSNameString(&q
->qname
, buf
)) { LogMsg("Error: GetStaticHostname - bad name %s", buf
); return; }
2541 q
->InterfaceID
= mDNSInterface_Any
;
2543 q
->qtype
= kDNSType_PTR
;
2544 q
->qclass
= kDNSClass_IN
;
2545 q
->LongLived
= mDNSfalse
;
2546 q
->ExpectUnique
= mDNSfalse
;
2547 q
->ForceMCast
= mDNSfalse
;
2548 q
->ReturnIntermed
= mDNStrue
;
2549 q
->SuppressUnusable
= mDNSfalse
;
2550 q
->AppendSearchDomains
= 0;
2551 q
->TimeoutQuestion
= 0;
2552 q
->WakeOnResolve
= 0;
2553 q
->UseBackgroundTraffic
= mDNSfalse
;
2554 q
->ProxyQuestion
= 0;
2555 q
->pid
= mDNSPlatformGetPID();
2557 q
->QuestionCallback
= FoundStaticHostname
;
2558 q
->QuestionContext
= mDNSNULL
;
2560 LogInfo("GetStaticHostname: %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
2561 err
= mDNS_StartQuery_internal(m
, q
);
2562 if (err
) LogMsg("Error: GetStaticHostname - StartQuery returned error %d", err
);
2565 mDNSexport
void mDNS_AddDynDNSHostName(mDNS
*m
, const domainname
*fqdn
, mDNSRecordCallback
*StatusCallback
, const void *StatusContext
)
2567 HostnameInfo
**ptr
= &m
->Hostnames
;
2569 LogInfo("mDNS_AddDynDNSHostName %##s", fqdn
);
2571 while (*ptr
&& !SameDomainName(fqdn
, &(*ptr
)->fqdn
)) ptr
= &(*ptr
)->next
;
2572 if (*ptr
) { LogMsg("DynDNSHostName %##s already in list", fqdn
->c
); return; }
2574 // allocate and format new address record
2575 *ptr
= (HostnameInfo
*) mDNSPlatformMemAllocateClear(sizeof(**ptr
));
2576 if (!*ptr
) { LogMsg("ERROR: mDNS_AddDynDNSHostName - malloc"); return; }
2578 AssignDomainName(&(*ptr
)->fqdn
, fqdn
);
2579 (*ptr
)->arv4
.state
= regState_Unregistered
;
2580 (*ptr
)->arv6
.state
= regState_Unregistered
;
2581 (*ptr
)->StatusCallback
= StatusCallback
;
2582 (*ptr
)->StatusContext
= StatusContext
;
2584 AdvertiseHostname(m
, *ptr
);
2587 mDNSexport
void mDNS_RemoveDynDNSHostName(mDNS
*m
, const domainname
*fqdn
)
2589 HostnameInfo
**ptr
= &m
->Hostnames
;
2591 LogInfo("mDNS_RemoveDynDNSHostName %##s", fqdn
);
2593 while (*ptr
&& !SameDomainName(fqdn
, &(*ptr
)->fqdn
)) ptr
= &(*ptr
)->next
;
2594 if (!*ptr
) LogMsg("mDNS_RemoveDynDNSHostName: no such domainname %##s", fqdn
->c
);
2597 HostnameInfo
*hi
= *ptr
;
2598 // We do it this way because, if we have no active v6 record, the "mDNS_Deregister_internal(m, &hi->arv4);"
2599 // below could free the memory, and we have to make sure we don't touch hi fields after that.
2600 mDNSBool f4
= hi
->arv4
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
&& hi
->arv4
.state
!= regState_Unregistered
;
2601 mDNSBool f6
= hi
->arv6
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
&& hi
->arv6
.state
!= regState_Unregistered
;
2602 *ptr
= (*ptr
)->next
; // unlink
2607 LogInfo("mDNS_RemoveDynDNSHostName removing v4 %##s", fqdn
);
2608 mDNS_Deregister_internal(m
, &hi
->arv4
, mDNS_Dereg_normal
);
2612 LogInfo("mDNS_RemoveDynDNSHostName removing v6 %##s", fqdn
);
2613 mDNS_Deregister_internal(m
, &hi
->arv6
, mDNS_Dereg_normal
);
2615 // When both deregistrations complete we'll free the memory in the mStatus_MemFree callback
2619 if (hi
->natinfo
.clientContext
)
2621 mDNS_StopNATOperation_internal(m
, &hi
->natinfo
);
2622 hi
->natinfo
.clientContext
= mDNSNULL
;
2624 mDNSPlatformMemFree(hi
);
2628 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2631 // Currently called without holding the lock
2632 // Maybe we should change that?
2633 mDNSexport
void mDNS_SetPrimaryInterfaceInfo(mDNS
*m
, const mDNSAddr
*v4addr
, const mDNSAddr
*v6addr
, const mDNSAddr
*router
)
2635 mDNSBool v4Changed
, v6Changed
, RouterChanged
;
2637 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
2638 LogMsg("mDNS_SetPrimaryInterfaceInfo: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
2640 if (v4addr
&& v4addr
->type
!= mDNSAddrType_IPv4
) { LogMsg("mDNS_SetPrimaryInterfaceInfo v4 address - incorrect type. Discarding. %#a", v4addr
); return; }
2641 if (v6addr
&& v6addr
->type
!= mDNSAddrType_IPv6
) { LogMsg("mDNS_SetPrimaryInterfaceInfo v6 address - incorrect type. Discarding. %#a", v6addr
); return; }
2642 if (router
&& router
->type
!= mDNSAddrType_IPv4
) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-v4 router. Discarding. %#a", router
); return; }
2646 v4Changed
= !mDNSSameIPv4Address(m
->AdvertisedV4
.ip
.v4
, v4addr
? v4addr
->ip
.v4
: zerov4Addr
);
2647 v6Changed
= !mDNSSameIPv6Address(m
->AdvertisedV6
.ip
.v6
, v6addr
? v6addr
->ip
.v6
: zerov6Addr
);
2648 RouterChanged
= !mDNSSameIPv4Address(m
->Router
.ip
.v4
, router
? router
->ip
.v4
: zerov4Addr
);
2650 if (v4addr
&& (v4Changed
|| RouterChanged
))
2651 debugf("mDNS_SetPrimaryInterfaceInfo: address changed from %#a to %#a", &m
->AdvertisedV4
, v4addr
);
2653 if (v4addr
) m
->AdvertisedV4
= *v4addr
;else m
->AdvertisedV4
.ip
.v4
= zerov4Addr
;
2654 if (v6addr
) m
->AdvertisedV6
= *v6addr
;else m
->AdvertisedV6
.ip
.v6
= zerov6Addr
;
2655 if (router
) m
->Router
= *router
;else m
->Router
.ip
.v4
= zerov4Addr
;
2656 // setting router to zero indicates that nat mappings must be reestablished when router is reset
2658 if (v4Changed
|| RouterChanged
|| v6Changed
)
2661 LogInfo("mDNS_SetPrimaryInterfaceInfo: %s%s%s%#a %#a %#a",
2662 v4Changed
? "v4Changed " : "",
2663 RouterChanged
? "RouterChanged " : "",
2664 v6Changed
? "v6Changed " : "", v4addr
, v6addr
, router
);
2666 for (i
= m
->Hostnames
; i
; i
= i
->next
)
2668 LogInfo("mDNS_SetPrimaryInterfaceInfo updating host name registrations for %##s", i
->fqdn
.c
);
2670 if (i
->arv4
.resrec
.RecordType
> kDNSRecordTypeDeregistering
&&
2671 !mDNSSameIPv4Address(i
->arv4
.resrec
.rdata
->u
.ipv4
, m
->AdvertisedV4
.ip
.v4
))
2673 LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m
, &i
->arv4
));
2674 mDNS_Deregister_internal(m
, &i
->arv4
, mDNS_Dereg_normal
);
2677 if (i
->arv6
.resrec
.RecordType
> kDNSRecordTypeDeregistering
&&
2678 !mDNSSameIPv6Address(i
->arv6
.resrec
.rdata
->u
.ipv6
, m
->AdvertisedV6
.ip
.v6
))
2680 LogInfo("mDNS_SetPrimaryInterfaceInfo deregistering %s", ARDisplayString(m
, &i
->arv6
));
2681 mDNS_Deregister_internal(m
, &i
->arv6
, mDNS_Dereg_normal
);
2684 // AdvertiseHostname will only register new address records.
2685 // For records still in the process of deregistering it will ignore them, and let the mStatus_MemFree callback handle them.
2686 AdvertiseHostname(m
, i
);
2689 if (v4Changed
|| RouterChanged
)
2691 // If we have a non-zero IPv4 address, we should try immediately to see if we have a NAT gateway
2692 // If we have no IPv4 address, we don't want to be in quite such a hurry to report failures to our clients
2693 // <rdar://problem/6935929> Sleeping server sometimes briefly disappears over Back to My Mac after it wakes up
2694 mDNSu32 waitSeconds
= v4addr
? 0 : 5;
2695 NATTraversalInfo
*n
;
2696 m
->ExtAddress
= zerov4Addr
;
2697 m
->LastNATMapResultCode
= NATErr_None
;
2699 RecreateNATMappings(m
, mDNSPlatformOneSecond
* waitSeconds
);
2701 for (n
= m
->NATTraversals
; n
; n
=n
->next
)
2702 n
->NewAddress
= zerov4Addr
;
2704 LogInfo("mDNS_SetPrimaryInterfaceInfo:%s%s: recreating NAT mappings in %d seconds",
2705 v4Changed
? " v4Changed" : "",
2706 RouterChanged
? " RouterChanged" : "",
2710 if (m
->ReverseMap
.ThisQInterval
!= -1) mDNS_StopQuery_internal(m
, &m
->ReverseMap
);
2711 m
->StaticHostname
.c
[0] = 0;
2713 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
);
2719 // ***************************************************************************
2720 #if COMPILER_LIKES_PRAGMA_MARK
2721 #pragma mark - Incoming Message Processing
2724 mDNSlocal mStatus
ParseTSIGError(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
, const domainname
*const displayname
)
2727 mStatus err
= mStatus_NoError
;
2730 ptr
= LocateAdditionals(msg
, end
);
2731 if (!ptr
) goto finish
;
2733 for (i
= 0; i
< msg
->h
.numAdditionals
; i
++)
2735 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
2736 if (!ptr
) goto finish
;
2737 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
)
2740 mDNSu8
*rd
= m
->rec
.r
.resrec
.rdata
->u
.data
;
2741 mDNSu8
*rdend
= rd
+ m
->rec
.r
.resrec
.rdlength
;
2742 int alglen
= DomainNameLengthLimit(&m
->rec
.r
.resrec
.rdata
->u
.name
, rdend
);
2743 if (alglen
> MAX_DOMAIN_NAME
) goto finish
;
2744 rd
+= alglen
; // algorithm name
2745 if (rd
+ 6 > rdend
) goto finish
;
2746 rd
+= 6; // 48-bit timestamp
2747 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2748 rd
+= sizeof(mDNSOpaque16
); // fudge
2749 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2750 macsize
= mDNSVal16(*(mDNSOpaque16
*)rd
);
2751 rd
+= sizeof(mDNSOpaque16
); // MAC size
2752 if (rd
+ macsize
> rdend
) goto finish
;
2754 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2755 rd
+= sizeof(mDNSOpaque16
); // orig id
2756 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2757 err
= mDNSVal16(*(mDNSOpaque16
*)rd
); // error code
2759 if (err
== TSIG_ErrBadSig
) { LogMsg("%##s: bad signature", displayname
->c
); err
= mStatus_BadSig
; }
2760 else if (err
== TSIG_ErrBadKey
) { LogMsg("%##s: bad key", displayname
->c
); err
= mStatus_BadKey
; }
2761 else if (err
== TSIG_ErrBadTime
) { LogMsg("%##s: bad time", displayname
->c
); err
= mStatus_BadTime
; }
2762 else if (err
) { LogMsg("%##s: unknown tsig error %d", displayname
->c
, err
); err
= mStatus_UnknownErr
; }
2765 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
2769 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
2773 mDNSlocal mStatus
checkUpdateResult(mDNS
*const m
, const domainname
*const displayname
, const mDNSu8 rcode
, const DNSMessage
*const msg
, const mDNSu8
*const end
)
2775 (void)msg
; // currently unused, needed for TSIG errors
2776 if (!rcode
) return mStatus_NoError
;
2777 else if (rcode
== kDNSFlag1_RC_YXDomain
)
2779 debugf("name in use: %##s", displayname
->c
);
2780 return mStatus_NameConflict
;
2782 else if (rcode
== kDNSFlag1_RC_Refused
)
2784 LogMsg("Update %##s refused", displayname
->c
);
2785 return mStatus_Refused
;
2787 else if (rcode
== kDNSFlag1_RC_NXRRSet
)
2789 LogMsg("Reregister refused (NXRRSET): %##s", displayname
->c
);
2790 return mStatus_NoSuchRecord
;
2792 else if (rcode
== kDNSFlag1_RC_NotAuth
)
2794 // TSIG errors should come with FormErr as per RFC 2845, but BIND 9 sends them with NotAuth so we look here too
2795 mStatus tsigerr
= ParseTSIGError(m
, msg
, end
, displayname
);
2798 LogMsg("Permission denied (NOAUTH): %##s", displayname
->c
);
2799 return mStatus_UnknownErr
;
2801 else return tsigerr
;
2803 else if (rcode
== kDNSFlag1_RC_FormErr
)
2805 mStatus tsigerr
= ParseTSIGError(m
, msg
, end
, displayname
);
2808 LogMsg("Format Error: %##s", displayname
->c
);
2809 return mStatus_UnknownErr
;
2811 else return tsigerr
;
2815 LogMsg("Update %##s failed with rcode %d", displayname
->c
, rcode
);
2816 return mStatus_UnknownErr
;
2820 mDNSlocal mDNSu32
RRAdditionalSize(DomainAuthInfo
*AuthInfo
)
2822 mDNSu32 leaseSize
, tsigSize
;
2823 mDNSu32 rr_base_size
= 10; // type (2) class (2) TTL (4) rdlength (2)
2825 // OPT RR : Emptyname(.) + base size + rdataOPT
2826 leaseSize
= 1 + rr_base_size
+ sizeof(rdataOPT
);
2828 //TSIG: Resource Record Name + base size + RDATA
2830 // Algorithm name: hmac-md5.sig-alg.reg.int (8+7+3+3 + 5 bytes for length = 26 bytes)
2833 // Mac Size: 2 bytes
2840 if (AuthInfo
) tsigSize
= DomainNameLength(&AuthInfo
->keyname
) + rr_base_size
+ 58;
2842 return (leaseSize
+ tsigSize
);
2845 //Note: Make sure that RREstimatedSize is updated accordingly if anything that is done here
2846 //would modify rdlength/rdestimate
2847 mDNSlocal mDNSu8
* BuildUpdateMessage(mDNS
*const m
, mDNSu8
*ptr
, AuthRecord
*rr
, mDNSu8
*limit
)
2849 //If this record is deregistering, then just send the deletion record
2850 if (rr
->state
== regState_DeregPending
)
2852 rr
->expire
= 0; // Indicate that we have no active registration any more
2853 ptr
= putDeletionRecordWithLimit(&m
->omsg
, ptr
, &rr
->resrec
, limit
);
2854 if (!ptr
) goto exit
;
2858 // This is a common function to both sending an update in a group or individual
2859 // records separately. Hence, we change the state here.
2860 if (rr
->state
== regState_Registered
) rr
->state
= regState_Refresh
;
2861 if (rr
->state
!= regState_Refresh
&& rr
->state
!= regState_UpdatePending
)
2862 rr
->state
= regState_Pending
;
2864 // For Advisory records like e.g., _services._dns-sd, which is shared, don't send goodbyes as multiple
2865 // host might be registering records and deregistering from one does not make sense
2866 if (rr
->resrec
.RecordType
!= kDNSRecordTypeAdvisory
) rr
->RequireGoodbye
= mDNStrue
;
2868 if ((rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHostAndNATMAP
) &&
2869 !mDNSIPPortIsZero(rr
->NATinfo
.ExternalPort
))
2871 rr
->resrec
.rdata
->u
.srv
.port
= rr
->NATinfo
.ExternalPort
;
2874 if (rr
->state
== regState_UpdatePending
)
2877 SetNewRData(&rr
->resrec
, rr
->OrigRData
, rr
->OrigRDLen
);
2878 if (!(ptr
= putDeletionRecordWithLimit(&m
->omsg
, ptr
, &rr
->resrec
, limit
))) goto exit
; // delete old rdata
2881 SetNewRData(&rr
->resrec
, rr
->InFlightRData
, rr
->InFlightRDLen
);
2882 if (!(ptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, ptr
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
))) goto exit
;
2886 if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
|| rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
2888 // KnownUnique : Delete any previous value
2889 // For Unicast registrations, we don't verify that it is unique, but set to verified and hence we want to
2890 // delete any previous value
2891 ptr
= putDeleteRRSetWithLimit(&m
->omsg
, ptr
, rr
->resrec
.name
, rr
->resrec
.rrtype
, limit
);
2892 if (!ptr
) goto exit
;
2894 else if (rr
->resrec
.RecordType
!= kDNSRecordTypeShared
)
2896 // For now don't do this, until we have the logic for intelligent grouping of individual records into logical service record sets
2897 //ptr = putPrereqNameNotInUse(rr->resrec.name, &m->omsg, ptr, end);
2898 if (!ptr
) goto exit
;
2901 ptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, ptr
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
2902 if (!ptr
) goto exit
;
2907 LogMsg("BuildUpdateMessage: Error formatting message for %s", ARDisplayString(m
, rr
));
2911 // Called with lock held
2912 mDNSlocal
void SendRecordRegistration(mDNS
*const m
, AuthRecord
*rr
)
2914 mDNSu8
*ptr
= m
->omsg
.data
;
2915 mStatus err
= mStatus_UnknownErr
;
2917 DomainAuthInfo
*AuthInfo
;
2919 // For the ability to register large TXT records, we limit the single record registrations
2920 // to AbsoluteMaxDNSMessageData
2921 limit
= ptr
+ AbsoluteMaxDNSMessageData
;
2923 AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
2924 limit
-= RRAdditionalSize(AuthInfo
);
2928 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
2930 // We never call this function when there is no zone information . Log a message if it ever happens.
2931 LogMsg("SendRecordRegistration: No Zone information, should not happen %s", ARDisplayString(m
, rr
));
2935 rr
->updateid
= mDNS_NewMessageID(m
);
2936 InitializeDNSMessage(&m
->omsg
.h
, rr
->updateid
, UpdateReqFlags
);
2939 ptr
= putZone(&m
->omsg
, ptr
, limit
, rr
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
2940 if (!ptr
) goto exit
;
2942 if (!(ptr
= BuildUpdateMessage(m
, ptr
, rr
, limit
))) goto exit
;
2946 ptr
= putUpdateLeaseWithLimit(&m
->omsg
, ptr
, DEFAULT_UPDATE_LEASE
, limit
);
2947 if (!ptr
) goto exit
;
2951 LogInfo("SendRecordRegistration TCP %p %s", rr
->tcp
, ARDisplayString(m
, rr
));
2952 if (rr
->tcp
) LogInfo("SendRecordRegistration: Disposing existing TCP connection for %s", ARDisplayString(m
, rr
));
2953 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2954 if (!rr
->nta
) { LogMsg("SendRecordRegistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
2955 rr
->tcp
= MakeTCPConn(m
, &m
->omsg
, ptr
, kTCPSocketFlags_UseTLS
, &rr
->nta
->Addr
, rr
->nta
->Port
, &rr
->nta
->Host
, mDNSNULL
, rr
);
2959 LogInfo("SendRecordRegistration UDP %s", ARDisplayString(m
, rr
));
2960 if (!rr
->nta
) { LogMsg("SendRecordRegistration:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
2961 err
= mDNSSendDNSMessage(m
, &m
->omsg
, ptr
, mDNSInterface_Any
, mDNSNULL
, mDNSNULL
, &rr
->nta
->Addr
, rr
->nta
->Port
, GetAuthInfoForName_internal(m
, rr
->resrec
.name
), mDNSfalse
);
2962 if (err
) debugf("ERROR: SendRecordRegistration - mDNSSendDNSMessage - %d", err
);
2965 SetRecordRetry(m
, rr
, 0);
2968 LogMsg("SendRecordRegistration: Error formatting message for %s, disabling further updates", ARDisplayString(m
, rr
));
2969 // Disable this record from future updates
2970 rr
->state
= regState_NoTarget
;
2973 // Is the given record "rr" eligible for merging ?
2974 mDNSlocal mDNSBool
IsRecordMergeable(mDNS
*const m
, AuthRecord
*rr
, mDNSs32 time
)
2976 DomainAuthInfo
*info
;
2977 // A record is eligible for merge, if the following properties are met.
2979 // 1. uDNS Resource Record
2980 // 2. It is time to send them now
2981 // 3. It is in proper state
2982 // 4. Update zone has been resolved
2983 // 5. if DomainAuthInfo exists for the zone, it should not be soon deleted
2984 // 6. Zone information is present
2985 // 7. Update server is not zero
2986 // 8. It has a non-null zone
2987 // 9. It uses a lease option
2988 // 10. DontMerge is not set
2990 // Following code is implemented as separate "if" statements instead of one "if" statement
2991 // is for better debugging purposes e.g., we know exactly what failed if debugging turned on.
2993 if (!AuthRecord_uDNS(rr
)) return mDNSfalse
;
2995 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- time
> 0)
2996 { debugf("IsRecordMergeable: Time %d not reached for %s", rr
->LastAPTime
+ rr
->ThisAPInterval
- m
->timenow
, ARDisplayString(m
, rr
)); return mDNSfalse
; }
2998 if (!rr
->zone
) return mDNSfalse
;
3000 info
= GetAuthInfoForName_internal(m
, rr
->zone
);
3002 if (info
&& info
->deltime
&& m
->timenow
- info
->deltime
>= 0) {debugf("IsRecordMergeable: Domain %##s will be deleted soon", info
->domain
.c
); return mDNSfalse
;}
3004 if (rr
->state
!= regState_DeregPending
&& rr
->state
!= regState_Pending
&& rr
->state
!= regState_Registered
&& rr
->state
!= regState_Refresh
&& rr
->state
!= regState_UpdatePending
)
3005 { debugf("IsRecordMergeable: state %d not right %s", rr
->state
, ARDisplayString(m
, rr
)); return mDNSfalse
; }
3007 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
)) return mDNSfalse
;
3009 if (!rr
->uselease
) return mDNSfalse
;
3011 if (rr
->mState
== mergeState_DontMerge
) {debugf("IsRecordMergeable Dontmerge true %s", ARDisplayString(m
, rr
)); return mDNSfalse
;}
3012 debugf("IsRecordMergeable: Returning true for %s", ARDisplayString(m
, rr
));
3016 // Is the resource record "rr" eligible to merge to with "currentRR" ?
3017 mDNSlocal mDNSBool
AreRecordsMergeable(mDNS
*const m
, AuthRecord
*currentRR
, AuthRecord
*rr
, mDNSs32 time
)
3019 // A record is eligible to merge with another record as long it is eligible for merge in itself
3020 // and it has the same zone information as the other record
3021 if (!IsRecordMergeable(m
, rr
, time
)) return mDNSfalse
;
3023 if (!SameDomainName(currentRR
->zone
, rr
->zone
))
3024 { debugf("AreRecordMergeable zone mismatch current rr Zone %##s, rr zone %##s", currentRR
->zone
->c
, rr
->zone
->c
); return mDNSfalse
; }
3026 if (!mDNSSameIPv4Address(currentRR
->nta
->Addr
.ip
.v4
, rr
->nta
->Addr
.ip
.v4
)) return mDNSfalse
;
3028 if (!mDNSSameIPPort(currentRR
->nta
->Port
, rr
->nta
->Port
)) return mDNSfalse
;
3030 debugf("AreRecordsMergeable: Returning true for %s", ARDisplayString(m
, rr
));
3034 // If we can't build the message successfully because of problems in pre-computing
3035 // the space, we disable merging for all the current records
3036 mDNSlocal
void RRMergeFailure(mDNS
*const m
)
3039 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
3041 rr
->mState
= mergeState_DontMerge
;
3042 rr
->SendRNow
= mDNSNULL
;
3043 // Restarting the registration is much simpler than saving and restoring
3045 ActivateUnicastRegistration(m
, rr
);
3049 mDNSlocal
void SendGroupRRMessage(mDNS
*const m
, AuthRecord
*anchorRR
, mDNSu8
*ptr
, DomainAuthInfo
*info
)
3052 if (!anchorRR
) {debugf("SendGroupRRMessage: Could not merge records"); return;}
3054 limit
= m
->omsg
.data
+ NormalMaxDNSMessageData
;
3056 // This has to go in the additional section and hence need to be done last
3057 ptr
= putUpdateLeaseWithLimit(&m
->omsg
, ptr
, DEFAULT_UPDATE_LEASE
, limit
);
3060 LogMsg("SendGroupRRMessage: ERROR: Could not put lease option, failing the group registration");
3061 // if we can't put the lease, we need to undo the merge
3065 if (anchorRR
->Private
)
3067 if (anchorRR
->tcp
) debugf("SendGroupRRMessage: Disposing existing TCP connection for %s", ARDisplayString(m
, anchorRR
));
3068 if (anchorRR
->tcp
) { DisposeTCPConn(anchorRR
->tcp
); anchorRR
->tcp
= mDNSNULL
; }
3069 if (!anchorRR
->nta
) { LogMsg("SendGroupRRMessage:ERROR!! nta is NULL for %s", ARDisplayString(m
, anchorRR
)); return; }
3070 anchorRR
->tcp
= MakeTCPConn(m
, &m
->omsg
, ptr
, kTCPSocketFlags_UseTLS
, &anchorRR
->nta
->Addr
, anchorRR
->nta
->Port
, &anchorRR
->nta
->Host
, mDNSNULL
, anchorRR
);
3071 if (!anchorRR
->tcp
) LogInfo("SendGroupRRMessage: Cannot establish TCP connection for %s", ARDisplayString(m
, anchorRR
));
3072 else LogInfo("SendGroupRRMessage: Sent a group update ID: %d start %p, end %p, limit %p", mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.data
, ptr
, limit
);
3076 mStatus err
= mDNSSendDNSMessage(m
, &m
->omsg
, ptr
, mDNSInterface_Any
, mDNSNULL
, mDNSNULL
, &anchorRR
->nta
->Addr
, anchorRR
->nta
->Port
, info
, mDNSfalse
);
3077 if (err
) LogInfo("SendGroupRRMessage: Cannot send UDP message for %s", ARDisplayString(m
, anchorRR
));
3078 else LogInfo("SendGroupRRMessage: Sent a group UDP update ID: %d start %p, end %p, limit %p", mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.data
, ptr
, limit
);
3083 // As we always include the zone information and the resource records contain zone name
3084 // at the end, it will get compressed. Hence, we subtract zoneSize and add two bytes for
3085 // the compression pointer
3086 mDNSlocal mDNSu32
RREstimatedSize(AuthRecord
*rr
, int zoneSize
)
3090 // Note: Estimation of the record size has to mirror the logic in BuildUpdateMessage, otherwise estimation
3091 // would be wrong. Currently BuildUpdateMessage calls SetNewRData in UpdatePending case. Hence, we need
3092 // to account for that here. Otherwise, we might under estimate the size.
3093 if (rr
->state
== regState_UpdatePending
)
3094 // old RData that will be deleted
3095 // new RData that will be added
3096 rdlength
= rr
->OrigRDLen
+ rr
->InFlightRDLen
;
3098 rdlength
= rr
->resrec
.rdestimate
;
3100 if (rr
->state
== regState_DeregPending
)
3102 debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
3103 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), DomainNameLength(rr
->resrec
.name
), zoneSize
, rdlength
);
3104 return DomainNameLength(rr
->resrec
.name
) - zoneSize
+ 2 + 10 + rdlength
;
3107 // For SRV, TXT, AAAA etc. that are Unique/Verified, we also send a Deletion Record
3108 if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
|| rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
3110 // Deletion Record: Resource Record Name + Base size (10) + 0
3111 // Record: Resource Record Name (Compressed = 2) + Base size (10) + rdestimate
3113 debugf("RREstimatedSize: ResourceRecord %##s (%s), DomainNameLength %d, zoneSize %d, rdestimate %d",
3114 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), DomainNameLength(rr
->resrec
.name
), zoneSize
, rdlength
);
3115 return DomainNameLength(rr
->resrec
.name
) - zoneSize
+ 2 + 10 + 2 + 10 + rdlength
;
3119 return DomainNameLength(rr
->resrec
.name
) - zoneSize
+ 2 + 10 + rdlength
;
3123 mDNSlocal AuthRecord
*MarkRRForSending(mDNS
*const m
)
3126 AuthRecord
*firstRR
= mDNSNULL
;
3128 // Look for records that needs to be sent in the next two seconds (MERGE_DELAY_TIME is set to 1 second).
3129 // The logic is as follows.
3131 // 1. Record 1 finishes getting zone data and its registration gets delayed by 1 second
3132 // 2. Record 2 comes 0.1 second later, finishes getting its zone data and its registration is also delayed by
3133 // 1 second which is now scheduled at 1.1 second
3135 // By looking for 1 second into the future (m->timenow + MERGE_DELAY_TIME below does that) we have merged both
3136 // of the above records. Note that we can't look for records too much into the future as this will affect the
3137 // retry logic. The first retry is scheduled at 3 seconds. Hence, we should always look smaller than that.
3138 // Anything more than one second will affect the first retry to happen sooner.
3140 // Note: As a side effect of looking one second into the future to facilitate merging, the retries happen
3141 // one second sooner.
3142 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
3146 if (!IsRecordMergeable(m
, rr
, m
->timenow
+ MERGE_DELAY_TIME
)) continue;
3149 else if (!AreRecordsMergeable(m
, firstRR
, rr
, m
->timenow
+ MERGE_DELAY_TIME
)) continue;
3151 if (rr
->SendRNow
) LogMsg("MarkRRForSending: Resourcerecord %s already marked for sending", ARDisplayString(m
, rr
));
3152 rr
->SendRNow
= uDNSInterfaceMark
;
3155 // We parsed through all records and found something to send. The services/records might
3156 // get registered at different times but we want the refreshes to be all merged and sent
3157 // as one update. Hence, we accelerate some of the records so that they will sync up in
3158 // the future. Look at the records excluding the ones that we have already sent in the
3159 // previous pass. If it half way through its scheduled refresh/retransmit, merge them
3160 // into this packet.
3162 // Note that we only look at Registered/Refresh state to keep it simple. As we don't know
3163 // whether the current update will fit into one or more packets, merging a resource record
3164 // (which is in a different state) that has been scheduled for retransmit would trigger
3165 // sending more packets.
3169 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
3171 if ((rr
->state
!= regState_Registered
&& rr
->state
!= regState_Refresh
) ||
3172 (rr
->SendRNow
== uDNSInterfaceMark
) ||
3173 (!AreRecordsMergeable(m
, firstRR
, rr
, m
->timenow
+ rr
->ThisAPInterval
/2)))
3175 rr
->SendRNow
= uDNSInterfaceMark
;
3178 if (acc
) LogInfo("MarkRRForSending: Accelereated %d records", acc
);
3183 mDNSlocal mDNSBool
SendGroupUpdates(mDNS
*const m
)
3186 mDNSs32 spaceleft
= 0;
3187 mDNSs32 zoneSize
, rrSize
;
3188 mDNSu8
*oldnext
; // for debugging
3189 mDNSu8
*next
= m
->omsg
.data
;
3191 AuthRecord
*anchorRR
= mDNSNULL
;
3193 AuthRecord
*startRR
= m
->ResourceRecords
;
3194 mDNSu8
*limit
= mDNSNULL
;
3195 DomainAuthInfo
*AuthInfo
= mDNSNULL
;
3196 mDNSBool sentallRecords
= mDNStrue
;
3199 // We try to fit as many ResourceRecords as possible in AbsoluteNormal/MaxDNSMessageData. Before we start
3200 // putting in resource records, we need to reserve space for a few things. Every group/packet should
3201 // have the following.
3203 // 1) Needs space for the Zone information (which needs to be at the beginning)
3204 // 2) Additional section MUST have space for lease option, HINFO and TSIG option (which needs to
3205 // to be at the end)
3207 // In future we need to reserve space for the pre-requisites which also goes at the beginning.
3208 // To accomodate pre-requisites in the future, first we walk the whole list marking records
3209 // that can be sent in this packet and computing the space needed for these records.
3210 // For TXT and SRV records, we delete the previous record if any by sending the same
3211 // resource record with ANY RDATA and zero rdlen. Hence, we need to have space for both of them.
3215 AuthInfo
= mDNSNULL
;
3216 anchorRR
= mDNSNULL
;
3219 for (rr
= startRR
; rr
; rr
= rr
->next
)
3221 if (rr
->SendRNow
!= uDNSInterfaceMark
) continue;
3223 rr
->SendRNow
= mDNSNULL
;
3227 AuthInfo
= GetAuthInfoForName_internal(m
, rr
->zone
);
3229 // Though we allow single record registrations for UDP to be AbsoluteMaxDNSMessageData (See
3230 // SendRecordRegistration) to handle large TXT records, to avoid fragmentation we limit UDP
3231 // message to NormalMaxDNSMessageData
3232 spaceleft
= NormalMaxDNSMessageData
;
3234 next
= m
->omsg
.data
;
3235 spaceleft
-= RRAdditionalSize(AuthInfo
);
3238 LogMsg("SendGroupUpdates: ERROR!!: spaceleft is zero at the beginning");
3242 limit
= next
+ spaceleft
;
3244 // Build the initial part of message before putting in the other records
3245 msgid
= mDNS_NewMessageID(m
);
3246 InitializeDNSMessage(&m
->omsg
.h
, msgid
, UpdateReqFlags
);
3248 // We need zone information at the beginning of the packet. Length: ZNAME, ZTYPE(2), ZCLASS(2)
3249 // zone has to be non-NULL for a record to be mergeable, hence it is safe to set/ examine zone
3250 //without checking for NULL.
3251 zoneSize
= DomainNameLength(rr
->zone
) + 4;
3252 spaceleft
-= zoneSize
;
3255 LogMsg("SendGroupUpdates: ERROR no space for zone information, disabling merge");
3259 next
= putZone(&m
->omsg
, next
, limit
, rr
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
3262 LogMsg("SendGroupUpdates: ERROR! Cannot put zone, disabling merge");
3269 rrSize
= RREstimatedSize(rr
, zoneSize
- 4);
3271 if ((spaceleft
- rrSize
) < 0)
3273 // If we can't fit even a single message, skip it, it will be sent separately
3274 // in CheckRecordUpdates
3277 LogInfo("SendGroupUpdates: Skipping message %s, spaceleft %d, rrSize %d", ARDisplayString(m
, rr
), spaceleft
, rrSize
);
3278 // Mark this as not sent so that the caller knows about it
3279 rr
->SendRNow
= uDNSInterfaceMark
;
3280 // We need to remove the merge delay so that we can send it immediately
3281 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3282 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3284 anchorRR
= mDNSNULL
;
3285 sentallRecords
= mDNSfalse
;
3289 LogInfo("SendGroupUpdates:1: Parsed %d records and sending using %s, spaceleft %d, rrSize %d", nrecords
, ARDisplayString(m
, anchorRR
), spaceleft
, rrSize
);
3290 SendGroupRRMessage(m
, anchorRR
, next
, AuthInfo
);
3292 break; // breaks out of for loop
3294 spaceleft
-= rrSize
;
3296 LogInfo("SendGroupUpdates: Building a message with resource record %s, next %p, state %d, ttl %d", ARDisplayString(m
, rr
), next
, rr
->state
, rr
->resrec
.rroriginalttl
);
3297 if (!(next
= BuildUpdateMessage(m
, next
, rr
, limit
)))
3299 // We calculated the space and if we can't fit in, we had some bug in the calculation,
3300 // disable merge completely.
3301 LogMsg("SendGroupUpdates: ptr NULL while building message with %s", ARDisplayString(m
, rr
));
3305 // If our estimate was higher, adjust to the actual size
3306 if ((next
- oldnext
) > rrSize
)
3307 LogMsg("SendGroupUpdates: ERROR!! Record size estimation is wrong for %s, Estimate %d, Actual %d, state %d", ARDisplayString(m
, rr
), rrSize
, next
- oldnext
, rr
->state
);
3308 else { spaceleft
+= rrSize
; spaceleft
-= (next
- oldnext
); }
3311 // We could have sent an update earlier with this "rr" as anchorRR for which we never got a response.
3312 // To preserve ordering, we blow away the previous connection before sending this.
3313 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
;}
3314 rr
->updateid
= msgid
;
3316 // By setting the retry time interval here, we will not be looking at these records
3317 // again when we return to CheckGroupRecordUpdates.
3318 SetRecordRetry(m
, rr
, 0);
3320 // Either we have parsed all the records or stopped at "rr" above due to lack of space
3326 LogInfo("SendGroupUpdates: Parsed %d records and sending using %s", nrecords
, ARDisplayString(m
, anchorRR
));
3327 SendGroupRRMessage(m
, anchorRR
, next
, AuthInfo
);
3329 return sentallRecords
;
3332 // Merge the record registrations and send them as a group only if they
3333 // have same DomainAuthInfo and hence the same key to put the TSIG
3334 mDNSlocal
void CheckGroupRecordUpdates(mDNS
*const m
)
3336 AuthRecord
*rr
, *nextRR
;
3337 // Keep sending as long as there is at least one record to be sent
3338 while (MarkRRForSending(m
))
3340 if (!SendGroupUpdates(m
))
3342 // if everything that was marked was not sent, send them out individually
3343 for (rr
= m
->ResourceRecords
; rr
; rr
= nextRR
)
3345 // SendRecordRegistrtion might delete the rr from list, hence
3346 // dereference nextRR before calling the function
3348 if (rr
->SendRNow
== uDNSInterfaceMark
)
3350 // Any records marked for sending should be eligible to be sent out
3351 // immediately. Just being cautious
3352 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- m
->timenow
> 0)
3353 { LogMsg("CheckGroupRecordUpdates: ERROR!! Resourcerecord %s not ready", ARDisplayString(m
, rr
)); continue; }
3354 rr
->SendRNow
= mDNSNULL
;
3355 SendRecordRegistration(m
, rr
);
3361 debugf("CheckGroupRecordUpdates: No work, returning");
3365 mDNSlocal
void hndlSRVChanged(mDNS
*const m
, AuthRecord
*rr
)
3367 // Reevaluate the target always as NAT/Target could have changed while
3368 // we were registering/deeregistering
3370 const domainname
*target
= GetServiceTarget(m
, rr
);
3371 if (!target
|| target
->c
[0] == 0)
3373 // we don't have a target, if we just derregistered, then we don't have to do anything
3374 if (rr
->state
== regState_DeregPending
)
3376 LogInfo("hndlSRVChanged: SRVChanged, No Target, SRV Deregistered for %##s, state %d", rr
->resrec
.name
->c
,
3378 rr
->SRVChanged
= mDNSfalse
;
3379 dt
= GetRRDomainNameTarget(&rr
->resrec
);
3380 if (dt
) dt
->c
[0] = 0;
3381 rr
->state
= regState_NoTarget
; // Wait for the next target change
3382 rr
->resrec
.rdlength
= rr
->resrec
.rdestimate
= 0;
3386 // we don't have a target, if we just registered, we need to deregister
3387 if (rr
->state
== regState_Pending
)
3389 LogInfo("hndlSRVChanged: SRVChanged, No Target, Deregistering again %##s, state %d", rr
->resrec
.name
->c
, rr
->state
);
3390 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3391 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3392 rr
->state
= regState_DeregPending
;
3395 LogInfo("hndlSRVChanged: Not in DeregPending or RegPending state %##s, state %d", rr
->resrec
.name
->c
, rr
->state
);
3399 // If we were in registered state and SRV changed to NULL, we deregister and come back here
3400 // if we have a target, we need to register again.
3402 // if we just registered check to see if it is same. If it is different just re-register the
3403 // SRV and its assoicated records
3405 // UpdateOneSRVRecord takes care of re-registering all service records
3406 if ((rr
->state
== regState_DeregPending
) ||
3407 (rr
->state
== regState_Pending
&& !SameDomainName(target
, &rr
->resrec
.rdata
->u
.srv
.target
)))
3409 dt
= GetRRDomainNameTarget(&rr
->resrec
);
3410 if (dt
) dt
->c
[0] = 0;
3411 rr
->state
= regState_NoTarget
; // NoTarget will allow us to pick up new target OR nat traversal state
3412 rr
->resrec
.rdlength
= rr
->resrec
.rdestimate
= 0;
3413 LogInfo("hndlSRVChanged: SRVChanged, Valid Target %##s, Registering all records for %##s, state %d",
3414 target
->c
, rr
->resrec
.name
->c
, rr
->state
);
3415 rr
->SRVChanged
= mDNSfalse
;
3416 UpdateOneSRVRecord(m
, rr
);
3419 // Target did not change while this record was registering. Hence, we go to
3420 // Registered state - the state we started from.
3421 if (rr
->state
== regState_Pending
) rr
->state
= regState_Registered
;
3424 rr
->SRVChanged
= mDNSfalse
;
3427 // Called with lock held
3428 mDNSlocal
void hndlRecordUpdateReply(mDNS
*m
, AuthRecord
*rr
, mStatus err
, mDNSu32 random
)
3430 mDNSBool InvokeCallback
= mDNStrue
;
3431 mDNSIPPort UpdatePort
= zeroIPPort
;
3435 LogInfo("hndlRecordUpdateReply: err %d ID %d state %d %s(%p)", err
, mDNSVal16(rr
->updateid
), rr
->state
, ARDisplayString(m
, rr
), rr
);
3437 rr
->updateError
= err
;
3439 SetRecordRetry(m
, rr
, random
);
3441 rr
->updateid
= zeroID
; // Make sure that this is not considered as part of a group anymore
3442 // Later when need to send an update, we will get the zone data again. Thus we avoid
3443 // using stale information.
3445 // Note: By clearing out the zone info here, it also helps better merging of records
3446 // in some cases. For example, when we get out regState_NoTarget state e.g., move out
3447 // of Double NAT, we want all the records to be in one update. Some BTMM records like
3448 // _autotunnel6 and host records are registered/deregistered when NAT state changes.
3449 // As they are re-registered the zone information is cleared out. To merge with other
3450 // records that might be possibly going out, clearing out the information here helps
3451 // as all of them try to get the zone data.
3454 // We always expect the question to be stopped when we get a valid response from the server.
3455 // If the zone info tries to change during this time, updateid would be different and hence
3456 // this response should not have been accepted.
3457 if (rr
->nta
->question
.ThisQInterval
!= -1)
3458 LogMsg("hndlRecordUpdateReply: ResourceRecord %s, zone info question %##s (%s) interval %d not -1",
3459 ARDisplayString(m
, rr
), rr
->nta
->question
.qname
.c
, DNSTypeName(rr
->nta
->question
.qtype
), rr
->nta
->question
.ThisQInterval
);
3460 UpdatePort
= rr
->nta
->Port
;
3461 CancelGetZoneData(m
, rr
->nta
);
3465 // If we are deregistering the record, then complete the deregistration. Ignore any NAT/SRV change
3466 // that could have happened during that time.
3467 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->state
== regState_DeregPending
)
3469 debugf("hndlRecordUpdateReply: Received reply for deregister record %##s type %d", rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
3470 if (err
) LogMsg("ERROR: Deregistration of record %##s type %d failed with error %d",
3471 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, err
);
3472 rr
->state
= regState_Unregistered
;
3473 CompleteDeregistration(m
, rr
);
3477 // We are returning early without updating the state. When we come back from sleep we will re-register after
3478 // re-initializing all the state as though it is a first registration. If the record can't be registered e.g.,
3479 // no target, it will be deregistered. Hence, the updating to the right state should not matter when going
3483 // Need to set it to NoTarget state so that RecordReadyForSleep knows that
3485 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& rr
->state
== regState_DeregPending
)
3486 rr
->state
= regState_NoTarget
;
3490 if (rr
->state
== regState_UpdatePending
)
3492 if (err
) LogMsg("Update record failed for %##s (err %d)", rr
->resrec
.name
->c
, err
);
3493 rr
->state
= regState_Registered
;
3494 // deallocate old RData
3495 if (rr
->UpdateCallback
) rr
->UpdateCallback(m
, rr
, rr
->OrigRData
, rr
->OrigRDLen
);
3496 SetNewRData(&rr
->resrec
, rr
->InFlightRData
, rr
->InFlightRDLen
);
3497 rr
->OrigRData
= mDNSNULL
;
3498 rr
->InFlightRData
= mDNSNULL
;
3503 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
3504 hndlSRVChanged(m
, rr
);
3507 LogInfo("hndlRecordUpdateReply: Deregistered %##s (%s), state %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->state
);
3508 rr
->SRVChanged
= mDNSfalse
;
3509 if (rr
->state
!= regState_DeregPending
) LogMsg("hndlRecordUpdateReply: ResourceRecord %s not in DeregPending state %d", ARDisplayString(m
, rr
), rr
->state
);
3510 rr
->state
= regState_NoTarget
; // Wait for the next target change
3515 if (rr
->state
== regState_Pending
|| rr
->state
== regState_Refresh
)
3519 if (rr
->state
== regState_Refresh
) InvokeCallback
= mDNSfalse
;
3520 rr
->state
= regState_Registered
;
3524 // Retry without lease only for non-Private domains
3525 LogMsg("hndlRecordUpdateReply: Registration of record %##s type %d failed with error %d", rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, err
);
3526 if (!rr
->Private
&& rr
->uselease
&& err
== mStatus_UnknownErr
&& mDNSSameIPPort(UpdatePort
, UnicastDNSPort
))
3528 LogMsg("hndlRecordUpdateReply: Will retry update of record %##s without lease option", rr
->resrec
.name
->c
);
3529 rr
->uselease
= mDNSfalse
;
3530 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3531 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3532 SetNextuDNSEvent(m
, rr
);
3535 // Communicate the error to the application in the callback below
3539 if (rr
->QueuedRData
&& rr
->state
== regState_Registered
)
3541 rr
->state
= regState_UpdatePending
;
3542 rr
->InFlightRData
= rr
->QueuedRData
;
3543 rr
->InFlightRDLen
= rr
->QueuedRDLen
;
3544 rr
->OrigRData
= rr
->resrec
.rdata
;
3545 rr
->OrigRDLen
= rr
->resrec
.rdlength
;
3546 rr
->QueuedRData
= mDNSNULL
;
3547 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
3548 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
3549 SetNextuDNSEvent(m
, rr
);
3553 // Don't invoke the callback on error as this may not be useful to the client.
3554 // The client may potentially delete the resource record on error which we normally
3555 // delete during deregistration
3556 if (!err
&& InvokeCallback
&& rr
->RecordCallback
)
3558 LogInfo("hndlRecordUpdateReply: Calling record callback on %##s", rr
->resrec
.name
->c
);
3559 mDNS_DropLockBeforeCallback();
3560 rr
->RecordCallback(m
, rr
, err
);
3561 mDNS_ReclaimLockAfterCallback();
3563 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
3564 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
3567 mDNSlocal
void uDNS_ReceiveNATPMPPacket(mDNS
*m
, const mDNSInterfaceID InterfaceID
, mDNSu8
*pkt
, mDNSu16 len
)
3569 NATTraversalInfo
*ptr
;
3570 NATAddrReply
*AddrReply
= (NATAddrReply
*)pkt
;
3571 NATPortMapReply
*PortMapReply
= (NATPortMapReply
*)pkt
;
3572 mDNSu32 nat_elapsed
, our_elapsed
;
3574 // Minimum NAT-PMP packet is vers (1) opcode (1) + err (2) = 4 bytes
3575 if (len
< 4) { LogMsg("NAT-PMP message too short (%d bytes)", len
); return; }
3577 // Read multi-byte error value (field is identical in a NATPortMapReply)
3578 AddrReply
->err
= (mDNSu16
) ((mDNSu16
)pkt
[2] << 8 | pkt
[3]);
3580 if (AddrReply
->err
== NATErr_Vers
)
3582 NATTraversalInfo
*n
;
3583 LogInfo("NAT-PMP version unsupported message received");
3584 for (n
= m
->NATTraversals
; n
; n
=n
->next
)
3586 // Send a NAT-PMP request for this operation as needed
3587 // and update the state variables
3588 uDNS_SendNATMsg(m
, n
, mDNSfalse
, mDNSfalse
);
3591 m
->NextScheduledNATOp
= m
->timenow
;
3596 // The minimum reasonable NAT-PMP packet length is vers (1) + opcode (1) + err (2) + upseconds (4) = 8 bytes
3597 // If it's not at least this long, bail before we byte-swap the upseconds field & overrun our buffer.
3598 // The retry timer will ensure we converge to correctness.
3601 LogMsg("NAT-PMP message too short (%d bytes) 0x%X 0x%X", len
, AddrReply
->opcode
, AddrReply
->err
);
3605 // Read multi-byte upseconds value (field is identical in a NATPortMapReply)
3606 AddrReply
->upseconds
= (mDNSs32
) ((mDNSs32
)pkt
[4] << 24 | (mDNSs32
)pkt
[5] << 16 | (mDNSs32
)pkt
[6] << 8 | pkt
[7]);
3608 nat_elapsed
= AddrReply
->upseconds
- m
->LastNATupseconds
;
3609 our_elapsed
= (m
->timenow
- m
->LastNATReplyLocalTime
) / mDNSPlatformOneSecond
;
3610 debugf("uDNS_ReceiveNATPMPPacket %X upseconds %u nat_elapsed %d our_elapsed %d", AddrReply
->opcode
, AddrReply
->upseconds
, nat_elapsed
, our_elapsed
);
3612 // We compute a conservative estimate of how much the NAT gateways's clock should have advanced
3613 // 1. We subtract 12.5% from our own measured elapsed time, to allow for NAT gateways that have an inacurate clock that runs slowly
3614 // 2. We add a two-second safety margin to allow for rounding errors: e.g.
3615 // -- if NAT gateway sends a packet at t=2.000 seconds, then one at t=7.999, that's approximately 6 real seconds,
3616 // but based on the values in the packet (2,7) the apparent difference according to the packet is only 5 seconds
3617 // -- if we're slow handling packets and/or we have coarse clock granularity,
3618 // we could receive the t=2 packet at our t=1.999 seconds, which we round down to 1
3619 // and the t=7.999 packet at our t=8.000 seconds, which we record as 8,
3620 // giving an apparent local time difference of 7 seconds
3621 // The two-second safety margin coves this possible calculation discrepancy
3622 if (AddrReply
->upseconds
< m
->LastNATupseconds
|| nat_elapsed
+ 2 < our_elapsed
- our_elapsed
/8)
3623 { LogMsg("NAT-PMP epoch time check failed: assuming NAT gateway %#a rebooted", &m
->Router
); RecreateNATMappings(m
, 0); }
3625 m
->LastNATupseconds
= AddrReply
->upseconds
;
3626 m
->LastNATReplyLocalTime
= m
->timenow
;
3627 #ifdef _LEGACY_NAT_TRAVERSAL_
3629 #endif // _LEGACY_NAT_TRAVERSAL_
3631 if (AddrReply
->opcode
== NATOp_AddrResponse
)
3633 #if APPLE_OSX_mDNSResponder
3634 LogInfo("uDNS_ReceiveNATPMPPacket: AddressRequest %s error %d", AddrReply
->err
? "failure" : "success", AddrReply
->err
);
3636 if (!AddrReply
->err
&& len
< sizeof(NATAddrReply
)) { LogMsg("NAT-PMP AddrResponse message too short (%d bytes)", len
); return; }
3637 natTraversalHandleAddressReply(m
, AddrReply
->err
, AddrReply
->ExtAddr
);
3639 else if (AddrReply
->opcode
== NATOp_MapUDPResponse
|| AddrReply
->opcode
== NATOp_MapTCPResponse
)
3641 mDNSu8 Protocol
= AddrReply
->opcode
& 0x7F;
3642 #if APPLE_OSX_mDNSResponder
3643 LogInfo("uDNS_ReceiveNATPMPPacket: PortMapRequest %s %s - error %d",
3644 PortMapReply
->err
? "failure" : "success", (AddrReply
->opcode
== NATOp_MapUDPResponse
) ? "UDP" : "TCP", PortMapReply
->err
);
3646 if (!PortMapReply
->err
)
3648 if (len
< sizeof(NATPortMapReply
)) { LogMsg("NAT-PMP PortMapReply message too short (%d bytes)", len
); return; }
3649 PortMapReply
->NATRep_lease
= (mDNSu32
) ((mDNSu32
)pkt
[12] << 24 | (mDNSu32
)pkt
[13] << 16 | (mDNSu32
)pkt
[14] << 8 | pkt
[15]);
3652 // Since some NAT-PMP server implementations don't return the requested internal port in
3653 // the reply, we can't associate this reply with a particular NATTraversalInfo structure.
3654 // We globally keep track of the most recent error code for mappings.
3655 m
->LastNATMapResultCode
= PortMapReply
->err
;
3657 for (ptr
= m
->NATTraversals
; ptr
; ptr
=ptr
->next
)
3658 if (ptr
->Protocol
== Protocol
&& mDNSSameIPPort(ptr
->IntPort
, PortMapReply
->intport
))
3659 natTraversalHandlePortMapReply(m
, ptr
, InterfaceID
, PortMapReply
->err
, PortMapReply
->extport
, PortMapReply
->NATRep_lease
, NATTProtocolNATPMP
);
3661 else { LogMsg("Received NAT-PMP response with unknown opcode 0x%X", AddrReply
->opcode
); return; }
3663 // Don't need an SSDP socket if we get a NAT-PMP packet
3664 if (m
->SSDPSocket
) { debugf("uDNS_ReceiveNATPMPPacket destroying SSDPSocket %p", &m
->SSDPSocket
); mDNSPlatformUDPClose(m
->SSDPSocket
); m
->SSDPSocket
= mDNSNULL
; }
3667 mDNSlocal
void uDNS_ReceivePCPPacket(mDNS
*m
, const mDNSInterfaceID InterfaceID
, mDNSu8
*pkt
, mDNSu16 len
)
3669 NATTraversalInfo
*ptr
;
3670 PCPMapReply
*reply
= (PCPMapReply
*)pkt
;
3671 mDNSu32 client_delta
, server_delta
;
3672 mDNSBool checkEpochValidity
= m
->LastNATupseconds
!= 0;
3673 mDNSu8 strippedOpCode
;
3674 mDNSv4Addr mappedAddress
= zerov4Addr
;
3675 mDNSu8 protocol
= 0;
3676 mDNSIPPort intport
= zeroIPPort
;
3677 mDNSIPPort extport
= zeroIPPort
;
3679 // Minimum PCP packet is 24 bytes
3682 LogMsg("uDNS_ReceivePCPPacket: message too short (%d bytes)", len
);
3686 strippedOpCode
= reply
->opCode
& 0x7f;
3688 if ((reply
->opCode
& 0x80) == 0x00 || (strippedOpCode
!= PCPOp_Announce
&& strippedOpCode
!= PCPOp_Map
))
3690 LogMsg("uDNS_ReceivePCPPacket: unhandled opCode %u", reply
->opCode
);
3694 // Read multi-byte values
3695 reply
->lifetime
= (mDNSs32
)((mDNSs32
)pkt
[4] << 24 | (mDNSs32
)pkt
[5] << 16 | (mDNSs32
)pkt
[ 6] << 8 | pkt
[ 7]);
3696 reply
->epoch
= (mDNSs32
)((mDNSs32
)pkt
[8] << 24 | (mDNSs32
)pkt
[9] << 16 | (mDNSs32
)pkt
[10] << 8 | pkt
[11]);
3698 client_delta
= (m
->timenow
- m
->LastNATReplyLocalTime
) / mDNSPlatformOneSecond
;
3699 server_delta
= reply
->epoch
- m
->LastNATupseconds
;
3700 debugf("uDNS_ReceivePCPPacket: %X %X upseconds %u client_delta %d server_delta %d", reply
->opCode
, reply
->result
, reply
->epoch
, client_delta
, server_delta
);
3702 // If seconds since the epoch is 0, use 1 so we'll check epoch validity next time
3703 m
->LastNATupseconds
= reply
->epoch
? reply
->epoch
: 1;
3704 m
->LastNATReplyLocalTime
= m
->timenow
;
3706 #ifdef _LEGACY_NAT_TRAVERSAL_
3708 #endif // _LEGACY_NAT_TRAVERSAL_
3710 // Don't need an SSDP socket if we get a PCP packet
3711 if (m
->SSDPSocket
) { debugf("uDNS_ReceivePCPPacket: destroying SSDPSocket %p", &m
->SSDPSocket
); mDNSPlatformUDPClose(m
->SSDPSocket
); m
->SSDPSocket
= mDNSNULL
; }
3713 if (checkEpochValidity
&& (client_delta
+ 2 < server_delta
- server_delta
/ 16 || server_delta
+ 2 < client_delta
- client_delta
/ 16))
3715 // If this is an ANNOUNCE packet, wait a random interval up to 5 seconds
3716 // otherwise, refresh immediately
3717 mDNSu32 waitTicks
= strippedOpCode
? 0 : mDNSRandom(PCP_WAITSECS_AFTER_EPOCH_INVALID
* mDNSPlatformOneSecond
);
3718 LogMsg("uDNS_ReceivePCPPacket: Epoch invalid, %#a likely rebooted, waiting %u ticks", &m
->Router
, waitTicks
);
3719 RecreateNATMappings(m
, waitTicks
);
3720 // we can ignore the rest of this packet, as new requests are about to go out
3724 if (strippedOpCode
== PCPOp_Announce
)
3727 // We globally keep track of the most recent error code for mappings.
3728 // This seems bad to do with PCP, but best not change it now.
3729 m
->LastNATMapResultCode
= reply
->result
;
3733 if (len
< sizeof(PCPMapReply
))
3735 LogMsg("uDNS_ReceivePCPPacket: mapping response too short (%d bytes)", len
);
3740 if (reply
->nonce
[0] != m
->PCPNonce
[0] || reply
->nonce
[1] != m
->PCPNonce
[1] || reply
->nonce
[2] != m
->PCPNonce
[2])
3742 LogMsg("uDNS_ReceivePCPPacket: invalid nonce, ignoring. received { %x %x %x } expected { %x %x %x }",
3743 reply
->nonce
[0], reply
->nonce
[1], reply
->nonce
[2],
3744 m
->PCPNonce
[0], m
->PCPNonce
[1], m
->PCPNonce
[2]);
3749 protocol
= reply
->protocol
;
3750 intport
= reply
->intPort
;
3751 extport
= reply
->extPort
;
3753 // Get the external address, which should be mapped, since we only support IPv4
3754 if (!mDNSAddrIPv4FromMappedIPv6(&reply
->extAddress
, &mappedAddress
))
3756 LogMsg("uDNS_ReceivePCPPacket: unexpected external address: %.16a", &reply
->extAddress
);
3757 reply
->result
= NATErr_NetFail
;
3758 // fall through to report the error
3760 else if (mDNSIPv4AddressIsZero(mappedAddress
))
3762 // If this is the deletion case, we will have sent the zero IPv4-mapped address
3763 // in our request, and the server should reflect it in the response, so we
3764 // should not log about receiving a zero address. And in this case, we no
3765 // longer have a NATTraversal to report errors back to, so it's ok to set the
3767 // In other cases, a zero address is an error, and we will have a NATTraversal
3768 // to report back to, so set an error and fall through to report it.
3769 // CheckNATMappings will log the error.
3770 reply
->result
= NATErr_NetFail
;
3775 LogInfo("uDNS_ReceivePCPPacket: error received from server. opcode %X result %X lifetime %X epoch %X",
3776 reply
->opCode
, reply
->result
, reply
->lifetime
, reply
->epoch
);
3778 // If the packet is long enough, get the protocol & intport for matching to report
3780 if (len
>= sizeof(PCPMapReply
))
3782 protocol
= reply
->protocol
;
3783 intport
= reply
->intPort
;
3787 for (ptr
= m
->NATTraversals
; ptr
; ptr
=ptr
->next
)
3789 mDNSu8 ptrProtocol
= ((ptr
->Protocol
& NATOp_MapTCP
) == NATOp_MapTCP
? PCPProto_TCP
: PCPProto_UDP
);
3790 if ((protocol
== ptrProtocol
&& mDNSSameIPPort(ptr
->IntPort
, intport
)) ||
3791 (!ptr
->Protocol
&& protocol
== PCPProto_TCP
&& mDNSSameIPPort(DiscardPort
, intport
)))
3793 natTraversalHandlePortMapReplyWithAddress(m
, ptr
, InterfaceID
, reply
->result
? NATErr_NetFail
: NATErr_None
, mappedAddress
, extport
, reply
->lifetime
, NATTProtocolPCP
);
3798 mDNSexport
void uDNS_ReceiveNATPacket(mDNS
*m
, const mDNSInterfaceID InterfaceID
, mDNSu8
*pkt
, mDNSu16 len
)
3801 LogMsg("uDNS_ReceiveNATPacket: zero length packet");
3802 else if (pkt
[0] == PCP_VERS
)
3803 uDNS_ReceivePCPPacket(m
, InterfaceID
, pkt
, len
);
3804 else if (pkt
[0] == NATMAP_VERS
)
3805 uDNS_ReceiveNATPMPPacket(m
, InterfaceID
, pkt
, len
);
3807 LogMsg("uDNS_ReceiveNATPacket: packet with version %u (expected %u or %u)", pkt
[0], PCP_VERS
, NATMAP_VERS
);
3810 // Called from mDNSCoreReceive with the lock held
3811 mDNSexport
void uDNS_ReceiveMsg(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
, const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
)
3814 mStatus err
= mStatus_NoError
;
3816 mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
3817 mDNSu8 UpdateR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
3818 mDNSu8 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
3819 mDNSu8 rcode
= (mDNSu8
)(msg
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
3821 (void)srcport
; // Unused
3823 debugf("uDNS_ReceiveMsg from %#-15a with "
3824 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
3826 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
3827 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
3828 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
3829 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? "" : "s", end
- msg
->data
);
3830 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
3831 if (NumUnreachableDNSServers
> 0)
3832 SymptomReporterDNSServerReachable(m
, srcaddr
);
3837 //if (srcaddr && recvLLQResponse(m, msg, end, srcaddr, srcport)) return;
3838 for (qptr
= m
->Questions
; qptr
; qptr
= qptr
->next
)
3839 if (msg
->h
.flags
.b
[0] & kDNSFlag0_TC
&& mDNSSameOpaque16(qptr
->TargetQID
, msg
->h
.id
) && m
->timenow
- qptr
->LastQTime
< RESPONSE_WINDOW
)
3841 if (!srcaddr
) LogMsg("uDNS_ReceiveMsg: TCP DNS response had TC bit set: ignoring");
3844 uDNS_RestartQuestionAsTCP(m
, qptr
, srcaddr
, srcport
);
3845 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
3846 qptr
->metrics
.dnsOverTCPState
= DNSOverTCP_Truncated
;
3852 if (QR_OP
== UpdateR
)
3854 mDNSu32 pktlease
= 0;
3855 mDNSBool gotlease
= GetPktLease(m
, msg
, end
, &pktlease
);
3856 mDNSu32 lease
= gotlease
? pktlease
: 60 * 60; // If lease option missing, assume one hour
3857 mDNSs32 expire
= m
->timenow
+ (mDNSs32
)lease
* mDNSPlatformOneSecond
;
3858 mDNSu32 random
= mDNSRandom((mDNSs32
)lease
* mDNSPlatformOneSecond
/10);
3860 //rcode = kDNSFlag1_RC_ServFail; // Simulate server failure (rcode 2)
3862 // Walk through all the records that matches the messageID. There could be multiple
3863 // records if we had sent them in a group
3864 if (m
->CurrentRecord
)
3865 LogMsg("uDNS_ReceiveMsg ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3866 m
->CurrentRecord
= m
->ResourceRecords
;
3867 while (m
->CurrentRecord
)
3869 AuthRecord
*rptr
= m
->CurrentRecord
;
3870 m
->CurrentRecord
= m
->CurrentRecord
->next
;
3871 if (AuthRecord_uDNS(rptr
) && mDNSSameOpaque16(rptr
->updateid
, msg
->h
.id
))
3873 err
= checkUpdateResult(m
, rptr
->resrec
.name
, rcode
, msg
, end
);
3874 if (!err
&& rptr
->uselease
&& lease
)
3875 if (rptr
->expire
- expire
>= 0 || rptr
->state
!= regState_UpdatePending
)
3877 rptr
->expire
= expire
;
3878 rptr
->refreshCount
= 0;
3880 // We pass the random value to make sure that if we update multiple
3881 // records, they all get the same random value
3882 hndlRecordUpdateReply(m
, rptr
, err
, random
);
3886 debugf("Received unexpected response: ID %d matches no active records", mDNSVal16(msg
->h
.id
));
3889 // ***************************************************************************
3890 #if COMPILER_LIKES_PRAGMA_MARK
3891 #pragma mark - Query Routines
3894 mDNSexport
void sendLLQRefresh(mDNS
*m
, DNSQuestion
*q
)
3900 if ((q
->state
== LLQ_Established
&& q
->ntries
>= kLLQ_MAX_TRIES
) || q
->expire
- m
->timenow
< 0)
3902 LogMsg("Unable to refresh LLQ %##s (%s) - will retry in %d seconds", q
->qname
.c
, DNSTypeName(q
->qtype
), LLQ_POLL_INTERVAL
/ mDNSPlatformOneSecond
);
3903 StartLLQPolling(m
,q
);
3907 llq
.vers
= kLLQ_Vers
;
3908 llq
.llqOp
= kLLQOp_Refresh
;
3909 llq
.err
= q
->tcp
? GetLLQEventPort(m
, &q
->servAddr
) : LLQErr_NoError
; // If using TCP tell server what UDP port to send notifications to
3911 llq
.llqlease
= q
->ReqLease
;
3913 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, uQueryFlags
);
3914 end
= putLLQ(&m
->omsg
, m
->omsg
.data
, q
, &llq
);
3915 if (!end
) { LogMsg("sendLLQRefresh: putLLQ failed %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
)); return; }
3920 LogInfo("sendLLQRefresh: using existing UDP session %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3922 err
= mDNSSendDNSMessage(m
, &m
->omsg
, end
, mDNSInterface_Any
, q
->tcp
? q
->tcp
->sock
: mDNSNULL
, q
->LocalSocket
, &q
->servAddr
, q
->servPort
, mDNSNULL
, mDNSfalse
);
3925 LogMsg("sendLLQRefresh: mDNSSendDNSMessage%s failed: %d", q
->tcp
? " (TCP)" : "", err
);
3926 if (q
->tcp
) { DisposeTCPConn(q
->tcp
); q
->tcp
= mDNSNULL
; }
3932 debugf("sendLLQRefresh ntries %d %##s (%s)", q
->ntries
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3934 q
->LastQTime
= m
->timenow
;
3935 SetNextQueryTime(m
, q
);
3938 mDNSexport
void LLQGotZoneData(mDNS
*const m
, mStatus err
, const ZoneData
*zoneInfo
)
3940 DNSQuestion
*q
= (DNSQuestion
*)zoneInfo
->ZoneDataContext
;
3944 // If we get here it means that the GetZoneData operation has completed.
3945 // We hold on to the zone data if it is AutoTunnel as we use the hostname
3946 // in zoneInfo during the TLS connection setup.
3947 q
->servAddr
= zeroAddr
;
3948 q
->servPort
= zeroIPPort
;
3950 if (!err
&& !mDNSIPPortIsZero(zoneInfo
->Port
) && !mDNSAddressIsZero(&zoneInfo
->Addr
) && zoneInfo
->Host
.c
[0])
3952 q
->servAddr
= zoneInfo
->Addr
;
3953 q
->servPort
= zoneInfo
->Port
;
3954 // We don't need the zone data as we use it only for the Host information which we
3955 // don't need if we are not going to use TLS connections.
3958 if (q
->nta
!= zoneInfo
) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p) %##s (%s)", q
->nta
, zoneInfo
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3959 CancelGetZoneData(m
, q
->nta
);
3963 debugf("LLQGotZoneData %#a:%d", &q
->servAddr
, mDNSVal16(q
->servPort
));
3964 startLLQHandshake(m
, q
);
3970 if (q
->nta
!= zoneInfo
) LogMsg("LLQGotZoneData: nta (%p) != zoneInfo (%p) %##s (%s)", q
->nta
, zoneInfo
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3971 CancelGetZoneData(m
, q
->nta
);
3974 StartLLQPolling(m
,q
);
3975 if (err
== mStatus_NoSuchNameErr
)
3977 // this actually failed, so mark it by setting address to all ones
3978 q
->servAddr
.type
= mDNSAddrType_IPv4
;
3979 q
->servAddr
.ip
.v4
= onesIPv4Addr
;
3986 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
3987 mDNSexport
void DNSPushNotificationGotZoneData(mDNS
*const m
, mStatus err
, const ZoneData
*zoneInfo
)
3989 DNSQuestion
*q
= (DNSQuestion
*)zoneInfo
->ZoneDataContext
;
3992 // If we get here it means that the GetZoneData operation has completed.
3993 q
->servAddr
= zeroAddr
;
3994 q
->servPort
= zeroIPPort
;
3995 if (!err
&& zoneInfo
&& !mDNSIPPortIsZero(zoneInfo
->Port
) && zoneInfo
->Host
.c
[0])
3997 q
->state
= LLQ_DNSPush_Connecting
;
3998 LogInfo("DNSPushNotificationGotZoneData %##s%%%d", &zoneInfo
->Host
, ntohs(zoneInfo
->Port
.NotAnInteger
));
3999 q
->dnsPushServer
= SubscribeToDNSPushNotificationServer(m
, q
);
4000 if (q
->dnsPushServer
== mDNSNULL
|| (q
->dnsPushServer
->connectState
!= DNSPushServerConnectionInProgress
&&
4001 q
->dnsPushServer
->connectState
!= DNSPushServerConnected
&&
4002 q
->dnsPushServer
->connectState
!= DNSPushServerSessionEstablished
))
4010 q
->state
= LLQ_InitialRequest
;
4011 startLLQHandshake(m
,q
);
4017 // ***************************************************************************
4018 #if COMPILER_LIKES_PRAGMA_MARK
4019 #pragma mark - Dynamic Updates
4022 // Called in normal callback context (i.e. mDNS_busy and mDNS_reentrancy are both 1)
4023 mDNSexport
void RecordRegistrationGotZoneData(mDNS
*const m
, mStatus err
, const ZoneData
*zoneData
)
4029 if (!zoneData
) { LogMsg("ERROR: RecordRegistrationGotZoneData invoked with NULL result and no error"); return; }
4031 newRR
= (AuthRecord
*)zoneData
->ZoneDataContext
;
4033 if (newRR
->nta
!= zoneData
)
4034 LogMsg("RecordRegistrationGotZoneData: nta (%p) != zoneData (%p) %##s (%s)", newRR
->nta
, zoneData
, newRR
->resrec
.name
->c
, DNSTypeName(newRR
->resrec
.rrtype
));
4036 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
4037 LogMsg("RecordRegistrationGotZoneData: mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4039 // make sure record is still in list (!!!)
4040 for (ptr
= m
->ResourceRecords
; ptr
; ptr
= ptr
->next
) if (ptr
== newRR
) break;
4043 LogMsg("RecordRegistrationGotZoneData - RR no longer in list. Discarding.");
4044 CancelGetZoneData(m
, newRR
->nta
);
4045 newRR
->nta
= mDNSNULL
;
4049 // check error/result
4052 if (err
!= mStatus_NoSuchNameErr
) LogMsg("RecordRegistrationGotZoneData: error %d", err
);
4053 CancelGetZoneData(m
, newRR
->nta
);
4054 newRR
->nta
= mDNSNULL
;
4058 if (newRR
->resrec
.rrclass
!= zoneData
->ZoneClass
)
4060 LogMsg("ERROR: New resource record's class (%d) does not match zone class (%d)", newRR
->resrec
.rrclass
, zoneData
->ZoneClass
);
4061 CancelGetZoneData(m
, newRR
->nta
);
4062 newRR
->nta
= mDNSNULL
;
4066 // Don't try to do updates to the root name server.
4067 // We might be tempted also to block updates to any single-label name server (e.g. com, edu, net, etc.) but some
4068 // organizations use their own private pseudo-TLD, like ".home", etc, and we don't want to block that.
4069 if (zoneData
->ZoneName
.c
[0] == 0)
4071 LogInfo("RecordRegistrationGotZoneData: No name server found claiming responsibility for \"%##s\"!", newRR
->resrec
.name
->c
);
4072 CancelGetZoneData(m
, newRR
->nta
);
4073 newRR
->nta
= mDNSNULL
;
4077 // Store discovered zone data
4078 c1
= CountLabels(newRR
->resrec
.name
);
4079 c2
= CountLabels(&zoneData
->ZoneName
);
4082 LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" is longer than \"%##s\"", zoneData
->ZoneName
.c
, newRR
->resrec
.name
->c
);
4083 CancelGetZoneData(m
, newRR
->nta
);
4084 newRR
->nta
= mDNSNULL
;
4087 newRR
->zone
= SkipLeadingLabels(newRR
->resrec
.name
, c1
-c2
);
4088 if (!SameDomainName(newRR
->zone
, &zoneData
->ZoneName
))
4090 LogMsg("RecordRegistrationGotZoneData: Zone \"%##s\" does not match \"%##s\" for \"%##s\"", newRR
->zone
->c
, zoneData
->ZoneName
.c
, newRR
->resrec
.name
->c
);
4091 CancelGetZoneData(m
, newRR
->nta
);
4092 newRR
->nta
= mDNSNULL
;
4096 if (mDNSIPPortIsZero(zoneData
->Port
) || mDNSAddressIsZero(&zoneData
->Addr
) || !zoneData
->Host
.c
[0])
4098 LogInfo("RecordRegistrationGotZoneData: No _dns-update._udp service found for \"%##s\"!", newRR
->resrec
.name
->c
);
4099 CancelGetZoneData(m
, newRR
->nta
);
4100 newRR
->nta
= mDNSNULL
;
4104 newRR
->Private
= zoneData
->ZonePrivate
;
4105 debugf("RecordRegistrationGotZoneData: Set zone information for %##s %##s to %#a:%d",
4106 newRR
->resrec
.name
->c
, zoneData
->ZoneName
.c
, &zoneData
->Addr
, mDNSVal16(zoneData
->Port
));
4108 // If we are deregistering, uDNS_DeregisterRecord will do that as it has the zone data now.
4109 if (newRR
->state
== regState_DeregPending
)
4112 uDNS_DeregisterRecord(m
, newRR
);
4117 if (newRR
->resrec
.rrtype
== kDNSType_SRV
)
4119 const domainname
*target
;
4120 // Reevaluate the target always as NAT/Target could have changed while
4121 // we were fetching zone data.
4123 target
= GetServiceTarget(m
, newRR
);
4125 if (!target
|| target
->c
[0] == 0)
4127 domainname
*t
= GetRRDomainNameTarget(&newRR
->resrec
);
4128 LogInfo("RecordRegistrationGotZoneData - no target for %##s", newRR
->resrec
.name
->c
);
4130 newRR
->resrec
.rdlength
= newRR
->resrec
.rdestimate
= 0;
4131 newRR
->state
= regState_NoTarget
;
4132 CancelGetZoneData(m
, newRR
->nta
);
4133 newRR
->nta
= mDNSNULL
;
4137 // If we have non-zero service port (always?)
4138 // and a private address, and update server is non-private
4139 // and this service is AutoTarget
4140 // then initiate a NAT mapping request. On completion it will do SendRecordRegistration() for us
4141 if (newRR
->resrec
.rrtype
== kDNSType_SRV
&& !mDNSIPPortIsZero(newRR
->resrec
.rdata
->u
.srv
.port
) &&
4142 mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
) && newRR
->nta
&& !mDNSAddrIsRFC1918(&newRR
->nta
->Addr
) &&
4143 newRR
->AutoTarget
== Target_AutoHostAndNATMAP
)
4145 // During network transitions, we are called multiple times in different states. Setup NAT
4146 // state just once for this record.
4147 if (!newRR
->NATinfo
.clientContext
)
4149 LogInfo("RecordRegistrationGotZoneData StartRecordNatMap %s", ARDisplayString(m
, newRR
));
4150 newRR
->state
= regState_NATMap
;
4151 StartRecordNatMap(m
, newRR
);
4154 else LogInfo("RecordRegistrationGotZoneData: StartRecordNatMap for %s, state %d, context %p", ARDisplayString(m
, newRR
), newRR
->state
, newRR
->NATinfo
.clientContext
);
4157 // We want IsRecordMergeable to check whether it is a record whose update can be
4158 // sent with others. We set the time before we call IsRecordMergeable, so that
4159 // it does not fail this record based on time. We are interested in other checks
4160 // at this time. If a previous update resulted in error, then don't reset the
4161 // interval. Preserve the back-off so that we don't keep retrying aggressively.
4162 if (newRR
->updateError
== mStatus_NoError
)
4164 newRR
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
4165 newRR
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
4167 if (IsRecordMergeable(m
, newRR
, m
->timenow
+ MERGE_DELAY_TIME
))
4169 // Delay the record registration by MERGE_DELAY_TIME so that we can merge them
4171 LogInfo("RecordRegistrationGotZoneData: Delayed registration for %s", ARDisplayString(m
, newRR
));
4172 newRR
->LastAPTime
+= MERGE_DELAY_TIME
;
4177 mDNSlocal
void SendRecordDeregistration(mDNS
*m
, AuthRecord
*rr
)
4179 mDNSu8
*ptr
= m
->omsg
.data
;
4181 DomainAuthInfo
*AuthInfo
;
4185 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
4187 LogMsg("SendRecordDeRegistration: No zone info for Resource record %s RecordType %d", ARDisplayString(m
, rr
), rr
->resrec
.RecordType
);
4191 limit
= ptr
+ AbsoluteMaxDNSMessageData
;
4192 AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
4193 limit
-= RRAdditionalSize(AuthInfo
);
4195 rr
->updateid
= mDNS_NewMessageID(m
);
4196 InitializeDNSMessage(&m
->omsg
.h
, rr
->updateid
, UpdateReqFlags
);
4199 ptr
= putZone(&m
->omsg
, ptr
, limit
, rr
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
4200 if (!ptr
) goto exit
;
4202 ptr
= BuildUpdateMessage(m
, ptr
, rr
, limit
);
4204 if (!ptr
) goto exit
;
4208 LogInfo("SendRecordDeregistration TCP %p %s", rr
->tcp
, ARDisplayString(m
, rr
));
4209 if (rr
->tcp
) LogInfo("SendRecordDeregistration: Disposing existing TCP connection for %s", ARDisplayString(m
, rr
));
4210 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
4211 if (!rr
->nta
) { LogMsg("SendRecordDeregistration:Private:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
4212 rr
->tcp
= MakeTCPConn(m
, &m
->omsg
, ptr
, kTCPSocketFlags_UseTLS
, &rr
->nta
->Addr
, rr
->nta
->Port
, &rr
->nta
->Host
, mDNSNULL
, rr
);
4217 LogInfo("SendRecordDeregistration UDP %s", ARDisplayString(m
, rr
));
4218 if (!rr
->nta
) { LogMsg("SendRecordDeregistration:ERROR!! nta is NULL for %s", ARDisplayString(m
, rr
)); return; }
4219 err
= mDNSSendDNSMessage(m
, &m
->omsg
, ptr
, mDNSInterface_Any
, mDNSNULL
, mDNSNULL
, &rr
->nta
->Addr
, rr
->nta
->Port
, GetAuthInfoForName_internal(m
, rr
->resrec
.name
), mDNSfalse
);
4220 if (err
) debugf("ERROR: SendRecordDeregistration - mDNSSendDNSMessage - %d", err
);
4221 //if (rr->state == regState_DeregPending) CompleteDeregistration(m, rr); // Don't touch rr after this
4223 SetRecordRetry(m
, rr
, 0);
4226 LogMsg("SendRecordDeregistration: Error formatting message for %s", ARDisplayString(m
, rr
));
4229 mDNSexport mStatus
uDNS_DeregisterRecord(mDNS
*const m
, AuthRecord
*const rr
)
4231 DomainAuthInfo
*info
;
4233 LogInfo("uDNS_DeregisterRecord: Resource Record %s, state %d", ARDisplayString(m
, rr
), rr
->state
);
4237 case regState_Refresh
:
4238 case regState_Pending
:
4239 case regState_UpdatePending
:
4240 case regState_Registered
: break;
4241 case regState_DeregPending
: break;
4243 case regState_NATError
:
4244 case regState_NATMap
:
4245 // A record could be in NoTarget to start with if the corresponding SRV record could not find a target.
4246 // It is also possible to reenter the NoTarget state when we move to a network with a NAT that has
4247 // no {PCP, NAT-PMP, UPnP/IGD} support. In that case before we entered NoTarget, we already deregistered with
4249 case regState_NoTarget
:
4250 case regState_Unregistered
:
4253 LogInfo("uDNS_DeregisterRecord: State %d for %##s type %s", rr
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
4254 // This function may be called during sleep when there are no sleep proxy servers
4255 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) CompleteDeregistration(m
, rr
);
4256 return mStatus_NoError
;
4259 // if unsent rdata is queued, free it.
4261 // The data may be queued in QueuedRData or InFlightRData.
4263 // 1) If the record is in Registered state, we store it in InFlightRData and copy the same in "rdata"
4264 // *just* before sending the update to the server. Till we get the response, InFlightRData and "rdata"
4265 // in the resource record are same. We don't want to free in that case. It will be freed when "rdata"
4266 // is freed. If they are not same, the update has not been sent and we should free it here.
4268 // 2) If the record is in UpdatePending state, we queue the update in QueuedRData. When the previous update
4269 // comes back from the server, we copy it from QueuedRData to InFlightRData and repeat (1). This implies
4270 // that QueuedRData can never be same as "rdata" in the resource record. As long as we have something
4271 // left in QueuedRData, we should free it here.
4273 if (rr
->InFlightRData
&& rr
->UpdateCallback
)
4275 if (rr
->InFlightRData
!= rr
->resrec
.rdata
)
4277 LogInfo("uDNS_DeregisterRecord: Freeing InFlightRData for %s", ARDisplayString(m
, rr
));
4278 rr
->UpdateCallback(m
, rr
, rr
->InFlightRData
, rr
->InFlightRDLen
);
4279 rr
->InFlightRData
= mDNSNULL
;
4282 LogInfo("uDNS_DeregisterRecord: InFlightRData same as rdata for %s", ARDisplayString(m
, rr
));
4285 if (rr
->QueuedRData
&& rr
->UpdateCallback
)
4287 if (rr
->QueuedRData
== rr
->resrec
.rdata
)
4288 LogMsg("uDNS_DeregisterRecord: ERROR!! QueuedRData same as rdata for %s", ARDisplayString(m
, rr
));
4291 LogInfo("uDNS_DeregisterRecord: Freeing QueuedRData for %s", ARDisplayString(m
, rr
));
4292 rr
->UpdateCallback(m
, rr
, rr
->QueuedRData
, rr
->QueuedRDLen
);
4293 rr
->QueuedRData
= mDNSNULL
;
4297 // If a current group registration is pending, we can't send this deregisration till that registration
4298 // has reached the server i.e., the ordering is important. Previously, if we did not send this
4299 // registration in a group, then the previous connection will be torn down as part of sending the
4300 // deregistration. If we send this in a group, we need to locate the resource record that was used
4301 // to send this registration and terminate that connection. This means all the updates on that might
4302 // be lost (assuming the response is not waiting for us at the socket) and the retry will send the
4303 // update again sometime in the near future.
4305 // NOTE: SSL handshake failures normally free the TCP connection immediately. Hence, you may not
4306 // find the TCP below there. This case can happen only when tcp is trying to actively retransmit
4307 // the request or SSL negotiation taking time i.e resource record is actively trying to get the
4308 // message to the server. During that time a deregister has to happen.
4310 if (!mDNSOpaque16IsZero(rr
->updateid
))
4312 AuthRecord
*anchorRR
;
4313 mDNSBool found
= mDNSfalse
;
4314 for (anchorRR
= m
->ResourceRecords
; anchorRR
; anchorRR
= anchorRR
->next
)
4316 if (AuthRecord_uDNS(rr
) && mDNSSameOpaque16(anchorRR
->updateid
, rr
->updateid
) && anchorRR
->tcp
)
4318 LogInfo("uDNS_DeregisterRecord: Found Anchor RR %s terminated", ARDisplayString(m
, anchorRR
));
4320 LogMsg("uDNS_DeregisterRecord: ERROR: Another anchorRR %s found", ARDisplayString(m
, anchorRR
));
4321 DisposeTCPConn(anchorRR
->tcp
);
4322 anchorRR
->tcp
= mDNSNULL
;
4326 if (!found
) LogInfo("uDNSDeregisterRecord: Cannot find the anchor Resource Record for %s, not an error", ARDisplayString(m
, rr
));
4329 // Retry logic for deregistration should be no different from sending registration the first time.
4330 // Currently ThisAPInterval most likely is set to the refresh interval
4331 rr
->state
= regState_DeregPending
;
4332 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
4333 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
4334 info
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
4335 if (IsRecordMergeable(m
, rr
, m
->timenow
+ MERGE_DELAY_TIME
))
4337 // Delay the record deregistration by MERGE_DELAY_TIME so that we can merge them
4338 // into one update. If the domain is being deleted, delay by 2 * MERGE_DELAY_TIME
4339 // so that we can merge all the AutoTunnel records and the service records in
4340 // one update (they get deregistered a little apart)
4341 if (info
&& info
->deltime
) rr
->LastAPTime
+= (2 * MERGE_DELAY_TIME
);
4342 else rr
->LastAPTime
+= MERGE_DELAY_TIME
;
4344 // IsRecordMergeable could have returned false for several reasons e.g., DontMerge is set or
4345 // no zone information. Most likely it is the latter, CheckRecordUpdates will fetch the zone
4346 // data when it encounters this record.
4348 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
4349 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
4351 return mStatus_NoError
;
4354 mDNSexport mStatus
uDNS_UpdateRecord(mDNS
*m
, AuthRecord
*rr
)
4356 LogInfo("uDNS_UpdateRecord: Resource Record %##s, state %d", rr
->resrec
.name
->c
, rr
->state
);
4359 case regState_DeregPending
:
4360 case regState_Unregistered
:
4361 // not actively registered
4364 case regState_NATMap
:
4365 case regState_NoTarget
:
4366 // change rdata directly since it hasn't been sent yet
4367 if (rr
->UpdateCallback
) rr
->UpdateCallback(m
, rr
, rr
->resrec
.rdata
, rr
->resrec
.rdlength
);
4368 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
4369 rr
->NewRData
= mDNSNULL
;
4370 return mStatus_NoError
;
4372 case regState_Pending
:
4373 case regState_Refresh
:
4374 case regState_UpdatePending
:
4375 // registration in-flight. queue rdata and return
4376 if (rr
->QueuedRData
&& rr
->UpdateCallback
)
4377 // if unsent rdata is already queued, free it before we replace it
4378 rr
->UpdateCallback(m
, rr
, rr
->QueuedRData
, rr
->QueuedRDLen
);
4379 rr
->QueuedRData
= rr
->NewRData
;
4380 rr
->QueuedRDLen
= rr
->newrdlength
;
4381 rr
->NewRData
= mDNSNULL
;
4382 return mStatus_NoError
;
4384 case regState_Registered
:
4385 rr
->OrigRData
= rr
->resrec
.rdata
;
4386 rr
->OrigRDLen
= rr
->resrec
.rdlength
;
4387 rr
->InFlightRData
= rr
->NewRData
;
4388 rr
->InFlightRDLen
= rr
->newrdlength
;
4389 rr
->NewRData
= mDNSNULL
;
4390 rr
->state
= regState_UpdatePending
;
4391 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
4392 rr
->LastAPTime
= m
->timenow
- INIT_RECORD_REG_INTERVAL
;
4393 SetNextuDNSEvent(m
, rr
);
4394 return mStatus_NoError
;
4396 case regState_NATError
:
4397 LogMsg("ERROR: uDNS_UpdateRecord called for record %##s with bad state regState_NATError", rr
->resrec
.name
->c
);
4398 return mStatus_UnknownErr
; // states for service records only
4400 default: LogMsg("uDNS_UpdateRecord: Unknown state %d for %##s", rr
->state
, rr
->resrec
.name
->c
);
4404 LogMsg("uDNS_UpdateRecord: Requested update of record %##s type %d, in erroneous state %d",
4405 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, rr
->state
);
4406 return mStatus_Invalid
;
4409 // ***************************************************************************
4410 #if COMPILER_LIKES_PRAGMA_MARK
4411 #pragma mark - Periodic Execution Routines
4414 mDNSlocal
void uDNS_HandleLLQState(mDNS
*const m
, DNSQuestion
*q
)
4416 LogMsg("->uDNS_HandleLLQState: %##s %d", &q
->qname
, q
->state
);
4420 // If DNS Push isn't supported, LLQ_Init falls through to LLQ_InitialRequest.
4421 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
4422 // First attempt to use DNS Push Notification.
4423 DiscoverDNSPushNotificationServer(m
, q
);
4426 case LLQ_DNSPush_ServerDiscovery
:
4427 case LLQ_DNSPush_Connecting
:
4428 case LLQ_DNSPush_Established
:
4429 // Sanity check the server state to see if it matches. If we find that we aren't connected, when
4430 // we think we should be, change our state.
4431 if (q
->dnsPushServer
== NULL
)
4433 q
->state
= LLQ_Init
;
4434 q
->ThisQInterval
= 0;
4435 q
->LastQTime
= m
->timenow
;
4436 SetNextQueryTime(m
, q
);
4440 switch(q
->dnsPushServer
->connectState
)
4442 case DNSPushServerDisconnected
:
4443 case DNSPushServerConnectFailed
:
4444 case DNSPushServerNoDNSPush
:
4445 LogMsg("uDNS_HandleLLQState: %##s, server state %d doesn't match question state %d",
4446 &q
->dnsPushServer
->serverName
, q
->state
, q
->dnsPushServer
->connectState
);
4447 q
->state
= LLQ_Poll
;
4448 q
->ThisQInterval
= (mDNSPlatformOneSecond
* 5);
4449 q
->LastQTime
= m
->timenow
;
4450 SetNextQueryTime(m
, q
);
4452 case DNSPushServerSessionEstablished
:
4453 LogMsg("uDNS_HandleLLQState: %##s, server connection established but question state is %d",
4454 &q
->dnsPushServer
->serverName
, q
->state
);
4455 q
->state
= LLQ_DNSPush_Established
;
4456 q
->ThisQInterval
= 0;
4457 q
->LastQTime
= m
->timenow
;
4458 SetNextQueryTime(m
, q
);
4461 case DNSPushServerConnectionInProgress
:
4462 case DNSPushServerConnected
:
4468 // Silence warnings; these are never reached without DNS Push
4469 case LLQ_DNSPush_ServerDiscovery
:
4470 case LLQ_DNSPush_Connecting
:
4471 case LLQ_DNSPush_Established
:
4472 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
4473 case LLQ_InitialRequest
: startLLQHandshake(m
, q
); break;
4474 case LLQ_SecondaryRequest
: sendChallengeResponse(m
, q
, mDNSNULL
); break;
4475 case LLQ_Established
: sendLLQRefresh(m
, q
); break;
4476 case LLQ_Poll
: break; // Do nothing (handled below)
4478 LogMsg("<-uDNS_HandleLLQState: %##s %d %d", &q
->qname
, q
->state
);
4481 // The question to be checked is not passed in as an explicit parameter;
4482 // instead it is implicit that the question to be checked is m->CurrentQuestion.
4483 mDNSlocal
void uDNS_CheckCurrentQuestion(mDNS
*const m
)
4485 DNSQuestion
*q
= m
->CurrentQuestion
;
4486 if (m
->timenow
- NextQSendTime(q
) < 0) return;
4490 uDNS_HandleLLQState(m
,q
);
4493 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4494 Querier_HandleUnicastQuestion(q
);
4496 // We repeat the check above (rather than just making this the "else" case) because startLLQHandshake can change q->state to LLQ_Poll
4497 if (!(q
->LongLived
&& q
->state
!= LLQ_Poll
))
4499 if (q
->unansweredQueries
>= MAX_UCAST_UNANSWERED_QUERIES
)
4501 DNSServer
*orig
= q
->qDNSServer
;
4504 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4505 "[R%u->Q%u] uDNS_CheckCurrentQuestion: Sent %d unanswered queries for " PRI_DM_NAME
" (" PUB_S
") to " PRI_IP_ADDR
":%d (" PRI_DM_NAME
")",
4506 q
->request_id
, mDNSVal16(q
->TargetQID
), q
->unansweredQueries
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), &orig
->addr
, mDNSVal16(orig
->port
), DM_NAME_PARAM(&orig
->domain
));
4509 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
4510 SymptomReporterDNSServerUnreachable(orig
);
4512 PenalizeDNSServer(m
, q
, zeroID
);
4513 q
->noServerResponse
= 1;
4515 // There are two cases here.
4517 // 1. We have only one DNS server for this question. It is not responding even after we sent MAX_UCAST_UNANSWERED_QUERIES.
4518 // In that case, we need to keep retrying till we get a response. But we need to backoff as we retry. We set
4519 // noServerResponse in the block above and below we do not touch the question interval. When we come here, we
4520 // already waited for the response. We need to send another query right at this moment. We do that below by
4521 // reinitializing dns servers and reissuing the query.
4523 // 2. We have more than one DNS server. If at least one server did not respond, we would have set noServerResponse
4524 // either now (the last server in the list) or before (non-last server in the list). In either case, if we have
4525 // reached the end of DNS server list, we need to try again from the beginning. Ideally we should try just the
4526 // servers that did not respond, but for simplicity we try all the servers. Once we reached the end of list, we
4527 // set triedAllServersOnce so that we don't try all the servers aggressively. See PenalizeDNSServer.
4528 if (!q
->qDNSServer
&& q
->noServerResponse
)
4532 q
->triedAllServersOnce
= mDNStrue
;
4533 // Re-initialize all DNS servers for this question. If we have a DNSServer, DNSServerChangeForQuestion will
4534 // handle all the work including setting the new DNS server.
4535 SetValidDNSServers(m
, q
);
4536 new = GetServerForQuestion(m
, q
);
4539 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4540 "[R%u->Q%u] uDNS_checkCurrentQuestion: Retrying question %p " PRI_DM_NAME
" (" PUB_S
") DNS Server " PRI_IP_ADDR
":%d ThisQInterval %d",
4541 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), new ? &new->addr
: mDNSNULL
, mDNSVal16(new ? new->port
: zeroIPPort
), q
->ThisQInterval
);
4542 DNSServerChangeForQuestion(m
, q
, new);
4544 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
4545 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
4550 mStatus err
= mStatus_NoError
;
4551 mDNSOpaque16 HeaderFlags
= uQueryFlags
;
4553 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, HeaderFlags
);
4554 end
= putQuestion(&m
->omsg
, m
->omsg
.data
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
, &q
->qname
, q
->qtype
, q
->qclass
);
4556 if (end
> m
->omsg
.data
)
4558 debugf("uDNS_CheckCurrentQuestion sending %p %##s (%s) %#a:%d UnansweredQueries %d",
4559 q
, q
->qname
.c
, DNSTypeName(q
->qtype
),
4560 q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
, mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
), q
->unansweredQueries
);
4561 #if APPLE_OSX_mDNSResponder
4562 // When a DNS proxy network extension initiates the close of a UDP flow (this usually happens when a DNS
4563 // proxy gets disabled or crashes), mDNSResponder's corresponding UDP socket will be marked with the
4564 // SS_CANTRCVMORE state flag. Reading from such a socket is no longer possible, so close the current
4565 // socket pair so that we can create a new pair.
4566 if (q
->LocalSocket
&& mDNSPlatformUDPSocketEncounteredEOF(q
->LocalSocket
))
4568 mDNSPlatformUDPClose(q
->LocalSocket
);
4569 q
->LocalSocket
= mDNSNULL
;
4572 if (!q
->LocalSocket
)
4574 q
->LocalSocket
= mDNSPlatformUDPSocket(zeroIPPort
);
4577 mDNSPlatformSetSocktOpt(q
->LocalSocket
, mDNSTransport_UDP
, mDNSAddrType_IPv4
, q
);
4578 mDNSPlatformSetSocktOpt(q
->LocalSocket
, mDNSTransport_UDP
, mDNSAddrType_IPv6
, q
);
4581 if (!q
->LocalSocket
) err
= mStatus_NoMemoryErr
; // If failed to make socket (should be very rare), we'll try again next time
4584 err
= mDNSSendDNSMessage(m
, &m
->omsg
, end
, q
->qDNSServer
->interface
, mDNSNULL
, q
->LocalSocket
, &q
->qDNSServer
->addr
, q
->qDNSServer
->port
, mDNSNULL
, q
->UseBackgroundTraffic
);
4586 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4589 MetricsUpdateDNSQuerySize((mDNSu32
)(end
- (mDNSu8
*)&m
->omsg
));
4590 if (q
->metrics
.answered
)
4592 q
->metrics
.querySendCount
= 0;
4593 q
->metrics
.answered
= mDNSfalse
;
4595 if (q
->metrics
.querySendCount
++ == 0)
4597 q
->metrics
.firstQueryTime
= NonZeroTime(m
->timenow
);
4604 if (err
== mStatus_HostUnreachErr
)
4606 DNSServer
*newServer
;
4608 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4609 "[R%u->Q%u] uDNS_CheckCurrentQuestion: host unreachable error for DNS server " PRI_IP_ADDR
" for question [%p] " PRI_DM_NAME
" (" PUB_S
")",
4610 q
->request_id
, mDNSVal16(q
->TargetQID
), &q
->qDNSServer
->addr
, q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
4612 if (!StrictUnicastOrdering
)
4614 q
->qDNSServer
->penaltyTime
= NonZeroTime(m
->timenow
+ DNSSERVER_PENALTY_TIME
);
4617 newServer
= GetServerForQuestion(m
, q
);
4620 q
->triedAllServersOnce
= mDNStrue
;
4621 SetValidDNSServers(m
, q
);
4622 newServer
= GetServerForQuestion(m
, q
);
4626 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4627 "[R%u->Q%u] uDNS_checkCurrentQuestion: Retrying question %p " PRI_DM_NAME
" (" PUB_S
") DNS Server " PRI_IP_ADDR
":%u ThisQInterval %d",
4628 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
),
4629 newServer
? &newServer
->addr
: mDNSNULL
, mDNSVal16(newServer
? newServer
->port
: zeroIPPort
), q
->ThisQInterval
);
4630 DNSServerChangeForQuestion(m
, q
, newServer
);
4632 if (q
->triedAllServersOnce
)
4634 q
->LastQTime
= m
->timenow
;
4638 q
->ThisQInterval
= InitialQuestionInterval
;
4639 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4641 q
->unansweredQueries
= 0;
4645 if (err
!= mStatus_TransientErr
) // if it is not a transient error backoff and DO NOT flood queries unnecessarily
4647 // If all DNS Servers are not responding, then we back-off using the multiplier UDNSBackOffMultiplier(*2).
4648 // Only increase interval if send succeeded
4650 q
->ThisQInterval
= q
->ThisQInterval
* UDNSBackOffMultiplier
;
4651 if ((q
->ThisQInterval
> 0) && (q
->ThisQInterval
< MinQuestionInterval
)) // We do not want to retx within 1 sec
4652 q
->ThisQInterval
= MinQuestionInterval
;
4654 q
->unansweredQueries
++;
4655 if (q
->ThisQInterval
> MAX_UCAST_POLL_INTERVAL
)
4656 q
->ThisQInterval
= MAX_UCAST_POLL_INTERVAL
;
4657 if (q
->qDNSServer
->isCell
)
4659 // We don't want to retransmit too soon. Schedule our first retransmisson at
4660 // MIN_UCAST_RETRANS_TIMEOUT seconds.
4661 if (q
->ThisQInterval
< MIN_UCAST_RETRANS_TIMEOUT
)
4662 q
->ThisQInterval
= MIN_UCAST_RETRANS_TIMEOUT
;
4664 debugf("uDNS_CheckCurrentQuestion: Increased ThisQInterval to %d for %##s (%s), cell %d", q
->ThisQInterval
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
->isCell
);
4666 q
->LastQTime
= m
->timenow
;
4668 SetNextQueryTime(m
, q
);
4672 // If we have no server for this query, or the only server is a disabled one, then we deliver
4673 // a transient failure indication to the client. This is important for things like iPhone
4674 // where we want to return timely feedback to the user when no network is available.
4675 // After calling MakeNegativeCacheRecord() we store the resulting record in the
4676 // cache so that it will be visible to other clients asking the same question.
4677 // (When we have a group of identical questions, only the active representative of the group gets
4678 // passed to uDNS_CheckCurrentQuestion -- we only want one set of query packets hitting the wire --
4679 // but we want *all* of the questions to get answer callbacks.)
4681 const mDNSu32 slot
= HashSlotFromNameHash(q
->qnamehash
);
4682 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
4686 if (!mDNSOpaque128IsZero(&q
->validDNSServers
))
4687 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
4688 "[R%u->Q%u] uDNS_CheckCurrentQuestion: ERROR!!: valid DNSServer bits not zero 0x%x, 0x%x 0x%x 0x%x for question " PRI_DM_NAME
" (" PUB_S
")",
4689 q
->request_id
, mDNSVal16(q
->TargetQID
), q
->validDNSServers
.l
[3], q
->validDNSServers
.l
[2], q
->validDNSServers
.l
[1], q
->validDNSServers
.l
[0], DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
4690 // If we reached the end of list while picking DNS servers, then we don't want to deactivate the
4691 // question. Try after 60 seconds. We find this by looking for valid DNSServers for this question,
4692 // if we find any, then we must have tried them before we came here. This avoids maintaining
4693 // another state variable to see if we had valid DNS servers for this question.
4694 SetValidDNSServers(m
, q
);
4695 if (mDNSOpaque128IsZero(&q
->validDNSServers
))
4697 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4698 "[R%u->Q%u] uDNS_CheckCurrentQuestion: no DNS server for " PRI_DM_NAME
" (" PUB_S
")",
4699 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
4700 q
->ThisQInterval
= 0;
4705 // Pretend that we sent this question. As this is an ActiveQuestion, the NextScheduledQuery should
4706 // be set properly. Also, we need to properly backoff in cases where we don't set the question to
4707 // MaxQuestionInterval when we answer the question e.g., LongLived, we need to keep backing off
4708 q
->ThisQInterval
= q
->ThisQInterval
* QuestionIntervalStep
;
4709 q
->LastQTime
= m
->timenow
;
4710 SetNextQueryTime(m
, q
);
4711 // Pick a new DNS server now. Otherwise, when the cache is 80% of its expiry, we will try
4712 // to send a query and come back to the same place here and log the above message.
4713 q
->qDNSServer
= GetServerForQuestion(m
, q
);
4714 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
4715 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
4716 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4717 "[R%u->Q%u] uDNS_checkCurrentQuestion: Tried all DNS servers, retry question %p SuppressUnusable %d " PRI_DM_NAME
" (" PUB_S
") with DNS Server " PRI_IP_ADDR
":%d after 60 seconds, ThisQInterval %d",
4718 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, q
->SuppressUnusable
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
),
4719 q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
, mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
), q
->ThisQInterval
);
4724 q
->ThisQInterval
= 0;
4725 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4726 "[R%u->Q%u] uDNS_CheckCurrentQuestion DNS server " PRI_IP_ADDR
":%d for " PRI_DM_NAME
" is disabled",
4727 q
->request_id
, mDNSVal16(q
->TargetQID
), &q
->qDNSServer
->addr
, mDNSVal16(q
->qDNSServer
->port
), DM_NAME_PARAM(&q
->qname
));
4732 for (cr
= cg
->members
; cr
; cr
=cr
->next
)
4734 if (SameNameCacheRecordAnswersQuestion(cr
, q
))
4736 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4737 "[R%u->Q%u] uDNS_CheckCurrentQuestion: Purged resourcerecord " PRI_S
,
4738 q
->request_id
, mDNSVal16(q
->TargetQID
), CRDisplayString(m
, cr
));
4739 mDNS_PurgeCacheResourceRecord(m
, cr
);
4743 // For some of the WAB queries that we generate form within the mDNSResponder, most of the home routers
4744 // don't understand and return ServFail/NXDomain. In those cases, we don't want to try too often. We try
4745 // every fifteen minutes in that case
4746 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, (DomainEnumQuery(&q
->qname
) ? 60 * 15 : 60), mDNSInterface_Any
, q
->qDNSServer
);
4747 q
->unansweredQueries
= 0;
4748 if (!mDNSOpaque16IsZero(q
->responseFlags
))
4749 m
->rec
.r
.responseFlags
= q
->responseFlags
;
4750 // We're already using the m->CurrentQuestion pointer, so CacheRecordAdd can't use it to walk the question list.
4751 // To solve this problem we set cr->DelayDelivery to a nonzero value (which happens to be 'now') so that we
4752 // momentarily defer generating answer callbacks until mDNS_Execute time.
4753 CreateNewCacheEntry(m
, slot
, cg
, NonZeroTime(m
->timenow
), mDNStrue
, mDNSNULL
);
4754 ScheduleNextCacheCheckTime(m
, slot
, NonZeroTime(m
->timenow
));
4755 m
->rec
.r
.responseFlags
= zeroID
;
4756 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4757 // MUST NOT touch m->CurrentQuestion (or q) after this -- client callback could have deleted it
4760 #endif // MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4763 mDNSexport
void CheckNATMappings(mDNS
*m
)
4765 mDNSBool rfc1918
= mDNSv4AddrIsRFC1918(&m
->AdvertisedV4
.ip
.v4
);
4766 mDNSBool HaveRoutable
= !rfc1918
&& !mDNSIPv4AddressIsZero(m
->AdvertisedV4
.ip
.v4
);
4767 m
->NextScheduledNATOp
= m
->timenow
+ FutureTime
;
4769 if (HaveRoutable
) m
->ExtAddress
= m
->AdvertisedV4
.ip
.v4
;
4771 if (m
->NATTraversals
&& rfc1918
) // Do we need to open a socket to receive multicast announcements from router?
4773 if (m
->NATMcastRecvskt
== mDNSNULL
) // If we are behind a NAT and the socket hasn't been opened yet, open it
4775 // we need to log a message if we can't get our socket, but only the first time (after success)
4776 static mDNSBool needLog
= mDNStrue
;
4777 m
->NATMcastRecvskt
= mDNSPlatformUDPSocket(NATPMPAnnouncementPort
);
4778 if (!m
->NATMcastRecvskt
)
4782 LogMsg("CheckNATMappings: Failed to allocate port 5350 UDP multicast socket for PCP & NAT-PMP announcements");
4783 needLog
= mDNSfalse
;
4790 else // else, we don't want to listen for announcements, so close them if they're open
4792 if (m
->NATMcastRecvskt
) { mDNSPlatformUDPClose(m
->NATMcastRecvskt
); m
->NATMcastRecvskt
= mDNSNULL
; }
4793 if (m
->SSDPSocket
) { debugf("CheckNATMappings destroying SSDPSocket %p", &m
->SSDPSocket
); mDNSPlatformUDPClose(m
->SSDPSocket
); m
->SSDPSocket
= mDNSNULL
; }
4796 uDNS_RequestAddress(m
);
4798 if (m
->CurrentNATTraversal
) LogMsg("WARNING m->CurrentNATTraversal already in use");
4799 m
->CurrentNATTraversal
= m
->NATTraversals
;
4801 while (m
->CurrentNATTraversal
)
4803 NATTraversalInfo
*cur
= m
->CurrentNATTraversal
;
4804 mDNSv4Addr EffectiveAddress
= HaveRoutable
? m
->AdvertisedV4
.ip
.v4
: cur
->NewAddress
;
4805 m
->CurrentNATTraversal
= m
->CurrentNATTraversal
->next
;
4807 if (HaveRoutable
) // If not RFC 1918 address, our own address and port are effectively our external address and port
4809 cur
->ExpiryTime
= 0;
4810 cur
->NewResult
= mStatus_NoError
;
4812 else // Check if it's time to send port mapping packet(s)
4814 if (m
->timenow
- cur
->retryPortMap
>= 0) // Time to send a mapping request for this packet
4816 if (cur
->ExpiryTime
&& cur
->ExpiryTime
- m
->timenow
< 0) // Mapping has expired
4818 cur
->ExpiryTime
= 0;
4819 cur
->retryInterval
= NATMAP_INIT_RETRY
;
4822 uDNS_SendNATMsg(m
, cur
, mDNStrue
, mDNSfalse
); // Will also do UPnP discovery for us, if necessary
4824 if (cur
->ExpiryTime
) // If have active mapping then set next renewal time halfway to expiry
4825 NATSetNextRenewalTime(m
, cur
);
4826 else // else no mapping; use exponential backoff sequence
4828 if (cur
->retryInterval
< NATMAP_INIT_RETRY
) cur
->retryInterval
= NATMAP_INIT_RETRY
;
4829 else if (cur
->retryInterval
< NATMAP_MAX_RETRY_INTERVAL
/ 2) cur
->retryInterval
*= 2;
4830 else cur
->retryInterval
= NATMAP_MAX_RETRY_INTERVAL
;
4831 cur
->retryPortMap
= m
->timenow
+ cur
->retryInterval
;
4835 if (m
->NextScheduledNATOp
- cur
->retryPortMap
> 0)
4837 m
->NextScheduledNATOp
= cur
->retryPortMap
;
4841 // Notify the client if necessary. We invoke the callback if:
4842 // (1) We have an effective address,
4843 // or we've tried and failed a couple of times to discover it
4845 // (2) the client requested the address only,
4846 // or the client won't need a mapping because we have a routable address,
4847 // or the client has an expiry time and therefore a successful mapping,
4848 // or we've tried and failed a couple of times (see "Time line" below)
4850 // (3) we have new data to give the client that's changed since the last callback
4852 // Time line is: Send, Wait 500ms, Send, Wait 1sec, Send, Wait 2sec, Send
4853 // At this point we've sent three requests without an answer, we've just sent our fourth request,
4854 // retryInterval is now 4 seconds, which is greater than NATMAP_INIT_RETRY * 8 (2 seconds),
4855 // so we return an error result to the caller.
4856 if (!mDNSIPv4AddressIsZero(EffectiveAddress
) || cur
->retryInterval
> NATMAP_INIT_RETRY
* 8)
4858 const mStatus EffectiveResult
= cur
->NewResult
? cur
->NewResult
: mDNSv4AddrIsRFC1918(&EffectiveAddress
) ? mStatus_DoubleNAT
: mStatus_NoError
;
4859 const mDNSIPPort ExternalPort
= HaveRoutable
? cur
->IntPort
:
4860 !mDNSIPv4AddressIsZero(EffectiveAddress
) && cur
->ExpiryTime
? cur
->RequestedPort
: zeroIPPort
;
4862 if (!cur
->Protocol
|| HaveRoutable
|| cur
->ExpiryTime
|| cur
->retryInterval
> NATMAP_INIT_RETRY
* 8)
4864 if (!mDNSSameIPv4Address(cur
->ExternalAddress
, EffectiveAddress
) ||
4865 !mDNSSameIPPort (cur
->ExternalPort
, ExternalPort
) ||
4866 cur
->Result
!= EffectiveResult
)
4868 //LogMsg("NAT callback %d %d %d", cur->Protocol, cur->ExpiryTime, cur->retryInterval);
4869 if (cur
->Protocol
&& mDNSIPPortIsZero(ExternalPort
) && !mDNSIPv4AddressIsZero(m
->Router
.ip
.v4
))
4871 if (!EffectiveResult
)
4872 LogInfo("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4873 cur
, &m
->Router
, &EffectiveAddress
, mDNSVal16(cur
->IntPort
), cur
->retryInterval
, EffectiveResult
);
4875 LogMsg("CheckNATMapping: Failed to obtain NAT port mapping %p from router %#a external address %.4a internal port %5d interval %d error %d",
4876 cur
, &m
->Router
, &EffectiveAddress
, mDNSVal16(cur
->IntPort
), cur
->retryInterval
, EffectiveResult
);
4879 cur
->ExternalAddress
= EffectiveAddress
;
4880 cur
->ExternalPort
= ExternalPort
;
4881 cur
->Lifetime
= cur
->ExpiryTime
&& !mDNSIPPortIsZero(ExternalPort
) ?
4882 (cur
->ExpiryTime
- m
->timenow
+ mDNSPlatformOneSecond
/2) / mDNSPlatformOneSecond
: 0;
4883 cur
->Result
= EffectiveResult
;
4884 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
4885 if (cur
->clientCallback
)
4886 cur
->clientCallback(m
, cur
);
4887 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4888 // MUST NOT touch cur after invoking the callback
4895 mDNSlocal mDNSs32
CheckRecordUpdates(mDNS
*m
)
4898 mDNSs32 nextevent
= m
->timenow
+ FutureTime
;
4900 CheckGroupRecordUpdates(m
);
4902 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4904 if (!AuthRecord_uDNS(rr
)) continue;
4905 if (rr
->state
== regState_NoTarget
) {debugf("CheckRecordUpdates: Record %##s in NoTarget", rr
->resrec
.name
->c
); continue;}
4906 // While we are waiting for the port mapping, we have nothing to do. The port mapping callback
4907 // will take care of this
4908 if (rr
->state
== regState_NATMap
) {debugf("CheckRecordUpdates: Record %##s in NATMap", rr
->resrec
.name
->c
); continue;}
4909 if (rr
->state
== regState_Pending
|| rr
->state
== regState_DeregPending
|| rr
->state
== regState_UpdatePending
||
4910 rr
->state
== regState_Refresh
|| rr
->state
== regState_Registered
)
4912 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- m
->timenow
<= 0)
4914 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
4915 if (!rr
->nta
|| mDNSIPv4AddressIsZero(rr
->nta
->Addr
.ip
.v4
))
4917 // Zero out the updateid so that if we have a pending response from the server, it won't
4918 // be accepted as a valid response. If we accept the response, we might free the new "nta"
4919 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
4920 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
4922 // We have just started the GetZoneData. We need to wait for it to finish. SetRecordRetry here
4923 // schedules the update timer to fire in the future.
4925 // There are three cases.
4927 // 1) When the updates are sent the first time, the first retry is intended to be at three seconds
4928 // in the future. But by calling SetRecordRetry here we set it to nine seconds. But it does not
4929 // matter because when the answer comes back, RecordRegistrationGotZoneData resets the interval
4930 // back to INIT_RECORD_REG_INTERVAL. This also gives enough time for the query.
4932 // 2) In the case of update errors (updateError), this causes further backoff as
4933 // RecordRegistrationGotZoneData does not reset the timer. This is intentional as in the case of
4934 // errors, we don't want to update aggressively.
4936 // 3) We might be refreshing the update. This is very similar to case (1). RecordRegistrationGotZoneData
4937 // resets it back to INIT_RECORD_REG_INTERVAL.
4939 SetRecordRetry(m
, rr
, 0);
4941 else if (rr
->state
== regState_DeregPending
) SendRecordDeregistration(m
, rr
);
4942 else SendRecordRegistration(m
, rr
);
4945 if (nextevent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) > 0)
4946 nextevent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
4951 mDNSexport
void uDNS_Tasks(mDNS
*const m
)
4954 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4958 m
->NextuDNSEvent
= m
->timenow
+ FutureTime
;
4960 nexte
= CheckRecordUpdates(m
);
4961 if (m
->NextuDNSEvent
- nexte
> 0)
4962 m
->NextuDNSEvent
= nexte
;
4964 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4965 for (d
= m
->DNSServers
; d
; d
=d
->next
)
4968 if (m
->timenow
- d
->penaltyTime
>= 0)
4970 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
4971 "DNS server " PRI_IP_ADDR
":%d out of penalty box", &d
->addr
, mDNSVal16(d
->port
));
4975 if (m
->NextuDNSEvent
- d
->penaltyTime
> 0)
4976 m
->NextuDNSEvent
= d
->penaltyTime
;
4980 if (m
->CurrentQuestion
)
4982 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
4983 "uDNS_Tasks ERROR m->CurrentQuestion already set: " PRI_DM_NAME
" (" PRI_S
")",
4984 DM_NAME_PARAM(&m
->CurrentQuestion
->qname
), DNSTypeName(m
->CurrentQuestion
->qtype
));
4986 m
->CurrentQuestion
= m
->Questions
;
4987 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4989 DNSQuestion
*const q
= m
->CurrentQuestion
;
4990 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
))
4992 uDNS_CheckCurrentQuestion(m
);
4993 if (q
== m
->CurrentQuestion
)
4994 if (m
->NextuDNSEvent
- NextQSendTime(q
) > 0)
4995 m
->NextuDNSEvent
= NextQSendTime(q
);
4997 // If m->CurrentQuestion wasn't modified out from under us, advance it now
4998 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion()
4999 // depends on having m->CurrentQuestion point to the right question
5000 if (m
->CurrentQuestion
== q
)
5001 m
->CurrentQuestion
= q
->next
;
5003 m
->CurrentQuestion
= mDNSNULL
;
5006 // ***************************************************************************
5007 #if COMPILER_LIKES_PRAGMA_MARK
5008 #pragma mark - Startup, Shutdown, and Sleep
5011 mDNSexport
void SleepRecordRegistrations(mDNS
*m
)
5014 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
5016 if (AuthRecord_uDNS(rr
))
5018 // Zero out the updateid so that if we have a pending response from the server, it won't
5019 // be accepted as a valid response.
5020 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
5022 if (rr
->NATinfo
.clientContext
)
5024 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
5025 rr
->NATinfo
.clientContext
= mDNSNULL
;
5027 // We are waiting to update the resource record. The original data of the record is
5028 // in OrigRData and the updated value is in InFlightRData. Free the old and the new
5029 // one will be registered when we come back.
5030 if (rr
->state
== regState_UpdatePending
)
5032 // act as if the update succeeded, since we're about to delete the name anyway
5033 rr
->state
= regState_Registered
;
5034 // deallocate old RData
5035 if (rr
->UpdateCallback
) rr
->UpdateCallback(m
, rr
, rr
->OrigRData
, rr
->OrigRDLen
);
5036 SetNewRData(&rr
->resrec
, rr
->InFlightRData
, rr
->InFlightRDLen
);
5037 rr
->OrigRData
= mDNSNULL
;
5038 rr
->InFlightRData
= mDNSNULL
;
5041 // If we have not begun the registration process i.e., never sent a registration packet,
5042 // then uDNS_DeregisterRecord will not send a deregistration
5043 uDNS_DeregisterRecord(m
, rr
);
5045 // When we wake, we call ActivateUnicastRegistration which starts at StartGetZoneData
5050 mDNSexport
void mDNS_AddSearchDomain(const domainname
*const domain
, mDNSInterfaceID InterfaceID
)
5053 SearchListElem
*tmp
= mDNSNULL
;
5055 // Check to see if we already have this domain in our list
5056 for (p
= &SearchList
; *p
; p
= &(*p
)->next
)
5057 if (((*p
)->InterfaceID
== InterfaceID
) && SameDomainName(&(*p
)->domain
, domain
))
5059 // If domain is already in list, and marked for deletion, unmark the delete
5060 // Be careful not to touch the other flags that may be present
5061 LogInfo("mDNS_AddSearchDomain already in list %##s", domain
->c
);
5062 if ((*p
)->flag
& SLE_DELETE
) (*p
)->flag
&= ~SLE_DELETE
;
5065 tmp
->next
= mDNSNULL
;
5070 // move to end of list so that we maintain the same order
5071 while (*p
) p
= &(*p
)->next
;
5076 // if domain not in list, add to list, mark as add (1)
5077 *p
= (SearchListElem
*) mDNSPlatformMemAllocateClear(sizeof(**p
));
5078 if (!*p
) { LogMsg("ERROR: mDNS_AddSearchDomain - malloc"); return; }
5079 AssignDomainName(&(*p
)->domain
, domain
);
5080 (*p
)->next
= mDNSNULL
;
5081 (*p
)->InterfaceID
= InterfaceID
;
5082 LogInfo("mDNS_AddSearchDomain created new %##s, InterfaceID %p", domain
->c
, InterfaceID
);
5086 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
5089 if (result
== mStatus_MemFree
) mDNSPlatformMemFree(rr
->RecordContext
);
5092 mDNSlocal
void FoundDomain(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
5094 SearchListElem
*slElem
= question
->QuestionContext
;
5098 if (answer
->rrtype
!= kDNSType_PTR
) return;
5099 if (answer
->RecordType
== kDNSRecordTypePacketNegative
) return;
5100 if (answer
->InterfaceID
== mDNSInterface_LocalOnly
) return;
5102 if (question
== &slElem
->BrowseQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowse
];
5103 else if (question
== &slElem
->DefBrowseQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowseDefault
];
5104 else if (question
== &slElem
->AutomaticBrowseQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowseAutomatic
];
5105 else if (question
== &slElem
->RegisterQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeRegistration
];
5106 else if (question
== &slElem
->DefRegisterQ
) name
= mDNS_DomainTypeNames
[mDNS_DomainTypeRegistrationDefault
];
5107 else { LogMsg("FoundDomain - unknown question"); return; }
5109 LogInfo("FoundDomain: %p %s %s Q %##s A %s", answer
->InterfaceID
, AddRecord
? "Add" : "Rmv", name
, question
->qname
.c
, RRDisplayString(m
, answer
));
5113 ARListElem
*arElem
= (ARListElem
*) mDNSPlatformMemAllocateClear(sizeof(*arElem
));
5114 if (!arElem
) { LogMsg("ERROR: FoundDomain out of memory"); return; }
5115 mDNS_SetupResourceRecord(&arElem
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, AuthRecordLocalOnly
, FreeARElemCallback
, arElem
);
5116 MakeDomainNameFromDNSNameString(&arElem
->ar
.namestorage
, name
);
5117 AppendDNSNameString (&arElem
->ar
.namestorage
, "local");
5118 AssignDomainName(&arElem
->ar
.resrec
.rdata
->u
.name
, &answer
->rdata
->u
.name
);
5119 LogInfo("FoundDomain: Registering %s", ARDisplayString(m
, &arElem
->ar
));
5120 err
= mDNS_Register(m
, &arElem
->ar
);
5121 if (err
) { LogMsg("ERROR: FoundDomain - mDNS_Register returned %d", err
); mDNSPlatformMemFree(arElem
); return; }
5122 arElem
->next
= slElem
->AuthRecs
;
5123 slElem
->AuthRecs
= arElem
;
5127 ARListElem
**ptr
= &slElem
->AuthRecs
;
5130 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, &answer
->rdata
->u
.name
))
5132 ARListElem
*dereg
= *ptr
;
5133 *ptr
= (*ptr
)->next
;
5134 LogInfo("FoundDomain: Deregistering %s", ARDisplayString(m
, &dereg
->ar
));
5135 err
= mDNS_Deregister(m
, &dereg
->ar
);
5136 if (err
) LogMsg("ERROR: FoundDomain - mDNS_Deregister returned %d", err
);
5137 // Memory will be freed in the FreeARElemCallback
5140 ptr
= &(*ptr
)->next
;
5145 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
5146 mDNSexport
void udns_validatelists(void *const v
)
5150 NATTraversalInfo
*n
;
5151 for (n
= m
->NATTraversals
; n
; n
=n
->next
)
5152 if (n
->next
== (NATTraversalInfo
*)~0 || n
->clientCallback
== (NATTraversalClientCallback
) ~0)
5153 LogMemCorruption("m->NATTraversals: %p is garbage", n
);
5156 for (d
= m
->DNSServers
; d
; d
=d
->next
)
5157 if (d
->next
== (DNSServer
*)~0)
5158 LogMemCorruption("m->DNSServers: %p is garbage", d
);
5160 DomainAuthInfo
*info
;
5161 for (info
= m
->AuthInfoList
; info
; info
= info
->next
)
5162 if (info
->next
== (DomainAuthInfo
*)~0)
5163 LogMemCorruption("m->AuthInfoList: %p is garbage", info
);
5166 for (hi
= m
->Hostnames
; hi
; hi
= hi
->next
)
5167 if (hi
->next
== (HostnameInfo
*)~0 || hi
->StatusCallback
== (mDNSRecordCallback
*)~0)
5168 LogMemCorruption("m->Hostnames: %p is garbage", n
);
5170 SearchListElem
*ptr
;
5171 for (ptr
= SearchList
; ptr
; ptr
= ptr
->next
)
5172 if (ptr
->next
== (SearchListElem
*)~0 || ptr
->AuthRecs
== (void*)~0)
5173 LogMemCorruption("SearchList: %p is garbage (%X)", ptr
, ptr
->AuthRecs
);
5177 // This should probably move to the UDS daemon -- the concept of legacy clients and automatic registration / automatic browsing
5178 // is really a UDS API issue, not something intrinsic to uDNS
5180 mDNSlocal
void uDNS_DeleteWABQueries(mDNS
*const m
, SearchListElem
*ptr
, int delete)
5182 const char *name1
= mDNSNULL
;
5183 const char *name2
= mDNSNULL
;
5184 ARListElem
**arList
= &ptr
->AuthRecs
;
5185 domainname namestorage1
, namestorage2
;
5188 // "delete" parameter indicates the type of query.
5191 case UDNS_WAB_BROWSE_QUERY
:
5192 mDNS_StopGetDomains(m
, &ptr
->BrowseQ
);
5193 mDNS_StopGetDomains(m
, &ptr
->DefBrowseQ
);
5194 name1
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowse
];
5195 name2
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowseDefault
];
5197 case UDNS_WAB_LBROWSE_QUERY
:
5198 mDNS_StopGetDomains(m
, &ptr
->AutomaticBrowseQ
);
5199 name1
= mDNS_DomainTypeNames
[mDNS_DomainTypeBrowseAutomatic
];
5201 case UDNS_WAB_REG_QUERY
:
5202 mDNS_StopGetDomains(m
, &ptr
->RegisterQ
);
5203 mDNS_StopGetDomains(m
, &ptr
->DefRegisterQ
);
5204 name1
= mDNS_DomainTypeNames
[mDNS_DomainTypeRegistration
];
5205 name2
= mDNS_DomainTypeNames
[mDNS_DomainTypeRegistrationDefault
];
5208 LogMsg("uDNS_DeleteWABQueries: ERROR!! returning from default");
5211 // When we get the results to the domain enumeration queries, we add a LocalOnly
5212 // entry. For example, if we issue a domain enumeration query for b._dns-sd._udp.xxxx.com,
5213 // and when we get a response, we add a LocalOnly entry b._dns-sd._udp.local whose RDATA
5214 // points to what we got in the response. Locate the appropriate LocalOnly entries and delete
5218 MakeDomainNameFromDNSNameString(&namestorage1
, name1
);
5219 AppendDNSNameString(&namestorage1
, "local");
5223 MakeDomainNameFromDNSNameString(&namestorage2
, name2
);
5224 AppendDNSNameString(&namestorage2
, "local");
5228 ARListElem
*dereg
= *arList
;
5229 if ((name1
&& SameDomainName(&dereg
->ar
.namestorage
, &namestorage1
)) ||
5230 (name2
&& SameDomainName(&dereg
->ar
.namestorage
, &namestorage2
)))
5232 LogInfo("uDNS_DeleteWABQueries: Deregistering PTR %##s -> %##s", dereg
->ar
.resrec
.name
->c
, dereg
->ar
.resrec
.rdata
->u
.name
.c
);
5233 *arList
= dereg
->next
;
5234 err
= mDNS_Deregister(m
, &dereg
->ar
);
5235 if (err
) LogMsg("uDNS_DeleteWABQueries:: ERROR!! mDNS_Deregister returned %d", err
);
5236 // Memory will be freed in the FreeARElemCallback
5240 LogInfo("uDNS_DeleteWABQueries: Skipping PTR %##s -> %##s", dereg
->ar
.resrec
.name
->c
, dereg
->ar
.resrec
.rdata
->u
.name
.c
);
5241 arList
= &(*arList
)->next
;
5246 mDNSexport
void uDNS_SetupWABQueries(mDNS
*const m
)
5248 SearchListElem
**p
= &SearchList
, *ptr
;
5252 // step 1: mark each element for removal
5253 for (ptr
= SearchList
; ptr
; ptr
= ptr
->next
)
5254 ptr
->flag
|= SLE_DELETE
;
5256 // Make sure we have the search domains from the platform layer so that if we start the WAB
5257 // queries below, we have the latest information.
5259 if (!mDNSPlatformSetDNSConfig(mDNSfalse
, mDNStrue
, mDNSNULL
, mDNSNULL
, mDNSNULL
, mDNSfalse
))
5261 // If the configuration did not change, clear the flag so that we don't free the searchlist.
5262 // We still have to start the domain enumeration queries as we may not have started them
5264 for (ptr
= SearchList
; ptr
; ptr
= ptr
->next
)
5265 ptr
->flag
&= ~SLE_DELETE
;
5266 LogInfo("uDNS_SetupWABQueries: No config change");
5270 if (m
->WABBrowseQueriesCount
)
5271 action
|= UDNS_WAB_BROWSE_QUERY
;
5272 if (m
->WABLBrowseQueriesCount
)
5273 action
|= UDNS_WAB_LBROWSE_QUERY
;
5274 if (m
->WABRegQueriesCount
)
5275 action
|= UDNS_WAB_REG_QUERY
;
5278 // delete elems marked for removal, do queries for elems marked add
5282 LogInfo("uDNS_SetupWABQueries:action 0x%x: Flags 0x%x, AuthRecs %p, InterfaceID %p %##s", action
, ptr
->flag
, ptr
->AuthRecs
, ptr
->InterfaceID
, ptr
->domain
.c
);
5283 // If SLE_DELETE is set, stop all the queries, deregister all the records and free the memory.
5284 // Otherwise, check to see what the "action" requires. If a particular action bit is not set and
5285 // we have started the corresponding queries as indicated by the "flags", stop those queries and
5286 // deregister the records corresponding to them.
5287 if ((ptr
->flag
& SLE_DELETE
) ||
5288 (!(action
& UDNS_WAB_BROWSE_QUERY
) && (ptr
->flag
& SLE_WAB_BROWSE_QUERY_STARTED
)) ||
5289 (!(action
& UDNS_WAB_LBROWSE_QUERY
) && (ptr
->flag
& SLE_WAB_LBROWSE_QUERY_STARTED
)) ||
5290 (!(action
& UDNS_WAB_REG_QUERY
) && (ptr
->flag
& SLE_WAB_REG_QUERY_STARTED
)))
5292 if (ptr
->flag
& SLE_DELETE
)
5294 ARListElem
*arList
= ptr
->AuthRecs
;
5295 ptr
->AuthRecs
= mDNSNULL
;
5298 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries
5299 // We suppressed the domain enumeration for scoped search domains below. When we enable that
5301 if ((ptr
->flag
& SLE_WAB_BROWSE_QUERY_STARTED
) &&
5302 !SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5304 LogInfo("uDNS_SetupWABQueries: DELETE Browse for domain %##s", ptr
->domain
.c
);
5305 mDNS_StopGetDomains(m
, &ptr
->BrowseQ
);
5306 mDNS_StopGetDomains(m
, &ptr
->DefBrowseQ
);
5308 if ((ptr
->flag
& SLE_WAB_LBROWSE_QUERY_STARTED
) &&
5309 !SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5311 LogInfo("uDNS_SetupWABQueries: DELETE Legacy Browse for domain %##s", ptr
->domain
.c
);
5312 mDNS_StopGetDomains(m
, &ptr
->AutomaticBrowseQ
);
5314 if ((ptr
->flag
& SLE_WAB_REG_QUERY_STARTED
) &&
5315 !SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5317 LogInfo("uDNS_SetupWABQueries: DELETE Registration for domain %##s", ptr
->domain
.c
);
5318 mDNS_StopGetDomains(m
, &ptr
->RegisterQ
);
5319 mDNS_StopGetDomains(m
, &ptr
->DefRegisterQ
);
5322 mDNSPlatformMemFree(ptr
);
5324 // deregister records generated from answers to the query
5327 ARListElem
*dereg
= arList
;
5328 arList
= arList
->next
;
5329 LogInfo("uDNS_SetupWABQueries: DELETE Deregistering PTR %##s -> %##s", dereg
->ar
.resrec
.name
->c
, dereg
->ar
.resrec
.rdata
->u
.name
.c
);
5330 err
= mDNS_Deregister(m
, &dereg
->ar
);
5331 if (err
) LogMsg("uDNS_SetupWABQueries:: ERROR!! mDNS_Deregister returned %d", err
);
5332 // Memory will be freed in the FreeARElemCallback
5337 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries
5338 // We suppressed the domain enumeration for scoped search domains below. When we enable that
5340 if (!(action
& UDNS_WAB_BROWSE_QUERY
) && (ptr
->flag
& SLE_WAB_BROWSE_QUERY_STARTED
) &&
5341 !SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5343 LogInfo("uDNS_SetupWABQueries: Deleting Browse for domain %##s", ptr
->domain
.c
);
5344 ptr
->flag
&= ~SLE_WAB_BROWSE_QUERY_STARTED
;
5345 uDNS_DeleteWABQueries(m
, ptr
, UDNS_WAB_BROWSE_QUERY
);
5348 if (!(action
& UDNS_WAB_LBROWSE_QUERY
) && (ptr
->flag
& SLE_WAB_LBROWSE_QUERY_STARTED
) &&
5349 !SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5351 LogInfo("uDNS_SetupWABQueries: Deleting Legacy Browse for domain %##s", ptr
->domain
.c
);
5352 ptr
->flag
&= ~SLE_WAB_LBROWSE_QUERY_STARTED
;
5353 uDNS_DeleteWABQueries(m
, ptr
, UDNS_WAB_LBROWSE_QUERY
);
5356 if (!(action
& UDNS_WAB_REG_QUERY
) && (ptr
->flag
& SLE_WAB_REG_QUERY_STARTED
) &&
5357 !SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5359 LogInfo("uDNS_SetupWABQueries: Deleting Registration for domain %##s", ptr
->domain
.c
);
5360 ptr
->flag
&= ~SLE_WAB_REG_QUERY_STARTED
;
5361 uDNS_DeleteWABQueries(m
, ptr
, UDNS_WAB_REG_QUERY
);
5364 // Fall through to handle the ADDs
5367 if ((action
& UDNS_WAB_BROWSE_QUERY
) && !(ptr
->flag
& SLE_WAB_BROWSE_QUERY_STARTED
))
5369 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries.
5370 // Also, suppress the domain enumeration for scoped search domains for now until there is a need.
5371 if (!SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5374 err1
= mDNS_GetDomains(m
, &ptr
->BrowseQ
, mDNS_DomainTypeBrowse
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
5377 LogMsg("uDNS_SetupWABQueries: GetDomains for domain %##s returned error(s):\n"
5378 "%d (mDNS_DomainTypeBrowse)\n", ptr
->domain
.c
, err1
);
5382 LogInfo("uDNS_SetupWABQueries: Starting Browse for domain %##s", ptr
->domain
.c
);
5384 err2
= mDNS_GetDomains(m
, &ptr
->DefBrowseQ
, mDNS_DomainTypeBrowseDefault
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
5387 LogMsg("uDNS_SetupWABQueries: GetDomains for domain %##s returned error(s):\n"
5388 "%d (mDNS_DomainTypeBrowseDefault)\n", ptr
->domain
.c
, err2
);
5392 LogInfo("uDNS_SetupWABQueries: Starting Default Browse for domain %##s", ptr
->domain
.c
);
5394 // For simplicity, we mark a single bit for denoting that both the browse queries have started.
5395 // It is not clear as to why one would fail to start and the other would succeed in starting up.
5396 // If that happens, we will try to stop both the queries and one of them won't be in the list and
5397 // it is not a hard error.
5400 ptr
->flag
|= SLE_WAB_BROWSE_QUERY_STARTED
;
5404 if ((action
& UDNS_WAB_LBROWSE_QUERY
) && !(ptr
->flag
& SLE_WAB_LBROWSE_QUERY_STARTED
))
5406 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries.
5407 // Also, suppress the domain enumeration for scoped search domains for now until there is a need.
5408 if (!SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5411 err1
= mDNS_GetDomains(m
, &ptr
->AutomaticBrowseQ
, mDNS_DomainTypeBrowseAutomatic
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
5414 LogMsg("uDNS_SetupWABQueries: GetDomains for domain %##s returned error(s):\n"
5415 "%d (mDNS_DomainTypeBrowseAutomatic)\n",
5416 ptr
->domain
.c
, err1
);
5420 ptr
->flag
|= SLE_WAB_LBROWSE_QUERY_STARTED
;
5421 LogInfo("uDNS_SetupWABQueries: Starting Legacy Browse for domain %##s", ptr
->domain
.c
);
5425 if ((action
& UDNS_WAB_REG_QUERY
) && !(ptr
->flag
& SLE_WAB_REG_QUERY_STARTED
))
5427 // If the user has "local" in their DNS searchlist, we ignore that for the purposes of domain enumeration queries.
5428 // Also, suppress the domain enumeration for scoped search domains for now until there is a need.
5429 if (!SameDomainName(&ptr
->domain
, &localdomain
) && (ptr
->InterfaceID
== mDNSInterface_Any
))
5432 err1
= mDNS_GetDomains(m
, &ptr
->RegisterQ
, mDNS_DomainTypeRegistration
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
5435 LogMsg("uDNS_SetupWABQueries: GetDomains for domain %##s returned error(s):\n"
5436 "%d (mDNS_DomainTypeRegistration)\n", ptr
->domain
.c
, err1
);
5440 LogInfo("uDNS_SetupWABQueries: Starting Registration for domain %##s", ptr
->domain
.c
);
5442 err2
= mDNS_GetDomains(m
, &ptr
->DefRegisterQ
, mDNS_DomainTypeRegistrationDefault
, &ptr
->domain
, ptr
->InterfaceID
, FoundDomain
, ptr
);
5445 LogMsg("uDNS_SetupWABQueries: GetDomains for domain %##s returned error(s):\n"
5446 "%d (mDNS_DomainTypeRegistrationDefault)", ptr
->domain
.c
, err2
);
5450 LogInfo("uDNS_SetupWABQueries: Starting Default Registration for domain %##s", ptr
->domain
.c
);
5454 ptr
->flag
|= SLE_WAB_REG_QUERY_STARTED
;
5463 // mDNS_StartWABQueries is called once per API invocation where normally
5464 // one of the bits is set.
5465 mDNSexport
void uDNS_StartWABQueries(mDNS
*const m
, int queryType
)
5467 if (queryType
& UDNS_WAB_BROWSE_QUERY
)
5469 m
->WABBrowseQueriesCount
++;
5470 LogInfo("uDNS_StartWABQueries: Browse query count %d", m
->WABBrowseQueriesCount
);
5472 if (queryType
& UDNS_WAB_LBROWSE_QUERY
)
5474 m
->WABLBrowseQueriesCount
++;
5475 LogInfo("uDNS_StartWABQueries: Legacy Browse query count %d", m
->WABLBrowseQueriesCount
);
5477 if (queryType
& UDNS_WAB_REG_QUERY
)
5479 m
->WABRegQueriesCount
++;
5480 LogInfo("uDNS_StartWABQueries: Reg query count %d", m
->WABRegQueriesCount
);
5482 uDNS_SetupWABQueries(m
);
5485 // mDNS_StopWABQueries is called once per API invocation where normally
5486 // one of the bits is set.
5487 mDNSexport
void uDNS_StopWABQueries(mDNS
*const m
, int queryType
)
5489 if (queryType
& UDNS_WAB_BROWSE_QUERY
)
5491 m
->WABBrowseQueriesCount
--;
5492 LogInfo("uDNS_StopWABQueries: Browse query count %d", m
->WABBrowseQueriesCount
);
5494 if (queryType
& UDNS_WAB_LBROWSE_QUERY
)
5496 m
->WABLBrowseQueriesCount
--;
5497 LogInfo("uDNS_StopWABQueries: Legacy Browse query count %d", m
->WABLBrowseQueriesCount
);
5499 if (queryType
& UDNS_WAB_REG_QUERY
)
5501 m
->WABRegQueriesCount
--;
5502 LogInfo("uDNS_StopWABQueries: Reg query count %d", m
->WABRegQueriesCount
);
5504 uDNS_SetupWABQueries(m
);
5507 mDNSexport domainname
*uDNS_GetNextSearchDomain(mDNSInterfaceID InterfaceID
, int *searchIndex
, mDNSBool ignoreDotLocal
)
5509 SearchListElem
*p
= SearchList
;
5510 int count
= *searchIndex
;
5512 if (count
< 0) { LogMsg("uDNS_GetNextSearchDomain: count %d less than zero", count
); return mDNSNULL
; }
5514 // Skip the domains that we already looked at before. Guard against "p"
5515 // being NULL. When search domains change we may not set the SearchListIndex
5516 // of the question to zero immediately e.g., domain enumeration query calls
5517 // uDNS_SetupWABQueries which reads in the new search domain but does not
5518 // restart the questions immediately. Questions are restarted as part of
5519 // network change and hence temporarily SearchListIndex may be out of range.
5521 for (; count
&& p
; count
--)
5526 int labels
= CountLabels(&p
->domain
);
5529 const domainname
*d
= SkipLeadingLabels(&p
->domain
, labels
- 1);
5530 if (SameDomainLabel(d
->c
, (const mDNSu8
*)"\x4" "arpa"))
5532 LogInfo("uDNS_GetNextSearchDomain: skipping search domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
5537 if (ignoreDotLocal
&& SameDomainLabel(d
->c
, (const mDNSu8
*)"\x5" "local"))
5539 LogInfo("uDNS_GetNextSearchDomain: skipping local domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
5545 // Point to the next one in the list which we will look at next time.
5547 if (p
->InterfaceID
== InterfaceID
)
5549 LogInfo("uDNS_GetNextSearchDomain returning domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
5552 LogInfo("uDNS_GetNextSearchDomain skipping domain %##s, InterfaceID %p", p
->domain
.c
, p
->InterfaceID
);
5558 mDNSexport
void uDNS_RestartQuestionAsTCP(mDNS
*m
, DNSQuestion
*const q
, const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
)
5560 // Don't reuse TCP connections. We might have failed over to a different DNS server
5561 // while the first TCP connection is in progress. We need a new TCP connection to the
5562 // new DNS server. So, always try to establish a new connection.
5563 if (q
->tcp
) { DisposeTCPConn(q
->tcp
); q
->tcp
= mDNSNULL
; }
5564 q
->tcp
= MakeTCPConn(m
, mDNSNULL
, mDNSNULL
, kTCPSocketFlags_Zero
, srcaddr
, srcport
, mDNSNULL
, q
, mDNSNULL
);
5567 mDNSlocal
void FlushAddressCacheRecords(mDNS
*const m
)
5572 FORALL_CACHERECORDS(slot
, cg
, cr
)
5574 if (cr
->resrec
.InterfaceID
) continue;
5576 // If a resource record can answer A or AAAA, they need to be flushed so that we will
5577 // deliver an ADD or RMV
5578 if (RRTypeAnswersQuestionType(&cr
->resrec
, kDNSType_A
) ||
5579 RRTypeAnswersQuestionType(&cr
->resrec
, kDNSType_AAAA
))
5581 LogInfo("FlushAddressCacheRecords: Purging Resourcerecord %s", CRDisplayString(m
, cr
));
5582 mDNS_PurgeCacheResourceRecord(m
, cr
);
5587 // Retry questions which has seach domains appended
5588 mDNSexport
void RetrySearchDomainQuestions(mDNS
*const m
)
5591 mDNSBool found
= mDNSfalse
;
5593 // Check to see if there are any questions which needs search domains to be applied.
5594 // If there is none, search domains can't possibly affect them.
5595 for (q
= m
->Questions
; q
; q
= q
->next
)
5597 if (q
->AppendSearchDomains
)
5605 LogInfo("RetrySearchDomainQuestions: Questions with AppendSearchDomain not found");
5608 LogInfo("RetrySearchDomainQuestions: Question with AppendSearchDomain found %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5609 // Purge all the A/AAAA cache records and restart the queries. mDNSCoreRestartAddressQueries
5610 // does this. When we restart the question, we first want to try the new search domains rather
5611 // than use the entries that is already in the cache. When we appended search domains, we might
5612 // have created cache entries which is no longer valid as there are new search domains now
5613 mDNSCoreRestartAddressQueries(m
, mDNStrue
, FlushAddressCacheRecords
, mDNSNULL
, mDNSNULL
);
5616 // Construction of Default Browse domain list (i.e. when clients pass NULL) is as follows:
5617 // 1) query for b._dns-sd._udp.local on LocalOnly interface
5618 // (.local manually generated via explicit callback)
5619 // 2) for each search domain (from prefs pane), query for b._dns-sd._udp.<searchdomain>.
5620 // 3) for each result from (2), register LocalOnly PTR record b._dns-sd._udp.local. -> <result>
5621 // 4) result above should generate a callback from question in (1). result added to global list
5622 // 5) global list delivered to client via GetSearchDomainList()
5623 // 6) client calls to enumerate domains now go over LocalOnly interface
5624 // (!!!KRS may add outgoing interface in addition)
5626 struct CompileTimeAssertionChecks_uDNS
5628 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
5629 // other overly-large structures instead of having a pointer to them, can inadvertently
5630 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
5631 char sizecheck_tcpInfo_t
[(sizeof(tcpInfo_t
) <= 9056) ? 1 : -1];
5632 char sizecheck_SearchListElem
[(sizeof(SearchListElem
) <= 6381) ? 1 : -1];
5635 #if COMPILER_LIKES_PRAGMA_MARK
5636 #pragma mark - DNS Push Notification functions
5639 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
5640 mDNSlocal
void DNSPushProcessResponse(mDNS
*const m
, const DNSMessage
*const msg
,
5641 DNSPushNotificationServer
*server
, ResourceRecord
*mrr
)
5643 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
5644 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
5645 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
5646 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
5647 CacheRecord
**cfp
= &CacheFlushRecords
;
5648 enum { removeName
, removeClass
, removeRRset
, removeRR
, addRR
} action
;
5650 // Ignore records we don't want to cache.
5652 // Don't want to cache OPT or TSIG pseudo-RRs
5653 if (mrr
->rrtype
== kDNSType_TSIG
)
5657 if (mrr
->rrtype
== kDNSType_OPT
)
5662 if ((mrr
->rrtype
== kDNSType_CNAME
) && SameDomainName(mrr
->name
, &mrr
->rdata
->u
.name
))
5664 LogInfo("DNSPushProcessResponse: CNAME loop domain name %##s", mrr
->name
->c
);
5668 // TTL == -1: delete individual record
5669 // TTL == -2: wildcard delete
5670 // CLASS != ANY, TYPE != ANY: delete all records of specified type and class
5671 // CLASS != ANY, TYPE == ANY: delete all RRs of specified class
5672 // CLASS == ANY: delete all RRs on the name, regardless of type or class (TYPE is ignored).
5673 // If TTL is zero, this is a delete, not an add.
5674 if ((mDNSs32
)mrr
->rroriginalttl
== -1)
5676 LogMsg("DNSPushProcessResponse: Got remove on %##s with type %s",
5677 mrr
->name
, DNSTypeName(mrr
->rrtype
));
5680 else if ((mDNSs32
)mrr
->rroriginalttl
== -2)
5682 if (mrr
->rrclass
== kDNSQClass_ANY
)
5684 LogMsg("DNSPushProcessResponse: Got Remove Name on %##s", mrr
->name
);
5685 action
= removeName
;
5687 else if (mrr
->rrtype
== kDNSQType_ANY
)
5689 LogMsg("DNSPushProcessResponse: Got Remove Name on %##s", mrr
->name
);
5690 action
= removeClass
;
5694 LogMsg("DNSPushProcessResponse: Got Remove RRset on %##s, type %s, rdlength %d",
5695 mrr
->name
, DNSTypeName(mrr
->rrtype
), mrr
->rdlength
);
5696 action
= removeRRset
;
5704 if (action
!= addRR
)
5706 if (m
->rrcache_size
)
5709 // Remember the unicast question that we found, which we use to make caching
5710 // decisions later on in this function
5711 CacheGroup
*cg
= CacheGroupForName(m
, mrr
->namehash
, mrr
->name
);
5712 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
5714 if ( action
== removeName
||
5715 (action
== removeClass
&& rr
->resrec
.rrclass
== mrr
->rrclass
) ||
5716 (rr
->resrec
.rrclass
== mrr
->rrclass
&&
5717 ((action
== removeRRset
&& rr
->resrec
.rrtype
== mrr
->rrtype
) ||
5718 (action
== removeRR
&& rr
->resrec
.rrtype
== mrr
->rrtype
&&
5719 SameRDataBody(mrr
, &rr
->resrec
.rdata
->u
, SameDomainName
)))))
5721 LogInfo("DNSPushProcessResponse purging %##s (%s) %s",
5722 rr
->resrec
.name
, DNSTypeName(mrr
->rrtype
), CRDisplayString(m
, rr
));
5723 // We've found a cache entry to delete. Now what?
5724 mDNS_PurgeCacheResourceRecord(m
, rr
);
5732 LogMsg("DNSPushProcessResponse: Got add RR on %##s, type %s, length %d",
5733 mrr
->name
, DNSTypeName(mrr
->rrtype
), mrr
->rdlength
);
5735 // When we receive DNS Push responses, we assume a long cache lifetime --
5736 // This path is only reached for DNS Push responses; as long as the connection to the server is
5737 // live, the RR should stay ypdated.
5738 mrr
->rroriginalttl
= kLLQ_DefLease
/* XXX */;
5740 // Use the DNS Server we remember from the question that created this DNS Push server structure.
5741 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5742 mdns_replace(&mrr
->dnsservice
, server
->dnsservice
);
5744 mrr
->rDNSServer
= server
->qDNSServer
;
5747 // 2. See if we want to add this packet resource record to our cache
5748 // We only try to cache answers if we have a cache to put them in
5749 if (m
->rrcache_size
)
5751 const mDNSu32 slot
= HashSlotFromNameHash(mrr
->namehash
);
5752 CacheGroup
*cg
= CacheGroupForName(m
, mrr
->namehash
, mrr
->name
);
5753 CacheRecord
*rr
= mDNSNULL
;
5755 // 2a. Check if this packet resource record is already in our cache.
5756 rr
= mDNSCoreReceiveCacheCheck(m
, msg
, uDNS_LLQ_Events
, slot
, cg
, &cfp
, mDNSNULL
);
5758 // If packet resource record not in our cache, add it now
5759 // (unless it is just a deletion of a record we never had, in which case we don't care)
5760 if (!rr
&& mrr
->rroriginalttl
> 0)
5762 rr
= CreateNewCacheEntry(m
, slot
, cg
, 0,
5763 mDNStrue
, &server
->connection
->transport
->remote_addr
);
5766 // Not clear that this is ever used, but for verisimilitude, set this to look like
5767 // an authoritative response to a regular query.
5768 rr
->responseFlags
.b
[0] = kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
| kDNSFlag0_AA
;
5769 rr
->responseFlags
.b
[1] = kDNSFlag1_RC_NoErr
| kDNSFlag0_AA
;
5776 mDNSlocal
void DNSPushProcessResponses(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*firstAnswer
,
5777 const mDNSu8
*const end
, DNSPushNotificationServer
*server
)
5780 const mDNSu8
*ptr
= firstAnswer
;
5782 port
.NotAnInteger
= 0;
5783 ResourceRecord
*mrr
= &m
->rec
.r
.resrec
;
5785 // Validate the contents of the message
5786 // XXX Right now this code will happily parse all the valid data and then hit invalid data
5787 // and give up. I don't think there's a risk here, but we should discuss it.
5788 // XXX what about source validation? Like, if we have a VPN, are we safe? I think yes, but let's think about it.
5789 while ((ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, mDNSNULL
, kDNSRecordTypePacketAns
, &m
->rec
)))
5792 for (q
= m
->Questions
; q
; q
= q
->next
)
5795 (q
->qtype
== mrr
->rrtype
|| q
->qtype
== kDNSServiceType_ANY
)
5796 && q
->qnamehash
== mrr
->namehash
&& SameDomainName(&q
->qname
, mrr
->name
))
5798 LogMsg("DNSPushProcessResponses found %##s (%s) %d %s %s",
5799 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->state
,
5800 q
->dnsPushServer
? (q
->dnsPushServer
->connection
5801 ? q
->dnsPushServer
->connection
->remote_name
5802 : "<no push server>") : "<no push server>",
5803 server
->connection
->remote_name
);
5804 if (q
->dnsPushServer
== server
)
5807 DNSPushProcessResponse(m
, msg
, server
, mrr
);
5808 break; // question list may have changed
5813 LogMsg("DNSPushProcessResponses: no match for %##s %d %d", mrr
->name
, mrr
->rrtype
, mrr
->rrclass
);
5815 mrr
->RecordType
= 0; // Clear RecordType to show we're not still using it
5820 DNSPushStartConnecting(DNSPushNotificationServer
*server
)
5822 if (dso_connect(server
->connectInfo
))
5824 server
->connectState
= DNSPushServerConnectionInProgress
;
5828 server
->connectState
= DNSPushServerConnectFailed
;
5832 mDNSexport
void DNSPushReconcileConnection(mDNS
*m
, DNSQuestion
*q
)
5834 DNSPushNotificationZone
*zone
;
5835 DNSPushNotificationZone
*nextZone
;
5837 if (q
->dnsPushServer
== mDNSNULL
)
5842 // Update the counts
5843 for (zone
= m
->DNSPushZones
; zone
!= mDNSNULL
; zone
= zone
->next
)
5845 if (zone
->server
== q
->dnsPushServer
)
5847 zone
->numberOfQuestions
--;
5850 q
->dnsPushServer
->numberOfQuestions
--;
5852 nextZone
= mDNSNULL
;
5853 for (zone
= m
->DNSPushZones
; zone
!= mDNSNULL
; zone
= nextZone
)
5855 nextZone
= zone
->next
;
5856 if (zone
->numberOfQuestions
== 0)
5858 if (zone
== m
->DNSPushZones
)
5859 m
->DNSPushZones
= nextZone
;
5860 LogInfo("DNSPushReconcileConnection: zone %##s is being freed", &zone
->zoneName
);
5861 mDNSPlatformMemFree(zone
);
5865 q
->dnsPushServer
= mDNSNULL
;
5868 static const char kDNSPushActivity_Subscription
[] = "dns-push-subscription";
5870 static void DNSPushSendKeepalive(DNSPushNotificationServer
*server
, mDNSu32 inactivity_timeout
, mDNSu32 keepalive_interval
)
5872 dso_message_t state
;
5873 dso_transport_t
*transport
= server
->connection
->transport
;
5874 if (transport
== NULL
|| transport
->outbuf
== NULL
) {
5875 // Should be impossible, don't crash.
5876 LogInfo("DNSPushNotificationSendSubscribe: no transport!");
5879 dso_make_message(&state
, transport
->outbuf
, transport
->outbuf_size
, server
->connection
, false, 0);
5880 dso_start_tlv(&state
, kDSOType_Keepalive
);
5881 dso_add_tlv_u32(&state
, inactivity_timeout
);
5882 dso_add_tlv_u32(&state
, keepalive_interval
);
5883 dso_finish_tlv(&state
);
5884 dso_message_write(server
->connection
, &state
, mDNSfalse
);
5887 static void DNSPushNotificationSendSubscriptionChange(mDNSBool subscribe
, dso_state_t
*dso
, DNSQuestion
*q
)
5889 dso_message_t state
;
5890 dso_transport_t
*transport
= dso
->transport
;
5892 if (transport
== NULL
|| transport
->outbuf
== NULL
) {
5893 // Should be impossible, don't crash.
5894 LogInfo("DNSPushNotificationSendSubscribe: no transport!");
5897 dso_make_message(&state
, transport
->outbuf
, transport
->outbuf_size
, dso
, subscribe
? false : true, q
);
5898 dso_start_tlv(&state
, subscribe
? kDSOType_DNSPushSubscribe
: kDSOType_DNSPushUnsubscribe
);
5899 len
= DomainNameLengthLimit(&q
->qname
, q
->qname
.c
+ (sizeof q
->qname
));
5900 dso_add_tlv_bytes(&state
, q
->qname
.c
, len
);
5901 dso_add_tlv_u16(&state
, q
->qtype
);
5902 dso_add_tlv_u16(&state
, q
->qclass
);
5903 dso_finish_tlv(&state
);
5904 dso_message_write(dso
, &state
, mDNSfalse
);
5907 static void DNSPushStop(mDNS
*m
, DNSPushNotificationServer
*server
)
5909 mDNSBool found
= mDNStrue
;
5914 server
->connectState
= DNSPushServerNoDNSPush
;
5916 for (q
= m
->Questions
; q
; q
= q
->next
)
5918 if (q
->dnsPushServer
== server
)
5920 DNSPushReconcileConnection(m
, q
);
5921 q
->dnsPushServer
= NULL
;
5922 q
->state
= LLQ_Poll
;
5923 q
->ThisQInterval
= 0;
5924 q
->LastQTime
= m
->timenow
;
5925 SetNextQueryTime(m
, q
);
5932 mDNSexport
void DNSPushServerDrop(DNSPushNotificationServer
*server
)
5934 if (server
->connection
)
5936 dso_drop(server
->connection
);
5937 server
->connection
= NULL
;
5939 if (server
->connectInfo
)
5941 dso_connect_state_drop(server
->connectInfo
);
5945 static void DNSPushServerFree(mDNS
*m
, DNSPushNotificationServer
*server
)
5947 DNSPushNotificationServer
**sp
;
5948 DNSPushServerDrop(server
);
5950 sp
= &m
->DNSPushServers
;
5963 mDNSPlatformMemFree(server
);
5966 static void DNSPushDSOCallback(void *context
, const void *event_context
,
5967 dso_state_t
*dso
, dso_event_type_t eventType
)
5969 const DNSMessage
*message
;
5970 DNSPushNotificationServer
*server
= context
;
5971 dso_activity_t
*activity
;
5972 const dso_query_receive_context_t
*receive_context
;
5973 const dso_disconnect_context_t
*disconnect_context
;
5974 const dso_keepalive_context_t
*keepalive_context
;
5977 mDNSs32 reconnect_when
= 0;
5978 mDNS
*m
= server
->m
;
5984 case kDSOEventType_DNSMessage
:
5985 // We shouldn't get here because we won't use this connection for DNS messages.
5986 message
= event_context
;
5987 LogMsg("DNSPushDSOCallback: DNS Message (opcode=%d) received from %##s",
5988 (message
->h
.flags
.b
[0] & kDNSFlag0_OP_Mask
) >> 3, &server
->serverName
);
5991 case kDSOEventType_DNSResponse
:
5992 // We shouldn't get here because we already handled any DNS messages
5993 message
= event_context
;
5994 LogMsg("DNSPushDSOCallback: DNS Response (opcode=%d) received from %##s",
5995 (message
->h
.flags
.b
[0] & kDNSFlag0_OP_Mask
) >> 3, &server
->serverName
);
5998 case kDSOEventType_DSOMessage
:
5999 message
= event_context
;
6000 if (dso
->primary
.opcode
== kDSOType_DNSPushUpdate
) {
6001 DNSPushProcessResponses(server
->m
, message
, dso
->primary
.payload
,
6002 dso
->primary
.payload
+ dso
->primary
.length
, server
);
6004 dso_send_not_implemented(dso
, &message
->h
);
6005 LogMsg("DNSPushDSOCallback: Unknown DSO Message (Primary TLV=%d) received from %##s",
6006 dso
->primary
.opcode
, &server
->serverName
);
6010 case kDSOEventType_DSOResponse
:
6011 receive_context
= event_context
;
6012 q
= receive_context
->query_context
;
6013 rcode
= receive_context
->rcode
;
6015 // If we got an error on a subscribe, we need to evaluate what went wrong
6016 if (rcode
== kDNSFlag1_RC_NoErr
) {
6017 LogMsg("DNSPushDSOCallback: Subscription for %##s/%d/%d succeeded.", q
->qname
.c
, q
->qtype
, q
->qclass
);
6018 q
->state
= LLQ_DNSPush_Established
;
6019 server
->connectState
= DNSPushServerSessionEstablished
;
6021 // Don't use this server.
6022 q
->dnsPushServer
->connectState
= DNSPushServerNoDNSPush
;
6023 q
->state
= LLQ_Poll
;
6024 q
->ThisQInterval
= 0;
6025 q
->LastQTime
= m
->timenow
;
6026 SetNextQueryTime(m
, q
);
6027 LogMsg("DNSPushDSOCallback: Subscription for %##s/%d/%d failed.", q
->qname
.c
, q
->qtype
, q
->qclass
);
6030 LogMsg("DNSPushDSOCallback: DSO Response (Primary TLV=%d) (RCODE=%d) (no query) received from %##s",
6031 dso
->primary
.opcode
, receive_context
->rcode
, &server
->serverName
);
6032 server
->connectState
= DNSPushServerSessionEstablished
;
6036 case kDSOEventType_Finalize
:
6037 LogMsg("DNSPushDSOCallback: Finalize");
6040 case kDSOEventType_Connected
:
6041 LogMsg("DNSPushDSOCallback: Connected to %##s", &server
->serverName
);
6042 server
->connectState
= DNSPushServerConnected
;
6043 for (activity
= dso
->activities
; activity
; activity
= activity
->next
) {
6044 DNSPushNotificationSendSubscriptionChange(mDNStrue
, dso
, activity
->context
);
6048 case kDSOEventType_ConnectFailed
:
6049 DNSPushStop(m
, server
);
6050 LogMsg("DNSPushDSOCallback: Connection to %##s failed", &server
->serverName
);
6053 case kDSOEventType_Disconnected
:
6054 disconnect_context
= event_context
;
6056 // If a network glitch broke the connection, try to reconnect immediately. But if this happens
6057 // twice, don't just blindly reconnect.
6058 if (disconnect_context
->reconnect_delay
== 0) {
6059 if ((server
->lastDisconnect
+ 90 * mDNSPlatformOneSecond
) - m
->timenow
> 0) {
6060 reconnect_when
= 3600000; // If we get two disconnects in quick succession, wait an hour before trying again.
6062 DNSPushStartConnecting(server
);
6063 LogMsg("DNSPushDSOCallback: Connection to %##s disconnected, trying immediate reconnect",
6064 &server
->serverName
);
6067 reconnect_when
= disconnect_context
->reconnect_delay
;
6069 if (reconnect_when
!= 0) {
6070 LogMsg("DNSPushDSOCallback: Holding server %##s out as not reconnectable for %lf seconds",
6071 &server
->serverName
, 1000.0 * (reconnect_when
- m
->timenow
) / (double)mDNSPlatformOneSecond
);
6072 dso_schedule_reconnect(m
, server
->connectInfo
, reconnect_when
);
6074 server
->lastDisconnect
= m
->timenow
;
6075 server
->connection
= mDNSNULL
;
6078 // We don't reconnect unless there is demand. The reason we have this event is so that we can
6079 // leave the DNSPushNotificationServer data structure around to _prevent_ attempts to reconnect
6080 // before the reconnect delay interval has expired. When we get this call, we just free up the
6082 case kDSOEventType_ShouldReconnect
:
6083 // This should be unnecessary, but it would be bad to accidentally have a question pointing at
6084 // a server that had been freed, so make sure we don't.
6085 LogMsg("DNSPushDSOCallback: ShouldReconnect timer for %##s fired, disposing of it.", &server
->serverName
);
6086 DNSPushStop(m
, server
);
6087 DNSPushServerFree(m
, server
);
6090 case kDSOEventType_Keepalive
:
6091 LogMsg("DNSPushDSOCallback: Keepalive timer for %##s fired.", &server
->serverName
);
6092 keepalive_context
= event_context
;
6093 DNSPushSendKeepalive(server
, keepalive_context
->inactivity_timeout
, keepalive_context
->keepalive_interval
);
6096 case kDSOEventType_KeepaliveRcvd
:
6097 LogMsg("DNSPushDSOCallback: Keepalive message received from %##s.", &server
->serverName
);
6100 case kDSOEventType_Inactive
:
6101 // The set of activities went to zero, and we set the idle timeout. And it expired without any
6102 // new activities starting. So we can disconnect.
6103 LogMsg("DNSPushDSOCallback: Inactivity timer for %##s fired, disposing of it.", &server
->serverName
);
6104 DNSPushStop(m
, server
);
6105 DNSPushServerFree(m
, server
);
6108 case kDSOEventType_RetryDelay
:
6109 disconnect_context
= event_context
;
6110 DNSPushStop(m
, server
);
6111 dso_schedule_reconnect(m
, server
->connectInfo
, disconnect_context
->reconnect_delay
);
6116 DNSPushNotificationServer
*GetConnectionToDNSPushNotificationServer(mDNS
*m
, DNSQuestion
*q
)
6118 DNSPushNotificationZone
*zone
;
6119 DNSPushNotificationServer
*server
;
6120 DNSPushNotificationZone
*newZone
;
6121 DNSPushNotificationServer
*newServer
;
6122 char name
[MAX_ESCAPED_DOMAIN_NAME
];
6124 // If we already have a question for this zone and if the server is the same, reuse it
6125 for (zone
= m
->DNSPushZones
; zone
!= mDNSNULL
; zone
= zone
->next
)
6127 LogMsg("GetConnectionToDNSPushNotificationServer: zone compare zone %##s question %##s", &zone
->zoneName
, &q
->nta
->ChildName
);
6128 if (SameDomainName(&q
->nta
->ChildName
, &zone
->zoneName
))
6130 DNSPushNotificationServer
*zoneServer
= mDNSNULL
;
6131 zoneServer
= zone
->server
;
6132 if (zoneServer
!= mDNSNULL
) {
6133 LogMsg("GetConnectionToDNSPushNotificationServer: server compare server %##s question %##s",
6134 &zoneServer
->serverName
, &q
->nta
->Host
);
6135 if (SameDomainName(&q
->nta
->Host
, &zoneServer
->serverName
))
6137 LogMsg("GetConnectionToDNSPushNotificationServer: server and zone already present.");
6138 zone
->numberOfQuestions
++;
6139 zoneServer
->numberOfQuestions
++;
6146 // If we have a connection to this server but it is for a differnt zone, create a new zone entry and reuse the connection
6147 for (server
= m
->DNSPushServers
; server
!= mDNSNULL
; server
= server
->next
)
6149 LogMsg("GetConnectionToDNSPushNotificationServer: server compare server %##s question %##s",
6150 &server
->serverName
, &q
->nta
->Host
);
6151 if (SameDomainName(&q
->nta
->Host
, &server
->serverName
))
6153 newZone
= (DNSPushNotificationZone
*) mDNSPlatformMemAllocateClear(sizeof(*newZone
));
6154 if (newZone
== NULL
)
6158 newZone
->numberOfQuestions
= 1;
6159 newZone
->zoneName
= q
->nta
->ChildName
;
6160 newZone
->server
= server
;
6162 // Add the new zone to the begining of the list
6163 newZone
->next
= m
->DNSPushZones
;
6164 m
->DNSPushZones
= newZone
;
6166 server
->numberOfQuestions
++;
6167 LogMsg("GetConnectionToDNSPushNotificationServer: server already present.");
6172 // If we do not have any existing connections, create a new connection
6173 newServer
= (DNSPushNotificationServer
*) mDNSPlatformMemAllocateClear(sizeof(*newServer
));
6174 if (newServer
== NULL
)
6178 newZone
= (DNSPushNotificationZone
*) mDNSPlatformMemAllocateClear(sizeof(*newZone
));
6179 if (newZone
== NULL
)
6181 mDNSPlatformMemFree(newServer
);
6186 newServer
->numberOfQuestions
= 1;
6187 AssignDomainName(&newServer
->serverName
, &q
->nta
->Host
);
6188 newServer
->port
= q
->nta
->Port
;
6189 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
6190 mdns_replace(&newServer
->dnsservice
, q
->dnsservice
);
6192 newServer
->qDNSServer
= q
->qDNSServer
;
6194 ConvertDomainNameToCString(&newServer
->serverName
, name
);
6195 newServer
->connection
= dso_create(mDNSfalse
, 10, name
, DNSPushDSOCallback
, newServer
, NULL
);
6196 if (newServer
->connection
== NULL
)
6198 mDNSPlatformMemFree(newServer
);
6199 mDNSPlatformMemFree(newZone
);
6202 newServer
->connectInfo
= dso_connect_state_create(name
, mDNSNULL
, newServer
->port
, 10,
6203 AbsoluteMaxDNSMessageData
, AbsoluteMaxDNSMessageData
,
6204 DNSPushDSOCallback
, newServer
->connection
, newServer
, "GetDSOConnectionToPushServer");
6205 if (newServer
->connectInfo
)
6207 dso_connect_state_use_tls(newServer
->connectInfo
);
6208 DNSPushStartConnecting(newServer
);
6212 newServer
->connectState
= DNSPushServerConnectFailed
;
6214 newZone
->numberOfQuestions
= 1;
6215 newZone
->zoneName
= q
->nta
->ChildName
;
6216 newZone
->server
= newServer
;
6218 // Add the new zone to the begining of the list
6219 newZone
->next
= m
->DNSPushZones
;
6220 m
->DNSPushZones
= newZone
;
6222 newServer
->next
= m
->DNSPushServers
;
6223 m
->DNSPushServers
= newServer
;
6224 LogMsg("GetConnectionToDNSPushNotificationServer: allocated new server.");
6229 DNSPushNotificationServer
*SubscribeToDNSPushNotificationServer(mDNS
*m
, DNSQuestion
*q
)
6231 DNSPushNotificationServer
*server
= GetConnectionToDNSPushNotificationServer(m
, q
);
6232 char name
[MAX_ESCAPED_DOMAIN_NAME
+ 9]; // type(hex)+class(hex)+name
6233 dso_activity_t
*activity
;
6234 if (server
== mDNSNULL
) return server
;
6236 // Now we have a connection to a push notification server. It may be pending, or it may be active,
6237 // but either way we can add a DNS Push subscription to the server object.
6238 mDNS_snprintf(name
, sizeof name
, "%04x%04x", q
->qtype
, q
->qclass
);
6239 ConvertDomainNameToCString(&q
->qname
, &name
[8]);
6240 activity
= dso_add_activity(server
->connection
, name
, kDNSPushActivity_Subscription
, q
, mDNSNULL
);
6241 if (activity
== mDNSNULL
)
6243 LogInfo("SubscribeToDNSPushNotificationServer: failed to add question %##s", &q
->qname
);
6246 // If we're already connected, send the subscribe request immediately.
6247 if (server
->connectState
== DNSPushServerConnected
|| server
->connectState
== DNSPushServerSessionEstablished
)
6249 DNSPushNotificationSendSubscriptionChange(mDNStrue
, server
->connection
, q
);
6254 mDNSexport
void DiscoverDNSPushNotificationServer(mDNS
*m
, DNSQuestion
*q
)
6256 LogInfo("DiscoverDNSPushNotificationServer: StartGetZoneData for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6257 q
->ThisQInterval
= LLQ_POLL_INTERVAL
+ mDNSRandom(LLQ_POLL_INTERVAL
/10); // Retry in approx 15 minutes
6258 q
->LastQTime
= m
->timenow
;
6259 SetNextQueryTime(m
, q
);
6260 if (q
->nta
) CancelGetZoneData(m
, q
->nta
);
6261 q
->nta
= StartGetZoneData(m
, &q
->qname
, ZoneServiceDNSPush
, DNSPushNotificationGotZoneData
, q
);
6262 q
->state
= LLQ_DNSPush_ServerDiscovery
;
6265 mDNSexport
void UnSubscribeToDNSPushNotificationServer(mDNS
*m
, DNSQuestion
*q
)
6267 dso_activity_t
*activity
;
6269 if (q
->dnsPushServer
!= mDNSNULL
)
6271 if (q
->dnsPushServer
->connection
!= mDNSNULL
)
6273 if (q
->dnsPushServer
->connectState
== DNSPushServerSessionEstablished
||
6274 q
->dnsPushServer
->connectState
== DNSPushServerConnected
)
6276 // Ignore any response we get to a pending subscribe.
6277 dso_ignore_response(q
->dnsPushServer
->connection
, q
);
6278 DNSPushNotificationSendSubscriptionChange(mDNSfalse
, q
->dnsPushServer
->connection
, q
);
6280 // activities linger even if we are not connected.
6281 activity
= dso_find_activity(q
->dnsPushServer
->connection
, mDNSNULL
, kDNSPushActivity_Subscription
, q
);
6282 if (activity
!= mDNSNULL
) {
6283 dso_drop_activity(q
->dnsPushServer
->connection
, activity
);
6286 DNSPushReconcileConnection(m
, q
);
6288 // We let the DSO Idle mechanism clean up the connection to the server.
6290 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
6292 #if COMPILER_LIKES_PRAGMA_MARK
6295 #else // !UNICAST_DISABLED
6297 mDNSexport
const domainname
*GetServiceTarget(mDNS
*m
, AuthRecord
*const rr
)
6305 mDNSexport DomainAuthInfo
*GetAuthInfoForName_internal(mDNS
*m
, const domainname
*const name
)
6313 mDNSexport DomainAuthInfo
*GetAuthInfoForQuestion(mDNS
*m
, const DNSQuestion
*const q
)
6321 mDNSexport
void startLLQHandshake(mDNS
*m
, DNSQuestion
*q
)
6327 mDNSexport
void DisposeTCPConn(struct tcpInfo_t
*tcp
)
6332 mDNSexport mStatus
mDNS_StartNATOperation_internal(mDNS
*m
, NATTraversalInfo
*traversal
)
6337 return mStatus_UnsupportedErr
;
6340 mDNSexport mStatus
mDNS_StopNATOperation_internal(mDNS
*m
, NATTraversalInfo
*traversal
)
6345 return mStatus_UnsupportedErr
;
6348 mDNSexport
void sendLLQRefresh(mDNS
*m
, DNSQuestion
*q
)
6354 mDNSexport ZoneData
*StartGetZoneData(mDNS
*const m
, const domainname
*const name
, const ZoneService target
, ZoneDataCallback callback
, void *ZoneDataContext
)
6360 (void) ZoneDataContext
;
6365 mDNSexport
void RecordRegistrationGotZoneData(mDNS
*const m
, mStatus err
, const ZoneData
*zoneData
)
6372 mDNSexport uDNS_LLQType
uDNS_recvLLQResponse(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
6373 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, DNSQuestion
**matchQuestion
)
6380 (void) matchQuestion
;
6382 return uDNS_LLQ_Not
;
6385 mDNSexport
void PenalizeDNSServer(mDNS
*const m
, DNSQuestion
*q
, mDNSOpaque16 responseFlags
)
6389 (void) responseFlags
;
6392 mDNSexport
void mDNS_AddSearchDomain(const domainname
*const domain
, mDNSInterfaceID InterfaceID
)
6398 mDNSexport
void RetrySearchDomainQuestions(mDNS
*const m
)
6403 mDNSexport mStatus
mDNS_SetSecretForDomain(mDNS
*m
, DomainAuthInfo
*info
, const domainname
*domain
, const domainname
*keyname
, const char *b64keydata
, const domainname
*hostname
, mDNSIPPort
*port
)
6413 return mStatus_UnsupportedErr
;
6416 mDNSexport domainname
*uDNS_GetNextSearchDomain(mDNSInterfaceID InterfaceID
, mDNSs8
*searchIndex
, mDNSBool ignoreDotLocal
)
6420 (void) ignoreDotLocal
;
6425 mDNSexport DomainAuthInfo
*GetAuthInfoForName(mDNS
*m
, const domainname
*const name
)
6433 mDNSexport mStatus
mDNS_StartNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
)
6438 return mStatus_UnsupportedErr
;
6441 mDNSexport mStatus
mDNS_StopNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
)
6446 return mStatus_UnsupportedErr
;
6449 mDNSexport DNSServer
*mDNS_AddDNSServer(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, const mDNSs32 serviceID
, const mDNSAddr
*addr
,
6450 const mDNSIPPort port
, ScopeType scopeType
, mDNSu32 timeout
, mDNSBool isCell
, mDNSBool isExpensive
, mDNSBool isConstrained
, mDNSBool isCLAT46
,
6451 mDNSu32 resGroupID
, mDNSBool reqA
, mDNSBool reqAAAA
, mDNSBool reqDO
)
6464 (void) isConstrained
;
6473 mDNSexport
void uDNS_SetupWABQueries(mDNS
*const m
)
6478 mDNSexport
void uDNS_StartWABQueries(mDNS
*const m
, int queryType
)
6484 mDNSexport
void uDNS_StopWABQueries(mDNS
*const m
, int queryType
)
6490 mDNSexport
void mDNS_AddDynDNSHostName(mDNS
*m
, const domainname
*fqdn
, mDNSRecordCallback
*StatusCallback
, const void *StatusContext
)
6494 (void) StatusCallback
;
6495 (void) StatusContext
;
6497 mDNSexport
void mDNS_SetPrimaryInterfaceInfo(mDNS
*m
, const mDNSAddr
*v4addr
, const mDNSAddr
*v6addr
, const mDNSAddr
*router
)
6505 mDNSexport
void mDNS_RemoveDynDNSHostName(mDNS
*m
, const domainname
*fqdn
)
6511 mDNSexport
void RecreateNATMappings(mDNS
*const m
, const mDNSu32 waitTicks
)
6517 mDNSexport mDNSBool
IsGetZoneDataQuestion(DNSQuestion
*q
)
6524 mDNSexport
void SubscribeToDNSPushNotificationServer(mDNS
*m
, DNSQuestion
*q
)
6530 mDNSexport
void UnSubscribeToDNSPushNotificationServer(mDNS
*m
, DNSQuestion
*q
)
6536 mDNSexport
void DiscoverDNSPushNotificationServer(mDNS
*m
, DNSQuestion
*q
)
6542 #endif // !UNICAST_DISABLED
6548 // c-file-style: "bsd"
6549 // c-basic-offset: 4
6551 // indent-tabs-mode: nil