1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
3 * Copyright (c) 2002-2019 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * This code is completely 100% portable C. It does not depend on any external header files
18 * from outside the mDNS project -- all the types it expects to find are defined right here.
20 * The previous point is very important: This file does not depend on any external
21 * header files. It should compile on *any* platform that has a C compiler, without
22 * making *any* assumptions about availability of so-called "standard" C functions,
23 * routines, or types (which may or may not be present on any given platform).
26 #include "DNSCommon.h" // Defines general DNS utility routines
27 #include "uDNS.h" // Defines entry points into unicast-specific routines
31 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
35 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
36 #include "SymptomReporter.h"
39 // Disable certain benign warnings with Microsoft compilers
40 #if (defined(_MSC_VER))
41 // Disable "conditional expression is constant" warning for debug macros.
42 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
43 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
44 #pragma warning(disable:4127)
46 // Disable "assignment within conditional expression".
47 // Other compilers understand the convention that if you place the assignment expression within an extra pair
48 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
49 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
50 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
51 #pragma warning(disable:4706)
54 #include "dns_sd.h" // for kDNSServiceFlags* definitions
55 #include "dns_sd_internal.h"
57 #if APPLE_OSX_mDNSResponder
58 // Delay in seconds before disabling multicast after there are no active queries or registrations.
59 #define BONJOUR_DISABLE_DELAY 60
62 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
63 #include <WebFilterDNS/WebFilterDNS.h>
65 WCFConnection
*WCFConnectionNew(void) __attribute__((weak_import
));
66 void WCFConnectionDealloc(WCFConnection
* c
) __attribute__((weak_import
));
69 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
73 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
77 // Forward declarations
78 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
);
79 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
);
80 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
);
81 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
);
82 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
);
83 mDNSlocal
void CheckForDNSSECRecords(mDNS
*const m
, DNSQuestion
*q
);
84 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
);
85 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
,
86 mDNSu32
*seq
, mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
);
88 typedef mDNSu32 DeadvertiseFlags
;
89 #define kDeadvertiseFlag_NormalHostname (1U << 0)
90 #define kDeadvertiseFlag_RandHostname (1U << 1)
91 #define kDeadvertiseFlag_All (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname)
93 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, DeadvertiseFlags flags
);
94 mDNSlocal
void AdvertiseInterfaceIfNeeded(mDNS
*const m
, NetworkInterfaceInfo
*set
);
95 mDNSlocal
void FreeNSECRecords(mDNS
*const m
, CacheRecord
*NSECRecords
);
96 mDNSlocal
void mDNSParseNSEC3Records(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
97 const mDNSInterfaceID InterfaceID
, CacheRecord
**NSEC3Records
);
98 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
);
100 // ***************************************************************************
101 #if COMPILER_LIKES_PRAGMA_MARK
102 #pragma mark - Program Constants
105 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
106 #define MDNS_TRACER 1
108 // Any records bigger than this are considered 'large' records
109 #define SmallRecordLimit 1024
111 #define kMaxUpdateCredits 10
112 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
114 // define special NR_AnswerTo values
115 #define NR_AnswerMulticast (mDNSu8*)~0
116 #define NR_AnswerUnicast (mDNSu8*)~1
118 // Question default timeout values
119 #define DEFAULT_MCAST_TIMEOUT 5
120 #define DEFAULT_LO_OR_P2P_TIMEOUT 5
122 // The code (see SendQueries() and BuildQuestion()) needs to have the
123 // RequestUnicast value set to a value one greater than the number of times you want the query
124 // sent with the "request unicast response" (QU) bit set.
125 #define SET_QU_IN_FIRST_QUERY 2
126 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
128 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
129 #define DARK_WAKE_DELAY_SLEEP 5
130 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
132 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
133 #define MAX_CONFLICT_PROCESSING_DELAYS 3
135 // RFC 6762 defines Passive Observation Of Failures (POOF)
137 // A host observes the multicast queries issued by the other hosts on
138 // the network. One of the major benefits of also sending responses
139 // using multicast is that it allows all hosts to see the responses
140 // (or lack thereof) to those queries.
142 // If a host sees queries, for which a record in its cache would be
143 // expected to be given as an answer in a multicast response, but no
144 // such answer is seen, then the host may take this as an indication
145 // that the record may no longer be valid.
147 // After seeing two or more of these queries, and seeing no multicast
148 // response containing the expected answer within ten seconds, then even
149 // though its TTL may indicate that it is not yet due to expire, that
150 // record SHOULD be flushed from the cache.
152 // <https://tools.ietf.org/html/rfc6762#section-10.5>
154 #define POOF_ENABLED 1
156 mDNSexport
const char *const mDNS_DomainTypeNames
[] =
158 "b._dns-sd._udp.", // Browse
159 "db._dns-sd._udp.", // Default Browse
160 "lb._dns-sd._udp.", // Automatic Browse
161 "r._dns-sd._udp.", // Registration
162 "dr._dns-sd._udp." // Default Registration
165 #ifdef UNICAST_DISABLED
166 #define uDNS_IsActiveQuery(q, u) mDNSfalse
169 // ***************************************************************************
170 #if COMPILER_LIKES_PRAGMA_MARK
172 #pragma mark - General Utility Functions
175 #if MDNS_MALLOC_DEBUGGING
176 // When doing memory allocation debugging, this function traverses all lists in the mDNS query
177 // structures and caches and checks each entry in the list to make sure it's still good.
178 mDNSlocal
void mDNS_ValidateLists(void *context
)
181 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
182 mDNSu32 NumAllInterfaceRecords
= 0;
183 mDNSu32 NumAllInterfaceQuestions
= 0;
186 // Check core mDNS lists
188 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
190 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
191 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
192 if (rr
->resrec
.name
!= &rr
->namestorage
)
193 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
194 rr
, rr
->resrec
.name
->c
, rr
->namestorage
.c
, rr
->namestorage
.c
);
195 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
196 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
200 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
)
202 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
203 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
204 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
205 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
209 rr
= m
->NewLocalRecords
;
211 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
212 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
214 rr
= m
->CurrentRecord
;
216 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
217 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
220 for (q
= m
->Questions
; q
; q
=q
->next
)
222 if (q
->next
== (DNSQuestion
*)~0 || q
->ThisQInterval
== (mDNSs32
) ~0)
223 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q
, q
->ThisQInterval
, q
->next
);
224 if (q
->DuplicateOf
&& q
->LocalSocket
)
225 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
226 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
227 if (!LocalOnlyOrP2PInterface(q
->InterfaceID
) && mDNSOpaque16IsZero(q
->TargetQID
))
228 NumAllInterfaceQuestions
++;
235 FORALL_CACHERECORDS(slot
, cg
, cr
)
237 if (cr
->resrec
.RecordType
== 0 || cr
->resrec
.RecordType
== 0xFF)
238 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot
, cr
, cr
->resrec
.RecordType
);
239 if (cr
->CRActiveQuestion
)
241 for (q
= m
->Questions
; q
; q
=q
->next
) if (q
== cr
->CRActiveQuestion
) break;
242 if (!q
) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot
, cr
->CRActiveQuestion
, CRDisplayString(m
, cr
));
246 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
247 if (m
->NumAllInterfaceRecords
!= NumAllInterfaceRecords
)
248 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m
->NumAllInterfaceRecords
, NumAllInterfaceRecords
);
250 if (m
->NumAllInterfaceQuestions
!= NumAllInterfaceQuestions
)
251 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m
->NumAllInterfaceQuestions
, NumAllInterfaceQuestions
);
252 #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
254 #endif // MDNS_MALLOC_DEBUGGING
256 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
257 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
258 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
259 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
260 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
261 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
262 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
263 (rr)->resrec.rrtype == kDNSType_CNAME || \
264 (rr)->resrec.rrtype == kDNSType_PTR))
266 mDNSlocal
void SetNextQueryStopTime(mDNS
*const m
, const DNSQuestion
*const q
)
270 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
271 m
->NextScheduledStopTime
= q
->StopTime
;
274 mDNSexport
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
278 if (ActiveQuestion(q
))
280 // Depending on whether this is a multicast or unicast question we want to set either:
281 // m->NextScheduledQuery = NextQSendTime(q) or
282 // m->NextuDNSEvent = NextQSendTime(q)
283 mDNSs32
*const timer
= mDNSOpaque16IsZero(q
->TargetQID
) ? &m
->NextScheduledQuery
: &m
->NextuDNSEvent
;
284 if (*timer
- NextQSendTime(q
) > 0)
285 *timer
= NextQSendTime(q
);
289 mDNSlocal
void ReleaseAuthEntity(AuthHash
*r
, AuthEntity
*e
)
291 #if MDNS_MALLOC_DEBUGGING >= 1
293 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
295 e
->next
= r
->rrauth_free
;
297 r
->rrauth_totalused
--;
300 mDNSlocal
void ReleaseAuthGroup(AuthHash
*r
, AuthGroup
**cp
)
302 AuthEntity
*e
= (AuthEntity
*)(*cp
);
303 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp
)->name
->c
);
304 if ((*cp
)->rrauth_tail
!= &(*cp
)->members
)
305 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
306 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
307 (*cp
)->name
= mDNSNULL
;
308 *cp
= (*cp
)->next
; // Cut record from list
309 ReleaseAuthEntity(r
, e
);
312 mDNSlocal AuthEntity
*GetAuthEntity(AuthHash
*r
, const AuthGroup
*const PreserveAG
)
314 AuthEntity
*e
= mDNSNULL
;
316 if (r
->rrauth_lock
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
321 // We allocate just one AuthEntity at a time because we need to be able
322 // free them all individually which normally happens when we parse /etc/hosts into
323 // AuthHash where we add the "new" entries and discard (free) the already added
324 // entries. If we allocate as chunks, we can't free them individually.
325 AuthEntity
*storage
= (AuthEntity
*) mDNSPlatformMemAllocateClear(sizeof(*storage
));
326 storage
->next
= mDNSNULL
;
327 r
->rrauth_free
= storage
;
330 // If we still have no free records, recycle all the records we can.
331 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
334 mDNSu32 oldtotalused
= r
->rrauth_totalused
;
336 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
338 AuthGroup
**cp
= &r
->rrauth_hash
[slot
];
341 if ((*cp
)->members
|| (*cp
)==PreserveAG
) cp
=&(*cp
)->next
;
342 else ReleaseAuthGroup(r
, cp
);
345 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
346 oldtotalused
- r
->rrauth_totalused
, oldtotalused
, r
->rrauth_totalused
);
349 if (r
->rrauth_free
) // If there are records in the free list, take one
352 r
->rrauth_free
= e
->next
;
353 if (++r
->rrauth_totalused
>= r
->rrauth_report
)
355 LogInfo("RR Auth now using %ld objects", r
->rrauth_totalused
);
356 if (r
->rrauth_report
< 100) r
->rrauth_report
+= 10;
357 else if (r
->rrauth_report
< 1000) r
->rrauth_report
+= 100;
358 else r
->rrauth_report
+= 1000;
360 mDNSPlatformMemZero(e
, sizeof(*e
));
368 mDNSexport AuthGroup
*AuthGroupForName(AuthHash
*r
, const mDNSu32 namehash
, const domainname
*const name
)
371 const mDNSu32 slot
= namehash
% AUTH_HASH_SLOTS
;
373 for (ag
= r
->rrauth_hash
[slot
]; ag
; ag
=ag
->next
)
374 if (ag
->namehash
== namehash
&& SameDomainName(ag
->name
, name
))
379 mDNSexport AuthGroup
*AuthGroupForRecord(AuthHash
*r
, const ResourceRecord
*const rr
)
381 return(AuthGroupForName(r
, rr
->namehash
, rr
->name
));
384 mDNSlocal AuthGroup
*GetAuthGroup(AuthHash
*r
, const ResourceRecord
*const rr
)
386 mDNSu16 namelen
= DomainNameLength(rr
->name
);
387 AuthGroup
*ag
= (AuthGroup
*)GetAuthEntity(r
, mDNSNULL
);
388 const mDNSu32 slot
= rr
->namehash
% AUTH_HASH_SLOTS
;
389 if (!ag
) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
390 ag
->next
= r
->rrauth_hash
[slot
];
391 ag
->namehash
= rr
->namehash
;
392 ag
->members
= mDNSNULL
;
393 ag
->rrauth_tail
= &ag
->members
;
394 ag
->NewLocalOnlyRecords
= mDNSNULL
;
395 if (namelen
> sizeof(ag
->namestorage
))
396 ag
->name
= (domainname
*) mDNSPlatformMemAllocate(namelen
);
398 ag
->name
= (domainname
*)ag
->namestorage
;
401 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
402 ReleaseAuthEntity(r
, (AuthEntity
*)ag
);
405 AssignDomainName(ag
->name
, rr
->name
);
407 if (AuthGroupForRecord(r
, rr
)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr
->name
->c
);
408 r
->rrauth_hash
[slot
] = ag
;
409 if (AuthGroupForRecord(r
, rr
) != ag
) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr
->name
->c
);
414 // Returns the AuthGroup in which the AuthRecord was inserted
415 mDNSexport AuthGroup
*InsertAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
420 ag
= AuthGroupForRecord(r
, &rr
->resrec
);
421 if (!ag
) ag
= GetAuthGroup(r
, &rr
->resrec
); // If we don't have a AuthGroup for this name, make one now
424 *(ag
->rrauth_tail
) = rr
; // Append this record to tail of cache slot list
425 ag
->rrauth_tail
= &(rr
->next
); // Advance tail pointer
430 mDNSexport AuthGroup
*RemoveAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
435 a
= AuthGroupForRecord(r
, &rr
->resrec
);
436 if (!a
) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m
, rr
)); return mDNSNULL
; }
444 // We don't break here, so that we can set the tail below without tracking "prev" pointers
446 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m
, rr
));
447 *rp
= (*rp
)->next
; // Cut record from list
450 // TBD: If there are no more members, release authgroup ?
455 mDNSexport CacheGroup
*CacheGroupForName(const mDNS
*const m
, const mDNSu32 namehash
, const domainname
*const name
)
458 mDNSu32 slot
= HashSlotFromNameHash(namehash
);
459 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
460 if (cg
->namehash
== namehash
&& SameDomainName(cg
->name
, name
))
465 mDNSlocal CacheGroup
*CacheGroupForRecord(const mDNS
*const m
, const ResourceRecord
*const rr
)
467 return(CacheGroupForName(m
, rr
->namehash
, rr
->name
));
470 mDNSexport mDNSBool
mDNS_AddressIsLocalSubnet(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, const mDNSAddr
*addr
)
472 NetworkInterfaceInfo
*intf
;
474 if (addr
->type
== mDNSAddrType_IPv4
)
476 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
477 if (mDNSv4AddressIsLinkLocal(&addr
->ip
.v4
)) return(mDNStrue
);
478 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
479 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
480 if (((intf
->ip
.ip
.v4
.NotAnInteger
^ addr
->ip
.v4
.NotAnInteger
) & intf
->mask
.ip
.v4
.NotAnInteger
) == 0)
484 if (addr
->type
== mDNSAddrType_IPv6
)
486 if (mDNSv6AddressIsLinkLocal(&addr
->ip
.v6
)) return(mDNStrue
);
487 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
488 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
489 if ((((intf
->ip
.ip
.v6
.l
[0] ^ addr
->ip
.v6
.l
[0]) & intf
->mask
.ip
.v6
.l
[0]) == 0) &&
490 (((intf
->ip
.ip
.v6
.l
[1] ^ addr
->ip
.v6
.l
[1]) & intf
->mask
.ip
.v6
.l
[1]) == 0) &&
491 (((intf
->ip
.ip
.v6
.l
[2] ^ addr
->ip
.v6
.l
[2]) & intf
->mask
.ip
.v6
.l
[2]) == 0) &&
492 (((intf
->ip
.ip
.v6
.l
[3] ^ addr
->ip
.v6
.l
[3]) & intf
->mask
.ip
.v6
.l
[3]) == 0))
499 mDNSlocal NetworkInterfaceInfo
*FirstInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
501 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
502 while (intf
&& intf
->InterfaceID
!= InterfaceID
) intf
= intf
->next
;
506 mDNSlocal NetworkInterfaceInfo
*FirstIPv4LLInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
508 NetworkInterfaceInfo
*intf
;
513 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
514 // we still want to find the first IPv4 Link-Local interface
515 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
517 if (intf
->InterfaceID
== InterfaceID
&&
518 intf
->ip
.type
== mDNSAddrType_IPv4
&& mDNSv4AddressIsLinkLocal(&intf
->ip
.ip
.v4
))
520 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf
->ip
.ip
.v4
);
527 mDNSexport
char *InterfaceNameForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
529 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
530 return(intf
? intf
->ifname
: mDNSNULL
);
533 // Caller should hold the lock
534 mDNSlocal
void GenerateNegativeResponseEx(mDNS
*const m
, mDNSInterfaceID InterfaceID
, QC_result qc
, mDNSBool noData
)
537 if (!m
->CurrentQuestion
) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
538 q
= m
->CurrentQuestion
;
539 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
540 "[R%d->Q%d] GenerateNegativeResponse: Generating negative response for question " PRI_DM_NAME
" (" PUB_S
")",
541 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
543 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, InterfaceID
, mDNSNULL
);
544 m
->rec
.r
.resrec
.negativeRecordType
= noData
? kNegativeRecordType_NoData
: kNegativeRecordType_Unspecified
;
546 // We need to force the response through in the following cases
548 // a) SuppressUnusable questions that are suppressed
549 // b) Append search domains and retry the question
551 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
552 // through we use "QC_forceresponse".
553 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, qc
);
554 if (m
->CurrentQuestion
== q
) { q
->ThisQInterval
= 0; } // Deactivate this question
555 // Don't touch the question after this
556 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
558 #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse)
560 mDNSexport
void AnswerQuestionByFollowingCNAME(mDNS
*const m
, DNSQuestion
*q
, ResourceRecord
*rr
)
562 const mDNSBool selfref
= SameDomainName(&q
->qname
, &rr
->rdata
->u
.name
);
563 if (q
->CNAMEReferrals
>= 10 || selfref
)
565 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
566 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME
" (" PUB_S
") NOT following CNAME referral %d" PUB_S
" for " PRI_S
,
567 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
),
568 q
->CNAMEReferrals
, selfref
? " (Self-Referential)" : "", RRDisplayString(m
, rr
));
573 const mDNSu32 c
= q
->CNAMEReferrals
+ 1; // Stash a copy of the new q->CNAMEReferrals value
574 UDPSocket
*sock
= q
->LocalSocket
;
575 mDNSOpaque16 id
= q
->TargetQID
;
576 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
580 q
->LocalSocket
= mDNSNULL
;
582 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
583 // themselves. Without that check we can get into a case where we have two duplicate questions,
584 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
585 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
586 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
587 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
588 // for either of them. This is not a problem for CNAME loops of two or more records because in
589 // those cases the newly re-appended question A has a different target name and therefore cannot be
590 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
592 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
593 // and track CNAMEs coming and going, we should really create a subordinate query here,
594 // which we would subsequently cancel and retract if the CNAME referral record were removed.
595 // In reality this is such a corner case we'll ignore it until someone actually needs it.
597 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
598 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME
" (" PUB_S
") following CNAME referral %d for " PRI_S
,
599 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
),
600 q
->CNAMEReferrals
, RRDisplayString(m
, rr
));
602 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
603 if ((q
->CNAMEReferrals
== 0) && !q
->metrics
.originalQName
)
608 qNameLen
= DomainNameLength(&q
->qname
);
609 if ((qNameLen
> 0) && (qNameLen
<= MAX_DOMAIN_NAME
))
611 qName
= (domainname
*) mDNSPlatformMemAllocate(qNameLen
);
614 mDNSPlatformMemCopy(qName
->c
, q
->qname
.c
, qNameLen
);
615 q
->metrics
.originalQName
= qName
;
619 metrics
= q
->metrics
;
620 mDNSPlatformMemZero(&q
->metrics
, sizeof(q
->metrics
));
622 mDNS_StopQuery_internal(m
, q
); // Stop old query
623 AssignDomainName(&q
->qname
, &rr
->rdata
->u
.name
); // Update qname
624 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
625 // If a unicast query results in a CNAME that points to a .local, we need to re-try
626 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
627 // to try this as unicast query even though it is a .local name
628 if (!mDNSOpaque16IsZero(q
->TargetQID
) && IsLocalDomain(&q
->qname
))
630 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
631 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p " PRI_DM_NAME
" (" PUB_S
") Record " PRI_S
,
632 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
), RRDisplayString(m
, rr
));
633 q
->IsUnicastDotLocal
= mDNStrue
;
635 mDNS_StartQuery_internal(m
, q
); // start new query
636 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
637 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
638 q
->CNAMEReferrals
= c
;
639 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
640 metrics
.expiredAnswerState
= q
->metrics
.expiredAnswerState
; // We want the newly initialized state for this value
641 metrics
.dnsOverTCPState
= q
->metrics
.dnsOverTCPState
; // We want the newly initialized state for this value
642 q
->metrics
= metrics
;
646 // If our new query is a duplicate, then it can't have a socket of its own, so we have to close the one we saved.
647 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
650 // Transplant the old socket into the new question, and copy the query ID across too.
651 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
652 q
->LocalSocket
= sock
;
661 #include <unicode/uidna.h>
663 // #define DEBUG_PUNYCODE 1
665 mDNSlocal mDNSu8
*PunycodeConvert(const mDNSu8
*const src
, mDNSu8
*const dst
, const mDNSu8
*const end
)
667 UErrorCode errorCode
= U_ZERO_ERROR
;
668 UIDNAInfo info
= UIDNA_INFO_INITIALIZER
;
669 UIDNA
*uts46
= uidna_openUTS46(UIDNA_USE_STD3_RULES
|UIDNA_NONTRANSITIONAL_TO_UNICODE
, &errorCode
);
670 int32_t len
= uidna_nameToASCII_UTF8(uts46
, (const char *)src
+1, src
[0], (char *)dst
+1, end
-(dst
+1), &info
, &errorCode
);
673 if (errorCode
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src
, errorCode
);
674 if (info
.errors
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src
, info
.errors
);
675 if (len
> MAX_DOMAIN_LABEL
) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src
, len
);
677 if (errorCode
|| info
.errors
|| len
> MAX_DOMAIN_LABEL
) return mDNSNULL
;
679 return(dst
+ 1 + len
);
682 mDNSlocal mDNSBool
IsHighASCIILabel(const mDNSu8
*d
)
685 for (i
=1; i
<=d
[0]; i
++) if (d
[i
] & 0x80) return mDNStrue
;
689 mDNSlocal
const mDNSu8
*FindLastHighASCIILabel(const domainname
*const d
)
691 const mDNSu8
*ptr
= d
->c
;
692 const mDNSu8
*ans
= mDNSNULL
;
695 const mDNSu8
*const next
= ptr
+ 1 + ptr
[0];
696 if (ptr
[0] > MAX_DOMAIN_LABEL
|| next
>= d
->c
+ MAX_DOMAIN_NAME
) return mDNSNULL
;
697 if (IsHighASCIILabel(ptr
)) ans
= ptr
;
703 mDNSlocal mDNSBool
PerformNextPunycodeConversion(const DNSQuestion
*const q
, domainname
*const newname
)
705 const mDNSu8
*h
= FindLastHighASCIILabel(&q
->qname
);
707 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q
->qname
.c
, DNSTypeName(q
->qtype
), h
);
709 if (!h
) return mDNSfalse
; // There are no high-ascii labels to convert
711 mDNSu8
*const dst
= PunycodeConvert(h
, newname
->c
+ (h
- q
->qname
.c
), newname
->c
+ MAX_DOMAIN_NAME
);
713 return mDNSfalse
; // The label was not convertible to Punycode
716 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
717 const mDNSu8
*const src
= h
+ 1 + h
[0];
718 const mDNSu8 remainder
= DomainNameLength((domainname
*)src
);
719 if (dst
+ remainder
> newname
->c
+ MAX_DOMAIN_NAME
) return mDNSfalse
; // Name too long -- cannot be converted to Punycode
721 mDNSPlatformMemCopy(newname
->c
, q
->qname
.c
, h
- q
->qname
.c
); // Fill in the leading part
722 mDNSPlatformMemCopy(dst
, src
, remainder
); // Fill in the trailing part
724 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q
->qname
.c
, newname
->c
);
732 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
733 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
734 mDNSlocal
void AnswerLocalQuestionWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
736 DNSQuestion
*q
= m
->CurrentQuestion
;
737 mDNSBool followcname
;
741 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m
, rr
));
745 followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
747 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
748 if (!(rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
))
750 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
751 AddRecord
? "Add" : "Rmv", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
755 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
756 if (AddRecord
) rr
->AnsweredLocalQ
= mDNStrue
;
757 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
758 if (q
->QuestionCallback
&& !q
->NoAnswer
)
760 q
->CurrentAnswers
+= AddRecord
? 1 : -1;
761 if (UniqueLocalOnlyRecord(rr
))
763 if (!followcname
|| q
->ReturnIntermed
)
765 // Don't send this packet on the wire as we answered from /etc/hosts
766 q
->ThisQInterval
= 0;
767 q
->LOAddressAnswers
+= AddRecord
? 1 : -1;
768 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
770 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
771 // The callback above could have caused the question to stop. Detect that
772 // using m->CurrentQuestion
773 if (followcname
&& m
->CurrentQuestion
== q
)
774 AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
779 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
782 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
785 mDNSlocal
void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*ar
, QC_result AddRecord
)
787 if (m
->CurrentQuestion
)
788 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
789 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
790 m
->CurrentQuestion
= m
->Questions
;
791 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
794 DNSQuestion
*q
= m
->CurrentQuestion
;
796 answered
= AuthRecordAnswersQuestion(ar
, q
);
798 answered
= LocalOnlyRecordAnswersQuestion(ar
, q
);
800 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, AddRecord
); // MUST NOT dereference q again
801 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
802 m
->CurrentQuestion
= q
->next
;
804 m
->CurrentQuestion
= mDNSNULL
;
807 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
808 // delivers the appropriate add/remove events to listening questions:
809 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
810 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
811 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
812 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
813 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
815 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
816 // and by mDNS_Deregister_internal()
818 mDNSlocal
void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*ar
, QC_result AddRecord
)
820 if (m
->CurrentQuestion
)
821 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
822 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
824 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
825 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
828 DNSQuestion
*q
= m
->CurrentQuestion
;
829 // We are called with both LocalOnly/P2P record or a regular AuthRecord
831 answered
= AuthRecordAnswersQuestion(ar
, q
);
833 answered
= LocalOnlyRecordAnswersQuestion(ar
, q
);
835 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, AddRecord
); // MUST NOT dereference q again
836 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
837 m
->CurrentQuestion
= q
->next
;
840 m
->CurrentQuestion
= mDNSNULL
;
842 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
843 if (ar
->ARType
== AuthRecordLocalOnly
|| ar
->ARType
== AuthRecordP2P
)
844 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m
, ar
, AddRecord
);
848 // ***************************************************************************
849 #if COMPILER_LIKES_PRAGMA_MARK
851 #pragma mark - Resource Record Utility Functions
854 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
856 mDNSlocal mDNSBool
ResourceRecordIsValidAnswer(const AuthRecord
*const rr
)
858 if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
) &&
859 ((rr
->Additional1
== mDNSNULL
) || (rr
->Additional1
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)) &&
860 ((rr
->Additional2
== mDNSNULL
) || (rr
->Additional2
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)) &&
861 ((rr
->DependentOn
== mDNSNULL
) || (rr
->DependentOn
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)))
871 mDNSlocal mDNSBool
IsInterfaceValidForAuthRecord(const AuthRecord
*const rr
, const mDNSInterfaceID InterfaceID
)
873 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
875 return mDNSPlatformValidRecordForInterface(rr
, InterfaceID
);
879 return ((rr
->resrec
.InterfaceID
== InterfaceID
) ? mDNStrue
: mDNSfalse
);
883 mDNSlocal mDNSBool
ResourceRecordIsValidInterfaceAnswer(const AuthRecord
*const rr
, const mDNSInterfaceID interfaceID
)
885 return ((IsInterfaceValidForAuthRecord(rr
, interfaceID
) && ResourceRecordIsValidAnswer(rr
)) ? mDNStrue
: mDNSfalse
);
888 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
889 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
891 // Parameters for handling probing conflicts
892 #define kMaxAllowedMCastProbingConflicts 1 // Maximum number of conflicts to allow from mcast messages.
893 #define kProbingConflictPauseDuration mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict.
895 // See RFC 6762: "8.3 Announcing"
896 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
897 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
898 #define InitialAnnounceCount ((mDNSu8)4)
900 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
901 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
902 // and then if the machine fails to wake, 3 goodbye packets).
903 #define GoodbyeCount ((mDNSu8)3)
904 #define WakeupCount ((mDNSu8)18)
905 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
906 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week
908 // Number of wakeups we send if WakeOnResolve is set in the question
909 #define InitialWakeOnResolveCount ((mDNSu8)3)
911 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
912 // This means that because the announce interval is doubled after sending the first packet, the first
913 // observed on-the-wire inter-packet interval between announcements is actually one second.
914 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
915 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
916 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
917 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
919 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
920 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
921 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
923 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
924 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
925 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
927 // Adjustment factor to avoid race condition (used for unicast cache entries) :
928 // Suppose real record has TTL of 3600, and our local caching server has held it for 3500 seconds, so it returns an aged TTL of 100.
929 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
930 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
931 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
932 // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds,
933 // the cached copy at our local caching server will already have expired, so the server will be forced
934 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
936 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
937 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
939 #define MaxUnansweredQueries 4
941 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
942 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
943 // TTL and rdata may differ.
944 // This is used for cache flush management:
945 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
946 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
948 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
950 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
952 mDNSlocal mDNSBool
SameResourceRecordNameClassInterface(const AuthRecord
*const r1
, const AuthRecord
*const r2
)
954 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
955 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
956 if (r1
->resrec
.InterfaceID
&&
957 r2
->resrec
.InterfaceID
&&
958 r1
->resrec
.InterfaceID
!= r2
->resrec
.InterfaceID
) return(mDNSfalse
);
960 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
&&
961 r1
->resrec
.namehash
== r2
->resrec
.namehash
&&
962 SameDomainName(r1
->resrec
.name
, r2
->resrec
.name
));
965 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
966 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
967 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
968 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
969 // so a response of any type should match, even if it is not actually the type the client plans to use.
971 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
972 // and require the rrtypes to match for the rdata to be considered potentially conflicting
973 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
975 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
976 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
977 if (pktrr
->resrec
.InterfaceID
&&
978 authrr
->resrec
.InterfaceID
&&
979 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
980 if (!(authrr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) || authrr
->WakeUp
.HMAC
.l
[0])
981 if (pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
982 if ((authrr
->resrec
.InterfaceID
== mDNSInterface_Any
) &&
983 !mDNSPlatformValidRecordForInterface(authrr
, pktrr
->resrec
.InterfaceID
)) return(mDNSfalse
);
985 pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&&
986 pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&&
987 SameDomainName(pktrr
->resrec
.name
, authrr
->resrec
.name
));
990 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
991 // This is the information that the requester believes to be correct.
992 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
993 // This is the information that we believe to be correct.
994 // We've already determined that we plan to give this answer on this interface
995 // (either the record is non-specific, or it is specific to this interface)
996 // so now we just need to check the name, type, class, rdata and TTL.
997 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
999 // If RR signature is different, or data is different, then don't suppress our answer
1000 if (!IdenticalResourceRecord(&ka
->resrec
, &rr
->resrec
)) return(mDNSfalse
);
1002 // If the requester's indicated TTL is less than half the real TTL,
1003 // we need to give our answer before the requester's copy expires.
1004 // If the requester's indicated TTL is at least half the real TTL,
1005 // then we can suppress our answer this time.
1006 // If the requester's indicated TTL is greater than the TTL we believe,
1007 // then that's okay, and we don't need to do anything about it.
1008 // (If two responders on the network are offering the same information,
1009 // that's okay, and if they are offering the information with different TTLs,
1010 // the one offering the lower TTL should defer to the one offering the higher TTL.)
1011 return (mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
1014 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
1016 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1018 if ((rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
> mDNSPlatformOneSecond
* 10)
1020 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr
->ProbeCount
, (rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
, ARDisplayString(m
, rr
));
1021 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m
->SuppressProbes
, m
->timenow
, m
->SuppressProbes
- m
->timenow
);
1023 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1024 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1025 // Some defensive code:
1026 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
1027 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
1028 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
1029 if (m
->NextScheduledProbe
- m
->timenow
< 0)
1030 m
->NextScheduledProbe
= m
->timenow
;
1032 else if (rr
->AnnounceCount
&& (ResourceRecordIsValidAnswer(rr
) || rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
))
1034 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1035 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1039 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
1041 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
1042 rr
->ThisAPInterval
= rr
->AddressProxy
.type
? mDNSPlatformOneSecond
: DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
1044 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
1045 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
1046 // records that are going to probe, then we delay its first announcement so that it will
1047 // go out synchronized with the first announcement for the other records that *are* probing.
1048 // This is a minor performance tweak that helps keep groups of related records synchronized together.
1049 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
1050 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
1051 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
1052 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
1053 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
1057 rr
->ProbingConflictCount
= 0;
1058 // If we have no probe suppression time set, or it is in the past, set it now
1059 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
1061 // To allow us to aggregate probes when a group of services are registered together,
1062 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
1063 // This means the common-case behaviour is:
1064 // randomized wait; probe
1065 // 1/4 second wait; probe
1066 // 1/4 second wait; probe
1067 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
1068 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
1070 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
1071 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
1072 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledProbe
);
1073 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
1074 m
->SuppressProbes
= m
->timenow
;
1076 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
1077 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
1078 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledQuery
);
1079 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
1080 m
->SuppressProbes
= m
->timenow
;
1082 // except... don't expect to be able to send before the m->SuppressSending timer fires
1083 if (m
->SuppressSending
&& m
->SuppressProbes
- m
->SuppressSending
< 0)
1084 m
->SuppressProbes
= NonZeroTime(m
->SuppressSending
);
1086 if (m
->SuppressProbes
- m
->timenow
> mDNSPlatformOneSecond
* 8)
1088 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
1089 m
->SuppressProbes
- m
->timenow
,
1090 m
->NextScheduledProbe
- m
->timenow
,
1091 m
->NextScheduledQuery
- m
->timenow
,
1093 m
->SuppressSending
- m
->timenow
);
1094 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
1097 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
1099 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
1100 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
1101 else if ((rr
->resrec
.RecordType
!= kDNSRecordTypeKnownUnique
) && (rr
->resrec
.RecordType
!= kDNSRecordTypeShared
) && m
->SuppressProbes
&& (m
->SuppressProbes
- m
->timenow
>= 0))
1102 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
+ DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
1104 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1106 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
1107 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
1108 // After three probes one second apart with no answer, we conclude the client is now sleeping
1109 // and we can begin broadcasting our announcements to take over ownership of that IP address.
1110 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
1111 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
1112 if (rr
->AddressProxy
.type
)
1113 rr
->LastAPTime
= m
->timenow
;
1115 // Set LastMCTime to now, to inhibit multicast responses
1116 // (no need to send additional multicast responses when we're announcing anyway)
1117 rr
->LastMCTime
= m
->timenow
;
1118 rr
->LastMCInterface
= mDNSInterfaceMark
;
1120 SetNextAnnounceProbeTime(m
, rr
);
1123 mDNSlocal
const domainname
*SetUnicastTargetToHostName(mDNS
*const m
, AuthRecord
*rr
)
1125 const domainname
*target
;
1128 rr
->AutoTarget
= Target_AutoHostAndNATMAP
;
1131 target
= GetServiceTarget(m
, rr
);
1132 if (!target
|| target
->c
[0] == 0)
1134 // defer registration until we've got a target
1135 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m
, rr
));
1136 rr
->state
= regState_NoTarget
;
1141 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target
->c
, ARDisplayString(m
,rr
));
1146 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1147 mDNSlocal mDNSBool
AuthRecordIncludesOrIsAWDL(const AuthRecord
*const ar
)
1149 return ((AuthRecordIncludesAWDL(ar
) || mDNSPlatformInterfaceIsAWDL(ar
->resrec
.InterfaceID
)) ? mDNStrue
: mDNSfalse
);
1153 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1154 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1155 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
1157 domainname
*const target
= GetRRDomainNameTarget(&rr
->resrec
);
1158 const domainname
*newname
;
1160 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1161 if (AuthRecordIncludesOrIsAWDL(rr
))
1163 newname
= &m
->RandomizedHostname
;
1168 newname
= &m
->MulticastHostname
;
1170 if (!target
) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr
->resrec
.rrtype
));
1172 if (!(rr
->ForceMCast
|| rr
->ARType
== AuthRecordLocalOnly
|| rr
->ARType
== AuthRecordP2P
|| IsLocalDomain(&rr
->namestorage
)))
1174 const domainname
*const n
= SetUnicastTargetToHostName(m
, rr
);
1176 else { if (target
) target
->c
[0] = 0; SetNewRData(&rr
->resrec
, mDNSNULL
, 0); return; }
1179 if (target
&& SameDomainName(target
, newname
))
1180 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
->c
, target
->c
);
1182 if (target
&& !SameDomainName(target
, newname
))
1184 AssignDomainName(target
, newname
);
1185 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
1187 // If we're in the middle of probing this record, we need to start again,
1188 // because changing its rdata may change the outcome of the tie-breaker.
1189 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1190 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1192 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1193 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1194 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1195 if (rr
->RequireGoodbye
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
1196 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1197 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1199 rr
->AnnounceCount
= InitialAnnounceCount
;
1200 rr
->RequireGoodbye
= mDNSfalse
;
1201 rr
->ProbeRestartCount
= 0;
1202 InitializeLastAPTime(m
, rr
);
1206 mDNSlocal
void AcknowledgeRecord(mDNS
*const m
, AuthRecord
*const rr
)
1208 if (rr
->RecordCallback
)
1210 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1211 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1212 rr
->Acknowledged
= mDNStrue
;
1213 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1214 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
1215 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1219 mDNSexport
void ActivateUnicastRegistration(mDNS
*const m
, AuthRecord
*const rr
)
1221 // Make sure that we don't activate the SRV record and associated service records, if it is in
1222 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1223 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1224 // the target becomes available, the records will be reregistered.
1225 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
1227 AuthRecord
*srvRR
= mDNSNULL
;
1228 if (rr
->resrec
.rrtype
== kDNSType_PTR
)
1229 srvRR
= rr
->Additional1
;
1230 else if (rr
->resrec
.rrtype
== kDNSType_TXT
)
1231 srvRR
= rr
->DependentOn
;
1234 if (srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
1236 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
1240 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1241 ARDisplayString(m
, srvRR
), srvRR
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1242 rr
->state
= srvRR
->state
;
1247 if (rr
->state
== regState_NoTarget
)
1249 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m
, rr
));
1252 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1253 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1254 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1255 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1256 // to sleep, then it is okay to start in Pending state as we will go back to NoTarget state if we don't have a target.
1257 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1259 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m
, rr
), rr
->state
);
1260 rr
->state
= regState_DeregPending
;
1264 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m
, rr
), rr
->state
);
1265 rr
->state
= regState_Pending
;
1267 rr
->ProbingConflictCount
= 0;
1268 rr
->LastConflictPktNum
= 0;
1269 rr
->ProbeRestartCount
= 0;
1271 rr
->AnnounceCount
= 0;
1272 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1273 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1274 rr
->expire
= 0; // Forget about all the leases, start fresh
1275 rr
->uselease
= mDNStrue
;
1276 rr
->updateid
= zeroID
;
1277 rr
->SRVChanged
= mDNSfalse
;
1278 rr
->updateError
= mStatus_NoError
;
1279 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1280 // The records might already be registered with the server and hence could have NAT state.
1281 if (rr
->NATinfo
.clientContext
)
1283 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1284 rr
->NATinfo
.clientContext
= mDNSNULL
;
1286 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
1287 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1288 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1289 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1292 // Two records qualify to be local duplicates if:
1293 // (a) the RecordTypes are the same, or
1294 // (b) one is Unique and the other Verified
1295 // (c) either is in the process of deregistering
1296 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1297 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1298 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1300 #define RecordIsLocalDuplicate(A,B) \
1301 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1303 mDNSlocal AuthRecord
*CheckAuthIdenticalRecord(AuthHash
*r
, AuthRecord
*rr
)
1308 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1309 if (!a
) return mDNSNULL
;
1313 if (!RecordIsLocalDuplicate(rp
, rr
))
1317 if (rp
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1319 rp
->AnnounceCount
= 0;
1328 mDNSlocal mDNSBool
CheckAuthRecordConflict(AuthHash
*r
, AuthRecord
*rr
)
1331 const AuthRecord
*rp
;
1333 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1334 if (!a
) return mDNSfalse
;
1338 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
1339 const AuthRecord
*s2
= rp
->RRSet
? rp
->RRSet
: rp
;
1340 if (s1
!= s2
&& SameResourceRecordSignature(rp
, rr
) && !IdenticalSameNameRecord(&rp
->resrec
, &rr
->resrec
))
1348 // checks to see if "rr" is already present
1349 mDNSlocal AuthRecord
*CheckAuthSameRecord(AuthHash
*r
, AuthRecord
*rr
)
1354 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1355 if (!a
) return mDNSNULL
;
1369 mDNSlocal
void DecrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1371 if (RRLocalOnly(rr
))
1373 // A sanity check, this should be prevented in calling code.
1374 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1378 if (!AuthRecord_uDNS(rr
) && (rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHost
))
1380 NetworkInterfaceInfo
*intf
;
1381 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1382 DeadvertiseFlags flags
= 0; // DeadvertiseFlags for non-AWDL interfaces.
1383 DeadvertiseFlags flagsAWDL
= 0; // DeadvertiseFlags for AWDL interfaces.
1384 if (AuthRecordIncludesOrIsAWDL(rr
))
1386 if (AuthRecordIncludesAWDL(rr
))
1388 m
->AutoTargetAWDLIncludedCount
--;
1389 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1390 "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S
,
1391 m
->AutoTargetAWDLIncludedCount
, ARDisplayString(m
, rr
));
1392 if (m
->AutoTargetAWDLIncludedCount
== 0)
1394 flags
|= kDeadvertiseFlag_RandHostname
;
1395 if (m
->AutoTargetAWDLOnlyCount
== 0) flagsAWDL
|= kDeadvertiseFlag_RandHostname
;
1400 m
->AutoTargetAWDLOnlyCount
--;
1401 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1402 "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S
,
1403 m
->AutoTargetAWDLOnlyCount
, ARDisplayString(m
, rr
));
1404 if ((m
->AutoTargetAWDLIncludedCount
== 0) && (m
->AutoTargetAWDLOnlyCount
== 0))
1406 flagsAWDL
|= kDeadvertiseFlag_RandHostname
;
1409 if (flags
|| flagsAWDL
)
1411 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1413 if (!intf
->Advertise
) continue;
1414 if (mDNSPlatformInterfaceIsAWDL(intf
->InterfaceID
))
1416 if (flagsAWDL
) DeadvertiseInterface(m
, intf
, flagsAWDL
);
1420 if (flags
) DeadvertiseInterface(m
, intf
, flags
);
1424 if ((m
->AutoTargetAWDLIncludedCount
== 0) && (m
->AutoTargetAWDLOnlyCount
== 0))
1426 GetRandomUUIDLocalHostname(&m
->RandomizedHostname
);
1432 m
->AutoTargetServices
--;
1433 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1434 "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S
,
1435 m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1436 if (m
->AutoTargetServices
== 0)
1438 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1440 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
, kDeadvertiseFlag_NormalHostname
);
1446 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1447 if (!AuthRecord_uDNS(rr
))
1449 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1450 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
1451 m
->NumAllInterfaceRecords
--;
1452 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1453 "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S
,
1454 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1459 mDNSlocal
void AdvertiseNecessaryInterfaceRecords(mDNS
*const m
)
1461 NetworkInterfaceInfo
*intf
;
1462 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1464 if (intf
->Advertise
) AdvertiseInterfaceIfNeeded(m
, intf
);
1468 mDNSlocal
void IncrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1470 mDNSBool enablingBonjour
= mDNSfalse
;
1472 if (RRLocalOnly(rr
))
1474 // A sanity check, this should be prevented in calling code.
1475 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1479 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1480 if (!AuthRecord_uDNS(rr
))
1482 m
->NumAllInterfaceRecords
++;
1483 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1484 "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S
,
1485 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1486 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1488 m
->NextBonjourDisableTime
= 0;
1489 if (m
->BonjourEnabled
== 0)
1491 // Enable Bonjour immediately by scheduling network changed processing where
1492 // we will join the multicast group on each active interface.
1493 m
->BonjourEnabled
= 1;
1494 enablingBonjour
= mDNStrue
;
1495 m
->NetworkChanged
= m
->timenow
;
1501 if (!AuthRecord_uDNS(rr
) && (rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHost
))
1503 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1504 if (AuthRecordIncludesAWDL(rr
))
1506 m
->AutoTargetAWDLIncludedCount
++;
1507 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1508 "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S
,
1509 m
->AutoTargetAWDLIncludedCount
, ARDisplayString(m
, rr
));
1511 else if (mDNSPlatformInterfaceIsAWDL(rr
->resrec
.InterfaceID
))
1513 m
->AutoTargetAWDLOnlyCount
++;
1514 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1515 "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S
,
1516 m
->AutoTargetAWDLOnlyCount
, ARDisplayString(m
, rr
));
1521 m
->AutoTargetServices
++;
1522 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1523 "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S
,
1524 m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1526 // If this is the first advertised service and we did not just enable Bonjour above, then
1527 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1528 // be advertised during the network changed processing scheduled above, so no need
1530 if (!enablingBonjour
) AdvertiseNecessaryInterfaceRecords(m
);
1534 mDNSlocal
void getKeepaliveRaddr(mDNS
*const m
, AuthRecord
*rr
, mDNSAddr
*raddr
)
1536 mDNSAddr laddr
= zeroAddr
;
1537 mDNSEthAddr eth
= zeroEthAddr
;
1538 mDNSIPPort lport
= zeroIPPort
;
1539 mDNSIPPort rport
= zeroIPPort
;
1540 mDNSu32 timeout
= 0;
1545 if (mDNS_KeepaliveRecord(&rr
->resrec
))
1547 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
1548 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
1550 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, raddr
, rport
.NotAnInteger
);
1556 // Exported so uDNS.c can call this
1557 mDNSexport mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
1559 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
1561 AuthRecord
**p
= &m
->ResourceRecords
;
1562 AuthRecord
**d
= &m
->DuplicateRecords
;
1564 if ((mDNSs32
)rr
->resrec
.rroriginalttl
<= 0)
1565 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr
->resrec
.rroriginalttl
, ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1567 if (!rr
->resrec
.RecordType
)
1568 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1570 if (m
->ShutdownTime
)
1571 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m
, rr
)); return(mStatus_ServiceNotRunning
); }
1573 if (m
->DivertMulticastAdvertisements
&& !AuthRecord_uDNS(rr
))
1575 mDNSInterfaceID previousID
= rr
->resrec
.InterfaceID
;
1576 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1578 rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
;
1579 rr
->ARType
= AuthRecordLocalOnly
;
1581 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
)
1583 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1584 if (intf
&& !intf
->Advertise
) { rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
; rr
->ARType
= AuthRecordLocalOnly
; }
1586 if (rr
->resrec
.InterfaceID
!= previousID
)
1587 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m
, rr
));
1590 if (RRLocalOnly(rr
))
1592 if (CheckAuthSameRecord(&m
->rrauth
, rr
))
1594 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1595 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1596 return(mStatus_AlreadyRegistered
);
1601 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1604 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1605 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1606 return(mStatus_AlreadyRegistered
);
1610 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
1613 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1614 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1615 return(mStatus_AlreadyRegistered
);
1618 if (rr
->DependentOn
)
1620 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1621 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1622 else if (rr
->resrec
.RecordType
!= kDNSRecordTypeKnownUnique
)
1624 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1625 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1626 return(mStatus_Invalid
);
1628 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
)))
1630 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1631 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
1632 return(mStatus_Invalid
);
1636 rr
->next
= mDNSNULL
;
1638 // Field Group 1: The actual information pertaining to this resource record
1639 // Set up by client prior to call
1641 // Field Group 2: Persistent metadata for Authoritative Records
1642 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1643 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1644 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1645 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1646 // rr->Callback = already set in mDNS_SetupResourceRecord
1647 // rr->Context = already set in mDNS_SetupResourceRecord
1648 // rr->RecordType = already set in mDNS_SetupResourceRecord
1649 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1650 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1651 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1652 if (rr
->AutoTarget
&& target
) target
->c
[0] = 0;
1654 // Field Group 3: Transient state for Authoritative Records
1655 rr
->Acknowledged
= mDNSfalse
;
1656 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1657 rr
->ProbeRestartCount
= 0;
1658 rr
->AnnounceCount
= InitialAnnounceCount
;
1659 rr
->RequireGoodbye
= mDNSfalse
;
1660 rr
->AnsweredLocalQ
= mDNSfalse
;
1661 rr
->IncludeInProbe
= mDNSfalse
;
1662 rr
->ImmedUnicast
= mDNSfalse
;
1663 rr
->SendNSECNow
= mDNSNULL
;
1664 rr
->ImmedAnswer
= mDNSNULL
;
1665 rr
->ImmedAdditional
= mDNSNULL
;
1666 rr
->SendRNow
= mDNSNULL
;
1667 rr
->v4Requester
= zerov4Addr
;
1668 rr
->v6Requester
= zerov6Addr
;
1669 rr
->NextResponse
= mDNSNULL
;
1670 rr
->NR_AnswerTo
= mDNSNULL
;
1671 rr
->NR_AdditionalTo
= mDNSNULL
;
1672 if (!rr
->AutoTarget
) InitializeLastAPTime(m
, rr
);
1673 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1674 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1675 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1676 rr
->NewRData
= mDNSNULL
;
1677 rr
->newrdlength
= 0;
1678 rr
->UpdateCallback
= mDNSNULL
;
1679 rr
->UpdateCredits
= kMaxUpdateCredits
;
1680 rr
->NextUpdateCredit
= 0;
1681 rr
->UpdateBlocked
= 0;
1683 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1684 if (rr
->WakeUp
.HMAC
.l
[0] && !rr
->AddressProxy
.type
) rr
->AnnounceCount
= 2;
1686 // Field Group 4: Transient uDNS state for Authoritative Records
1687 rr
->state
= regState_Zero
;
1691 rr
->updateid
= zeroID
;
1692 rr
->updateIntID
= zeroOpaque64
;
1693 rr
->zone
= rr
->resrec
.name
;
1698 rr
->InFlightRData
= 0;
1699 rr
->InFlightRDLen
= 0;
1700 rr
->QueuedRData
= 0;
1701 rr
->QueuedRDLen
= 0;
1702 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1703 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1704 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1705 // times with different values if the external NAT port changes during the lifetime of the service registration.
1706 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1708 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1709 // rr->resrec.name->c = MUST be set by client
1710 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1711 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1712 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1713 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1715 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1716 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1717 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1718 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rr
->resrec
.rdlength
== 0) { rr
->resrec
.rdlength
= 1; rr
->resrec
.rdata
->u
.txt
.c
[0] = 0; }
1722 SetTargetToHostName(m
, rr
); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1723 #ifndef UNICAST_DISABLED
1724 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1725 // In this case we leave the record half-formed in the list, and later we'll remove it from the list and re-add it properly.
1726 if (rr
->state
== regState_NoTarget
)
1728 // Initialize the target so that we don't crash while logging etc.
1729 domainname
*tar
= GetRRDomainNameTarget(&rr
->resrec
);
1730 if (tar
) tar
->c
[0] = 0;
1731 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m
, rr
));
1737 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
1738 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
1741 if (!ValidateDomainName(rr
->resrec
.name
))
1742 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1744 // Don't do this until *after* we've set rr->resrec.rdlength
1745 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
1746 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1748 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
1749 rr
->resrec
.rdatahash
= target
? DomainNameHashValue(target
) : RDataHashValue(&rr
->resrec
);
1751 if (RRLocalOnly(rr
))
1753 // If this is supposed to be unique, make sure we don't have any name conflicts.
1754 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1755 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1756 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1757 // Hence, just bail out.
1758 // This comment is doesn’t make any sense. -- SC
1759 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1761 if (CheckAuthRecordConflict(&m
->rrauth
, rr
))
1763 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m
, rr
), rr
, rr
->resrec
.InterfaceID
);
1764 return mStatus_NameConflict
;
1769 // For uDNS records, we don't support duplicate checks at this time.
1770 #ifndef UNICAST_DISABLED
1771 if (AuthRecord_uDNS(rr
))
1773 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1774 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1775 // records to the list, so we now need to update p to advance to the new end to the list before appending our new record.
1776 while (*p
) p
=&(*p
)->next
;
1778 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1780 rr
->ProbeRestartCount
= 0;
1781 rr
->AnnounceCount
= 0;
1782 if (rr
->state
!= regState_NoTarget
) ActivateUnicastRegistration(m
, rr
);
1783 return(mStatus_NoError
); // <--- Note: For unicast records, code currently bails out at this point
1787 // Now that we've finished building our new record, make sure it's not identical to one we already have
1788 if (RRLocalOnly(rr
))
1791 rr
->ProbeRestartCount
= 0;
1792 rr
->AnnounceCount
= 0;
1793 r
= CheckAuthIdenticalRecord(&m
->rrauth
, rr
);
1797 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
1798 if (RecordIsLocalDuplicate(r
, rr
))
1800 if (r
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) r
->AnnounceCount
= 0;
1807 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m
,rr
));
1809 // If the previous copy of this record is already verified unique,
1810 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1811 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1812 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1813 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
1818 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m
,rr
));
1819 if (RRLocalOnly(rr
))
1822 ag
= InsertAuthRecord(m
, &m
->rrauth
, rr
);
1823 if (ag
&& !ag
->NewLocalOnlyRecords
)
1825 m
->NewLocalOnlyRecords
= mDNStrue
;
1826 ag
->NewLocalOnlyRecords
= rr
;
1828 // No probing for LocalOnly records; acknowledge them right away
1829 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1830 AcknowledgeRecord(m
, rr
);
1831 return(mStatus_NoError
);
1835 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1840 if (!AuthRecord_uDNS(rr
)) // This check is superfluous, given that for unicast records we (currently) bail out above
1842 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1843 IncrementAutoTargetServices(m
, rr
);
1845 // For records that are not going to probe, acknowledge them right away
1846 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
1847 AcknowledgeRecord(m
, rr
);
1849 // Adding a record may affect whether or not we should sleep
1850 mDNS_UpdateAllowSleep(m
);
1853 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1854 // This is used by the in-NIC proxy to send the keepalive packets.
1855 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
1858 // Set the record type to known unique to prevent probing keep alive records.
1859 // Also make sure we do not announce the keepalive records.
1860 rr
->resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
1861 rr
->AnnounceCount
= 0;
1862 getKeepaliveRaddr(m
, rr
, &raddr
);
1863 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1864 // asynchronous task to update the resource record
1865 mDNSPlatformGetRemoteMacAddr(&raddr
);
1868 return(mStatus_NoError
);
1871 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
1873 m
->ProbeFailTime
= m
->timenow
;
1874 m
->NumFailedProbes
++;
1875 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1876 // If a bunch of hosts have all been configured with the same name, then they'll all
1877 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1878 // up to name-10. After that they'll start adding random increments in the range 1-100,
1879 // so they're more likely to branch out in the available namespace and settle on a set of
1880 // unique names quickly. If after five more tries the host is still conflicting, then we
1881 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1882 if (m
->NumFailedProbes
>= 15)
1884 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
1885 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1886 m
->NumFailedProbes
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1890 mDNSlocal
void CompleteRDataUpdate(mDNS
*const m
, AuthRecord
*const rr
)
1892 RData
*OldRData
= rr
->resrec
.rdata
;
1893 mDNSu16 OldRDLen
= rr
->resrec
.rdlength
;
1894 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
1895 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
1896 if (rr
->UpdateCallback
)
1897 rr
->UpdateCallback(m
, rr
, OldRData
, OldRDLen
); // ... and let the client know
1900 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1901 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1902 // Exported so uDNS.c can call this
1903 mDNSexport mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
1906 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
1907 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
1908 mDNSBool dupList
= mDNSfalse
;
1910 if (RRLocalOnly(rr
))
1915 a
= AuthGroupForRecord(&m
->rrauth
, &rr
->resrec
);
1916 if (!a
) return mDNSfalse
;
1918 while (*rp
&& *rp
!= rr
) rp
=&(*rp
)->next
;
1923 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1928 // We found our record on the main list. See if there are any duplicates that need special handling.
1929 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
1931 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1932 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1933 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
) if (RecordIsLocalDuplicate(r2
, rr
)) r2
->ProbeCount
= 0xFF;
1937 // Before we delete the record (and potentially send a goodbye packet)
1938 // first see if we have a record on the duplicate list ready to take over from it.
1939 AuthRecord
**d
= &m
->DuplicateRecords
;
1940 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
1943 AuthRecord
*dup
= *d
;
1944 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1945 dup
, rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1946 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
1947 if (RRLocalOnly(rr
))
1949 dup
->next
= mDNSNULL
;
1950 if (!InsertAuthRecord(m
, &m
->rrauth
, dup
)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m
, dup
));
1954 dup
->next
= rr
->next
; // And then...
1955 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
1957 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
1958 dup
->ProbeCount
= rr
->ProbeCount
;
1959 dup
->ProbeRestartCount
= rr
->ProbeRestartCount
;
1960 dup
->AnnounceCount
= rr
->AnnounceCount
;
1961 dup
->RequireGoodbye
= rr
->RequireGoodbye
;
1962 dup
->AnsweredLocalQ
= rr
->AnsweredLocalQ
;
1963 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
1964 dup
->ImmedUnicast
= rr
->ImmedUnicast
;
1965 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
1966 dup
->v4Requester
= rr
->v4Requester
;
1967 dup
->v6Requester
= rr
->v6Requester
;
1968 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
1969 dup
->LastAPTime
= rr
->LastAPTime
;
1970 dup
->LastMCTime
= rr
->LastMCTime
;
1971 dup
->LastMCInterface
= rr
->LastMCInterface
;
1972 dup
->Private
= rr
->Private
;
1973 dup
->state
= rr
->state
;
1974 rr
->RequireGoodbye
= mDNSfalse
;
1975 rr
->AnsweredLocalQ
= mDNSfalse
;
1981 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1982 p
= &m
->DuplicateRecords
;
1983 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1984 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1987 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1988 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1989 // also that have been marked above in this function. In that case, we come here and if we don't
1990 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1991 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1993 rr
->WakeUp
.HMAC
= zeroEthAddr
;
1994 rr
->RequireGoodbye
= mDNSfalse
;
1995 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1998 if (*p
) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1999 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2004 // No need to log an error message if we already know this is a potentially repeated deregistration
2005 if (drt
!= mDNS_Dereg_repeat
)
2006 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr
, ARDisplayString(m
,rr
));
2007 return(mStatus_BadReferenceErr
);
2010 // If this is a shared record and we've announced it at least once,
2011 // we need to retract that announcement before we delete the record
2013 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
2014 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe.
2015 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
2016 // mechanism to cope with the client callback modifying the question list while that's happening.
2017 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
2018 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
2019 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
2020 // records, thereby invoking yet more callbacks, without limit.
2021 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
2022 // actual goodbye packets.
2024 #ifndef UNICAST_DISABLED
2025 if (AuthRecord_uDNS(rr
))
2027 if (rr
->RequireGoodbye
)
2029 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2030 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2031 m
->LocalRemoveEvents
= mDNStrue
;
2032 uDNS_DeregisterRecord(m
, rr
);
2033 // At this point unconditionally we bail out
2034 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
2035 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
2036 // process and will complete asynchronously. Either way we don't need to do anything more here.
2037 return(mStatus_NoError
);
2039 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
2040 // from the server. In that case, if the records have been part of a group update, clear the
2042 rr
->updateid
= zeroID
;
2044 // We defer cleaning up NAT state only after sending goodbyes. This is important because
2045 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
2046 // This happens today when we turn on/off interface where we get multiple network transitions
2047 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
2048 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
2049 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
2050 // NAT state here takes care of the case where we did not send goodbyes at all.
2051 if (rr
->NATinfo
.clientContext
)
2053 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
2054 rr
->NATinfo
.clientContext
= mDNSNULL
;
2056 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
2057 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2059 #endif // UNICAST_DISABLED
2061 if (RecordType
== kDNSRecordTypeUnregistered
)
2062 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m
, rr
));
2063 else if (RecordType
== kDNSRecordTypeDeregistering
)
2065 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m
, rr
));
2066 return(mStatus_BadReferenceErr
);
2069 if (rr
->WakeUp
.HMAC
.l
[0] ||
2070 (((RecordType
== kDNSRecordTypeShared
) || (rr
->ARType
== AuthRecordLocalOnly
)) &&
2071 (rr
->RequireGoodbye
|| rr
->AnsweredLocalQ
)))
2073 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m
, rr
));
2074 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2075 rr
->resrec
.rroriginalttl
= 0;
2076 rr
->AnnounceCount
= rr
->WakeUp
.HMAC
.l
[0] ? WakeupCount
: (drt
== mDNS_Dereg_rapid
) ? 1 : GoodbyeCount
;
2077 rr
->ThisAPInterval
= mDNSPlatformOneSecond
* 2;
2078 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
2079 m
->LocalRemoveEvents
= mDNStrue
;
2080 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
2081 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
2085 if (!dupList
&& RRLocalOnly(rr
))
2087 AuthGroup
*ag
= RemoveAuthRecord(m
, &m
->rrauth
, rr
);
2088 if (ag
->NewLocalOnlyRecords
== rr
) ag
->NewLocalOnlyRecords
= rr
->next
;
2092 *p
= rr
->next
; // Cut this record from the list
2093 if (m
->NewLocalRecords
== rr
) m
->NewLocalRecords
= rr
->next
;
2094 DecrementAutoTargetServices(m
, rr
);
2096 // If someone is about to look at this, bump the pointer forward
2097 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
2098 rr
->next
= mDNSNULL
;
2100 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m
, rr
));
2101 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
2103 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
2104 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2105 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2107 // If we have an update queued up which never executed, give the client a chance to free that memory
2108 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
2111 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2112 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2113 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2114 // so any attempt to touch rr after this is likely to lead to a crash.
2115 if (drt
!= mDNS_Dereg_conflict
)
2117 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2118 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m
, rr
));
2119 if (rr
->RecordCallback
)
2120 rr
->RecordCallback(m
, rr
, mStatus_MemFree
); // MUST NOT touch rr after this
2121 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2125 RecordProbeFailure(m
, rr
);
2126 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2127 if (rr
->RecordCallback
)
2128 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
); // MUST NOT touch rr after this
2129 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2130 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
2131 // Note that with all the client callbacks going on, by the time we get here all the
2132 // records we marked may have been explicitly deregistered by the client anyway.
2133 r2
= m
->DuplicateRecords
;
2136 if (r2
->ProbeCount
!= 0xFF)
2142 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2143 // See if this record was also registered with any D2D plugins.
2144 D2D_stop_advertising_record(r2
);
2146 mDNS_Deregister_internal(m
, r2
, mDNS_Dereg_conflict
);
2147 // As this is a duplicate record, it will be unlinked from the list
2149 r2
= m
->DuplicateRecords
;
2154 mDNS_UpdateAllowSleep(m
);
2155 return(mStatus_NoError
);
2158 // ***************************************************************************
2159 #if COMPILER_LIKES_PRAGMA_MARK
2161 #pragma mark - Packet Sending Functions
2164 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
2166 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
2169 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
2170 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
2171 // The referenced record will definitely be acceptable (by recursive application of this rule)
2172 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
2173 rr
->NR_AdditionalTo
= add
;
2174 *nrpp
= &rr
->NextResponse
;
2176 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2179 mDNSlocal
void AddRRSetAdditionalsToResponseList(mDNS
*const m
, AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*additional
, const mDNSInterfaceID InterfaceID
)
2182 if (additional
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2184 for (rr2
= m
->ResourceRecords
; rr2
; rr2
= rr2
->next
)
2186 if ((rr2
->resrec
.namehash
== additional
->resrec
.namehash
) &&
2187 (rr2
->resrec
.rrtype
== additional
->resrec
.rrtype
) &&
2188 (rr2
!= additional
) &&
2189 (rr2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) &&
2190 (rr2
->resrec
.rrclass
== additional
->resrec
.rrclass
) &&
2191 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) &&
2192 SameDomainName(rr2
->resrec
.name
, additional
->resrec
.name
))
2194 AddRecordToResponseList(nrpp
, rr2
, rr
);
2200 mDNSlocal
void AddAdditionalsToResponseList(mDNS
*const m
, AuthRecord
*ResponseRecords
, AuthRecord
***nrpp
, const mDNSInterfaceID InterfaceID
)
2202 AuthRecord
*rr
, *rr2
;
2203 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
2205 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
2206 // later in the "for" loop, and we will follow further "additional" links then.)
2207 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
2209 AddRecordToResponseList(nrpp
, rr
->Additional1
, rr
);
2210 AddRRSetAdditionalsToResponseList(m
, nrpp
, rr
, rr
->Additional1
, InterfaceID
);
2213 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
2215 AddRecordToResponseList(nrpp
, rr
->Additional2
, rr
);
2216 AddRRSetAdditionalsToResponseList(m
, nrpp
, rr
, rr
->Additional2
, InterfaceID
);
2219 // For SRV records, automatically add the Address record(s) for the target host
2220 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
2222 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
2223 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2224 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
2225 rr
->resrec
.rdatahash
== rr2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2226 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, rr2
->resrec
.name
))
2227 AddRecordToResponseList(nrpp
, rr2
, rr
);
2229 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
)) // For A or AAAA, put counterpart as additional
2231 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
2232 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2233 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
2234 rr
->resrec
.namehash
== rr2
->resrec
.namehash
&& // ... and have the same name
2235 SameDomainName(rr
->resrec
.name
, rr2
->resrec
.name
))
2236 AddRecordToResponseList(nrpp
, rr2
, rr
);
2238 else if (rr
->resrec
.rrtype
== kDNSType_PTR
) // For service PTR, see if we want to add DeviceInfo record
2240 if (ResourceRecordIsValidInterfaceAnswer(&m
->DeviceInfo
, InterfaceID
) &&
2241 SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2242 AddRecordToResponseList(nrpp
, &m
->DeviceInfo
, rr
);
2247 mDNSlocal
void SendDelayedUnicastResponse(mDNS
*const m
, const mDNSAddr
*const dest
, const mDNSInterfaceID InterfaceID
)
2250 AuthRecord
*ResponseRecords
= mDNSNULL
;
2251 AuthRecord
**nrp
= &ResponseRecords
;
2252 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
2254 // Make a list of all our records that need to be unicast to this destination
2255 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2257 // If we find we can no longer unicast this answer, clear ImmedUnicast
2258 if (rr
->ImmedAnswer
== mDNSInterfaceMark
||
2259 mDNSSameIPv4Address(rr
->v4Requester
, onesIPv4Addr
) ||
2260 mDNSSameIPv6Address(rr
->v6Requester
, onesIPv6Addr
) )
2261 rr
->ImmedUnicast
= mDNSfalse
;
2263 if (rr
->ImmedUnicast
&& rr
->ImmedAnswer
== InterfaceID
)
2265 if ((dest
->type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->v4Requester
, dest
->ip
.v4
)) ||
2266 (dest
->type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->v6Requester
, dest
->ip
.v6
)))
2268 rr
->ImmedAnswer
= mDNSNULL
; // Clear the state fields
2269 rr
->ImmedUnicast
= mDNSfalse
;
2270 rr
->v4Requester
= zerov4Addr
;
2271 rr
->v6Requester
= zerov6Addr
;
2273 // Only sent records registered for P2P over P2P interfaces
2274 if (intf
&& !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
))
2279 if (rr
->NextResponse
== mDNSNULL
&& nrp
!= &rr
->NextResponse
) // rr->NR_AnswerTo
2281 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
2283 nrp
= &rr
->NextResponse
;
2289 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
2291 while (ResponseRecords
)
2293 mDNSu8
*responseptr
= m
->omsg
.data
;
2295 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2297 // Put answers in the packet
2298 while (ResponseRecords
&& ResponseRecords
->NR_AnswerTo
)
2300 rr
= ResponseRecords
;
2301 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2302 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2304 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
);
2306 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2307 if (!newptr
&& m
->omsg
.h
.numAnswers
)
2309 break; // If packet full, send it now
2311 if (newptr
) responseptr
= newptr
;
2312 ResponseRecords
= rr
->NextResponse
;
2313 rr
->NextResponse
= mDNSNULL
;
2314 rr
->NR_AnswerTo
= mDNSNULL
;
2315 rr
->NR_AdditionalTo
= mDNSNULL
;
2316 rr
->RequireGoodbye
= mDNStrue
;
2319 // Add additionals, if there's space
2320 while (ResponseRecords
&& !ResponseRecords
->NR_AnswerTo
)
2322 rr
= ResponseRecords
;
2323 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2324 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2325 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2326 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2328 if (newptr
) responseptr
= newptr
;
2329 if (newptr
&& m
->omsg
.h
.numAnswers
) rr
->RequireGoodbye
= mDNStrue
;
2330 else if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
->ImmedAnswer
= mDNSInterfaceMark
;
2331 ResponseRecords
= rr
->NextResponse
;
2332 rr
->NextResponse
= mDNSNULL
;
2333 rr
->NR_AnswerTo
= mDNSNULL
;
2334 rr
->NR_AdditionalTo
= mDNSNULL
;
2337 if (m
->omsg
.h
.numAnswers
)
2338 mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, InterfaceID
, mDNSNULL
, mDNSNULL
, dest
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
2342 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2343 // and the client's mStatus_MemFree callback will have been invoked
2344 mDNSexport
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
2346 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m
, rr
));
2347 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2348 // it should go ahead and immediately dispose of this registration
2349 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
2350 rr
->RequireGoodbye
= mDNSfalse
;
2351 rr
->WakeUp
.HMAC
= zeroEthAddr
;
2352 if (rr
->AnsweredLocalQ
) { AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_rmv
); rr
->AnsweredLocalQ
= mDNSfalse
; }
2353 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
); // Don't touch rr after this
2356 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2357 // any deregistering records that remain in the m->ResourceRecords list.
2358 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2359 // which may change the record list and/or question list.
2360 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2361 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
2363 if (m
->CurrentRecord
)
2364 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2365 m
->CurrentRecord
= m
->ResourceRecords
;
2367 while (m
->CurrentRecord
)
2369 AuthRecord
*rr
= m
->CurrentRecord
;
2370 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2371 CompleteDeregistration(m
, rr
); // Don't touch rr after this
2373 m
->CurrentRecord
= rr
->next
;
2377 mDNSlocal mStatus
GetLabelDecimalValue(const mDNSu8
*const src
, mDNSu8
*dst
)
2380 if (src
[0] < 1 || src
[0] > 3) return(mStatus_Invalid
);
2381 for (i
=1; i
<=src
[0]; i
++)
2383 if (src
[i
] < '0' || src
[i
] > '9') return(mStatus_Invalid
);
2384 val
= val
* 10 + src
[i
] - '0';
2386 if (val
> 255) return(mStatus_Invalid
);
2388 return(mStatus_NoError
);
2391 mDNSlocal mStatus
GetIPv4FromName(mDNSAddr
*const a
, const domainname
*const name
)
2393 int skip
= CountLabels(name
) - 6;
2394 if (skip
< 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2395 if (GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+3)->c
, &a
->ip
.v4
.b
[0]) ||
2396 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+2)->c
, &a
->ip
.v4
.b
[1]) ||
2397 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+1)->c
, &a
->ip
.v4
.b
[2]) ||
2398 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+0)->c
, &a
->ip
.v4
.b
[3])) return mStatus_Invalid
;
2399 a
->type
= mDNSAddrType_IPv4
;
2400 return(mStatus_NoError
);
2403 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2404 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2405 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2407 mDNSlocal mStatus
GetIPv6FromName(mDNSAddr
*const a
, const domainname
*const name
)
2410 const domainname
*n
;
2412 int skip
= CountLabels(name
) - 34;
2413 if (skip
< 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2415 n
= SkipLeadingLabels(name
, skip
);
2416 for (i
=0; i
<16; i
++)
2418 if (n
->c
[0] != 1) return mStatus_Invalid
;
2419 l
= HexVal(n
->c
[1]);
2420 n
= (const domainname
*)(n
->c
+ 2);
2422 if (n
->c
[0] != 1) return mStatus_Invalid
;
2423 h
= HexVal(n
->c
[1]);
2424 n
= (const domainname
*)(n
->c
+ 2);
2426 if (l
<0 || h
<0) return mStatus_Invalid
;
2427 a
->ip
.v6
.b
[15-i
] = (mDNSu8
)((h
<< 4) | l
);
2430 a
->type
= mDNSAddrType_IPv6
;
2431 return(mStatus_NoError
);
2434 mDNSlocal mDNSs32
ReverseMapDomainType(const domainname
*const name
)
2436 int skip
= CountLabels(name
) - 2;
2439 const domainname
*suffix
= SkipLeadingLabels(name
, skip
);
2440 if (SameDomainName(suffix
, (const domainname
*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4
;
2441 if (SameDomainName(suffix
, (const domainname
*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6
;
2443 return(mDNSAddrType_None
);
2446 mDNSlocal
void SendARP(mDNS
*const m
, const mDNSu8 op
, const AuthRecord
*const rr
,
2447 const mDNSv4Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv4Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2450 mDNSu8
*ptr
= m
->omsg
.data
;
2451 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2452 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2454 // 0x00 Destination address
2455 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2457 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2458 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
2460 // 0x0C ARP Ethertype (0x0806)
2461 *ptr
++ = 0x08; *ptr
++ = 0x06;
2464 *ptr
++ = 0x00; *ptr
++ = 0x01; // Hardware address space; Ethernet = 1
2465 *ptr
++ = 0x08; *ptr
++ = 0x00; // Protocol address space; IP = 0x0800
2466 *ptr
++ = 6; // Hardware address length
2467 *ptr
++ = 4; // Protocol address length
2468 *ptr
++ = 0x00; *ptr
++ = op
; // opcode; Request = 1, Response = 2
2470 // 0x16 Sender hardware address (our MAC address)
2471 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[i
];
2473 // 0x1C Sender protocol address
2474 for (i
=0; i
<4; i
++) *ptr
++ = spa
->b
[i
];
2476 // 0x20 Target hardware address
2477 for (i
=0; i
<6; i
++) *ptr
++ = tha
->b
[i
];
2479 // 0x26 Target protocol address
2480 for (i
=0; i
<4; i
++) *ptr
++ = tpa
->b
[i
];
2482 // 0x2A Total ARP Packet length 42 bytes
2483 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2486 mDNSlocal mDNSu16
CheckSum(const void *const data
, mDNSs32 length
, mDNSu32 sum
)
2488 const mDNSu16
*ptr
= data
;
2489 while (length
> 0) { length
-= 2; sum
+= *ptr
++; }
2490 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2491 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2492 return(sum
!= 0xFFFF ? sum
: 0);
2495 mDNSlocal mDNSu16
IPv6CheckSum(const mDNSv6Addr
*const src
, const mDNSv6Addr
*const dst
, const mDNSu8 protocol
, const void *const data
, const mDNSu32 length
)
2497 IPv6PseudoHeader ph
;
2500 ph
.len
.b
[0] = length
>> 24;
2501 ph
.len
.b
[1] = length
>> 16;
2502 ph
.len
.b
[2] = length
>> 8;
2503 ph
.len
.b
[3] = length
;
2507 ph
.pro
.b
[3] = protocol
;
2508 return CheckSum(&ph
, sizeof(ph
), CheckSum(data
, length
, 0));
2511 mDNSlocal
void SendNDP(mDNS
*const m
, const mDNSu8 op
, const mDNSu8 flags
, const AuthRecord
*const rr
,
2512 const mDNSv6Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv6Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2515 mDNSOpaque16 checksum
;
2516 mDNSu8
*ptr
= m
->omsg
.data
;
2517 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2518 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2519 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2520 const mDNSv6Addr mc
= { { 0xFF,0x02,0x00,0x00, 0,0,0,0, 0,0,0,1, 0xFF,tpa
->b
[0xD],tpa
->b
[0xE],tpa
->b
[0xF] } };
2521 const mDNSv6Addr
*const v6dst
= (op
== NDP_Sol
) ? &mc
: tpa
;
2522 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2523 if (!intf
) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2525 // 0x00 Destination address
2526 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2527 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2528 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2529 // link with a pointless link-layer multicast.
2530 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2531 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2535 // *ptr++ = tpa->b[0xD];
2536 // *ptr++ = tpa->b[0xE];
2537 // *ptr++ = tpa->b[0xF];
2539 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2540 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2542 // 0x0C IPv6 Ethertype (0x86DD)
2543 *ptr
++ = 0x86; *ptr
++ = 0xDD;
2546 *ptr
++ = 0x60; *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00; // Version, Traffic Class, Flow Label
2547 *ptr
++ = 0x00; *ptr
++ = 0x20; // Length
2548 *ptr
++ = 0x3A; // Protocol == ICMPv6
2549 *ptr
++ = 0xFF; // Hop Limit
2551 // 0x16 Sender IPv6 address
2552 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2554 // 0x26 Destination IPv6 address
2555 for (i
=0; i
<16; i
++) *ptr
++ = v6dst
->b
[i
];
2558 *ptr
++ = op
; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2559 *ptr
++ = 0x00; // Code
2560 *ptr
++ = 0x00; *ptr
++ = 0x00; // Checksum placeholder (0x38, 0x39)
2562 *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00;
2564 if (op
== NDP_Sol
) // Neighbor Solicitation. The NDP "target" is the address we seek.
2567 for (i
=0; i
<16; i
++) *ptr
++ = tpa
->b
[i
];
2568 // 0x4E Source Link-layer Address
2569 // <http://www.ietf.org/rfc/rfc2461.txt>
2570 // MUST NOT be included when the source IP address is the unspecified address.
2571 // Otherwise, on link layers that have addresses this option MUST be included
2572 // in multicast solicitations and SHOULD be included in unicast solicitations.
2573 if (!mDNSIPv6AddressIsZero(*spa
))
2575 *ptr
++ = NDP_SrcLL
; // Option Type 1 == Source Link-layer Address
2576 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2577 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2580 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2583 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2584 // 0x4E Target Link-layer Address
2585 *ptr
++ = NDP_TgtLL
; // Option Type 2 == Target Link-layer Address
2586 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2587 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2590 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2591 m
->omsg
.data
[0x13] = ptr
- &m
->omsg
.data
[0x36]; // Compute actual length
2592 checksum
.NotAnInteger
= ~IPv6CheckSum(spa
, v6dst
, 0x3A, &m
->omsg
.data
[0x36], m
->omsg
.data
[0x13]);
2593 m
->omsg
.data
[0x38] = checksum
.b
[0];
2594 m
->omsg
.data
[0x39] = checksum
.b
[1];
2596 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2599 mDNSlocal
void SetupTracerOpt(const mDNS
*const m
, rdataOPT
*const Trace
)
2601 mDNSu32 DNS_VERS
= _DNS_SD_H
;
2602 Trace
->u
.tracer
.platf
= m
->mDNS_plat
;
2603 Trace
->u
.tracer
.mDNSv
= DNS_VERS
;
2605 Trace
->opt
= kDNSOpt_Trace
;
2606 Trace
->optlen
= DNSOpt_TraceData_Space
- 4;
2609 mDNSlocal
void SetupOwnerOpt(const mDNS
*const m
, const NetworkInterfaceInfo
*const intf
, rdataOPT
*const owner
)
2611 owner
->u
.owner
.vers
= 0;
2612 owner
->u
.owner
.seq
= m
->SleepSeqNum
;
2613 owner
->u
.owner
.HMAC
= m
->PrimaryMAC
;
2614 owner
->u
.owner
.IMAC
= intf
->MAC
;
2615 owner
->u
.owner
.password
= zeroEthAddr
;
2617 // Don't try to compute the optlen until *after* we've set up the data fields
2618 // Right now the DNSOpt_Owner_Space macro does not depend on the owner->u.owner being set up correctly, but in the future it might
2619 owner
->opt
= kDNSOpt_Owner
;
2620 owner
->optlen
= DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) - 4;
2623 mDNSlocal
void GrantUpdateCredit(AuthRecord
*rr
)
2625 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
2626 else rr
->NextUpdateCredit
= NonZeroTime(rr
->NextUpdateCredit
+ kUpdateCreditRefreshInterval
);
2629 mDNSlocal mDNSBool
ShouldSendGoodbyesBeforeSleep(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, AuthRecord
*rr
)
2631 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2632 // and hence there is no need to check for Transfering state. But if we have sleep
2633 // proxies and partially sending goodbyes for some records, we will be in Transfering
2634 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2635 // we are not awake handles both cases.
2636 if ((rr
->AuthFlags
& AuthFlagsWakeOnly
) && (m
->SleepState
!= SleepState_Awake
))
2638 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m
, rr
));
2642 if (m
->SleepState
!= SleepState_Sleeping
)
2645 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2646 // whether you can send goodbyes or not.
2647 if (!intf
->SendGoodbyes
)
2649 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2654 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2659 // Note about acceleration of announcements to facilitate automatic coalescing of
2660 // multiple independent threads of announcements into a single synchronized thread:
2661 // The announcements in the packet may be at different stages of maturity;
2662 // One-second interval, two-second interval, four-second interval, and so on.
2663 // After we've put in all the announcements that are due, we then consider
2664 // whether there are other nearly-due announcements that are worth accelerating.
2665 // To be eligible for acceleration, a record MUST NOT be older (further along
2666 // its timeline) than the most mature record we've already put in the packet.
2667 // In other words, younger records can have their timelines accelerated to catch up
2668 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2669 // Older records cannot have their timelines accelerated; this would just widen
2670 // the gap between them and their younger bretheren and get them even more out of sync.
2672 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2673 // the record list and/or question list.
2674 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2675 mDNSlocal
void SendResponses(mDNS
*const m
)
2678 AuthRecord
*rr
, *r2
;
2679 mDNSs32 maxExistingAnnounceInterval
= 0;
2680 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
2682 m
->NextScheduledResponse
= m
->timenow
+ FutureTime
;
2684 if (m
->SleepState
== SleepState_Transferring
) RetrySPSRegistrations(m
);
2686 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2687 if (rr
->ImmedUnicast
)
2689 mDNSAddr v4
= { mDNSAddrType_IPv4
, {{{0}}} };
2690 mDNSAddr v6
= { mDNSAddrType_IPv6
, {{{0}}} };
2691 v4
.ip
.v4
= rr
->v4Requester
;
2692 v6
.ip
.v6
= rr
->v6Requester
;
2693 if (!mDNSIPv4AddressIsZero(rr
->v4Requester
)) SendDelayedUnicastResponse(m
, &v4
, rr
->ImmedAnswer
);
2694 if (!mDNSIPv6AddressIsZero(rr
->v6Requester
)) SendDelayedUnicastResponse(m
, &v6
, rr
->ImmedAnswer
);
2695 if (rr
->ImmedUnicast
)
2697 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m
, rr
));
2698 rr
->ImmedUnicast
= mDNSfalse
;
2703 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2706 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2707 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2709 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
2710 if (TimeToAnnounceThisRecord(rr
, m
->timenow
))
2712 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2714 if (!rr
->WakeUp
.HMAC
.l
[0])
2716 if (rr
->AnnounceCount
) rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send goodbye packet on all interfaces
2720 mDNSBool unicastOnly
;
2721 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr
->AnnounceCount
-3, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
2722 unicastOnly
= ((rr
->AnnounceCount
== WakeupCount
) || (rr
->AnnounceCount
== WakeupCount
- 1)) ? mDNStrue
: mDNSfalse
;
2723 SendWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.IMAC
, &rr
->WakeUp
.password
, unicastOnly
);
2724 for (r2
= rr
; r2
; r2
=r2
->next
)
2725 if ((r2
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) && r2
->AnnounceCount
&& (r2
->resrec
.InterfaceID
== rr
->resrec
.InterfaceID
) &&
2726 mDNSSameEthAddress(&r2
->WakeUp
.IMAC
, &rr
->WakeUp
.IMAC
) && !mDNSSameEthAddress(&zeroEthAddr
, &r2
->WakeUp
.HMAC
))
2728 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2729 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2730 if (r2
->AddressProxy
.type
== mDNSAddrType_IPv6
&& r2
->AnnounceCount
== WakeupCount
)
2732 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2733 r2
->AnnounceCount
-3, &r2
->WakeUp
.HMAC
, &r2
->WakeUp
.IMAC
, ARDisplayString(m
,r2
));
2734 SendNDP(m
, NDP_Adv
, NDP_Override
, r2
, &r2
->AddressProxy
.ip
.v6
, &r2
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2736 r2
->LastAPTime
= m
->timenow
;
2737 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2738 if (--r2
->AnnounceCount
<= GoodbyeCount
) r2
->WakeUp
.HMAC
= zeroEthAddr
;
2742 else if (ResourceRecordIsValidAnswer(rr
))
2744 if (rr
->AddressProxy
.type
)
2746 if (!mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
2748 rr
->AnnounceCount
--;
2749 rr
->ThisAPInterval
*= 2;
2750 rr
->LastAPTime
= m
->timenow
;
2751 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv4
)
2753 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2754 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2755 SendARP(m
, 1, rr
, &rr
->AddressProxy
.ip
.v4
, &zeroEthAddr
, &rr
->AddressProxy
.ip
.v4
, &onesEthAddr
);
2757 else if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
2759 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2760 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2761 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2767 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2768 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
2769 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
2770 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
2776 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2777 // Eligible records that are more than half-way to their announcement time are accelerated
2778 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2779 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
2780 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
2781 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
2782 !rr
->AddressProxy
.type
&& // Don't include ARP Annoucements when considering which records to accelerate
2783 ResourceRecordIsValidAnswer(rr
)))
2784 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2786 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2787 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2788 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2789 // then all that means is that it won't get sent -- which would not be the end of the world.
2790 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2792 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
2793 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
2794 if (RRTypeIsAddressType(r2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2795 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
2796 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
2797 rr
->resrec
.rdatahash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2798 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, r2
->resrec
.name
) &&
2799 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
2800 r2
->ImmedAdditional
= r2
->resrec
.InterfaceID
; // ... then mark this address record for sending too
2801 // We also make sure we send the DeviceInfo TXT record too, if necessary
2802 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2803 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2804 if (rr
->ImmedAnswer
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->resrec
.rrtype
== kDNSType_PTR
)
2805 if (ResourceRecordIsValidAnswer(&m
->DeviceInfo
) && SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2807 if (!m
->DeviceInfo
.ImmedAnswer
) m
->DeviceInfo
.ImmedAnswer
= rr
->ImmedAnswer
;
2808 else m
->DeviceInfo
.ImmedAnswer
= mDNSInterfaceMark
;
2812 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2813 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2814 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2815 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2816 // -- If a record is marked to be sent on a certain interface, make sure the whole set is marked to be sent on that interface
2817 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2818 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2819 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2821 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
2823 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2825 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2826 (r2
->ImmedAnswer
!= mDNSInterfaceMark
) && (r2
->ImmedAnswer
!= rr
->ImmedAnswer
) &&
2827 SameResourceRecordSignature(r2
, rr
) &&
2828 ((rr
->ImmedAnswer
== mDNSInterfaceMark
) || IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAnswer
)))
2830 r2
->ImmedAnswer
= !r2
->ImmedAnswer
? rr
->ImmedAnswer
: mDNSInterfaceMark
;
2834 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
2836 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2838 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2839 (r2
->ImmedAdditional
!= rr
->ImmedAdditional
) &&
2840 SameResourceRecordSignature(r2
, rr
) &&
2841 IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAdditional
))
2843 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
2849 // Now set SendRNow state appropriately
2850 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2852 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
2854 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
2855 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
2856 rr
->LastMCTime
= m
->timenow
;
2857 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2858 rr
->ProbeRestartCount
= 0; // Reset the probe restart count
2859 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2860 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
2862 rr
->AnnounceCount
--;
2863 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
2864 rr
->ThisAPInterval
*= 2;
2865 rr
->LastAPTime
= m
->timenow
;
2866 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
2869 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
2871 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
2872 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
2873 rr
->LastMCTime
= m
->timenow
;
2874 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2876 SetNextAnnounceProbeTime(m
, rr
);
2877 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2881 // *** 2. Loop through interface list, sending records as appropriate
2886 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
2887 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
2889 int numAnnounce
= 0;
2891 mDNSu8
*responseptr
= m
->omsg
.data
;
2893 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2895 // First Pass. Look for:
2896 // 1. Deregistering records that need to send their goodbye packet
2897 // 2. Updated records that need to retract their old data
2898 // 3. Answers and announcements we need to send
2899 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2902 // Skip this interface if the record InterfaceID is *Any and the record is not
2903 // appropriate for the interface type.
2904 if ((rr
->SendRNow
== intf
->InterfaceID
) &&
2905 ((rr
->resrec
.InterfaceID
== mDNSInterface_Any
) && !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
)))
2907 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2909 else if (rr
->SendRNow
== intf
->InterfaceID
)
2911 RData
*OldRData
= rr
->resrec
.rdata
;
2912 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
2913 mDNSu8 active
= (mDNSu8
)
2914 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& !ShouldSendGoodbyesBeforeSleep(m
, intf
, rr
));
2916 if (rr
->NewRData
&& active
)
2918 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2919 if (ResourceRecordIsValidAnswer(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
2921 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, 0);
2922 if (newptr
) { responseptr
= newptr
; numDereg
++; rr
->RequireGoodbye
= mDNSfalse
; }
2923 else continue; // If this packet is already too full to hold the goodbye for this record, skip it for now and we'll retry later
2925 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
2928 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2929 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2930 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, active
? rr
->resrec
.rroriginalttl
: 0);
2931 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2934 responseptr
= newptr
;
2935 rr
->RequireGoodbye
= active
;
2936 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) numDereg
++;
2937 else if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++;else numAnswer
++;
2940 if (rr
->NewRData
&& active
)
2941 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
2943 // The first time through (pktcount==0), if this record is verified unique
2944 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2945 if (!pktcount
&& active
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2946 rr
->SendNSECNow
= mDNSInterfaceMark
;
2948 if (newptr
) // If succeeded in sending, advance to next interface
2950 // If sending on all interfaces, go to next interface; else we're finished now
2951 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
2952 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2954 rr
->SendRNow
= mDNSNULL
;
2959 // Second Pass. Add additional records, if there's space.
2960 newptr
= responseptr
;
2961 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2962 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
2963 if (ResourceRecordIsValidAnswer(rr
))
2965 // If we have at least one answer already in the packet, then plan to add additionals too
2966 mDNSBool SendAdditional
= (m
->omsg
.h
.numAnswers
> 0);
2968 // If we're not planning to send any additionals, but this record is a unique one, then
2969 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2970 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2971 if (!SendAdditional
&& (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
2973 const AuthRecord
*a
;
2974 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
2975 if (a
->LastMCTime
== m
->timenow
&&
2976 a
->LastMCInterface
== intf
->InterfaceID
&&
2977 SameResourceRecordSignature(a
, rr
)) { SendAdditional
= mDNStrue
; break; }
2979 if (!SendAdditional
) // If we don't want to send this after all,
2980 rr
->ImmedAdditional
= mDNSNULL
; // then cancel its ImmedAdditional field
2981 else if (newptr
) // Else, try to add it if we can
2983 // The first time through (pktcount==0), if this record is verified unique
2984 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2985 if (!pktcount
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2986 rr
->SendNSECNow
= mDNSInterfaceMark
;
2988 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2989 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2990 newptr
= PutRR_OS(newptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2991 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2994 responseptr
= newptr
;
2995 rr
->ImmedAdditional
= mDNSNULL
;
2996 rr
->RequireGoodbye
= mDNStrue
;
2997 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2998 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2999 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
3000 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
3001 rr
->LastMCTime
= m
->timenow
;
3002 rr
->LastMCInterface
= intf
->InterfaceID
;
3007 // Third Pass. Add NSEC records, if there's space.
3008 // When we're generating an NSEC record in response to a specify query for that type
3009 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
3010 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
3011 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3012 if (rr
->SendNSECNow
== mDNSInterfaceMark
|| rr
->SendNSECNow
== intf
->InterfaceID
)
3017 mDNS_SetupResourceRecord(&nsec
, mDNSNULL
, mDNSInterface_Any
, kDNSType_NSEC
, rr
->resrec
.rroriginalttl
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3018 nsec
.resrec
.rrclass
|= kDNSClass_UniqueRRSet
;
3019 AssignDomainName(&nsec
.namestorage
, rr
->resrec
.name
);
3020 ptr
= nsec
.rdatastorage
.u
.data
;
3021 len
= DomainNameLength(rr
->resrec
.name
);
3022 // We have a nxt name followed by window number, window length and a window bitmap
3023 nsec
.resrec
.rdlength
= len
+ 2 + NSEC_MCAST_WINDOW_SIZE
;
3024 if (nsec
.resrec
.rdlength
<= StandardAuthRDSize
)
3026 mDNSPlatformMemZero(ptr
, nsec
.resrec
.rdlength
);
3027 AssignDomainName((domainname
*)ptr
, rr
->resrec
.name
);
3029 *ptr
++ = 0; // window number
3030 *ptr
++ = NSEC_MCAST_WINDOW_SIZE
; // window length
3031 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3032 if (ResourceRecordIsValidAnswer(r2
) && SameResourceRecordNameClassInterface(r2
, rr
))
3034 if (r2
->resrec
.rrtype
>= kDNSQType_ANY
) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m
, r2
)); break; }
3035 else ptr
[r2
->resrec
.rrtype
>> 3] |= 128 >> (r2
->resrec
.rrtype
& 7);
3037 newptr
= responseptr
;
3038 if (!r2
) // If we successfully built our NSEC record, add it to the packet now
3040 newptr
= PutRR_OS(responseptr
, &m
->omsg
.h
.numAdditionals
, &nsec
.resrec
);
3041 if (newptr
) responseptr
= newptr
;
3044 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec
.resrec
.rdlength
);
3046 // If we successfully put the NSEC record, clear the SendNSECNow flag
3047 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
3048 if (newptr
|| rr
->SendNSECNow
== mDNSInterfaceMark
)
3050 rr
->SendNSECNow
= mDNSNULL
;
3051 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
3052 for (r2
= rr
->next
; r2
; r2
=r2
->next
)
3053 if (SameResourceRecordNameClassInterface(r2
, rr
))
3054 if (r2
->SendNSECNow
== mDNSInterfaceMark
|| r2
->SendNSECNow
== intf
->InterfaceID
)
3055 r2
->SendNSECNow
= mDNSNULL
;
3059 if (m
->omsg
.h
.numAnswers
|| m
->omsg
.h
.numAdditionals
)
3061 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3062 if (OwnerRecordSpace
|| TraceRecordSpace
)
3065 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3066 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
3067 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
3068 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
3069 if (OwnerRecordSpace
&& TraceRecordSpace
)
3071 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
3072 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
3073 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3074 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
3076 else if (OwnerRecordSpace
)
3078 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3080 else if (TraceRecordSpace
)
3082 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
3084 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
);
3087 responseptr
= newptr
;
3089 else if (m
->omsg
.h
.numAnswers
+ m
->omsg
.h
.numAuthorities
+ m
->omsg
.h
.numAdditionals
== 1)
3091 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
3092 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3096 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
3097 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3101 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3102 numDereg
, numDereg
== 1 ? "" : "s",
3103 numAnnounce
, numAnnounce
== 1 ? "" : "s",
3104 numAnswer
, numAnswer
== 1 ? "" : "s",
3105 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
3107 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
3108 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
3109 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
3110 if (++pktcount
>= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
3111 // There might be more things to send on this interface, so go around one more time and try again.
3113 else // Nothing more to send on this interface; go to next
3115 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3116 #if MDNS_DEBUGMSGS && 0
3117 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3118 debugf(msg
, intf
, next
);
3121 pktcount
= 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3126 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3129 if (m
->CurrentRecord
)
3130 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3131 m
->CurrentRecord
= m
->ResourceRecords
;
3132 while (m
->CurrentRecord
)
3134 rr
= m
->CurrentRecord
;
3135 m
->CurrentRecord
= rr
->next
;
3139 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
)
3140 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3141 IIDPrintable(rr
->SendRNow
), IIDPrintable(rr
->resrec
.InterfaceID
), rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
3142 rr
->SendRNow
= mDNSNULL
;
3145 if (rr
->ImmedAnswer
|| rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3147 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
3149 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->AnnounceCount
== 0)
3151 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3152 if (!AuthRecord_uDNS(rr
)) CompleteDeregistration(m
, rr
); // Don't touch rr after this
3156 rr
->ImmedAnswer
= mDNSNULL
;
3157 rr
->ImmedUnicast
= mDNSfalse
;
3158 rr
->v4Requester
= zerov4Addr
;
3159 rr
->v6Requester
= zerov6Addr
;
3163 verbosedebugf("SendResponses: Next in %ld ticks", m
->NextScheduledResponse
- m
->timenow
);
3166 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3167 // so we want to be lazy about how frequently we do it.
3168 // 1. If a cache record is currently referenced by *no* active questions,
3169 // then we don't mind expiring it up to a minute late (who will know?)
3170 // 2. Else, if a cache record is due for some of its final expiration queries,
3171 // we'll allow them to be late by up to 2% of the TTL
3172 // 3. Else, if a cache record has completed all its final expiration queries without success,
3173 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3174 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3175 // so allow at most 1/10 second lateness
3176 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3177 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3178 #define CacheCheckGracePeriod(CR) ( \
3179 ((CR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3180 ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50) : \
3181 ((CR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3182 ((CR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3184 #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR))
3186 mDNSexport
void ScheduleNextCacheCheckTime(mDNS
*const m
, const mDNSu32 slot
, const mDNSs32 event
)
3188 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
3189 m
->rrcache_nextcheck
[slot
] = event
;
3190 if (m
->NextCacheCheck
- event
> 0)
3191 m
->NextCacheCheck
= event
;
3194 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3196 // rr->resrec.rroriginalttl
3197 // rr->UnansweredQueries
3198 // rr->CRActiveQuestion
3199 mDNSexport
void SetNextCacheCheckTimeForRecord(mDNS
*const m
, CacheRecord
*const rr
)
3201 rr
->NextRequiredQuery
= RRExpireTime(rr
);
3203 // If we have an active question, then see if we want to schedule a refresher query for this record.
3204 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3205 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3207 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
3208 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
3209 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3210 (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
,rr
));
3212 ScheduleNextCacheCheckTime(m
, HashSlotFromNameHash(rr
->resrec
.namehash
), NextCacheCheckEvent(rr
));
3215 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3216 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3217 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3219 // Delay before restarting questions on a flapping interface.
3220 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3)
3221 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3222 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3223 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7))
3225 mDNSexport mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
3227 if (interval
< kMinimumReconfirmTime
)
3228 interval
= kMinimumReconfirmTime
;
3229 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3230 interval
= 0x10000000;
3232 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3233 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
3235 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3236 // For all the reconfirmations in a given batch, we want to use the same random value
3237 // so that the reconfirmation questions can be grouped into a single query packet
3238 if (!m
->RandomReconfirmDelay
) m
->RandomReconfirmDelay
= 1 + mDNSRandom(FutureTime
);
3239 interval
+= m
->RandomReconfirmDelay
% ((interval
/3) + 1);
3240 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
3241 rr
->resrec
.rroriginalttl
= (interval
* 4 + mDNSPlatformOneSecond
- 1) / mDNSPlatformOneSecond
;
3242 SetNextCacheCheckTimeForRecord(m
, rr
);
3244 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3245 RRExpireTime(rr
) - m
->timenow
, CRDisplayString(m
, rr
), rr
->CRActiveQuestion
);
3246 return(mStatus_NoError
);
3249 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3250 // It also appends to the list of known answer records that need to be included,
3251 // and updates the forcast for the size of the known answer section.
3252 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, DNSMessage
*query
, mDNSu8
**queryptr
,
3253 DNSQuestion
*q
, CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
3255 mDNSBool ucast
= (q
->LargeAnswers
|| q
->RequestUnicast
) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3256 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3257 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
3258 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
- *answerforecast
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
3261 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3266 mDNSu32 forecast
= *answerforecast
;
3267 const CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3269 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
3271 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // If we have a resource record in our cache,
3272 if (cr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3273 !(cr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && // which is a shared (i.e. not unique) record type
3274 cr
->NextInKAList
== mDNSNULL
&& ka
!= &cr
->NextInKAList
&& // which is not already in the known answer list
3275 cr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3276 SameNameCacheRecordAnswersQuestion(cr
, q
) && // which answers our question
3277 cr
->TimeRcvd
+ TicksTTL(cr
)/2 - m
->timenow
> // and its half-way-to-expiry time is at least 1 second away
3278 mDNSPlatformOneSecond
) // (also ensures we never include goodbye records with TTL=1)
3280 // We don't want to include unique records in the Known Answer section. The Known Answer section
3281 // is intended to suppress floods of shared-record replies from many other devices on the network.
3282 // That concept really does not apply to unique records, and indeed if we do send a query for
3283 // which we have a unique record already in our cache, then including that unique record as a
3284 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3286 *ka
= cr
; // Link this record into our known answer chain
3287 ka
= &cr
->NextInKAList
;
3288 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3289 forecast
+= 12 + cr
->resrec
.rdestimate
;
3290 // If we're trying to put more than one question in this packet, and it doesn't fit
3291 // then undo that last question and try again next time
3292 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
3294 query
->h
.numQuestions
--;
3295 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3296 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
, query
->h
.numQuestions
);
3297 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3298 while (*ka
) { CacheRecord
*c
= *ka
; *ka
= mDNSNULL
; ka
= &c
->NextInKAList
; }
3299 return(mDNSfalse
); // Return false, so we'll try again in the next packet
3303 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3304 *queryptr
= newptr
; // Update the packet pointer
3305 *answerforecast
= forecast
; // Update the forecast
3306 *kalistptrptr
= ka
; // Update the known answer list pointer
3307 if (ucast
) q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
3309 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // For every resource record in our cache,
3310 if (cr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3311 cr
->NextInKAList
== mDNSNULL
&& ka
!= &cr
->NextInKAList
&& // which is not in the known answer list
3312 SameNameCacheRecordAnswersQuestion(cr
, q
)) // which answers our question
3314 cr
->UnansweredQueries
++; // indicate that we're expecting a response
3315 cr
->LastUnansweredTime
= m
->timenow
;
3316 SetNextCacheCheckTimeForRecord(m
, cr
);
3323 // When we have a query looking for a specified name, but there appear to be no answers with
3324 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3325 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3326 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3327 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3328 // A typical reconfirmation scenario might go like this:
3329 // Depth 0: Name "myhost.local" has no address records
3330 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3331 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3332 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3333 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3334 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3335 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSInterfaceID InterfaceID
, const int depth
)
3338 const CacheGroup
*cg
;
3340 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth
, name
->c
);
3341 if (!InterfaceID
) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3342 FORALL_CACHERECORDS(slot
, cg
, cr
)
3344 const domainname
*crtarget
;
3345 if (cr
->resrec
.InterfaceID
!= InterfaceID
) continue; // Skip non-mDNS records and mDNS records from other interfaces.
3346 if (cr
->resrec
.rdatahash
!= namehash
) continue; // Skip records whose rdata hash doesn't match the name hash.
3347 crtarget
= GetRRDomainNameTarget(&cr
->resrec
);
3348 if (crtarget
&& SameDomainName(crtarget
, name
))
3350 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth
, InterfaceID
, CRDisplayString(m
, cr
));
3351 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
3353 ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, InterfaceID
, depth
+1);
3358 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3359 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3360 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3361 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3362 mDNSlocal
const CacheRecord
*CacheHasAddressTypeForName(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
3364 CacheGroup
*const cg
= CacheGroupForName(m
, namehash
, name
);
3365 const CacheRecord
*cr
= cg
? cg
->members
: mDNSNULL
;
3366 while (cr
&& !RRTypeIsAddressType(cr
->resrec
.rrtype
)) cr
=cr
->next
;
3371 mDNSlocal
const CacheRecord
*FindSPSInCache1(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*const c0
, const CacheRecord
*const c1
)
3373 #ifndef SPC_DISABLED
3374 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3375 const CacheRecord
*cr
, *bestcr
= mDNSNULL
;
3376 mDNSu32 bestmetric
= 1000000;
3377 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
3378 if (cr
->resrec
.rrtype
== kDNSType_PTR
&& cr
->resrec
.rdlength
>= 6) // If record is PTR type, with long enough name,
3379 if (cr
!= c0
&& cr
!= c1
) // that's not one we've seen before,
3380 if (SameNameCacheRecordAnswersQuestion(cr
, q
)) // and answers our browse query,
3381 if (!IdenticalSameNameRecord(&cr
->resrec
, &m
->SPSRecords
.RR_PTR
.resrec
)) // and is not our own advertised service...
3383 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
3384 if (bestmetric
> metric
) { bestmetric
= metric
; bestcr
= cr
; }
3387 #else // SPC_DISABLED
3394 #endif // SPC_DISABLED
3397 mDNSlocal
void CheckAndSwapSPS(const CacheRecord
**sps1
, const CacheRecord
**sps2
)
3399 const CacheRecord
*swap_sps
;
3400 mDNSu32 metric1
, metric2
;
3402 if (!(*sps1
) || !(*sps2
)) return;
3403 metric1
= SPSMetric((*sps1
)->resrec
.rdata
->u
.name
.c
);
3404 metric2
= SPSMetric((*sps2
)->resrec
.rdata
->u
.name
.c
);
3405 if (!SPSFeatures((*sps1
)->resrec
.rdata
->u
.name
.c
) && SPSFeatures((*sps2
)->resrec
.rdata
->u
.name
.c
) && (metric2
>= metric1
))
3413 mDNSlocal
void ReorderSPSByFeature(const CacheRecord
*sps
[3])
3415 CheckAndSwapSPS(&sps
[0], &sps
[1]);
3416 CheckAndSwapSPS(&sps
[0], &sps
[2]);
3417 CheckAndSwapSPS(&sps
[1], &sps
[2]);
3421 // Finds the three best Sleep Proxies we currently have in our cache
3422 mDNSexport
void FindSPSInCache(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*sps
[3])
3424 sps
[0] = FindSPSInCache1(m
, q
, mDNSNULL
, mDNSNULL
);
3425 sps
[1] = !sps
[0] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], mDNSNULL
);
3426 sps
[2] = !sps
[1] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], sps
[1]);
3428 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3429 // only if they have equally good metric and support features.
3430 ReorderSPSByFeature(sps
);
3433 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3434 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
3437 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3440 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
3443 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3446 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
3449 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3450 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3451 for (i
=0; i
<DupSuppressInfoSize
; i
++)
3452 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
3454 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
3455 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
3456 if (v4
&& v6
) return(mDNStrue
);
3461 mDNSlocal
void RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
3465 // See if we have this one in our list somewhere already
3466 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
3468 // If not, find a slot we can re-use
3469 if (i
>= DupSuppressInfoSize
)
3472 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
3473 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
3477 // Record the info about this query we saw
3479 ds
[i
].InterfaceID
= InterfaceID
;
3483 mDNSlocal
void mDNSSendWakeOnResolve(mDNS
*const m
, DNSQuestion
*q
)
3486 mDNSInterfaceID InterfaceID
= q
->InterfaceID
;
3487 domainname
*d
= &q
->qname
;
3489 // We can't send magic packets without knowing which interface to send it on.
3490 if (InterfaceID
== mDNSInterface_Any
|| LocalOnlyOrP2PInterface(InterfaceID
))
3492 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID
, q
->qname
.c
);
3496 // Split MAC@IPAddress and pass them separately
3499 for (i
= 1; i
< len
; i
++)
3503 char EthAddr
[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3504 char IPAddr
[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3507 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q
->qname
.c
, cnt
);
3510 if ((i
- 1) > (int) (sizeof(EthAddr
) - 1))
3512 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q
->qname
.c
, i
- 1);
3515 if ((len
- i
) > (int)(sizeof(IPAddr
) - 1))
3517 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q
->qname
.c
, len
- i
);
3520 mDNSPlatformMemCopy(EthAddr
, &d
->c
[1], i
- 1);
3522 mDNSPlatformMemCopy(IPAddr
, &d
->c
[i
+ 1], len
- i
);
3523 IPAddr
[len
- i
] = 0;
3524 m
->mDNSStats
.WakeOnResolves
++;
3525 mDNSPlatformSendWakeupPacket(InterfaceID
, EthAddr
, IPAddr
, InitialWakeOnResolveCount
- q
->WakeOnResolveCount
);
3528 else if (d
->c
[i
] == ':')
3531 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q
->qname
.c
);
3535 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
3537 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3538 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
3541 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3542 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
3544 // We forecast: qname (n) type (2) class (2)
3545 mDNSu32 forecast
= (mDNSu32
)DomainNameLength(&q
->qname
) + 4;
3546 const CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3547 const CacheRecord
*cr
;
3548 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // If we have a resource record in our cache,
3549 if (cr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3550 SameNameCacheRecordAnswersQuestion(cr
, q
) && // which answers our question
3551 cr
->TimeRcvd
+ TicksTTL(cr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3552 cr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0) // and we'll ask at least once again before NextRequiredQuery
3554 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3555 forecast
+= 12 + cr
->resrec
.rdestimate
;
3556 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
3564 // How Standard Queries are generated:
3565 // 1. The Question Section contains the question
3566 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3568 // How Probe Queries are generated:
3569 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3570 // if some other host is already using *any* records with this name, we want to know about it.
3571 // 2. The Authority Section contains the proposed values we intend to use for one or more
3572 // of our records with that name (analogous to the Update section of DNS Update packets)
3573 // because if some other host is probing at the same time, we each want to know what the other is
3574 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3576 mDNSlocal
void SendQueries(mDNS
*const m
)
3584 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3585 mDNSs32 maxExistingQuestionInterval
= 0;
3586 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3587 CacheRecord
*KnownAnswerList
= mDNSNULL
;
3589 // 1. If time for a query, work out what we need to do
3591 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3592 // to their NextRequiredQuery to be worth batching them together with this one
3593 FORALL_CACHERECORDS(slot
, cg
, cr
)
3595 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
3597 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
3599 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
3600 q
= cr
->CRActiveQuestion
;
3601 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(cr
)/20, cr
->resrec
.InterfaceID
);
3602 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3603 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3604 if (!mDNSOpaque16IsZero(q
->TargetQID
))
3606 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3607 cr
->UnansweredQueries
++;
3608 m
->mDNSStats
.CacheRefreshQueries
++;
3610 else if (q
->SendQNow
== mDNSNULL
)
3612 q
->SendQNow
= cr
->resrec
.InterfaceID
;
3614 else if (q
->SendQNow
!= cr
->resrec
.InterfaceID
)
3616 q
->SendQNow
= mDNSInterfaceMark
;
3619 // Indicate that this question was marked for sending
3620 // to update an existing cached answer record.
3621 // The browse throttling logic below uses this to determine
3622 // if the query should be sent.
3623 if (mDNSOpaque16IsZero(q
->TargetQID
))
3624 q
->CachedAnswerNeedsUpdate
= mDNStrue
;
3629 // Scan our list of questions to see which:
3630 // *WideArea* queries need to be sent
3631 // *unicast* queries need to be sent
3632 // *multicast* queries we're definitely going to send
3633 if (m
->CurrentQuestion
)
3634 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3635 m
->CurrentQuestion
= m
->Questions
;
3636 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3638 q
= m
->CurrentQuestion
;
3639 if (mDNSOpaque16IsZero(q
->TargetQID
) && TimeToSendThisQuestion(q
, m
->timenow
))
3641 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3642 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3643 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3644 maxExistingQuestionInterval
= q
->ThisQInterval
;
3646 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3647 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3648 // m->CurrentQuestion point to the right question
3649 if (q
== m
->CurrentQuestion
) m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3651 while (m
->CurrentQuestion
)
3653 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3654 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3656 m
->CurrentQuestion
= mDNSNULL
;
3658 // Scan our list of questions
3659 // (a) to see if there are any more that are worth accelerating, and
3660 // (b) to update the state variables for *all* the questions we're going to send
3661 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3662 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3663 // next thing we do is scan the list and call SetNextQueryTime() for every question we find, so we know we end up with the right value.
3664 m
->NextScheduledQuery
= m
->timenow
+ FutureTime
;
3665 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3667 if (mDNSOpaque16IsZero(q
->TargetQID
)
3668 && (q
->SendQNow
|| (ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
))))
3670 // If at least halfway to next query time, advance to next interval
3671 // If less than halfway to next query time, then
3672 // treat this as logically a repeat of the last transmission, without advancing the interval
3673 if (m
->timenow
- (q
->LastQTime
+ (q
->ThisQInterval
/2)) >= 0)
3675 // If we have reached the answer threshold for this question,
3676 // don't send it again until MaxQuestionInterval unless:
3677 // one of its cached answers needs to be refreshed,
3678 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3679 if (q
->BrowseThreshold
3680 && (q
->CurrentAnswers
>= q
->BrowseThreshold
)
3681 && (q
->CachedAnswerNeedsUpdate
== mDNSfalse
)
3682 && !((q
->flags
& kDNSServiceFlagsThresholdFinder
) && (q
->ThisQInterval
== InitialQuestionInterval
)))
3684 q
->SendQNow
= mDNSNULL
;
3685 q
->ThisQInterval
= MaxQuestionInterval
;
3686 q
->LastQTime
= m
->timenow
;
3687 q
->RequestUnicast
= 0;
3688 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3689 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
3693 // Mark this question for sending on all interfaces
3694 q
->SendQNow
= mDNSInterfaceMark
;
3695 q
->ThisQInterval
*= QuestionIntervalStep
;
3698 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3699 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
/ InitialQuestionInterval
, q
->RequestUnicast
);
3701 if (q
->ThisQInterval
> MaxQuestionInterval
)
3703 q
->ThisQInterval
= MaxQuestionInterval
;
3705 else if (mDNSOpaque16IsZero(q
->TargetQID
) && q
->InterfaceID
&&
3706 q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* QuestionIntervalStep3
&& !q
->RequestUnicast
&&
3707 !(RRTypeIsAddressType(q
->qtype
) && CacheHasAddressTypeForName(m
, &q
->qname
, q
->qnamehash
)))
3709 // Generally don't need to log this.
3710 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3711 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3712 // and when there simply happen to be no instances of the service the client is looking
3713 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3714 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3715 q
->qname
.c
, DNSTypeName(q
->qtype
));
3716 // Sending third query, and no answers yet; time to begin doubting the source
3717 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, q
->InterfaceID
, 0);
3721 // Mark for sending. (If no active interfaces, then don't even try.)
3722 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3725 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3726 q
->LastQTime
= m
->timenow
;
3729 // If we recorded a duplicate suppression for this question less than half an interval ago,
3730 // then we consider it recent enough that we don't need to do an identical query ourselves.
3731 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3733 q
->LastQTxTime
= m
->timenow
;
3734 q
->RecentAnswerPkts
= 0;
3735 if (q
->RequestUnicast
) q
->RequestUnicast
--;
3737 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3738 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3739 SetNextQueryTime(m
,q
);
3742 // 2. Scan our authoritative RR list to see what probes we might need to send
3744 m
->NextScheduledProbe
= m
->timenow
+ FutureTime
;
3746 if (m
->CurrentRecord
)
3747 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3748 m
->CurrentRecord
= m
->ResourceRecords
;
3749 while (m
->CurrentRecord
)
3751 ar
= m
->CurrentRecord
;
3752 m
->CurrentRecord
= ar
->next
;
3753 if (!AuthRecord_uDNS(ar
) && ar
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3755 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3756 if (m
->timenow
- (ar
->LastAPTime
+ ar
->ThisAPInterval
) < 0)
3758 SetNextAnnounceProbeTime(m
, ar
);
3760 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3761 else if (ar
->ProbeCount
)
3763 if (ar
->AddressProxy
.type
== mDNSAddrType_IPv4
)
3765 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3766 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3767 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3768 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3769 // A similar concern may apply to the NDP Probe too. -- SC
3770 LogSPS("SendQueries ARP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3771 SendARP(m
, 1, ar
, &zerov4Addr
, &zeroEthAddr
, &ar
->AddressProxy
.ip
.v4
, &ar
->WakeUp
.IMAC
);
3773 else if (ar
->AddressProxy
.type
== mDNSAddrType_IPv6
)
3775 LogSPS("SendQueries NDP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3776 // IPv6 source = zero
3777 // No target hardware address
3778 // IPv6 target address is address we're probing
3779 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3780 SendNDP(m
, NDP_Sol
, 0, ar
, &zerov6Addr
, mDNSNULL
, &ar
->AddressProxy
.ip
.v6
, &ar
->WakeUp
.IMAC
);
3782 // Mark for sending. (If no active interfaces, then don't even try.)
3783 ar
->SendRNow
= (!intf
|| ar
->WakeUp
.HMAC
.l
[0]) ? mDNSNULL
: ar
->resrec
.InterfaceID
? ar
->resrec
.InterfaceID
: intf
->InterfaceID
;
3784 ar
->LastAPTime
= m
->timenow
;
3785 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3786 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3787 if (ar
->ProbeCount
> DefaultProbeCountForTypeUnique
)
3788 ar
->ProbeCount
= DefaultProbeCountForTypeUnique
;
3790 SetNextAnnounceProbeTime(m
, ar
);
3791 if (ar
->ProbeCount
== 0)
3793 // If this is the last probe for this record, then see if we have any matching records
3794 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3796 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3797 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, ar
))
3799 // ... then acknowledge this record to the client.
3800 // We do this optimistically, just as we're about to send the third probe.
3801 // This helps clients that both advertise and browse, and want to filter themselves
3802 // from the browse results list, because it helps ensure that the registration
3803 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3804 // A potential downside is that we could deliver a registration confirmation and then find out
3805 // moments later that there's a name conflict, but applications have to be prepared to handle
3806 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3807 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
);
3810 // else, if it has now finished probing, move it to state Verified,
3811 // and update m->NextScheduledResponse so it will be announced
3814 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
); // Defensive, just in case it got missed somehow
3815 ar
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3816 ar
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3817 ar
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3818 SetNextAnnounceProbeTime(m
, ar
);
3822 m
->CurrentRecord
= m
->DuplicateRecords
;
3823 while (m
->CurrentRecord
)
3825 ar
= m
->CurrentRecord
;
3826 m
->CurrentRecord
= ar
->next
;
3827 if (ar
->resrec
.RecordType
== kDNSRecordTypeUnique
&& ar
->ProbeCount
== 0 && !ar
->Acknowledged
)
3828 AcknowledgeRecord(m
, ar
);
3831 // 3. Now we know which queries and probes we're sending,
3832 // go through our interface list sending the appropriate queries on each interface
3835 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
3836 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
3837 mDNSu8
*queryptr
= m
->omsg
.data
;
3838 mDNSBool useBackgroundTrafficClass
= mDNSfalse
; // set if we should use background traffic class
3840 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, QueryFlags
);
3841 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3842 if (!KnownAnswerList
)
3844 // Start a new known-answer list
3845 CacheRecord
**kalistptr
= &KnownAnswerList
;
3846 mDNSu32 answerforecast
= OwnerRecordSpace
+ TraceRecordSpace
; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3848 // Put query questions in this packet
3849 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3851 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
== intf
->InterfaceID
))
3853 mDNSBool Suppress
= mDNSfalse
;
3854 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3855 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3856 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- m
->omsg
.data
, queryptr
+ answerforecast
- m
->omsg
.data
);
3858 // If interface is P2P type, verify that query should be sent over it.
3859 if (!mDNSPlatformValidQuestionForInterface(q
, intf
))
3861 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3863 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3864 else if ((Suppress
= SuppressOnThisInterface(q
->DupSuppress
, intf
)) ||
3865 BuildQuestion(m
, intf
, &m
->omsg
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3868 m
->mDNSStats
.DupQuerySuppressions
++;
3870 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3871 if (q
->WakeOnResolveCount
)
3873 mDNSSendWakeOnResolve(m
, q
);
3874 q
->WakeOnResolveCount
--;
3877 // use background traffic class if any included question requires it
3878 if (q
->UseBackgroundTraffic
)
3880 useBackgroundTrafficClass
= mDNStrue
;
3886 // Put probe questions in this packet
3887 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3889 if (ar
->SendRNow
!= intf
->InterfaceID
)
3892 // If interface is a P2P variant, verify that the probe should be sent over it.
3893 if (!mDNSPlatformValidRecordForInterface(ar
, intf
->InterfaceID
))
3895 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3896 ar
->IncludeInProbe
= mDNSfalse
;
3900 mDNSBool ucast
= (ar
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3901 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3902 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.numQuestions
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3903 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3904 mDNSu32 forecast
= answerforecast
+ 12 + ar
->resrec
.rdestimate
;
3905 mDNSBool putProbe
= mDNStrue
;
3906 mDNSu16 qclass
= ar
->resrec
.rrclass
| ucbit
;
3908 {// Determine if this probe question is already in packet's dns message
3909 const mDNSu8
*questionptr
= m
->omsg
.data
;
3910 DNSQuestion question
;
3912 for (n
= 0; n
< m
->omsg
.h
.numQuestions
&& questionptr
; n
++)
3914 questionptr
= getQuestion(&m
->omsg
, questionptr
, limit
, mDNSInterface_Any
, &question
);
3915 if (questionptr
&& (question
.qtype
== kDNSQType_ANY
) && (question
.qclass
== qclass
) &&
3916 (question
.qnamehash
== ar
->resrec
.namehash
) && SameDomainName(&question
.qname
, ar
->resrec
.name
))
3918 putProbe
= mDNSfalse
; // set to false if already in message
3926 mDNSu8
*newptr
= putQuestion(&m
->omsg
, queryptr
, limit
- forecast
, ar
->resrec
.name
, kDNSQType_ANY
, qclass
);
3930 answerforecast
= forecast
;
3931 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3932 ar
->IncludeInProbe
= mDNStrue
;
3933 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3934 ar
->resrec
.name
->c
, DNSTypeName(ar
->resrec
.rrtype
), ar
->ProbeCount
, ar
->resrec
.InterfaceID
, ar
->resrec
.rdestimate
, answerforecast
);
3939 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3940 ar
->IncludeInProbe
= mDNStrue
;
3946 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3947 while (KnownAnswerList
)
3949 CacheRecord
*ka
= KnownAnswerList
;
3950 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- ka
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3951 mDNSu8
*newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAnswers
, &ka
->resrec
, ka
->resrec
.rroriginalttl
- SecsSinceRcvd
,
3952 m
->omsg
.data
+ NormalMaxDNSMessageData
- OwnerRecordSpace
- TraceRecordSpace
);
3955 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3956 ka
->resrec
.name
->c
, DNSTypeName(ka
->resrec
.rrtype
), queryptr
- m
->omsg
.data
, newptr
- m
->omsg
.data
);
3958 KnownAnswerList
= ka
->NextInKAList
;
3959 ka
->NextInKAList
= mDNSNULL
;
3963 // If we ran out of space and we have more than one question in the packet, that's an error --
3964 // we shouldn't have put more than one question if there was a risk of us running out of space.
3965 if (m
->omsg
.h
.numQuestions
> 1)
3966 LogMsg("SendQueries: Put %d answers; No more space for known answers", m
->omsg
.h
.numAnswers
);
3967 m
->omsg
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
3972 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3974 if (ar
->IncludeInProbe
)
3976 mDNSu8
*newptr
= PutResourceRecord(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAuthorities
, &ar
->resrec
);
3977 ar
->IncludeInProbe
= mDNSfalse
;
3978 if (newptr
) queryptr
= newptr
;
3979 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m
,ar
));
3983 if (queryptr
> m
->omsg
.data
)
3985 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3986 if (OwnerRecordSpace
|| TraceRecordSpace
)
3989 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3990 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
3991 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
3992 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
3993 if (OwnerRecordSpace
&& TraceRecordSpace
)
3995 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
3996 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
3997 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3998 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
4000 else if (OwnerRecordSpace
)
4002 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
4004 else if (TraceRecordSpace
)
4006 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
4008 queryptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAdditionals
,
4009 &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
4012 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
4013 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
4015 if (queryptr
> m
->omsg
.data
+ NormalMaxDNSMessageData
)
4017 if (m
->omsg
.h
.numQuestions
!= 1 || m
->omsg
.h
.numAnswers
!= 0 || m
->omsg
.h
.numAuthorities
!= 1 || m
->omsg
.h
.numAdditionals
!= 1)
4018 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "",
4019 TraceRecordSpace
? "TRACER" : "", m
->omsg
.data
, m
->omsg
.data
+ NormalMaxDNSMessageData
, queryptr
, m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
,
4020 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
4024 if ((m
->omsg
.h
.flags
.b
[0] & kDNSFlag0_TC
) && m
->omsg
.h
.numQuestions
> 1)
4025 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m
->omsg
.h
.numQuestions
);
4026 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %d (%s)",
4027 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
4028 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
4029 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAuthorities
== 1 ? "" : "s", IIDPrintable(intf
->InterfaceID
), intf
->ifname
);
4030 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, useBackgroundTrafficClass
);
4031 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, useBackgroundTrafficClass
);
4032 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
4033 if (++pktcount
>= 1000)
4034 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
4035 // There might be more records left in the known answer list, or more questions to send
4036 // on this interface, so go around one more time and try again.
4038 else // Nothing more to send on this interface; go to next
4040 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
4041 #if MDNS_DEBUGMSGS && 0
4042 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4043 debugf(msg
, intf
, next
);
4049 // 4. Final housekeeping
4051 // 4a. Debugging check: Make sure we announced all our records
4052 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
4055 if (ar
->ARType
!= AuthRecordLocalOnly
&& ar
->ARType
!= AuthRecordP2P
)
4056 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4057 IIDPrintable(ar
->SendRNow
), IIDPrintable(ar
->resrec
.InterfaceID
), ARDisplayString(m
, ar
));
4058 ar
->SendRNow
= mDNSNULL
;
4061 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4062 // that their interface which went away might come back again, the logic will want to send queries
4063 // for those records, but we can't because their interface isn't here any more, so to keep the
4064 // state machine ticking over we just pretend we did so.
4065 // If the interface does not come back in time, the cache record will expire naturally
4066 FORALL_CACHERECORDS(slot
, cg
, cr
)
4068 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
4070 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
4072 cr
->UnansweredQueries
++;
4073 cr
->CRActiveQuestion
->SendQNow
= mDNSNULL
;
4074 SetNextCacheCheckTimeForRecord(m
, cr
);
4079 // 4c. Debugging check: Make sure we sent all our planned questions
4080 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4081 // we legitimately couldn't send because the interface is no longer available
4082 for (q
= m
->Questions
; q
; q
=q
->next
)
4087 for (x
= m
->NewQuestions
; x
; x
=x
->next
) if (x
== q
) break; // Check if this question is a NewQuestion
4088 // There will not be an active interface for questions applied to mDNSInterface_BLE
4089 // so don't log the warning in that case.
4090 if (q
->InterfaceID
!= mDNSInterface_BLE
)
4091 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4092 IIDPrintable(q
->SendQNow
), x
? "new" : "old", IIDPrintable(q
->InterfaceID
), q
->qname
.c
, DNSTypeName(q
->qtype
));
4093 q
->SendQNow
= mDNSNULL
;
4095 q
->CachedAnswerNeedsUpdate
= mDNSfalse
;
4099 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
)
4103 mDNSu8
*ptr
= m
->omsg
.data
;
4104 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
4105 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID
); return; }
4107 // 0x00 Destination address
4108 for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4110 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4111 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
4113 // 0x0C Ethertype (0x0842)
4117 // 0x0E Wakeup sync sequence
4118 for (i
=0; i
<6; i
++) *ptr
++ = 0xFF;
4121 for (j
=0; j
<16; j
++) for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4124 for (i
=0; i
<6; i
++) *ptr
++ = password
->b
[i
];
4126 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4130 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4131 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4132 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4133 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4134 // So, we send one of each, unicast first, then broadcast second.
4135 for (i
=0; i
<6; i
++) m
->omsg
.data
[i
] = 0xFF;
4136 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4140 // ***************************************************************************
4141 #if COMPILER_LIKES_PRAGMA_MARK
4143 #pragma mark - RR List Management & Task Management
4146 // Whenever a question is answered, reset its state so that we don't query
4147 // the network repeatedly. This happens first time when we answer the question and
4148 // and later when we refresh the cache.
4149 mDNSlocal
void ResetQuestionState(mDNS
*const m
, DNSQuestion
*q
)
4151 q
->LastQTime
= m
->timenow
;
4152 q
->LastQTxTime
= m
->timenow
;
4153 q
->RecentAnswerPkts
= 0;
4154 q
->ThisQInterval
= MaxQuestionInterval
;
4155 q
->RequestUnicast
= 0;
4156 // Reset unansweredQueries so that we don't penalize this server later when we
4157 // start sending queries when the cache expires.
4158 q
->unansweredQueries
= 0;
4159 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4162 mDNSlocal
void AdjustUnansweredQueries(mDNS
*const m
, CacheRecord
*const rr
)
4164 const mDNSs32 expireTime
= RRExpireTime(rr
);
4165 const mDNSu32 interval
= TicksTTL(rr
) / 20; // Calculate 5% of the cache record's TTL.
4168 // If the record is expired or UnansweredQueries is already at the max, then return early.
4169 if (((m
->timenow
- expireTime
) >= 0) || (rr
->UnansweredQueries
>= MaxUnansweredQueries
)) return;
4173 LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr
), CRDisplayString(m
, rr
));
4177 // Calculate the number of whole 5% TTL intervals between now and expiration time.
4178 rem
= ((mDNSu32
)(expireTime
- m
->timenow
)) / interval
;
4180 // Calculate the expected number of remaining refresher queries.
4181 // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals.
4182 if (rem
> MaxUnansweredQueries
) rem
= MaxUnansweredQueries
;
4184 // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time
4185 // was missed. This can happen if the cache record didn't have an active question during any of the times at which
4186 // refresher queries would have been sent if the cache record did have an active question. The cache record's
4187 // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up
4188 // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an
4189 // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining
4190 // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to
4191 // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires.
4192 // Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed.
4193 if ((MaxUnansweredQueries
- rr
->UnansweredQueries
) > (mDNSs32
)rem
)
4195 if (rem
== 0) rem
++;
4196 rr
->UnansweredQueries
= (mDNSu8
)(MaxUnansweredQueries
- rem
);
4200 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4201 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4202 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4203 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4204 mDNSexport
void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
)
4206 DNSQuestion
*const q
= m
->CurrentQuestion
;
4207 const mDNSBool followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
4209 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
4210 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", MortalityDisplayString(rr
->resrec
.mortality
),
4211 rr
->resrec
.rroriginalttl
, CRDisplayString(m
, rr
));
4213 // When the response for the question was validated, the entire rrset was validated. If we deliver
4214 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
4215 // in the future, we will do the revalidation again.
4217 // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
4218 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
4219 // negative response which can happen e.g., when disconnecting from network that leads to a negative response
4220 // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
4221 // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
4222 // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
4223 // a real negative response, we would reset the state here and validate the results at the end of this function.
4224 // or the real response again if we purge the cache.
4225 if (q
->ValidationRequired
&& ((AddRecord
== QC_rmv
) ||
4226 (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
&& (AddRecord
== QC_add
))))
4228 q
->ValidationStatus
= 0;
4229 q
->ValidationState
= DNSSECValRequired
;
4232 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4233 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4234 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4235 // we check to see if that query already has a unique local answer.
4236 if (q
->LOAddressAnswers
)
4238 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4239 "LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
),
4240 q
->LOAddressAnswers
);
4244 if (q
->Suppressed
&& (AddRecord
!= QC_suppressed
))
4246 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4247 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4248 // that are timing out, which we know are answered with negative cache record when timing out.
4249 if (!q
->TimeoutQuestion
|| rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| (m
->timenow
- q
->StopTime
< 0))
4253 // Set the record to immortal if appropriate
4254 if (AddRecord
== QC_add
&& Question_uDNS(q
) && rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&&
4255 q
->allowExpired
!= AllowExpired_None
&& rr
->resrec
.mortality
== Mortality_Mortal
) rr
->resrec
.mortality
= Mortality_Immortal
; // Update a non-expired cache record to immortal if appropriate
4257 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4258 if ((AddRecord
== QC_add
) && Question_uDNS(q
) && !followcname
)
4260 const domainname
* queryName
;
4261 mDNSu32 responseLatencyMs
;
4262 mDNSBool isForCellular
;
4264 queryName
= q
->metrics
.originalQName
? q
->metrics
.originalQName
: &q
->qname
;
4265 isForCellular
= (q
->qDNSServer
&& q
->qDNSServer
->isCell
);
4266 if (!q
->metrics
.answered
)
4268 if (q
->metrics
.querySendCount
> 0)
4270 responseLatencyMs
= ((m
->timenow
- q
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
4274 responseLatencyMs
= 0;
4277 MetricsUpdateDNSQueryStats(queryName
, q
->qtype
, &rr
->resrec
, q
->metrics
.querySendCount
, q
->metrics
.expiredAnswerState
, q
->metrics
.dnsOverTCPState
, responseLatencyMs
, isForCellular
);
4278 q
->metrics
.answered
= mDNStrue
;
4282 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4283 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4284 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4286 if (AddRecord
== QC_add
&& !q
->DuplicateOf
&& rr
->CRActiveQuestion
!= q
&& rr
->resrec
.mortality
!= Mortality_Ghost
)
4288 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4289 rr
->CRActiveQuestion
, q
, CRDisplayString(m
,rr
), q
->CurrentAnswers
);
4290 if (!rr
->CRActiveQuestion
)
4292 m
->rrcache_active
++; // If not previously active, increment rrcache_active count
4293 AdjustUnansweredQueries(m
, rr
); // Adjust UnansweredQueries in case the record missed out on refresher queries
4295 rr
->CRActiveQuestion
= q
; // We know q is non-null
4296 SetNextCacheCheckTimeForRecord(m
, rr
);
4300 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4301 // (b) a normal add, where we have at least one unique-type answer,
4302 // then there's no need to keep polling the network.
4303 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4304 // We do this for mDNS questions and uDNS one-shot questions, but not for
4305 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4306 if ((AddRecord
== QC_addnocache
&& !q
->RequestUnicast
) ||
4307 (AddRecord
== QC_add
&& (q
->ExpectUnique
|| (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))))
4308 if (ActiveQuestion(q
) && (mDNSOpaque16IsZero(q
->TargetQID
) || !q
->LongLived
))
4310 ResetQuestionState(m
, q
);
4313 if (rr
->DelayDelivery
) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4315 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4316 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4317 if (!mDNSOpaque16IsZero(q
->TargetQID
) && DNS64StateMachine(m
, q
, &rr
->resrec
, AddRecord
)) return;
4321 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) // If negative answer, check if we need to try Punycode conversion
4324 if (PerformNextPunycodeConversion(q
, &newname
)) // Itertative Punycode conversion succeeded, so reissue question with new name
4326 UDPSocket
*const sock
= q
->LocalSocket
; // Save old socket and transaction ID
4327 const mDNSOpaque16 id
= q
->TargetQID
;
4328 q
->LocalSocket
= mDNSNULL
;
4329 mDNS_StopQuery_internal(m
, q
); // Stop old query
4330 AssignDomainName(&q
->qname
, &newname
); // Update qname
4331 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
4332 mDNS_StartQuery_internal(m
, q
); // Start new query
4334 if (sock
) // Transplant saved socket, if appropriate
4336 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
4337 else { q
->LocalSocket
= sock
; q
->TargetQID
= id
; }
4339 return; // All done for now; wait until we get the next answer
4342 #endif // USE_LIBIDN
4344 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4345 // for the purpose of retrying search domains/timeout OR the question is suppressed
4346 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
|| (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
)))
4347 if (!AddRecord
|| (AddRecord
!= QC_suppressed
&& AddRecord
!= QC_forceresponse
&& !q
->ReturnIntermed
)) return;
4349 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4350 if (q
->QuestionCallback
&& !q
->NoAnswer
&& (!followcname
|| q
->ReturnIntermed
))
4352 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4353 if (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
))
4356 MakeNegativeCacheRecord(m
, &neg
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 1, rr
->resrec
.InterfaceID
, q
->qDNSServer
);
4357 q
->QuestionCallback(m
, q
, &neg
.resrec
, AddRecord
);
4361 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4362 if (DNS64ShouldAnswerQuestion(q
, &rr
->resrec
))
4364 DNS64AnswerCurrentQuestion(m
, &rr
->resrec
, AddRecord
);
4369 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4372 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4374 // Note: Proceed with caution after this point because client callback function
4375 // invoked above is allowed to do anything, such as starting/stopping queries
4376 // (including this one itself, or the next or previous query in the linked list),
4377 // registering/deregistering records, starting/stopping NAT traversals, etc.
4379 // If this is an "Add" operation and this question needs validation, validate the response.
4380 // In the case of negative responses, extra care should be taken. Negative cache records are
4381 // used for many purposes. For example,
4383 // 1) Suppressing questions (SuppressUnusable)
4384 // 2) Timeout questions
4385 // 3) The name does not exist
4386 // 4) No DNS servers are available and we need a quick response for the application
4388 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
4389 // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
4390 // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
4391 // signature for (4) and hence the explicit check for q->qDNSServer.
4393 if (m
->CurrentQuestion
== q
&& (AddRecord
== QC_add
) && !q
->ValidatingResponse
&& q
->ValidationRequired
&&
4394 q
->ValidationState
== DNSSECValRequired
&& q
->qDNSServer
)
4396 q
->ValidationState
= DNSSECValInProgress
;
4397 // Treat it as callback call as that's what dnssec code expects
4398 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4399 VerifySignature(m
, mDNSNULL
, q
);
4400 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4404 if ((m
->CurrentQuestion
== q
) && !ValidatingQuestion(q
))
4406 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4407 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4408 // first before following it
4409 if (followcname
) AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
4411 // If we are returning expired RRs, then remember the first expired qname we we can start the query again
4412 if (rr
->resrec
.mortality
== Mortality_Ghost
&& !q
->firstExpiredQname
.c
[0] && (q
->allowExpired
== AllowExpired_AllowExpiredAnswers
) && rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
4414 debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m
,rr
), q
);
4415 // Note: question->qname is already changed at this point if following a CNAME
4416 AssignDomainName(&q
->firstExpiredQname
, rr
->resrec
.name
); // Update firstExpiredQname
4421 mDNSlocal
void CacheRecordDeferredAdd(mDNS
*const m
, CacheRecord
*cr
)
4423 cr
->DelayDelivery
= 0;
4424 if (m
->CurrentQuestion
)
4425 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4426 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4427 m
->CurrentQuestion
= m
->Questions
;
4428 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4430 DNSQuestion
*q
= m
->CurrentQuestion
;
4431 if (CacheRecordAnswersQuestion(cr
, q
))
4432 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
4433 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4434 m
->CurrentQuestion
= q
->next
;
4436 m
->CurrentQuestion
= mDNSNULL
;
4439 mDNSlocal mDNSs32
CheckForSoonToExpireRecords(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
4441 const mDNSs32 threshold
= m
->timenow
+ mDNSPlatformOneSecond
; // See if there are any records expiring within one second
4442 const mDNSs32 start
= m
->timenow
- 0x10000000;
4443 mDNSs32 delay
= start
;
4444 CacheGroup
*cg
= CacheGroupForName(m
, namehash
, name
);
4445 const CacheRecord
*rr
;
4447 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4449 if (threshold
- RRExpireTime(rr
) >= 0) // If we have records about to expire within a second
4451 if (delay
- RRExpireTime(rr
) < 0) // then delay until after they've been deleted
4452 delay
= RRExpireTime(rr
);
4455 if (delay
- start
> 0)
4456 return(NonZeroTime(delay
));
4461 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4462 // If new questions are created as a result of invoking client callbacks, they will be added to
4463 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4464 // rr is a new CacheRecord just received into our cache
4465 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4466 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4467 // which may change the record list and/or question list.
4468 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4469 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*cr
)
4473 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4474 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4475 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
4477 if (CacheRecordAnswersQuestion(cr
, q
))
4479 // If this question is one that's actively sending queries, and it's received ten answers within one
4480 // second of sending the last query packet, then that indicates some radical network topology change,
4481 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4482 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4483 // because we will anyway send another query within a few seconds. The first reset query is sent out
4484 // randomized over the next four seconds to reduce possible synchronization between machines.
4485 if (q
->LastAnswerPktNum
!= m
->PktNum
)
4487 q
->LastAnswerPktNum
= m
->PktNum
;
4488 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
) && ++q
->RecentAnswerPkts
>= 10 &&
4489 q
->ThisQInterval
> InitialQuestionInterval
* QuestionIntervalStep3
&& m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
4491 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4492 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->RecentAnswerPkts
, q
->ThisQInterval
);
4493 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
4494 q
->ThisQInterval
= InitialQuestionInterval
;
4495 SetNextQueryTime(m
,q
);
4498 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr
, cr
->resrec
.name
->c
,
4499 DNSTypeName(cr
->resrec
.rrtype
), cr
->resrec
.rroriginalttl
, cr
->resrec
.rDNSServer
?
4500 &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
, mDNSVal16(cr
->resrec
.rDNSServer
?
4501 cr
->resrec
.rDNSServer
->port
: zeroIPPort
), q
);
4502 q
->CurrentAnswers
++;
4504 q
->unansweredQueries
= 0;
4505 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4506 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4507 if (q
->CurrentAnswers
> 4000)
4509 static int msgcount
= 0;
4510 if (msgcount
++ < 10)
4511 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4512 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CurrentAnswers
);
4513 cr
->resrec
.rroriginalttl
= 0;
4514 cr
->UnansweredQueries
= MaxUnansweredQueries
;
4519 if (!cr
->DelayDelivery
)
4521 if (m
->CurrentQuestion
)
4522 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4523 m
->CurrentQuestion
= m
->Questions
;
4524 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4526 q
= m
->CurrentQuestion
;
4527 if (CacheRecordAnswersQuestion(cr
, q
))
4528 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
4529 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4530 m
->CurrentQuestion
= q
->next
;
4532 m
->CurrentQuestion
= mDNSNULL
;
4535 SetNextCacheCheckTimeForRecord(m
, cr
);
4538 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4539 // If new questions are created as a result of invoking client callbacks, they will be added to
4540 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4541 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4542 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4543 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4544 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4545 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4546 // which may change the record list and/or question list.
4547 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4548 mDNSlocal
void NoCacheAnswer(mDNS
*const m
, CacheRecord
*cr
)
4550 LogMsg("No cache space: Delivering non-cached result for %##s", m
->rec
.r
.resrec
.name
->c
);
4551 if (m
->CurrentQuestion
)
4552 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4553 m
->CurrentQuestion
= m
->Questions
;
4554 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4555 // since we're not caching the record and we'll get no opportunity to do this later
4556 while (m
->CurrentQuestion
)
4558 DNSQuestion
*q
= m
->CurrentQuestion
;
4559 if (CacheRecordAnswersQuestion(cr
, q
))
4560 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_addnocache
); // QC_addnocache means "don't expect remove events for this"
4561 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4562 m
->CurrentQuestion
= q
->next
;
4564 m
->CurrentQuestion
= mDNSNULL
;
4567 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4568 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4569 // If new questions are created as a result of invoking client callbacks, they will be added to
4570 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4571 // cr is an existing cache CacheRecord that just expired and is being deleted
4572 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4573 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4574 // which may change the record list and/or question list.
4575 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4576 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*cr
)
4578 if (m
->CurrentQuestion
)
4579 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4580 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4581 m
->CurrentQuestion
= m
->Questions
;
4583 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4584 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4585 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4587 DNSQuestion
*q
= m
->CurrentQuestion
;
4588 // When a question enters suppressed state, we generate RMV events and generate a negative
4589 // response. A cache may be present that answers this question e.g., cache entry generated
4590 // before the question became suppressed. We need to skip the suppressed questions here as
4591 // the RMV event has already been generated.
4592 if (!q
->Suppressed
&& CacheRecordAnswersQuestion(cr
, q
) &&
4593 (q
->allowExpired
== AllowExpired_None
|| cr
->resrec
.mortality
== Mortality_Mortal
))
4595 verbosedebugf("CacheRecordRmv %p %s", cr
, CRDisplayString(m
, cr
));
4596 q
->FlappingInterface1
= mDNSNULL
;
4597 q
->FlappingInterface2
= mDNSNULL
;
4599 if (q
->CurrentAnswers
== 0)
4600 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4601 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
4602 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
4605 q
->CurrentAnswers
--;
4606 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
4607 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
4610 // If we have dropped below the answer threshold for this mDNS question,
4611 // restart the queries at InitialQuestionInterval.
4612 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->BrowseThreshold
> 0) && (q
->CurrentAnswers
< q
->BrowseThreshold
))
4614 q
->ThisQInterval
= InitialQuestionInterval
;
4615 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4616 SetNextQueryTime(m
,q
);
4617 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4618 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
4620 if (cr
->resrec
.rdata
->MaxRDLength
) // Never generate "remove" events for negative results
4622 if ((q
->CurrentAnswers
== 0) && mDNSOpaque16IsZero(q
->TargetQID
))
4624 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4625 q
->qname
.c
, DNSTypeName(q
->qtype
));
4626 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, cr
->resrec
.InterfaceID
, 0);
4628 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_rmv
);
4631 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4632 m
->CurrentQuestion
= q
->next
;
4634 m
->CurrentQuestion
= mDNSNULL
;
4637 mDNSlocal
void ReleaseCacheEntity(mDNS
*const m
, CacheEntity
*e
)
4639 #if MDNS_MALLOC_DEBUGGING >= 1
4641 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
4643 e
->next
= m
->rrcache_free
;
4644 m
->rrcache_free
= e
;
4645 m
->rrcache_totalused
--;
4648 mDNSlocal
void ReleaseCacheGroup(mDNS
*const m
, CacheGroup
**cp
)
4650 CacheEntity
*e
= (CacheEntity
*)(*cp
);
4651 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4652 if ((*cp
)->rrcache_tail
!= &(*cp
)->members
)
4653 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4654 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4655 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4656 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
4657 (*cp
)->name
= mDNSNULL
;
4658 *cp
= (*cp
)->next
; // Cut record from list
4659 ReleaseCacheEntity(m
, e
);
4662 mDNSlocal
void ReleaseAdditionalCacheRecords(mDNS
*const m
, CacheRecord
**rp
)
4666 CacheRecord
*rr
= *rp
;
4667 *rp
= (*rp
)->next
; // Cut record from list
4668 if (rr
->resrec
.rdata
&& rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
)
4670 mDNSPlatformMemFree(rr
->resrec
.rdata
);
4671 rr
->resrec
.rdata
= mDNSNULL
;
4673 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4674 // of the CacheGroup.
4675 if (rr
->resrec
.name
)
4677 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
4678 mDNSPlatformMemFree((void *)rr
->resrec
.name
);
4679 rr
->resrec
.name
= mDNSNULL
;
4681 // Don't count the NSEC3 records used by anonymous browse/reg
4682 if (!rr
->resrec
.InterfaceID
)
4684 m
->rrcache_totalused_unicast
-= rr
->resrec
.rdlength
;
4685 if (DNSSECRecordType(rr
->resrec
.rrtype
))
4686 BumpDNSSECStats(m
, kStatsActionDecrement
, kStatsTypeMemoryUsage
, rr
->resrec
.rdlength
);
4688 ReleaseCacheEntity(m
, (CacheEntity
*)rr
);
4692 mDNSexport
void ReleaseCacheRecord(mDNS
*const m
, CacheRecord
*r
)
4696 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4697 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->smallrdatastorage
) mDNSPlatformMemFree(r
->resrec
.rdata
);
4698 r
->resrec
.rdata
= mDNSNULL
;
4700 cg
= CacheGroupForRecord(m
, &r
->resrec
);
4704 // It is okay to have this printed for NSEC/NSEC3s
4705 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4707 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4708 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4709 // (which is handled below) and in that case it should be freed here.
4710 if (r
->resrec
.name
&& cg
&& r
->resrec
.name
!= cg
->name
)
4712 debugf("ReleaseCacheRecord: freeing %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4713 mDNSPlatformMemFree((void *)r
->resrec
.name
);
4715 r
->resrec
.name
= mDNSNULL
;
4717 if (!r
->resrec
.InterfaceID
)
4719 m
->rrcache_totalused_unicast
-= r
->resrec
.rdlength
;
4720 if (DNSSECRecordType(r
->resrec
.rrtype
))
4721 BumpDNSSECStats(m
, kStatsActionDecrement
, kStatsTypeMemoryUsage
, r
->resrec
.rdlength
);
4724 ReleaseAdditionalCacheRecords(m
, &r
->nsec
);
4725 ReleaseAdditionalCacheRecords(m
, &r
->soa
);
4727 ReleaseCacheEntity(m
, (CacheEntity
*)r
);
4730 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4731 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4732 // callbacks for old records are delivered before callbacks for newer records.
4733 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*const cg
)
4735 CacheRecord
**rp
= &cg
->members
;
4737 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4738 m
->lock_rrcache
= 1;
4742 CacheRecord
*const rr
= *rp
;
4743 mDNSBool recordReleased
= mDNSfalse
;
4744 mDNSs32 event
= RRExpireTime(rr
);
4745 if (m
->timenow
- event
>= 0) // If expired, delete it
4747 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
4749 DNSQuestion
*q
= rr
->CRActiveQuestion
;
4750 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
4751 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4752 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4753 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4754 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4755 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4756 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4757 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4758 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4759 if (((mDNSOpaque16IsZero(q
->TargetQID
) && (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)) ||
4760 (!mDNSOpaque16IsZero(q
->TargetQID
) && !q
->LongLived
)) && ActiveQuestion(q
))
4762 q
->ThisQInterval
= InitialQuestionInterval
;
4763 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4764 SetNextQueryTime(m
, q
);
4766 CacheRecordRmv(m
, rr
);
4767 m
->rrcache_active
--;
4770 event
+= MAX_GHOST_TIME
; // Adjust so we can check for a ghost expiration
4771 if (rr
->resrec
.mortality
== Mortality_Mortal
|| // Normal expired mortal record that needs released
4772 (rr
->resrec
.mortality
== Mortality_Ghost
&& m
->timenow
- event
>= 0)) // A ghost record that expired more than MAX_GHOST_TIME ago
4773 { // Release as normal
4774 *rp
= rr
->next
; // Cut it from the list before ReleaseCacheRecord
4775 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
4776 MortalityDisplayString(rr
->resrec
.mortality
),
4777 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4778 ReleaseCacheRecord(m
, rr
);
4779 recordReleased
= mDNStrue
;
4781 else // An immortal record needs to become a ghost when it expires
4782 { // Don't release this entry
4783 if (rr
->resrec
.mortality
== Mortality_Immortal
)
4785 rr
->resrec
.mortality
= Mortality_Ghost
; // Expired immortal records become ghosts
4786 verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
4787 MortalityDisplayString(rr
->resrec
.mortality
),
4788 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4792 else // else, not expired; see if we need to query
4794 // If waiting to delay delivery, do nothing until then
4795 if (rr
->DelayDelivery
&& rr
->DelayDelivery
- m
->timenow
> 0)
4796 event
= rr
->DelayDelivery
;
4799 if (rr
->DelayDelivery
) CacheRecordDeferredAdd(m
, rr
);
4800 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
4802 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
4803 event
= NextCacheCheckEvent(rr
); // then just record when we want the next query
4804 else // else trigger our question to go out now
4806 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4807 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4808 m
->NextScheduledQuery
= m
->timenow
;
4809 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4810 // which will correctly update m->NextCacheCheck for us.
4811 event
= m
->timenow
+ FutureTime
;
4817 if (!recordReleased
) // Schedule if we did not release the record
4819 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4820 (event
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
, rr
));
4821 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
4822 m
->rrcache_nextcheck
[slot
] = event
;
4826 if (cg
->rrcache_tail
!= rp
) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg
->rrcache_tail
, rp
);
4827 cg
->rrcache_tail
= rp
;
4828 m
->lock_rrcache
= 0;
4831 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4833 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4834 // returns true if there is an answer.
4836 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4837 // returns true to indicate the same.
4838 mDNSlocal mDNSBool
AnswerQuestionWithLORecord(mDNS
*const m
, DNSQuestion
*q
, mDNSBool checkOnly
)
4843 if (m
->CurrentRecord
)
4844 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4846 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
4849 m
->CurrentRecord
= ag
->members
;
4850 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
4852 AuthRecord
*rr
= m
->CurrentRecord
;
4853 m
->CurrentRecord
= rr
->next
;
4855 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4856 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4858 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4859 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4860 // we handle both mDNSInterface_Any and scoped questions.
4862 if (rr
->ARType
== AuthRecordLocalOnly
|| (rr
->ARType
== AuthRecordP2P
&& (q
->InterfaceID
== mDNSInterface_Any
|| q
->InterfaceID
== mDNSInterface_BLE
)))
4863 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
4867 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q
->qname
.c
, DNSTypeName(q
->qtype
),
4868 ARDisplayString(m
, rr
));
4869 m
->CurrentRecord
= mDNSNULL
;
4872 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_add
);
4873 if (m
->CurrentQuestion
!= q
)
4874 break; // If callback deleted q, then we're finished here
4878 m
->CurrentRecord
= mDNSNULL
;
4880 if (m
->CurrentQuestion
!= q
)
4882 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4886 if (q
->LOAddressAnswers
)
4888 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4889 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4893 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4894 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4895 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4896 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4897 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4900 lr
= ag
->NewLocalOnlyRecords
;
4903 if (UniqueLocalOnlyRecord(lr
) && LocalOnlyRecordAnswersQuestion(lr
, q
))
4905 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4906 " LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4915 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4916 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4918 mDNSlocal
void AnswerSuppressedQuestion(mDNS
*const m
, DNSQuestion
*q
)
4920 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response,
4921 // just deactivate the DNSQuestion.
4922 if (q
->ReturnIntermed
)
4924 GenerateNegativeResponse(m
, mDNSInterface_Any
, QC_suppressed
);
4928 q
->ThisQInterval
= 0;
4932 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
4934 mDNSBool ShouldQueryImmediately
= mDNStrue
;
4935 DNSQuestion
*const q
= m
->NewQuestions
; // Grab the question we're going to answer
4936 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4937 if (!mDNSOpaque16IsZero(q
->TargetQID
)) DNS64HandleNewQuestion(m
, q
);
4939 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
4941 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4943 if (cg
) CheckCacheExpiration(m
, HashSlotFromNameHash(q
->qnamehash
), cg
);
4944 if (m
->NewQuestions
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit
; }
4945 m
->NewQuestions
= q
->next
;
4946 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4947 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4949 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4950 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4951 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4952 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4953 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4954 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4955 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4956 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4958 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4959 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4960 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4961 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4963 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4964 // This should be safe, because calling the client's question callback may cause the
4965 // question list to be modified, but should not ever cause the rrcache list to be modified.
4966 // If the client's question callback deletes the question, then m->CurrentQuestion will
4967 // be advanced, and we'll exit out of the loop
4968 m
->lock_rrcache
= 1;
4969 if (m
->CurrentQuestion
) {
4970 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
4971 "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME
" (" PUB_S
")",
4972 m
->CurrentQuestion
->request_id
, mDNSVal16(m
->CurrentQuestion
->TargetQID
),
4973 DM_NAME_PARAM(m
->CurrentQuestion
->qname
.c
), DNSTypeName(m
->CurrentQuestion
->qtype
));
4976 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4978 if (q
->NoAnswer
== NoAnswer_Fail
)
4980 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
4981 "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME
" (" PUB_S
")",
4982 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
4984 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->qDNSServer
);
4985 q
->NoAnswer
= NoAnswer_Normal
; // Temporarily turn off answer suppression
4986 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
4987 // Don't touch the question if it has been stopped already
4988 if (m
->CurrentQuestion
== q
) q
->NoAnswer
= NoAnswer_Fail
; // Restore NoAnswer state
4989 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4992 if (m
->CurrentQuestion
!= q
)
4994 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4998 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4999 // or P2P record, then we are done.
5000 if (AnswerQuestionWithLORecord(m
, q
, mDNSfalse
))
5003 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
5004 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
5005 // the question out.
5008 AnswerSuppressedQuestion(m
, q
);
5010 else if (!q
->ValidatingResponse
)
5013 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
5014 if (SameNameCacheRecordAnswersQuestion(cr
, q
))
5016 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
5017 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- cr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
5018 mDNSBool IsExpired
= (cr
->resrec
.rroriginalttl
<= SecsSinceRcvd
);
5019 if (IsExpired
&& q
->allowExpired
!= AllowExpired_AllowExpiredAnswers
) continue; // Go to next one in loop
5021 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
5022 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
5023 if ((cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) || (q
->ExpectUnique
))
5024 ShouldQueryImmediately
= mDNSfalse
;
5025 q
->CurrentAnswers
++;
5026 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
5027 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
5028 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
5029 if (q
->metrics
.expiredAnswerState
== ExpiredAnswer_Allowed
) q
->metrics
.expiredAnswerState
= IsExpired
? ExpiredAnswer_AnsweredWithExpired
: ExpiredAnswer_AnsweredWithCache
;
5031 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
5032 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5034 else if (mDNSOpaque16IsZero(q
->TargetQID
) && RRTypeIsAddressType(cr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
5035 ShouldQueryImmediately
= mDNSfalse
;
5037 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
5038 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
5039 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit
; }
5041 q
->InitialCacheMiss
= mDNStrue
; // Initial cache check is done, so mark as a miss from now on
5042 if (q
->allowExpired
== AllowExpired_AllowExpiredAnswers
)
5044 q
->allowExpired
= AllowExpired_MakeAnswersImmortal
; // After looking through the cache for an answer, demote to make immortal
5045 if (q
->firstExpiredQname
.c
[0]) // If an original query name was saved on an expired answer, start it over in case it is updated
5047 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
5048 "[R%d->Q%d] AnswerNewQuestion: Restarting original question %p firstExpiredQname " PRI_DM_NAME
" for allowExpiredAnswers question",
5049 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->firstExpiredQname
.c
));
5050 mDNS_StopQuery_internal(m
, q
); // Stop old query
5051 AssignDomainName(&q
->qname
, &q
->firstExpiredQname
); // Update qname
5052 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
5053 mDNS_StartQuery_internal(m
, q
); // start new query
5054 q
->CNAMEReferrals
= 0; // Reset referral count
5055 q
->firstExpiredQname
.c
[0] = 0; // Erase the domain name
5059 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
5060 // Hence we don't execute the following block of code for those cases.
5061 if (ShouldQueryImmediately
&& ActiveQuestion(q
))
5063 debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q
->request_id
, mDNSVal16(q
->TargetQID
), q
->qname
.c
, DNSTypeName(q
->qtype
));
5064 q
->ThisQInterval
= InitialQuestionInterval
;
5065 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
5066 if (mDNSOpaque16IsZero(q
->TargetQID
)) // For mDNS, spread packets to avoid a burst of simultaneous queries
5068 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
5069 if (!m
->RandomQueryDelay
)
5070 m
->RandomQueryDelay
= (mDNSPlatformOneSecond
+ mDNSRandom(mDNSPlatformOneSecond
*5) - 1) / 50 + 1;
5071 q
->LastQTime
+= m
->RandomQueryDelay
;
5075 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5076 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5077 // answers for this question until *after* its scheduled transmission time, in which case
5078 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5079 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5080 SetNextQueryTime(m
,q
);
5083 m
->CurrentQuestion
= mDNSNULL
;
5084 m
->lock_rrcache
= 0;
5087 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5088 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
5089 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
5092 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
5093 mDNSBool retEv
= mDNSfalse
;
5094 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewLocalOnlyQuestions to the next (if any)
5096 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5098 if (m
->CurrentQuestion
)
5099 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5100 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5101 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
5103 if (m
->CurrentRecord
)
5104 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
5106 // 1. First walk the LocalOnly records answering the LocalOnly question
5107 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5108 // walk the ResourceRecords list delivering the answers
5109 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
5112 m
->CurrentRecord
= ag
->members
;
5113 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
5115 AuthRecord
*rr
= m
->CurrentRecord
;
5116 m
->CurrentRecord
= rr
->next
;
5117 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
5120 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_add
);
5121 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5126 if (m
->CurrentQuestion
== q
)
5128 m
->CurrentRecord
= m
->ResourceRecords
;
5130 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
5132 AuthRecord
*ar
= m
->CurrentRecord
;
5133 m
->CurrentRecord
= ar
->next
;
5134 if (AuthRecordAnswersQuestion(ar
, q
))
5137 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, QC_add
);
5138 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5143 // The local host is the authoritative source for LocalOnly questions
5144 // so if no records exist and client requested intermediates, then generate a negative response
5145 if (!retEv
&& (m
->CurrentQuestion
== q
) && q
->ReturnIntermed
)
5146 GenerateNegativeResponse(m
, mDNSInterface_LocalOnly
, QC_forceresponse
);
5148 m
->CurrentQuestion
= mDNSNULL
;
5149 m
->CurrentRecord
= mDNSNULL
;
5152 mDNSlocal CacheEntity
*GetCacheEntity(mDNS
*const m
, const CacheGroup
*const PreserveCG
)
5154 CacheEntity
*e
= mDNSNULL
;
5156 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
5157 m
->lock_rrcache
= 1;
5159 // If we have no free records, ask the client layer to give us some more memory
5160 if (!m
->rrcache_free
&& m
->MainCallback
)
5162 if (m
->rrcache_totalused
!= m
->rrcache_size
)
5164 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
5165 "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u",
5166 m
->rrcache_totalused
, m
->rrcache_size
);
5169 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5170 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5171 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5172 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5173 // and recycle them, instead of allocating more memory.
5174 if (m
->rrcache_size
> 5000 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
5176 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
5177 "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u",
5178 m
->rrcache_size
, m
->rrcache_active
);
5182 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5183 m
->MainCallback(m
, mStatus_GrowCache
);
5184 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5188 // If we still have no free records, recycle all the records we can.
5189 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5190 if (!m
->rrcache_free
)
5192 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
5194 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5196 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5199 CacheRecord
**rp
= &(*cp
)->members
;
5202 // Records that answer still-active questions are not candidates for recycling
5203 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5204 if ((*rp
)->CRActiveQuestion
|| (*rp
)->NextInCFList
)
5208 CacheRecord
*rr
= *rp
;
5209 *rp
= (*rp
)->next
; // Cut record from list
5210 ReleaseCacheRecord(m
, rr
);
5213 if ((*cp
)->rrcache_tail
!= rp
)
5214 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot
, (*cp
)->rrcache_tail
, rp
);
5215 (*cp
)->rrcache_tail
= rp
;
5216 if ((*cp
)->members
|| (*cp
)==PreserveCG
) cp
=&(*cp
)->next
;
5217 else ReleaseCacheGroup(m
, cp
);
5220 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "GetCacheEntity recycled %d records to reduce cache from %d to %d",
5221 oldtotalused
- m
->rrcache_totalused
, oldtotalused
, m
->rrcache_totalused
);
5224 if (m
->rrcache_free
) // If there are records in the free list, take one
5226 e
= m
->rrcache_free
;
5227 m
->rrcache_free
= e
->next
;
5228 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
5230 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "RR Cache now using %u objects", m
->rrcache_totalused
);
5231 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
5232 else if (m
->rrcache_report
< 1000) m
->rrcache_report
+= 100;
5233 else m
->rrcache_report
+= 1000;
5235 mDNSPlatformMemZero(e
, sizeof(*e
));
5238 m
->lock_rrcache
= 0;
5243 mDNSlocal CacheRecord
*GetCacheRecord(mDNS
*const m
, CacheGroup
*cg
, mDNSu16 RDLength
)
5245 CacheRecord
*r
= (CacheRecord
*)GetCacheEntity(m
, cg
);
5248 r
->resrec
.rdata
= (RData
*)&r
->smallrdatastorage
; // By default, assume we're usually going to be using local storage
5249 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
5251 r
->resrec
.rdata
= (RData
*) mDNSPlatformMemAllocateClear(sizeofRDataHeader
+ RDLength
);
5252 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
5253 else { ReleaseCacheEntity(m
, (CacheEntity
*)r
); r
= mDNSNULL
; }
5259 mDNSlocal CacheGroup
*GetCacheGroup(mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
5261 mDNSu16 namelen
= DomainNameLength(rr
->name
);
5262 CacheGroup
*cg
= (CacheGroup
*)GetCacheEntity(m
, mDNSNULL
);
5263 if (!cg
) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
5264 cg
->next
= m
->rrcache_hash
[slot
];
5265 cg
->namehash
= rr
->namehash
;
5266 cg
->members
= mDNSNULL
;
5267 cg
->rrcache_tail
= &cg
->members
;
5268 if (namelen
> sizeof(cg
->namestorage
))
5269 cg
->name
= (domainname
*) mDNSPlatformMemAllocate(namelen
);
5271 cg
->name
= (domainname
*)cg
->namestorage
;
5274 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
5275 ReleaseCacheEntity(m
, (CacheEntity
*)cg
);
5278 AssignDomainName(cg
->name
, rr
->name
);
5280 if (CacheGroupForRecord(m
, rr
)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr
->name
->c
);
5281 m
->rrcache_hash
[slot
] = cg
;
5282 if (CacheGroupForRecord(m
, rr
) != cg
) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr
->name
->c
);
5287 mDNSexport
void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
5291 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5292 // a positive answer using an expired record (e.g. from an interface that has gone away).
5293 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5294 // summary deletion without giving the proper callback to any questions that are monitoring it.
5295 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5296 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
5297 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5298 rr
->resrec
.rroriginalttl
= 0;
5299 SetNextCacheCheckTimeForRecord(m
, rr
);
5302 mDNSexport mDNSs32
mDNS_TimeNow(const mDNS
*const m
)
5305 mDNSPlatformLock(m
);
5308 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5309 if (!m
->timenow
) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
5312 if (m
->timenow
) time
= m
->timenow
;
5313 else time
= mDNS_TimeNow_NoLock(m
);
5314 mDNSPlatformUnlock(m
);
5318 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5319 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5320 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5321 #define SetSPSProxyListChanged(X) do { \
5322 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5323 m->SPSProxyListChanged = (X); } while(0)
5325 // Called from mDNS_Execute() to expire stale proxy records
5326 mDNSlocal
void CheckProxyRecords(mDNS
*const m
, AuthRecord
*list
)
5328 m
->CurrentRecord
= list
;
5329 while (m
->CurrentRecord
)
5331 AuthRecord
*rr
= m
->CurrentRecord
;
5332 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& rr
->WakeUp
.HMAC
.l
[0])
5334 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5335 // so we need to cease proxying for *all* records we may have, expired or not.
5336 if (m
->SPSSocket
&& m
->timenow
- rr
->TimeExpire
< 0) // If proxy record not expired yet, update m->NextScheduledSPS
5338 if (m
->NextScheduledSPS
- rr
->TimeExpire
> 0)
5339 m
->NextScheduledSPS
= rr
->TimeExpire
;
5341 else // else proxy record expired, so remove it
5343 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5344 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, ARDisplayString(m
, rr
));
5345 SetSPSProxyListChanged(rr
->resrec
.InterfaceID
);
5346 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
5347 // Don't touch rr after this -- memory may have been free'd
5350 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5351 // new records could have been added to the end of the list as a result of that call.
5352 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
5353 m
->CurrentRecord
= rr
->next
;
5357 mDNSlocal
void CheckRmvEventsForLocalRecords(mDNS
*const m
)
5359 while (m
->CurrentRecord
)
5361 AuthRecord
*rr
= m
->CurrentRecord
;
5362 if (rr
->AnsweredLocalQ
&& rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
5364 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m
, rr
));
5365 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
5366 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_rmv
);
5367 if (m
->CurrentRecord
== rr
) // If rr still exists in list, restore its state now
5369 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
5370 rr
->AnsweredLocalQ
= mDNSfalse
;
5371 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5372 // For LocalOnly records, we don't do that and hence we need to do that here.
5373 if (RRLocalOnly(rr
)) CompleteDeregistration(m
, rr
);
5376 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5377 m
->CurrentRecord
= rr
->next
;
5381 mDNSlocal
void TimeoutQuestions_internal(mDNS
*const m
, DNSQuestion
* questions
, mDNSInterfaceID InterfaceID
)
5383 if (m
->CurrentQuestion
)
5384 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
,
5385 DNSTypeName(m
->CurrentQuestion
->qtype
));
5386 m
->CurrentQuestion
= questions
;
5387 while (m
->CurrentQuestion
)
5389 DNSQuestion
*const q
= m
->CurrentQuestion
;
5392 if (!q
->TimeoutQuestion
)
5393 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5395 if (m
->timenow
- q
->StopTime
>= 0)
5397 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q
, q
->qname
.c
, m
->timenow
- q
->StopTime
);
5398 q
->LOAddressAnswers
= 0; // unset since timing out the question
5399 GenerateNegativeResponse(m
, InterfaceID
, QC_forceresponse
);
5400 if (m
->CurrentQuestion
== q
) q
->StopTime
= 0;
5404 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
5405 m
->NextScheduledStopTime
= q
->StopTime
;
5408 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5409 // We can't do this at the start of the loop because GenerateNegativeResponse
5410 // depends on having m->CurrentQuestion point to the right question
5411 if (m
->CurrentQuestion
== q
)
5412 m
->CurrentQuestion
= q
->next
;
5414 m
->CurrentQuestion
= mDNSNULL
;
5417 mDNSlocal
void TimeoutQuestions(mDNS
*const m
)
5419 m
->NextScheduledStopTime
= m
->timenow
+ FutureTime
; // push reschedule of TimeoutQuestions to way off into the future
5420 TimeoutQuestions_internal(m
, m
->Questions
, mDNSInterface_Any
);
5421 TimeoutQuestions_internal(m
, m
->LocalOnlyQuestions
, mDNSInterface_LocalOnly
);
5424 mDNSlocal
void mDNSCoreFreeProxyRR(mDNS
*const m
)
5426 AuthRecord
*rrPtr
= m
->SPSRRSet
, *rrNext
= mDNSNULL
;
5427 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__
);
5430 rrNext
= rrPtr
->next
;
5431 mDNSPlatformMemFree(rrPtr
);
5434 m
->SPSRRSet
= mDNSNULL
;
5437 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
5439 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
5441 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
5444 AuthRecord
*head
, *tail
;
5448 verbosedebugf("mDNS_Execute");
5450 if (m
->CurrentQuestion
)
5451 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5452 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5454 if (m
->CurrentRecord
)
5455 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m
, m
->CurrentRecord
));
5457 // 1. If we're past the probe suppression time, we can clear it
5458 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
5460 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5461 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
5463 // 3. Purge our cache of stale old records
5464 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
5466 mDNSu32 numchecked
= 0;
5467 m
->NextCacheCheck
= m
->timenow
+ FutureTime
;
5468 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5470 if (m
->timenow
- m
->rrcache_nextcheck
[slot
] >= 0)
5472 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5473 m
->rrcache_nextcheck
[slot
] = m
->timenow
+ FutureTime
;
5476 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked
, slot
, *cp
? (*cp
)->name
: (domainname
*)"\x04NULL");
5478 CheckCacheExpiration(m
, slot
, *cp
);
5479 if ((*cp
)->members
) cp
=&(*cp
)->next
;
5480 else ReleaseCacheGroup(m
, cp
);
5483 // Even if we didn't need to actually check this slot yet, still need to
5484 // factor its nextcheck time into our overall NextCacheCheck value
5485 if (m
->NextCacheCheck
- m
->rrcache_nextcheck
[slot
] > 0)
5486 m
->NextCacheCheck
= m
->rrcache_nextcheck
[slot
];
5488 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked
, m
->NextCacheCheck
- m
->timenow
);
5491 if (m
->timenow
- m
->NextScheduledSPS
>= 0)
5493 m
->NextScheduledSPS
= m
->timenow
+ FutureTime
;
5494 CheckProxyRecords(m
, m
->DuplicateRecords
); // Clear m->DuplicateRecords first, then m->ResourceRecords
5495 CheckProxyRecords(m
, m
->ResourceRecords
);
5498 SetSPSProxyListChanged(mDNSNULL
); // Perform any deferred BPF reconfiguration now
5500 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5501 // as records could have expired during that check
5502 if (m
->timenow
- m
->NextScheduledKA
>= 0)
5504 m
->NextScheduledKA
= m
->timenow
+ FutureTime
;
5505 mDNS_SendKeepalives(m
);
5508 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5509 if (m
->NextBonjourDisableTime
&& (m
->timenow
- m
->NextBonjourDisableTime
>= 0))
5511 // Schedule immediate network change processing to leave the multicast group
5512 // since the delay time has expired since the previous active registration or query.
5513 m
->NetworkChanged
= m
->timenow
;
5514 m
->NextBonjourDisableTime
= 0;
5515 m
->BonjourEnabled
= 0;
5517 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5521 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5522 if (m
->AnnounceOwner
&& m
->timenow
- m
->AnnounceOwner
>= 0)
5524 m
->AnnounceOwner
= 0;
5527 if (m
->DelaySleep
&& m
->timenow
- m
->DelaySleep
>= 0)
5530 if (m
->SleepState
== SleepState_Transferring
)
5532 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5533 BeginSleepProcessing(m
);
5537 // 4. See if we can answer any of our new local questions from the cache
5538 for (i
=0; m
->NewQuestions
&& i
<1000; i
++)
5540 if (m
->NewQuestions
->DelayAnswering
&& m
->timenow
- m
->NewQuestions
->DelayAnswering
< 0) break;
5541 AnswerNewQuestion(m
);
5543 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5545 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5546 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5547 for (i
=0; i
<1000 && m
->LocalRemoveEvents
; i
++)
5549 m
->LocalRemoveEvents
= mDNSfalse
;
5550 m
->CurrentRecord
= m
->ResourceRecords
;
5551 CheckRmvEventsForLocalRecords(m
);
5552 // Walk the LocalOnly records and deliver the RMV events
5553 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5554 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5556 m
->CurrentRecord
= ag
->members
;
5557 if (m
->CurrentRecord
) CheckRmvEventsForLocalRecords(m
);
5561 if (i
>= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5563 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
5564 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5566 head
= tail
= mDNSNULL
;
5567 for (i
=0; i
<1000 && m
->NewLocalRecords
&& m
->NewLocalRecords
!= head
; i
++)
5569 AuthRecord
*rr
= m
->NewLocalRecords
;
5570 m
->NewLocalRecords
= m
->NewLocalRecords
->next
;
5571 if (LocalRecordReady(rr
))
5573 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5574 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_add
);
5578 // If we have just one record that is not ready, we don't have to unlink and
5579 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5580 // terminate and set the NewLocalRecords to rr.
5581 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m
, rr
));
5582 if (head
!= mDNSNULL
|| m
->NewLocalRecords
!= mDNSNULL
)
5583 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head
, m
->NewLocalRecords
);
5589 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
5590 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m
, rr
));
5591 // if this is the first record we are skipping, move to the end of the list.
5592 // if we have already skipped records before, append it at the end.
5593 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
5594 if (*p
) *p
= rr
->next
; // Cut this record from the list
5595 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m
, rr
)); break; }
5598 while (*p
) p
=&(*p
)->next
;
5607 rr
->next
= mDNSNULL
;
5610 m
->NewLocalRecords
= head
;
5611 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head
? ARDisplayString(m
, head
) : "NULL"));
5613 if (i
>= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5615 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5616 // to our local questions
5617 if (m
->NewLocalOnlyRecords
)
5619 m
->NewLocalOnlyRecords
= mDNSfalse
;
5620 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5622 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5624 for (i
=0; i
<100 && ag
->NewLocalOnlyRecords
; i
++)
5626 AuthRecord
*rr
= ag
->NewLocalOnlyRecords
;
5627 ag
->NewLocalOnlyRecords
= ag
->NewLocalOnlyRecords
->next
;
5628 // LocalOnly records should always be ready as they never probe
5629 if (LocalRecordReady(rr
))
5631 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5632 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_add
);
5634 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m
, rr
));
5636 // We limit about 100 per AuthGroup that can be serviced at a time
5637 if (i
>= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5642 // 5. See what packets we need to send
5643 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| (m
->SleepState
== SleepState_Sleeping
))
5644 DiscardDeregistrations(m
);
5645 if (m
->mDNSPlatformStatus
== mStatus_NoError
&& (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0))
5647 // If the platform code is ready, and we're not suppressing packet generation right now
5648 // then send our responses, probes, and questions.
5649 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5650 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5651 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5652 // Finally, we send responses, including the previously mentioned records that just completed probing.
5653 m
->SuppressSending
= 0;
5655 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5656 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
5657 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
5660 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5661 m
->timenow
, m
->NextScheduledQuery
, m
->timenow
- m
->NextScheduledQuery
);
5662 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
5663 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
5664 if (ActiveQuestion(q
) && m
->timenow
- NextQSendTime(q
) >= 0)
5665 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5667 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
5669 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5670 m
->timenow
, m
->NextScheduledProbe
, m
->timenow
- m
->NextScheduledProbe
);
5671 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
5674 // 7. Send Response packets, including probing records just advanced to announcing state
5675 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
5676 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
5678 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5679 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
5683 // Clear RandomDelay values, ready to pick a new different value next time
5684 m
->RandomQueryDelay
= 0;
5685 m
->RandomReconfirmDelay
= 0;
5687 // See if any questions (or local-only questions) have timed out
5688 if (m
->NextScheduledStopTime
&& m
->timenow
- m
->NextScheduledStopTime
>= 0) TimeoutQuestions(m
);
5689 #ifndef UNICAST_DISABLED
5690 if (m
->NextSRVUpdate
&& m
->timenow
- m
->NextSRVUpdate
>= 0) UpdateAllSRVRecords(m
);
5691 if (m
->timenow
- m
->NextScheduledNATOp
>= 0) CheckNATMappings(m
);
5692 if (m
->timenow
- m
->NextuDNSEvent
>= 0) uDNS_Tasks(m
);
5694 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5695 extern void serviceBLE();
5696 if (m
->NextBLEServiceTime
&& (m
->timenow
- m
->NextBLEServiceTime
>= 0)) serviceBLE();
5697 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5700 // Note about multi-threaded systems:
5701 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5702 // performing mDNS API operations that change our next scheduled event time.
5704 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5705 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5706 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5707 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5708 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5709 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5710 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5711 // without blocking. This avoids the race condition between the signal from the other thread arriving
5712 // just *before* or just *after* the main thread enters the blocking primitive.
5714 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5715 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5716 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5717 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5718 // by the time it gets to the timer callback function).
5720 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5721 return(m
->NextScheduledEvent
);
5724 #ifndef UNICAST_DISABLED
5725 mDNSlocal
void SuspendLLQs(mDNS
*m
)
5728 for (q
= m
->Questions
; q
; q
= q
->next
)
5729 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->state
== LLQ_Established
)
5730 { q
->ReqLease
= 0; sendLLQRefresh(m
, q
); }
5732 #endif // UNICAST_DISABLED
5734 mDNSlocal mDNSBool
QuestionHasLocalAnswers(mDNS
*const m
, DNSQuestion
*q
)
5739 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
5742 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
5743 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5744 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
5746 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
));
5753 // ActivateUnicastQuery() is called from three places:
5754 // 1. When a new question is created
5755 // 2. On wake from sleep
5756 // 3. When the DNS configuration changes
5757 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5758 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5759 mDNSlocal
void ActivateUnicastQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool ScheduleImmediately
)
5761 if (!question
->DuplicateOf
)
5763 debugf("ActivateUnicastQuery: %##s %s%s",
5764 question
->qname
.c
, DNSTypeName(question
->qtype
), ScheduleImmediately
? " ScheduleImmediately" : "");
5765 question
->CNAMEReferrals
= 0;
5766 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
5767 if (question
->LongLived
)
5769 question
->state
= LLQ_Init
;
5770 question
->id
= zeroOpaque64
;
5771 question
->servPort
= zeroIPPort
;
5772 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
5774 // If the question has local answers, then we don't want answers from outside
5775 if (ScheduleImmediately
&& !QuestionHasLocalAnswers(m
, question
))
5777 question
->ThisQInterval
= InitialQuestionInterval
;
5778 question
->LastQTime
= m
->timenow
- question
->ThisQInterval
;
5779 SetNextQueryTime(m
, question
);
5784 // Caller should hold the lock
5785 mDNSexport
void mDNSCoreRestartAddressQueries(mDNS
*const m
, mDNSBool SearchDomainsChanged
, FlushCache flushCacheRecords
,
5786 CallbackBeforeStartQuery BeforeStartCallback
, void *context
)
5789 DNSQuestion
*restart
= mDNSNULL
;
5793 // 1. Flush the cache records
5794 if (flushCacheRecords
) flushCacheRecords(m
);
5796 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5797 // we are going to stop the question. Hence we need to deliver the RMV event before we
5798 // stop the question.
5800 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5801 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5802 // *any* other question which could be the next one that we may process here. RestartQuestion
5803 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5804 // if the "next" question is stopped while the CurrentQuestion is stopped
5806 if (m
->RestartQuestion
)
5807 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5808 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
5810 m
->RestartQuestion
= m
->Questions
;
5811 while (m
->RestartQuestion
)
5813 q
= m
->RestartQuestion
;
5814 m
->RestartQuestion
= q
->next
;
5815 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5816 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5817 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5818 // question followed by the original query that refers to this GetZoneData question, we will end up
5819 // freeing the GetZoneData question and then start the "freed" question at the end.
5821 if (IsGetZoneDataQuestion(q
))
5823 DNSQuestion
*refq
= q
->next
;
5824 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5825 // debug stuff, we just try to find the referencing question and don't do much with it
5828 if (q
== &refq
->nta
->question
)
5830 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq
, refq
->qname
.c
, DNSTypeName(refq
->qtype
), q
);
5837 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5838 if (q
->qtype
!= kDNSType_A
&& q
->qtype
!= kDNSType_AAAA
&& q
->qtype
!= kDNSType_CNAME
) continue;
5840 // If the search domains did not change, then we restart all the queries. Otherwise, only
5841 // for queries for which we "might" have appended search domains ("might" because we may
5842 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5843 if (!SearchDomainsChanged
|| q
->AppendSearchDomains
)
5845 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5846 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5847 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5848 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5849 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5850 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5851 // for the original query using these cache entries as ADDs were never delivered using these cache
5852 // entries and hence this order is needed.
5854 // If the query is suppressed, the RMV events won't be delivered
5855 if (!CacheRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5857 // Suppressed status does not affect questions that are answered using local records
5858 if (!LocalRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5860 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q
,
5861 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->AppendSearchDomains
);
5862 mDNS_StopQuery_internal(m
, q
);
5863 if (q
->ResetHandler
) q
->ResetHandler(q
);
5869 // 3. Callback before we start the query
5870 if (BeforeStartCallback
) BeforeStartCallback(m
, context
);
5872 // 4. Restart all the stopped queries
5876 restart
= restart
->next
;
5878 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5879 mDNS_StartQuery_internal(m
, q
);
5883 mDNSexport
void mDNSCoreRestartQueries(mDNS
*const m
)
5887 #ifndef UNICAST_DISABLED
5888 // Retrigger all our uDNS questions
5889 if (m
->CurrentQuestion
)
5890 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5891 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5892 m
->CurrentQuestion
= m
->Questions
;
5893 while (m
->CurrentQuestion
)
5895 q
= m
->CurrentQuestion
;
5896 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
5897 if (!mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
)) ActivateUnicastQuery(m
, q
, mDNStrue
);
5901 // Retrigger all our mDNS questions
5902 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5903 mDNSCoreRestartQuestion(m
, q
);
5906 // restart question if it's multicast and currently active
5907 mDNSexport
void mDNSCoreRestartQuestion(mDNS
*const m
, DNSQuestion
*q
)
5909 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
5911 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
5912 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
5913 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
5914 q
->RecentAnswerPkts
= 0;
5915 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
5916 m
->NextScheduledQuery
= m
->timenow
;
5920 // restart the probe/announce cycle for multicast record
5921 mDNSexport
void mDNSCoreRestartRegistration(mDNS
*const m
, AuthRecord
*rr
, int announceCount
)
5923 if (!AuthRecord_uDNS(rr
))
5925 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5926 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
5928 if (mDNS_KeepaliveRecord(&rr
->resrec
))
5930 rr
->AnnounceCount
= 0; // Do not announce keepalive records
5934 // announceCount < 0 indicates default announce count should be used
5935 if (announceCount
< 0)
5936 announceCount
= InitialAnnounceCount
;
5937 if (rr
->AnnounceCount
< (mDNSu8
)announceCount
)
5938 rr
->AnnounceCount
= (mDNSu8
)announceCount
;
5941 rr
->SendNSECNow
= mDNSNULL
;
5942 InitializeLastAPTime(m
, rr
);
5946 // ***************************************************************************
5947 #if COMPILER_LIKES_PRAGMA_MARK
5949 #pragma mark - Power Management (Sleep/Wake)
5952 mDNSexport
void mDNS_UpdateAllowSleep(mDNS
*const m
)
5954 #ifndef IDLESLEEPCONTROL_DISABLED
5955 mDNSBool allowSleep
= mDNStrue
;
5960 if (m
->SystemSleepOnlyIfWakeOnLAN
)
5962 // Don't sleep if we are a proxy for any services
5963 if (m
->ProxyRecords
)
5965 allowSleep
= mDNSfalse
;
5966 mDNS_snprintf(reason
, sizeof(reason
), "sleep proxy for %d records", m
->ProxyRecords
);
5967 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m
->ProxyRecords
);
5970 if (allowSleep
&& mDNSCoreHaveAdvertisedMulticastServices(m
))
5972 // Scan the list of active interfaces
5973 NetworkInterfaceInfo
*intf
;
5974 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5976 if (intf
->McastTxRx
&& !intf
->Loopback
&& !mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
5978 // Disallow sleep if this interface doesn't support NetWake
5981 allowSleep
= mDNSfalse
;
5982 mDNS_snprintf(reason
, sizeof(reason
), "%s does not support NetWake", intf
->ifname
);
5983 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf
->ifname
);
5987 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
5988 // that will be offloaded. If not, we should prevent sleep.
5989 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
5990 #if APPLE_OSX_mDNSResponder
5991 if (!SupportsInNICProxy(intf
))
5994 // Disallow sleep if there is no sleep proxy server
5995 const CacheRecord
*cr
= FindSPSInCache1(m
, &intf
->NetWakeBrowse
, mDNSNULL
, mDNSNULL
);
5996 if ( cr
== mDNSNULL
)
5998 allowSleep
= mDNSfalse
;
5999 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server on %s", intf
->ifname
);
6000 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf
->ifname
);
6003 else if (m
->SPSType
!= 0)
6005 mDNSu32 mymetric
= LocalSPSMetric(m
);
6006 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
6007 if (metric
>= mymetric
)
6009 allowSleep
= mDNSfalse
;
6010 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server with better metric on %s", intf
->ifname
);
6011 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf
->ifname
);
6021 // Call the platform code to enable/disable sleep
6022 mDNSPlatformSetAllowSleep(allowSleep
, reason
);
6025 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
6028 mDNSlocal mDNSBool
mDNSUpdateOkToSend(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSu32 scopeid
)
6030 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
6031 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
6033 if (AuthRecord_uDNS(rr
) || (rr
->AuthFlags
& AuthFlagsWakeOnly
) || mDNSOpaque16IsZero(rr
->updateid
) ||
6034 m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
6039 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
6040 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
6041 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
6042 // updateid and we should have returned from above.
6044 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
6045 // platform function to extract the value from "intf" every time.
6047 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
6048 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
6054 mDNSexport
void UpdateRMAC(mDNS
*const m
, void *context
)
6056 IPAddressMACMapping
*addrmap
= (IPAddressMACMapping
*)context
;
6057 m
->CurrentRecord
= m
->ResourceRecords
;
6061 LogMsg("UpdateRMAC: Address mapping is NULL");
6065 while (m
->CurrentRecord
)
6067 AuthRecord
*rr
= m
->CurrentRecord
;
6068 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6069 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
6072 getKeepaliveRaddr(m
, rr
, &raddr
);
6073 if (mDNSSameAddress(&raddr
, &addrmap
->ipaddr
))
6075 // Update the MAC address only if it is not a zero MAC address
6076 mDNSEthAddr macAddr
;
6077 mDNSu8
*ptr
= GetValueForMACAddr((mDNSu8
*)(addrmap
->ethaddr
), (mDNSu8
*) (addrmap
->ethaddr
+ sizeof(addrmap
->ethaddr
)), &macAddr
);
6078 if (ptr
!= mDNSNULL
&& !mDNSEthAddressIsZero(macAddr
))
6080 UpdateKeepaliveRData(m
, rr
, mDNSNULL
, mDNStrue
, (char *)(addrmap
->ethaddr
));
6084 m
->CurrentRecord
= rr
->next
;
6088 mDNSPlatformMemFree(addrmap
);
6092 mDNSexport mStatus
UpdateKeepaliveRData(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSBool updateMac
, char *ethAddr
)
6094 mDNSu16 newrdlength
;
6095 mDNSAddr laddr
= zeroAddr
;
6096 mDNSAddr raddr
= zeroAddr
;
6097 mDNSEthAddr eth
= zeroEthAddr
;
6098 mDNSIPPort lport
= zeroIPPort
;
6099 mDNSIPPort rport
= zeroIPPort
;
6100 mDNSu32 timeout
= 0;
6110 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
6111 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6112 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
6113 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
6115 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, &raddr
, rport
.NotAnInteger
);
6116 return mStatus_UnknownErr
;
6121 if (laddr
.type
== mDNSAddrType_IPv4
)
6122 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%s", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ethAddr
);
6124 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%s", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ethAddr
);
6129 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6130 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6131 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6132 mDNSPlatformMemZero(&mti
, sizeof (mDNSTCPInfo
));
6133 ret
= mDNSPlatformRetrieveTCPInfo(&laddr
, &lport
, &raddr
, &rport
, &mti
);
6134 if (ret
!= mStatus_NoError
)
6136 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret
);
6139 if ((intf
!= mDNSNULL
) && (mti
.IntfId
!= intf
->InterfaceID
))
6141 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti
.IntfId
, intf
->InterfaceID
);
6142 return mStatus_BadParamErr
;
6145 if (laddr
.type
== mDNSAddrType_IPv4
)
6146 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ð
, mti
.seq
, mti
.ack
, mti
.window
);
6148 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ð
, mti
.seq
, mti
.ack
, mti
.window
);
6151 // Did we insert a null byte at the end ?
6152 if (newrdlength
== (sizeof(txt
.c
) - 1))
6154 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m
, rr
));
6155 return mStatus_NoMemoryErr
;
6158 // Include the length for the null byte at the end
6159 txt
.c
[0] = newrdlength
+ 1;
6160 // Account for the first length byte and the null byte at the end
6163 rdsize
= newrdlength
> sizeof(RDataBody
) ? newrdlength
: sizeof(RDataBody
);
6164 newrd
= (RData
*) mDNSPlatformMemAllocate(sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
6165 if (!newrd
) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr
; }
6167 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
6168 mDNSPlatformMemCopy(&newrd
->u
, txt
.c
, newrdlength
);
6170 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6171 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6172 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6173 // free that memory here before copying in the new data.
6174 if ( rr
->resrec
.rdata
!= &rr
->rdatastorage
)
6176 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m
, rr
));
6177 mDNSPlatformMemFree(rr
->resrec
.rdata
);
6179 SetNewRData(&rr
->resrec
, newrd
, newrdlength
); // Update our rdata
6181 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m
, rr
));
6182 return mStatus_NoError
;
6185 mDNSlocal
void SendSPSRegistrationForOwner(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
, const OwnerOptData
*const owner
)
6187 const int optspace
= DNSOpt_Header_Space
+ DNSOpt_LeaseData_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
);
6188 const int sps
= intf
->NextSPSAttempt
/ 3;
6193 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6194 if (!intf
->SPSAddr
[sps
].type
)
6196 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6197 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
6198 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
6199 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf
->ifname
, intf
->NextSPSAttempt
, sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6203 // Mark our mDNS records (not unicast records) for transfer to SPS
6204 if (mDNSOpaque16IsZero(id
))
6206 // We may have to register this record over multiple interfaces and we don't want to
6207 // overwrite the id. We send the registration over interface X with id "IDX" and before
6208 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6209 // for "IDX". Hence, we want to use the same ID across all interfaces.
6211 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6212 // option check below will set the same ID across the records from the same owner. Records
6213 // with different owner option gets different ID.
6214 msgid
= mDNS_NewMessageID(m
);
6215 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6217 if (!(rr
->AuthFlags
& AuthFlagsWakeOnly
) && rr
->resrec
.RecordType
> kDNSRecordTypeDeregistering
)
6219 if (rr
->resrec
.InterfaceID
== intf
->InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
6221 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6223 rr
->SendRNow
= mDNSInterfaceMark
; // mark it now
6224 // When we are registering on the first interface, rr->updateid is zero in which case
6225 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6226 // At the end, all the updates sent across all the interfaces with the same ID.
6227 if (mDNSOpaque16IsZero(rr
->updateid
))
6228 rr
->updateid
= msgid
;
6230 msgid
= rr
->updateid
;
6241 mDNSu8
*p
= m
->omsg
.data
;
6242 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6243 // For now we follow that same logic for SPS registrations too.
6244 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6245 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6246 InitializeDNSMessage(&m
->omsg
.h
, msgid
, UpdateReqFlags
);
6248 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6249 if (rr
->SendRNow
|| mDNSUpdateOkToSend(m
, rr
, intf
, scopeid
))
6251 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6254 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.mDNS_numUpdates
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
) - optspace
;
6256 // If we can't update the keepalive record, don't send it
6257 if (mDNS_KeepaliveRecord(&rr
->resrec
) && (UpdateKeepaliveRData(m
, rr
, intf
, mDNSfalse
, mDNSNULL
) != mStatus_NoError
))
6259 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
6261 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
6263 rr
->SendRNow
= mDNSNULL
;
6267 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
6268 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6269 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
6270 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear 'unique' bit back to normal state
6272 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf
->ifname
, p
- m
->omsg
.data
, limit
- m
->omsg
.data
, ARDisplayString(m
, rr
));
6275 LogSPS("SendSPSRegistration put %s 0x%x 0x%x (updateid %d) %s", intf
->ifname
, rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(m
->omsg
.h
.id
), ARDisplayString(m
, rr
));
6276 rr
->SendRNow
= mDNSNULL
;
6277 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
6278 rr
->LastAPTime
= m
->timenow
;
6279 // should be initialized above
6280 if (mDNSOpaque16IsZero(rr
->updateid
)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m
, rr
));
6281 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6282 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
6288 if (!m
->omsg
.h
.mDNS_numUpdates
) break;
6292 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
6293 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
6294 opt
.resrec
.rdlength
= sizeof(rdataOPT
) * 2; // Two options in this OPT record
6295 opt
.resrec
.rdestimate
= sizeof(rdataOPT
) * 2;
6296 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
6297 opt
.resrec
.rdata
->u
.opt
[0].optlen
= DNSOpt_LeaseData_Space
- 4;
6298 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= DEFAULT_UPDATE_LEASE
;
6299 if (!owner
->HMAC
.l
[0]) // If no owner data,
6300 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[1]); // use our own interface information
6301 else // otherwise, use the owner data we were given
6303 opt
.resrec
.rdata
->u
.opt
[1].u
.owner
= *owner
;
6304 opt
.resrec
.rdata
->u
.opt
[1].opt
= kDNSOpt_Owner
;
6305 opt
.resrec
.rdata
->u
.opt
[1].optlen
= DNSOpt_Owner_Space(&owner
->HMAC
, &owner
->IMAC
) - 4;
6307 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, &opt
));
6308 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
6310 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m
->omsg
.h
.mDNS_numUpdates
, ARDisplayString(m
, &opt
));
6315 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf
->ifname
, intf
->NextSPSAttempt
, sps
,
6316 mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.h
.mDNS_numUpdates
, p
- m
->omsg
.data
, &intf
->SPSAddr
[sps
], mDNSVal16(intf
->SPSPort
[sps
]));
6317 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6318 err
= mDNSSendDNSMessage(m
, &m
->omsg
, p
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &intf
->SPSAddr
[sps
], intf
->SPSPort
[sps
], mDNSNULL
, mDNSfalse
);
6319 if (err
) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err
);
6320 if (err
&& intf
->SPSAddr
[sps
].type
== mDNSAddrType_IPv4
&& intf
->NetWakeResolve
[sps
].ThisQInterval
== -1)
6322 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6323 intf
->NetWakeResolve
[sps
].qtype
= kDNSType_AAAA
;
6324 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[sps
]);
6331 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
* 10; // If successful, update NextSPSAttemptTime
6334 if (mDNSOpaque16IsZero(id
) && intf
->NextSPSAttempt
< 8) intf
->NextSPSAttempt
++;
6337 mDNSlocal mDNSBool
RecordIsFirstOccurrenceOfOwner(mDNS
*const m
, const AuthRecord
*const rr
)
6340 for (ar
= m
->ResourceRecords
; ar
&& ar
!= rr
; ar
=ar
->next
)
6341 if (mDNSPlatformMemSame(&rr
->WakeUp
, &ar
->WakeUp
, sizeof(rr
->WakeUp
))) return mDNSfalse
;
6345 mDNSlocal
void mDNSCoreStoreProxyRR(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, AuthRecord
*const rr
)
6347 AuthRecord
*newRR
= (AuthRecord
*) mDNSPlatformMemAllocateClear(sizeof(*newRR
));
6348 if (newRR
== mDNSNULL
)
6350 LogSPS("%s : could not allocate memory for new resource record", __func__
);
6354 mDNS_SetupResourceRecord(newRR
, mDNSNULL
, InterfaceID
, rr
->resrec
.rrtype
,
6355 rr
->resrec
.rroriginalttl
, rr
->resrec
.RecordType
,
6356 rr
->ARType
, mDNSNULL
, mDNSNULL
);
6358 AssignDomainName(&newRR
->namestorage
, &rr
->namestorage
);
6359 newRR
->resrec
.rdlength
= DomainNameLength(rr
->resrec
.name
);
6360 newRR
->resrec
.namehash
= DomainNameHashValue(newRR
->resrec
.name
);
6361 newRR
->resrec
.rrclass
= rr
->resrec
.rrclass
;
6363 if (rr
->resrec
.rrtype
== kDNSType_A
)
6365 newRR
->resrec
.rdata
->u
.ipv4
= rr
->resrec
.rdata
->u
.ipv4
;
6367 else if (rr
->resrec
.rrtype
== kDNSType_AAAA
)
6369 newRR
->resrec
.rdata
->u
.ipv6
= rr
->resrec
.rdata
->u
.ipv6
;
6371 SetNewRData(&newRR
->resrec
, mDNSNULL
, 0);
6373 // Insert the new node at the head of the list.
6374 newRR
->next
= m
->SPSRRSet
;
6375 m
->SPSRRSet
= newRR
;
6376 LogSPS("%s : Storing proxy record : %s ", __func__
, ARDisplayString(m
, rr
));
6379 // Some records are interface specific and some are not. The ones that are supposed to be registered
6380 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6381 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6382 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6383 // registration on all the interfaces
6384 mDNSlocal
void SPSInitRecordsBeforeUpdate(mDNS
*const m
, mDNSOpaque64 updateIntID
, mDNSBool
*WakeOnlyService
)
6387 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID
.l
[1], updateIntID
.l
[0]);
6389 *WakeOnlyService
= mDNSfalse
;
6391 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6392 // make sure that the old sleep proxy records are removed.
6393 mDNSCoreFreeProxyRR(m
);
6395 // For records that are registered only on a specific interface, mark only that bit as it will
6396 // never be registered on any other interface. For others, it should be sent on all interfaces.
6397 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6399 ar
->updateIntID
= zeroOpaque64
;
6400 ar
->updateid
= zeroID
;
6401 if (AuthRecord_uDNS(ar
))
6405 if (ar
->AuthFlags
& AuthFlagsWakeOnly
)
6407 if (ar
->resrec
.RecordType
== kDNSRecordTypeShared
&& ar
->RequireGoodbye
)
6409 ar
->ImmedAnswer
= mDNSInterfaceMark
;
6410 *WakeOnlyService
= mDNStrue
;
6414 if (!ar
->resrec
.InterfaceID
)
6416 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID
.l
[1], updateIntID
.l
[0], ARDisplayString(m
, ar
));
6417 ar
->updateIntID
= updateIntID
;
6421 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6423 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, ar
->resrec
.InterfaceID
, mDNStrue
);
6424 if ((scopeid
< (sizeof(updateIntID
) * mDNSNBBY
)) && bit_get_opaque64(updateIntID
, scopeid
))
6426 bit_set_opaque64(ar
->updateIntID
, scopeid
);
6427 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid
, ar
->updateIntID
.l
[1],
6428 ar
->updateIntID
.l
[0], ARDisplayString(m
, ar
));
6432 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid
);
6435 // Store the A and AAAA records that we registered with the sleep proxy.
6436 // We will use this to prevent spurious name conflicts that may occur when we wake up
6437 if (ar
->resrec
.rrtype
== kDNSType_A
|| ar
->resrec
.rrtype
== kDNSType_AAAA
)
6439 mDNSCoreStoreProxyRR(m
, ar
->resrec
.InterfaceID
, ar
);
6444 mDNSlocal
void SendSPSRegistration(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
)
6447 OwnerOptData owner
= zeroOwner
;
6449 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6451 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6453 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)) && RecordIsFirstOccurrenceOfOwner(m
, ar
))
6456 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6461 // RetrySPSRegistrations is called from SendResponses, with the lock held
6462 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
)
6465 NetworkInterfaceInfo
*intf
;
6467 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6468 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6469 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10)
6470 intf
->NextSPSAttemptTime
++;
6472 // Retry any record registrations that are due
6473 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6474 if (!AuthRecord_uDNS(rr
) && !mDNSOpaque16IsZero(rr
->updateid
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6476 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6478 // If we still have registrations pending on this interface, send it now
6479 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6480 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
6481 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
6483 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
, rr
));
6484 SendSPSRegistration(m
, intf
, rr
->updateid
);
6489 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6490 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6491 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10 && intf
->NextSPSAttempt
< 8)
6492 intf
->NextSPSAttempt
++;
6495 mDNSlocal
void NetWakeResolve(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
6497 NetworkInterfaceInfo
*intf
= (NetworkInterfaceInfo
*)question
->QuestionContext
;
6498 int sps
= (int)(question
- intf
->NetWakeResolve
);
6500 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps
, AddRecord
, RRDisplayString(m
, answer
));
6502 if (!AddRecord
) return; // Don't care about REMOVE events
6503 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
6505 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6507 if (answer
->rrtype
== kDNSType_SRV
)
6509 // 1. Got the SRV record; now look up the target host's IP address
6510 mDNS_StopQuery(m
, question
);
6511 intf
->SPSPort
[sps
] = answer
->rdata
->u
.srv
.port
;
6512 AssignDomainName(&question
->qname
, &answer
->rdata
->u
.srv
.target
);
6513 question
->qtype
= kDNSType_A
;
6514 mDNS_StartQuery(m
, question
);
6516 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== sizeof(mDNSv4Addr
))
6518 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6519 mDNS_StopQuery(m
, question
);
6520 question
->ThisQInterval
= -1;
6521 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv4
;
6522 intf
->SPSAddr
[sps
].ip
.v4
= answer
->rdata
->u
.ipv4
;
6524 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6527 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== 0)
6529 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6530 mDNS_StopQuery(m
, question
);
6531 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps
, question
->qname
.c
);
6532 question
->qtype
= kDNSType_AAAA
;
6533 mDNS_StartQuery(m
, question
);
6535 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== sizeof(mDNSv6Addr
) && mDNSv6AddressIsLinkLocal(&answer
->rdata
->u
.ipv6
))
6537 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6538 mDNS_StopQuery(m
, question
);
6539 question
->ThisQInterval
= -1;
6540 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv6
;
6541 intf
->SPSAddr
[sps
].ip
.v6
= answer
->rdata
->u
.ipv6
;
6543 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6548 mDNSexport mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
)
6551 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6552 if (mDNS_KeepaliveRecord(&rr
->resrec
) || (rr
->resrec
.rrtype
== kDNSType_SRV
&& !AuthRecord_uDNS(rr
) && !mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, DiscardPort
)))
6557 #define WAKE_ONLY_SERVICE 1
6558 #define AC_ONLY_SERVICE 2
6560 #ifdef APPLE_OSX_mDNSResponder
6561 mDNSlocal
void SendGoodbyesForSelectServices(mDNS
*const m
, mDNSBool
*servicePresent
, mDNSu32 serviceType
)
6564 *servicePresent
= mDNSfalse
;
6566 // Mark all the records we need to deregister and send them
6567 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6569 // If the service type is wake only service and the auth flags match and requires a goodbye
6570 // OR if the service type is AC only and it is not a keepalive record,
6571 // mark the records we need to deregister and send them
6572 if ((serviceType
== WAKE_ONLY_SERVICE
&& (rr
->AuthFlags
& AuthFlagsWakeOnly
) &&
6573 rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
) ||
6574 (serviceType
== AC_ONLY_SERVICE
&& !mDNS_KeepaliveRecord(&rr
->resrec
)))
6576 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6577 *servicePresent
= mDNStrue
;
6583 #ifdef APPLE_OSX_mDNSResponder
6584 // This function is used only in the case of local NIC proxy. For external
6585 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6586 // walk the resource records.
6587 mDNSlocal
void SendGoodbyesForWakeOnlyService(mDNS
*const m
, mDNSBool
*WakeOnlyService
)
6589 return SendGoodbyesForSelectServices(m
, WakeOnlyService
, WAKE_ONLY_SERVICE
);
6591 #endif // APPLE_OSX_mDNSResponder
6594 mDNSlocal
void SendSleepGoodbyes(mDNS
*const m
, mDNSBool AllInterfaces
, mDNSBool unicast
)
6597 m
->SleepState
= SleepState_Sleeping
;
6599 // If AllInterfaces is not set, the caller has already marked it appropriately
6600 // on which interfaces this should be sent.
6603 NetworkInterfaceInfo
*intf
;
6604 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6606 intf
->SendGoodbyes
= 1;
6611 #ifndef UNICAST_DISABLED
6612 SleepRecordRegistrations(m
); // If we have no SPS, need to deregister our uDNS records
6613 #endif /* UNICAST_DISABLED */
6616 // Mark all the records we need to deregister and send them
6617 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6618 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
6619 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6624 * This function attempts to detect if multiple interfaces are on the same subnet.
6625 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6626 * IPv6 link local addresses that are configured by default on all interfaces make
6627 * it hard to make this determination
6629 * The 'real' fix for this would be to send out multicast packets over one interface
6630 * and conclude that multiple interfaces are on the same subnet only if these packets
6631 * are seen on other interfaces on the same system
6633 mDNSlocal mDNSBool
skipSameSubnetRegistration(mDNS
*const m
, mDNSInterfaceID
*regID
, mDNSu32 count
, mDNSInterfaceID intfid
)
6635 NetworkInterfaceInfo
*intf
;
6636 NetworkInterfaceInfo
*newIntf
;
6639 for (newIntf
= FirstInterfaceForID(m
, intfid
); newIntf
; newIntf
= newIntf
->next
)
6641 if ((newIntf
->InterfaceID
!= intfid
) ||
6642 (newIntf
->ip
.type
!= mDNSAddrType_IPv4
))
6646 for ( i
= 0; i
< count
; i
++)
6648 for (intf
= FirstInterfaceForID(m
, regID
[i
]); intf
; intf
= intf
->next
)
6650 if ((intf
->InterfaceID
!= regID
[i
]) ||
6651 (intf
->ip
.type
!= mDNSAddrType_IPv4
))
6655 if ((intf
->ip
.ip
.v4
.NotAnInteger
& intf
->mask
.ip
.v4
.NotAnInteger
) == (newIntf
->ip
.ip
.v4
.NotAnInteger
& newIntf
->mask
.ip
.v4
.NotAnInteger
))
6657 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__
, intf
->ifname
);
6666 mDNSlocal
void DoKeepaliveCallbacks(mDNS
*m
)
6668 // Loop through the keepalive records and callback with an error
6669 m
->CurrentRecord
= m
->ResourceRecords
;
6670 while (m
->CurrentRecord
)
6672 AuthRecord
*const rr
= m
->CurrentRecord
;
6673 if ((mDNS_KeepaliveRecord(&rr
->resrec
)) && (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
))
6675 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m
, rr
));
6676 if (rr
->RecordCallback
)
6677 rr
->RecordCallback(m
, rr
, mStatus_BadStateErr
);
6679 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
6680 m
->CurrentRecord
= rr
->next
;
6684 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6685 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
)
6687 mDNSBool SendGoodbyes
= mDNStrue
;
6688 mDNSBool WakeOnlyService
= mDNSfalse
;
6689 mDNSBool invokeKACallback
= mDNStrue
;
6690 const CacheRecord
*sps
[3] = { mDNSNULL
};
6691 mDNSOpaque64 updateIntID
= zeroOpaque64
;
6692 mDNSInterfaceID registeredIntfIDS
[128] = { 0 };
6693 mDNSu32 registeredCount
= 0;
6694 int skippedRegistrations
= 0;
6696 m
->NextScheduledSPRetry
= m
->timenow
;
6698 // Clear out the SCDynamic entry that stores the external SPS information
6699 mDNSPlatformClearSPSData();
6701 if (!m
->SystemWakeOnLANEnabled
) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6702 else if (!mDNSCoreHaveAdvertisedMulticastServices(m
)) LogSPS("BeginSleepProcessing: No advertised services");
6703 else // If we have at least one advertised service
6705 NetworkInterfaceInfo
*intf
;
6706 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6708 mDNSBool skipFullSleepProxyRegistration
= mDNSfalse
;
6709 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6710 intf
->SendGoodbyes
= 0;
6712 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6714 if (!intf
->McastTxRx
|| mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
6716 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf
->ifname
);
6720 // If we are not capable of WOMP, then don't register with sleep proxy.
6722 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6723 // We might find sleep proxy servers in the cache and start a resolve on them.
6724 // But then if the interface goes away, we won't stop these questions because
6725 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6726 // to stop both the browse and resolve questions.
6729 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf
->ifname
);
6730 intf
->SendGoodbyes
= 1;
6731 skippedRegistrations
++;
6735 // Check if we have already registered with a sleep proxy for this subnet.
6736 // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
6737 // to the interface.
6738 if (skipSameSubnetRegistration(m
, registeredIntfIDS
, registeredCount
, intf
->InterfaceID
))
6740 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__
, intf
->ifname
);
6741 skipFullSleepProxyRegistration
= mDNStrue
;
6744 #if APPLE_OSX_mDNSResponder
6745 if (SupportsInNICProxy(intf
))
6747 mDNSBool keepaliveOnly
= mDNSfalse
;
6748 const mStatus err
= ActivateLocalProxy(intf
, skipFullSleepProxyRegistration
, &keepaliveOnly
);
6749 if (!skipFullSleepProxyRegistration
&& !err
)
6751 SendGoodbyesForWakeOnlyService(m
, &WakeOnlyService
);
6753 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6754 SendGoodbyes
= (keepaliveOnly
) ? mDNStrue
: mDNSfalse
;
6755 invokeKACallback
= mDNSfalse
;
6756 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf
->ifname
);
6757 // This will leave m->SleepState set to SleepState_Transferring,
6758 // which is okay because with no outstanding resolves, or updates in flight,
6759 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6761 // Setting this flag activates the SleepLimit which delays sleep by 5 seconds and
6762 // will allow the system to deregister any BTMM records.
6763 m
->NextScheduledSPRetry
= m
->timenow
+ (5 * mDNSPlatformOneSecond
);
6764 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6769 #endif // APPLE_OSX_mDNSResponder
6770 if (!skipFullSleepProxyRegistration
)
6772 #if APPLE_OSX_mDNSResponder
6773 // If on battery, do not attempt to offload to external sleep proxies
6774 if (m
->SystemWakeOnLANEnabled
== mDNS_WakeOnBattery
)
6776 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6779 #endif // APPLE_OSX_mDNSResponder
6780 FindSPSInCache(m
, &intf
->NetWakeBrowse
, sps
);
6781 if (!sps
[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6782 intf
->ifname
, &intf
->ip
, NextQSendTime(&intf
->NetWakeBrowse
) - m
->timenow
, intf
->NetWakeBrowse
.ThisQInterval
);
6787 SendGoodbyes
= mDNSfalse
;
6788 intf
->NextSPSAttempt
= 0;
6789 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6791 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6792 // Now we know for sure that we have to wait for registration to complete on this interface.
6793 if (scopeid
< (sizeof(updateIntID
) * mDNSNBBY
))
6794 bit_set_opaque64(updateIntID
, scopeid
);
6796 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6800 if (intf
->SPSAddr
[i
].type
)
6801 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf
->ifname
, i
, intf
->SPSAddr
[i
].type
);
6802 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0)
6803 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf
->ifname
, i
, intf
->NetWakeResolve
[i
].ThisQInterval
);
6805 intf
->SPSAddr
[i
].type
= mDNSAddrType_None
;
6806 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery(m
, &intf
->NetWakeResolve
[i
]);
6807 intf
->NetWakeResolve
[i
].ThisQInterval
= -1;
6810 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf
->ifname
, i
, sps
[i
]->resrec
.rroriginalttl
, CRDisplayString(m
, sps
[i
]));
6811 mDNS_SetupQuestion(&intf
->NetWakeResolve
[i
], intf
->InterfaceID
, &sps
[i
]->resrec
.rdata
->u
.name
, kDNSType_SRV
, NetWakeResolve
, intf
);
6812 intf
->NetWakeResolve
[i
].ReturnIntermed
= mDNStrue
;
6813 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[i
]);
6815 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6816 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6825 // If we have at least one interface on which we are registering with an external sleep proxy,
6826 // initialize all the records appropriately.
6827 if (!mDNSOpaque64IsZero(&updateIntID
))
6828 SPSInitRecordsBeforeUpdate(m
, updateIntID
, &WakeOnlyService
);
6830 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6831 // the records to a sleep proxy.
6832 if (invokeKACallback
)
6834 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6835 DoKeepaliveCallbacks(m
);
6838 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6839 // interfaces and also deregister unicast registrations.
6841 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6842 // for both multicast and unicast.
6844 // - If we skipped registrations on some interfaces, then we have already marked
6845 // them appropriately above. We don't need to send goodbyes for unicast as
6846 // we have registered with at least one sleep proxy.
6848 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6850 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6851 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6852 // at WakeOnlyServices first.
6855 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6856 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
6858 else if (skippedRegistrations
)
6860 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6861 SendSleepGoodbyes(m
, mDNSfalse
, mDNSfalse
);
6863 else if (WakeOnlyService
)
6865 // If we saw WakeOnly service above, send the goodbyes now.
6866 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6871 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6872 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6873 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6874 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleep
)
6878 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_INFO
,
6879 PUB_S
" (old state %d) at %d", sleep
? "Sleeping" : "Waking", m
->SleepState
, m
->timenow
);
6881 if (sleep
&& !m
->SleepState
) // Going to sleep
6884 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6887 mDNSu8 oldstate
= m
->SPSState
;
6888 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6890 #ifndef SPC_DISABLED
6891 if (oldstate
== 1) mDNS_DeregisterService(m
, &m
->SPSRecords
);
6895 mDNS_ReclaimLockAfterCallback();
6897 #ifdef _LEGACY_NAT_TRAVERSAL_
6900 mDNSPlatformUDPClose(m
->SSDPSocket
);
6901 m
->SSDPSocket
= mDNSNULL
;
6904 m
->SleepState
= SleepState_Transferring
;
6905 if (m
->SystemWakeOnLANEnabled
&& m
->DelaySleep
)
6907 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6908 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
6909 "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m
->DelaySleep
- m
->timenow
);
6910 m
->SleepLimit
= NonZeroTime(m
->DelaySleep
+ mDNSPlatformOneSecond
* 10);
6915 m
->SleepLimit
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 10);
6916 m
->mDNSStats
.Sleeps
++;
6917 BeginSleepProcessing(m
);
6920 #ifndef UNICAST_DISABLED
6923 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S
") seq %d",
6925 m
->SleepState
== SleepState_Transferring
? "Transferring" :
6926 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?", m
->SleepSeqNum
);
6929 else if (!sleep
) // Waking up
6934 NetworkInterfaceInfo
*intf
;
6935 mDNSs32 currtime
, diff
;
6938 // Reset SleepLimit back to 0 now that we're awake again.
6941 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6942 if (m
->SleepState
!= SleepState_Awake
)
6944 m
->SleepState
= SleepState_Awake
;
6946 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6947 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6948 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6949 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6950 m
->DelaySleep
= NonZeroTime(m
->timenow
+ kDarkWakeDelaySleep
);
6953 if (m
->SPSState
== 3)
6956 mDNSCoreBeSleepProxyServer_internal(m
, m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
);
6958 m
->mDNSStats
.Wakes
++;
6959 // ... and the same for NextSPSAttempt
6960 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
)) intf
->NextSPSAttempt
= -1;
6962 // Restart unicast and multicast queries
6963 mDNSCoreRestartQueries(m
);
6965 // and reactivtate service registrations
6966 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
6967 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
6968 "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
6970 // 2. Re-validate our cache records
6971 currtime
= mDNSPlatformUTC();
6973 diff
= currtime
- m
->TimeSlept
;
6974 FORALL_CACHERECORDS(slot
, cg
, cr
)
6976 // Temporary fix: For unicast cache records, look at how much time we slept.
6977 // Adjust the RecvTime by the amount of time we slept so that we age the
6978 // cache record appropriately. If it is expired already, purge. If there
6979 // is a network change that happens after the wakeup, we might purge the
6980 // cache anyways and this helps only in the case where there are no network
6981 // changes across sleep/wakeup transition.
6983 // Note: If there is a network/DNS server change that already happened and
6984 // these cache entries are already refreshed and we are getting a delayed
6985 // wake up notification, we might adjust the TimeRcvd based on the time slept
6986 // now which can cause the cache to purge pre-maturely. As this is not a very
6987 // common case, this should happen rarely.
6988 if (!cr
->resrec
.InterfaceID
)
6992 mDNSu32 uTTL
= RRUnadjustedTTL(cr
->resrec
.rroriginalttl
);
6993 const mDNSs32 remain
= uTTL
- (m
->timenow
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
6995 // -if we have slept longer than the remaining TTL, purge and start fresh.
6996 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6997 // a sufficiently big value which could cause the value to go into the future
6998 // because of the signed comparison of time. For this to happen, we should have been
6999 // sleeping really long (~24 days). For now, we want to be conservative and flush even
7000 // if we have slept for more than two days.
7002 if (diff
>= remain
|| diff
> (2 * 24 * 3600))
7004 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7005 "mDNSCoreMachineSleep: " PRI_S
": Purging cache entry SleptTime %d, Remaining TTL %d",
7006 CRDisplayString(m
, cr
), diff
, remain
);
7007 mDNS_PurgeCacheResourceRecord(m
, cr
);
7010 cr
->TimeRcvd
-= (diff
* mDNSPlatformOneSecond
);
7011 if (m
->timenow
- (cr
->TimeRcvd
+ ((mDNSs32
)uTTL
* mDNSPlatformOneSecond
)) >= 0)
7013 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7014 "mDNSCoreMachineSleep: " PRI_S
": Purging after adjusting the remaining TTL %d by %d seconds",
7015 CRDisplayString(m
, cr
), remain
, diff
);
7016 mDNS_PurgeCacheResourceRecord(m
, cr
);
7020 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7021 "mDNSCoreMachineSleep: " PRI_S
": Adjusted the remain ttl %u by %d seconds",
7022 CRDisplayString(m
, cr
), remain
, diff
);
7028 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForWake
);
7032 // 3. Retrigger probing and announcing for all our authoritative records
7033 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
7035 if (AuthRecord_uDNS(rr
))
7037 ActivateUnicastRegistration(m
, rr
);
7041 mDNSCoreRestartRegistration(m
, rr
, -1);
7045 // 4. Refresh NAT mappings
7046 // We don't want to have to assume that all hardware can necessarily keep accurate
7047 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7048 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7049 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7050 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7051 // than five seconds from now.
7052 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7053 RecreateNATMappings(m
, mDNSPlatformOneSecond
* 5);
7058 mDNSexport mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
)
7062 NetworkInterfaceInfo
*intf
;
7066 if (m
->DelaySleep
) goto notready
;
7068 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7069 if (m
->SleepLimit
- now
> 0 && m
->NextScheduledSPRetry
- now
> 0) goto notready
;
7071 m
->NextScheduledSPRetry
= now
+ 0x40000000UL
;
7073 // See if we might need to retransmit any lost Sleep Proxy Registrations
7074 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7075 if (intf
->NextSPSAttempt
>= 0)
7077 if (now
- intf
->NextSPSAttemptTime
>= 0)
7079 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7080 intf
->ifname
, intf
->NextSPSAttempt
/3, intf
->NextSPSAttempt
);
7081 SendSPSRegistration(m
, intf
, zeroID
);
7082 // Don't need to "goto notready" here, because if we do still have record registrations
7083 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7086 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
7087 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
7090 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7091 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7093 int sps
= (intf
->NextSPSAttempt
== 0) ? 0 : (intf
->NextSPSAttempt
-1)/3;
7094 if (intf
->NetWakeResolve
[sps
].ThisQInterval
>= 0)
7096 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7097 intf
->ifname
, intf
->NetWakeResolve
[sps
].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[sps
].qtype
));
7102 // Scan list of registered records
7103 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7104 if (!AuthRecord_uDNS(rr
))
7105 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
7106 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS updateIntID 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto spsnotready
; }
7108 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7109 for (q
= m
->Questions
; q
; q
= q
->next
)
7110 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->ReqLease
== 0 && q
->tcp
)
7112 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
7116 // Scan list of registered records
7117 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7118 if (AuthRecord_uDNS(rr
))
7120 if (rr
->state
== regState_Refresh
&& rr
->tcp
)
7121 { LogSPS("mDNSCoreReadyForSleep: waiting for Record updateIntID 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto notready
; }
7129 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7130 // and allow up to ten seconds more to complete wide-area deregistration instead
7131 if (now
- m
->SleepLimit
>= 0)
7133 LogMsg("Failed to register with SPS, now sending goodbyes");
7135 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7136 if (intf
->NetWakeBrowse
.ThisQInterval
>= 0)
7138 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7139 intf
->ifname
, intf
->NetWakeResolve
[0].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[0].qtype
));
7140 mDNS_DeactivateNetWake_internal(m
, intf
);
7143 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7144 if (!AuthRecord_uDNS(rr
))
7145 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
7147 LogSPS("ReadyForSleep clearing updateIntID 0x%x 0x%x (updateid %d) for %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
, rr
));
7148 rr
->updateIntID
= zeroOpaque64
;
7151 // We'd really like to allow up to ten seconds more here,
7152 // but if we don't respond to the sleep notification within 30 seconds
7153 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7154 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7155 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7156 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7157 m
->SleepLimit
= now
+ mDNSPlatformOneSecond
* 1;
7159 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
7167 mDNSexport mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
)
7171 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7172 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7173 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7174 // and if that happens we don't want to just give up and go back to sleep and never try again.
7175 mDNSs32 e
= now
+ (120 * 60 * mDNSPlatformOneSecond
); // Sleep for at most 120 minutes
7177 NATTraversalInfo
*nat
;
7178 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
7179 if (nat
->Protocol
&& nat
->ExpiryTime
&& nat
->ExpiryTime
- now
> mDNSPlatformOneSecond
*4)
7181 mDNSs32 t
= nat
->ExpiryTime
- (nat
->ExpiryTime
- now
) / 10; // Wake up when 90% of the way to the expiry time
7182 if (e
- t
> 0) e
= t
;
7183 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7184 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
7185 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
7186 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
7187 nat
->retryInterval
/ mDNSPlatformOneSecond
,
7188 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
7189 (t
- now
) / mDNSPlatformOneSecond
);
7192 // This loop checks both the time we need to renew wide-area registrations,
7193 // and the time we need to renew Sleep Proxy registrations
7194 for (ar
= m
->ResourceRecords
; ar
; ar
= ar
->next
)
7195 if (ar
->expire
&& ar
->expire
- now
> mDNSPlatformOneSecond
*4)
7197 mDNSs32 t
= ar
->expire
- (ar
->expire
- now
) / 10; // Wake up when 90% of the way to the expiry time
7198 if (e
- t
> 0) e
= t
;
7199 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7200 ar
, ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
7201 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
7202 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
7203 (t
- now
) / mDNSPlatformOneSecond
, ARDisplayString(m
, ar
));
7209 // ***************************************************************************
7210 #if COMPILER_LIKES_PRAGMA_MARK
7212 #pragma mark - Packet Reception Functions
7215 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7217 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
7218 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
7220 mDNSu8
*responseptr
= response
->data
;
7221 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
7222 const mDNSu8
*ptr
= query
->data
;
7224 mDNSu32 maxttl
= (!InterfaceID
) ? mDNSMaximumUnicastTTLSeconds
: mDNSMaximumMulticastTTLSeconds
;
7227 // Initialize the response fields so we can answer the questions
7228 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
7231 // *** 1. Write out the list of questions we are actually going to answer with this packet
7235 maxttl
= kStaticCacheTTL
;
7236 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7239 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
7240 if (!ptr
) return(mDNSNULL
);
7242 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
7244 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
7245 { // then put the question in the question section
7246 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
7247 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
7248 break; // break out of the ResponseRecords loop, and go on to the next question
7253 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
7257 // *** 2. Write Answers
7259 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7260 if (rr
->NR_AnswerTo
)
7262 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
,
7263 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7264 if (p
) responseptr
= p
;
7265 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
7269 // *** 3. Write Additionals
7271 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7272 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
7274 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
,
7275 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7276 if (p
) responseptr
= p
;
7277 else debugf("GenerateUnicastResponse: No more space for additionals");
7280 return(responseptr
);
7283 // AuthRecord *our is our Resource Record
7284 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7285 // Returns 0 if there is no conflict
7286 // Returns +1 if there was a conflict and we won
7287 // Returns -1 if there was a conflict and we lost and have to rename
7288 mDNSlocal
int CompareRData(const AuthRecord
*const our
, const CacheRecord
*const pkt
)
7290 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
7291 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
7292 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7293 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7295 #if defined(__clang_analyzer__)
7296 // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData().
7297 // There are no clear indications from the analyzer of the cause of the supposed problem.
7298 mDNSPlatformMemZero(ourdata
, 1);
7299 mDNSPlatformMemZero(pktdata
, 1);
7301 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
7302 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
7303 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
7304 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
7306 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
7307 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
7308 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
7309 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
7311 LogMsg("CompareRData ERROR: Invalid state");
7315 mDNSlocal mDNSBool
PacketRecordMatches(const AuthRecord
*const rr
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
7317 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
7319 const AuthRecord
*r2
= rr
;
7320 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
7321 if (r2
== master
) return(mDNStrue
);
7326 // See if we have an authoritative record that's identical to this packet record,
7327 // whose canonical DependentOn record is the specified master record.
7328 // The DependentOn pointer is typically used for the TXT record of service registrations
7329 // It indicates that there is no inherent conflict detection for the TXT record
7330 // -- it depends on the SRV record to resolve name conflicts
7331 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7332 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7333 // If the record has no DependentOn, then just return that record's pointer
7334 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7335 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
7337 const AuthRecord
*r1
;
7338 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
7340 if (PacketRecordMatches(r1
, pktrr
, master
)) return(mDNStrue
);
7342 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
7344 if (PacketRecordMatches(r1
, pktrr
, master
)) return(mDNStrue
);
7349 // Find the canonical RRSet pointer for this RR received in a packet.
7350 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7351 // pointers (if any) to make sure we return the canonical member of this name/type/class
7352 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7353 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
7355 const AuthRecord
*rr
;
7356 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
7358 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
7360 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
7367 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7368 // as one of our records (our) but different rdata.
7369 // 1. If our record is not a type that's supposed to be unique, we don't care.
7370 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7371 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7372 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7373 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7374 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7375 // are members of the same RRSet, then this is not a conflict.
7376 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
7378 // If not supposed to be unique, not a conflict
7379 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
7381 // If a dependent record, not a conflict
7382 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
7385 // If the pktrr matches a member of ourset, not a conflict
7386 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
7387 const AuthRecord
*pktset
= FindRRSet(m
, pktrr
);
7388 if (pktset
== ourset
) return(mDNSfalse
);
7390 // For records we're proxying, where we don't know the full
7391 // relationship between the records, having any matching record
7392 // in our AuthRecords list is sufficient evidence of non-conflict
7393 if (our
->WakeUp
.HMAC
.l
[0] && pktset
) return(mDNSfalse
);
7396 // Okay, this is a conflict
7400 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7401 // the record list and/or question list.
7402 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7403 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7404 DNSQuestion
*q
, AuthRecord
*our
)
7407 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
7408 mDNSBool FoundUpdate
= mDNSfalse
;
7410 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
7412 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
7414 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& CacheRecordAnswersQuestion(&m
->rec
.r
, q
))
7416 FoundUpdate
= mDNStrue
;
7417 if (PacketRRConflict(m
, our
, &m
->rec
.r
))
7419 int result
= (int)our
->resrec
.rrclass
- (int)m
->rec
.r
.resrec
.rrclass
;
7420 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)m
->rec
.r
.resrec
.rrtype
;
7421 if (!result
) result
= CompareRData(our
, &m
->rec
.r
);
7424 const char *const msg
= (result
< 0) ? "lost:" : (result
> 0) ? "won: " : "tie: ";
7425 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7426 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, msg
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7428 // If we lost the tie-break for simultaneous probes, we don't immediately give up, because we might be seeing stale packets on the network.
7429 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7430 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7433 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
7434 our
->ProbeCount
= DefaultProbeCountForTypeUnique
;
7435 our
->AnnounceCount
= InitialAnnounceCount
;
7436 InitializeLastAPTime(m
, our
);
7443 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7444 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7448 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7451 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
->c
, DNSTypeName(our
->resrec
.rrtype
));
7453 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7456 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, const ResourceRecord
*const pktrr
)
7458 CacheGroup
*cg
= CacheGroupForRecord(m
, pktrr
);
7461 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7463 if (!pktrr
->InterfaceID
)
7465 const mDNSu32 id1
= (pktrr
->rDNSServer
? pktrr
->rDNSServer
->resGroupID
: 0);
7466 const mDNSu32 id2
= (rr
->resrec
.rDNSServer
? rr
->resrec
.rDNSServer
->resGroupID
: 0);
7467 match
= (id1
== id2
);
7469 else match
= (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
);
7471 if (match
&& IdenticalSameNameRecord(pktrr
, &rr
->resrec
)) break;
7475 mDNSlocal
void DeregisterProxyRecord(mDNS
*const m
, AuthRecord
*const rr
)
7477 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7478 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
7479 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7480 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7483 mDNSlocal
void ClearKeepaliveProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
, const mDNSInterfaceID InterfaceID
)
7485 if (m
->CurrentRecord
)
7486 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7487 m
->CurrentRecord
= thelist
;
7489 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7490 // clean up the keepalive record.
7491 while (m
->CurrentRecord
)
7493 AuthRecord
*const rr
= m
->CurrentRecord
;
7494 if (InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7496 if (mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
7498 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7499 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7500 DeregisterProxyRecord(m
, rr
);
7503 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7504 // new records could have been added to the end of the list as a result of that call.
7505 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7506 m
->CurrentRecord
= rr
->next
;
7510 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7511 // to check our lists and discard any stale duplicates of this record we already have
7512 mDNSlocal
void ClearIdenticalProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7514 if (m
->CurrentRecord
)
7515 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7516 m
->CurrentRecord
= thelist
;
7517 while (m
->CurrentRecord
)
7519 AuthRecord
*const rr
= m
->CurrentRecord
;
7520 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7521 if (IdenticalResourceRecord(&rr
->resrec
, &m
->rec
.r
.resrec
))
7523 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7524 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7525 DeregisterProxyRecord(m
, rr
);
7527 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7528 // new records could have been added to the end of the list as a result of that call.
7529 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7530 m
->CurrentRecord
= rr
->next
;
7534 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7535 mDNSlocal
void ClearProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7537 if (m
->CurrentRecord
)
7538 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7539 m
->CurrentRecord
= thelist
;
7540 while (m
->CurrentRecord
)
7542 AuthRecord
*const rr
= m
->CurrentRecord
;
7543 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7544 if (owner
->seq
!= rr
->WakeUp
.seq
|| m
->timenow
- rr
->TimeRcvd
> mDNSPlatformOneSecond
* 60)
7546 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
7548 // We don't do this here because we know that the host is waking up at this point, so we don't send
7549 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7550 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7551 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7552 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7553 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
7554 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, &rr
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
7557 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7558 m
->ProxyRecords
, rr
->AnnounceCount
, rr
->resrec
.RecordType
,
7559 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7560 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
7561 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7562 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it, since real host is now back and functional
7563 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7564 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7566 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7567 // new records could have been added to the end of the list as a result of that call.
7568 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7569 m
->CurrentRecord
= rr
->next
;
7573 // ProcessQuery examines a received query to see if we have any answers to give
7574 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7575 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
7576 mDNSBool QueryWasLocalUnicast
, DNSMessage
*const response
)
7578 const mDNSBool FromLocalSubnet
= mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
7579 AuthRecord
*ResponseRecords
= mDNSNULL
;
7580 AuthRecord
**nrp
= &ResponseRecords
;
7583 mDNSBool notD2D
= !mDNSPlatformInterfaceIsD2D(InterfaceID
); // We don't run the POOF algorithm on D2D interfaces.
7584 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
7585 CacheRecord
**eap
= &ExpectedAnswers
;
7586 #endif // POOF_ENABLED
7588 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
7589 DNSQuestion
**dqp
= &DupQuestions
;
7590 mDNSs32 delayresponse
= 0;
7591 mDNSBool SendLegacyResponse
= mDNSfalse
;
7593 mDNSu8
*responseptr
= mDNSNULL
;
7596 CacheRecord
*McastNSEC3Records
= mDNSNULL
;
7599 // *** 1. Look in Additional Section for an OPT record
7601 ptr
= LocateOptRR(query
, end
, DNSOpt_OwnerData_ID_Space
);
7604 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAdd
, &m
->rec
);
7605 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
7607 const rdataOPT
*opt
;
7608 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
7609 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7610 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7611 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
7612 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
7614 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
7615 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
7618 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7622 // Look in Authority Section for NSEC3 record
7625 mDNSParseNSEC3Records(m
, query
, end
, InterfaceID
, &McastNSEC3Records
);
7628 // *** 2. Parse Question Section and mark potential answers
7631 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7633 mDNSBool QuestionNeedsMulticastResponse
;
7634 int NumAnswersForThisQuestion
= 0;
7635 AuthRecord
*NSECAnswer
= mDNSNULL
;
7636 DNSQuestion pktq
, *q
;
7637 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
7638 if (!ptr
) goto exit
;
7640 // The only queries that *need* a multicast response are:
7641 // * Queries sent via multicast
7643 // * that don't have the kDNSQClass_UnicastResponse bit set
7644 // These queries need multicast responses because other clients will:
7645 // * suppress their own identical questions when they see these questions, and
7646 // * expire their cache records if they don't see the expected responses
7647 // For other queries, we may still choose to send the occasional multicast response anyway,
7648 // to keep our neighbours caches warm, and for ongoing conflict detection.
7649 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
7651 if (pktq
.qclass
& kDNSQClass_UnicastResponse
)
7652 m
->mDNSStats
.UnicastBitInQueries
++;
7654 m
->mDNSStats
.NormalQueries
++;
7656 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7657 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
7659 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7660 // can result in user callbacks which may change the record list and/or question list.
7661 // Also note: we just mark potential answer records here, without trying to build the
7662 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7663 // from that list while we're in the middle of trying to build it.
7664 if (m
->CurrentRecord
)
7665 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7666 m
->CurrentRecord
= m
->ResourceRecords
;
7667 while (m
->CurrentRecord
)
7669 rr
= m
->CurrentRecord
;
7670 m
->CurrentRecord
= rr
->next
;
7671 if (AnyTypeRecordAnswersQuestion(rr
, &pktq
) && (QueryWasMulticast
|| QueryWasLocalUnicast
|| rr
->AllowRemoteQuery
))
7673 m
->mDNSStats
.MatchingAnswersForQueries
++;
7674 if (RRTypeAnswersQuestionType(&rr
->resrec
, pktq
.qtype
))
7676 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
7677 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
7678 else if (ResourceRecordIsValidAnswer(rr
))
7680 NumAnswersForThisQuestion
++;
7682 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7683 // unicast answer back to the source, because timeliness in answering probes is important.
7686 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7687 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7688 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7689 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7690 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7691 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7692 if (QuestionNeedsMulticastResponse
|| (!FromLocalSubnet
&& QueryWasMulticast
&& !LegacyQuery
))
7694 // We only mark this question for sending if it is at least one second since the last time we multicast it
7695 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7696 // This is to guard against the case where someone blasts us with queries as fast as they can.
7697 if ((mDNSu32
)(m
->timenow
- rr
->LastMCTime
) >= (mDNSu32
)mDNSPlatformOneSecond
||
7698 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
7699 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7701 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= LegacyQuery
? ptr
: NR_AnswerUnicast
;
7704 else if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && ResourceRecordIsValidAnswer(rr
))
7706 // If we don't have any answers for this question, but we do own another record with the same name,
7707 // then we'll want to mark it to generate an NSEC record on this interface
7708 if (!NSECAnswer
) NSECAnswer
= rr
;
7713 if (NumAnswersForThisQuestion
== 0 && NSECAnswer
)
7715 NumAnswersForThisQuestion
++;
7716 NSECAnswer
->SendNSECNow
= InterfaceID
;
7717 m
->NextScheduledResponse
= m
->timenow
;
7720 // If we couldn't answer this question, someone else might be able to,
7721 // so use random delay on response to reduce collisions
7722 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
7724 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
)
7725 m
->mDNSStats
.KnownAnswerMultiplePkts
++;
7726 // We only do the following accelerated cache expiration and duplicate question suppression processing
7727 // for non-truncated multicast queries with multicast responses.
7728 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7729 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7730 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7731 if (QuestionNeedsMulticastResponse
&& !(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7736 CacheGroup
*cg
= CacheGroupForName(m
, pktq
.qnamehash
, &pktq
.qname
);
7739 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7740 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7741 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
7743 if (SameNameCacheRecordAnswersQuestion(cr
, &pktq
) && cr
->resrec
.rdlength
<= SmallRecordLimit
)
7745 if (!cr
->NextInKAList
&& eap
!= &cr
->NextInKAList
)
7748 eap
= &cr
->NextInKAList
;
7753 #endif // POOF_ENABLED
7755 // Check if this question is the same as any of mine.
7756 // We only do this for non-truncated queries. Right now it would be too complicated to try
7757 // to keep track of duplicate suppression state between multiple packets, especially when we
7758 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7759 for (q
= m
->Questions
; q
; q
=q
->next
)
7761 if (ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
7763 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
7765 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
7767 if (q
->qtype
== pktq
.qtype
&&
7768 q
->qclass
== pktq
.qclass
&&
7769 q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
7770 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
7779 // *** 3. Now we can safely build the list of marked answers
7781 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
7782 if (rr
->NR_AnswerTo
) // If we marked the record...
7783 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
7786 // *** 4. Add additional records
7788 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
7791 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7793 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
7795 // Get the record...
7796 CacheRecord
*ourcacherr
;
7797 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &m
->rec
);
7798 if (!ptr
) goto exit
;
7799 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
7801 // See if this Known-Answer suppresses any of our currently planned answers
7802 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7804 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7806 m
->mDNSStats
.KnownAnswerSuppressions
++;
7807 rr
->NR_AnswerTo
= mDNSNULL
;
7808 rr
->NR_AdditionalTo
= mDNSNULL
;
7812 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7813 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
7815 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7816 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7818 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7820 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zerov4Addr
;
7822 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7824 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
7826 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
))
7828 m
->mDNSStats
.KnownAnswerSuppressions
++;
7829 rr
->ImmedAnswer
= mDNSNULL
;
7830 rr
->ImmedUnicast
= mDNSfalse
;
7831 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7832 LogMsg("Suppressed after%4d: %s", m
->timenow
- rr
->ImmedAnswerMarkTime
, ARDisplayString(m
, rr
));
7838 ourcacherr
= FindIdenticalRecordInCache(m
, &m
->rec
.r
.resrec
);
7843 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7844 // any records that are suppressed by the Known Answer list in this packet.
7845 eap
= &ExpectedAnswers
;
7848 CacheRecord
*cr
= *eap
;
7849 if (cr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
7850 { *eap
= cr
->NextInKAList
; cr
->NextInKAList
= mDNSNULL
; }
7851 else eap
= &cr
->NextInKAList
;
7854 #endif // POOF_ENABLED
7856 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7859 dqp
= &DupQuestions
;
7862 DNSQuestion
*q
= *dqp
;
7863 if (CacheRecordAnswersQuestion(&m
->rec
.r
, q
))
7864 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
7865 else dqp
= &q
->NextInDQList
;
7869 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7873 // *** 6. Cancel any additionals that were added because of now-deleted records
7875 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7876 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
7877 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
7880 // *** 7. Mark the send flags on the records we plan to send
7882 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7884 if (rr
->NR_AnswerTo
)
7886 mDNSBool SendMulticastResponse
= mDNSfalse
; // Send modern multicast response
7887 mDNSBool SendUnicastResponse
= mDNSfalse
; // Send modern unicast response (not legacy unicast response)
7889 // If it's been one TTL/4 since we multicast this, then send a multicast response
7890 // for conflict detection, etc.
7891 if ((mDNSu32
)(m
->timenow
- rr
->LastMCTime
) >= (mDNSu32
)TicksTTL(rr
)/4)
7893 SendMulticastResponse
= mDNStrue
;
7894 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7895 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7896 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7897 if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7899 m
->mDNSStats
.UnicastDemotedToMulticast
++;
7900 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7904 // If the client insists on a multicast response, then we'd better send one
7905 if (rr
->NR_AnswerTo
== NR_AnswerMulticast
)
7907 m
->mDNSStats
.MulticastResponses
++;
7908 SendMulticastResponse
= mDNStrue
;
7910 else if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7912 m
->mDNSStats
.UnicastResponses
++;
7913 SendUnicastResponse
= mDNStrue
;
7915 else if (rr
->NR_AnswerTo
)
7917 SendLegacyResponse
= mDNStrue
;
7920 if (SendMulticastResponse
|| SendUnicastResponse
)
7922 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7923 rr
->ImmedAnswerMarkTime
= m
->timenow
;
7925 m
->NextScheduledResponse
= m
->timenow
;
7926 // If we're already planning to send this on another interface, just send it on all interfaces
7927 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
7928 rr
->ImmedAnswer
= mDNSInterfaceMark
;
7931 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
7932 if (SendUnicastResponse
) rr
->ImmedUnicast
= mDNStrue
;
7933 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7935 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
7936 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
7938 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7940 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
7941 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
7945 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7946 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7947 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7948 // else, for a simple unique record reply, we can reply immediately; no need for delay
7949 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
7950 else if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
7952 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== NR_AnswerMulticast
)
7954 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7955 // If two clients on different interfaces do queries that invoke the same optional additional answer,
7956 // then the earlier client is out of luck
7957 rr
->ImmedAdditional
= InterfaceID
;
7958 // No need to set m->NextScheduledResponse here
7959 // We'll send these additional records when we send them, or not, as the case may be
7964 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7966 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
7968 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7969 mDNSs32 oldss
= m
->SuppressSending
;
7970 if (oldss
&& delayresponse
)
7971 LogMsg("Current SuppressSending delay%5ld; require%5ld", m
->SuppressSending
- m
->timenow
, (delayresponse
+ 49) / 50);
7973 // Pick a random delay:
7974 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7975 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7976 // This is an integer value, with resolution determined by the platform clock rate.
7977 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7978 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7979 // The +49 before dividing is to ensure we round up, not down, to ensure that even
7980 // on platforms where the native clock rate is less than fifty ticks per second,
7981 // we still guarantee that the final calculated delay is at least one platform tick.
7982 // We want to make sure we don't ever allow the delay to be zero ticks,
7983 // because if that happens we'll fail the Bonjour Conformance Test.
7984 // Our final computed delay is 20-120ms for normal delayed replies,
7985 // or 400-500ms in the case of multi-packet known-answer lists.
7986 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
7987 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
7988 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7989 if (oldss
&& delayresponse
)
7990 LogMsg("Set SuppressSending to %5ld", m
->SuppressSending
- m
->timenow
);
7995 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7997 if (SendLegacyResponse
)
7998 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
8001 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8004 // *** 10. Finally, clear our link chains ready for use next time
8006 while (ResponseRecords
)
8008 rr
= ResponseRecords
;
8009 ResponseRecords
= rr
->NextResponse
;
8010 rr
->NextResponse
= mDNSNULL
;
8011 rr
->NR_AnswerTo
= mDNSNULL
;
8012 rr
->NR_AdditionalTo
= mDNSNULL
;
8016 while (ExpectedAnswers
&& notD2D
)
8018 CacheRecord
*cr
= ExpectedAnswers
;
8019 ExpectedAnswers
= cr
->NextInKAList
;
8020 cr
->NextInKAList
= mDNSNULL
;
8022 // For non-truncated queries, we can definitively say that we should expect
8023 // to be seeing a response for any records still left in the ExpectedAnswers list
8024 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
8025 if (cr
->UnansweredQueries
== 0 || m
->timenow
- cr
->LastUnansweredTime
>= mDNSPlatformOneSecond
* 3/4)
8027 cr
->UnansweredQueries
++;
8028 cr
->LastUnansweredTime
= m
->timenow
;
8029 if (cr
->UnansweredQueries
> 1)
8030 debugf("ProcessQuery: UnansweredQueries %lu %s", cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
8031 SetNextCacheCheckTimeForRecord(m
, cr
);
8034 // If we've seen multiple unanswered queries for this record,
8035 // then mark it to expire in five seconds if we don't get a response by then.
8036 if (cr
->UnansweredQueries
>= MaxUnansweredQueries
)
8038 // Only show debugging message if this record was not about to expire anyway
8039 if (RRExpireTime(cr
) - m
->timenow
> (mDNSs32
) kDefaultReconfirmTimeForNoAnswer
* 4 / 3 + mDNSPlatformOneSecond
)
8040 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
8041 cr
->UnansweredQueries
, InterfaceID
, (RRExpireTime(cr
) - m
->timenow
+ mDNSPlatformOneSecond
-1) / mDNSPlatformOneSecond
, CRDisplayString(m
, cr
));
8043 m
->mDNSStats
.PoofCacheDeletions
++;
8044 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
8047 #endif // POOF_ENABLED
8049 while (DupQuestions
)
8051 DNSQuestion
*q
= DupQuestions
;
8052 DupQuestions
= q
->NextInDQList
;
8053 q
->NextInDQList
= mDNSNULL
;
8054 RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
8055 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
8056 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6");
8059 if (McastNSEC3Records
)
8061 debugf("ProcessQuery: McastNSEC3Records not used");
8062 FreeNSECRecords(m
, McastNSEC3Records
);
8065 return(responseptr
);
8068 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
8069 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8070 const mDNSInterfaceID InterfaceID
)
8072 mDNSu8
*responseend
= mDNSNULL
;
8073 mDNSBool QueryWasLocalUnicast
= srcaddr
&& dstaddr
&&
8074 !mDNSAddrIsDNSMulticast(dstaddr
) && mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
8076 if (!dstaddr
|| (!InterfaceID
&& mDNSAddrIsDNSMulticast(dstaddr
)))
8078 const char *const reason
= !dstaddr
? "Received over TCP connection" : "Multicast, but no InterfaceID";
8079 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8080 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8081 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8082 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8083 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8084 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8085 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
, reason
);
8089 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8090 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8091 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8092 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8093 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8094 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8095 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
8097 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
8098 !mDNSSameIPPort(srcport
, MulticastDNSPort
), mDNSAddrIsDNSMulticast(dstaddr
), QueryWasLocalUnicast
, &m
->omsg
);
8100 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
8102 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8103 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
8104 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
8105 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s",
8106 srcaddr
, mDNSVal16(srcport
), InterfaceID
, srcaddr
->type
);
8107 mDNSSendDNSMessage(m
, &m
->omsg
, responseend
, InterfaceID
, mDNSNULL
, mDNSNULL
, srcaddr
, srcport
, mDNSNULL
, mDNSfalse
);
8112 mDNSlocal mDNSBool
TrustedSource(const mDNS
*const m
, const mDNSAddr
*const srcaddr
)
8116 (void)srcaddr
; // Unused
8117 for (s
= m
->DNSServers
; s
; s
= s
->next
)
8118 if (mDNSSameAddress(srcaddr
, &s
->addr
)) return(mDNStrue
);
8123 struct UDPSocket_struct
8125 mDNSIPPort port
; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8128 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForQuestion(const mDNS
*const m
, const mDNSIPPort port
, const mDNSOpaque16 id
, const DNSQuestion
*const question
, mDNSBool tcp
, DNSQuestion
** suspiciousQ
)
8131 for (q
= m
->Questions
; q
; q
=q
->next
)
8133 if (!tcp
&& !q
->LocalSocket
) continue;
8134 if (mDNSSameIPPort(tcp
? q
->tcpSrcPort
: q
->LocalSocket
->port
, port
) &&
8135 q
->qtype
== question
->qtype
&&
8136 q
->qclass
== question
->qclass
&&
8137 q
->qnamehash
== question
->qnamehash
&&
8138 SameDomainName(&q
->qname
, &question
->qname
))
8140 if (mDNSSameOpaque16(q
->TargetQID
, id
)) return(q
);
8143 if (!tcp
&& suspiciousQ
) *suspiciousQ
= q
;
8151 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8152 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8153 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForRecord(mDNS
*const m
,
8154 const mDNSAddr
*const srcaddr
, const mDNSBool SrcLocal
, const mDNSIPPort port
, const mDNSOpaque16 id
, const CacheRecord
*const rr
, mDNSBool tcp
)
8159 for (q
= m
->Questions
; q
; q
=q
->next
)
8161 if (!q
->DuplicateOf
&& ResourceRecordAnswersUnicastResponse(&rr
->resrec
, q
))
8163 if (!mDNSOpaque16IsZero(q
->TargetQID
))
8165 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id
), mDNSVal16(q
->TargetQID
), CRDisplayString(m
, rr
));
8167 if (mDNSSameOpaque16(q
->TargetQID
, id
))
8172 srcp
= q
->LocalSocket
? q
->LocalSocket
->port
: zeroIPPort
;
8176 srcp
= q
->tcpSrcPort
;
8178 if (mDNSSameIPPort(srcp
, port
)) return(q
);
8180 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8181 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8182 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8183 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s",
8184 q
->qname
.c
, DNSTypeName(q
->qtype
), srcaddr
, mDNSVal16(port
), CRDisplayString(m
, rr
));
8190 if (SrcLocal
&& q
->ExpectUnicastResp
&& (mDNSu32
)(m
->timenow
- q
->ExpectUnicastResp
) < (mDNSu32
)(mDNSPlatformOneSecond
*2))
8198 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8199 // Currently this applies only to rdata types containing more than one domainname,
8200 // or types where the domainname is not the last item in the structure.
8201 mDNSlocal mDNSu16
GetRDLengthMem(const ResourceRecord
*const rr
)
8205 case kDNSType_SOA
: return sizeof(rdataSOA
);
8206 case kDNSType_RP
: return sizeof(rdataRP
);
8207 case kDNSType_PX
: return sizeof(rdataPX
);
8208 default: return rr
->rdlength
;
8212 mDNSexport CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
, mDNSs32 delay
, mDNSBool Add
, const mDNSAddr
*sourceAddress
)
8214 CacheRecord
*rr
= mDNSNULL
;
8215 mDNSu16 RDLength
= GetRDLengthMem(&m
->rec
.r
.resrec
);
8217 if (!m
->rec
.r
.resrec
.InterfaceID
) debugf("CreateNewCacheEntry %s", CRDisplayString(m
, &m
->rec
.r
));
8219 //if (RDLength > InlineCacheRDSize)
8220 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8222 if (!cg
) cg
= GetCacheGroup(m
, slot
, &m
->rec
.r
.resrec
); // If we don't have a CacheGroup for this name, make one now
8223 if (cg
) rr
= GetCacheRecord(m
, cg
, RDLength
); // Make a cache record, being careful not to recycle cg
8224 if (!rr
) NoCacheAnswer(m
, &m
->rec
.r
);
8227 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
8228 *rr
= m
->rec
.r
; // Block copy the CacheRecord object
8229 rr
->resrec
.rdata
= saveptr
; // Restore rr->resrec.rdata after the structure assignment
8230 rr
->resrec
.name
= cg
->name
; // And set rr->resrec.name to point into our CacheGroup header
8231 rr
->resrec
.mortality
= Mortality_Mortal
;
8233 rr
->DelayDelivery
= delay
;
8235 // If this is an oversized record with external storage allocated, copy rdata to external storage
8236 if (rr
->resrec
.rdata
== (RData
*)&rr
->smallrdatastorage
&& RDLength
> InlineCacheRDSize
)
8237 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8238 else if (rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
&& RDLength
<= InlineCacheRDSize
)
8239 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8240 if (RDLength
> InlineCacheRDSize
)
8241 mDNSPlatformMemCopy(rr
->resrec
.rdata
, m
->rec
.r
.resrec
.rdata
, sizeofRDataHeader
+ RDLength
);
8243 rr
->next
= mDNSNULL
; // Clear 'next' pointer
8244 rr
->nsec
= mDNSNULL
;
8248 rr
->sourceAddress
= *sourceAddress
;
8250 if (!rr
->resrec
.InterfaceID
)
8252 m
->rrcache_totalused_unicast
+= rr
->resrec
.rdlength
;
8253 if (DNSSECRecordType(rr
->resrec
.rrtype
))
8254 BumpDNSSECStats(m
, kStatsActionIncrement
, kStatsTypeMemoryUsage
, rr
->resrec
.rdlength
);
8259 *(cg
->rrcache_tail
) = rr
; // Append this record to tail of cache slot list
8260 cg
->rrcache_tail
= &(rr
->next
); // Advance tail pointer
8261 CacheRecordAdd(m
, rr
); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8265 // Can't use the "cg->name" if we are not adding to the cache as the
8266 // CacheGroup may be released anytime if it is empty
8267 domainname
*name
= (domainname
*) mDNSPlatformMemAllocate(DomainNameLength(cg
->name
));
8270 AssignDomainName(name
, cg
->name
);
8271 rr
->resrec
.name
= name
;
8275 ReleaseCacheRecord(m
, rr
);
8276 NoCacheAnswer(m
, &m
->rec
.r
);
8284 mDNSlocal
void RefreshCacheRecord(mDNS
*const m
, CacheRecord
*rr
, mDNSu32 ttl
)
8286 rr
->TimeRcvd
= m
->timenow
;
8287 rr
->resrec
.rroriginalttl
= ttl
;
8288 rr
->UnansweredQueries
= 0;
8289 if (rr
->resrec
.mortality
!= Mortality_Mortal
) rr
->resrec
.mortality
= Mortality_Immortal
;
8290 SetNextCacheCheckTimeForRecord(m
, rr
);
8293 mDNSexport
void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
)
8296 CacheGroup
*cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
8297 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
8298 if (rr
->CRActiveQuestion
== q
)
8300 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8301 RefreshCacheRecord(m
, rr
, lease
);
8305 mDNSlocal mDNSu32
GetEffectiveTTL(const uDNS_LLQType LLQType
, mDNSu32 ttl
) // TTL in seconds
8307 if (LLQType
== uDNS_LLQ_Entire
) ttl
= kLLQ_DefLease
;
8308 else if (LLQType
== uDNS_LLQ_Events
)
8310 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8311 if (ttl
== 0xFFFFFFFF) ttl
= 0;
8312 else ttl
= kLLQ_DefLease
;
8314 else // else not LLQ (standard uDNS response)
8316 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8317 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8318 if (ttl
> 0x60000000UL
/ mDNSPlatformOneSecond
) ttl
= 0x60000000UL
/ mDNSPlatformOneSecond
;
8320 ttl
= RRAdjustTTL(ttl
);
8322 // For mDNS, TTL zero means "delete this record"
8323 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8324 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8325 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8326 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8327 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8328 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8329 // (with the current code) result in the server having even less than three seconds to respond
8330 // before we deleted the record and reported a "remove" event to any active questions.
8331 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8332 // then things really break (e.g. we end up making a negative cache entry).
8333 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8334 if (ttl
< 15) ttl
= 15;
8340 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8342 mDNSlocal mDNSBool
IsResponseAcceptable(mDNS
*const m
, const CacheRecord
*crlist
, DNSQuestion
*q
, mDNSBool
*nseclist
)
8344 CacheRecord
*const newcr
= &m
->rec
.r
;
8345 ResourceRecord
*rr
= &newcr
->resrec
;
8346 const CacheRecord
*cr
;
8348 *nseclist
= mDNSfalse
;
8349 for (cr
= crlist
; cr
!= (CacheRecord
*)1; cr
= cr
->NextInCFList
)
8351 domainname
*target
= GetRRDomainNameTarget(&cr
->resrec
);
8352 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8353 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8354 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8355 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8356 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8358 if (target
&& cr
->resrec
.rdatahash
== rr
->namehash
&& SameDomainName(target
, rr
->name
))
8360 LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr
->name
->c
, CRDisplayString(m
, cr
));
8365 // Either the question requires validation or we are validating a response with DNSSEC in which case
8366 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8367 // we receive NSECs for our query which does not match the qname and we need to cache in that case
8368 // too. nseclist is set if they have to be cached as part of the negative cache record.
8369 if (q
&& DNSSECQuestion(q
))
8371 mDNSBool same
= SameDomainName(&q
->qname
, rr
->name
);
8372 if (same
&& (q
->qtype
== rr
->rrtype
|| rr
->rrtype
== kDNSType_CNAME
))
8374 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q
->qtype
),
8375 CRDisplayString(m
, newcr
));
8378 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
8379 // "nseclist" is set
8380 if (rr
->rrtype
== kDNSType_RRSIG
)
8382 RDataBody2
*const rdb
= (RDataBody2
*)newcr
->smallrdatastorage
.data
;
8383 rdataRRSig
*rrsig
= &rdb
->rrsig
;
8384 mDNSu16 typeCovered
= swap16(rrsig
->typeCovered
);
8386 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8387 // would match the qtype and they are cached normally as they are not used to prove the
8388 // non-existence of any name. In that case, it is like any other normal dnssec validation
8389 // and hence nseclist should not be set.
8391 if (same
&& ((typeCovered
== q
->qtype
) || (typeCovered
== kDNSType_CNAME
)))
8393 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m
, newcr
),
8394 DNSTypeName(q
->qtype
));
8397 else if (typeCovered
== kDNSType_NSEC
|| typeCovered
== kDNSType_NSEC3
)
8399 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m
, newcr
), DNSTypeName(typeCovered
));
8400 *nseclist
= mDNStrue
;
8403 else if (typeCovered
== kDNSType_SOA
)
8405 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m
, newcr
));
8406 *nseclist
= mDNStrue
;
8409 else return mDNSfalse
;
8411 if (rr
->rrtype
== kDNSType_NSEC
)
8413 if (!UNICAST_NSEC(rr
))
8415 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m
, newcr
));
8418 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8419 *nseclist
= mDNStrue
;
8422 if (rr
->rrtype
== kDNSType_SOA
)
8424 LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8425 *nseclist
= mDNStrue
;
8428 else if (rr
->rrtype
== kDNSType_NSEC3
)
8430 LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8431 *nseclist
= mDNStrue
;
8438 mDNSlocal
void FreeNSECRecords(mDNS
*const m
, CacheRecord
*NSECRecords
)
8440 CacheRecord
*rp
, *next
;
8442 for (rp
= NSECRecords
; rp
; rp
= next
)
8445 ReleaseCacheRecord(m
, rp
);
8449 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8450 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8451 mDNSlocal
void mDNSCoreReceiveNoDNSSECAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*dstaddr
,
8452 mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
)
8455 const mDNSu8
*ptr
= response
->data
;
8457 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
8460 DNSQuestion
*qptr
= mDNSNULL
;
8461 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &pktq
);
8462 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &pktq
, !dstaddr
, mDNSNULL
)) &&
8463 qptr
->ValidatingResponse
)
8465 DNSQuestion
*next
, *q
;
8467 if (qptr
->DuplicateOf
)
8468 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr
->qname
.c
, DNSTypeName(qptr
->qtype
));
8470 // Be careful to call the callback for duplicate questions first and then the original
8471 // question. If we called the callback on the original question, it could stop and
8472 // a duplicate question would become the original question.
8473 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
8474 for (q
= qptr
->next
; q
&& q
!= m
->NewQuestions
; q
= next
)
8477 if (q
->DuplicateOf
== qptr
)
8479 if (q
->ValidatingResponse
)
8480 LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q
->qname
.c
, DNSTypeName(q
->qtype
));
8482 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q
->qname
.c
, DNSTypeName(q
->qtype
));
8483 if (q
->QuestionCallback
)
8484 q
->QuestionCallback(m
, q
, mDNSNULL
, QC_nodnssec
);
8487 if (qptr
->QuestionCallback
)
8488 qptr
->QuestionCallback(m
, qptr
, mDNSNULL
, QC_nodnssec
);
8489 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8494 mDNSlocal
void mDNSCoreReceiveNoUnicastAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*dstaddr
,
8495 mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
, uDNS_LLQType LLQType
, mDNSu8 rcode
, CacheRecord
*NSECRecords
)
8498 const mDNSu8
*ptr
= response
->data
;
8499 CacheRecord
*SOARecord
= mDNSNULL
;
8501 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
8504 DNSQuestion
*qptr
= mDNSNULL
;
8505 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
8506 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
, mDNSNULL
)))
8508 CacheRecord
*cr
, *neg
= mDNSNULL
;
8509 CacheGroup
*cg
= CacheGroupForName(m
, q
.qnamehash
, &q
.qname
);
8510 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
8512 if (SameNameCacheRecordAnswersQuestion(cr
, qptr
))
8514 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8515 if (RRExpireTime(cr
) - m
->timenow
> 0) break;
8516 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8517 if (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) neg
= cr
;
8520 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8521 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8522 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8523 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8524 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8525 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8526 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8527 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8528 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8529 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8531 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8532 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8533 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8534 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8535 // do the appropriate thing. This negative response is also needed for appending new search domains.
8536 if (!InterfaceID
&& q
.qtype
!= kDNSType_SOA
&& IsLocalDomain(&q
.qname
))
8540 const mDNSBool noData
= ((response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
) == kDNSFlag1_RC_NoErr
) ? mDNStrue
: mDNSfalse
;
8541 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8542 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " PRI_DM_NAME
" (" PUB_S
")",
8543 q
.request_id
, mDNSVal16(q
.TargetQID
), DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
8544 m
->CurrentQuestion
= qptr
;
8545 // We are not creating a cache record in this case, we need to pass back
8546 // the error we got so that the proxy code can return the right one to
8548 if (qptr
->ProxyQuestion
)
8549 qptr
->responseFlags
= response
->h
.flags
;
8550 GenerateNegativeResponseEx(m
, mDNSInterface_Any
, QC_forceresponse
, noData
);
8551 m
->CurrentQuestion
= mDNSNULL
;
8555 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8556 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for " PRI_DM_NAME
" (" PUB_S
")",
8557 q
.request_id
, mDNSVal16(q
.TargetQID
), DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
8564 // We start off assuming a negative caching TTL of 60 seconds
8565 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8566 mDNSu32 negttl
= 60;
8568 const domainname
*name
= &q
.qname
;
8569 mDNSu32 hash
= q
.qnamehash
;
8571 // Special case for our special Microsoft Active Directory "local SOA" check.
8572 // Some cheap home gateways don't include an SOA record in the authority section when
8573 // they send negative responses, so we don't know how long to cache the negative result.
8574 // Because we don't want to keep hitting the root name servers with our query to find
8575 // if we're on a network using Microsoft Active Directory using "local" as a private
8576 // internal top-level domain, we make sure to cache the negative result for at least one day.
8577 if (q
.qtype
== kDNSType_SOA
&& SameDomainName(&q
.qname
, &localdomain
)) negttl
= 60 * 60 * 24;
8579 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8580 if (response
->h
.numAuthorities
&& (ptr
= LocateAuthorities(response
, end
)) != mDNSNULL
)
8582 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8583 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_SOA
)
8585 CacheGroup
*cgSOA
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
8586 const rdataSOA
*const soa
= (const rdataSOA
*)m
->rec
.r
.resrec
.rdata
->u
.data
;
8587 mDNSu32 ttl_s
= soa
->min
;
8588 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8589 // for the SOA record for ".", where the record is reported as non-cacheable
8590 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8591 if (ttl_s
> m
->rec
.r
.resrec
.rroriginalttl
&& m
->rec
.r
.resrec
.name
->c
[0])
8592 ttl_s
= m
->rec
.r
.resrec
.rroriginalttl
;
8593 if (negttl
< ttl_s
) negttl
= ttl_s
;
8595 // Create the SOA record as we may have to return this to the questions
8596 // that we are acting as a proxy for currently or in the future.
8597 SOARecord
= CreateNewCacheEntry(m
, HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
), cgSOA
, 1, mDNSfalse
, mDNSNULL
);
8599 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8600 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8601 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8602 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8604 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8605 // along with the negative cache record. For simplicity, we don't create the additional records.
8606 if (!qptr
->ProxyQuestion
&& q
.qtype
== kDNSType_SOA
)
8608 int qcount
= CountLabels(&q
.qname
);
8609 int scount
= CountLabels(m
->rec
.r
.resrec
.name
);
8610 if (qcount
- 1 > scount
)
8611 if (SameDomainName(SkipLeadingLabels(&q
.qname
, qcount
- scount
), m
->rec
.r
.resrec
.name
))
8612 repeat
= qcount
- 1 - scount
;
8615 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8618 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8619 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8620 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8621 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8622 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8623 // so that we back off our polling rate and don't keep hitting the server continually.
8626 if (negttl
< neg
->resrec
.rroriginalttl
* 2)
8627 negttl
= neg
->resrec
.rroriginalttl
* 2;
8632 negttl
= GetEffectiveTTL(LLQType
, negttl
); // Add 25% grace period if necessary
8634 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8637 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8638 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S
,
8639 q
.request_id
, mDNSVal16(q
.TargetQID
), neg
->resrec
.rroriginalttl
, negttl
, CRDisplayString(m
, neg
));
8640 RefreshCacheRecord(m
, neg
, negttl
);
8641 // When we created the cache for the first time and answered the question, the question's
8642 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8643 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8644 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8645 // we should reset its question interval here to MaxQuestionInterval.
8646 ResetQuestionState(m
, qptr
);
8647 if (DNSSECQuestion(qptr
))
8648 neg
->CRDNSSECQuestion
= 1;
8649 // Update the NSEC records again.
8650 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8653 if (!AddNSECSForCacheRecord(m
, NSECRecords
, neg
, rcode
))
8655 // We might just have an SOA record for zones that are not signed and hence don't log
8657 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
8658 "[R%u->Q%d] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr " PRI_S
" during refresh",
8659 q
.request_id
, mDNSVal16(q
.TargetQID
), CRDisplayString(m
, neg
));
8660 FreeNSECRecords(m
, NSECRecords
);
8661 neg
->CRDNSSECQuestion
= 0;
8663 NSECRecords
= mDNSNULL
;
8668 ReleaseCacheRecord(m
, neg
->soa
);
8669 neg
->soa
= SOARecord
;
8670 SOARecord
= mDNSNULL
;
8676 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl
, name
->c
, DNSTypeName(q
.qtype
));
8677 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, qptr
->qDNSServer
);
8678 m
->rec
.r
.responseFlags
= response
->h
.flags
;
8679 // We create SOA records above which might create new cache groups. Earlier
8680 // in the function we looked up the cache group for the name and it could have
8681 // been NULL. If we pass NULL cg to new cache entries that we create below,
8682 // it will create additional cache groups for the same name. To avoid that,
8683 // look up the cache group again to re-initialize cg again.
8684 cg
= CacheGroupForName(m
, hash
, name
);
8685 if (NSECRecords
&& DNSSECQuestion(qptr
))
8687 // Create the cache entry with delay and then add the NSEC records
8688 // to it and add it immediately.
8689 negcr
= CreateNewCacheEntry(m
, HashSlotFromNameHash(hash
), cg
, 1, mDNStrue
, mDNSNULL
);
8692 negcr
->CRDNSSECQuestion
= 0;
8693 if (!AddNSECSForCacheRecord(m
, NSECRecords
, negcr
, rcode
))
8695 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
8696 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr " PRI_S
,
8697 q
.request_id
, mDNSVal16(q
.TargetQID
), CRDisplayString(m
, negcr
));
8698 FreeNSECRecords(m
, NSECRecords
);
8702 negcr
->CRDNSSECQuestion
= 1;
8703 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8704 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for " PRI_S
,
8705 q
.request_id
, mDNSVal16(q
.TargetQID
), CRDisplayString(m
, negcr
));
8707 NSECRecords
= mDNSNULL
;
8708 negcr
->DelayDelivery
= 0;
8709 CacheRecordDeferredAdd(m
, negcr
);
8711 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8716 // Need to add with a delay so that we can tag the SOA record
8717 negcr
= CreateNewCacheEntry(m
, HashSlotFromNameHash(hash
), cg
, 1, mDNStrue
, mDNSNULL
);
8720 negcr
->CRDNSSECQuestion
= 0;
8721 if (DNSSECQuestion(qptr
))
8722 negcr
->CRDNSSECQuestion
= 1;
8723 negcr
->DelayDelivery
= 0;
8728 ReleaseCacheRecord(m
, negcr
->soa
);
8729 negcr
->soa
= SOARecord
;
8730 SOARecord
= mDNSNULL
;
8732 CacheRecordDeferredAdd(m
, negcr
);
8735 m
->rec
.r
.responseFlags
= zeroID
;
8736 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8739 name
= (const domainname
*)(name
->c
+ 1 + name
->c
[0]);
8740 hash
= DomainNameHashValue(name
);
8748 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used");
8749 FreeNSECRecords(m
, NSECRecords
);
8753 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used");
8754 ReleaseCacheRecord(m
, SOARecord
);
8758 mDNSlocal
void mDNSCorePrintStoredProxyRecords(mDNS
*const m
)
8760 AuthRecord
*rrPtr
= mDNSNULL
;
8761 if (!m
->SPSRRSet
) return;
8762 LogSPS("Stored Proxy records :");
8763 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8765 LogSPS("%s", ARDisplayString(m
, rrPtr
));
8769 mDNSlocal mDNSBool
mDNSCoreRegisteredProxyRecord(mDNS
*const m
, AuthRecord
*rr
)
8771 AuthRecord
*rrPtr
= mDNSNULL
;
8773 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8775 if (IdenticalResourceRecord(&rrPtr
->resrec
, &rr
->resrec
))
8777 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m
, rr
));
8781 mDNSCorePrintStoredProxyRecords(m
);
8785 mDNSexport CacheRecord
* mDNSCoreReceiveCacheCheck(mDNS
*const m
, const DNSMessage
*const response
, uDNS_LLQType LLQType
,
8786 const mDNSu32 slot
, CacheGroup
*cg
, DNSQuestion
*unicastQuestion
, CacheRecord
***cfp
, CacheRecord
**NSECCachePtr
,
8787 mDNSInterfaceID InterfaceID
)
8790 CacheRecord
**cflocal
= *cfp
;
8792 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
8795 // Resource record received via unicast, the resGroupID should match ?
8798 const mDNSu32 id1
= (cr
->resrec
.rDNSServer
? cr
->resrec
.rDNSServer
->resGroupID
: 0);
8799 const mDNSu32 id2
= (m
->rec
.r
.resrec
.rDNSServer
? m
->rec
.r
.resrec
.rDNSServer
->resGroupID
: 0);
8800 match
= (id1
== id2
);
8803 match
= (cr
->resrec
.InterfaceID
== InterfaceID
);
8804 // If we found this exact resource record, refresh its TTL
8805 if (match
&& IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
8807 if (m
->rec
.r
.resrec
.rdlength
> InlineCacheRDSize
)
8808 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8809 m
->rec
.r
.resrec
.rdlength
, InterfaceID
, CRDisplayString(m
, &m
->rec
.r
));
8811 if (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8813 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8814 if (cr
->NextInCFList
== mDNSNULL
&& *cfp
!= &cr
->NextInCFList
&& LLQType
!= uDNS_LLQ_Events
)
8817 cflocal
= &cr
->NextInCFList
;
8818 *cflocal
= (CacheRecord
*)1;
8819 *cfp
= &cr
->NextInCFList
;
8822 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8823 if (!(cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
8826 for (q
= m
->Questions
; q
; q
=q
->next
)
8828 if (CacheRecordAnswersQuestion(cr
, q
))
8831 cr
->resrec
.RecordType
= m
->rec
.r
.resrec
.RecordType
;
8835 if (!SameRDataBody(&m
->rec
.r
.resrec
, &cr
->resrec
.rdata
->u
, SameDomainNameCS
))
8837 // If the rdata of the packet record differs in name capitalization from the record in our cache
8838 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8839 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8840 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8841 cr
->resrec
.rroriginalttl
= 0;
8842 cr
->TimeRcvd
= m
->timenow
;
8843 cr
->UnansweredQueries
= MaxUnansweredQueries
;
8844 SetNextCacheCheckTimeForRecord(m
, cr
);
8845 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S
, CRDisplayString(m
, cr
));
8846 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S
, CRDisplayString(m
, &m
->rec
.r
));
8847 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8848 NextCacheCheckEvent(cr
) - m
->timenow
, slot
, m
->rrcache_nextcheck
[slot
] - m
->timenow
, m
->NextCacheCheck
- m
->timenow
);
8849 // DO NOT break out here -- we want to continue as if we never found it
8851 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0)
8855 m
->mDNSStats
.CacheRefreshed
++;
8857 if (cr
->resrec
.mortality
== Mortality_Ghost
&& unicastQuestion
&& (unicastQuestion
->allowExpired
!= AllowExpired_AllowExpiredAnswers
) && !cr
->DelayDelivery
)
8859 cr
->DelayDelivery
= NonZeroTime(m
->timenow
);
8860 debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m
->timenow
- RRExpireTime(cr
), CRDisplayString(m
, cr
));
8863 if (cr
->resrec
.rroriginalttl
== 0) debugf("uDNS rescuing %s", CRDisplayString(m
, cr
));
8864 RefreshCacheRecord(m
, cr
, m
->rec
.r
.resrec
.rroriginalttl
);
8865 cr
->responseFlags
= response
->h
.flags
;
8867 // If we may have NSEC records returned with the answer (which we don't know yet as it
8868 // has not been processed), we need to cache them along with the first cache
8869 // record in the list that answers the question so that it can be used for validation
8870 // later. The "type" check below is to make sure that we cache on the cache record
8871 // that would answer the question. It is possible that we might cache additional things
8872 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8873 // the record that answers the question.
8874 if (response
->h
.numAnswers
&& unicastQuestion
&& unicastQuestion
->qtype
== cr
->resrec
.rrtype
8875 && !(*NSECCachePtr
))
8877 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S
, CRDisplayString(m
, cr
));
8880 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8881 // polling the network once we get a valid response back. For the first time when a new
8882 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8883 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8884 // configuration changed, without flushing the cache, we reset the question interval here.
8885 // Currently, we do this for for both multicast and unicast questions as long as the record
8886 // type is unique. For unicast, resource record is always unique and for multicast it is
8887 // true for records like A etc. but not for PTR.
8888 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8890 for (q
= m
->Questions
; q
; q
=q
->next
)
8892 if (!q
->DuplicateOf
&& !q
->LongLived
&&
8893 ActiveQuestion(q
) && CacheRecordAnswersQuestion(cr
, q
))
8895 ResetQuestionState(m
, q
);
8896 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
8897 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8905 // If the packet TTL is zero, that means we're deleting this record.
8906 // To give other hosts on the network a chance to protest, we push the deletion
8907 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8908 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8909 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8910 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8911 // If the record is already going to expire in less than one second anyway, we leave it alone --
8912 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8913 debugf("DE for %s", CRDisplayString(m
, cr
));
8914 if (RRExpireTime(cr
) - m
->timenow
> mDNSPlatformOneSecond
)
8916 cr
->resrec
.rroriginalttl
= 1;
8917 cr
->TimeRcvd
= m
->timenow
;
8918 cr
->UnansweredQueries
= MaxUnansweredQueries
;
8919 SetNextCacheCheckTimeForRecord(m
, cr
);
8928 mDNSlocal
void mDNSParseNSEC3Records(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
8929 const mDNSInterfaceID InterfaceID
, CacheRecord
**NSEC3Records
)
8935 if (!response
->h
.numAuthorities
)
8937 ptr
= LocateAuthorities(response
, end
);
8940 LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8943 for (i
= 0; i
< response
->h
.numAuthorities
&& ptr
&& ptr
< end
; i
++)
8947 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8948 if (!ptr
|| m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
|| m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC3
)
8950 debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr
, CRDisplayString(m
, &m
->rec
.r
));
8951 m
->rec
.r
.resrec
.RecordType
= 0;
8954 cg
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
8955 // Create the cache entry but don't add it to the cache it. We need
8956 // to cache this along with the main cache record.
8957 rr
= CreateNewCacheEntry(m
, HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
), cg
, 0, mDNSfalse
, mDNSNULL
);
8960 debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m
, rr
));
8962 NSEC3Records
= &rr
->next
;
8964 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8968 mDNSlocal
void mDNSCoreResetRecord(mDNS
*const m
)
8970 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8973 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8974 // the record list and/or question list.
8975 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8976 // InterfaceID non-NULL tells us the interface this multicast response was received on
8977 // InterfaceID NULL tells us this was a unicast response
8978 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8979 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
8980 const DNSMessage
*const response
, const mDNSu8
*end
,
8981 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8982 const mDNSInterfaceID InterfaceID
)
8985 const mDNSBool ResponseMCast
= dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
);
8986 mDNSBool ResponseSrcLocal
= !srcaddr
|| mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
8987 DNSQuestion
*llqMatch
= mDNSNULL
;
8988 DNSQuestion
*unicastQuestion
= mDNSNULL
;
8989 uDNS_LLQType LLQType
= uDNS_recvLLQResponse(m
, response
, end
, srcaddr
, srcport
, &llqMatch
);
8991 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8992 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8993 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8994 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
8995 CacheRecord
**cfp
= &CacheFlushRecords
;
8996 CacheRecord
*NSECRecords
= mDNSNULL
;
8997 CacheRecord
*NSECCachePtr
= mDNSNULL
;
8998 CacheRecord
**nsecp
= &NSECRecords
;
8999 CacheRecord
*McastNSEC3Records
= mDNSNULL
;
9001 mDNSu8 rcode
= '\0';
9002 mDNSBool rrsigsCreated
= mDNSfalse
;
9003 mDNSBool DNSSECQuestion
= mDNSfalse
;
9004 NetworkInterfaceInfo
*llintf
= FirstIPv4LLInterfaceForID(m
, InterfaceID
);
9005 mDNSBool recordAcceptedInResponse
= mDNSfalse
; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
9007 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
9008 // to guard against spoof responses, then the only credible protection against that is cryptographic
9009 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
9010 int firstauthority
= response
->h
.numAnswers
;
9011 int firstadditional
= firstauthority
+ response
->h
.numAuthorities
;
9012 int totalrecords
= firstadditional
+ response
->h
.numAdditionals
;
9013 const mDNSu8
*ptr
= response
->data
;
9014 DNSServer
*uDNSServer
= mDNSNULL
;
9016 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
9017 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
9018 srcaddr
, dstaddr
, InterfaceID
,
9019 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
9020 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
9021 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
9022 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? " " : "s", end
- response
->data
, LLQType
);
9024 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9025 if (mDNSSameIPPort(srcport
, UnicastDNSPort
))
9027 MetricsUpdateDNSResponseSize((mDNSu32
)(end
- (mDNSu8
*)response
));
9031 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
9032 // When a DNS client receives a reply with TC
9033 // set, it should ignore that response, and query again, using a
9034 // mechanism, such as a TCP connection, that will permit larger replies.
9035 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
9036 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
9037 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
9038 // <rdar://problem/6690034> Can't bind to Active Directory
9039 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
9040 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
9041 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
9042 // and not even do the TCP query.
9043 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
9044 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
9045 // either the authority section or additional section, then that implies that truncation occurred beyond the answer
9046 // section, and the answer section is therefore assumed to be complete.
9048 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
9049 // When a response is so long that truncation is required, the truncation
9050 // should start at the end of the response and work forward in the
9051 // datagram. Thus if there is any data for the authority section, the
9052 // answer section is guaranteed to be unique.
9053 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
) &&
9054 ((response
->h
.numAnswers
== 0) || ((response
->h
.numAuthorities
== 0) && (response
->h
.numAdditionals
== 0)))) return;
9056 if (LLQType
== uDNS_LLQ_Ignore
) return;
9058 // 1. We ignore questions (if any) in mDNS response packets
9059 // 2. If this is an LLQ response, we handle it much the same
9060 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9061 if (ResponseMCast
|| LLQType
== uDNS_LLQ_Events
)
9062 ptr
= LocateAnswers(response
, end
);
9063 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9064 // in this response packet are immediately deemed to be invalid.
9067 mDNSBool failure
, returnEarly
;
9068 rcode
= (mDNSu8
)(response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
9069 failure
= !(rcode
== kDNSFlag1_RC_NoErr
|| rcode
== kDNSFlag1_RC_NXDomain
|| rcode
== kDNSFlag1_RC_NotAuth
);
9070 returnEarly
= mDNSfalse
;
9071 // We could possibly combine this with the similar loop at the end of this function --
9072 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9073 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9074 // which it was received (or refreshed), and then at the end if we find any cache records which
9075 // answer questions in this packet's question section, but which aren't tagged with this packet's
9076 // packet number, then we deduce they are old and delete them
9077 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
9079 DNSQuestion q
, *qptr
= mDNSNULL
, *suspiciousForQ
= mDNSNULL
;
9080 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
9081 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
, &suspiciousForQ
)))
9086 // Remember the unicast question that we found, which we use to make caching
9087 // decisions later on in this function
9088 CacheGroup
*cg
= CacheGroupForName(m
, q
.qnamehash
, &q
.qname
);
9089 if (!mDNSOpaque16IsZero(response
->h
.id
))
9091 unicastQuestion
= qptr
;
9092 if (qptr
->qDNSServer
&& DNSSECQuestion(qptr
))
9094 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9095 "[R%d->Q%d] mDNSCoreReceiveResponse: Setting aware for " PRI_DM_NAME
" (" PUB_S
") on " PRI_IP_ADDR
,
9096 qptr
->request_id
, mDNSVal16(qptr
->TargetQID
), DM_NAME_PARAM(qptr
->qname
.c
),
9097 DNSTypeName(qptr
->qtype
), &qptr
->qDNSServer
->addr
);
9099 qptr
->qDNSServer
->DNSSECAware
= mDNStrue
;
9100 qptr
->qDNSServer
->req_DO
= mDNStrue
;
9102 if (qptr
->ValidatingResponse
)
9103 DNSSECQuestion
= mDNStrue
;
9105 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
9107 if (SameNameCacheRecordAnswersQuestion(cr
, qptr
))
9109 debugf("uDNS marking %p %##s (%s) %p %s", q
.InterfaceID
, q
.qname
.c
, DNSTypeName(q
.qtype
),
9110 cr
->resrec
.InterfaceID
, CRDisplayString(m
, cr
));
9111 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9112 cr
->TimeRcvd
= m
->timenow
- TicksTTL(cr
) - 1;
9113 cr
->UnansweredQueries
= MaxUnansweredQueries
;
9114 cr
->CRDNSSECQuestion
= 0;
9115 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9117 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9118 "[R%d->Q%d] mDNSCoreReceiveResponse: CRDNSSECQuestion set for record " PRI_S
", question " PRI_DM_NAME
" (" PUB_S
")",
9119 unicastQuestion
->request_id
, mDNSVal16(unicastQuestion
->TargetQID
),
9120 CRDisplayString(m
, cr
), DM_NAME_PARAM(unicastQuestion
->qname
.c
),
9121 DNSTypeName(unicastQuestion
->qtype
));
9122 cr
->CRDNSSECQuestion
= 1;
9131 // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
9132 // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
9133 // req_DO to false here, the next retransmission for this question will turn off validation
9134 // and hence retransmit without the EDNS0/DOK option.
9135 if (DNSSECOptionalQuestion(qptr
) && qptr
->qDNSServer
&& !qptr
->qDNSServer
->DNSSECAware
)
9137 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9138 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query " PRI_DM_NAME
" (" PUB_S
"), clear DO flag",
9139 qptr
->request_id
, mDNSVal16(qptr
->TargetQID
), qptr
->qDNSServer
, rcode
,
9140 DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
9141 qptr
->qDNSServer
->req_DO
= mDNSfalse
;
9143 // For Unicast DNS Queries, penalize the DNSServer
9146 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9147 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " PRI_DM_NAME
" (" PUB_S
")",
9148 qptr
->request_id
, mDNSVal16(qptr
->TargetQID
), qptr
->qDNSServer
, rcode
,
9149 DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
9150 PenalizeDNSServer(m
, qptr
, response
->h
.flags
);
9153 returnEarly
= mDNStrue
;
9156 else if (!InterfaceID
&& suspiciousForQ
)
9158 // If a response is suspicious for a question, then reissue the question via TCP
9159 LogInfo("[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded suspiciously to query %##s (%s) qID %d != rID: %d",
9160 suspiciousForQ
->request_id
, mDNSVal16(suspiciousForQ
->TargetQID
),
9161 suspiciousForQ
->qDNSServer
, q
.qname
.c
, DNSTypeName(q
.qtype
),
9162 mDNSVal16(suspiciousForQ
->TargetQID
), mDNSVal16(response
->h
.id
));
9163 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
9164 m
->NextSuspiciousTimeout
= NonZeroTime(m
->timenow
+ (SUSPICIOUS_REPLY_DEFENSE_SECS
* mDNSPlatformOneSecond
));
9166 uDNS_RestartQuestionAsTCP(m
, suspiciousForQ
, srcaddr
, srcport
);
9167 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9168 suspiciousForQ
->metrics
.dnsOverTCPState
= DNSOverTCP_Suspicious
;
9175 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9176 "[Q%d] Ignoring %2d Answer" PUB_S
" %2d Authorit" PUB_S
" %2d Additional" PUB_S
,
9177 mDNSVal16(response
->h
.id
),
9178 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
9179 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
9180 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
9181 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9182 // generate negative cache entries (we want to query the next server)
9185 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9187 BumpDNSSECStats(m
, kStatsActionSet
, kStatsTypeMsgSize
, (end
- response
->data
));
9191 // Parse the NSEC3 records from the Authority section before we process
9192 // the Answer section so that we can cache them along with the proper
9193 // cache records we create.
9194 if (mDNSOpaque16IsZero(response
->h
.id
))
9195 mDNSParseNSEC3Records(m
, response
, end
, InterfaceID
, &McastNSEC3Records
);
9197 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
9199 // All responses sent via LL multicast are acceptable for caching
9200 // All responses received over our outbound TCP connections are acceptable for caching
9201 // We accept all records in a unicast response to a multicast query once we find one that
9202 // answers an active question.
9203 mDNSBool AcceptableResponse
= ResponseMCast
|| !dstaddr
|| LLQType
|| recordAcceptedInResponse
;
9204 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9205 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9207 const mDNSu8 RecordType
=
9208 (i
< firstauthority
) ? (mDNSu8
)kDNSRecordTypePacketAns
:
9209 (i
< firstadditional
) ? (mDNSu8
)kDNSRecordTypePacketAuth
: (mDNSu8
)kDNSRecordTypePacketAdd
;
9210 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &m
->rec
);
9211 if (!ptr
) goto exit
; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9213 if (m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
)
9215 mDNSCoreResetRecord(m
);
9219 // We have already parsed the NSEC3 records and cached them approrpriately for
9220 // multicast responses.
9221 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
== kDNSType_NSEC3
)
9223 mDNSCoreResetRecord(m
);
9226 // Don't want to cache OPT or TSIG pseudo-RRs
9227 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
)
9229 mDNSCoreResetRecord(m
);
9232 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
9234 const rdataOPT
*opt
;
9235 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
9236 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9237 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9238 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
9239 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
9241 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
9242 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
9244 mDNSCoreResetRecord(m
);
9247 // if a CNAME record points to itself, then don't add it to the cache
9248 if ((m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
) && SameDomainName(m
->rec
.r
.resrec
.name
, &m
->rec
.r
.resrec
.rdata
->u
.name
))
9250 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m
->rec
.r
.resrec
.name
->c
);
9251 mDNSCoreResetRecord(m
);
9255 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9256 // In the case of active LLQs, we'll get remove events when the records actually do go away
9257 // In the case of polling LLQs, we assume the record remains valid until the next poll
9258 if (!mDNSOpaque16IsZero(response
->h
.id
))
9259 m
->rec
.r
.resrec
.rroriginalttl
= GetEffectiveTTL(LLQType
, m
->rec
.r
.resrec
.rroriginalttl
);
9261 // If response was not sent via LL multicast,
9262 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9267 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9268 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9269 // queries to get ADD/RMV events. To lookup the question, we can't use
9270 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9271 // has already matched the question using the 64 bit Id in the packet and we use that here.
9273 if (llqMatch
!= mDNSNULL
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= llqMatch
->qDNSServer
;
9275 // If this is a DNSSEC question that is also LongLived, don't accept records from the
9276 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
9277 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
9278 // for both negative responses and wildcard expanded positive responses as both of come
9279 // back with NSEC/NSEC3s.
9280 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9281 AcceptableResponse
= mDNSfalse
;
9283 else if (!AcceptableResponse
|| !dstaddr
)
9285 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9286 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9287 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9290 DNSQuestion
*q
= ExpectingUnicastResponseForRecord(m
, srcaddr
, ResponseSrcLocal
, dstport
, response
->h
.id
, &m
->rec
.r
, !dstaddr
);
9292 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9295 // We could potentially lookup the DNS server based on the source address, but that may not work always
9296 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9297 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9298 // on the "id" and "source port", then this response answers the question and assume the response
9299 // came from the same DNS server that we sent the query to.
9303 AcceptableResponse
= mDNStrue
;
9306 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9307 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= q
->qDNSServer
;
9308 if (!unicastQuestion
) unicastQuestion
= q
; // Acceptable responses to unicast questions need to have (unicastQuestion != nil)
9312 // Accept all remaining records in this unicast response to an mDNS query.
9313 recordAcceptedInResponse
= mDNStrue
;
9314 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9315 "[R%d->Q%d] mDNSCoreReceiveResponse: Accepting response for query: " PRI_DM_NAME
" (" PUB_S
")",
9316 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
9321 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9322 // the question. The code below does that. So, make this record unacceptable for now
9325 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m
->rec
.r
.resrec
.name
->c
);
9326 AcceptableResponse
= mDNSfalse
;
9331 else if (llintf
&& llintf
->IgnoreIPv4LL
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_A
)
9333 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9334 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9335 // To work with these broken routers, client devices need to blacklist these broken
9336 // routers and ignore their bogus ARP responses. Some devices implement a technique
9337 // such as the one described in US Patent 7436783, which lets clients detect and
9338 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9340 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9341 // approach of just detecting these broken routers and completely disabling IPv4
9342 // link-local communication on interfaces where a broken router is detected.
9343 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9344 // that are deemed “safe” for IPv4 link-local communication;
9345 // the flag is cleared on interfaces where a broken router is detected.
9347 // OS X and iOS will not even try to communicate with an IPv4
9348 // link-local destination on an interface without the IFEF_ARPLL flag set.
9349 // This can cause some badly written applications to freeze for a long time if they
9350 // attempt to connect to an IPv4 link-local destination address and then wait for
9351 // that connection attempt to time out before trying other candidate addresses.
9353 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9354 // records on interfaces where we know the OS will be unwilling even to attempt
9355 // communication with those IPv4 link-local destination addresses.
9356 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9358 const CacheRecord
*const rr
= &m
->rec
.r
;
9359 const RDataBody2
*const rdb
= (RDataBody2
*)rr
->smallrdatastorage
.data
;
9360 if (mDNSv4AddressIsLinkLocal(&rdb
->ipv4
))
9362 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m
, &m
->rec
.r
));
9363 mDNSCoreResetRecord(m
);
9368 // 1. Check that this packet resource record does not conflict with any of ours
9369 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC
)
9371 if (m
->CurrentRecord
)
9372 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
9373 m
->CurrentRecord
= m
->ResourceRecords
;
9374 while (m
->CurrentRecord
)
9376 AuthRecord
*rr
= m
->CurrentRecord
;
9377 m
->CurrentRecord
= rr
->next
;
9378 // We accept all multicast responses, and unicast responses resulting from queries we issued
9379 // For other unicast responses, this code accepts them only for responses with an
9380 // (apparently) local source address that pertain to a record of our own that's in probing state
9381 if (!AcceptableResponse
&& !(ResponseSrcLocal
&& rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)) continue;
9383 if (PacketRRMatchesSignature(&m
->rec
.r
, rr
)) // If interface, name, type (if shared record) and class match...
9385 // ... check to see if type and rdata are identical
9386 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
9388 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9389 if (m
->rec
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
9391 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9392 if (rr
->ImmedAnswer
== InterfaceID
) { rr
->ImmedAnswer
= mDNSNULL
; rr
->ImmedUnicast
= mDNSfalse
; }
9396 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
9397 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
9400 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9401 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &m
->rec
.r
))
9403 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)",
9404 m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
), IIDPrintable(InterfaceID
));
9405 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9407 // If this record is marked DependentOn another record for conflict detection purposes,
9408 // then *that* record has to be bumped back to probing state to resolve the conflict
9409 if (rr
->DependentOn
)
9411 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
9412 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9415 // If we've just whacked this record's ProbeCount, don't need to do it again
9416 if (rr
->ProbeCount
> DefaultProbeCountForTypeUnique
)
9417 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m
, rr
));
9418 else if (rr
->ProbeCount
== DefaultProbeCountForTypeUnique
)
9419 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m
, rr
));
9422 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr
, mDNSVal16(srcport
), CRDisplayString(m
, &m
->rec
.r
));
9423 // If we'd previously verified this record, put it back to probing state and try again
9424 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
9426 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m
, rr
));
9427 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
9428 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9429 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9430 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9431 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9432 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
9433 rr
->AnnounceCount
= InitialAnnounceCount
;
9434 InitializeLastAPTime(m
, rr
);
9435 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
9437 // If we're probing for this record, we just failed
9438 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
9440 // At this point in the code, we're probing for uniqueness.
9441 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9442 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9443 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9444 if (!mDNSCoreRegisteredProxyRecord(m
, rr
))
9446 if ((rr
->ProbingConflictCount
== 0) || (m
->MPktNum
!= rr
->LastConflictPktNum
))
9448 const NetworkInterfaceInfo
*const intf
= FirstInterfaceForID(m
, InterfaceID
);
9449 rr
->ProbingConflictCount
++;
9450 rr
->LastConflictPktNum
= m
->MPktNum
;
9451 if (ResponseMCast
&& (!intf
|| intf
->SupportsUnicastMDNSResponse
) &&
9452 (rr
->ProbingConflictCount
<= kMaxAllowedMCastProbingConflicts
))
9454 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; restarting probing after %d-tick pause due to possibly "
9455 "spurious multicast conflict (%d/%d) via interface %d for %s",
9456 rr
->ProbeCount
, kProbingConflictPauseDuration
, rr
->ProbingConflictCount
,
9457 kMaxAllowedMCastProbingConflicts
, IIDPrintable(InterfaceID
), ARDisplayString(m
, rr
));
9458 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
9459 rr
->LastAPTime
= m
->timenow
+ kProbingConflictPauseDuration
- rr
->ThisAPInterval
;
9460 SetNextAnnounceProbeTime(m
, rr
);
9464 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s due to %scast conflict via interface %d",
9465 rr
->ProbeCount
, ARDisplayString(m
, rr
), ResponseMCast
? "multi" : "uni", IIDPrintable(InterfaceID
));
9466 m
->mDNSStats
.NameConflicts
++;
9467 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9468 // See if this record was also registered with any D2D plugins.
9469 D2D_stop_advertising_record(rr
);
9471 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9476 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9477 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9478 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9479 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9480 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9481 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
9483 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m
, rr
));
9484 m
->mDNSStats
.KnownUniqueNameConflicts
++;
9485 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9486 D2D_stop_advertising_record(rr
);
9488 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9491 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
9494 // Else, matching signature, different type or rdata, but not a considered a conflict.
9495 // If the packet record has the cache-flush bit set, then we check to see if we
9496 // have any record(s) of the same type that we should re-assert to rescue them
9497 // (see note about "multi-homing and bridged networks" at the end of this function).
9498 else if (m
->rec
.r
.resrec
.rrtype
== rr
->resrec
.rrtype
)
9499 if ((m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (mDNSu32
)(m
->timenow
- rr
->LastMCTime
) > (mDNSu32
)mDNSPlatformOneSecond
/2)
9500 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
9505 nseclist
= mDNSfalse
;
9506 if (!AcceptableResponse
)
9508 AcceptableResponse
= IsResponseAcceptable(m
, CacheFlushRecords
, unicastQuestion
, &nseclist
);
9509 if (AcceptableResponse
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
;
9512 // 2. See if we want to add this packet resource record to our cache
9513 // We only try to cache answers if we have a cache to put them in
9514 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9515 if (!AcceptableResponse
) {
9516 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[Q%d] mDNSCoreReceiveResponse ignoring " PRI_S
,
9517 mDNSVal16(response
->h
.id
), CRDisplayString(m
, &m
->rec
.r
));
9519 if (m
->rrcache_size
&& AcceptableResponse
)
9521 const mDNSu32 slot
= HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
);
9522 CacheGroup
*cg
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
9523 CacheRecord
*rr
= mDNSNULL
;
9525 // 2a. Check if this packet resource record is already in our cache.
9527 // If this record should go in the nseclist, don't look in the cache for updating it.
9528 // They are supposed to be cached under the "nsec" field of the cache record for
9529 // validation. Just create the cache record.
9532 rr
= mDNSCoreReceiveCacheCheck(m
, response
, LLQType
, slot
, cg
, unicastQuestion
, &cfp
, &NSECCachePtr
, InterfaceID
);
9535 // If packet resource record not in our cache, add it now
9536 // (unless it is just a deletion of a record we never had, in which case we don't care)
9537 if (!rr
&& m
->rec
.r
.resrec
.rroriginalttl
> 0)
9539 const mDNSBool AddToCFList
= (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (LLQType
!= uDNS_LLQ_Events
);
9543 delay
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
9545 delay
= CheckForSoonToExpireRecords(m
, m
->rec
.r
.resrec
.name
, m
->rec
.r
.resrec
.namehash
);
9547 // If unique, assume we may have to delay delivery of this 'add' event.
9548 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9549 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9550 // to schedule an mDNS_Execute task at the appropriate time.
9551 rr
= CreateNewCacheEntry(m
, slot
, cg
, delay
, !nseclist
, srcaddr
);
9554 rr
->responseFlags
= response
->h
.flags
;
9555 // If we are not creating signatures, then we need to inform DNSSEC so that
9556 // it does not wait forever. Don't do this if we got NSEC records
9557 // as it indicates that this name does not exist.
9558 if (rr
->resrec
.rrtype
== kDNSType_RRSIG
&& !nseclist
)
9560 rrsigsCreated
= mDNStrue
;
9562 // Remember whether we created a cache record in response to a DNSSEC question.
9563 // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9564 rr
->CRDNSSECQuestion
= 0;
9565 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9567 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9568 "[R%d->Q%d] mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record " PRI_S
", question " PRI_DM_NAME
" (" PUB_S
")",
9569 unicastQuestion
->request_id
, mDNSVal16(unicastQuestion
->TargetQID
), CRDisplayString(m
, rr
),
9570 DM_NAME_PARAM(unicastQuestion
->qname
.c
), DNSTypeName(unicastQuestion
->qtype
));
9571 rr
->CRDNSSECQuestion
= 1;
9573 // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9574 // which we should be creating below. It is also needed in the wildcard
9575 // expanded answer case and in that case it is cached along with the answer.
9578 rr
->TimeRcvd
= m
->timenow
;
9582 else if (AddToCFList
)
9585 cfp
= &rr
->NextInCFList
;
9586 *cfp
= (CacheRecord
*)1;
9588 else if (rr
->DelayDelivery
)
9590 ScheduleNextCacheCheckTime(m
, slot
, rr
->DelayDelivery
);
9595 mDNSCoreResetRecord(m
);
9599 mDNSCoreResetRecord(m
);
9601 // If we've just received one or more records with their cache flush bits set,
9602 // then scan that cache slot to see if there are any old stale records we need to flush
9603 while (CacheFlushRecords
!= (CacheRecord
*)1)
9605 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
9606 const mDNSu32 slot
= HashSlotFromNameHash(r1
->resrec
.namehash
);
9607 const CacheGroup
*cg
= CacheGroupForRecord(m
, &r1
->resrec
);
9608 mDNSBool purgedRecords
= mDNSfalse
;
9609 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
9610 r1
->NextInCFList
= mDNSNULL
;
9612 // Look for records in the cache with the same signature as this new one with the cache flush
9613 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9614 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9615 // We make these TTL adjustments *only* for records that still have *more* than one second
9616 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9617 // (and now has half a second remaining) could inadvertently get its life extended, by either
9618 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9619 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9620 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9621 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9622 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9623 // To avoid this, we need to ensure that the cache flushing operation will only act to
9624 // *decrease* a record's remaining lifetime, never *increase* it.
9625 for (r2
= cg
? cg
->members
: mDNSNULL
; r2
; r2
=r2
->next
)
9629 if (!r1
->resrec
.InterfaceID
)
9631 id1
= (r1
->resrec
.rDNSServer
? r1
->resrec
.rDNSServer
->resGroupID
: 0);
9632 id2
= (r2
->resrec
.rDNSServer
? r2
->resrec
.rDNSServer
->resGroupID
: 0);
9638 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9639 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9640 // the new RRSIG that we received. Process only if the typeCovered matches.
9641 if ((r1
->resrec
.rrtype
== r2
->resrec
.rrtype
) && (r1
->resrec
.rrtype
== kDNSType_RRSIG
))
9643 rdataRRSig
*rrsig1
= (rdataRRSig
*)(((RDataBody2
*)(r1
->resrec
.rdata
->u
.data
))->data
);
9644 rdataRRSig
*rrsig2
= (rdataRRSig
*)(((RDataBody2
*)(r2
->resrec
.rdata
->u
.data
))->data
);
9645 if (swap16(rrsig1
->typeCovered
) != swap16(rrsig2
->typeCovered
))
9647 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9648 DNSTypeName(swap16(rrsig1
->typeCovered
)), DNSTypeName(swap16(rrsig2
->typeCovered
)));
9653 // For Unicast (null InterfaceID) the resolver IDs should also match
9654 if ((r1
->resrec
.InterfaceID
== r2
->resrec
.InterfaceID
) &&
9655 (r1
->resrec
.InterfaceID
|| (id1
== id2
)) &&
9656 r1
->resrec
.rrtype
== r2
->resrec
.rrtype
&&
9657 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
)
9659 if (r1
->resrec
.mortality
== Mortality_Mortal
&& r2
->resrec
.mortality
!= Mortality_Mortal
)
9661 verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1
, r2
);
9662 r1
->resrec
.mortality
= Mortality_Immortal
; // Immortalize the replacement record
9665 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9666 // else, if record is old, mark it to be flushed
9667 if (m
->timenow
- r2
->TimeRcvd
< mDNSPlatformOneSecond
&& RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9669 // If we find mismatched TTLs in an RRSet, correct them.
9670 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9671 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9672 // which we treat as a goodbye followed by an addition) and in that case it would be
9673 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9675 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9676 // because certain early Bonjour devices are known to have this specific mismatch, and
9677 // there's no point filling syslog with messages about something we already know about.
9678 // We also don't log this for uDNS responses, since a caching name server is obliged
9679 // to give us an aged TTL to correct for how long it has held the record,
9680 // so our received TTLs are expected to vary in that case
9682 // We also suppress log message in the case of SRV records that are received
9683 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9684 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9686 if (r2
->resrec
.rroriginalttl
!= r1
->resrec
.rroriginalttl
&& r1
->resrec
.rroriginalttl
> 1)
9688 if (!(r2
->resrec
.rroriginalttl
== 240 && r1
->resrec
.rroriginalttl
== 60 && r2
->resrec
.rrtype
== kDNSType_TXT
) &&
9689 !(r2
->resrec
.rroriginalttl
== 120 && r1
->resrec
.rroriginalttl
== 4500 && r2
->resrec
.rrtype
== kDNSType_SRV
) &&
9690 mDNSOpaque16IsZero(response
->h
.id
))
9691 LogInfo("Correcting TTL from %4d to %4d for %s",
9692 r2
->resrec
.rroriginalttl
, r1
->resrec
.rroriginalttl
, CRDisplayString(m
, r2
));
9693 r2
->resrec
.rroriginalttl
= r1
->resrec
.rroriginalttl
;
9695 r2
->TimeRcvd
= m
->timenow
;
9696 SetNextCacheCheckTimeForRecord(m
, r2
);
9698 else if (r2
->resrec
.InterfaceID
) // else, if record is old, mark it to be flushed
9700 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1
, m
->timenow
- r1
->TimeRcvd
, RRExpireTime(r1
) - m
->timenow
, CRDisplayString(m
, r1
));
9701 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2
, m
->timenow
- r2
->TimeRcvd
, RRExpireTime(r2
) - m
->timenow
, CRDisplayString(m
, r2
));
9702 // We set stale records to expire in one second.
9703 // This gives the owner a chance to rescue it if necessary.
9704 // This is important in the case of multi-homing and bridged networks:
9705 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9706 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9707 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9708 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9709 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9710 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9712 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9713 // final expiration queries for this record.
9715 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9716 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9717 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9718 // <rdar://problem/5636422> Updating TXT records is too slow
9719 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9720 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9721 if (r2
->TimeRcvd
== m
->timenow
&& r2
->resrec
.rroriginalttl
== 1 && r2
->UnansweredQueries
== MaxUnansweredQueries
)
9723 LogInfo("Cache flush for DE record %s", CRDisplayString(m
, r2
));
9724 r2
->resrec
.rroriginalttl
= 0;
9726 else if (RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9728 // We only set a record to expire in one second if it currently has *more* than a second to live
9729 // If it's already due to expire in a second or less, we just leave it alone
9730 r2
->resrec
.rroriginalttl
= 1;
9731 r2
->UnansweredQueries
= MaxUnansweredQueries
;
9732 r2
->TimeRcvd
= m
->timenow
- 1;
9733 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9734 // that we marked for deletion via an explicit DE record
9736 SetNextCacheCheckTimeForRecord(m
, r2
);
9740 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9741 if (r2
->resrec
.mortality
== Mortality_Ghost
)
9744 for (q
= m
->Questions
; q
; q
=q
->next
)
9746 if (!q
->LongLived
&& ActiveQuestion(q
) &&
9747 CacheRecordAnswersQuestion(r2
, q
) &&
9748 q
->metrics
.expiredAnswerState
== ExpiredAnswer_AnsweredWithExpired
)
9750 q
->metrics
.expiredAnswerState
= ExpiredAnswer_ExpiredAnswerChanged
;
9755 // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9756 r2
->resrec
.mortality
= Mortality_Mortal
; // We want it purged, so remove any immortality
9757 mDNS_PurgeCacheResourceRecord(m
, r2
);
9758 purgedRecords
= mDNStrue
;
9763 if (r1
->DelayDelivery
) // If we were planning to delay delivery of this record, see if we still need to
9765 // If we had a unicast question for this response with at least one positive answer and we
9766 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9767 // signatures along with the cache record which will be used for validation later. If
9768 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9769 // use that instead.
9770 if (response
->h
.numAnswers
&& unicastQuestion
&& NSECRecords
)
9774 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9775 "[R%d->Q%d] mDNSCoreReceiveResponse: Updating NSECCachePtr to " PRI_S
,
9776 unicastQuestion
->request_id
, mDNSVal16(unicastQuestion
->TargetQID
), CRDisplayString(m
, r1
));
9779 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9780 // might start the verification process which needs these NSEC records
9781 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
9783 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
9784 FreeNSECRecords(m
, NSECRecords
);
9786 NSECRecords
= mDNSNULL
;
9787 NSECCachePtr
= mDNSNULL
;
9789 if (r1
->resrec
.InterfaceID
)
9791 r1
->DelayDelivery
= CheckForSoonToExpireRecords(m
, r1
->resrec
.name
, r1
->resrec
.namehash
);
9795 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9796 // them to be deleted before any ADD events for this record.
9797 r1
->DelayDelivery
= purgedRecords
? NonZeroTime(m
->timenow
) : 0;
9799 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9800 if (!r1
->DelayDelivery
) CacheRecordDeferredAdd(m
, r1
);
9801 else ScheduleNextCacheCheckTime(m
, slot
, r1
->DelayDelivery
);
9805 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9806 // update them now for future validations.
9807 if (NSECRecords
&& NSECCachePtr
)
9809 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m
, NSECCachePtr
));
9810 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
9812 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
9813 FreeNSECRecords(m
, NSECRecords
);
9815 NSECRecords
= mDNSNULL
;
9816 NSECCachePtr
= mDNSNULL
;
9819 // If there is at least one answer and we did not create RRSIGs and there was a
9820 // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9821 // were created. We don't need to give a hint:
9823 // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9824 // generate a negative response
9826 // - if we have NSECRecords, it means we might have a potential proof for
9827 // non-existence of name that we are looking for
9829 if (response
->h
.numAnswers
&& !rrsigsCreated
&& DNSSECQuestion
&& !NSECRecords
)
9830 mDNSCoreReceiveNoDNSSECAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
);
9832 // See if we need to generate negative cache entries for unanswered unicast questions
9833 mDNSCoreReceiveNoUnicastAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
, LLQType
, rcode
, NSECRecords
);
9835 if (McastNSEC3Records
)
9837 debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9838 FreeNSECRecords(m
, McastNSEC3Records
);
9842 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9843 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9844 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9845 // that warrants waking the sleeping host.
9846 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9848 mDNSlocal
void ScheduleWakeupForList(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
, AuthRecord
*const thelist
)
9850 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9851 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9852 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9853 // simple, we use the same mechanism for both lists.
9856 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9859 m
->CurrentRecord
= thelist
;
9860 while (m
->CurrentRecord
)
9862 AuthRecord
*const rr
= m
->CurrentRecord
;
9863 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& mDNSSameEthAddress(&rr
->WakeUp
.HMAC
, e
))
9865 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m
, rr
));
9866 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
9868 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
9869 m
->CurrentRecord
= rr
->next
;
9873 mDNSlocal
void ScheduleWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
)
9875 if (!e
->l
[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9876 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->DuplicateRecords
);
9877 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->ResourceRecords
);
9880 mDNSlocal
void SPSRecordCallback(mDNS
*const m
, AuthRecord
*const ar
, mStatus result
)
9882 if (result
&& result
!= mStatus_MemFree
)
9883 LogInfo("SPS Callback %d %s", result
, ARDisplayString(m
, ar
));
9885 if (result
== mStatus_NameConflict
)
9888 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), &ar
->WakeUp
.HMAC
, ARDisplayString(m
, ar
));
9889 if (ar
->WakeUp
.HMAC
.l
[0])
9891 SendWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.IMAC
, &ar
->WakeUp
.password
, mDNSfalse
); // Send one wakeup magic packet
9892 ScheduleWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.HMAC
); // Schedule all other records with the same owner to be woken
9897 if (result
== mStatus_NameConflict
|| result
== mStatus_MemFree
)
9900 mDNSPlatformMemFree(ar
);
9901 mDNS_UpdateAllowSleep(m
);
9905 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
)
9912 for (i
= 0; ptr
< limit
&& *ptr
!= ' ' && i
< 17; i
++, ptr
++)
9914 hval
= HexVal(*ptr
);
9920 else if (*ptr
== ':')
9924 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons
, val
);
9927 eth
->b
[colons
] = val
;
9934 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons
);
9937 eth
->b
[colons
] = val
;
9941 mDNSlocal mDNSu8
*GetValueForIPv6Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv6Addr
*v6
)
9946 int digitsProcessed
;
9951 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9952 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9954 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9955 // the result in "v6"
9957 numColons
= numBytes
= value
= digitsProcessed
= zeroFillStart
= 0;
9958 while (ptr
< limit
&& *ptr
!= ' ')
9960 hval
= HexVal(*ptr
);
9965 digitsProcessed
= 1;
9967 else if (*ptr
== ':')
9969 if (!digitsProcessed
)
9971 // If we have already seen a "::", we should not see one more. Handle the special
9975 // if we never filled any bytes and the next character is space (we have reached the end)
9977 if (!numBytes
&& (ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
9979 mDNSPlatformMemZero(v6
->b
, 16);
9982 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart
);
9986 // We processed "::". We need to fill zeroes later. For now, mark the
9987 // point where we will start filling zeroes from.
9988 zeroFillStart
= numBytes
;
9991 else if ((ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
9993 // We have a trailing ":" i.e., no more characters after ":"
9994 LogMsg("GetValueForIPv6Addr: Trailing colon");
9999 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
10000 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
10001 // filled here is 12 and 13.
10002 if (numBytes
> 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes
); return mDNSNULL
; }
10004 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
10005 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
10006 digitsProcessed
= value
= 0;
10008 // Make sure that we did not fill the 13th and 14th byte above
10009 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes
); return mDNSNULL
; }
10015 // We should be processing the last set of bytes following the last ":" here
10016 if (!digitsProcessed
)
10018 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes
);
10022 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes
); return mDNSNULL
; }
10023 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
10024 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
10029 for (i
= 0; i
< zeroFillStart
; i
++)
10030 v6
->b
[i
] = v6addr
[i
];
10031 for (j
= i
, n
= 0; n
< 16 - numBytes
; j
++, n
++)
10033 for (; j
< 16; i
++, j
++)
10034 v6
->b
[j
] = v6addr
[i
];
10036 else if (numBytes
== 16)
10037 mDNSPlatformMemCopy(v6
->b
, v6addr
, 16);
10040 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes
);
10046 mDNSlocal mDNSu8
*GetValueForIPv4Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv4Addr
*v4
)
10052 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
10054 if (*ptr
>= '0' && *ptr
<= '9')
10055 val
= val
* 10 + *ptr
- '0';
10056 else if (*ptr
== '.')
10058 if (val
> 255 || dots
>= 3)
10060 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
);
10063 v4
->b
[dots
++] = val
;
10068 // We have a zero at the end and if we reached that, then we are done.
10069 if (*ptr
== 0 && ptr
== limit
- 1 && dots
== 3)
10074 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
); return mDNSNULL
; }
10077 if (dots
!= 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots
); return mDNSNULL
; }
10082 mDNSlocal mDNSu8
*GetValueForKeepalive(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSu32
*value
)
10087 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
10089 if (*ptr
< '0' || *ptr
> '9')
10091 // We have a zero at the end and if we reached that, then we are done.
10092 if (*ptr
== 0 && ptr
== limit
- 1)
10097 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr
, ptr
, limit
, *(ptr
+ 1)); return mDNSNULL
; }
10099 val
= val
* 10 + *ptr
- '0';
10105 mDNSexport mDNSBool
mDNSValidKeepAliveRecord(AuthRecord
*rr
)
10107 mDNSAddr laddr
, raddr
;
10109 mDNSIPPort lport
, rport
;
10110 mDNSu32 timeout
, seq
, ack
;
10113 if (!mDNS_KeepaliveRecord(&rr
->resrec
))
10118 timeout
= seq
= ack
= 0;
10120 laddr
= raddr
= zeroAddr
;
10121 lport
= rport
= zeroIPPort
;
10124 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10126 if (mDNSAddressIsZero(&laddr
) || mDNSIPPortIsZero(lport
) ||
10127 mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(rport
) ||
10128 mDNSEthAddressIsZero(eth
))
10137 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
, mDNSu32
*seq
,
10138 mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
)
10140 if (ar
->resrec
.rrtype
!= kDNSType_NULL
)
10143 if (mDNS_KeepaliveRecord(&ar
->resrec
))
10145 int len
= ar
->resrec
.rdlength
;
10146 mDNSu8
*ptr
= &ar
->resrec
.rdata
->u
.txt
.c
[1];
10147 mDNSu8
*limit
= ptr
+ len
- 1; // Exclude the first byte that is the length
10150 while (ptr
< limit
)
10152 mDNSu8 param
= *ptr
;
10153 ptr
+= 2; // Skip the letter and the "="
10156 laddr
->type
= mDNSAddrType_IPv4
;
10157 ptr
= GetValueForIPv4Addr(ptr
, limit
, &laddr
->ip
.v4
);
10159 else if (param
== 'd')
10161 raddr
->type
= mDNSAddrType_IPv4
;
10162 ptr
= GetValueForIPv4Addr(ptr
, limit
, &raddr
->ip
.v4
);
10164 else if (param
== 'H')
10166 laddr
->type
= mDNSAddrType_IPv6
;
10167 ptr
= GetValueForIPv6Addr(ptr
, limit
, &laddr
->ip
.v6
);
10169 else if (param
== 'D')
10171 raddr
->type
= mDNSAddrType_IPv6
;
10172 ptr
= GetValueForIPv6Addr(ptr
, limit
, &raddr
->ip
.v6
);
10174 else if (param
== 'm')
10176 ptr
= GetValueForMACAddr(ptr
, limit
, eth
);
10180 ptr
= GetValueForKeepalive(ptr
, limit
, &value
);
10182 if (!ptr
) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10184 // Extract everything in network order so that it is easy for sending a keepalive and also
10185 // for matching incoming TCP packets
10190 //if (*timeout < 120) *timeout = 120;
10201 lport
->NotAnInteger
= swap16((mDNSu16
)value
);
10204 rport
->NotAnInteger
= swap16((mDNSu16
)value
);
10207 *seq
= swap32(value
);
10210 *ack
= swap32(value
);
10213 *win
= swap16((mDNSu16
)value
);
10216 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param
);
10220 ptr
++; // skip the space
10225 // Matches the proxied auth records to the incoming TCP packet and returns the match and its sequence and ack in "rseq" and "rack" so that
10226 // the clients need not retrieve this information from the auth record again.
10227 mDNSlocal AuthRecord
* mDNS_MatchKeepaliveInfo(mDNS
*const m
, const mDNSAddr
* pladdr
, const mDNSAddr
* praddr
, const mDNSIPPort plport
,
10228 const mDNSIPPort prport
, mDNSu32
*rseq
, mDNSu32
*rack
)
10231 mDNSAddr laddr
, raddr
;
10233 mDNSIPPort lport
, rport
;
10234 mDNSu32 timeout
, seq
, ack
;
10237 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10239 timeout
= seq
= ack
= 0;
10241 laddr
= raddr
= zeroAddr
;
10242 lport
= rport
= zeroIPPort
;
10244 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10246 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10248 // Did we parse correctly ?
10249 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10251 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10255 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10256 &laddr
, pladdr
, &raddr
, praddr
, mDNSVal16(lport
), mDNSVal16(plport
), mDNSVal16(rport
), mDNSVal16(prport
));
10258 // Does it match the incoming TCP packet ?
10259 if (mDNSSameAddress(&laddr
, pladdr
) && mDNSSameAddress(&raddr
, praddr
) && mDNSSameIPPort(lport
, plport
) && mDNSSameIPPort(rport
, prport
))
10261 // returning in network order
10270 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
)
10274 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10276 mDNSu32 timeout
, seq
, ack
;
10278 mDNSAddr laddr
, raddr
;
10280 mDNSIPPort lport
, rport
;
10282 timeout
= seq
= ack
= 0;
10285 laddr
= raddr
= zeroAddr
;
10286 lport
= rport
= zeroIPPort
;
10288 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10290 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10292 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10294 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10297 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10299 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10300 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10301 if (!ar
->KATimeExpire
|| (m
->timenow
- ar
->KATimeExpire
>= 0))
10303 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10304 ar
->KATimeExpire
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
10306 if (m
->NextScheduledKA
- ar
->KATimeExpire
> 0)
10307 m
->NextScheduledKA
= ar
->KATimeExpire
;
10311 mDNSlocal
void mDNS_SendKeepaliveACK(mDNS
*const m
, AuthRecord
*ar
)
10313 mDNSu32 timeout
, seq
, ack
, seqInc
;
10315 mDNSAddr laddr
, raddr
;
10317 mDNSIPPort lport
, rport
;
10320 if (ar
== mDNSNULL
)
10322 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10326 timeout
= seq
= ack
= 0;
10329 laddr
= raddr
= zeroAddr
;
10330 lport
= rport
= zeroIPPort
;
10332 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10334 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10336 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10340 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10341 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10342 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10343 // it's converted to host byte order before incrementing it by one.
10344 ptr
= (mDNSu8
*)&seq
;
10345 seqInc
= (mDNSu32
)((ptr
[0] << 24) | (ptr
[1] << 16) | (ptr
[2] << 8) | ptr
[3]) + 1;
10346 ptr
[0] = (mDNSu8
)((seqInc
>> 24) & 0xFF);
10347 ptr
[1] = (mDNSu8
)((seqInc
>> 16) & 0xFF);
10348 ptr
[2] = (mDNSu8
)((seqInc
>> 8) & 0xFF);
10349 ptr
[3] = (mDNSu8
)((seqInc
) & 0xFF);
10350 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10351 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10354 mDNSlocal
void mDNSCoreReceiveUpdate(mDNS
*const m
,
10355 const DNSMessage
*const msg
, const mDNSu8
*end
,
10356 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
10357 const mDNSInterfaceID InterfaceID
)
10361 mDNSu8
*p
= m
->omsg
.data
;
10362 OwnerOptData owner
= zeroOwner
; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10363 mDNSu32 updatelease
= 0;
10366 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10367 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10368 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
10369 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
10370 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
10371 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
10372 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
10374 if (!InterfaceID
|| !m
->SPSSocket
|| !mDNSSameIPPort(dstport
, m
->SPSSocket
->port
)) return;
10376 if (mDNS_PacketLoggingEnabled
)
10377 DumpPacket(mStatus_NoError
, mDNSfalse
, "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
, InterfaceID
);
10379 ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
+ DNSOpt_OwnerData_ID_Space
);
10382 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
10383 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
10386 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
10387 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
10389 if (o
->opt
== kDNSOpt_Lease
) updatelease
= o
->u
.updatelease
;
10390 else if (o
->opt
== kDNSOpt_Owner
&& o
->u
.owner
.vers
== 0) owner
= o
->u
.owner
;
10393 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10396 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, UpdateRespFlags
);
10398 if (!updatelease
|| !owner
.HMAC
.l
[0])
10400 static int msgs
= 0;
10404 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr
, mDNSVal16(srcport
),
10405 !updatelease
? " No lease" : "", !owner
.HMAC
.l
[0] ? " No owner" : "");
10407 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_FormErr
;
10409 else if (m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
> MAX_PROXY_RECORDS
)
10411 static int msgs
= 0;
10415 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr
, mDNSVal16(srcport
),
10416 m
->ProxyRecords
, msg
->h
.mDNS_numUpdates
, m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
, MAX_PROXY_RECORDS
);
10418 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10422 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
10424 if (updatelease
> 24 * 60 * 60)
10425 updatelease
= 24 * 60 * 60;
10427 if (updatelease
> 0x40000000UL
/ mDNSPlatformOneSecond
)
10428 updatelease
= 0x40000000UL
/ mDNSPlatformOneSecond
;
10430 ptr
= LocateAuthorities(msg
, end
);
10432 // Clear any stale TCP keepalive records that may exist
10433 ClearKeepaliveProxyRecords(m
, &owner
, m
->DuplicateRecords
, InterfaceID
);
10434 ClearKeepaliveProxyRecords(m
, &owner
, m
->ResourceRecords
, InterfaceID
);
10436 for (i
= 0; i
< msg
->h
.mDNS_numUpdates
&& ptr
&& ptr
< end
; i
++)
10438 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
10439 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
10441 mDNSu16 RDLengthMem
= GetRDLengthMem(&m
->rec
.r
.resrec
);
10442 AuthRecord
*ar
= (AuthRecord
*) mDNSPlatformMemAllocateClear(sizeof(AuthRecord
) - sizeof(RDataBody
) + RDLengthMem
);
10445 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10450 mDNSu8 RecordType
= m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
? kDNSRecordTypeUnique
: kDNSRecordTypeShared
;
10451 m
->rec
.r
.resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
;
10452 // All stale keepalive records have been flushed prior to this loop.
10453 if (!mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
10455 ClearIdenticalProxyRecords(m
, &owner
, m
->DuplicateRecords
); // Make sure we don't have any old stale duplicates of this record
10456 ClearIdenticalProxyRecords(m
, &owner
, m
->ResourceRecords
);
10458 mDNS_SetupResourceRecord(ar
, mDNSNULL
, InterfaceID
, m
->rec
.r
.resrec
.rrtype
, m
->rec
.r
.resrec
.rroriginalttl
, RecordType
, AuthRecordAny
, SPSRecordCallback
, ar
);
10459 AssignDomainName(&ar
->namestorage
, m
->rec
.r
.resrec
.name
);
10460 ar
->resrec
.rdlength
= GetRDLength(&m
->rec
.r
.resrec
, mDNSfalse
);
10461 ar
->resrec
.rdata
->MaxRDLength
= RDLengthMem
;
10462 mDNSPlatformMemCopy(ar
->resrec
.rdata
->u
.data
, m
->rec
.r
.resrec
.rdata
->u
.data
, RDLengthMem
);
10463 ar
->ForceMCast
= mDNStrue
;
10464 ar
->WakeUp
= owner
;
10465 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_PTR
)
10467 mDNSs32 t
= ReverseMapDomainType(m
->rec
.r
.resrec
.name
);
10468 if (t
== mDNSAddrType_IPv4
) GetIPv4FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10469 else if (t
== mDNSAddrType_IPv6
) GetIPv6FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10470 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t
, ar
->AddressProxy
.type
, &ar
->AddressProxy
, ARDisplayString(m
, ar
));
10471 if (ar
->AddressProxy
.type
) SetSPSProxyListChanged(InterfaceID
);
10473 ar
->TimeRcvd
= m
->timenow
;
10474 ar
->TimeExpire
= m
->timenow
+ updatelease
* mDNSPlatformOneSecond
;
10475 if (m
->NextScheduledSPS
- ar
->TimeExpire
> 0)
10476 m
->NextScheduledSPS
= ar
->TimeExpire
;
10477 ar
->KATimeExpire
= 0;
10478 mDNS_Register_internal(m
, ar
);
10481 mDNS_UpdateAllowSleep(m
);
10482 LogSPS("SPS Registered %4d %X %s", m
->ProxyRecords
, RecordType
, ARDisplayString(m
,ar
));
10485 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10488 if (m
->omsg
.h
.flags
.b
[1] & kDNSFlag1_RC_Mask
)
10490 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr
, mDNSVal16(srcport
));
10491 ClearProxyRecords(m
, &owner
, m
->DuplicateRecords
);
10492 ClearProxyRecords(m
, &owner
, m
->ResourceRecords
);
10496 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10497 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10498 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
10499 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10500 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
10501 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= updatelease
;
10502 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
10506 if (p
) mDNSSendDNSMessage(m
, &m
->omsg
, p
, InterfaceID
, mDNSNULL
, m
->SPSSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSfalse
);
10507 mDNS_SendKeepalives(m
);
10510 mDNSlocal mDNSu32
mDNSGenerateOwnerOptForInterface(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, DNSMessage
*msg
)
10512 mDNSu8
*ptr
= msg
->data
;
10513 mDNSu8
*end
= mDNSNULL
;
10514 mDNSu32 length
= 0;
10516 NetworkInterfaceInfo
*intf
;
10518 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10519 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10520 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
10521 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10523 intf
= FirstInterfaceForID(m
, InterfaceID
);
10524 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
10526 LogSPS("Generated OPT record : %s", ARDisplayString(m
, &opt
));
10527 end
= PutResourceRecord(msg
, ptr
, &msg
->h
.numAdditionals
, &opt
.resrec
);
10528 if (end
!= mDNSNULL
)
10530 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10531 SwapDNSHeaderBytes(msg
);
10532 length
= (end
- msg
->data
);
10535 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10540 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10541 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10542 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10543 // Really, both should be unified and handled in one place.
10544 mDNSlocal
void mDNSCoreReceiveUpdateR(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
)
10548 mDNSu32 pktlease
= 0, spsupdates
= 0;
10549 const mDNSBool gotlease
= GetPktLease(m
, msg
, end
, &pktlease
);
10550 const mDNSu32 updatelease
= gotlease
? pktlease
: 60 * 60; // If SPS fails to indicate lease time, assume one hour
10551 if (gotlease
) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease
, mDNSVal16(msg
->h
.id
), InterfaceID
);
10553 if (m
->CurrentRecord
)
10554 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
10555 m
->CurrentRecord
= m
->ResourceRecords
;
10556 while (m
->CurrentRecord
)
10558 AuthRecord
*const rr
= m
->CurrentRecord
;
10559 if (rr
->resrec
.InterfaceID
== InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
10560 if (mDNSSameOpaque16(rr
->updateid
, msg
->h
.id
))
10562 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10563 // Clear the updateid when we are done sending on all interfaces.
10564 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, InterfaceID
, mDNStrue
);
10565 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
10566 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
10567 if (mDNSOpaque64IsZero(&rr
->updateIntID
))
10568 rr
->updateid
= zeroID
;
10569 rr
->expire
= NonZeroTime(m
->timenow
+ updatelease
* mDNSPlatformOneSecond
);
10571 LogSPS("Sleep Proxy %s record %2d %5d 0x%x 0x%x (%d) %s", rr
->WakeUp
.HMAC
.l
[0] ? "transferred" : "registered", spsupdates
, updatelease
, rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
));
10572 if (rr
->WakeUp
.HMAC
.l
[0])
10574 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10575 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
10576 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
10579 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10580 // new records could have been added to the end of the list as a result of that call.
10581 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
10582 m
->CurrentRecord
= rr
->next
;
10584 if (spsupdates
) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10590 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10591 ifname
= InterfaceNameForID(m
, InterfaceID
);
10592 mDNSPlatformMemCopy(&spsaddr
, srcaddr
, sizeof (mDNSAddr
));
10593 mDNSPlatformStoreSPSMACAddr(&spsaddr
, ifname
);
10595 // Store the Owner OPT record for this interface.
10596 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10597 InitializeDNSMessage(&optMsg
.h
, zeroID
, ResponseFlags
);
10598 length
= mDNSGenerateOwnerOptForInterface(m
, InterfaceID
, &optMsg
);
10601 length
+= sizeof(DNSMessageHeader
);
10602 mDNSPlatformStoreOwnerOptRecord(ifname
, &optMsg
, length
);
10606 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10607 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10608 if (m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
10611 mDNSexport
void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
,
10612 const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
, DNSServer
*dnsserver
)
10614 if (cr
== &m
->rec
.r
&& m
->rec
.r
.resrec
.RecordType
)
10615 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m
, &m
->rec
.r
));
10617 // Create empty resource record
10618 cr
->resrec
.RecordType
= kDNSRecordTypePacketNegative
;
10619 cr
->resrec
.InterfaceID
= InterfaceID
;
10620 cr
->resrec
.rDNSServer
= dnsserver
;
10621 cr
->resrec
.name
= name
; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10622 cr
->resrec
.rrtype
= rrtype
;
10623 cr
->resrec
.rrclass
= rrclass
;
10624 cr
->resrec
.rroriginalttl
= ttl_seconds
;
10625 cr
->resrec
.rdlength
= 0;
10626 cr
->resrec
.rdestimate
= 0;
10627 cr
->resrec
.namehash
= namehash
;
10628 cr
->resrec
.rdatahash
= 0;
10629 cr
->resrec
.rdata
= (RData
*)&cr
->smallrdatastorage
;
10630 cr
->resrec
.rdata
->MaxRDLength
= 0;
10632 cr
->NextInKAList
= mDNSNULL
;
10633 cr
->TimeRcvd
= m
->timenow
;
10634 cr
->DelayDelivery
= 0;
10635 cr
->NextRequiredQuery
= m
->timenow
;
10636 cr
->CRActiveQuestion
= mDNSNULL
;
10637 cr
->UnansweredQueries
= 0;
10638 cr
->LastUnansweredTime
= 0;
10639 cr
->NextInCFList
= mDNSNULL
;
10640 cr
->nsec
= mDNSNULL
;
10641 cr
->soa
= mDNSNULL
;
10642 cr
->CRDNSSECQuestion
= 0;
10643 // Initialize to the basic one and the caller can set it to more
10644 // specific based on the response if any
10645 cr
->responseFlags
= ResponseFlags
;
10648 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
10649 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
,
10650 const mDNSInterfaceID InterfaceID
)
10652 mDNSInterfaceID ifid
= InterfaceID
;
10653 const mDNSu8
*const pkt
= (mDNSu8
*)msg
;
10654 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
10655 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
10656 const mDNSu8 UpdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_Update
;
10657 const mDNSu8 UpdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
10659 mDNSu8
*ptr
= mDNSNULL
;
10660 mDNSBool TLS
= (dstaddr
== (mDNSAddr
*)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10661 if (TLS
) dstaddr
= mDNSNULL
;
10663 #ifndef UNICAST_DISABLED
10664 if (mDNSSameAddress(srcaddr
, &m
->Router
))
10666 #ifdef _LEGACY_NAT_TRAVERSAL_
10667 if (mDNSSameIPPort(srcport
, SSDPPort
) || (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)))
10670 LNT_ConfigureRouterInfo(m
, InterfaceID
, (mDNSu8
*)msg
, (mDNSu16
)(end
- pkt
));
10675 if (mDNSSameIPPort(srcport
, NATPMPPort
))
10678 uDNS_ReceiveNATPacket(m
, InterfaceID
, (mDNSu8
*)msg
, (mDNSu16
)(end
- pkt
));
10683 #ifdef _LEGACY_NAT_TRAVERSAL_
10684 else if (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr
, mDNSVal16(srcport
)); return; }
10688 if ((unsigned)(end
- pkt
) < sizeof(DNSMessageHeader
))
10690 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), (int)(end
- pkt
));
10693 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
10694 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10695 ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
10696 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
10697 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
10698 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
10699 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
10701 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10703 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10704 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10705 if (!mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
10709 if (mDNSOpaque16IsZero(msg
->h
.id
))
10712 #if APPLE_OSX_mDNSResponder
10713 // Track the number of multicast packets received from a source outside our subnet.
10714 // Check the destination address to avoid accounting for spurious packets that
10715 // comes in with message id zero.
10716 if (!mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
) && dstaddr
&&
10717 mDNSAddressIsAllDNSLinkGroup(dstaddr
))
10721 #endif // #if APPLE_OSX_mDNSResponder
10724 #ifndef UNICAST_DISABLED
10725 if (!dstaddr
|| (!mDNSAddressIsAllDNSLinkGroup(dstaddr
) && (QR_OP
== StdR
|| QR_OP
== UpdR
)))
10726 if (!mDNSOpaque16IsZero(msg
->h
.id
)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10728 ifid
= mDNSInterface_Any
;
10729 if (mDNS_PacketLoggingEnabled
)
10730 DumpPacket(mStatus_NoError
, mDNSfalse
, TLS
? "TLS" : !dstaddr
? "TCP" : "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
, InterfaceID
);
10731 uDNS_ReceiveMsg(m
, msg
, end
, srcaddr
, srcport
);
10732 // Note: mDNSCore also needs to get access to received unicast responses
10735 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10736 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10737 else if (QR_OP
== UpdQ
) mDNSCoreReceiveUpdate (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
10738 else if (QR_OP
== UpdR
) mDNSCoreReceiveUpdateR (m
, msg
, end
, srcaddr
, InterfaceID
);
10741 if (mDNS_LoggingEnabled
)
10743 static int msgCount
= 0;
10744 if (msgCount
< 1000) {
10747 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10748 msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1], srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), (int)(end
- pkt
), InterfaceID
);
10749 while (i
< (int)(end
- pkt
))
10752 char *p
= buffer
+ mDNS_snprintf(buffer
, sizeof(buffer
), "%04X", i
);
10753 do if (i
< (int)(end
- pkt
)) p
+= mDNS_snprintf(p
, sizeof(buffer
), " %02X", pkt
[i
]);while (++i
& 15);
10754 LogInfo("%s", buffer
);
10759 // Packet reception often causes a change to the task list:
10760 // 1. Inbound queries can cause us to need to send responses
10761 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10762 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10763 // 4. Response packets that answer questions may cause our client to issue new questions
10767 // ***************************************************************************
10768 #if COMPILER_LIKES_PRAGMA_MARK
10770 #pragma mark - Searcher Functions
10773 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10774 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10775 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10776 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10777 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10779 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10780 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10781 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10782 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10783 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10784 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10785 // breaks this design principle.
10788 // If IsLLQ(Q) is true, it means the question is both:
10789 // (a) long-lived and
10790 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10791 // for multicast questions, we don't want to treat LongLived as anything special
10792 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10793 #define AWDLIsIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10794 #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID))
10796 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
10799 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10800 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10801 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10802 // further in the list.
10803 for (q
= m
->Questions
; q
&& (q
!= question
); q
= q
->next
)
10805 if (!SameQuestionKind(q
, question
)) continue;
10806 if (q
->qnamehash
!= question
->qnamehash
) continue;
10807 if (q
->InterfaceID
!= question
->InterfaceID
) continue;
10808 if (q
->qtype
!= question
->qtype
) continue;
10809 if (q
->qclass
!= question
->qclass
) continue;
10810 if (IsLLQ(q
) != IsLLQ(question
)) continue;
10811 if (q
->AuthInfo
&& !question
->AuthInfo
) continue;
10812 if (q
->ValidationRequired
!= question
->ValidationRequired
) continue;
10813 if (q
->ValidatingResponse
!= question
->ValidatingResponse
) continue;
10814 if (!q
->Suppressed
!= !question
->Suppressed
) continue;
10815 if (q
->BrowseThreshold
!= question
->BrowseThreshold
) continue;
10816 if (AWDLIsIncluded(q
) != AWDLIsIncluded(question
)) continue;
10817 if (!SameDomainName(&q
->qname
, &question
->qname
)) continue;
10823 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10824 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, DNSQuestion
*const question
)
10827 DNSQuestion
*first
= mDNSNULL
;
10829 // This is referring to some other question as duplicate. No other question can refer to this
10830 // question as a duplicate.
10831 if (question
->DuplicateOf
)
10833 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
10834 "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME
" (" PUB_S
") duplicate of %p " PRI_DM_NAME
" (" PUB_S
")",
10835 question
->request_id
, mDNSVal16(question
->DuplicateOf
->TargetQID
), mDNSVal16(question
->TargetQID
),
10836 question
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
), question
->DuplicateOf
,
10837 DM_NAME_PARAM(question
->DuplicateOf
->qname
.c
), DNSTypeName(question
->DuplicateOf
->qtype
));
10841 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
10842 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
10844 q
->DuplicateOf
= first
;
10848 // If q used to be a duplicate, but now is not,
10849 // then inherit the state from the question that's going away
10850 q
->LastQTime
= question
->LastQTime
;
10851 q
->ThisQInterval
= question
->ThisQInterval
;
10852 q
->ExpectUnicastResp
= question
->ExpectUnicastResp
;
10853 q
->LastAnswerPktNum
= question
->LastAnswerPktNum
;
10854 q
->RecentAnswerPkts
= question
->RecentAnswerPkts
;
10855 q
->RequestUnicast
= question
->RequestUnicast
;
10856 q
->LastQTxTime
= question
->LastQTxTime
;
10857 q
->CNAMEReferrals
= question
->CNAMEReferrals
;
10858 q
->nta
= question
->nta
;
10859 q
->servAddr
= question
->servAddr
;
10860 q
->servPort
= question
->servPort
;
10861 q
->qDNSServer
= question
->qDNSServer
;
10862 q
->validDNSServers
= question
->validDNSServers
;
10863 q
->unansweredQueries
= question
->unansweredQueries
;
10864 q
->noServerResponse
= question
->noServerResponse
;
10865 q
->triedAllServersOnce
= question
->triedAllServersOnce
;
10867 q
->TargetQID
= question
->TargetQID
;
10868 q
->LocalSocket
= question
->LocalSocket
;
10869 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10871 q
->state
= question
->state
;
10872 // q->tcp = question->tcp;
10873 q
->ReqLease
= question
->ReqLease
;
10874 q
->expire
= question
->expire
;
10875 q
->ntries
= question
->ntries
;
10876 q
->id
= question
->id
;
10878 question
->LocalSocket
= mDNSNULL
;
10879 question
->nta
= mDNSNULL
; // If we've got a GetZoneData in progress, transfer it to the newly active question
10880 // question->tcp = mDNSNULL;
10882 if (q
->LocalSocket
)
10883 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10887 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10888 q
->nta
->ZoneDataContext
= q
;
10891 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10892 if (question
->tcp
) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10894 if (question
->state
== LLQ_Established
)
10896 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10897 question
->state
= 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10900 SetNextQueryTime(m
,q
);
10905 mDNSexport McastResolver
*mDNS_AddMcastResolver(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, mDNSu32 timeout
)
10907 McastResolver
**p
= &m
->McastResolvers
;
10908 McastResolver
*tmp
= mDNSNULL
;
10910 if (!d
) d
= (const domainname
*)"";
10912 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
10913 "mDNS_AddMcastResolver: Adding " PUB_DM_NAME
", InterfaceID %p, timeout %u", DM_NAME_PARAM(d
), interface
, timeout
);
10917 while (*p
) // Check if we already have this {interface, domain} tuple registered
10919 if ((*p
)->interface
== interface
&& SameDomainName(&(*p
)->domain
, d
))
10921 if (!((*p
)->flags
& McastResolver_FlagDelete
)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d
->c
, interface
);
10922 (*p
)->flags
&= ~McastResolver_FlagDelete
;
10925 tmp
->next
= mDNSNULL
;
10931 if (tmp
) *p
= tmp
; // move to end of list, to ensure ordering from platform layer
10934 // allocate, add to list
10935 *p
= (McastResolver
*) mDNSPlatformMemAllocateClear(sizeof(**p
));
10936 if (!*p
) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10939 (*p
)->interface
= interface
;
10940 (*p
)->flags
= McastResolver_FlagNew
;
10941 (*p
)->timeout
= timeout
;
10942 AssignDomainName(&(*p
)->domain
, d
);
10943 (*p
)->next
= mDNSNULL
;
10949 mDNSinline mDNSs32
PenaltyTimeForServer(mDNS
*m
, DNSServer
*server
)
10952 if (server
->penaltyTime
!= 0)
10954 ptime
= server
->penaltyTime
- m
->timenow
;
10957 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10958 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10960 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10961 ptime
, server
->penaltyTime
, m
->timenow
);
10962 server
->penaltyTime
= 0;
10969 //Checks to see whether the newname is a better match for the name, given the best one we have
10970 //seen so far (given in bestcount).
10971 //Returns -1 if the newname is not a better match
10972 //Returns 0 if the newname is the same as the old match
10973 //Returns 1 if the newname is a better match
10974 mDNSlocal
int BetterMatchForName(const domainname
*name
, int namecount
, const domainname
*newname
, int newcount
,
10977 // If the name contains fewer labels than the new server's domain or the new name
10978 // contains fewer labels than the current best, then it can't possibly be a better match
10979 if (namecount
< newcount
|| newcount
< bestcount
) return -1;
10981 // If there is no match, return -1 and the caller will skip this newname for
10984 // If we find a match and the number of labels is the same as bestcount, then
10985 // we return 0 so that the caller can do additional logic to pick one of
10986 // the best based on some other factors e.g., penaltyTime
10988 // If we find a match and the number of labels is more than bestcount, then we
10989 // return 1 so that the caller can pick this over the old one.
10991 // Note: newcount can either be equal or greater than bestcount beause of the
10994 if (SameDomainName(SkipLeadingLabels(name
, namecount
- newcount
), newname
))
10995 return bestcount
== newcount
? 0 : 1;
11000 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
11001 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
11002 // names. In that case, we give a default timeout of 5 seconds
11003 #define DEFAULT_MCAST_TIMEOUT 5
11004 mDNSlocal mDNSu32
GetTimeoutForMcastQuestion(mDNS
*m
, DNSQuestion
*question
)
11006 McastResolver
*curmatch
= mDNSNULL
;
11007 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
11008 McastResolver
*curr
;
11009 int bettermatch
, currcount
;
11010 for (curr
= m
->McastResolvers
; curr
; curr
= curr
->next
)
11012 currcount
= CountLabels(&curr
->domain
);
11013 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11014 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
11015 // the timeout value from the first one
11016 if (bettermatch
== 1)
11019 bestmatchlen
= currcount
;
11022 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question
->qname
.c
, curmatch
,
11023 curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
11024 return ( curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
11027 // Returns true if it is a Domain Enumeration Query
11028 mDNSexport mDNSBool
DomainEnumQuery(const domainname
*qname
)
11030 const mDNSu8
*mDNS_DEQLabels
[] = { (const mDNSu8
*)"\001b", (const mDNSu8
*)"\002db", (const mDNSu8
*)"\002lb",
11031 (const mDNSu8
*)"\001r", (const mDNSu8
*)"\002dr", (const mDNSu8
*)mDNSNULL
, };
11032 const domainname
*d
= qname
;
11033 const mDNSu8
*label
;
11036 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
11037 if (CountLabels(qname
) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname
->c
); return mDNSfalse
; }
11039 label
= (const mDNSu8
*)d
;
11040 while (mDNS_DEQLabels
[i
] != (const mDNSu8
*)mDNSNULL
)
11042 if (SameDomainLabel(mDNS_DEQLabels
[i
], label
)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
); break;}
11045 if (mDNS_DEQLabels
[i
] == (const mDNSu8
*)mDNSNULL
)
11047 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname
->c
);
11050 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
);
11052 // CountLabels already verified the number of labels
11053 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Second Label
11054 label
= (const mDNSu8
*)d
;
11055 if (!SameDomainLabel(label
, (const mDNSu8
*)"\007_dns-sd"))
11057 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname
->c
);
11060 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname
->c
);
11062 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Third Label
11063 label
= (const mDNSu8
*)d
;
11064 if (!SameDomainLabel(label
, (const mDNSu8
*)"\004_udp"))
11066 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname
->c
);
11069 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname
->c
);
11071 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname
->c
);
11076 // Note: InterfaceID is the InterfaceID of the question
11077 mDNSlocal mDNSBool
DNSServerMatch(DNSServer
*d
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
11079 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11080 // with scopeType set to kScopeNone)
11082 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11083 // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match.
11085 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11086 // with scopeType set to kScopeServiceID) and their ServiceIDs should match.
11088 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11089 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11091 // If the first condition fails, following are the possible cases (the notes below are using
11092 // InterfaceID for discussion and the same holds good for ServiceID):
11094 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11095 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11097 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11098 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11099 // would fail in this case.
11101 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11102 // should match (Refer to (2) above).
11104 if (((d
->scopeType
== kScopeNone
) && (!InterfaceID
&& ServiceID
== -1)) ||
11105 ((d
->scopeType
== kScopeInterfaceID
) && d
->interface
== InterfaceID
) ||
11106 ((d
->scopeType
== kScopeServiceID
) && d
->serviceID
== ServiceID
))
11113 // Sets all the Valid DNS servers for a question
11114 mDNSexport mDNSu32
SetValidDNSServers(mDNS
*m
, DNSQuestion
*question
)
11116 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
11118 int bettermatch
, currcount
;
11120 mDNSu32 timeout
= 0;
11123 question
->validDNSServers
= zeroOpaque128
;
11124 DEQuery
= DomainEnumQuery(&question
->qname
);
11125 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11127 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11128 // skip servers that will soon be deleted
11129 if (curr
->flags
& DNSServerFlag_Delete
)
11131 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11135 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11136 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11137 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11138 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11139 // match the scoped entries by mistake.
11141 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11143 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11144 if (((curr
->scopeType
== kScopeInterfaceID
) && (curr
->interface
== mDNSInterface_Any
)) ||
11145 ((curr
->scopeType
== kScopeServiceID
) && (curr
->serviceID
<= 0)))
11147 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]",
11148 (int)curr
->scopeType
, &curr
->addr
, curr
->domain
.c
, curr
->interface
, curr
->serviceID
);
11152 currcount
= CountLabels(&curr
->domain
);
11153 if ((!DEQuery
|| !curr
->isCell
) && DNSServerMatch(curr
, question
->InterfaceID
, question
->ServiceID
))
11155 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11157 // If we found a better match (bettermatch == 1) then clear all the bits
11158 // corresponding to the old DNSServers that we have may set before and start fresh.
11159 // If we find an equal match, then include that DNSServer also by setting the corresponding
11161 if ((bettermatch
== 1) || (bettermatch
== 0))
11163 bestmatchlen
= currcount
;
11166 debugf("SetValidDNSServers: Resetting all the bits");
11167 question
->validDNSServers
= zeroOpaque128
;
11170 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11171 " Timeout %d, interface %p", question
->qname
.c
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
, index
, curr
->timeout
,
11173 timeout
+= curr
->timeout
;
11175 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question
->qname
.c
, &curr
->addr
, curr
->isCell
);
11176 bit_set_opaque128(question
->validDNSServers
, index
);
11181 question
->noServerResponse
= 0;
11183 debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)",
11184 question
->validDNSServers
.l
[3], question
->validDNSServers
.l
[2], question
->validDNSServers
.l
[1], question
->validDNSServers
.l
[0], question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11185 // If there are no matching resolvers, then use the default timeout value.
11186 // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
11187 return ((question
->ProxyQuestion
|| question
->ValidatingResponse
) ? DEFAULT_UDNSSEC_TIMEOUT
: timeout
? timeout
: DEFAULT_UDNS_TIMEOUT
);
11190 // Get the Best server that matches a name. If you find penalized servers, look for the one
11191 // that will come out of the penalty box soon
11192 mDNSlocal DNSServer
*GetBestServer(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
, mDNSOpaque128 validBits
,
11193 int *selected
, mDNSBool nameMatch
)
11195 DNSServer
*curmatch
= mDNSNULL
;
11196 int bestmatchlen
= -1, namecount
= name
? CountLabels(name
) : 0;
11198 mDNSs32 bestPenaltyTime
, currPenaltyTime
;
11199 int bettermatch
, currcount
;
11201 int currindex
= -1;
11203 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits
.l
[1], validBits
.l
[0]);
11204 bestPenaltyTime
= DNSSERVER_PENALTY_TIME
+ 1;
11205 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11207 // skip servers that will soon be deleted
11208 if (curr
->flags
& DNSServerFlag_Delete
)
11210 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11214 // Check if this is a valid DNSServer
11215 if (!bit_get_opaque64(validBits
, index
))
11217 debugf("GetBestServer: continuing for index %d", index
);
11222 currcount
= CountLabels(&curr
->domain
);
11223 currPenaltyTime
= PenaltyTimeForServer(m
, curr
);
11225 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11226 &curr
->addr
, curr
->domain
.c
, curr
->penaltyTime
, currPenaltyTime
);
11228 // If there are multiple best servers for a given question, we will pick the first one
11229 // if none of them are penalized. If some of them are penalized in that list, we pick
11230 // the least penalized one. BetterMatchForName walks through all best matches and
11231 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11232 // in the list when there are no penalized servers and least one among them
11233 // when there are some penalized servers.
11235 if (DNSServerMatch(curr
, InterfaceID
, ServiceID
))
11238 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11239 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11240 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11241 // part and still do some redundant steps e.g., InterfaceID match
11244 bettermatch
= BetterMatchForName(name
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11248 // If we found a better match (bettermatch == 1) then we don't need to
11249 // compare penalty times. But if we found an equal match, then we compare
11250 // the penalty times to pick a better match
11252 if ((bettermatch
== 1) || ((bettermatch
== 0) && currPenaltyTime
< bestPenaltyTime
))
11256 bestmatchlen
= currcount
;
11257 bestPenaltyTime
= currPenaltyTime
;
11262 if (selected
) *selected
= currindex
;
11266 // Look up a DNS Server, matching by name and InterfaceID
11267 mDNSlocal DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
11269 DNSServer
*curmatch
= mDNSNULL
;
11270 char *ifname
= mDNSNULL
; // for logging purposes only
11271 mDNSOpaque128 allValid
;
11273 if (InterfaceID
== mDNSInterface_LocalOnly
)
11274 InterfaceID
= mDNSNULL
;
11276 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
11278 // By passing in all ones, we make sure that every DNS server is considered
11279 allValid
.l
[0] = allValid
.l
[1] = allValid
.l
[2] = allValid
.l
[3] = 0xFFFFFFFF;
11281 curmatch
= GetBestServer(m
, name
, InterfaceID
, ServiceID
, allValid
, mDNSNULL
, mDNStrue
);
11283 if (curmatch
!= mDNSNULL
)
11284 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch
->addr
,
11285 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
11286 InterfaceID
, name
);
11288 LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname
? ifname
: "None", InterfaceID
, name
);
11293 // Look up a DNS Server for a question within its valid DNSServer bits
11294 mDNSexport DNSServer
*GetServerForQuestion(mDNS
*m
, DNSQuestion
*question
)
11296 DNSServer
*curmatch
= mDNSNULL
;
11297 char *ifname
= mDNSNULL
; // for logging purposes only
11298 mDNSInterfaceID InterfaceID
= question
->InterfaceID
;
11299 const domainname
*name
= &question
->qname
;
11302 if (InterfaceID
== mDNSInterface_LocalOnly
)
11303 InterfaceID
= mDNSNULL
;
11306 ifname
= InterfaceNameForID(m
, InterfaceID
);
11308 if (!mDNSOpaque128IsZero(&question
->validDNSServers
))
11310 curmatch
= GetBestServer(m
, name
, InterfaceID
, question
->ServiceID
, question
->validDNSServers
, &currindex
, mDNSfalse
);
11311 if (currindex
!= -1)
11312 bit_clr_opaque128(question
->validDNSServers
, currindex
);
11315 if (curmatch
!= mDNSNULL
)
11317 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11318 "[R%d->Q%d] GetServerForQuestion: %p DNS server (%p) " PRI_IP_ADDR
":%d (Penalty Time Left %d) (Scope " PUB_S
":%p:%d) for " PRI_DM_NAME
" (" PUB_S
")",
11319 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, curmatch
, &curmatch
->addr
,
11320 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0),
11321 ifname
? ifname
: "None", InterfaceID
, question
->ServiceID
, DM_NAME_PARAM(name
), DNSTypeName(question
->qtype
));
11325 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11326 "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S
":%p:%d) for " PRI_DM_NAME
" (" PUB_S
")",
11327 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, ifname
? ifname
: "None", InterfaceID
,
11328 question
->ServiceID
, DM_NAME_PARAM(name
), DNSTypeName(question
->qtype
));
11334 // Called in normal client context (lock not held)
11335 mDNSlocal
void LLQNATCallback(mDNS
*m
, NATTraversalInfo
*n
)
11339 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n
->ExternalAddress
, mDNSVal16(n
->ExternalPort
), n
->Result
);
11340 n
->clientContext
= mDNSNULL
; // we received at least one callback since starting this NAT-T
11341 for (q
= m
->Questions
; q
; q
=q
->next
)
11342 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
)
11343 startLLQHandshake(m
, q
); // If ExternalPort is zero, will do StartLLQPolling instead
11347 // This function takes the DNSServer as a separate argument because sometimes the
11348 // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed
11349 // status before switching to it.
11350 mDNSlocal mDNSBool
ShouldSuppressUnicastQuery(const DNSQuestion
*const q
, const DNSServer
*const server
)
11352 mDNSBool suppress
= mDNSfalse
;
11353 const char *reason
= NULL
;
11355 if (q
->BlockedByPolicy
)
11357 suppress
= mDNStrue
;
11358 reason
= " (blocked by policy)";
11362 if (!q
->IsUnicastDotLocal
)
11364 suppress
= mDNStrue
;
11365 reason
= " (no DNS server)";
11368 else if (server
->isCell
&& (q
->flags
& kDNSServiceFlagsDenyCellular
))
11370 suppress
= mDNStrue
;
11371 reason
= " (interface is cellular)";
11373 else if (server
->isExpensive
&& (q
->flags
& kDNSServiceFlagsDenyExpensive
))
11375 suppress
= mDNStrue
;
11376 reason
= " (interface is expensive)";
11378 else if (server
->isConstrained
&& (q
->flags
& kDNSServiceFlagsDenyConstrained
))
11380 suppress
= mDNStrue
;
11381 reason
= " (interface is constrained)";
11383 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
11384 else if (q
->SuppressUnusable
&& !DNS64IsQueryingARecord(q
->dns64
.state
))
11386 else if (q
->SuppressUnusable
)
11389 if (q
->qtype
== kDNSType_A
)
11391 if (!server
->usableA
)
11393 suppress
= mDNStrue
;
11394 reason
= " (A records are unusable)";
11396 // If the server's configuration allows A record queries, suppress this query if
11397 // 1. the interface associated with the server is CLAT46; and
11398 // 2. the query has the kDNSServiceFlagsPathEvaluationDone flag, indicating that it's from libnetwork.
11399 // See <rdar://problem/42672030> for more info.
11400 else if (server
->isCLAT46
&& (q
->flags
& kDNSServiceFlagsPathEvaluationDone
))
11402 suppress
= mDNStrue
;
11403 reason
= " (CLAT46 A records are unusable)";
11406 else if (q
->qtype
== kDNSType_AAAA
)
11408 if (!server
->usableAAAA
)
11410 suppress
= mDNStrue
;
11411 reason
= " (AAAA records are unusable)";
11417 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11418 "[Q%u] ShouldSuppressUnicastQuery: Query suppressed for " PRI_DM_NAME
" " PUB_S PUB_S
,
11419 mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), reason
? reason
: "");
11424 mDNSlocal mDNSBool
ShouldSuppressQuery(DNSQuestion
*q
)
11426 if (q
->InterfaceID
== mDNSInterface_LocalOnly
)
11430 if (!q
->IsUnicastDotLocal
&& IsLocalDomain(&q
->qname
))
11434 return (ShouldSuppressUnicastQuery(q
, q
->qDNSServer
));
11437 mDNSlocal
void CacheRecordRmvEventsForCurrentQuestion(mDNS
*const m
, DNSQuestion
*q
)
11442 cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
11443 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
11445 // Don't deliver RMV events for negative records
11446 if (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
11448 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11449 "[R%u->Q%u] CacheRecordRmvEventsForCurrentQuestion: CacheRecord " PRI_S
" Suppressing RMV events for question %p " PRI_DM_NAME
" (" PUB_S
"), CRActiveQuestion %p, CurrentAnswers %d",
11450 q
->request_id
, mDNSVal16(q
->TargetQID
), CRDisplayString(m
, cr
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
), cr
->CRActiveQuestion
, q
->CurrentAnswers
);
11454 if (SameNameCacheRecordAnswersQuestion(cr
, q
))
11456 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11457 q
->qname
.c
, CRDisplayString(m
, cr
), q
->LOAddressAnswers
);
11459 q
->CurrentAnswers
--;
11460 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
11461 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
11462 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_rmv
);
11463 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
11468 mDNSlocal mDNSBool
IsQuestionNew(mDNS
*const m
, DNSQuestion
*question
)
11471 for (q
= m
->NewQuestions
; q
; q
= q
->next
)
11472 if (q
== question
) return mDNStrue
;
11476 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11481 if (m
->CurrentQuestion
)
11482 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11483 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11485 if (IsQuestionNew(m
, q
))
11487 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11490 m
->CurrentQuestion
= q
;
11491 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
11494 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
11495 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11496 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
11498 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11499 ARDisplayString(m
, rr
));
11500 if (q
->CurrentAnswers
<= 0 || q
->LOAddressAnswers
<= 0)
11502 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11503 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
),
11504 q
->CurrentAnswers
, q
->LOAddressAnswers
);
11507 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_rmv
); // MUST NOT dereference q again
11508 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11511 m
->CurrentQuestion
= mDNSNULL
;
11515 // Returns false if the question got deleted while delivering the RMV events
11516 // The caller should handle the case
11517 mDNSexport mDNSBool
CacheRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11519 if (m
->CurrentQuestion
)
11520 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11521 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11523 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11524 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11525 if (!IsQuestionNew(m
, q
) && !q
->LOAddressAnswers
)
11527 m
->CurrentQuestion
= q
;
11528 CacheRecordRmvEventsForCurrentQuestion(m
, q
);
11529 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11530 m
->CurrentQuestion
= mDNSNULL
;
11532 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q
, q
->qname
.c
, DNSTypeName(q
->qtype
)); }
11536 mDNSlocal
void SuppressStatusChanged(mDNS
*const m
, DNSQuestion
*q
, DNSQuestion
**restart
)
11538 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11539 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11540 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11543 q
->Suppressed
= mDNSfalse
;
11544 if (!CacheRecordRmvEventsForQuestion(m
, q
))
11546 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11547 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache",
11548 q
->request_id
, mDNSVal16(q
->TargetQID
));
11551 q
->Suppressed
= mDNStrue
;
11554 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11555 // and Suppressed status does not mean anything for these questions. As we are going to stop the
11556 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11557 // the restart will not be a duplicate ADD
11558 if (!LocalRecordRmvEventsForQuestion(m
, q
))
11560 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11561 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords",
11562 q
->request_id
, mDNSVal16(q
->TargetQID
));
11566 // There are two cases here.
11568 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11569 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11570 // because when we get the response, if we had entries in the cache already, it will not answer
11571 // this question if the cache entry did not change. Hence, we need to restart
11572 // the query so that it can be answered from the cache.
11574 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11575 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11576 // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false).
11577 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11578 // (Suppressed is true). The reason for this is that when a question is suppressed, we want an
11579 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11580 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11581 // This affects both efficiency and also the current design where there is only one active question
11582 // pointed to from a cache entry.
11584 // We restart queries in a two step process by first calling stop and build a temporary list which we
11585 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11586 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11587 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11588 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11589 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11591 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11593 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11594 "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME
" (" PUB_S
")",
11595 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
11596 mDNS_StopQuery_internal(m
, q
);
11597 q
->next
= *restart
;
11601 // The caller should hold the lock
11602 mDNSexport
void CheckSuppressUnusableQuestions(mDNS
*const m
)
11605 DNSQuestion
*restart
= mDNSNULL
;
11607 // We look through all questions including new questions. During network change events,
11608 // we potentially restart questions here in this function that ends up as new questions,
11609 // which may be suppressed at this instance. Before it is handled we get another network
11610 // event that changes the status e.g., address becomes available. If we did not process
11611 // new questions, we would never change its Suppressed status.
11613 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11614 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11615 // *any* other question which could be the next one that we may process here. RestartQuestion
11616 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11617 // if the "next" question is stopped while the CurrentQuestion is stopped
11618 if (m
->RestartQuestion
)
11619 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11620 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11621 m
->RestartQuestion
= m
->Questions
;
11622 while (m
->RestartQuestion
)
11624 q
= m
->RestartQuestion
;
11625 m
->RestartQuestion
= q
->next
;
11626 if (q
->SuppressUnusable
)
11628 const mDNSBool old
= q
->Suppressed
;
11629 q
->Suppressed
= ShouldSuppressQuery(q
);
11630 if (q
->Suppressed
!= old
)
11632 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11633 // followed by a negative cache response. Temporarily turn off suppression so that
11634 // AnswerCurrentQuestionWithResourceRecord can answer the question
11635 SuppressStatusChanged(m
, q
, &restart
);
11642 restart
= restart
->next
;
11643 q
->next
= mDNSNULL
;
11644 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
11645 mDNS_StartQuery_internal(m
, q
);
11649 mDNSlocal
void RestartUnicastQuestions(mDNS
*const m
)
11652 DNSQuestion
*restartList
= mDNSNULL
;
11654 if (m
->RestartQuestion
)
11655 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11656 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11657 m
->RestartQuestion
= m
->Questions
;
11658 while (m
->RestartQuestion
)
11660 q
= m
->RestartQuestion
;
11661 m
->RestartQuestion
= q
->next
;
11664 if (mDNSOpaque16IsZero(q
->TargetQID
))
11665 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11667 q
->Restart
= mDNSfalse
;
11668 SuppressStatusChanged(m
, q
, &restartList
);
11671 while ((q
= restartList
) != mDNSNULL
)
11673 restartList
= q
->next
;
11674 q
->next
= mDNSNULL
;
11675 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11676 "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME
" (" PUB_S
")",
11677 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
11678 mDNS_StartQuery_internal(m
, q
);
11682 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11683 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11684 mDNSlocal mStatus
ValidateParameters(mDNS
*const m
, DNSQuestion
*const question
)
11686 if (!ValidateDomainName(&question
->qname
))
11688 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
11689 return(mStatus_Invalid
);
11692 // If this question is referencing a specific interface, verify it exists
11693 if (question
->InterfaceID
&& !LocalOnlyOrP2PInterface(question
->InterfaceID
))
11695 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, question
->InterfaceID
);
11697 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11698 IIDPrintable(question
->InterfaceID
), question
->qname
.c
, DNSTypeName(question
->qtype
));
11701 return(mStatus_NoError
);
11704 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11705 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
11706 mDNSlocal
void InitDNSConfig(mDNS
*const m
, DNSQuestion
*const question
)
11708 // First reset all DNS Configuration
11709 question
->qDNSServer
= mDNSNULL
;
11710 question
->validDNSServers
= zeroOpaque128
;
11711 question
->triedAllServersOnce
= mDNSfalse
;
11712 question
->noServerResponse
= mDNSfalse
;
11713 question
->StopTime
= (question
->TimeoutQuestion
) ? question
->StopTime
: 0;
11714 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
11715 mDNSPlatformMemZero(&question
->metrics
, sizeof(question
->metrics
));
11716 question
->metrics
.expiredAnswerState
= (question
->allowExpired
!= AllowExpired_None
) ? ExpiredAnswer_Allowed
: ExpiredAnswer_None
;
11719 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11720 if (LocalOnlyOrP2PInterface(question
->InterfaceID
) && !question
->TimeoutQuestion
)
11722 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11723 if (!mDNSOpaque16IsZero(question
->TargetQID
))
11725 mDNSu32 timeout
= SetValidDNSServers(m
, question
);
11726 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11727 // So if a question is restarted when a network change occurs, the StopTime is not reset.
11728 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11729 // it gets a full timeout value even if the original question times out earlier.
11730 if (question
->TimeoutQuestion
&& !question
->StopTime
)
11732 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
11733 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11734 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME
" (" PUB_S
")",
11735 mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
));
11738 question
->qDNSServer
= GetServerForQuestion(m
, question
);
11739 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
11740 "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME
" " PUB_S
" Timeout %d, DNS Server " PRI_IP_ADDR
":%d",
11741 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(question
->qname
.c
),
11742 DNSTypeName(question
->qtype
), timeout
, question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11743 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
11745 else if (question
->TimeoutQuestion
&& !question
->StopTime
)
11747 // If the question is to be timed out and its a multicast, local-only or P2P case,
11748 // then set it's stop time.
11749 mDNSu32 timeout
= LocalOnlyOrP2PInterface(question
->InterfaceID
) ?
11750 DEFAULT_LO_OR_P2P_TIMEOUT
: GetTimeoutForMcastQuestion(m
, question
);
11751 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
11752 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11753 "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME
" (" PUB_S
")",
11754 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
));
11756 // Set StopTime here since it is a part of DNS Configuration
11757 if (question
->StopTime
)
11758 SetNextQueryStopTime(m
, question
);
11759 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11760 // will never be transmitted on the wire.
11761 if (!(LocalOnlyOrP2PInterface(question
->InterfaceID
)))
11762 SetNextQueryTime(m
,question
);
11765 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11766 // state fields of the DNS Question. These are independent of the Client layer.
11767 mDNSlocal
void InitCommonState(mDNS
*const m
, DNSQuestion
*const question
)
11770 mDNSBool isBlocked
= mDNSfalse
;
11772 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11773 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11774 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11775 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11776 // that to go out immediately.
11777 question
->next
= mDNSNULL
;
11778 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11779 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11780 // the question list to check if ThisQInterval is negative which means the question has been
11781 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11782 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11783 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11784 // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11785 question
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
11786 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
11787 question
->DelayAnswering
= mDNSOpaque16IsZero(question
->TargetQID
) ? CheckForSoonToExpireRecords(m
, &question
->qname
, question
->qnamehash
) : 0;
11788 question
->LastQTime
= m
->timenow
;
11789 question
->ExpectUnicastResp
= 0;
11790 question
->LastAnswerPktNum
= m
->PktNum
;
11791 question
->RecentAnswerPkts
= 0;
11792 question
->CurrentAnswers
= 0;
11794 #if APPLE_OSX_mDNSResponder
11796 // Initial browse threshold used by Finder.
11797 #define mDNSFinderBrowseThreshold 20
11799 // Set the threshold at which we move to a passive browse state,
11800 // not actively sending queries.
11801 if (question
->flags
& kDNSServiceFlagsThresholdOne
)
11802 question
->BrowseThreshold
= 1;
11803 else if (question
->flags
& kDNSServiceFlagsThresholdFinder
)
11804 question
->BrowseThreshold
= mDNSFinderBrowseThreshold
;
11806 question
->BrowseThreshold
= 0;
11808 #else // APPLE_OSX_mDNSResponder
11809 question
->BrowseThreshold
= 0;
11810 #endif // APPLE_OSX_mDNSResponder
11811 question
->CachedAnswerNeedsUpdate
= mDNSfalse
;
11813 question
->LargeAnswers
= 0;
11814 question
->UniqueAnswers
= 0;
11815 question
->LOAddressAnswers
= 0;
11816 question
->FlappingInterface1
= mDNSNULL
;
11817 question
->FlappingInterface2
= mDNSNULL
;
11819 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11820 // since we would already have the question->ServiceID in that case.
11821 if (!(question
->flags
& kDNSServiceFlagsServiceIndex
))
11823 #if APPLE_OSX_mDNSResponder
11824 mDNSPlatformGetDNSRoutePolicy(question
, &isBlocked
);
11826 question
->ServiceID
= -1;
11830 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question
->qname
.c
,
11831 DNSTypeName(question
->qtype
), question
->pid
, question
->euid
, question
->ServiceID
);
11833 InitDNSConfig(m
, question
);
11835 question
->AuthInfo
= GetAuthInfoForQuestion(m
, question
);
11837 // The question's BlockedByPolicy value must be set before calling ShouldSuppressQuery().
11838 question
->BlockedByPolicy
= isBlocked
? mDNStrue
: mDNSfalse
;
11839 question
->Suppressed
= ShouldSuppressQuery(question
);
11840 question
->NextInDQList
= mDNSNULL
;
11841 question
->SendQNow
= mDNSNULL
;
11842 question
->SendOnAll
= mDNSfalse
;
11843 question
->RequestUnicast
= kDefaultRequestUnicastCount
;
11845 #if APPLE_OSX_mDNSResponder
11846 // Set the QU bit in the first query for the following options.
11847 if ((question
->flags
& kDNSServiceFlagsUnicastResponse
) || (question
->flags
& kDNSServiceFlagsThresholdFinder
))
11849 question
->RequestUnicast
= SET_QU_IN_FIRST_QUERY
;
11850 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question
->RequestUnicast
, question
->qname
.c
,
11851 DNSTypeName(question
->qtype
));
11853 #endif // APPLE_OSX_mDNSResponder
11855 question
->LastQTxTime
= m
->timenow
;
11856 question
->CNAMEReferrals
= 0;
11858 question
->WakeOnResolveCount
= 0;
11859 if (question
->WakeOnResolve
)
11861 question
->WakeOnResolveCount
= InitialWakeOnResolveCount
;
11864 for (i
=0; i
<DupSuppressInfoSize
; i
++)
11865 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
11867 question
->Restart
= mDNSfalse
;
11869 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11870 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, m
->timenow
,
11871 NextQSendTime(question
) - m
->timenow
,
11872 question
->DelayAnswering
? question
->DelayAnswering
- m
->timenow
: 0,
11873 question
, question
->DuplicateOf
? "duplicate of" : "not duplicate", question
->DuplicateOf
);
11875 if (question
->DelayAnswering
)
11876 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11877 question
->DelayAnswering
- m
->timenow
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11880 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11881 mDNSlocal
void InitWABState(DNSQuestion
*const question
)
11883 // We'll create our question->LocalSocket on demand, if needed.
11884 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11885 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11886 // NAT mapping for receiving inbound add/remove events.
11887 question
->LocalSocket
= mDNSNULL
;
11888 question
->unansweredQueries
= 0;
11889 question
->nta
= mDNSNULL
;
11890 question
->servAddr
= zeroAddr
;
11891 question
->servPort
= zeroIPPort
;
11892 question
->tcp
= mDNSNULL
;
11893 question
->NoAnswer
= NoAnswer_Normal
;
11896 mDNSlocal
void InitLLQNATState(mDNS
*const m
)
11898 // If we don't have our NAT mapping active, start it now
11899 if (!m
->LLQNAT
.clientCallback
)
11901 m
->LLQNAT
.Protocol
= NATOp_MapUDP
;
11902 m
->LLQNAT
.IntPort
= m
->UnicastPort4
;
11903 m
->LLQNAT
.RequestedPort
= m
->UnicastPort4
;
11904 m
->LLQNAT
.clientCallback
= LLQNATCallback
;
11905 m
->LLQNAT
.clientContext
= (void*)1; // Means LLQ NAT Traversal just started
11906 mDNS_StartNATOperation_internal(m
, &m
->LLQNAT
);
11910 mDNSlocal
void InitLLQState(DNSQuestion
*const question
)
11912 question
->state
= LLQ_Init
;
11913 question
->ReqLease
= 0;
11914 question
->expire
= 0;
11915 question
->ntries
= 0;
11916 question
->id
= zeroOpaque64
;
11919 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11920 // DNSSEC & DNS Proxy fields of the DNS Question.
11921 mDNSlocal
void InitDNSSECProxyState(mDNS
*const m
, DNSQuestion
*const question
)
11925 // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11926 // or the request is going over cellular interface.
11928 // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11929 // at ValidationRequired setting also.
11930 if (question
->qDNSServer
)
11932 if (question
->qDNSServer
->isCell
)
11934 debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question
->qname
.c
, DNSTypeName(question
->qtype
));
11935 question
->ValidationRequired
= mDNSfalse
;
11937 if (DNSSECOptionalQuestion(question
) && !(question
->qDNSServer
->req_DO
))
11939 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
11940 question
->qname
.c
, DNSTypeName(question
->qtype
));
11941 question
->ValidationRequired
= DNSSEC_VALIDATION_NONE
;
11944 question
->ValidationState
= (question
->ValidationRequired
? DNSSECValRequired
: DNSSECValNotRequired
);
11945 question
->ValidationStatus
= 0;
11946 question
->responseFlags
= zeroID
;
11949 // Once the question is completely initialized including the duplicate logic, this function
11950 // is called to finalize the unicast question which requires flushing the cache if needed,
11951 // activating the query etc.
11952 mDNSlocal
void FinalizeUnicastQuestion(mDNS
*const m
, DNSQuestion
*question
)
11954 // Ensure DNS related info of duplicate question is same as the orig question
11955 if (question
->DuplicateOf
)
11957 question
->validDNSServers
= question
->DuplicateOf
->validDNSServers
;
11958 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11959 // then we log a line as it could indicate an issue
11960 if (question
->DuplicateOf
->qDNSServer
== mDNSNULL
)
11962 if (question
->qDNSServer
) {
11963 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11964 "[R%d->Q%d] FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(" PRI_IP_ADDR
":%d) but original question(%p) has no DNS Server! " PRI_DM_NAME
" (" PUB_S
")",
11965 question
->request_id
, mDNSVal16(question
->TargetQID
), question
,
11966 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11967 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
), question
->DuplicateOf
,
11968 DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
));
11972 question
->qDNSServer
= question
->DuplicateOf
->qDNSServer
;
11973 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11974 "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME
" (" PUB_S
"), DNS Server " PRI_IP_ADDR
":%d",
11975 question
->request_id
, mDNSVal16(question
->DuplicateOf
->TargetQID
), mDNSVal16(question
->TargetQID
),
11976 question
, question
->DuplicateOf
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
),
11977 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11978 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
11981 ActivateUnicastQuery(m
, question
, mDNSfalse
);
11983 if (!question
->DuplicateOf
&& DNSSECQuestion(question
))
11985 // For DNSSEC questions, we need to have the RRSIGs also for verification.
11986 CheckForDNSSECRecords(m
, question
);
11988 if (question
->LongLived
)
11990 // Unlike other initializations, InitLLQNATState should be done after
11991 // we determine that it is a unicast question. LongLived is set for
11992 // both multicast and unicast browse questions but we should initialize
11993 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11994 // start the NAT traversal that is not needed.
11995 InitLLQNATState(m
);
11999 mDNSexport mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
12004 // First check for cache space (can't do queries if there is no cache space allocated)
12005 if (m
->rrcache_size
== 0)
12006 return(mStatus_NoCache
);
12008 vStatus
= ValidateParameters(m
, question
);
12013 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12014 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12015 // This applies to the top label (TLD) only
12016 // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails.
12017 if (IsHighASCIILabel(LastLabel(&question
->qname
)))
12019 domainname newname
;
12020 if (PerformNextPunycodeConversion(question
, &newname
))
12021 AssignDomainName(&question
->qname
, &newname
);
12023 #endif // USE_LIBIDN
12025 #ifndef UNICAST_DISABLED
12026 question
->TargetQID
= Question_uDNS(question
) ? mDNS_NewMessageID(m
) : zeroID
;
12028 question
->TargetQID
= zeroID
;
12030 debugf("mDNS_StartQuery_internal: %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12032 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12034 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12035 q
= &m
->LocalOnlyQuestions
;
12036 while (*q
&& *q
!= question
)
12041 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12042 question
->qname
.c
, DNSTypeName(question
->qtype
), question
);
12043 return(mStatus_AlreadyRegistered
);
12047 // Intialize the question. The only ordering constraint we have today is that
12048 // InitDNSSECProxyState should be called after the DNS server is selected (in
12049 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12052 InitCommonState(m
, question
);
12053 InitWABState(question
);
12054 InitLLQState(question
);
12055 InitDNSSECProxyState(m
, question
);
12057 // FindDuplicateQuestion should be called last after all the intialization
12058 // as the duplicate logic could be potentially based on any field in the
12060 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
12061 if (question
->DuplicateOf
)
12062 question
->AuthInfo
= question
->DuplicateOf
->AuthInfo
;
12064 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12066 if (!m
->NewLocalOnlyQuestions
)
12067 m
->NewLocalOnlyQuestions
= question
;
12071 if (!m
->NewQuestions
)
12072 m
->NewQuestions
= question
;
12074 // If the question's id is non-zero, then it's Wide Area
12075 // MUST NOT do this Wide Area setup until near the end of
12076 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12077 // NS, etc.) and if we haven't finished setting up our own question and setting
12078 // m->NewQuestions if necessary then we could end up recursively re-entering
12079 // this routine with the question list data structures in an inconsistent state.
12080 if (!mDNSOpaque16IsZero(question
->TargetQID
))
12082 FinalizeUnicastQuestion(m
, question
);
12086 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12087 m
->NumAllInterfaceQuestions
++;
12088 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
12089 "mDNS_StartQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME
" (" PUB_S
")",
12090 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
12091 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12093 m
->NextBonjourDisableTime
= 0;
12094 if (m
->BonjourEnabled
== 0)
12096 // Enable Bonjour immediately by scheduling network changed processing where
12097 // we will join the multicast group on each active interface.
12098 m
->BonjourEnabled
= 1;
12099 m
->NetworkChanged
= m
->timenow
;
12103 if (question
->WakeOnResolve
)
12105 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question
->qname
.c
);
12106 mDNS_PurgeBeforeResolve(m
, question
);
12111 return(mStatus_NoError
);
12114 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12115 mDNSexport
void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
)
12117 debugf("CancelGetZoneData %##s (%s)", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
));
12118 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12119 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12121 if (nta
->question
.ThisQInterval
!= -1)
12123 mDNS_StopQuery_internal(m
, &nta
->question
);
12124 if (nta
->question
.ThisQInterval
!= -1)
12125 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
), nta
->question
.ThisQInterval
);
12127 mDNSPlatformMemFree(nta
);
12130 mDNSexport mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
12132 CacheGroup
*cg
= CacheGroupForName(m
, question
->qnamehash
, &question
->qname
);
12134 DNSQuestion
**qp
= &m
->Questions
;
12136 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12138 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12139 qp
= &m
->LocalOnlyQuestions
;
12140 while (*qp
&& *qp
!= question
) qp
=&(*qp
)->next
;
12141 if (*qp
) *qp
= (*qp
)->next
;
12145 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
12147 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question
->qname
.c
, DNSTypeName(question
->qtype
));
12148 return(mStatus_BadReferenceErr
);
12151 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12152 if (!LocalOnlyOrP2PInterface(question
->InterfaceID
) && mDNSOpaque16IsZero(question
->TargetQID
))
12154 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12155 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
12156 m
->NumAllInterfaceQuestions
--;
12157 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
12158 "mDNS_StopQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME
" (" PUB_S
")",
12159 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
12163 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12164 if (Question_uDNS(question
) && !question
->metrics
.answered
&& (question
->metrics
.querySendCount
> 0))
12166 const domainname
* queryName
;
12167 mDNSBool isForCell
;
12168 mDNSu32 durationMs
;
12170 queryName
= question
->metrics
.originalQName
? question
->metrics
.originalQName
: &question
->qname
;
12171 isForCell
= (question
->qDNSServer
&& question
->qDNSServer
->isCell
);
12172 durationMs
= ((m
->timenow
- question
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
12173 MetricsUpdateDNSQueryStats(queryName
, question
->qtype
, mDNSNULL
, question
->metrics
.querySendCount
, question
->metrics
.expiredAnswerState
, question
->metrics
.dnsOverTCPState
, durationMs
, isForCell
);
12176 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12177 UpdateQuestionDuplicates(m
, question
);
12178 // But don't trash ThisQInterval until afterwards.
12179 question
->ThisQInterval
= -1;
12181 // If there are any cache records referencing this as their active question, then see if there is any
12182 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12183 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
12185 if (cr
->CRActiveQuestion
== question
)
12188 DNSQuestion
*replacement
= mDNSNULL
;
12189 // If we find an active question that is answered by this cached record, use it as the cache record's
12190 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12191 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12192 // via CacheRecordRmv() when the cache record expires.
12193 for (q
= m
->Questions
; q
&& (q
!= m
->NewQuestions
); q
= q
->next
)
12195 if (!q
->DuplicateOf
&& !q
->Suppressed
&& CacheRecordAnswersQuestion(cr
, q
))
12197 if (q
->ThisQInterval
> 0)
12202 else if (!replacement
)
12209 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12210 "CurrentAnswers %d, Suppressed %d", replacement
, CRDisplayString(m
,cr
), question
->CurrentAnswers
, replacement
->CurrentAnswers
, replacement
->Suppressed
);
12211 cr
->CRActiveQuestion
= replacement
; // Question used to be active; new value may or may not be null
12212 if (!replacement
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
12216 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12217 // bump its pointer forward one question.
12218 if (m
->CurrentQuestion
== question
)
12220 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12221 question
->qname
.c
, DNSTypeName(question
->qtype
));
12222 m
->CurrentQuestion
= question
->next
;
12225 if (m
->NewQuestions
== question
)
12227 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12228 question
->qname
.c
, DNSTypeName(question
->qtype
));
12229 m
->NewQuestions
= question
->next
;
12232 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
12234 if (m
->RestartQuestion
== question
)
12236 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12237 question
->qname
.c
, DNSTypeName(question
->qtype
));
12238 m
->RestartQuestion
= question
->next
;
12241 if (m
->ValidationQuestion
== question
)
12243 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
12244 question
->qname
.c
, DNSTypeName(question
->qtype
));
12245 m
->ValidationQuestion
= question
->next
;
12248 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12249 question
->next
= mDNSNULL
;
12251 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12253 // And finally, cancel any associated GetZoneData operation that's still running.
12254 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12255 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12256 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12257 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12258 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
12259 if (question
->LocalSocket
) { mDNSPlatformUDPClose(question
->LocalSocket
); question
->LocalSocket
= mDNSNULL
; }
12260 if (!mDNSOpaque16IsZero(question
->TargetQID
) && question
->LongLived
)
12262 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12264 for (q
= m
->Questions
; q
; q
=q
->next
)
12265 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
) break;
12268 if (!m
->LLQNAT
.clientCallback
) // Should never happen, but just in case...
12270 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12274 LogInfo("Stopping LLQNAT");
12275 mDNS_StopNATOperation_internal(m
, &m
->LLQNAT
);
12276 m
->LLQNAT
.clientCallback
= mDNSNULL
; // Means LLQ NAT Traversal not running
12280 // If necessary, tell server it can delete this LLQ state
12281 if (question
->state
== LLQ_Established
)
12283 question
->ReqLease
= 0;
12284 sendLLQRefresh(m
, question
);
12285 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12286 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12287 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12288 // we let that run out its natural course and complete asynchronously.
12291 question
->tcp
->question
= mDNSNULL
;
12292 question
->tcp
= mDNSNULL
;
12295 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
12296 else if (question
->dnsPushServer
!= mDNSNULL
)
12298 UnSubscribeToDNSPushNotificationServer(m
, question
);
12302 // wait until we send the refresh above which needs the nta
12303 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
12305 if (question
->ValidationRequired
&& question
->DNSSECAuthInfo
)
12307 LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question
->qname
.c
);
12308 question
->DAIFreeCallback(m
, question
->DNSSECAuthInfo
);
12309 question
->DNSSECAuthInfo
= mDNSNULL
;
12311 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12312 if (question
->metrics
.originalQName
)
12314 mDNSPlatformMemFree(question
->metrics
.originalQName
);
12315 question
->metrics
.originalQName
= mDNSNULL
;
12319 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
12320 DNS64ResetState(question
);
12323 return(mStatus_NoError
);
12326 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
12330 status
= mDNS_StartQuery_internal(m
, question
);
12335 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
12339 status
= mDNS_StopQuery_internal(m
, question
);
12344 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12345 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12346 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12347 // specifically to catch and report if the client callback does try to make API calls
12348 mDNSexport mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
)
12354 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12355 for (qq
= m
->NewQuestions
; qq
; qq
=qq
->next
) if (qq
== question
) break;
12357 status
= mDNS_StopQuery_internal(m
, question
);
12358 if (status
== mStatus_NoError
&& !qq
)
12360 const CacheRecord
*cr
;
12361 CacheGroup
*const cg
= CacheGroupForName(m
, question
->qnamehash
, &question
->qname
);
12362 LogInfo("Generating terminal removes for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12363 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
12365 if (cr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& SameNameCacheRecordAnswersQuestion(cr
, question
))
12367 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12368 if (question
->QuestionCallback
)
12369 question
->QuestionCallback(m
, question
, &cr
->resrec
, mDNSfalse
);
12377 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const cr
)
12381 status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12382 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, cr
->resrec
.InterfaceID
, 0);
12387 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
12389 mStatus status
= mStatus_BadReferenceErr
;
12392 cr
= FindIdenticalRecordInCache(m
, rr
);
12393 debugf("mDNS_ReconfirmByValue: %p %s", cr
, RRDisplayString(m
, rr
));
12394 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12395 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, cr
->resrec
.InterfaceID
, 0);
12400 mDNSlocal mStatus
mDNS_StartBrowse_internal(mDNS
*const m
, DNSQuestion
*const question
,
12401 const domainname
*const srv
, const domainname
*const domain
,
12402 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12403 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12404 mDNSQuestionCallback
*Callback
, void *Context
)
12406 question
->InterfaceID
= InterfaceID
;
12407 question
->flags
= flags
;
12408 question
->qtype
= kDNSType_PTR
;
12409 question
->qclass
= kDNSClass_IN
;
12410 question
->LongLived
= mDNStrue
;
12411 question
->ExpectUnique
= mDNSfalse
;
12412 question
->ForceMCast
= ForceMCast
;
12413 question
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
12414 question
->SuppressUnusable
= mDNSfalse
;
12415 question
->AppendSearchDomains
= mDNSfalse
;
12416 question
->TimeoutQuestion
= 0;
12417 question
->WakeOnResolve
= 0;
12418 question
->UseBackgroundTraffic
= useBackgroundTrafficClass
;
12419 question
->ValidationRequired
= 0;
12420 question
->ValidatingResponse
= 0;
12421 question
->ProxyQuestion
= 0;
12422 question
->QuestionCallback
= Callback
;
12423 question
->QuestionContext
= Context
;
12425 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
))
12426 return(mStatus_BadParamErr
);
12428 return(mDNS_StartQuery_internal(m
, question
));
12431 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
12432 const domainname
*const srv
, const domainname
*const domain
,
12433 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12434 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12435 mDNSQuestionCallback
*Callback
, void *Context
)
12439 status
= mDNS_StartBrowse_internal(m
, question
, srv
, domain
, InterfaceID
, flags
, ForceMCast
, useBackgroundTrafficClass
, Callback
, Context
);
12445 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
12446 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
12448 question
->InterfaceID
= InterfaceID
;
12449 question
->flags
= 0;
12450 question
->qtype
= kDNSType_PTR
;
12451 question
->qclass
= kDNSClass_IN
;
12452 question
->LongLived
= mDNSfalse
;
12453 question
->ExpectUnique
= mDNSfalse
;
12454 question
->ForceMCast
= mDNSfalse
;
12455 question
->ReturnIntermed
= mDNSfalse
;
12456 question
->SuppressUnusable
= mDNSfalse
;
12457 question
->AppendSearchDomains
= mDNSfalse
;
12458 question
->TimeoutQuestion
= 0;
12459 question
->WakeOnResolve
= 0;
12460 question
->UseBackgroundTraffic
= mDNSfalse
;
12461 question
->ValidationRequired
= 0;
12462 question
->ValidatingResponse
= 0;
12463 question
->ProxyQuestion
= 0;
12464 question
->pid
= mDNSPlatformGetPID();
12465 question
->euid
= 0;
12466 question
->QuestionCallback
= Callback
;
12467 question
->QuestionContext
= Context
;
12468 if (DomainType
> mDNS_DomainTypeMax
) return(mStatus_BadParamErr
);
12469 if (!MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
12470 if (!dom
) dom
= &localdomain
;
12471 if (!AppendDomainName(&question
->qname
, dom
)) return(mStatus_BadParamErr
);
12472 return(mDNS_StartQuery(m
, question
));
12475 // ***************************************************************************
12476 #if COMPILER_LIKES_PRAGMA_MARK
12478 #pragma mark - Responder Functions
12481 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
12485 status
= mDNS_Register_internal(m
, rr
);
12490 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
12491 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
12493 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
12495 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr
->resrec
, &newrdata
->u
, m
->MsgBuffer
));
12496 return(mStatus_Invalid
);
12501 // If TTL is unspecified, leave TTL unchanged
12502 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
12504 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12507 RData
*n
= rr
->NewRData
;
12508 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
12509 if (rr
->UpdateCallback
)
12510 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
); // ...and let the client free this memory, if necessary
12513 rr
->NewRData
= newrdata
;
12514 rr
->newrdlength
= newrdlength
;
12515 rr
->UpdateCallback
= Callback
;
12517 #ifndef UNICAST_DISABLED
12518 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
&& !IsLocalDomain(rr
->resrec
.name
))
12520 mStatus status
= uDNS_UpdateRecord(m
, rr
);
12521 // The caller frees the memory on error, don't retain stale pointers
12522 if (status
!= mStatus_NoError
) { rr
->NewRData
= mDNSNULL
; rr
->newrdlength
= 0; }
12528 if (RRLocalOnly(rr
) || (rr
->resrec
.rroriginalttl
== newttl
&&
12529 rr
->resrec
.rdlength
== newrdlength
&& mDNSPlatformMemSame(rr
->resrec
.rdata
->u
.data
, newrdata
->u
.data
, newrdlength
)))
12530 CompleteRDataUpdate(m
, rr
);
12533 rr
->AnnounceCount
= InitialAnnounceCount
;
12534 InitializeLastAPTime(m
, rr
);
12535 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
12536 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
12537 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= NonZeroTime(m
->timenow
+ kUpdateCreditRefreshInterval
);
12538 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
12539 if (rr
->UpdateCredits
<= 5)
12541 mDNSu32 delay
= 6 - rr
->UpdateCredits
; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12542 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= NonZeroTime(m
->timenow
+ (mDNSs32
)delay
* mDNSPlatformOneSecond
);
12543 rr
->ThisAPInterval
*= 4;
12544 rr
->LastAPTime
= rr
->UpdateBlocked
- rr
->ThisAPInterval
;
12545 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12546 rr
->resrec
.name
->c
, delay
, delay
> 1 ? "s" : "");
12548 rr
->resrec
.rroriginalttl
= newttl
;
12552 return(mStatus_NoError
);
12555 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12556 // the record list and/or question list.
12557 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12558 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
12562 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
12567 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12568 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
12569 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12570 mDNSlocal
void mDNS_RandomizedHostNameCallback(mDNS
*m
, AuthRecord
*rr
, mStatus result
);
12573 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
12575 NetworkInterfaceInfo
*intf
;
12576 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12577 if (intf
->Advertise
) break;
12581 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12582 // (It's a set of records, not a set of interfaces.)
12583 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12584 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool useRandomizedHostname
)
12586 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12589 NetworkInterfaceInfo
*primary
;
12590 const domainname
*hostname
;
12591 mDNSRecordCallback
*hostnameCallback
;
12592 AuthRecord
*addrAR
;
12594 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12595 const mDNSBool interfaceIsAWDL
= mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
);
12597 mDNSu8 addrRecordType
;
12598 char buffer
[MAX_REVERSE_MAPPING_NAME
];
12600 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12601 if (interfaceIsAWDL
|| useRandomizedHostname
)
12603 hostname
= &m
->RandomizedHostname
;
12604 hostnameCallback
= mDNS_RandomizedHostNameCallback
;
12609 hostname
= &m
->MulticastHostname
;
12610 hostnameCallback
= mDNS_HostNameCallback
;
12613 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12614 if (!interfaceIsAWDL
&& useRandomizedHostname
)
12616 addrAR
= &set
->RR_AddrRand
;
12622 addrAR
= &set
->RR_A
;
12623 ptrAR
= &set
->RR_PTR
;
12625 if (addrAR
->resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
12627 addrRecordType
= set
->DirectLink
? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
12628 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12629 if (hostname
== &m
->RandomizedHostname
) addrRecordType
= kDNSRecordTypeKnownUnique
;
12630 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12631 "AdvertiseInterface: Advertising " PUB_S
" hostname on interface " PUB_S
,
12632 (hostname
== &m
->RandomizedHostname
) ? "randomized" : "normal", set
->ifname
);
12634 LogInfo("AdvertiseInterface: Advertising for ifname %s", set
->ifname
);
12637 // Send dynamic update for non-linklocal IPv4 Addresses
12638 mDNS_SetupResourceRecord(addrAR
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kHostNameTTL
, addrRecordType
, AuthRecordAny
, hostnameCallback
, set
);
12639 if (ptrAR
) mDNS_SetupResourceRecord(ptrAR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
12641 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12642 addrAR
->AllowRemoteQuery
= mDNStrue
;
12643 if (ptrAR
) ptrAR
->AllowRemoteQuery
= mDNStrue
;
12645 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12646 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12647 AssignDomainName(&addrAR
->namestorage
, hostname
);
12648 if (set
->ip
.type
== mDNSAddrType_IPv4
)
12650 addrAR
->resrec
.rrtype
= kDNSType_A
;
12651 addrAR
->resrec
.rdata
->u
.ipv4
= set
->ip
.ip
.v4
;
12652 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12653 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
12654 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
12656 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
12659 addrAR
->resrec
.rrtype
= kDNSType_AAAA
;
12660 addrAR
->resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
12661 for (i
= 0; i
< 16; i
++)
12663 static const char hexValues
[] = "0123456789ABCDEF";
12664 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
12665 buffer
[i
* 4 + 1] = '.';
12666 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
12667 buffer
[i
* 4 + 3] = '.';
12669 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
12674 MakeDomainNameFromDNSNameString(&ptrAR
->namestorage
, buffer
);
12675 ptrAR
->AutoTarget
= Target_AutoHost
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12676 ptrAR
->ForceMCast
= mDNStrue
; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12679 primary
= FindFirstAdvertisedInterface(m
);
12680 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
12681 // We should never have primary be NULL, because even if there is
12682 // no other interface yet, we should always find ourself in the list.
12684 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12685 if (!interfaceIsAWDL
&& useRandomizedHostname
)
12687 addrAR
->RRSet
= &primary
->RR_AddrRand
;
12692 addrAR
->RRSet
= &primary
->RR_A
;
12694 mDNS_Register_internal(m
, addrAR
);
12695 if (ptrAR
) mDNS_Register_internal(m
, ptrAR
);
12697 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12698 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12699 D2D_start_advertising_interface(set
);
12703 mDNSlocal
void AdvertiseInterfaceIfNeeded(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12705 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12706 if (mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
))
12708 if ((m
->AutoTargetAWDLIncludedCount
> 0) || (m
->AutoTargetAWDLOnlyCount
> 0))
12710 AdvertiseInterface(m
, set
, mDNSfalse
);
12715 if (m
->AutoTargetServices
> 0) AdvertiseInterface(m
, set
, mDNSfalse
);
12716 if (m
->AutoTargetAWDLIncludedCount
> 0) AdvertiseInterface(m
, set
, mDNStrue
);
12719 if (m
->AutoTargetServices
> 0) AdvertiseInterface(m
, set
);
12723 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, DeadvertiseFlags flags
)
12725 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12726 const mDNSBool interfaceIsAWDL
= mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
);
12729 // Unregister these records.
12730 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12731 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12732 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12733 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12734 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12735 if ((!interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_NormalHostname
)) ||
12736 ( interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_RandHostname
)))
12738 if (flags
& kDeadvertiseFlag_NormalHostname
)
12741 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12742 "DeadvertiseInterface: Deadvertising " PUB_S
" hostname on interface " PUB_S
,
12743 (flags
& kDeadvertiseFlag_RandHostname
) ? "randomized" : "normal", set
->ifname
);
12744 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12745 D2D_stop_advertising_interface(set
);
12747 if (set
->RR_A
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
12748 if (set
->RR_PTR
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
12750 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12751 if (!interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_RandHostname
))
12753 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12754 "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S
, set
->ifname
);
12755 AuthRecord
*const ar
= &set
->RR_AddrRand
;
12756 if (ar
->resrec
.RecordType
) mDNS_Deregister_internal(m
, ar
, mDNS_Dereg_normal
);
12761 // Change target host name for record.
12762 mDNSlocal
void UpdateTargetHostName(mDNS
*const m
, AuthRecord
*const rr
)
12764 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12765 // If this record was also registered with any D2D plugins, stop advertising
12766 // the version with the old host name.
12767 D2D_stop_advertising_record(rr
);
12770 SetTargetToHostName(m
, rr
);
12772 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12773 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12774 D2D_start_advertising_record(rr
);
12778 mDNSlocal
void DeadvertiseAllInterfaceRecords(mDNS
*const m
, DeadvertiseFlags flags
)
12780 NetworkInterfaceInfo
*intf
;
12781 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12783 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
, flags
);
12787 mDNSexport
void mDNS_SetFQDN(mDNS
*const m
)
12789 domainname newmname
;
12793 if (!AppendDomainLabel(&newmname
, &m
->hostlabel
)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12794 if (!AppendLiteralLabelString(&newmname
, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12798 if (SameDomainNameCS(&m
->MulticastHostname
, &newmname
)) debugf("mDNS_SetFQDN - hostname unchanged");
12801 AssignDomainName(&m
->MulticastHostname
, &newmname
);
12802 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_NormalHostname
);
12803 AdvertiseNecessaryInterfaceRecords(m
);
12806 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12807 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12808 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12813 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
12815 (void)rr
; // Unused parameter
12819 char *msg
= "Unknown result";
12820 if (result
== mStatus_NoError
) msg
= "Name registered";
12821 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
12822 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
12826 if (result
== mStatus_NoError
)
12828 // Notify the client that the host name is successfully registered
12829 if (m
->MainCallback
)
12830 m
->MainCallback(m
, mStatus_NoError
);
12832 else if (result
== mStatus_NameConflict
)
12834 domainlabel oldlabel
= m
->hostlabel
;
12836 // 1. First give the client callback a chance to pick a new name
12837 if (m
->MainCallback
)
12838 m
->MainCallback(m
, mStatus_NameConflict
);
12840 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12841 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12842 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12843 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
12844 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
12846 // 3. Generate the FQDNs from the hostlabel,
12847 // and make sure all SRV records, etc., are updated to reference our new hostname
12849 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel
.c
, m
->hostlabel
.c
);
12851 else if (result
== mStatus_MemFree
)
12853 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12854 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12855 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12858 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result
, rr
->resrec
.name
->c
);
12861 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12862 mDNSlocal
void mDNS_RandomizedHostNameCallback(mDNS
*const m
, AuthRecord
*const addrRecord
, const mStatus result
)
12864 (void)addrRecord
; // Unused parameter
12866 if (result
== mStatus_NameConflict
)
12869 domainlabel newUUIDLabel
;
12871 GetRandomUUIDLabel(&newUUIDLabel
);
12872 if (SameDomainLabel(newUUIDLabel
.c
, m
->RandomizedHostname
.c
))
12874 IncrementLabelSuffix(&newUUIDLabel
, mDNSfalse
);
12879 m
->RandomizedHostname
.c
[0] = 0;
12880 AppendDomainLabel(&m
->RandomizedHostname
, &newUUIDLabel
);
12881 AppendLiteralLabelString(&m
->RandomizedHostname
, "local");
12883 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_RandHostname
);
12884 AdvertiseNecessaryInterfaceRecords(m
);
12885 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
12887 if (rr
->AutoTarget
&& AuthRecordIncludesOrIsAWDL(rr
)) UpdateTargetHostName(m
, rr
);
12889 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
12891 if (rr
->AutoTarget
&& AuthRecordIncludesOrIsAWDL(rr
)) UpdateTargetHostName(m
, rr
);
12899 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
12901 NetworkInterfaceInfo
*intf
;
12902 active
->IPv4Available
= mDNSfalse
;
12903 active
->IPv6Available
= mDNSfalse
;
12904 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12905 if (intf
->InterfaceID
== active
->InterfaceID
)
12907 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->McastTxRx
) active
->IPv4Available
= mDNStrue
;
12908 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->McastTxRx
) active
->IPv6Available
= mDNStrue
;
12912 mDNSlocal
void RestartRecordGetZoneData(mDNS
* const m
)
12915 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12916 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
12917 if (AuthRecord_uDNS(rr
) && rr
->state
!= regState_NoTarget
)
12919 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr
->resrec
.name
->c
);
12920 // Zero out the updateid so that if we have a pending response from the server, it won't
12921 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12922 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
12923 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
12927 mDNSlocal
void InitializeNetWakeState(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12930 // We initialize ThisQInterval to -1 indicating that the question has not been started
12931 // yet. If the question (browse) is started later during interface registration, it will
12932 // be stopped during interface deregistration. We can't sanity check to see if the
12933 // question has been stopped or not before initializing it to -1 because we need to
12934 // initialize it to -1 the very first time.
12936 set
->NetWakeBrowse
.ThisQInterval
= -1;
12937 for (i
=0; i
<3; i
++)
12939 set
->NetWakeResolve
[i
].ThisQInterval
= -1;
12940 set
->SPSAddr
[i
].type
= mDNSAddrType_None
;
12942 set
->NextSPSAttempt
= -1;
12943 set
->NextSPSAttemptTime
= m
->timenow
;
12946 mDNSexport
void mDNS_ActivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12948 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
12949 while (p
&& p
!= set
) p
=p
->next
;
12950 if (!p
) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
12952 if (set
->InterfaceActive
)
12954 LogSPS("ActivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
12955 mDNS_StartBrowse_internal(m
, &set
->NetWakeBrowse
, &SleepProxyServiceType
, &localdomain
, set
->InterfaceID
, 0, mDNSfalse
, mDNSfalse
, m
->SPSBrowseCallback
, set
);
12959 mDNSexport
void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12961 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
12962 while (p
&& p
!= set
) p
=p
->next
;
12963 if (!p
) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
12965 // Note: We start the browse only if the interface is NetWake capable and we use this to
12966 // stop the resolves also. Hence, the resolves should not be started without the browse
12967 // being started i.e, resolves should not happen unless NetWake capable which is
12968 // guaranteed by BeginSleepProcessing.
12969 if (set
->NetWakeBrowse
.ThisQInterval
>= 0)
12972 LogSPS("DeactivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
12974 // Stop our browse and resolve operations
12975 mDNS_StopQuery_internal(m
, &set
->NetWakeBrowse
);
12976 for (i
=0; i
<3; i
++) if (set
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &set
->NetWakeResolve
[i
]);
12978 // Make special call to the browse callback to let it know it can to remove all records for this interface
12979 if (m
->SPSBrowseCallback
)
12981 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12982 m
->SPSBrowseCallback(m
, &set
->NetWakeBrowse
, mDNSNULL
, mDNSfalse
);
12983 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12986 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12987 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12988 InitializeNetWakeState(m
, set
);
12992 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, InterfaceActivationSpeed activationSpeed
)
12995 mDNSBool FirstOfType
= mDNStrue
;
12996 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
12998 if (!set
->InterfaceID
)
12999 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set
->ip
); return(mStatus_Invalid
); }
13001 if (!mDNSAddressIsValidNonZero(&set
->mask
))
13002 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set
->ip
, &set
->mask
); return(mStatus_Invalid
); }
13006 // Assume this interface will be active now, unless we find a duplicate already in the list
13007 set
->InterfaceActive
= mDNStrue
;
13008 set
->IPv4Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
);
13009 set
->IPv6Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
);
13011 InitializeNetWakeState(m
, set
);
13013 // Scan list to see if this InterfaceID is already represented
13018 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
13020 return(mStatus_AlreadyRegistered
);
13023 if ((*p
)->InterfaceID
== set
->InterfaceID
)
13025 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13026 set
->InterfaceActive
= mDNSfalse
;
13027 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
13028 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
) (*p
)->IPv4Available
= mDNStrue
;
13029 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
) (*p
)->IPv6Available
= mDNStrue
;
13035 set
->next
= mDNSNULL
;
13038 if (set
->Advertise
) AdvertiseInterfaceIfNeeded(m
, set
);
13040 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
13041 "mDNS_RegisterInterface: InterfaceID %u " PUB_S
" (" PRI_IP_ADDR
") " PUB_S
,
13042 IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
, set
->InterfaceActive
?
13043 "not represented in list; marking active and retriggering queries" :
13044 "already represented in list; marking inactive for now");
13046 if (set
->NetWake
) mDNS_ActivateNetWake_internal(m
, set
);
13048 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13049 // giving the false impression that there's an active representative of this interface when there really isn't.
13050 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13051 // even if we believe that we previously had an active representative of this interface.
13052 if (set
->McastTxRx
&& (FirstOfType
|| set
->InterfaceActive
))
13055 // Normally, after an interface comes up, we pause half a second before beginning probing.
13056 // This is to guard against cases where there's rapid interface changes, where we could be confused by
13057 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13058 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13059 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13060 // and think it's a conflicting answer to our probe.
13061 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13062 mDNSs32 probedelay
;
13063 mDNSu8 numannounce
;
13064 switch (activationSpeed
)
13066 case FastActivation
:
13067 probedelay
= (mDNSs32
)0;
13068 numannounce
= InitialAnnounceCount
;
13069 LogMsg("mDNS_RegisterInterface: Using fast activation for DirectLink interface %s (%#a)", set
->ifname
, &set
->ip
);
13072 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13073 case SlowActivation
:
13074 probedelay
= mDNSPlatformOneSecond
* 5;
13075 numannounce
= (mDNSu8
)1;
13076 LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a), doing slow activation", set
->ifname
, &set
->ip
);
13077 m
->mDNSStats
.InterfaceUpFlap
++;
13081 case NormalActivation
:
13083 probedelay
= mDNSPlatformOneSecond
/ 2;
13084 numannounce
= InitialAnnounceCount
;
13088 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set
->ifname
, &set
->ip
, probedelay
);
13090 // No probe or sending suppression on DirectLink type interfaces.
13091 if (activationSpeed
== FastActivation
)
13093 m
->SuppressSending
= 0;
13094 m
->SuppressProbes
= 0;
13098 // Use a small amount of randomness:
13099 // In the case of a network administrator turning on an Ethernet hub so that all the
13100 // connected machines establish link at exactly the same time, we don't want them all
13101 // to go and hit the network with identical queries at exactly the same moment.
13102 // We set a random delay of up to InitialQuestionInterval (1/3 second).
13103 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13104 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13105 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13106 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13107 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13108 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
13110 if (m
->SuppressProbes
== 0 ||
13111 m
->SuppressProbes
- NonZeroTime(m
->timenow
+ probedelay
) < 0)
13112 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ probedelay
);
13115 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13116 // it here also handles the wake up case as the network link comes UP after waking causing
13117 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13118 // that the network link comes UP after 60 seconds and we never set the OWNER option
13119 m
->AnnounceOwner
= NonZeroTime(m
->timenow
+ 60 * mDNSPlatformOneSecond
);
13120 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "mDNS_RegisterInterface: Setting AnnounceOwner");
13122 m
->mDNSStats
.InterfaceUp
++;
13123 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
13125 if (mDNSOpaque16IsZero(q
->TargetQID
))
13127 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
13128 { // then reactivate this question
13129 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13130 // If flapping, delay between first and second queries is nine seconds instead of one second
13131 mDNSBool dodelay
= (activationSpeed
== SlowActivation
) && (q
->FlappingInterface1
== set
->InterfaceID
|| q
->FlappingInterface2
== set
->InterfaceID
);
13132 mDNSs32 initial
= dodelay
? InitialQuestionInterval
* QuestionIntervalStep2
: InitialQuestionInterval
;
13133 mDNSs32 qdelay
= dodelay
? kDefaultQueryDelayTimeForFlappingInterface
: 0;
13134 if (dodelay
) LogInfo("No cache records expired for %##s (%s); delaying questions by %d seconds", q
->qname
.c
, DNSTypeName(q
->qtype
), qdelay
);
13136 mDNSs32 initial
= InitialQuestionInterval
;
13137 mDNSs32 qdelay
= 0;
13140 if (!q
->ThisQInterval
|| q
->ThisQInterval
> initial
)
13142 q
->ThisQInterval
= initial
;
13143 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
13145 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ qdelay
;
13146 q
->RecentAnswerPkts
= 0;
13147 SetNextQueryTime(m
,q
);
13152 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13153 // we now need them to re-probe if necessary, and then re-announce.
13154 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13156 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13158 mDNSCoreRestartRegistration(m
, rr
, numannounce
);
13161 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
13166 RestartRecordGetZoneData(m
);
13168 mDNS_UpdateAllowSleep(m
);
13171 return(mStatus_NoError
);
13174 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13175 // the record list and/or question list.
13176 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13177 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, InterfaceActivationSpeed activationSpeed
)
13179 #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13180 (void)activationSpeed
; // Unused parameter
13182 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
13183 mDNSBool revalidate
= mDNSfalse
;
13184 NetworkInterfaceInfo
*primary
;
13185 NetworkInterfaceInfo
*intf
;
13190 // Find this record in our list
13191 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
13192 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
13194 mDNS_DeactivateNetWake_internal(m
, set
);
13196 // Unlink this record from our list
13198 set
->next
= mDNSNULL
;
13200 if (!set
->InterfaceActive
)
13202 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13203 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13204 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
13205 UpdateInterfaceProtocols(m
, intf
);
13209 intf
= FirstInterfaceForID(m
, set
->InterfaceID
);
13212 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %d %s (%#a) exists;"
13213 " making it active", IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13214 if (intf
->InterfaceActive
)
13215 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set
->ifname
, &set
->ip
);
13216 intf
->InterfaceActive
= mDNStrue
;
13217 UpdateInterfaceProtocols(m
, intf
);
13219 if (intf
->NetWake
) mDNS_ActivateNetWake_internal(m
, intf
);
13221 // See if another representative *of the same type* exists. If not, we mave have gone from
13222 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13223 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13224 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
13226 if (!intf
) revalidate
= mDNStrue
;
13235 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %d %s (%#a) deregistered;"
13236 " marking questions etc. dormant", IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13238 m
->mDNSStats
.InterfaceDown
++;
13240 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13241 if (set
->McastTxRx
&& (activationSpeed
== SlowActivation
))
13243 LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
13244 m
->mDNSStats
.InterfaceDownFlap
++;
13248 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13249 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13250 for (q
= m
->Questions
; q
; q
=q
->next
)
13252 if (mDNSOpaque16IsZero(q
->TargetQID
)) // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.)
13254 if (q
->InterfaceID
== set
->InterfaceID
) q
->ThisQInterval
= 0;
13255 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
)
13257 q
->FlappingInterface2
= q
->FlappingInterface1
;
13258 q
->FlappingInterface1
= set
->InterfaceID
; // Keep history of the last two interfaces to go away
13263 // 2. Flush any cache records received on this interface
13264 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
13265 FORALL_CACHERECORDS(slot
, cg
, rr
)
13267 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13269 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13270 // If this interface is deemed flapping,
13271 // postpone deleting the cache records in case the interface comes back again
13272 if (set
->McastTxRx
&& (activationSpeed
== SlowActivation
))
13274 // For a flapping interface we want these records to go away after
13275 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13276 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13277 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13278 // if the interface does come back, any relevant questions will be reactivated anyway
13279 rr
->UnansweredQueries
= MaxUnansweredQueries
;
13284 rr
->resrec
.mortality
= Mortality_Mortal
;
13285 mDNS_PurgeCacheResourceRecord(m
, rr
);
13292 // If we still have address records referring to this one, update them.
13293 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13294 // so the call to FindFirstAdvertisedInterface() won’t accidentally find it.
13295 primary
= FindFirstAdvertisedInterface(m
);
13296 A
= primary
? &primary
->RR_A
: mDNSNULL
;
13297 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13298 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
13299 intf
->RR_A
.RRSet
= A
;
13301 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13302 if (set
->Advertise
) DeadvertiseInterface(m
, set
, kDeadvertiseFlag_All
);
13304 // If we have any cache records received on this interface that went away, then re-verify them.
13305 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13306 // giving the false impression that there's an active representative of this interface when there really isn't.
13307 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13308 if (revalidate
&& !m
->ShutdownTime
)
13313 FORALL_CACHERECORDS(slot
, cg
, rr
)
13314 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13315 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13318 mDNS_UpdateAllowSleep(m
);
13323 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13325 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13326 (void)m
; // Unused parameter
13330 char *msg
= "Unknown result";
13331 if (result
== mStatus_NoError
) msg
= "Name Registered";
13332 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
13333 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
13334 debugf("ServiceCallback: %##s (%s) %s (%d)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
13338 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13339 if (result
== mStatus_NoError
&& rr
!= &sr
->RR_SRV
) return;
13341 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13342 if (result
== mStatus_NameConflict
)
13344 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
13345 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
13349 if (result
== mStatus_MemFree
)
13351 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13352 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13353 // every record is finished cleaning up.
13355 ExtraResourceRecord
*e
= sr
->Extras
;
13357 if (sr
->RR_SRV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13358 if (sr
->RR_TXT
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13359 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13360 if (sr
->RR_ADV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13361 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13365 if (e
->r
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13369 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13370 // then we can now report the NameConflict to the client
13371 if (sr
->Conflict
) result
= mStatus_NameConflict
;
13375 LogInfo("ServiceCallback: All records %s for %##s", (result
== mStatus_MemFree
? "Unregistered" : "Registered"), sr
->RR_PTR
.resrec
.name
->c
);
13376 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13377 // function is allowed to do anything, including deregistering this service and freeing its memory.
13378 if (sr
->ServiceCallback
)
13379 sr
->ServiceCallback(m
, sr
, result
);
13382 mDNSlocal
void NSSCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13384 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13385 if (sr
->ServiceCallback
)
13386 sr
->ServiceCallback(m
, sr
, result
);
13390 // Derive AuthRecType from the kDNSServiceFlags* values.
13391 mDNSlocal AuthRecType
setAuthRecType(mDNSInterfaceID InterfaceID
, mDNSu32 flags
)
13393 AuthRecType artype
;
13395 if (InterfaceID
== mDNSInterface_LocalOnly
)
13396 artype
= AuthRecordLocalOnly
;
13397 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13398 artype
= AuthRecordP2P
;
13399 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
)
13400 && (flags
& kDNSServiceFlagsIncludeAWDL
))
13401 artype
= AuthRecordAnyIncludeAWDLandP2P
;
13402 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
))
13403 artype
= AuthRecordAnyIncludeP2P
;
13404 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeAWDL
))
13405 artype
= AuthRecordAnyIncludeAWDL
;
13407 artype
= AuthRecordAny
;
13413 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13414 // Type is service type (e.g. "_ipp._tcp.")
13415 // Domain is fully qualified domain name (i.e. ending with a null label)
13416 // We always register a TXT, even if it is empty (so that clients are not
13417 // left waiting forever looking for a nonexistent record.)
13418 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13419 // then the default host name (m->MulticastHostname) is automatically used
13420 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13421 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
13422 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13423 const domainname
*const host
, mDNSIPPort port
, RData
*const txtrdata
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
13424 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
13425 mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
, mDNSu32 flags
)
13429 AuthRecType artype
;
13430 mDNSu8 recordType
= (flags
& kDNSServiceFlagsKnownUnique
) ? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
13432 sr
->ServiceCallback
= Callback
;
13433 sr
->ServiceContext
= Context
;
13434 sr
->Conflict
= mDNSfalse
;
13436 sr
->Extras
= mDNSNULL
;
13437 sr
->NumSubTypes
= NumSubTypes
;
13438 sr
->SubTypes
= SubTypes
;
13441 artype
= setAuthRecType(InterfaceID
, flags
);
13443 // Initialize the AuthRecord objects to sane values
13444 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13445 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeAdvisory
, artype
, ServiceCallback
, sr
);
13446 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13448 if (flags
& kDNSServiceFlagsWakeOnlyService
)
13450 sr
->RR_PTR
.AuthFlags
= AuthFlagsWakeOnly
;
13453 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, recordType
, artype
, ServiceCallback
, sr
);
13454 mDNS_SetupResourceRecord(&sr
->RR_TXT
, txtrdata
, InterfaceID
, kDNSType_TXT
, kStandardTTL
, recordType
, artype
, ServiceCallback
, sr
);
13456 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13457 if (mDNSIPPortIsZero(port
))
13458 return(mDNS_RegisterNoSuchService(m
, &sr
->RR_SRV
, name
, type
, domain
, mDNSNULL
, InterfaceID
, NSSCallback
, sr
, flags
));
13460 // If the caller is registering an oversized TXT record,
13461 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13462 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
13463 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
13465 // Set up the record names
13466 // For now we only create an advisory record for the main type, not for subtypes
13467 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13468 if (ConstructServiceName(&sr
->RR_ADV
.namestorage
, (const domainlabel
*)"\x09_services", (const domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
13469 return(mStatus_BadParamErr
);
13470 if (ConstructServiceName(&sr
->RR_PTR
.namestorage
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13471 if (ConstructServiceName(&sr
->RR_SRV
.namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13472 AssignDomainName(&sr
->RR_TXT
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13474 // 1. Set up the ADV record rdata to advertise our service type
13475 AssignDomainName(&sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
13477 // 2. Set up the PTR record rdata to point to our service name
13478 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13479 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13480 AssignDomainName(&sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
13481 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
13482 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
13484 // 2a. Set up any subtype PTRs to point to our service name
13485 // If the client is using subtypes, it is the client's responsibility to have
13486 // already set the first label of the record name to the subtype being registered
13487 for (i
=0; i
<NumSubTypes
; i
++)
13490 AssignDomainName(&st
, sr
->SubTypes
[i
].resrec
.name
);
13491 st
.c
[1+st
.c
[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13492 AppendDomainName(&st
, type
);
13493 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13494 if (ConstructServiceName(&sr
->SubTypes
[i
].namestorage
, mDNSNULL
, &st
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13495 AssignDomainName(&sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, &sr
->RR_SRV
.namestorage
);
13496 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
13497 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
13500 // 3. Set up the SRV record rdata.
13501 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
13502 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
13503 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
13505 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13506 if (host
&& host
->c
[0]) AssignDomainName(&sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, host
);
13507 else { sr
->RR_SRV
.AutoTarget
= Target_AutoHost
; sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = '\0'; }
13509 // 4. Set up the TXT record rdata,
13510 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13511 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13512 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
13513 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
13515 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
13516 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
13517 mDNSPlatformMemCopy(sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtinfo
, txtlen
);
13519 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
13522 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13523 // that if the SRV cannot find a target, rest of the records that belong to this service
13524 // will not be activated.
13525 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
13526 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13527 // any list and hence no need to deregister. We could probably do similar checks for other
13528 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13534 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
13535 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13536 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13537 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13538 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13539 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13540 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
13541 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
13542 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
13546 if (err
) mDNS_DeregisterService(m
, sr
);
13550 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
13551 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
, mDNSu32 flags
)
13553 ExtraResourceRecord
**e
;
13555 AuthRecType artype
;
13556 mDNSInterfaceID InterfaceID
= sr
->RR_PTR
.resrec
.InterfaceID
;
13557 ResourceRecord
*rr
;
13559 artype
= setAuthRecType(InterfaceID
, flags
);
13561 extra
->next
= mDNSNULL
;
13562 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
,
13563 extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, artype
, ServiceCallback
, sr
);
13564 AssignDomainName(&extra
->r
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13568 if (extra
->r
.resrec
.rrtype
== kDNSType_TXT
)
13570 if (sr
->RR_TXT
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_TXT
.resrec
;
13572 else if (extra
->r
.resrec
.rrtype
== kDNSType_SRV
)
13574 if (sr
->RR_SRV
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_SRV
.resrec
;
13579 ExtraResourceRecord
*srExtra
;
13581 for (srExtra
= sr
->Extras
; srExtra
; srExtra
= srExtra
->next
)
13583 if ((srExtra
->r
.resrec
.rrtype
== extra
->r
.resrec
.rrtype
) && (srExtra
->r
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
13585 rr
= &srExtra
->r
.resrec
;
13591 if (rr
&& (extra
->r
.resrec
.rroriginalttl
!= rr
->rroriginalttl
))
13593 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13594 extra
->r
.resrec
.rroriginalttl
, rr
->rroriginalttl
, RRDisplayString(m
, &extra
->r
.resrec
));
13595 extra
->r
.resrec
.rroriginalttl
= rr
->rroriginalttl
;
13599 while (*e
) e
= &(*e
)->next
;
13601 extra
->r
.DependentOn
= &sr
->RR_SRV
;
13603 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13604 extra
->r
.resrec
.name
->c
, DNSTypeName(extra
->r
.resrec
.rrtype
), extra
->r
.resrec
.rdlength
);
13606 status
= mDNS_Register_internal(m
, &extra
->r
);
13607 if (status
== mStatus_NoError
) *e
= extra
;
13613 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
,
13614 mDNSRecordCallback MemFreeCallback
, void *Context
)
13616 ExtraResourceRecord
**e
;
13621 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
13624 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
->c
);
13625 status
= mStatus_BadReferenceErr
;
13629 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
->c
);
13630 extra
->r
.RecordCallback
= MemFreeCallback
;
13631 extra
->r
.RecordContext
= Context
;
13633 status
= mDNS_Deregister_internal(m
, &extra
->r
, mDNS_Dereg_normal
);
13639 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
13641 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13642 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13643 domainlabel name1
, name2
;
13644 domainname type
, domain
;
13645 const domainname
*host
= sr
->RR_SRV
.AutoTarget
? mDNSNULL
: &sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
13646 ExtraResourceRecord
*extras
= sr
->Extras
;
13649 DeconstructServiceName(sr
->RR_SRV
.resrec
.name
, &name1
, &type
, &domain
);
13653 IncrementLabelSuffix(&name2
, mDNStrue
);
13657 if (SameDomainName(&domain
, &localdomain
))
13658 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type
.c
, name1
.c
, newname
->c
);
13659 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type
.c
, domain
.c
, name1
.c
, newname
->c
);
13661 // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made
13662 // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration.
13663 if (sr
->RR_TXT
.NewRData
) CompleteRDataUpdate(m
, &sr
->RR_TXT
);
13664 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
13665 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
,
13666 (sr
->RR_TXT
.resrec
.rdata
!= &sr
->RR_TXT
.rdatastorage
) ? sr
->RR_TXT
.resrec
.rdata
: mDNSNULL
,
13667 sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
13668 sr
->SubTypes
, sr
->NumSubTypes
,
13669 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
, sr
->flags
);
13671 // mDNS_RegisterService() just reset sr->Extras to NULL.
13672 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13673 // through the old list of extra records, and re-add them to our freshly created service registration
13674 while (!err
&& extras
)
13676 ExtraResourceRecord
*e
= extras
;
13677 extras
= extras
->next
;
13678 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
, 0);
13684 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13685 // which may change the record list and/or question list.
13686 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13687 mDNSexport mStatus
mDNS_DeregisterService_drt(mDNS
*const m
, ServiceRecordSet
*sr
, mDNS_Dereg_type drt
)
13689 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13690 if (mDNSIPPortIsZero(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
)) return(mDNS_DeregisterNoSuchService(m
, &sr
->RR_SRV
));
13692 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
13694 debugf("Service set for %##s already deregistered", sr
->RR_SRV
.resrec
.name
->c
);
13695 return(mStatus_BadReferenceErr
);
13697 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
13699 LogInfo("Service set for %##s already in the process of deregistering", sr
->RR_SRV
.resrec
.name
->c
);
13700 // Avoid race condition:
13701 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13702 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13703 // If the client happens to deregister the service in the middle of that process, then
13704 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13705 // instead of incorrectly promoting it to mStatus_NameConflict.
13706 // This race condition is exposed particularly when the conformance test generates
13707 // a whole batch of simultaneous conflicts across a range of services all advertised
13708 // using the same system default name, and if we don't take this precaution then
13709 // we end up incrementing m->nicelabel multiple times instead of just once.
13710 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13711 sr
->Conflict
= mDNSfalse
;
13712 return(mStatus_NoError
);
13718 ExtraResourceRecord
*e
;
13722 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13723 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13724 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
13725 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
13726 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, drt
);
13728 // We deregister all of the extra records, but we leave the sr->Extras list intact
13729 // in case the client wants to do a RenameAndReregister and reinstate the registration
13732 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
13736 for (i
=0; i
<sr
->NumSubTypes
; i
++)
13737 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], drt
);
13739 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, drt
);
13745 // Create a registration that asserts that no such service exists with this name.
13746 // This can be useful where there is a given function is available through several protocols.
13747 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13748 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13749 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13750 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13751 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
13752 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13753 const domainname
*const host
,
13754 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
, mDNSu32 flags
)
13756 AuthRecType artype
;
13758 artype
= setAuthRecType(InterfaceID
, flags
);
13760 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, artype
, Callback
, Context
);
13761 if (ConstructServiceName(&rr
->namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13762 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
13763 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
13764 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
13765 if (host
&& host
->c
[0]) AssignDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, host
);
13766 else rr
->AutoTarget
= Target_AutoHost
;
13767 return(mDNS_Register(m
, rr
));
13770 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
13771 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
13773 AuthRecType artype
;
13775 if (InterfaceID
== mDNSInterface_LocalOnly
)
13776 artype
= AuthRecordLocalOnly
;
13777 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13778 artype
= AuthRecordP2P
;
13780 artype
= AuthRecordAny
;
13781 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, mDNSNULL
, mDNSNULL
);
13782 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
13783 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
13784 return(mDNS_Register(m
, rr
));
13787 mDNSlocal mDNSBool
mDNS_IdUsedInResourceRecordsList(mDNS
* const m
, mDNSOpaque16 id
)
13790 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (mDNSSameOpaque16(id
, r
->updateid
)) return mDNStrue
;
13794 mDNSlocal mDNSBool
mDNS_IdUsedInQuestionsList(mDNS
* const m
, mDNSOpaque16 id
)
13797 for (q
= m
->Questions
; q
; q
=q
->next
) if (mDNSSameOpaque16(id
, q
->TargetQID
)) return mDNStrue
;
13801 mDNSexport mDNSOpaque16
mDNS_NewMessageID(mDNS
* const m
)
13806 for (i
=0; i
<10; i
++)
13808 id
= mDNSOpaque16fromIntVal(1 + (mDNSu16
)mDNSRandom(0xFFFE));
13809 if (!mDNS_IdUsedInResourceRecordsList(m
, id
) && !mDNS_IdUsedInQuestionsList(m
, id
)) break;
13812 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id
));
13817 // ***************************************************************************
13818 #if COMPILER_LIKES_PRAGMA_MARK
13820 #pragma mark - Sleep Proxy Server
13823 mDNSlocal
void RestartARPProbing(mDNS
*const m
, AuthRecord
*const rr
)
13825 // If we see an ARP from a machine we think is sleeping, then either
13826 // (i) the machine has woken, or
13827 // (ii) it's just a stray old packet from before the machine slept
13828 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13829 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13830 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13831 // If it was a stray old packet, then after 10 seconds we'll probe again and then start answering ARPs again. In this case we *do*
13832 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13833 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13835 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
13836 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
13837 rr
->ProbeRestartCount
++;
13839 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13840 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13841 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13842 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13843 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13844 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13845 if (rr
->AnnounceCount
== InitialAnnounceCount
&& m
->timenow
- rr
->LastAPTime
>= 0)
13846 InitializeLastAPTime(m
, rr
);
13849 rr
->AnnounceCount
= InitialAnnounceCount
;
13850 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
13851 rr
->LastAPTime
= m
->timenow
+ mDNSPlatformOneSecond
* 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13852 SetNextAnnounceProbeTime(m
, rr
);
13856 mDNSlocal
void mDNSCoreReceiveRawARP(mDNS
*const m
, const ARP_EthIP
*const arp
, const mDNSInterfaceID InterfaceID
)
13858 static const mDNSOpaque16 ARP_op_request
= { { 0, 1 } };
13860 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
13866 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13867 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13868 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13869 // The times we might need to react to an ARP Announcement are:
13870 // (i) as an indication that the host in question has not gone to sleep yet (so we should delay beginning to proxy for it) or
13871 // (ii) if it's a conflicting Announcement from another host
13872 // -- and we check for these in Pass 2 below.
13873 if (mDNSSameOpaque16(arp
->op
, ARP_op_request
) && !mDNSSameIPv4Address(arp
->spa
, arp
->tpa
))
13875 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13876 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13877 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->tpa
))
13879 static const char msg1
[] = "ARP Req from owner -- re-probing";
13880 static const char msg2
[] = "Ignoring ARP Request from ";
13881 static const char msg3
[] = "Creating Local ARP Cache entry ";
13882 static const char msg4
[] = "Answering ARP Request from ";
13883 const char *const msg
= mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
13884 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
13885 mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
) ? msg3
: msg4
;
13886 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13887 intf
->ifname
, msg
, arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
,
13888 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13891 if ( rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
13892 RestartARPProbing(m
, rr
);
13894 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
13896 else if (msg
== msg3
)
13898 mDNSPlatformSetLocalAddressCacheEntry(&rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
13900 else if (msg
== msg4
)
13902 SendARP(m
, 2, rr
, (mDNSv4Addr
*)arp
->tpa
.b
, &arp
->sha
, (mDNSv4Addr
*)arp
->spa
.b
, &arp
->sha
);
13908 // For all types of ARP packet we check the Sender IP address to make sure it doesn't conflict with any AddressProxy record we're holding.
13909 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13910 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13911 // We ignore ARPs we sent ourselves (Sender MAC address is our MAC address) because our own proxy ARPs do not constitute a conflict that we need to handle.
13912 // If we see an apparently conflicting ARP, we check the sender hardware address:
13913 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13914 // If the sender hardware address is *not* the original owner, then this is a conflict, and we need to wake the sleeping machine to handle it.
13915 if (mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
))
13916 debugf("ARP from self for %.4a", arp
->tpa
.b
);
13919 if (!mDNSSameIPv4Address(arp
->spa
, zerov4Addr
))
13920 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13921 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13922 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
13924 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
13926 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
13927 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13931 RestartARPProbing(m
, rr
);
13932 if (mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
))
13934 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf
->ifname
,
13935 mDNSSameIPv4Address(arp
->spa
, arp
->tpa
) ? "Announcement " : mDNSSameOpaque16(arp
->op
, ARP_op_request
) ? "Request " : "Response ",
13936 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, ARDisplayString(m
, rr
));
13940 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
13941 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13942 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
13952 // Option 1 is Source Link Layer Address Option
13953 // Option 2 is Target Link Layer Address Option
13954 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
13956 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
13957 while (options < end)
13959 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
13960 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
13961 options += options[1] * 8;
13967 mDNSlocal
void mDNSCoreReceiveRawND(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSv6Addr
*spa
,
13968 const IPv6NDP
*const ndp
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
13971 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
13976 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
13977 if (ndp
->type
== NDP_Sol
)
13979 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
13981 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13982 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13983 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, ndp
->target
))
13985 static const char msg1
[] = "NDP Req from owner -- re-probing";
13986 static const char msg2
[] = "Ignoring NDP Request from ";
13987 static const char msg3
[] = "Creating Local NDP Cache entry ";
13988 static const char msg4
[] = "Answering NDP Request from ";
13989 static const char msg5
[] = "Answering NDP Probe from ";
13990 const char *const msg
= mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
13991 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
13992 mDNSSameEthAddress(sha
, &intf
->MAC
) ? msg3
:
13993 mDNSIPv6AddressIsZero(*spa
) ? msg4
: msg5
;
13994 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
13995 intf
->ifname
, msg
, sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13998 if (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
13999 RestartARPProbing(m
, rr
);
14001 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
14003 else if (msg
== msg3
)
14004 mDNSPlatformSetLocalAddressCacheEntry(&rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
14005 else if (msg
== msg4
)
14006 SendNDP(m
, NDP_Adv
, NDP_Solicited
, rr
, &ndp
->target
, mDNSNULL
, spa
, sha
);
14007 else if (msg
== msg5
)
14008 SendNDP(m
, NDP_Adv
, 0, rr
, &ndp
->target
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
14012 // Pass 2: For all types of NDP packet we check the Sender IP address to make sure it doesn't conflict with any AddressProxy record we're holding.
14013 if (mDNSSameEthAddress(sha
, &intf
->MAC
))
14014 debugf("NDP from self for %.16a", &ndp
->target
);
14017 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14018 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14019 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14020 // Hence it is the NDP target address we care about, not the actual packet source address.
14021 if (ndp
->type
== NDP_Adv
) spa
= &ndp
->target
;
14022 if (!mDNSSameIPv6Address(*spa
, zerov6Addr
))
14023 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14024 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14025 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, *spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
14027 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
14029 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14030 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14034 RestartARPProbing(m
, rr
);
14035 if (mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
))
14037 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf
->ifname
,
14038 ndp
->type
== NDP_Sol
? "Solicitation " : "Advertisement", sha
, spa
, &ndp
->target
, ARDisplayString(m
, rr
));
14042 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14043 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14044 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14053 mDNSlocal
void mDNSCoreReceiveRawTransportPacket(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSAddr
*const src
, const mDNSAddr
*const dst
, const mDNSu8 protocol
,
14054 const mDNSu8
*const p
, const TransportLayerPacket
*const t
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
, const mDNSu16 len
)
14056 const mDNSIPPort port
= (protocol
== 0x06) ? t
->tcp
.dst
: (protocol
== 0x11) ? t
->udp
.dst
: zeroIPPort
;
14057 mDNSBool wake
= mDNSfalse
;
14058 mDNSBool kaWake
= mDNSfalse
;
14062 #define XX wake ? "Received" : "Ignoring", end-p
14063 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end
-p
, src
, dst
);
14069 #define TH_FIN 0x01
14070 #define TH_SYN 0x02
14071 #define TH_RST 0x04
14072 #define TH_ACK 0x10
14074 kr
= mDNS_MatchKeepaliveInfo(m
, dst
, src
, port
, t
->tcp
.src
, &seq
, &ack
);
14077 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
));
14079 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14080 // (b) packet that contains new data and acks a sequence number higher than the one
14081 // we have been sending in the keepalive
14083 wake
= ((t
->tcp
.flags
& TH_RST
) || (t
->tcp
.flags
& TH_FIN
)) ;
14087 mDNSu32 pseq
, pack
;
14088 mDNSBool data
= mDNSfalse
;
14091 // Convert to host order
14092 ptr
= (mDNSu8
*)&seq
;
14093 seq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14095 ptr
= (mDNSu8
*)&ack
;
14096 ack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14099 ptr
= (mDNSu8
*)&pseq
;
14100 pseq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14103 ptr
= (mDNSu8
*)&pack
;
14104 pack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14106 // If the other side is acking one more than our sequence number (keepalive is one
14107 // less than the last valid sequence sent) and it's sequence is more than what we
14109 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14110 tcphlen
= ((t
->tcp
.offset
>> 4) * 4);
14111 if (end
- ((mDNSu8
*)t
+ tcphlen
) > 0) data
= mDNStrue
;
14112 wake
= ((int)(pack
- seq
) > 0) && ((int)(pseq
- ack
) >= 0) && data
;
14114 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14115 if ((t
->tcp
.flags
& TH_ACK
) && (data
== mDNSfalse
) &&
14116 ((int)(ack
- pseq
) == 1))
14119 mDNS_SendKeepaliveACK(m
, kr
);
14121 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14122 end
, tcphlen
, end
- ((mDNSu8
*)t
+ tcphlen
), pack
, seq
, pseq
, ack
, wake
);
14124 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t
->tcp
.flags
); }
14130 // (a) RST is not set, AND
14131 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14132 wake
= (!(t
->tcp
.flags
& TH_RST
) && (t
->tcp
.flags
& (TH_FIN
|TH_SYN
)) != TH_FIN
);
14134 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14135 // except for ssh connections, where we'll wake for plain data packets too
14136 if (!mDNSSameIPPort(port
, SSHPort
) && !(t
->tcp
.flags
& 2)) wake
= mDNSfalse
;
14138 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX
,
14139 src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
),
14140 (t
->tcp
.flags
& 2) ? " SYN" : "",
14141 (t
->tcp
.flags
& 1) ? " FIN" : "",
14142 (t
->tcp
.flags
& 4) ? " RST" : "");
14148 #define ARD_AsNumber 3283
14149 static const mDNSIPPort ARD
= { { ARD_AsNumber
>> 8, ARD_AsNumber
& 0xFF } };
14150 const mDNSu16 udplen
= (mDNSu16
)((mDNSu16
)t
->bytes
[4] << 8 | t
->bytes
[5]); // Length *including* 8-byte UDP header
14151 if (udplen
>= sizeof(UDPHeader
))
14153 const mDNSu16 datalen
= udplen
- sizeof(UDPHeader
);
14156 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14157 if (mDNSSameIPPort(port
, IPSECPort
))
14159 // Specifically ignore NAT keepalive packets
14160 if (datalen
== 1 && end
>= &t
->bytes
[9] && t
->bytes
[8] == 0xFF) wake
= mDNSfalse
;
14163 // Skip over the Non-ESP Marker if present
14164 const mDNSBool NonESP
= (end
>= &t
->bytes
[12] && t
->bytes
[8] == 0 && t
->bytes
[9] == 0 && t
->bytes
[10] == 0 && t
->bytes
[11] == 0);
14165 const IKEHeader
*const ike
= (IKEHeader
*)(t
+ (NonESP
? 12 : 8));
14166 const mDNSu16 ikelen
= datalen
- (NonESP
? 4 : 0);
14167 if (ikelen
>= sizeof(IKEHeader
) && end
>= ((mDNSu8
*)ike
) + sizeof(IKEHeader
))
14168 if ((ike
->Version
& 0x10) == 0x10)
14170 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14171 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14172 if (ike
->ExchangeType
== 5 || ike
->ExchangeType
== 34) wake
= mDNSfalse
;
14173 LogSPS("%s %d-byte IKE ExchangeType %d", XX
, ike
->ExchangeType
);
14178 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14179 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14180 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14181 // UDP header (8 bytes)
14182 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14183 if (mDNSSameIPPort(port
, ARD
)) wake
= (datalen
>= 110 && end
>= &t
->bytes
[10] && t
->bytes
[8] == 0x13 && t
->bytes
[9] == 0x88);
14185 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX
, src
, mDNSVal16(t
->udp
.src
), dst
, mDNSVal16(port
));
14190 case 0x3A: if (&t
->bytes
[len
] <= end
)
14192 mDNSu16 checksum
= IPv6CheckSum(&src
->ip
.v6
, &dst
->ip
.v6
, protocol
, t
->bytes
, len
);
14193 if (!checksum
) mDNSCoreReceiveRawND(m
, sha
, &src
->ip
.v6
, &t
->ndp
, &t
->bytes
[len
], InterfaceID
);
14194 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum
, t
->bytes
[2], t
->bytes
[3], src
, dst
);
14198 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end
-p
, protocol
, src
, dst
);
14204 AuthRecord
*rr
, *r2
;
14207 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14208 if (rr
->resrec
.InterfaceID
== InterfaceID
&&
14209 rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14210 rr
->AddressProxy
.type
&& mDNSSameAddress(&rr
->AddressProxy
, dst
))
14212 const mDNSu8
*const tp
= (protocol
== 6) ? (const mDNSu8
*)"\x4_tcp" : (const mDNSu8
*)"\x4_udp";
14213 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
14214 if (r2
->resrec
.InterfaceID
== InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.HMAC
, &rr
->WakeUp
.HMAC
) &&
14215 r2
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14216 r2
->resrec
.rrtype
== kDNSType_SRV
&& mDNSSameIPPort(r2
->resrec
.rdata
->u
.srv
.port
, port
) &&
14217 SameDomainLabel(ThirdLabel(r2
->resrec
.name
)->c
, tp
))
14219 if (!r2
&& mDNSSameIPPort(port
, IPSECPort
)) r2
= rr
; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14220 if (!r2
&& kaWake
) r2
= rr
; // So that we wake for keepalive packets, even without a matching SRV record
14223 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14224 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, r2
));
14225 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14228 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14229 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, tp
, mDNSVal16(port
));
14235 mDNSexport
void mDNSCoreReceiveRawPacket(mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
14237 static const mDNSOpaque16 Ethertype_ARP
= { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14238 static const mDNSOpaque16 Ethertype_IPv4
= { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14239 static const mDNSOpaque16 Ethertype_IPv6
= { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14240 static const mDNSOpaque16 ARP_hrd_eth
= { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14241 static const mDNSOpaque16 ARP_pro_ip
= { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14243 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14244 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14245 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14246 // since it points to a an address 14 bytes before pkt.
14247 const EthernetHeader
*const eth
= (const EthernetHeader
*)p
;
14248 const NetworkLayerPacket
*const pkt
= (const NetworkLayerPacket
*)(eth
+1);
14250 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14252 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14253 if (end
>= p
+42 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_ARP
) && mDNSSameOpaque16(pkt
->arp
.hrd
, ARP_hrd_eth
) && mDNSSameOpaque16(pkt
->arp
.pro
, ARP_pro_ip
))
14254 mDNSCoreReceiveRawARP(m
, &pkt
->arp
, InterfaceID
);
14255 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14256 else if (end
>= p
+34 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv4
) && (pkt
->v4
.flagsfrags
.b
[0] & 0x1F) == 0 && pkt
->v4
.flagsfrags
.b
[1] == 0)
14258 const mDNSu8
*const trans
= p
+ 14 + (pkt
->v4
.vlen
& 0xF) * 4;
14259 const mDNSu8
* transEnd
= p
+ 14 + mDNSVal16(pkt
->v4
.totlen
);
14260 if (transEnd
> end
) transEnd
= end
;
14261 debugf("Got IPv4 %02X from %.4a to %.4a", pkt
->v4
.protocol
, &pkt
->v4
.src
.b
, &pkt
->v4
.dst
.b
);
14262 src
.type
= mDNSAddrType_IPv4
; src
.ip
.v4
= pkt
->v4
.src
;
14263 dst
.type
= mDNSAddrType_IPv4
; dst
.ip
.v4
= pkt
->v4
.dst
;
14264 if (transEnd
>= trans
+ RequiredCapLen(pkt
->v4
.protocol
))
14265 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v4
.protocol
, p
, (TransportLayerPacket
*)trans
, transEnd
, InterfaceID
, 0);
14267 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14268 else if (end
>= p
+54 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv6
))
14270 const mDNSu8
*const trans
= p
+ 54;
14271 debugf("Got IPv6 %02X from %.16a to %.16a", pkt
->v6
.pro
, &pkt
->v6
.src
.b
, &pkt
->v6
.dst
.b
);
14272 src
.type
= mDNSAddrType_IPv6
; src
.ip
.v6
= pkt
->v6
.src
;
14273 dst
.type
= mDNSAddrType_IPv6
; dst
.ip
.v6
= pkt
->v6
.dst
;
14274 if (end
>= trans
+ RequiredCapLen(pkt
->v6
.pro
))
14275 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v6
.pro
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
,
14276 (mDNSu16
)pkt
->bytes
[4] << 8 | pkt
->bytes
[5]);
14280 mDNSlocal
void ConstructSleepProxyServerName(mDNS
*const m
, domainlabel
*name
)
14282 name
->c
[0] = (mDNSu8
)mDNS_snprintf((char*)name
->c
+1, 62, "%d-%d-%d-%d.%d %#s",
14283 m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
, &m
->nicelabel
);
14286 #ifndef SPC_DISABLED
14287 mDNSlocal
void SleepProxyServerCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
14289 if (result
== mStatus_NameConflict
)
14290 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
14291 else if (result
== mStatus_MemFree
)
14297 m
->SPSState
= (mDNSu8
)(m
->SPSSocket
!= mDNSNULL
);
14301 ConstructSleepProxyServerName(m
, &name
);
14302 mDNS_RegisterService(m
, srs
,
14303 &name
, &SleepProxyServiceType
, &localdomain
,
14304 mDNSNULL
, m
->SPSSocket
->port
, // Host, port
14306 (mDNSu8
*)"", 1, // TXT data, length
14307 mDNSNULL
, 0, // Subtypes (none)
14308 mDNSInterface_Any
, // Interface ID
14309 SleepProxyServerCallback
, mDNSNULL
, 0); // Callback, context, flags
14311 LogSPS("Sleep Proxy Server %#s %s", srs
->RR_SRV
.resrec
.name
->c
, m
->SPSState
? "started" : "stopped");
14317 // Called with lock held
14318 mDNSexport
void mDNSCoreBeSleepProxyServer_internal(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
, mDNSu8 features
)
14320 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14321 mDNS_DropLockBeforeCallback();
14323 // If turning off SPS, close our socket
14324 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14325 if (!sps
&& m
->SPSSocket
) { mDNSPlatformUDPClose(m
->SPSSocket
); m
->SPSSocket
= mDNSNULL
; }
14327 // If turning off, or changing type, deregister old name
14328 #ifndef SPC_DISABLED
14329 if (m
->SPSState
== 1 && sps
!= m
->SPSType
)
14330 { m
->SPSState
= 2; mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, sps
? mDNS_Dereg_rapid
: mDNS_Dereg_normal
); }
14331 #endif // SPC_DISABLED
14333 // Record our new SPS parameters
14335 m
->SPSPortability
= port
;
14336 m
->SPSMarginalPower
= marginalpower
;
14337 m
->SPSTotalPower
= totpower
;
14338 m
->SPSFeatureFlags
= features
;
14339 // If turning on, open socket and advertise service
14344 m
->SPSSocket
= mDNSPlatformUDPSocket(zeroIPPort
);
14345 if (!m
->SPSSocket
) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail
; }
14347 #ifndef SPC_DISABLED
14348 if (m
->SPSState
== 0) SleepProxyServerCallback(m
, &m
->SPSRecords
, mStatus_MemFree
);
14349 #endif // SPC_DISABLED
14351 else if (m
->SPSState
)
14353 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m
->SPSState
);
14354 m
->NextScheduledSPS
= m
->timenow
;
14357 mDNS_ReclaimLockAfterCallback();
14360 // ***************************************************************************
14361 #if COMPILER_LIKES_PRAGMA_MARK
14363 #pragma mark - Startup and Shutdown
14366 mDNSlocal
void mDNS_GrowCache_internal(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14368 if (storage
&& numrecords
)
14371 debugf("Adding cache storage for %d more records (%d bytes)", numrecords
, numrecords
*sizeof(CacheEntity
));
14372 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
14373 storage
[numrecords
-1].next
= m
->rrcache_free
;
14374 m
->rrcache_free
= storage
;
14375 m
->rrcache_size
+= numrecords
;
14379 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14382 mDNS_GrowCache_internal(m
, storage
, numrecords
);
14386 mDNSlocal mStatus
mDNS_InitStorage(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
14387 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
14388 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
14394 if (!rrcachestorage
) rrcachesize
= 0;
14396 m
->next_request_id
= 1;
14398 m
->NetworkChanged
= 0;
14399 m
->CanReceiveUnicastOn5353
= mDNSfalse
; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14400 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
14401 m
->DivertMulticastAdvertisements
= mDNSfalse
;
14402 m
->mDNSPlatformStatus
= mStatus_Waiting
;
14403 m
->UnicastPort4
= zeroIPPort
;
14404 m
->UnicastPort6
= zeroIPPort
;
14405 m
->PrimaryMAC
= zeroEthAddr
;
14406 m
->MainCallback
= Callback
;
14407 m
->MainContext
= Context
;
14408 m
->rec
.r
.resrec
.RecordType
= 0;
14410 // For debugging: To catch and report locking failures
14412 m
->mDNS_reentrancy
= 0;
14413 m
->ShutdownTime
= 0;
14414 m
->lock_rrcache
= 0;
14415 m
->lock_Questions
= 0;
14416 m
->lock_Records
= 0;
14418 // Task Scheduling variables
14419 result
= mDNSPlatformTimeInit();
14420 if (result
!= mStatus_NoError
) return(result
);
14421 m
->timenow_adjust
= (mDNSs32
)mDNSRandom(0xFFFFFFFF);
14422 timenow
= mDNS_TimeNow_NoLock(m
);
14424 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14425 m
->timenow_last
= timenow
;
14426 m
->NextScheduledEvent
= timenow
;
14427 m
->SuppressSending
= timenow
;
14428 m
->NextCacheCheck
= timenow
+ FutureTime
;
14429 m
->NextScheduledQuery
= timenow
+ FutureTime
;
14430 m
->NextScheduledProbe
= timenow
+ FutureTime
;
14431 m
->NextScheduledResponse
= timenow
+ FutureTime
;
14432 m
->NextScheduledNATOp
= timenow
+ FutureTime
;
14433 m
->NextScheduledSPS
= timenow
+ FutureTime
;
14434 m
->NextScheduledKA
= timenow
+ FutureTime
;
14435 m
->NextScheduledStopTime
= timenow
+ FutureTime
;
14436 m
->NextBLEServiceTime
= 0; // zero indicates inactive
14438 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14439 m
->NextBonjourDisableTime
= 0; // Timer active when non zero.
14440 m
->BonjourEnabled
= 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14442 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
14443 m
->NextSuspiciousTimeout
= 0;
14446 m
->RandomQueryDelay
= 0;
14447 m
->RandomReconfirmDelay
= 0;
14450 m
->LocalRemoveEvents
= mDNSfalse
;
14451 m
->SleepState
= SleepState_Awake
;
14452 m
->SleepSeqNum
= 0;
14453 m
->SystemWakeOnLANEnabled
= mDNSfalse
;
14454 m
->AnnounceOwner
= NonZeroTime(timenow
+ 60 * mDNSPlatformOneSecond
);
14458 #if APPLE_OSX_mDNSResponder
14459 m
->UnicastPacketsSent
= 0;
14460 m
->MulticastPacketsSent
= 0;
14461 m
->RemoteSubnet
= 0;
14462 #endif // APPLE_OSX_mDNSResponder
14464 // These fields only required for mDNS Searcher...
14465 m
->Questions
= mDNSNULL
;
14466 m
->NewQuestions
= mDNSNULL
;
14467 m
->CurrentQuestion
= mDNSNULL
;
14468 m
->LocalOnlyQuestions
= mDNSNULL
;
14469 m
->NewLocalOnlyQuestions
= mDNSNULL
;
14470 m
->RestartQuestion
= mDNSNULL
;
14471 m
->ValidationQuestion
= mDNSNULL
;
14472 m
->rrcache_size
= 0;
14473 m
->rrcache_totalused
= 0;
14474 m
->rrcache_active
= 0;
14475 m
->rrcache_report
= 10;
14476 m
->rrcache_free
= mDNSNULL
;
14478 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
14480 m
->rrcache_hash
[slot
] = mDNSNULL
;
14481 m
->rrcache_nextcheck
[slot
] = timenow
+ FutureTime
;;
14484 mDNS_GrowCache_internal(m
, rrcachestorage
, rrcachesize
);
14485 m
->rrauth
.rrauth_free
= mDNSNULL
;
14487 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
14488 m
->rrauth
.rrauth_hash
[slot
] = mDNSNULL
;
14490 // Fields below only required for mDNS Responder...
14491 m
->hostlabel
.c
[0] = 0;
14492 m
->nicelabel
.c
[0] = 0;
14493 m
->MulticastHostname
.c
[0] = 0;
14494 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
14495 m
->RandomizedHostname
.c
[0] = 0;
14497 m
->HIHardware
.c
[0] = 0;
14498 m
->HISoftware
.c
[0] = 0;
14499 m
->ResourceRecords
= mDNSNULL
;
14500 m
->DuplicateRecords
= mDNSNULL
;
14501 m
->NewLocalRecords
= mDNSNULL
;
14502 m
->NewLocalOnlyRecords
= mDNSfalse
;
14503 m
->CurrentRecord
= mDNSNULL
;
14504 m
->HostInterfaces
= mDNSNULL
;
14505 m
->ProbeFailTime
= 0;
14506 m
->NumFailedProbes
= 0;
14507 m
->SuppressProbes
= 0;
14509 #ifndef UNICAST_DISABLED
14510 m
->NextuDNSEvent
= timenow
+ FutureTime
;
14511 m
->NextSRVUpdate
= timenow
+ FutureTime
;
14513 m
->DNSServers
= mDNSNULL
;
14515 m
->Router
= zeroAddr
;
14516 m
->AdvertisedV4
= zeroAddr
;
14517 m
->AdvertisedV6
= zeroAddr
;
14519 m
->AuthInfoList
= mDNSNULL
;
14521 m
->ReverseMap
.ThisQInterval
= -1;
14522 m
->StaticHostname
.c
[0] = 0;
14524 m
->Hostnames
= mDNSNULL
;
14526 m
->WABBrowseQueriesCount
= 0;
14527 m
->WABLBrowseQueriesCount
= 0;
14528 m
->WABRegQueriesCount
= 0;
14529 m
->AutoTargetServices
= 0;
14531 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14532 m
->NumAllInterfaceRecords
= 0;
14533 m
->NumAllInterfaceQuestions
= 0;
14535 // NAT traversal fields
14536 m
->LLQNAT
.clientCallback
= mDNSNULL
;
14537 m
->LLQNAT
.clientContext
= mDNSNULL
;
14538 m
->NATTraversals
= mDNSNULL
;
14539 m
->CurrentNATTraversal
= mDNSNULL
;
14540 m
->retryIntervalGetAddr
= 0; // delta between time sent and retry
14541 m
->retryGetAddr
= timenow
+ FutureTime
; // absolute time when we retry
14542 m
->ExtAddress
= zerov4Addr
;
14543 m
->PCPNonce
[0] = mDNSRandom(-1);
14544 m
->PCPNonce
[1] = mDNSRandom(-1);
14545 m
->PCPNonce
[2] = mDNSRandom(-1);
14547 m
->NATMcastRecvskt
= mDNSNULL
;
14548 m
->LastNATupseconds
= 0;
14549 m
->LastNATReplyLocalTime
= timenow
;
14550 m
->LastNATMapResultCode
= NATErr_None
;
14552 m
->UPnPInterfaceID
= 0;
14553 m
->SSDPSocket
= mDNSNULL
;
14554 m
->SSDPWANPPPConnection
= mDNSfalse
;
14555 m
->UPnPRouterPort
= zeroIPPort
;
14556 m
->UPnPSOAPPort
= zeroIPPort
;
14557 m
->UPnPRouterURL
= mDNSNULL
;
14558 m
->UPnPWANPPPConnection
= mDNSfalse
;
14559 m
->UPnPSOAPURL
= mDNSNULL
;
14560 m
->UPnPRouterAddressString
= mDNSNULL
;
14561 m
->UPnPSOAPAddressString
= mDNSNULL
;
14563 m
->SPSPortability
= 0;
14564 m
->SPSMarginalPower
= 0;
14565 m
->SPSTotalPower
= 0;
14566 m
->SPSFeatureFlags
= 0;
14568 m
->SPSProxyListChanged
= mDNSNULL
;
14569 m
->SPSSocket
= mDNSNULL
;
14570 m
->SPSBrowseCallback
= mDNSNULL
;
14571 m
->ProxyRecords
= 0;
14573 m
->DNSPushServers
= mDNSNULL
;
14574 m
->DNSPushZones
= mDNSNULL
;
14577 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
14578 if (WCFConnectionNew
)
14580 m
->WCF
= WCFConnectionNew();
14581 if (!m
->WCF
) { LogMsg("WCFConnectionNew failed"); return -1; }
14588 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
14589 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
14590 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
14592 mStatus result
= mDNS_InitStorage(m
, p
, rrcachestorage
, rrcachesize
, AdvertiseLocalAddresses
, Callback
, Context
);
14593 if (result
!= mStatus_NoError
)
14596 #if MDNS_MALLOC_DEBUGGING
14597 static mDNSListValidator lv
;
14598 mDNSPlatformAddListValidator(&lv
, mDNS_ValidateLists
, "mDNS_ValidateLists", m
);
14600 result
= mDNSPlatformInit(m
);
14602 #ifndef UNICAST_DISABLED
14603 // It's better to do this *after* the platform layer has set up the
14604 // interface list and security credentials
14605 uDNS_SetupDNSConfig(m
); // Get initial DNS configuration
14611 mDNSexport
void mDNS_ConfigChanged(mDNS
*const m
)
14613 if (m
->SPSState
== 1)
14615 domainlabel name
, newname
;
14616 #ifndef SPC_DISABLED
14617 domainname type
, domain
;
14618 DeconstructServiceName(m
->SPSRecords
.RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
14619 #endif // SPC_DISABLED
14620 ConstructSleepProxyServerName(m
, &newname
);
14621 if (!SameDomainLabelCS(name
.c
, newname
.c
))
14623 LogSPS("Renaming SPS from “%#s” to “%#s”", name
.c
, newname
.c
);
14624 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14625 // it will reregister the service under the new name
14627 #ifndef SPC_DISABLED
14628 mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, mDNS_Dereg_rapid
);
14629 #endif // SPC_DISABLED
14633 if (m
->MainCallback
)
14634 m
->MainCallback(m
, mStatus_ConfigChanged
);
14637 mDNSlocal
void DynDNSHostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
14640 debugf("NameStatusCallback: result %d for registration of name %##s", result
, rr
->resrec
.name
->c
);
14641 mDNSPlatformDynDNSHostNameStatusChanged(rr
->resrec
.name
, result
);
14644 mDNSlocal
void PurgeOrReconfirmCacheRecord(mDNS
*const m
, CacheRecord
*cr
)
14646 mDNSBool purge
= cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
||
14647 cr
->resrec
.rrtype
== kDNSType_A
||
14648 cr
->resrec
.rrtype
== kDNSType_AAAA
||
14649 cr
->resrec
.rrtype
== kDNSType_SRV
||
14650 cr
->resrec
.rrtype
== kDNSType_CNAME
;
14652 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s",
14653 purge
? "purging" : "reconfirming",
14654 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
,
14655 cr
->resrec
.rDNSServer
? mDNSVal16(cr
->resrec
.rDNSServer
->port
) : -1,
14656 cr
->resrec
.rDNSServer
? cr
->resrec
.rDNSServer
->domain
.c
: mDNSNULL
, CRDisplayString(m
, cr
));
14660 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14661 cr
->resrec
.mortality
= Mortality_Mortal
;
14662 mDNS_PurgeCacheResourceRecord(m
, cr
);
14666 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14667 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
14671 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
)
14673 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
14675 mDNSu8 validatingResponse
= 0;
14677 // For DNSSEC questions, purge the corresponding RRSIGs also.
14678 if (DNSSECQuestion(q
))
14680 validatingResponse
= q
->ValidatingResponse
;
14681 q
->ValidatingResponse
= mDNStrue
;
14683 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14685 if (SameNameCacheRecordAnswersQuestion(rp
, q
))
14687 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m
, rp
));
14688 mDNS_PurgeCacheResourceRecord(m
, rp
);
14691 if (DNSSECQuestion(q
))
14693 q
->ValidatingResponse
= validatingResponse
;
14697 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14698 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14699 // Just re-issuing the question for RRSIGs does not work in practice as the response
14700 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14702 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14703 // have the cached NSECs, purge them. For positive responses, if we don't have the
14704 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14706 mDNSlocal
void CheckForDNSSECRecords(mDNS
*const m
, DNSQuestion
*q
)
14708 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
14711 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14713 if (SameNameCacheRecordAnswersQuestion(rp
, q
))
14715 if (rp
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| !rp
->nsec
)
14717 if (!rp
->CRDNSSECQuestion
)
14719 LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m
, rp
));
14720 mDNS_PurgeCacheResourceRecord(m
, rp
);
14727 mDNSexport
void DNSServerChangeForQuestion(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
14733 if (q
->DuplicateOf
)
14734 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q
->qname
.c
);
14736 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14737 // of events for all of them are consistent. Duplicates for a question are always inserted
14738 // after in the list.
14739 q
->qDNSServer
= new;
14740 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
14742 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= new; }
14746 mDNSlocal
void SetConfigState(mDNS
*const m
, mDNSBool
delete)
14753 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14755 ptr
->penaltyTime
= 0;
14756 ptr
->flags
|= DNSServerFlag_Delete
;
14757 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14758 if (ptr
->flags
& DNSServerFlag_Unreachable
)
14759 NumUnreachableDNSServers
--;
14762 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14763 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14765 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14766 mr
->flags
|= McastResolver_FlagDelete
;
14770 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14772 ptr
->penaltyTime
= 0;
14773 ptr
->flags
&= ~DNSServerFlag_Delete
;
14774 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14775 if (ptr
->flags
& DNSServerFlag_Unreachable
)
14776 NumUnreachableDNSServers
++;
14779 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14780 mr
->flags
&= ~McastResolver_FlagDelete
;
14784 mDNSlocal
void SetDynDNSHostNameIfChanged(mDNS
*const m
, domainname
*const fqdn
)
14786 // Did our FQDN change?
14787 if (!SameDomainName(fqdn
, &m
->FQDN
))
14789 if (m
->FQDN
.c
[0]) mDNS_RemoveDynDNSHostName(m
, &m
->FQDN
);
14791 AssignDomainName(&m
->FQDN
, fqdn
);
14795 mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1);
14796 mDNS_AddDynDNSHostName(m
, &m
->FQDN
, DynDNSHostNameCallback
, mDNSNULL
);
14801 // Even though this is called “Setup” it is not called just once at startup.
14802 // It’s actually called multiple times, every time there’s a configuration change.
14803 mDNSexport mStatus
uDNS_SetupDNSConfig(mDNS
*const m
)
14808 mDNSAddr v4
, v6
, r
;
14810 DNSServer
*ptr
, **p
= &m
->DNSServers
;
14811 const DNSServer
*oldServers
= m
->DNSServers
;
14813 McastResolver
*mr
, **mres
= &m
->McastResolvers
;
14814 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14815 DNSPushNotificationServer
**psp
;
14818 debugf("uDNS_SetupDNSConfig: entry");
14820 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14821 uDNS_SetupWABQueries(m
);
14825 // We need to first mark all the entries to be deleted. If the configuration changed, then
14826 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14828 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14829 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14830 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14831 // for the dns configuration change notification.
14832 SetConfigState(m
, mDNStrue
);
14833 if (!mDNSPlatformSetDNSConfig(mDNStrue
, mDNSfalse
, &fqdn
, mDNSNULL
, mDNSNULL
, mDNStrue
))
14835 SetDynDNSHostNameIfChanged(m
, &fqdn
);
14836 SetConfigState(m
, mDNSfalse
);
14838 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14839 return mStatus_NoError
;
14842 // For now, we just delete the mcast resolvers. We don't deal with cache or
14843 // questions here. Neither question nor cache point to mcast resolvers. Questions
14844 // do inherit the timeout values from mcast resolvers. But we don't bother
14845 // affecting them as they never change.
14848 if (((*mres
)->flags
& McastResolver_FlagDelete
) != 0)
14851 *mres
= (*mres
)->next
;
14852 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr
, mr
->domain
.c
);
14853 mDNSPlatformMemFree(mr
);
14857 (*mres
)->flags
&= ~McastResolver_FlagNew
;
14858 mres
= &(*mres
)->next
;
14862 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14864 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14865 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14866 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14867 // DNSServers and flush the cache.
14869 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14870 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14871 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14872 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14873 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14874 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14875 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14876 // the same resGroupID.
14878 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14879 // of the old followed by ADD of the new records.
14881 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14882 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14883 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14885 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14886 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14887 // non-scoped question and vice versa.
14889 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
14890 DNS64RestartQuestions(m
);
14893 // First, restart questions whose suppression status will change. The suppression status of each question in a given
14894 // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example,
14895 // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question
14896 // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain
14897 // suppressed (or non-suppressed).
14898 for (q
= m
->Questions
; q
; q
= q
->next
)
14901 const DNSServer
*t
;
14902 mDNSBool oldSuppressed
;
14904 if (mDNSOpaque16IsZero(q
->TargetQID
)) continue;
14906 SetValidDNSServers(m
, q
);
14907 q
->triedAllServersOnce
= mDNSfalse
;
14908 s
= GetServerForQuestion(m
, q
);
14912 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
14913 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR
":%d (" PRI_DM_NAME
") to "
14914 PRI_IP_ADDR
":%d (" PRI_DM_NAME
") for question " PRI_DM_NAME
" (" PUB_S
") (scope:%p)",
14915 q
->request_id
, mDNSVal16(q
->TargetQID
),
14916 t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), DM_NAME_PARAM(t
? t
->domain
.c
: (mDNSu8
*)""),
14917 s
? &s
->addr
: mDNSNULL
, mDNSVal16(s
? s
->port
: zeroIPPort
), DM_NAME_PARAM(s
? s
->domain
.c
: (mDNSu8
*)""),
14918 DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
), q
->InterfaceID
);
14919 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14920 // If this question had a DNS Push server associated with it, substitute the new server for the
14921 // old one. If there is no new server, then we'll clean up the push server later.
14922 if (!q
->DuplicateOf
&& (q
->dnsPushServer
!= mDNSNULL
))
14924 if (q
->dnsPushServer
->qDNSServer
== t
)
14926 q
->dnsPushServer
->qDNSServer
= s
; // which might be null
14928 // If it is null, do the accounting and drop the push server.
14929 if (q
->dnsPushServer
->qDNSServer
== mDNSNULL
)
14931 DNSPushReconcileConnection(m
, q
);
14936 oldSuppressed
= q
->Suppressed
;
14937 q
->Suppressed
= ShouldSuppressUnicastQuery(q
, s
);
14938 if (!q
->Suppressed
!= !oldSuppressed
) q
->Restart
= mDNStrue
;
14940 RestartUnicastQuestions(m
);
14942 // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed
14943 // have already had their server changed by being restarted.
14944 for (q
= m
->Questions
; q
; q
= q
->next
)
14947 const DNSServer
*t
;
14949 if (mDNSOpaque16IsZero(q
->TargetQID
) || q
->DuplicateOf
) continue;
14951 SetValidDNSServers(m
, q
);
14952 q
->triedAllServersOnce
= mDNSfalse
;
14953 s
= GetServerForQuestion(m
, q
);
14955 DNSServerChangeForQuestion(m
, q
, s
);
14956 if (s
== t
) continue;
14958 q
->Suppressed
= ShouldSuppressUnicastQuery(q
, s
);
14959 q
->unansweredQueries
= 0;
14960 q
->TargetQID
= mDNS_NewMessageID(m
);
14961 if (!q
->Suppressed
) ActivateUnicastQuery(m
, q
, mDNStrue
);
14964 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14965 // The above code may have found some DNS Push servers that are no longer valid. Now that we
14966 // are done running through the code, we need to drop our connections to those servers.
14967 // When we get here, any such servers should have zero questions associated with them.
14968 for (psp
= &m
->DNSPushServers
; *psp
!= mDNSNULL
; )
14970 DNSPushNotificationServer
*server
= *psp
;
14972 // It's possible that a push server whose DNS server has been deleted could be still connected but
14973 // not referenced by any questions. In this case, we just delete the push server rather than trying
14974 // to figure out with which DNS server (if any) to associate it.
14975 if (server
->qDNSServer
!= mDNSNULL
&& server
->qDNSServer
->flags
& DNSServerFlag_Delete
)
14977 server
->qDNSServer
= mDNSNULL
;
14980 if (server
->qDNSServer
== mDNSNULL
)
14982 // This would be a programming error, so should never happen.
14983 if (server
->numberOfQuestions
!= 0)
14985 LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server
->serverName
);
14987 DNSPushServerDrop(server
);
14988 *psp
= server
->next
;
14989 mDNSPlatformMemFree(server
);
14993 psp
= &(*psp
)->next
;
14998 FORALL_CACHERECORDS(slot
, cg
, cr
)
15000 if (cr
->resrec
.InterfaceID
) continue;
15002 // We already walked the questions and restarted/reactivated them if the dns server
15003 // change affected the question. That should take care of updating the cache. But
15004 // what if there is no active question at this point when the DNS server change
15005 // happened ? There could be old cache entries lying around and if we don't flush
15006 // them, a new question after the DNS server change could pick up these stale
15007 // entries and get a wrong answer.
15009 // For cache entries that have active questions we might have skipped rescheduling
15010 // the questions if they were suppressed (see above). To keep it simple, we walk
15011 // all the cache entries to make sure that there are no stale entries. We use the
15012 // active question's InterfaceID/ServiceID for looking up the right DNS server.
15014 // Note: If GetServerForName returns NULL, it could either mean that there are no
15015 // DNS servers or no matching DNS servers for this question. In either case,
15016 // the cache should get purged below when we process deleted DNS servers.
15018 // If it is a DNSSEC question, purge the cache as the DNSSEC capabilities of the
15019 // DNS server may have changed.
15021 if (cr
->CRActiveQuestion
&& !DNSSECQuestion(cr
->CRActiveQuestion
))
15023 // Purge or Reconfirm if this cache entry would use the new DNS server
15024 ptr
= GetServerForName(m
, cr
->resrec
.name
, cr
->CRActiveQuestion
->InterfaceID
, cr
->CRActiveQuestion
->ServiceID
);
15025 if (ptr
&& (ptr
!= cr
->resrec
.rDNSServer
))
15027 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a",
15028 CRDisplayString(m
, cr
), &ptr
->addr
,
15029 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
);
15030 PurgeOrReconfirmCacheRecord(m
, cr
);
15032 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15033 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15034 if (!cr
->resrec
.rDNSServer
&& cr
->CRActiveQuestion
->qDNSServer
)
15036 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr
->CRActiveQuestion
->qDNSServer
->addr
, CRDisplayString(m
, cr
));
15037 cr
->resrec
.rDNSServer
= cr
->CRActiveQuestion
->qDNSServer
;
15041 if (cr
->resrec
.rDNSServer
&& cr
->resrec
.rDNSServer
->flags
& DNSServerFlag_Delete
)
15043 DNSQuestion
*qptr
= cr
->CRActiveQuestion
;
15044 if (qptr
->qDNSServer
== cr
->resrec
.rDNSServer
)
15046 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15047 " to be freed", CRDisplayString(m
, cr
),
15048 qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
,
15049 &cr
->resrec
.rDNSServer
->addr
);
15050 qptr
->validDNSServers
= zeroOpaque128
;
15051 qptr
->qDNSServer
= mDNSNULL
;
15052 cr
->resrec
.rDNSServer
= mDNSNULL
;
15056 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15057 " resetting to question's DNSServer Address %#a", CRDisplayString(m
, cr
),
15058 qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
,
15059 &cr
->resrec
.rDNSServer
->addr
,
15060 qptr
->qDNSServer
? &qptr
->qDNSServer
->addr
: mDNSNULL
);
15061 cr
->resrec
.rDNSServer
= qptr
->qDNSServer
;
15063 PurgeOrReconfirmCacheRecord(m
, cr
);
15066 else if (!cr
->resrec
.rDNSServer
|| cr
->resrec
.rDNSServer
->flags
& DNSServerFlag_Delete
)
15068 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
15069 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S
", DNS server " PUB_S
" " PRI_IP_ADDR
" " PUB_S
,
15070 CRDisplayString(m
, cr
), !cr
->resrec
.rDNSServer
? "(to be deleted)" : "",
15071 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
,
15072 cr
->resrec
.rDNSServer
? DNSScopeToString(cr
->resrec
.rDNSServer
->scopeType
) : "" );
15073 cr
->resrec
.rDNSServer
= mDNSNULL
;
15074 cr
->resrec
.mortality
= Mortality_Mortal
;
15075 mDNS_PurgeCacheResourceRecord(m
, cr
);
15079 // Delete all the DNS servers that are flagged for deletion
15082 if (((*p
)->flags
& DNSServerFlag_Delete
) != 0)
15086 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
);
15087 mDNSPlatformMemFree(ptr
);
15094 LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m
));
15096 // If we now have no DNS servers at all and we used to have some, then immediately purge all unicast cache records (including for LLQs).
15097 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15098 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15099 // Similarly, if we now have some DNS servers and we used to have none, we want to purge any fake negative results we may have generated.
15100 if ((m
->DNSServers
!= mDNSNULL
) != (oldServers
!= mDNSNULL
))
15103 FORALL_CACHERECORDS(slot
, cg
, cr
)
15105 if (!cr
->resrec
.InterfaceID
)
15107 mDNS_PurgeCacheResourceRecord(m
, cr
);
15111 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15112 m
->DNSServers
? "DNS server became" : "No DNS servers", count
);
15114 // Force anything that needs to get zone data to get that information again
15115 RestartRecordGetZoneData(m
);
15118 SetDynDNSHostNameIfChanged(m
, &fqdn
);
15122 // handle router and primary interface changes
15123 v4
= v6
= r
= zeroAddr
;
15124 v4
.type
= r
.type
= mDNSAddrType_IPv4
;
15126 if (mDNSPlatformGetPrimaryInterface(&v4
, &v6
, &r
) == mStatus_NoError
&& !mDNSv4AddressIsLinkLocal(&v4
.ip
.v4
))
15128 mDNS_SetPrimaryInterfaceInfo(m
,
15129 !mDNSIPv4AddressIsZero(v4
.ip
.v4
) ? &v4
: mDNSNULL
,
15130 !mDNSIPv6AddressIsZero(v6
.ip
.v6
) ? &v6
: mDNSNULL
,
15131 !mDNSIPv4AddressIsZero(r
.ip
.v4
) ? &r
: mDNSNULL
);
15135 mDNS_SetPrimaryInterfaceInfo(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
15136 if (m
->FQDN
.c
[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1); // Set status to 1 to indicate temporary failure
15139 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m
));
15140 return mStatus_NoError
;
15143 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
15145 m
->mDNSPlatformStatus
= result
;
15146 if (m
->MainCallback
)
15149 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15150 m
->MainCallback(m
, mStatus_NoError
);
15151 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15156 mDNSlocal
void DeregLoop(mDNS
*const m
, AuthRecord
*const start
)
15158 m
->CurrentRecord
= start
;
15159 while (m
->CurrentRecord
)
15161 AuthRecord
*rr
= m
->CurrentRecord
;
15162 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15163 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
) ? "Initiating " : "Accelerating",
15164 rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15165 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
15166 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_rapid
);
15167 else if (rr
->AnnounceCount
> 1)
15169 rr
->AnnounceCount
= 1;
15170 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
15172 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15173 // new records could have been added to the end of the list as a result of that call.
15174 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
15175 m
->CurrentRecord
= rr
->next
;
15179 mDNSexport
void mDNS_StartExit(mDNS
*const m
)
15185 LogInfo("mDNS_StartExit");
15186 m
->ShutdownTime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
15188 mDNSCoreBeSleepProxyServer_internal(m
, 0, 0, 0, 0, 0);
15190 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
15191 if (WCFConnectionDealloc
)
15193 if (m
->WCF
) WCFConnectionDealloc(m
->WCF
);
15197 #ifndef UNICAST_DISABLED
15201 // Don't need to do SleepRecordRegistrations() here
15202 // because we deregister all records and services later in this routine
15203 while (m
->Hostnames
) mDNS_RemoveDynDNSHostName(m
, &m
->Hostnames
->fqdn
);
15205 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15206 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15207 // and we may crash because the list still contains dangling pointers.
15208 for (s
= SearchList
; s
; s
= s
->next
)
15209 while (s
->AuthRecs
)
15211 ARListElem
*dereg
= s
->AuthRecs
;
15212 s
->AuthRecs
= s
->AuthRecs
->next
;
15213 mDNS_Deregister_internal(m
, &dereg
->ar
, mDNS_Dereg_normal
); // Memory will be freed in the FreeARElemCallback
15218 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_All
);
15220 // Shut down all our active NAT Traversals
15221 while (m
->NATTraversals
)
15223 NATTraversalInfo
*t
= m
->NATTraversals
;
15224 mDNS_StopNATOperation_internal(m
, t
); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15226 // After stopping the NAT Traversal, we zero out the fields.
15227 // This has particularly important implications for our AutoTunnel records --
15228 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15229 // handlers to just turn around and attempt to re-register those same records.
15230 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15232 t
->ExternalAddress
= zerov4Addr
;
15233 t
->NewAddress
= zerov4Addr
;
15234 t
->ExternalPort
= zeroIPPort
;
15235 t
->RequestedPort
= zeroIPPort
;
15237 t
->Result
= mStatus_NoError
;
15240 // Make sure there are nothing but deregistering records remaining in the list
15241 if (m
->CurrentRecord
)
15242 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
15244 // We're in the process of shutting down, so queries, etc. are no longer available.
15245 // Consequently, determining certain information, e.g. the uDNS update server's IP
15246 // address, will not be possible. The records on the main list are more likely to
15247 // already contain such information, so we deregister the duplicate records first.
15248 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
15249 DeregLoop(m
, m
->DuplicateRecords
);
15250 LogInfo("mDNS_StartExit: Deregistering resource records");
15251 DeregLoop(m
, m
->ResourceRecords
);
15253 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15254 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15255 if (m
->NextScheduledResponse
- m
->timenow
< mDNSPlatformOneSecond
)
15257 m
->NextScheduledResponse
= m
->timenow
;
15258 m
->SuppressSending
= 0;
15261 if (m
->ResourceRecords
) LogInfo("mDNS_StartExit: Sending final record deregistrations");
15262 else LogInfo("mDNS_StartExit: No deregistering records remain");
15264 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
15265 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15267 // If any deregistering records remain, send their deregistration announcements before we exit
15268 if (m
->mDNSPlatformStatus
!= mStatus_NoError
) DiscardDeregistrations(m
);
15272 LogInfo("mDNS_StartExit: done");
15275 mDNSexport
void mDNS_FinalExit(mDNS
*const m
)
15277 mDNSu32 rrcache_active
= 0;
15278 mDNSu32 rrcache_totalused
= m
->rrcache_totalused
;
15282 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
15283 mDNSPlatformClose(m
);
15285 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
15287 while (m
->rrcache_hash
[slot
])
15289 CacheGroup
*cg
= m
->rrcache_hash
[slot
];
15290 while (cg
->members
)
15292 CacheRecord
*cr
= cg
->members
;
15293 cg
->members
= cg
->members
->next
;
15294 if (cr
->CRActiveQuestion
) rrcache_active
++;
15295 ReleaseCacheRecord(m
, cr
);
15297 cg
->rrcache_tail
= &cg
->members
;
15298 ReleaseCacheGroup(m
, &m
->rrcache_hash
[slot
]);
15301 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused
, rrcache_active
);
15302 if (rrcache_active
!= m
->rrcache_active
)
15303 LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused
, rrcache_active
, m
->rrcache_active
);
15305 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
15306 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15308 LogInfo("mDNS_FinalExit: done");
15312 #include "../unittests/mdns_ut.c"