2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
23 * This code is completely 100% portable C. It does not depend on any external header files
24 * from outside the mDNS project -- all the types it expects to find are defined right here.
26 * The previous point is very important: This file does not depend on any external
27 * header files. It should complile on *any* platform that has a C compiler, without
28 * making *any* assumptions about availability of so-called "standard" C functions,
29 * routines, or types (which may or may not be present on any given platform).
32 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
33 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
34 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
35 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
36 * therefore common sense dictates that if they are part of a compound statement then they
37 * should be indented to the same level as everything else in that compound statement.
38 * Indenting curly braces at the same level as the "if" implies that curly braces are
39 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
40 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
41 * understand why variable y is not of type "char*" just proves the point that poor code
42 * layout leads people to unfortunate misunderstandings about how the C language really works.)
44 Change History (most recent first):
47 Revision 1.307 2003/09/09 20:13:30 cheshire
48 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
49 Ammend checkin 1.304: Off-by-one error: By this place in the function we've already decremented
50 rr->AnnounceCount, so the check needs to be for InitialAnnounceCount-1, not InitialAnnounceCount
52 Revision 1.306 2003/09/09 03:00:03 cheshire
53 <rdar://problem/3413099> Services take a long time to disappear when switching networks.
54 Added two constants: kDefaultReconfirmTimeForNoAnswer and kDefaultReconfirmTimeForCableDisconnect
56 Revision 1.305 2003/09/09 02:49:31 cheshire
57 <rdar://problem/3413975> Initial probes and queries not grouped on wake-from-sleep
59 Revision 1.304 2003/09/09 02:41:19 cheshire
60 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
62 Revision 1.303 2003/09/05 19:55:02 cheshire
63 <rdar://problem/3409533> Include address records when announcing SRV records
65 Revision 1.302 2003/09/05 00:01:36 cheshire
66 <rdar://problem/3407549> Don't accelerate queries that have large KA lists
68 Revision 1.301 2003/09/04 22:51:13 cheshire
69 <rdar://problem/3398213> Group probes and goodbyes better
71 Revision 1.300 2003/09/03 02:40:37 cheshire
72 <rdar://problem/3404842> mDNSResponder complains about '_'s
73 Underscores are not supposed to be legal in standard DNS names, but IANA appears
74 to have allowed them in previous service name registrations, so we should too.
76 Revision 1.299 2003/09/03 02:33:09 cheshire
77 <rdar://problem/3404795> CacheRecordRmv ERROR
78 Don't update m->NewQuestions until *after* CheckCacheExpiration();
80 Revision 1.298 2003/09/03 01:47:01 cheshire
81 <rdar://problem/3319418> Rendezvous services always in a state of flux
82 Change mDNS_Reconfirm_internal() minimum timeout from 5 seconds to 45-60 seconds
84 Revision 1.297 2003/08/29 19:44:15 cheshire
85 <rdar://problem/3400967> Traffic reduction: Eliminate synchronized QUs when a new service appears
86 1. Use m->RandomQueryDelay to impose a random delay in the range 0-500ms on queries
87 that already have at least one unique answer in the cache
88 2. For these queries, go straight to QM, skipping QU
90 Revision 1.296 2003/08/29 19:08:21 cheshire
91 <rdar://problem/3400986> Traffic reduction: Eliminate huge KA lists after wake from sleep
92 Known answers are no longer eligible to go in the KA list if they are more than half-way to their expiry time.
94 Revision 1.295 2003/08/28 01:10:59 cheshire
95 <rdar://problem/3396034> Add syslog message to report when query is reset because of immediate answer burst
97 Revision 1.294 2003/08/27 02:30:22 cheshire
98 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
99 One more change: "query->GotTXT" is now a straightforward bi-state boolean again
101 Revision 1.293 2003/08/27 02:25:31 cheshire
102 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
104 Revision 1.292 2003/08/21 19:27:36 cheshire
105 <rdar://problem/3387878> Traffic reduction: No need to announce record for longer than TTL
107 Revision 1.291 2003/08/21 18:57:44 cheshire
108 <rdar://problem/3387140> Synchronized queries on the network
110 Revision 1.290 2003/08/21 02:25:23 cheshire
111 Minor changes to comments and debugf() messages
113 Revision 1.289 2003/08/21 02:21:50 cheshire
114 <rdar://problem/3386473> Efficiency: Reduce repeated queries
116 Revision 1.288 2003/08/20 23:39:30 cheshire
117 <rdar://problem/3344098> Review syslog messages, and remove as appropriate
119 Revision 1.287 2003/08/20 20:47:18 cheshire
122 Revision 1.286 2003/08/20 02:18:51 cheshire
123 <rdar://problem/3344098> Cleanup: Review syslog messages
125 Revision 1.285 2003/08/20 01:59:06 cheshire
126 <rdar://problem/3384478> rdatahash and rdnamehash not updated after changing rdata
127 Made new routine SetNewRData() to update rdlength, rdestimate, rdatahash and rdnamehash in one place
129 Revision 1.284 2003/08/19 22:20:00 cheshire
130 <rdar://problem/3376721> Don't use IPv6 on interfaces that have a routable IPv4 address configured
131 More minor refinements
133 Revision 1.283 2003/08/19 22:16:27 cheshire
134 Minor fix: Add missing "mDNS_Unlock(m);" in mDNS_DeregisterInterface() error case.
136 Revision 1.282 2003/08/19 06:48:25 cheshire
137 <rdar://problem/3376552> Guard against excessive record updates
138 Each record starts with 10 UpdateCredits.
139 Every update consumes one UpdateCredit.
140 UpdateCredits are replenished at a rate of one one per minute, up to a maximum of 10.
141 As the number of UpdateCredits declines, the number of announcements is similarly scaled back.
142 When fewer than 5 UpdateCredits remain, the first announcement is also delayed by an increasing amount.
144 Revision 1.281 2003/08/19 04:49:28 cheshire
145 <rdar://problem/3368159> Interaction between v4, v6 and dual-stack hosts not working quite right
146 1. A dual-stack host should only suppress its own query if it sees the same query from other hosts on BOTH IPv4 and IPv6.
147 2. When we see the first v4 (or first v6) member of a group, we re-trigger questions and probes on that interface.
148 3. When we see the last v4 (or v6) member of a group go away, we revalidate all the records received on that interface.
150 Revision 1.280 2003/08/19 02:33:36 cheshire
153 Revision 1.279 2003/08/19 02:31:11 cheshire
154 <rdar://problem/3378386> mDNSResponder overenthusiastic with final expiration queries
155 Final expiration queries now only mark the question for sending on the particular interface
156 pertaining to the record that's expiring.
158 Revision 1.278 2003/08/18 22:53:37 cheshire
159 <rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformTimeNow()
161 Revision 1.277 2003/08/18 19:05:44 cheshire
162 <rdar://problem/3382423> UpdateRecord not working right
163 Added "newrdlength" field to hold new length of updated rdata
165 Revision 1.276 2003/08/16 03:39:00 cheshire
166 <rdar://problem/3338440> InterfaceID -1 indicates "local only"
168 Revision 1.275 2003/08/16 02:51:27 cheshire
169 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
170 Don't try to compute namehash etc, until *after* validating the name
172 Revision 1.274 2003/08/16 01:12:40 cheshire
173 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
174 Now that the minimum rdata object size has been reduced to 64 bytes, it is no longer safe to do a
175 simple C structure assignment of a domainname, because that object is defined to be 256 bytes long,
176 and in the process of copying it, the C compiler may run off the end of the rdata object into
177 unmapped memory. All assignments of domainname objects of uncertain size are now replaced with a
178 call to the macro AssignDomainName(), which is careful to copy only as many bytes as are valid.
180 Revision 1.273 2003/08/15 20:16:02 cheshire
181 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
182 We want to avoid touching the rdata pages, so we don't page them in.
183 1. RDLength was stored with the rdata, which meant touching the page just to find the length.
184 Moved this from the RData to the ResourceRecord object.
185 2. To avoid unnecessarily touching the rdata just to compare it,
186 compute a hash of the rdata and store the hash in the ResourceRecord object.
188 Revision 1.272 2003/08/14 19:29:04 cheshire
189 <rdar://problem/3378473> Include cache records in SIGINFO output
190 Moved declarations of DNSTypeName() and GetRRDisplayString to mDNSClientAPI.h so daemon.c can use them
192 Revision 1.271 2003/08/14 02:17:05 cheshire
193 <rdar://problem/3375491> Split generic ResourceRecord type into two separate types: AuthRecord and CacheRecord
195 Revision 1.270 2003/08/13 17:07:28 ksekar
196 Bug #: <rdar://problem/3376458>: Extra RR linked to list even if registration fails - causes crash
197 Added check to result of mDNS_Register() before linking extra record into list.
199 Revision 1.269 2003/08/12 19:56:23 cheshire
202 Revision 1.268 2003/08/12 15:01:10 cheshire
205 Revision 1.267 2003/08/12 14:59:27 cheshire
206 <rdar://problem/3374490> Rate-limiting blocks some legitimate responses
207 When setting LastMCTime also record LastMCInterface. When checking LastMCTime to determine
208 whether to suppress the response, also check LastMCInterface to see if it matches.
210 Revision 1.266 2003/08/12 12:47:16 cheshire
211 In mDNSCoreMachineSleep debugf message, display value of m->timenow
213 Revision 1.265 2003/08/11 20:04:28 cheshire
214 <rdar://problem/3366553> Improve efficiency by restricting cases where we have to walk the entire cache
216 Revision 1.264 2003/08/09 00:55:02 cheshire
217 <rdar://problem/3366553> mDNSResponder is taking 20-30% of the CPU
218 Don't scan the whole cache after every packet.
220 Revision 1.263 2003/08/09 00:35:29 cheshire
221 Moved AnswerNewQuestion() later in the file, in preparation for next checkin
223 Revision 1.262 2003/08/08 19:50:33 cheshire
224 <rdar://problem/3370332> Remove "Cache size now xxx" messages
226 Revision 1.261 2003/08/08 19:18:45 cheshire
227 <rdar://problem/3271219> Only retrigger questions on platforms with the "PhantomInterfaces" bug
229 Revision 1.260 2003/08/08 18:55:48 cheshire
230 <rdar://problem/3370365> Guard against time going backwards
232 Revision 1.259 2003/08/08 18:36:04 cheshire
233 <rdar://problem/3344154> Only need to revalidate on interface removal on platforms that have the PhantomInterfaces bug
235 Revision 1.258 2003/08/08 16:22:05 cheshire
236 <rdar://problem/3335473> Need to check validity of TXT (and other) records
237 Remove unneeded LogMsg
239 Revision 1.257 2003/08/07 01:41:08 cheshire
240 <rdar://problem/3367346> Ignore packets with invalid source address (all zeroes or all ones)
242 Revision 1.256 2003/08/06 23:25:51 cheshire
243 <rdar://problem/3290674> Increase TTL for A/AAAA/SRV from one minute to four
245 Revision 1.255 2003/08/06 23:22:50 cheshire
246 Add symbolic constants: kDefaultTTLforUnique (one minute) and kDefaultTTLforShared (two hours)
248 Revision 1.254 2003/08/06 21:33:39 cheshire
249 Fix compiler warnings on PocketPC 2003 (Windows CE)
251 Revision 1.253 2003/08/06 20:43:57 cheshire
252 <rdar://problem/3335473> Need to check validity of TXT (and other) records
253 Created ValidateDomainName() and ValidateRData(), used by mDNS_Register_internal() and mDNS_Update()
255 Revision 1.252 2003/08/06 20:35:47 cheshire
256 Enhance debugging routine GetRRDisplayString() so it can also be used to display
257 other RDataBody objects, not just the one currently attached the given ResourceRecord
259 Revision 1.251 2003/08/06 19:07:34 cheshire
260 <rdar://problem/3366251> mDNSResponder not inhibiting multicast responses as much as it should
261 Was checking LastAPTime instead of LastMCTime
263 Revision 1.250 2003/08/06 19:01:55 cheshire
266 Revision 1.249 2003/08/06 00:13:28 cheshire
267 Tidy up debugf messages
269 Revision 1.248 2003/08/05 22:20:15 cheshire
270 <rdar://problem/3330324> Need to check IP TTL on responses
272 Revision 1.247 2003/08/05 00:56:39 cheshire
273 <rdar://problem/3357075> mDNSResponder sending additional records, even after precursor record suppressed
275 Revision 1.246 2003/08/04 19:20:49 cheshire
276 Add kDNSQType_ANY to list in DNSTypeName() so it can be displayed in debugging messages
278 Revision 1.245 2003/08/02 01:56:29 cheshire
279 For debugging: log message if we ever get more than one question in a truncated packet
281 Revision 1.244 2003/08/01 23:55:32 cheshire
282 Fix for compiler warnings on Windows, submitted by Bob Bradley
284 Revision 1.243 2003/07/25 02:26:09 cheshire
285 Typo: FIxed missing semicolon
287 Revision 1.242 2003/07/25 01:18:41 cheshire
288 Fix memory leak on shutdown in mDNS_Close() (detected in Windows version)
290 Revision 1.241 2003/07/23 21:03:42 cheshire
291 Only show "Found record..." debugf message in verbose mode
293 Revision 1.240 2003/07/23 21:01:11 cheshire
294 <rdar://problem/3340584> Need Nagle-style algorithm to coalesce multiple packets into one
295 After sending a packet, suppress further sending for the next 100ms.
297 Revision 1.239 2003/07/22 01:30:05 cheshire
298 <rdar://problem/3329099> Don't try to add the same question to the duplicate-questions list more than once
300 Revision 1.238 2003/07/22 00:10:20 cheshire
301 <rdar://problem/3337355> ConvertDomainLabelToCString() needs to escape escape characters
303 Revision 1.237 2003/07/19 03:23:13 cheshire
304 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
306 Revision 1.236 2003/07/19 03:04:55 cheshire
307 Fix warnings; some debugf message improvements
309 Revision 1.235 2003/07/19 00:03:32 cheshire
310 <rdar://problem/3160248> ScheduleNextTask needs to be smarter after a no-op packet is received
311 ScheduleNextTask is quite an expensive operation.
312 We don't need to do all that work after receiving a no-op packet that didn't change our state.
314 Revision 1.234 2003/07/18 23:52:11 cheshire
315 To improve consistency of field naming, global search-and-replace:
316 NextProbeTime -> NextScheduledProbe
317 NextResponseTime -> NextScheduledResponse
319 Revision 1.233 2003/07/18 00:29:59 cheshire
320 <rdar://problem/3268878> Remove mDNSResponder version from packet header and use HINFO record instead
322 Revision 1.232 2003/07/18 00:11:38 cheshire
323 Add extra case to switch statements to handle HINFO data for Get, Put and Display
324 (In all but GetRDLength(), this is is just a fall-through to kDNSType_TXT)
326 Revision 1.231 2003/07/18 00:06:37 cheshire
327 To make code a little easier to read in GetRDLength(), search-and-replace "rr->rdata->u." with "rd->"
329 Revision 1.230 2003/07/17 18:16:54 cheshire
330 <rdar://problem/3319418> Rendezvous services always in a state of flux
331 In preparation for working on this, made some debugf messages a little more selective
333 Revision 1.229 2003/07/17 17:35:04 cheshire
334 <rdar://problem/3325583> Rate-limit responses, to guard against packet flooding
336 Revision 1.228 2003/07/16 20:50:27 cheshire
337 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
339 Revision 1.227 2003/07/16 05:01:36 cheshire
340 Add fields 'LargeAnswers' and 'ExpectUnicastResponse' in preparation for
341 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
343 Revision 1.226 2003/07/16 04:51:44 cheshire
344 Fix use of constant 'mDNSPlatformOneSecond' where it should have said 'InitialQuestionInterval'
346 Revision 1.225 2003/07/16 04:46:41 cheshire
347 Minor wording cleanup: The correct DNS term is "response", not "reply"
349 Revision 1.224 2003/07/16 04:39:02 cheshire
350 Textual cleanup (no change to functionality):
351 Construct "c >= 'A' && c <= 'Z'" appears in too many places; replaced with macro "mDNSIsUpperCase(c)"
353 Revision 1.223 2003/07/16 00:09:22 cheshire
354 Textual cleanup (no change to functionality):
355 Construct "((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)" appears in too many places;
356 replace with macro "TicksTTL(rr)"
357 Construct "rr->TimeRcvd + ((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)"
358 replaced with macro "RRExpireTime(rr)"
360 Revision 1.222 2003/07/15 23:40:46 cheshire
361 Function rename: UpdateDupSuppressInfo() is more accurately called ExpireDupSuppressInfo()
363 Revision 1.221 2003/07/15 22:17:56 cheshire
364 <rdar://problem/3328394> mDNSResponder is not being efficient when doing certain queries
366 Revision 1.220 2003/07/15 02:12:51 cheshire
367 Slight tidy-up of debugf messages and comments
369 Revision 1.219 2003/07/15 01:55:12 cheshire
370 <rdar://problem/3315777> Need to implement service registration with subtypes
372 Revision 1.218 2003/07/14 16:26:06 cheshire
373 <rdar://problem/3324795> Duplicate query suppression not working right
374 Refinement: Don't record DS information for a question in the first quarter second
375 right after we send it -- in the case where a question happens to be accelerated by
376 the maximum allowed amount, we don't want it to then be suppressed because the previous
377 time *we* sent that question falls (just) within the valid duplicate suppression window.
379 Revision 1.217 2003/07/13 04:43:53 cheshire
380 <rdar://problem/3325169> Services on multiple interfaces not always resolving
381 Minor refinement: No need to make address query broader than the original SRV query that provoked it
383 Revision 1.216 2003/07/13 03:13:17 cheshire
384 <rdar://problem/3325169> Services on multiple interfaces not always resolving
385 If we get an identical SRV on a second interface, convert address queries to non-specific
387 Revision 1.215 2003/07/13 02:28:00 cheshire
388 <rdar://problem/3325166> SendResponses didn't all its responses
389 Delete all references to RRInterfaceActive -- it's now superfluous
391 Revision 1.214 2003/07/13 01:47:53 cheshire
392 Fix one error and one warning in the Windows build
394 Revision 1.213 2003/07/12 04:25:48 cheshire
395 Fix minor signed/unsigned warnings
397 Revision 1.212 2003/07/12 01:59:11 cheshire
398 Minor changes to debugf messages
400 Revision 1.211 2003/07/12 01:47:01 cheshire
401 <rdar://problem/3324495> After name conflict, appended number should be higher than previous number
403 Revision 1.210 2003/07/12 01:43:28 cheshire
404 <rdar://problem/3324795> Duplicate query suppression not working right
405 The correct cutoff time for duplicate query suppression is timenow less one-half the query interval.
406 The code was incorrectly using the last query time plus one-half the query interval.
407 This was only correct in the case where query acceleration was not in effect.
409 Revision 1.209 2003/07/12 01:27:50 cheshire
410 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
411 Fix missing "-1" in RemoveLabelSuffix()
413 Revision 1.208 2003/07/11 01:32:38 cheshire
414 Syntactic cleanup (no change to funcationality): Now that we only have one host name,
415 rename field "hostname1" to "hostname", and field "RR_A1" to "RR_A".
417 Revision 1.207 2003/07/11 01:28:00 cheshire
418 <rdar://problem/3161289> No more local.arpa
420 Revision 1.206 2003/07/11 00:45:02 cheshire
421 <rdar://problem/3321909> Client should get callback confirming successful host name registration
423 Revision 1.205 2003/07/11 00:40:18 cheshire
424 Tidy up debug message in HostNameCallback()
426 Revision 1.204 2003/07/11 00:20:32 cheshire
427 <rdar://problem/3320087> mDNSResponder should log a message after 16 unsuccessful probes
429 Revision 1.203 2003/07/10 23:53:41 cheshire
430 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
432 Revision 1.202 2003/07/04 02:23:20 cheshire
433 <rdar://problem/3311955> Responder too aggressive at flushing stale data
434 Changed mDNSResponder to require four unanswered queries before purging a record, instead of two.
436 Revision 1.201 2003/07/04 01:09:41 cheshire
437 <rdar://problem/3315775> Need to implement subtype queries
438 Modified ConstructServiceName() to allow three-part service types
440 Revision 1.200 2003/07/03 23:55:26 cheshire
441 Minor change to wording of syslog warning messages
443 Revision 1.199 2003/07/03 23:51:13 cheshire
444 <rdar://problem/3315652>: Lots of "have given xxx answers" syslog warnings
445 Added more detailed debugging information
447 Revision 1.198 2003/07/03 22:19:30 cheshire
448 <rdar://problem/3314346> Bug fix in 3274153 breaks TiVo
449 Make exception to allow _tivo_servemedia._tcp.
451 Revision 1.197 2003/07/02 22:33:05 cheshire
452 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
454 When cache is exhausted, verify that rrcache_totalused == rrcache_size and report if not
455 Allow cache to grow to 512 records before considering it a potential denial-of-service attack
457 Revision 1.196 2003/07/02 21:19:45 cheshire
458 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
460 Revision 1.195 2003/07/02 19:56:58 cheshire
461 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
462 Minor refinement: m->rrcache_active was not being decremented when
463 an active record was deleted because its TTL expired
465 Revision 1.194 2003/07/02 18:47:40 cheshire
466 Minor wording change to log messages
468 Revision 1.193 2003/07/02 02:44:13 cheshire
469 Fix warning in non-debug build
471 Revision 1.192 2003/07/02 02:41:23 cheshire
472 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
474 Revision 1.191 2003/07/02 02:30:51 cheshire
475 HashSlot() returns an array index. It can't be negative; hence it should not be signed.
477 Revision 1.190 2003/06/27 00:03:05 vlubet
478 <rdar://problem/3304625> Merge of build failure fix for gcc 3.3
480 Revision 1.189 2003/06/11 19:24:03 cheshire
481 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
482 Slight refinement to previous checkin
484 Revision 1.188 2003/06/10 20:33:28 cheshire
485 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
487 Revision 1.187 2003/06/10 04:30:44 cheshire
488 <rdar://problem/3286234> Need to re-probe/re-announce on configuration change
489 Only interface-specific records were re-probing and re-announcing, not non-specific records.
491 Revision 1.186 2003/06/10 04:24:39 cheshire
492 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
493 Some additional refinements:
494 Don't try to do this for unicast-response queries
495 better tracking of Qs and KAs in multi-packet KA lists
497 Revision 1.185 2003/06/10 03:52:49 cheshire
498 Update comments and debug messages
500 Revision 1.184 2003/06/10 02:26:39 cheshire
501 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
502 Make mDNS_Reconfirm() call mDNS_Lock(), like the other API routines
504 Revision 1.183 2003/06/09 18:53:13 cheshire
505 Simplify some debugf() statements (replaced block of 25 lines with 2 lines)
507 Revision 1.182 2003/06/09 18:38:42 cheshire
508 <rdar://problem/3285082> Need to be more tolerant when there are mDNS proxies on the network
509 Only issue a correction if the TTL in the proxy packet is less than half the correct value.
511 Revision 1.181 2003/06/07 06:45:05 cheshire
512 <rdar://problem/3283666> No need for multiple machines to all be sending the same queries
514 Revision 1.180 2003/06/07 06:31:07 cheshire
515 Create little four-line helper function "FindIdenticalRecordInCache()"
517 Revision 1.179 2003/06/07 06:28:13 cheshire
518 For clarity, change name of "DNSQuestion q" to "DNSQuestion pktq"
520 Revision 1.178 2003/06/07 06:25:12 cheshire
523 Revision 1.177 2003/06/07 04:50:53 cheshire
524 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
526 Revision 1.176 2003/06/07 04:33:26 cheshire
527 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
528 Minor change: Increment/decrement logic for q->CurrentAnswers should be in
529 CacheRecordAdd() and CacheRecordRmv(), not AnswerQuestionWithResourceRecord()
531 Revision 1.175 2003/06/07 04:11:52 cheshire
532 Minor changes to comments and debug messages
534 Revision 1.174 2003/06/07 01:46:38 cheshire
535 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
537 Revision 1.173 2003/06/07 01:22:13 cheshire
538 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
540 Revision 1.172 2003/06/07 00:59:42 cheshire
541 <rdar://problem/3283454> Need some randomness to spread queries on the network
543 Revision 1.171 2003/06/06 21:41:10 cheshire
544 For consistency, mDNS_StopQuery() should return an mStatus result, just like all the other mDNSCore routines
546 Revision 1.170 2003/06/06 21:38:55 cheshire
547 Renamed 'NewData' as 'FreshData' (The data may not be new data, just a refresh of data that we
548 already had in our cache. This refreshes our TTL on the data, but the data itself stays the same.)
550 Revision 1.169 2003/06/06 21:35:55 cheshire
551 Fix mis-named macro: GetRRHostNameTarget is really GetRRDomainNameTarget
552 (the target is a domain name, but not necessarily a host name)
554 Revision 1.168 2003/06/06 21:33:31 cheshire
555 Instead of using (mDNSPlatformOneSecond/2) all over the place, define a constant "InitialQuestionInterval"
557 Revision 1.167 2003/06/06 21:30:42 cheshire
558 <rdar://problem/3282962> Don't delay queries for shared record types
560 Revision 1.166 2003/06/06 17:20:14 cheshire
561 For clarity, rename question fields name/rrtype/rrclass as qname/qtype/qclass
562 (Global search-and-replace; no functional change to code execution.)
564 Revision 1.165 2003/06/04 02:53:21 cheshire
565 Add some "#pragma warning" lines so it compiles clean on Microsoft compilers
567 Revision 1.164 2003/06/04 01:25:33 cheshire
568 <rdar://problem/3274950> Cannot perform multi-packet known-answer suppression messages
569 Display time interval between first and subsequent queries
571 Revision 1.163 2003/06/03 19:58:14 cheshire
572 <rdar://problem/3277665> mDNS_DeregisterService() fixes:
573 When forcibly deregistering after a conflict, ensure we don't send an incorrect goodbye packet.
574 Guard against a couple of possible mDNS_DeregisterService() race conditions.
576 Revision 1.162 2003/06/03 19:30:39 cheshire
577 Minor addition refinements for
578 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
580 Revision 1.161 2003/06/03 18:29:03 cheshire
581 Minor changes to comments and debugf() messages
583 Revision 1.160 2003/06/03 05:02:16 cheshire
584 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
586 Revision 1.159 2003/06/03 03:31:57 cheshire
587 <rdar://problem/3277033> False self-conflict when there are duplicate registrations on one machine
589 Revision 1.158 2003/06/02 22:57:09 cheshire
590 Minor clarifying changes to comments and log messages;
591 IdenticalResourceRecordAnyInterface() is really more accurately called just IdenticalResourceRecord()
593 Revision 1.157 2003/05/31 00:09:49 cheshire
594 <rdar://problem/3274862> Add ability to discover what services are on a network
596 Revision 1.156 2003/05/30 23:56:49 cheshire
597 <rdar://problem/3274847> Crash after error in mDNS_RegisterService()
598 Need to set "sr->Extras = mDNSNULL" before returning
600 Revision 1.155 2003/05/30 23:48:00 cheshire
601 <rdar://problem/3274832> Announcements not properly grouped
602 Due to inconsistent setting of rr->LastAPTime at different places in the
603 code, announcements were not properly grouped into a single packet.
604 Fixed by creating a single routine called InitializeLastAPTime().
606 Revision 1.154 2003/05/30 23:38:14 cheshire
607 <rdar://problem/3274814> Fix error in IPv6 reverse-mapping PTR records
608 Wrote buffer[32] where it should have said buffer[64]
610 Revision 1.153 2003/05/30 19:10:56 cheshire
611 <rdar://problem/3274153> ConstructServiceName needs to be more restrictive
613 Revision 1.152 2003/05/29 22:39:16 cheshire
614 <rdar://problem/3273209> Don't truncate strings in the middle of a UTF-8 character
616 Revision 1.151 2003/05/29 06:35:42 cheshire
617 <rdar://problem/3272221> mDNSCoreReceiveResponse() purging wrong record
619 Revision 1.150 2003/05/29 06:25:45 cheshire
620 <rdar://problem/3272218> Need to call CheckCacheExpiration() *before* AnswerNewQuestion()
622 Revision 1.149 2003/05/29 06:18:39 cheshire
623 <rdar://problem/3272217> Split AnswerLocalQuestions into CacheRecordAdd and CacheRecordRmv
625 Revision 1.148 2003/05/29 06:11:34 cheshire
626 <rdar://problem/3272214> Report if there appear to be too many "Resolve" callbacks
628 Revision 1.147 2003/05/29 06:01:18 cheshire
629 Change some debugf() calls to LogMsg() calls to help with debugging
631 Revision 1.146 2003/05/28 21:00:44 cheshire
632 Re-enable "immediate answer burst" debugf message
634 Revision 1.145 2003/05/28 20:57:44 cheshire
635 <rdar://problem/3271550> mDNSResponder reports "Cannot perform multi-packet
636 known-answer suppression ..." This is a known issue caused by a bug in the OS X 10.2
637 version of mDNSResponder, so for now we should suppress this warning message.
639 Revision 1.144 2003/05/28 18:05:12 cheshire
640 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
641 Fix silly mistake: old logic allowed "TDP" and "UCP" as valid names
643 Revision 1.143 2003/05/28 04:31:29 cheshire
644 <rdar://problem/3270733> mDNSResponder not sending probes at the prescribed time
646 Revision 1.142 2003/05/28 03:13:07 cheshire
647 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
648 Require that the transport protocol be _udp or _tcp
650 Revision 1.141 2003/05/28 02:19:12 cheshire
651 <rdar://problem/3270634> Misleading messages generated by iChat
652 Better fix: Only generate the log message for queries where the TC bit is set.
654 Revision 1.140 2003/05/28 01:55:24 cheshire
655 Minor change to log messages
657 Revision 1.139 2003/05/28 01:52:51 cheshire
658 <rdar://problem/3270634> Misleading messages generated by iChat
660 Revision 1.138 2003/05/27 22:35:00 cheshire
661 <rdar://problem/3270277> mDNS_RegisterInterface needs to retrigger questions
663 Revision 1.137 2003/05/27 20:04:33 cheshire
664 <rdar://problem/3269900> mDNSResponder crash in mDNS_vsnprintf()
666 Revision 1.136 2003/05/27 18:50:07 cheshire
667 <rdar://problem/3269768> mDNS_StartResolveService doesn't inform client of port number changes
669 Revision 1.135 2003/05/26 04:57:28 cheshire
670 <rdar://problem/3268953> Delay queries when there are already answers in the cache
672 Revision 1.134 2003/05/26 04:54:54 cheshire
673 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
674 Accidentally deleted '%' case from the switch statement
676 Revision 1.133 2003/05/26 03:21:27 cheshire
677 Tidy up address structure naming:
678 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
679 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
680 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
682 Revision 1.132 2003/05/26 03:01:26 cheshire
683 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
685 Revision 1.131 2003/05/26 00:42:05 cheshire
686 <rdar://problem/3268876> Temporarily include mDNSResponder version in packets
688 Revision 1.130 2003/05/24 16:39:48 cheshire
689 <rdar://problem/3268631> SendResponses also needs to handle multihoming better
691 Revision 1.129 2003/05/23 02:15:37 cheshire
692 Fixed misleading use of the term "duplicate suppression" where it should have
693 said "known answer suppression". (Duplicate answer suppression is something
694 different, and duplicate question suppression is yet another thing, so the use
695 of the completely vague term "duplicate suppression" was particularly bad.)
697 Revision 1.128 2003/05/23 01:55:13 cheshire
698 <rdar://problem/3267127> After name change, mDNSResponder needs to re-probe for name uniqueness
700 Revision 1.127 2003/05/23 01:02:15 ksekar
701 Bug #: <rdar://problem/3032577>: mDNSResponder needs to include unique id in default name
703 Revision 1.126 2003/05/22 02:29:22 cheshire
704 <rdar://problem/2984918> SendQueries needs to handle multihoming better
705 Complete rewrite of SendQueries. Works much better now :-)
707 Revision 1.125 2003/05/22 01:50:45 cheshire
708 Fix warnings, and improve log messages
710 Revision 1.124 2003/05/22 01:41:50 cheshire
711 DiscardDeregistrations doesn't need InterfaceID parameter
713 Revision 1.123 2003/05/22 01:38:55 cheshire
714 Change bracketing of #pragma mark
716 Revision 1.122 2003/05/21 19:59:04 cheshire
717 <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
718 Minor refinements; make sure we don't truncate in the middle of a multi-byte UTF-8 character
720 Revision 1.121 2003/05/21 17:54:07 ksekar
721 Bug #: <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
722 New rename behavior - domain name "foo" becomes "foo--2" on conflict, richtext name becomes "foo (2)"
724 Revision 1.120 2003/05/19 22:14:14 ksekar
725 <rdar://problem/3162914> mDNS probe denials/conflicts not detected unless conflict is of the same type
727 Revision 1.119 2003/05/16 01:34:10 cheshire
730 Revision 1.118 2003/05/14 18:48:40 cheshire
731 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
732 More minor refinements:
733 CFSocket.c needs to do *all* its mDNS_DeregisterInterface calls before freeing memory
734 mDNS_DeregisterInterface revalidates cache record when *any* representative of an interface goes away
736 Revision 1.117 2003/05/14 07:08:36 cheshire
737 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
738 Previously, when there was any network configuration change, mDNSResponder
739 would tear down the entire list of active interfaces and start again.
740 That was very disruptive, and caused the entire cache to be flushed,
741 and caused lots of extra network traffic. Now it only removes interfaces
742 that have really gone, and only adds new ones that weren't there before.
744 Revision 1.116 2003/05/14 06:51:56 cheshire
745 <rdar://problem/3027144> Rendezvous doesn't refresh server info if changed during sleep
747 Revision 1.115 2003/05/14 06:44:31 cheshire
748 Improve debugging message
750 Revision 1.114 2003/05/07 01:47:03 cheshire
751 <rdar://problem/3250330> Also protect against NULL domainlabels
753 Revision 1.113 2003/05/07 00:28:18 cheshire
754 <rdar://problem/3250330> Need to make mDNSResponder more defensive against bad clients
756 Revision 1.112 2003/05/06 00:00:46 cheshire
757 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
759 Revision 1.111 2003/05/05 23:42:08 cheshire
760 <rdar://problem/3245631> Resolves never succeed
761 Was setting "rr->LastAPTime = timenow - rr->LastAPTime"
762 instead of "rr->LastAPTime = timenow - rr->ThisAPInterval"
764 Revision 1.110 2003/04/30 21:09:59 cheshire
765 <rdar://problem/3244727> mDNS_vsnprintf needs to be more defensive against invalid domain names
767 Revision 1.109 2003/04/26 02:41:56 cheshire
768 <rdar://problem/3241281> Change timenow from a local variable to a structure member
770 Revision 1.108 2003/04/25 01:45:56 cheshire
771 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
773 Revision 1.107 2003/04/25 00:41:31 cheshire
774 <rdar://problem/3239912> Create single routine PurgeCacheResourceRecord(), to avoid bugs in future
776 Revision 1.106 2003/04/22 03:14:45 cheshire
777 <rdar://problem/3232229> Include Include instrumented mDNSResponder in panther now
779 Revision 1.105 2003/04/22 01:07:43 cheshire
780 <rdar://problem/3176248> DNSServiceRegistrationUpdateRecord should support a default ttl
781 If TTL parameter is zero, leave record TTL unchanged
783 Revision 1.104 2003/04/21 19:15:52 cheshire
784 Fix some compiler warnings
786 Revision 1.103 2003/04/19 02:26:35 cheshire
787 Bug #: <rdar://problem/3233804> Incorrect goodbye packet after conflict
789 Revision 1.102 2003/04/17 03:06:28 cheshire
790 Bug #: <rdar://problem/3231321> No need to query again when a service goes away
791 Set UnansweredQueries to 2 when receiving a "goodbye" packet
793 Revision 1.101 2003/04/15 20:58:31 jgraessl
795 Added a hash to lookup records in the cache.
797 Revision 1.100 2003/04/15 18:53:14 cheshire
798 Bug #: <rdar://problem/3229064> Bug in ScheduleNextTask
799 mDNS.c 1.94 incorrectly combined two "if" statements into one.
801 Revision 1.99 2003/04/15 18:09:13 jgraessl
803 Reviewed by: Stuart Cheshire
804 Added code to keep track of when the next cache item will expire so we can
805 call TidyRRCache only when necessary.
807 Revision 1.98 2003/04/03 03:43:55 cheshire
808 <rdar://problem/3216837> Off-by-one error in probe rate limiting
810 Revision 1.97 2003/04/02 01:48:17 cheshire
811 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
812 Additional fix pointed out by Josh:
813 Also set ProbeFailTime when incrementing NumFailedProbes when resetting a record back to probing state
815 Revision 1.96 2003/04/01 23:58:55 cheshire
816 Minor comment changes
818 Revision 1.95 2003/04/01 23:46:05 cheshire
819 <rdar://problem/3214832> mDNSResponder can get stuck in infinite loop after many location cycles
820 mDNS_DeregisterInterface() flushes the RR cache by marking all records received on that interface
821 to expire in one second. However, if a mDNS_StartResolveService() call is made in that one-second
822 window, it can get an SRV answer from one of those soon-to-be-deleted records, resulting in
823 FoundServiceInfoSRV() making an interface-specific query on the interface that was just removed.
825 Revision 1.94 2003/03/29 01:55:19 cheshire
826 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
827 Solution: Major cleanup of packet timing and conflict handling rules
829 Revision 1.93 2003/03/28 01:54:36 cheshire
830 Minor tidyup of IPv6 (AAAA) code
832 Revision 1.92 2003/03/27 03:30:55 cheshire
833 <rdar://problem/3210018> Name conflicts not handled properly, resulting in memory corruption, and eventual crash
834 Problem was that HostNameCallback() was calling mDNS_DeregisterInterface(), which is not safe in a callback
836 1. Make mDNS_DeregisterInterface() safe to call from a callback
837 2. Make HostNameCallback() use mDNS_DeadvertiseInterface() instead
838 (it never really needed to deregister the interface at all)
840 Revision 1.91 2003/03/15 04:40:36 cheshire
841 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
843 Revision 1.90 2003/03/14 20:26:37 cheshire
844 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
846 Revision 1.89 2003/03/12 19:57:50 cheshire
847 Fixed typo in debug message
849 Revision 1.88 2003/03/12 00:17:44 cheshire
850 <rdar://problem/3195426> GetFreeCacheRR needs to be more willing to throw away recent records
852 Revision 1.87 2003/03/11 01:27:20 cheshire
853 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
855 Revision 1.86 2003/03/06 20:44:33 cheshire
858 Revision 1.85 2003/03/05 03:38:35 cheshire
859 Bug #: 3185731 Bogus error message in console: died or deallocated, but no record of client can be found!
860 Fixed by leaving client in list after conflict, until client explicitly deallocates
862 Revision 1.84 2003/03/05 01:27:30 cheshire
863 Bug #: 3185482 Different TTL for multicast versus unicast responses
864 When building unicast responses, record TTLs are capped to 10 seconds
866 Revision 1.83 2003/03/04 23:48:52 cheshire
867 Bug #: 3188865 Double probes after wake from sleep
868 Don't reset record type to kDNSRecordTypeUnique if record is DependentOn another
870 Revision 1.82 2003/03/04 23:38:29 cheshire
871 Bug #: 3099194 mDNSResponder needs performance improvements
872 Only set rr->CRActiveQuestion to point to the
873 currently active representative of a question set
875 Revision 1.81 2003/02/21 03:35:34 cheshire
876 Bug #: 3179007 mDNSResponder needs to include AAAA records in additional answer section
878 Revision 1.80 2003/02/21 02:47:53 cheshire
879 Bug #: 3099194 mDNSResponder needs performance improvements
880 Several places in the code were calling CacheRRActive(), which searched the entire
881 question list every time, to see if this cache resource record answers any question.
882 Instead, we now have a field "CRActiveQuestion" in the resource record structure
884 Revision 1.79 2003/02/21 01:54:07 cheshire
885 Bug #: 3099194 mDNSResponder needs performance improvements
886 Switched to using new "mDNS_Execute" model (see "Implementer Notes.txt")
888 Revision 1.78 2003/02/20 06:48:32 cheshire
889 Bug #: 3169535 Xserve RAID needs to do interface-specific registrations
890 Reviewed by: Josh Graessley, Bob Bradley
892 Revision 1.77 2003/01/31 03:35:59 cheshire
893 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
894 When there were *two* active questions in the list, they were incorrectly
895 finding *each other* and *both* being marked as duplicates of another question
897 Revision 1.76 2003/01/29 02:46:37 cheshire
899 A physical interface is identified solely by its InterfaceID (not by IP and type).
900 On a given InterfaceID, mDNSCore may send both v4 and v6 multicasts.
901 In cases where the requested outbound protocol (v4 or v6) is not supported on
902 that InterfaceID, the platform support layer should simply discard that packet.
904 Revision 1.75 2003/01/29 01:47:40 cheshire
905 Rename 'Active' to 'CRActive' or 'InterfaceActive' for improved clarity
907 Revision 1.74 2003/01/28 05:26:25 cheshire
908 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
909 Add 'Active' flag for interfaces
911 Revision 1.73 2003/01/28 03:45:12 cheshire
912 Fixed missing "not" in "!mDNSAddrIsDNSMulticast(dstaddr)"
914 Revision 1.72 2003/01/28 01:49:48 cheshire
915 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
916 FindDuplicateQuestion() was incorrectly finding the question itself in the list,
917 and incorrectly marking it as a duplicate (of itself), so that it became inactive.
919 Revision 1.71 2003/01/28 01:41:44 cheshire
920 Bug #: 3153091 Race condition when network change causes bad stuff
921 When an interface goes away, interface-specific questions on that interface become orphaned.
922 Orphan questions cause HaveQueries to return true, but there's no interface to send them on.
923 Fix: mDNS_DeregisterInterface() now calls DeActivateInterfaceQuestions()
925 Revision 1.70 2003/01/23 19:00:20 cheshire
926 Protect against infinite loops in mDNS_Execute
928 Revision 1.69 2003/01/21 22:56:32 jgraessl
929 Bug #: 3124348 service name changes are not properly handled
930 Submitted by: Stuart Cheshire
931 Reviewed by: Joshua Graessley
932 Applying changes for 3124348 to main branch. 3124348 changes went in to a
935 Revision 1.68 2003/01/17 04:09:27 cheshire
936 Bug #: 3141038 mDNSResponder Resolves are unreliable on multi-homed hosts
938 Revision 1.67 2003/01/17 03:56:45 cheshire
939 Default 24-hour TTL is far too long. Changing to two hours.
941 Revision 1.66 2003/01/13 23:49:41 jgraessl
942 Merged changes for the following fixes in to top of tree:
943 3086540 computer name changes not handled properly
944 3124348 service name changes are not properly handled
945 3124352 announcements sent in pairs, failing chattiness test
947 Revision 1.65 2002/12/23 22:13:28 jgraessl
948 Reviewed by: Stuart Cheshire
949 Initial IPv6 support for mDNSResponder.
951 Revision 1.64 2002/11/26 20:49:06 cheshire
952 Bug #: 3104543 RFC 1123 allows the first character of a name label to be either a letter or a digit
954 Revision 1.63 2002/09/21 20:44:49 zarzycki
957 Revision 1.62 2002/09/20 03:25:37 cheshire
958 Fix some compiler warnings
960 Revision 1.61 2002/09/20 01:05:24 cheshire
961 Don't kill the Extras list in mDNS_DeregisterService()
963 Revision 1.60 2002/09/19 23:47:35 cheshire
964 Added mDNS_RegisterNoSuchService() function for assertion of non-existance
965 of a particular named service
967 Revision 1.59 2002/09/19 21:25:34 cheshire
968 mDNS_snprintf() doesn't need to be in a separate file
970 Revision 1.58 2002/09/19 04:20:43 cheshire
971 Remove high-ascii characters that confuse some systems
973 Revision 1.57 2002/09/17 01:07:08 cheshire
974 Change mDNS_AdvertiseLocalAddresses to be a parameter to mDNS_Init()
976 Revision 1.56 2002/09/16 19:44:17 cheshire
977 Merge in license terms from Quinn's copy, in preparation for Darwin release
980 #define TEST_LOCALONLY_FOR_EVERYTHING 0
982 #include "mDNSClientAPI.h" // Defines the interface provided to the client layer above
983 #include "mDNSPlatformFunctions.h" // Defines the interface required of the supporting layer below
985 // Disable certain benign warnings with Microsoft compilers
986 #if(defined(_MSC_VER))
987 // Disable "conditional expression is constant" warning for debug macros.
988 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
989 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
990 #pragma warning(disable:4127)
992 // Disable "const object should be initialized"
993 // We know that static/globals are defined to be zeroed in ANSI C, and to avoid this warning would require some
994 // *really* ugly chunk of zeroes and curly braces to initialize zeroRR and mDNSprintf_format_default to all zeroes
995 #pragma warning(disable:4132)
997 // Disable "assignment within conditional expression".
998 // Other compilers understand the convention that if you place the assignment expression within an extra pair
999 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
1000 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
1001 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
1002 #pragma warning(disable:4706)
1005 // ***************************************************************************
1006 #if COMPILER_LIKES_PRAGMA_MARK
1007 #pragma mark - DNS Protocol Constants
1012 kDNSFlag0_QR_Mask
= 0x80, // Query or response?
1013 kDNSFlag0_QR_Query
= 0x00,
1014 kDNSFlag0_QR_Response
= 0x80,
1016 kDNSFlag0_OP_Mask
= 0x78, // Operation type
1017 kDNSFlag0_OP_StdQuery
= 0x00,
1018 kDNSFlag0_OP_Iquery
= 0x08,
1019 kDNSFlag0_OP_Status
= 0x10,
1020 kDNSFlag0_OP_Unused3
= 0x18,
1021 kDNSFlag0_OP_Notify
= 0x20,
1022 kDNSFlag0_OP_Update
= 0x28,
1024 kDNSFlag0_QROP_Mask
= kDNSFlag0_QR_Mask
| kDNSFlag0_OP_Mask
,
1026 kDNSFlag0_AA
= 0x04, // Authoritative Answer?
1027 kDNSFlag0_TC
= 0x02, // Truncated?
1028 kDNSFlag0_RD
= 0x01, // Recursion Desired?
1029 kDNSFlag1_RA
= 0x80, // Recursion Available?
1031 kDNSFlag1_Zero
= 0x40, // Reserved; must be zero
1032 kDNSFlag1_AD
= 0x20, // Authentic Data [RFC 2535]
1033 kDNSFlag1_CD
= 0x10, // Checking Disabled [RFC 2535]
1035 kDNSFlag1_RC
= 0x0F, // Response code
1036 kDNSFlag1_RC_NoErr
= 0x00,
1037 kDNSFlag1_RC_FmtErr
= 0x01,
1038 kDNSFlag1_RC_SrvErr
= 0x02,
1039 kDNSFlag1_RC_NXDomain
= 0x03,
1040 kDNSFlag1_RC_NotImpl
= 0x04,
1041 kDNSFlag1_RC_Refused
= 0x05,
1042 kDNSFlag1_RC_YXDomain
= 0x06,
1043 kDNSFlag1_RC_YXRRSet
= 0x07,
1044 kDNSFlag1_RC_NXRRSet
= 0x08,
1045 kDNSFlag1_RC_NotAuth
= 0x09,
1046 kDNSFlag1_RC_NotZone
= 0x0A
1049 // ***************************************************************************
1050 #if COMPILER_LIKES_PRAGMA_MARK
1052 #pragma mark - Program Constants
1055 mDNSexport
const ResourceRecord zeroRR
;
1056 mDNSexport
const mDNSIPPort zeroIPPort
= { { 0 } };
1057 mDNSexport
const mDNSv4Addr zeroIPAddr
= { { 0 } };
1058 mDNSexport
const mDNSv6Addr zerov6Addr
= { { 0 } };
1059 mDNSexport
const mDNSv4Addr onesIPv4Addr
= { { 255, 255, 255, 255 } };
1060 mDNSexport
const mDNSv6Addr onesIPv6Addr
= { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } };
1061 mDNSlocal
const mDNSAddr zeroAddr
= { mDNSAddrType_None
, {{{ 0 }}} };
1063 mDNSexport
const mDNSInterfaceID mDNSInterface_Any
= { 0 };
1064 mDNSlocal
const mDNSInterfaceID mDNSInterfaceMark
= { (mDNSInterfaceID
)~0 };
1066 #define UnicastDNSPortAsNumber 53
1067 #define MulticastDNSPortAsNumber 5353
1068 mDNSexport
const mDNSIPPort UnicastDNSPort
= { { UnicastDNSPortAsNumber
>> 8, UnicastDNSPortAsNumber
& 0xFF } };
1069 mDNSexport
const mDNSIPPort MulticastDNSPort
= { { MulticastDNSPortAsNumber
>> 8, MulticastDNSPortAsNumber
& 0xFF } };
1070 mDNSexport
const mDNSv4Addr AllDNSAdminGroup
= { { 239, 255, 255, 251 } };
1071 mDNSexport
const mDNSv4Addr AllDNSLinkGroup
= { { 224, 0, 0, 251 } };
1072 mDNSexport
const mDNSv6Addr AllDNSLinkGroupv6
= { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } };
1073 mDNSexport
const mDNSAddr AllDNSLinkGroup_v4
= { mDNSAddrType_IPv4
, { { { 224, 0, 0, 251 } } } };
1074 mDNSexport
const mDNSAddr AllDNSLinkGroup_v6
= { mDNSAddrType_IPv6
, { { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } } } };
1076 static const mDNSOpaque16 zeroID
= { { 0, 0 } };
1077 static const mDNSOpaque16 QueryFlags
= { { kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
, 0 } };
1078 static const mDNSOpaque16 ResponseFlags
= { { kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
| kDNSFlag0_AA
, 0 } };
1079 #define zeroDomainNamePtr ((domainname*)"")
1081 // Any records bigger than this are considered 'large' records
1082 #define SmallRecordLimit 1024
1084 #define kDefaultTTLforUnique 240
1085 #define kDefaultTTLforShared (2*3600)
1087 #define kMaxUpdateCredits 10
1089 static const char *const mDNS_DomainTypeNames
[] =
1091 "_browse._mdns._udp.local.",
1092 "_default._browse._mdns._udp.local.",
1093 "_register._mdns._udp.local.",
1094 "_default._register._mdns._udp.local."
1097 #define AssignDomainName(DST, SRC) mDNSPlatformMemCopy((SRC).c, (DST).c, DomainNameLength(&(SRC)))
1099 // ***************************************************************************
1100 #if COMPILER_LIKES_PRAGMA_MARK
1102 #pragma mark - Specialized mDNS version of vsnprintf
1105 static const struct mDNSprintf_format
1107 unsigned leftJustify
: 1;
1108 unsigned forceSign
: 1;
1109 unsigned zeroPad
: 1;
1110 unsigned havePrecision
: 1;
1114 char sign
; // +, - or space
1115 unsigned int fieldWidth
;
1116 unsigned int precision
;
1117 } mDNSprintf_format_default
;
1119 mDNSexport mDNSu32
mDNS_vsnprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, va_list arg
)
1121 mDNSu32 nwritten
= 0;
1123 buflen
--; // Pre-reserve one space in the buffer for the terminating nul
1125 for (c
= *fmt
; c
!= 0; c
= *++fmt
)
1129 *sbuffer
++ = (char)c
;
1130 if (++nwritten
>= buflen
) goto exit
;
1134 unsigned int i
=0, j
;
1135 // The mDNS Vsprintf Argument Conversion Buffer is used as a temporary holding area for
1136 // generating decimal numbers, hexdecimal numbers, IP addresses, domain name strings, etc.
1137 // The size needs to be enough for a 256-byte domain name plus some error text.
1138 #define mDNS_VACB_Size 300
1139 char mDNS_VACB
[mDNS_VACB_Size
];
1140 #define mDNS_VACB_Lim (&mDNS_VACB[mDNS_VACB_Size])
1141 #define mDNS_VACB_Remain(s) ((mDNSu32)(mDNS_VACB_Lim - s))
1142 char *s
= mDNS_VACB_Lim
, *digits
;
1143 struct mDNSprintf_format F
= mDNSprintf_format_default
;
1145 while (1) // decode flags
1148 if (c
== '-') F
.leftJustify
= 1;
1149 else if (c
== '+') F
.forceSign
= 1;
1150 else if (c
== ' ') F
.sign
= ' ';
1151 else if (c
== '#') F
.altForm
++;
1152 else if (c
== '0') F
.zeroPad
= 1;
1156 if (c
== '*') // decode field width
1158 int f
= va_arg(arg
, int);
1159 if (f
< 0) { f
= -f
; F
.leftJustify
= 1; }
1160 F
.fieldWidth
= (unsigned int)f
;
1165 for (; c
>= '0' && c
<= '9'; c
= *++fmt
)
1166 F
.fieldWidth
= (10 * F
.fieldWidth
) + (c
- '0');
1169 if (c
== '.') // decode precision
1171 if ((c
= *++fmt
) == '*')
1172 { F
.precision
= va_arg(arg
, unsigned int); c
= *++fmt
; }
1173 else for (; c
>= '0' && c
<= '9'; c
= *++fmt
)
1174 F
.precision
= (10 * F
.precision
) + (c
- '0');
1175 F
.havePrecision
= 1;
1178 if (F
.leftJustify
) F
.zeroPad
= 0;
1181 switch (c
) // perform appropriate conversion
1184 case 'h' : F
.hSize
= 1; c
= *++fmt
; goto conv
;
1185 case 'l' : // fall through
1186 case 'L' : F
.lSize
= 1; c
= *++fmt
; goto conv
;
1188 case 'i' : if (F
.lSize
) n
= (unsigned long)va_arg(arg
, long);
1189 else n
= (unsigned long)va_arg(arg
, int);
1190 if (F
.hSize
) n
= (short) n
;
1191 if ((long) n
< 0) { n
= (unsigned long)-(long)n
; F
.sign
= '-'; }
1192 else if (F
.forceSign
) F
.sign
= '+';
1194 case 'u' : if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1195 else n
= va_arg(arg
, unsigned int);
1196 if (F
.hSize
) n
= (unsigned short) n
;
1199 decimal
: if (!F
.havePrecision
)
1203 F
.precision
= F
.fieldWidth
;
1204 if (F
.sign
) --F
.precision
;
1206 if (F
.precision
< 1) F
.precision
= 1;
1208 if (F
.precision
> mDNS_VACB_Size
- 1)
1209 F
.precision
= mDNS_VACB_Size
- 1;
1210 for (i
= 0; n
; n
/= 10, i
++) *--s
= (char)(n
% 10 + '0');
1211 for (; i
< F
.precision
; i
++) *--s
= '0';
1212 if (F
.sign
) { *--s
= F
.sign
; i
++; }
1215 case 'o' : if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1216 else n
= va_arg(arg
, unsigned int);
1217 if (F
.hSize
) n
= (unsigned short) n
;
1218 if (!F
.havePrecision
)
1220 if (F
.zeroPad
) F
.precision
= F
.fieldWidth
;
1221 if (F
.precision
< 1) F
.precision
= 1;
1223 if (F
.precision
> mDNS_VACB_Size
- 1)
1224 F
.precision
= mDNS_VACB_Size
- 1;
1225 for (i
= 0; n
; n
/= 8, i
++) *--s
= (char)(n
% 8 + '0');
1226 if (F
.altForm
&& i
&& *s
!= '0') { *--s
= '0'; i
++; }
1227 for (; i
< F
.precision
; i
++) *--s
= '0';
1231 unsigned char *a
= va_arg(arg
, unsigned char *);
1232 if (!a
) { static char emsg
[] = "<<NULL>>"; s
= emsg
; i
= sizeof(emsg
)-1; }
1235 unsigned short *w
= (unsigned short *)a
;
1236 s
= mDNS_VACB
; // Adjust s to point to the start of the buffer, not the end
1239 mDNSAddr
*ip
= (mDNSAddr
*)a
;
1240 a
= (unsigned char *)&ip
->ip
.v4
;
1241 w
= (unsigned short *)&ip
->ip
.v6
;
1244 case mDNSAddrType_IPv4
: F
.precision
= 4; break;
1245 case mDNSAddrType_IPv6
: F
.precision
= 16; break;
1246 default: F
.precision
= 0; break;
1249 switch (F
.precision
)
1251 case 4: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%d.%d.%d.%d",
1252 a
[0], a
[1], a
[2], a
[3]); break;
1253 case 6: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%02X:%02X:%02X:%02X:%02X:%02X",
1254 a
[0], a
[1], a
[2], a
[3], a
[4], a
[5]); break;
1255 case 16: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X",
1256 w
[0], w
[1], w
[2], w
[3], w
[4], w
[5], w
[6], w
[7]); break;
1257 default: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%s", "<< ERROR: Must specify address size "
1258 "(i.e. %.4a=IPv4, %.6a=Ethernet, %.16a=IPv6) >>"); break;
1264 case 'p' : F
.havePrecision
= F
.lSize
= 1;
1266 case 'X' : digits
= "0123456789ABCDEF";
1268 case 'x' : digits
= "0123456789abcdef";
1269 hexadecimal
:if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1270 else n
= va_arg(arg
, unsigned int);
1271 if (F
.hSize
) n
= (unsigned short) n
;
1272 if (!F
.havePrecision
)
1276 F
.precision
= F
.fieldWidth
;
1277 if (F
.altForm
) F
.precision
-= 2;
1279 if (F
.precision
< 1) F
.precision
= 1;
1281 if (F
.precision
> mDNS_VACB_Size
- 1)
1282 F
.precision
= mDNS_VACB_Size
- 1;
1283 for (i
= 0; n
; n
/= 16, i
++) *--s
= digits
[n
% 16];
1284 for (; i
< F
.precision
; i
++) *--s
= '0';
1285 if (F
.altForm
) { *--s
= (char)c
; *--s
= '0'; i
+= 2; }
1288 case 'c' : *--s
= (char)va_arg(arg
, int); i
= 1; break;
1290 case 's' : s
= va_arg(arg
, char *);
1291 if (!s
) { static char emsg
[] = "<<NULL>>"; s
= emsg
; i
= sizeof(emsg
)-1; }
1292 else switch (F
.altForm
)
1294 case 0: { char *a
=s
; i
=0; while(*a
++) i
++; break; } // C string
1295 case 1: i
= (unsigned char) *s
++; break; // Pascal string
1296 case 2: { // DNS label-sequence name
1297 unsigned char *a
= (unsigned char *)s
;
1298 s
= mDNS_VACB
; // Adjust s to point to the start of the buffer, not the end
1299 if (*a
== 0) *s
++ = '.'; // Special case for root DNS name
1302 if (*a
> 63) { s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "<<INVALID LABEL LENGTH %u>>", *a
); break; }
1303 if (s
+ *a
>= &mDNS_VACB
[254]) { s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "<<NAME TOO LONG>>"); break; }
1304 s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "%#s.", a
);
1307 i
= (mDNSu32
)(s
- mDNS_VACB
);
1308 s
= mDNS_VACB
; // Reset s back to the start of the buffer
1312 if (F
.havePrecision
&& i
> F
.precision
) // Make sure we don't truncate in the middle of a UTF-8 character
1313 { i
= F
.precision
; while (i
>0 && (s
[i
] & 0xC0) == 0x80) i
--; }
1316 case 'n' : s
= va_arg(arg
, char *);
1317 if (F
.hSize
) * (short *) s
= (short)nwritten
;
1318 else if (F
.lSize
) * (long *) s
= (long)nwritten
;
1319 else * (int *) s
= (int)nwritten
;
1322 default: s
= mDNS_VACB
;
1323 i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "<<UNKNOWN FORMAT CONVERSION CODE %%%c>>", c
);
1325 case '%' : *sbuffer
++ = (char)c
;
1326 if (++nwritten
>= buflen
) goto exit
;
1330 if (i
< F
.fieldWidth
&& !F
.leftJustify
) // Pad on the left
1333 if (++nwritten
>= buflen
) goto exit
;
1334 } while (i
< --F
.fieldWidth
);
1336 if (i
> buflen
- nwritten
) // Make sure we don't truncate in the middle of a UTF-8 character
1337 { i
= buflen
- nwritten
; while (i
>0 && (s
[i
] & 0xC0) == 0x80) i
--; }
1338 for (j
=0; j
<i
; j
++) *sbuffer
++ = *s
++; // Write the converted result
1340 if (nwritten
>= buflen
) goto exit
;
1342 for (; i
< F
.fieldWidth
; i
++) // Pad on the right
1345 if (++nwritten
>= buflen
) goto exit
;
1354 mDNSexport mDNSu32
mDNS_snprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, ...)
1360 length
= mDNS_vsnprintf(sbuffer
, buflen
, fmt
, ptr
);
1366 // ***************************************************************************
1367 #if COMPILER_LIKES_PRAGMA_MARK
1369 #pragma mark - General Utility Functions
1372 mDNSexport
char *DNSTypeName(mDNSu16 rrtype
)
1376 case kDNSType_A
: return("Addr");
1377 case kDNSType_CNAME
:return("CNAME");
1378 case kDNSType_NULL
: return("NULL");
1379 case kDNSType_PTR
: return("PTR");
1380 case kDNSType_HINFO
:return("HINFO");
1381 case kDNSType_TXT
: return("TXT");
1382 case kDNSType_AAAA
: return("AAAA");
1383 case kDNSType_SRV
: return("SRV");
1384 case kDNSQType_ANY
: return("ANY");
1386 static char buffer
[16];
1387 mDNS_snprintf(buffer
, sizeof(buffer
), "(%d)", rrtype
);
1393 mDNSexport
char *GetRRDisplayString_rdb(mDNS
*const m
, const ResourceRecord
*rr
, RDataBody
*rd
)
1395 char *ptr
= m
->MsgBuffer
;
1396 mDNSu32 length
= mDNS_snprintf(m
->MsgBuffer
, 79, "%4d %##s %s ", rr
->rdlength
, rr
->name
.c
, DNSTypeName(rr
->rrtype
));
1399 case kDNSType_A
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%.4a", &rd
->ip
); break;
1400 case kDNSType_CNAME
:// Same as PTR
1401 case kDNSType_PTR
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%##s", &rd
->name
); break;
1402 case kDNSType_HINFO
:// Display this the same as TXT (just show first string)
1403 case kDNSType_TXT
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%#s", rd
->txt
.c
); break;
1404 case kDNSType_AAAA
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%.16a", &rd
->ipv6
); break;
1405 case kDNSType_SRV
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%##s", &rd
->srv
.target
); break;
1406 default: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "RDLen %d: %s",
1407 rr
->rdlength
, rd
->data
); break;
1409 for (ptr
= m
->MsgBuffer
; *ptr
; ptr
++) if (*ptr
< ' ') *ptr
='.';
1410 return(m
->MsgBuffer
);
1413 mDNSlocal mDNSu32
mDNSRandom(mDNSu32 max
)
1415 static mDNSu32 seed
= 0;
1418 if (!seed
) seed
= (mDNSu32
)mDNSPlatformTimeNow();
1419 while (mask
< max
) mask
= (mask
<< 1) | 1;
1420 do seed
= seed
* 21 + 1; while ((seed
& mask
) > max
);
1421 return (seed
& mask
);
1424 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
1425 #define mDNSSameIPv6Address(A,B) ((A).l[0] == (B).l[0] && (A).l[1] == (B).l[1] && (A).l[2] == (B).l[2] && (A).l[3] == (B).l[3])
1427 #define mDNSIPv4AddressIsZero(A) mDNSSameIPv4Address((A), zeroIPAddr)
1428 #define mDNSIPv6AddressIsZero(A) mDNSSameIPv6Address((A), zerov6Addr)
1430 #define mDNSIPv4AddressIsOnes(A) mDNSSameIPv4Address((A), onesIPv4Addr)
1431 #define mDNSIPv6AddressIsOnes(A) mDNSSameIPv6Address((A), onesIPv6Addr)
1433 #define mDNSAddressIsZero(X) ( \
1434 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4)) || \
1435 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6)) )
1437 #define mDNSAddressIsOnes(X) ( \
1438 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4)) || \
1439 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6)) )
1441 #define mDNSAddressIsValid(X) ( \
1442 ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
1443 ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
1445 mDNSexport mDNSBool
mDNSSameAddress(const mDNSAddr
*ip1
, const mDNSAddr
*ip2
)
1447 if (ip1
->type
== ip2
->type
)
1451 case mDNSAddrType_IPv4
: return(mDNSBool
)(mDNSSameIPv4Address(ip1
->ip
.v4
, ip2
->ip
.v4
));
1452 case mDNSAddrType_IPv6
: return(mDNSBool
)(mDNSSameIPv6Address(ip1
->ip
.v6
, ip2
->ip
.v6
));
1458 mDNSlocal mDNSBool
mDNSAddrIsDNSMulticast(const mDNSAddr
*ip
)
1462 case mDNSAddrType_IPv4
: return(mDNSBool
)(ip
->ip
.v4
.NotAnInteger
== AllDNSLinkGroup
.NotAnInteger
);
1463 case mDNSAddrType_IPv6
: return(mDNSBool
)(ip
->ip
.v6
.l
[0] == AllDNSLinkGroupv6
.l
[0] &&
1464 ip
->ip
.v6
.l
[1] == AllDNSLinkGroupv6
.l
[1] &&
1465 ip
->ip
.v6
.l
[2] == AllDNSLinkGroupv6
.l
[2] &&
1466 ip
->ip
.v6
.l
[3] == AllDNSLinkGroupv6
.l
[3] );
1467 default: return(mDNSfalse
);
1471 mDNSlocal
const NetworkInterfaceInfo
*GetFirstActiveInterface(const NetworkInterfaceInfo
*intf
)
1473 while (intf
&& !intf
->InterfaceActive
) intf
= intf
->next
;
1477 mDNSlocal mDNSInterfaceID
GetNextActiveInterfaceID(const NetworkInterfaceInfo
*intf
)
1479 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
1480 if (next
) return(next
->InterfaceID
); else return(mDNSNULL
);
1483 #define InitialQuestionInterval (mDNSPlatformOneSecond/2)
1484 #define ActiveQuestion(Q) ((Q)->ThisQInterval > 0 && !(Q)->DuplicateOf)
1485 #define TimeToSendThisQuestion(Q,time) (ActiveQuestion(Q) && (time) - ((Q)->LastQTime + (Q)->ThisQInterval) >= 0)
1487 mDNSlocal
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
1489 if (ActiveQuestion(q
))
1490 if (m
->NextScheduledQuery
- (q
->LastQTime
+ q
->ThisQInterval
) > 0)
1491 m
->NextScheduledQuery
= (q
->LastQTime
+ q
->ThisQInterval
);
1494 // ***************************************************************************
1495 #if COMPILER_LIKES_PRAGMA_MARK
1497 #pragma mark - Domain Name Utility Functions
1500 #define mdnsIsDigit(X) ((X) >= '0' && (X) <= '9')
1501 #define mDNSIsUpperCase(X) ((X) >= 'A' && (X) <= 'Z')
1502 #define mDNSIsLowerCase(X) ((X) >= 'a' && (X) <= 'z')
1503 #define mdnsIsLetter(X) (mDNSIsUpperCase(X) || mDNSIsLowerCase(X))
1505 mDNSexport mDNSBool
SameDomainLabel(const mDNSu8
*a
, const mDNSu8
*b
)
1508 const int len
= *a
++;
1510 if (len
> MAX_DOMAIN_LABEL
)
1511 { debugf("Malformed label (too long)"); return(mDNSfalse
); }
1513 if (len
!= *b
++) return(mDNSfalse
);
1514 for (i
=0; i
<len
; i
++)
1518 if (mDNSIsUpperCase(ac
)) ac
+= 'a' - 'A';
1519 if (mDNSIsUpperCase(bc
)) bc
+= 'a' - 'A';
1520 if (ac
!= bc
) return(mDNSfalse
);
1525 mDNSexport mDNSBool
SameDomainName(const domainname
*const d1
, const domainname
*const d2
)
1527 const mDNSu8
* a
= d1
->c
;
1528 const mDNSu8
* b
= d2
->c
;
1529 const mDNSu8
*const max
= d1
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
1533 if (a
+ 1 + *a
>= max
)
1534 { debugf("Malformed domain name (more than 255 characters)"); return(mDNSfalse
); }
1535 if (!SameDomainLabel(a
, b
)) return(mDNSfalse
);
1543 // Returns length of a domain name INCLUDING the byte for the final null label
1544 // i.e. for the root label "." it returns one
1545 // For the FQDN "com." it returns 5 (length byte, three data bytes, final zero)
1546 // Legal results are 1 (just root label) to 255 (MAX_DOMAIN_NAME)
1547 // If the given domainname is invalid, result is 256
1548 mDNSexport mDNSu16
DomainNameLength(const domainname
*const name
)
1550 const mDNSu8
*src
= name
->c
;
1553 if (*src
> MAX_DOMAIN_LABEL
) return(MAX_DOMAIN_NAME
+1);
1555 if (src
- name
->c
>= MAX_DOMAIN_NAME
) return(MAX_DOMAIN_NAME
+1);
1557 return((mDNSu16
)(src
- name
->c
+ 1));
1560 // CompressedDomainNameLength returns the length of a domain name INCLUDING the byte
1561 // for the final null label i.e. for the root label "." it returns one.
1562 // E.g. for the FQDN "foo.com." it returns 9
1563 // (length, three data bytes, length, three more data bytes, final zero).
1564 // In the case where a parent domain name is provided, and the given name is a child
1565 // of that parent, CompressedDomainNameLength returns the length of the prefix portion
1566 // of the child name, plus TWO bytes for the compression pointer.
1567 // E.g. for the name "foo.com." with parent "com.", it returns 6
1568 // (length, three data bytes, two-byte compression pointer).
1569 mDNSlocal mDNSu16
CompressedDomainNameLength(const domainname
*const name
, const domainname
*parent
)
1571 const mDNSu8
*src
= name
->c
;
1572 if (parent
&& parent
->c
[0] == 0) parent
= mDNSNULL
;
1575 if (*src
> MAX_DOMAIN_LABEL
) return(MAX_DOMAIN_NAME
+1);
1576 if (parent
&& SameDomainName((domainname
*)src
, parent
)) return((mDNSu16
)(src
- name
->c
+ 2));
1578 if (src
- name
->c
>= MAX_DOMAIN_NAME
) return(MAX_DOMAIN_NAME
+1);
1580 return((mDNSu16
)(src
- name
->c
+ 1));
1583 // AppendLiteralLabelString appends a single label to an existing (possibly empty) domainname.
1584 // The C string contains the label as-is, with no escaping, etc.
1585 // Any dots in the name are literal dots, not label separators
1586 // If successful, AppendLiteralLabelString returns a pointer to the next unused byte
1587 // in the domainname bufer (i.e., the next byte after the terminating zero).
1588 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1589 // AppendLiteralLabelString returns mDNSNULL.
1590 mDNSexport mDNSu8
*AppendLiteralLabelString(domainname
*const name
, const char *cstr
)
1592 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1593 const mDNSu8
*const lim1
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1594 const mDNSu8
*const lim2
= ptr
+ 1 + MAX_DOMAIN_LABEL
;
1595 const mDNSu8
*const lim
= (lim1
< lim2
) ? lim1
: lim2
;
1596 mDNSu8
*lengthbyte
= ptr
++; // Record where the length is going to go
1598 while (*cstr
&& ptr
< lim
) *ptr
++ = (mDNSu8
)*cstr
++; // Copy the data
1599 *lengthbyte
= (mDNSu8
)(ptr
- lengthbyte
- 1); // Fill in the length byte
1600 *ptr
++ = 0; // Put the null root label on the end
1601 if (*cstr
) return(mDNSNULL
); // Failure: We didn't successfully consume all input
1602 else return(ptr
); // Success: return new value of ptr
1605 // AppendDNSNameString appends zero or more labels to an existing (possibly empty) domainname.
1606 // The C string is in conventional DNS syntax:
1607 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1608 // If successful, AppendDNSNameString returns a pointer to the next unused byte
1609 // in the domainname bufer (i.e., the next byte after the terminating zero).
1610 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1611 // AppendDNSNameString returns mDNSNULL.
1612 mDNSexport mDNSu8
*AppendDNSNameString(domainname
*const name
, const char *cstr
)
1614 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1615 const mDNSu8
*const lim
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1616 while (*cstr
&& ptr
< lim
) // While more characters, and space to put them...
1618 mDNSu8
*lengthbyte
= ptr
++; // Record where the length is going to go
1619 while (*cstr
&& *cstr
!= '.' && ptr
< lim
) // While we have characters in the label...
1621 mDNSu8 c
= (mDNSu8
)*cstr
++; // Read the character
1622 if (c
== '\\') // If escape character, check next character
1624 if (*cstr
== '\\' || *cstr
== '.') // If a second escape, or a dot,
1625 c
= (mDNSu8
)*cstr
++; // just use the second character
1626 else if (mdnsIsDigit(cstr
[0]) && mdnsIsDigit(cstr
[1]) && mdnsIsDigit(cstr
[2]))
1627 { // else, if three decimal digits,
1628 int v0
= cstr
[0] - '0'; // then interpret as three-digit decimal
1629 int v1
= cstr
[1] - '0';
1630 int v2
= cstr
[2] - '0';
1631 int val
= v0
* 100 + v1
* 10 + v2
;
1632 if (val
<= 255) { c
= (mDNSu8
)val
; cstr
+= 3; } // If valid value, use it
1635 *ptr
++ = c
; // Write the character
1637 if (*cstr
) cstr
++; // Skip over the trailing dot (if present)
1638 if (ptr
- lengthbyte
- 1 > MAX_DOMAIN_LABEL
) // If illegal label, abort
1640 *lengthbyte
= (mDNSu8
)(ptr
- lengthbyte
- 1); // Fill in the length byte
1643 *ptr
++ = 0; // Put the null root label on the end
1644 if (*cstr
) return(mDNSNULL
); // Failure: We didn't successfully consume all input
1645 else return(ptr
); // Success: return new value of ptr
1648 // AppendDomainLabel appends a single label to a name.
1649 // If successful, AppendDomainLabel returns a pointer to the next unused byte
1650 // in the domainname bufer (i.e., the next byte after the terminating zero).
1651 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1652 // AppendDomainLabel returns mDNSNULL.
1653 mDNSexport mDNSu8
*AppendDomainLabel(domainname
*const name
, const domainlabel
*const label
)
1656 mDNSu8
*ptr
= name
->c
+ DomainNameLength(name
) - 1;
1658 // Check label is legal
1659 if (label
->c
[0] > MAX_DOMAIN_LABEL
) return(mDNSNULL
);
1661 // Check that ptr + length byte + data bytes + final zero does not exceed our limit
1662 if (ptr
+ 1 + label
->c
[0] + 1 > name
->c
+ MAX_DOMAIN_NAME
) return(mDNSNULL
);
1664 for (i
=0; i
<=label
->c
[0]; i
++) *ptr
++ = label
->c
[i
]; // Copy the label data
1665 *ptr
++ = 0; // Put the null root label on the end
1669 mDNSexport mDNSu8
*AppendDomainName(domainname
*const name
, const domainname
*const append
)
1671 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1672 const mDNSu8
*const lim
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1673 const mDNSu8
* src
= append
->c
;
1677 if (ptr
+ 1 + src
[0] > lim
) return(mDNSNULL
);
1678 for (i
=0; i
<=src
[0]; i
++) *ptr
++ = src
[i
];
1679 *ptr
= 0; // Put the null root label on the end
1685 // MakeDomainLabelFromLiteralString makes a single domain label from a single literal C string (with no escaping).
1686 // If successful, MakeDomainLabelFromLiteralString returns mDNStrue.
1687 // If unable to convert the whole string to a legal domain label (i.e. because length is more than 63 bytes) then
1688 // MakeDomainLabelFromLiteralString makes a legal domain label from the first 63 bytes of the string and returns mDNSfalse.
1689 // In some cases silently truncated oversized names to 63 bytes is acceptable, so the return result may be ignored.
1690 // In other cases silent truncation may not be acceptable, so in those cases the calling function needs to check the return result.
1691 mDNSexport mDNSBool
MakeDomainLabelFromLiteralString(domainlabel
*const label
, const char *cstr
)
1693 mDNSu8
* ptr
= label
->c
+ 1; // Where we're putting it
1694 const mDNSu8
*const limit
= label
->c
+ 1 + MAX_DOMAIN_LABEL
; // The maximum we can put
1695 while (*cstr
&& ptr
< limit
) *ptr
++ = (mDNSu8
)*cstr
++; // Copy the label
1696 label
->c
[0] = (mDNSu8
)(ptr
- label
->c
- 1); // Set the length byte
1697 return(*cstr
== 0); // Return mDNStrue if we successfully consumed all input
1700 // MakeDomainNameFromDNSNameString makes a native DNS-format domainname from a C string.
1701 // The C string is in conventional DNS syntax:
1702 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1703 // If successful, MakeDomainNameFromDNSNameString returns a pointer to the next unused byte
1704 // in the domainname bufer (i.e., the next byte after the terminating zero).
1705 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1706 // MakeDomainNameFromDNSNameString returns mDNSNULL.
1707 mDNSexport mDNSu8
*MakeDomainNameFromDNSNameString(domainname
*const name
, const char *cstr
)
1709 name
->c
[0] = 0; // Make an empty domain name
1710 return(AppendDNSNameString(name
, cstr
)); // And then add this string to it
1713 mDNSexport
char *ConvertDomainLabelToCString_withescape(const domainlabel
*const label
, char *ptr
, char esc
)
1715 const mDNSu8
* src
= label
->c
; // Domain label we're reading
1716 const mDNSu8 len
= *src
++; // Read length of this (non-null) label
1717 const mDNSu8
*const end
= src
+ len
; // Work out where the label ends
1718 if (len
> MAX_DOMAIN_LABEL
) return(mDNSNULL
); // If illegal label, abort
1719 while (src
< end
) // While we have characters in the label
1724 if (c
== '.' || c
== esc
) // If character is a dot or the escape character
1725 *ptr
++ = esc
; // Output escape character
1726 else if (c
<= ' ') // If non-printing ascii,
1727 { // Output decimal escape sequence
1729 *ptr
++ = (char) ('0' + (c
/ 100) );
1730 *ptr
++ = (char) ('0' + (c
/ 10) % 10);
1731 c
= (mDNSu8
)('0' + (c
) % 10);
1734 *ptr
++ = (char)c
; // Copy the character
1736 *ptr
= 0; // Null-terminate the string
1737 return(ptr
); // and return
1740 // Note, to guarantee that there will be no possible overrun, cstr must be at least 1005 bytes
1741 // The longest legal domain name is 255 bytes, in the form of three 64-byte labels, one 62-byte label,
1742 // and the null root label.
1743 // If every label character has to be escaped as a four-byte escape sequence, the maximum textual
1744 // ascii display of this is 63*4 + 63*4 + 63*4 + 61*4 = 1000 label characters,
1745 // plus four dots and the null at the end of the C string = 1005
1746 mDNSexport
char *ConvertDomainNameToCString_withescape(const domainname
*const name
, char *ptr
, char esc
)
1748 const mDNSu8
*src
= name
->c
; // Domain name we're reading
1749 const mDNSu8
*const max
= name
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
1751 if (*src
== 0) *ptr
++ = '.'; // Special case: For root, just write a dot
1753 while (*src
) // While more characters in the domain name
1755 if (src
+ 1 + *src
>= max
) return(mDNSNULL
);
1756 ptr
= ConvertDomainLabelToCString_withescape((const domainlabel
*)src
, ptr
, esc
);
1757 if (!ptr
) return(mDNSNULL
);
1759 *ptr
++ = '.'; // Write the dot after the label
1762 *ptr
++ = 0; // Null-terminate the string
1763 return(ptr
); // and return
1767 // Host names must start with a letter, end with a letter or digit,
1768 // and have as interior characters only letters, digits, and hyphen.
1769 // This was subsequently modified in RFC 1123 to allow the first character to be either a letter or a digit
1770 #define mdnsValidHostChar(X, notfirst, notlast) (mdnsIsLetter(X) || mdnsIsDigit(X) || ((notfirst) && (notlast) && (X) == '-') )
1772 mDNSexport
void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name
[], domainlabel
*const hostlabel
)
1774 const mDNSu8
* src
= &UTF8Name
[1];
1775 const mDNSu8
*const end
= &UTF8Name
[1] + UTF8Name
[0];
1776 mDNSu8
* ptr
= &hostlabel
->c
[1];
1777 const mDNSu8
*const lim
= &hostlabel
->c
[1] + MAX_DOMAIN_LABEL
;
1780 // Delete apostrophes from source name
1781 if (src
[0] == '\'') { src
++; continue; } // Standard straight single quote
1782 if (src
+ 2 < end
&& src
[0] == 0xE2 && src
[1] == 0x80 && src
[2] == 0x99)
1783 { src
+= 3; continue; } // Unicode curly apostrophe
1786 if (mdnsValidHostChar(*src
, (ptr
> &hostlabel
->c
[1]), (src
< end
-1))) *ptr
++ = *src
;
1787 else if (ptr
> &hostlabel
->c
[1] && ptr
[-1] != '-') *ptr
++ = '-';
1791 while (ptr
> &hostlabel
->c
[1] && ptr
[-1] == '-') ptr
--; // Truncate trailing '-' marks
1792 hostlabel
->c
[0] = (mDNSu8
)(ptr
- &hostlabel
->c
[1]);
1795 mDNSexport mDNSu8
*ConstructServiceName(domainname
*const fqdn
,
1796 const domainlabel
*name
, const domainname
*type
, const domainname
*const domain
)
1799 mDNSu8
*dst
= fqdn
->c
;
1801 const char *errormsg
;
1803 // In the case where there is no name (and ONLY in that case),
1804 // a single-label subtype is allowed as the first label of a three-part "type"
1807 const mDNSu8
*s2
= type
->c
+ 1 + type
->c
[0];
1808 if (type
->c
[0] > 0 && type
->c
[0] < 0x40 &&
1809 s2
[0] > 0 && s2
[0] < 0x40 &&
1810 s2
[1+s2
[0]] > 0 && s2
[1+s2
[0]] < 0x40)
1812 name
= (domainlabel
*)type
;
1813 type
= (domainname
*)s2
;
1817 if (name
&& name
->c
[0])
1819 src
= name
->c
; // Put the service name into the domain name
1821 if (len
>= 0x40) { errormsg
="Service instance name too long"; goto fail
; }
1822 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1825 name
= (domainlabel
*)""; // Set this up to be non-null, to avoid errors if we have to call LogMsg() below
1827 src
= type
->c
; // Put the service type into the domain name
1829 if (len
< 2 || len
>= 0x40) { errormsg
="Invalid service application protocol name"; goto fail
; }
1830 if (src
[1] != '_') { errormsg
="Service application protocol name must begin with underscore"; goto fail
; }
1831 for (i
=2; i
<=len
; i
++)
1832 if (!mdnsIsLetter(src
[i
]) && !mdnsIsDigit(src
[i
]) && src
[i
] != '-' && src
[i
] != '_')
1833 { errormsg
="Service application protocol name must contain only letters, digits, and hyphens"; goto fail
; }
1834 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1837 //if (len == 0 || len >= 0x40) { errormsg="Invalid service transport protocol name"; goto fail; }
1838 if (!(len
== 4 && src
[1] == '_' &&
1839 (((src
[2] | 0x20) == 'u' && (src
[3] | 0x20) == 'd') || ((src
[2] | 0x20) == 't' && (src
[3] | 0x20) == 'c')) &&
1840 (src
[4] | 0x20) == 'p'))
1841 { errormsg
="Service transport protocol name must be _udp or _tcp"; goto fail
; }
1842 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1844 if (*src
) { errormsg
="Service type must have only two labels"; goto fail
; }
1847 dst
= AppendDomainName(fqdn
, domain
);
1848 if (!dst
) { errormsg
="Service domain too long"; goto fail
; }
1852 LogMsg("ConstructServiceName: %s: %#s.%##s%##s", errormsg
, name
->c
, type
->c
, domain
->c
);
1856 mDNSexport mDNSBool
DeconstructServiceName(const domainname
*const fqdn
,
1857 domainlabel
*const name
, domainname
*const type
, domainname
*const domain
)
1860 const mDNSu8
*src
= fqdn
->c
;
1861 const mDNSu8
*max
= fqdn
->c
+ MAX_DOMAIN_NAME
;
1864 dst
= name
->c
; // Extract the service name from the domain name
1866 if (len
>= 0x40) { debugf("DeconstructServiceName: service name too long"); return(mDNSfalse
); }
1867 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1869 dst
= type
->c
; // Extract the service type from the domain name
1871 if (len
>= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse
); }
1872 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1875 if (len
>= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse
); }
1876 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1877 *dst
++ = 0; // Put the null root label on the end of the service type
1879 dst
= domain
->c
; // Extract the service domain from the domain name
1884 { debugf("DeconstructServiceName: service domain label too long"); return(mDNSfalse
); }
1885 if (src
+ 1 + len
+ 1 >= max
)
1886 { debugf("DeconstructServiceName: service domain too long"); return(mDNSfalse
); }
1887 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1889 *dst
++ = 0; // Put the null root label on the end
1894 // Returns true if a rich text label ends in " (nnn)", or if an RFC 1034
1895 // name ends in "-nnn", where n is some decimal number.
1896 mDNSlocal mDNSBool
LabelContainsSuffix(const domainlabel
*const name
, const mDNSBool RichText
)
1898 mDNSu16 l
= name
->c
[0];
1902 if (l
< 4) return mDNSfalse
; // Need at least " (2)"
1903 if (name
->c
[l
--] != ')') return mDNSfalse
; // Last char must be ')'
1904 if (!mdnsIsDigit(name
->c
[l
])) return mDNSfalse
; // Preceeded by a digit
1906 while (l
> 2 && mdnsIsDigit(name
->c
[l
])) l
--; // Strip off digits
1907 return (name
->c
[l
] == '(' && name
->c
[l
- 1] == ' ');
1911 if (l
< 2) return mDNSfalse
; // Need at least "-2"
1912 if (!mdnsIsDigit(name
->c
[l
])) return mDNSfalse
; // Last char must be a digit
1914 while (l
> 2 && mdnsIsDigit(name
->c
[l
])) l
--; // Strip off digits
1915 return (name
->c
[l
] == '-');
1919 // removes an auto-generated suffix (appended on a name collision) from a label. caller is
1920 // responsible for ensuring that the label does indeed contain a suffix. returns the number
1921 // from the suffix that was removed.
1922 mDNSlocal mDNSu32
RemoveLabelSuffix(domainlabel
*name
, mDNSBool RichText
)
1924 mDNSu32 val
= 0, multiplier
= 1;
1926 // Chop closing parentheses from RichText suffix
1927 if (RichText
&& name
->c
[0] >= 1 && name
->c
[name
->c
[0]] == ')') name
->c
[0]--;
1929 // Get any existing numerical suffix off the name
1930 while (mdnsIsDigit(name
->c
[name
->c
[0]]))
1931 { val
+= (name
->c
[name
->c
[0]] - '0') * multiplier
; multiplier
*= 10; name
->c
[0]--; }
1933 // Chop opening parentheses or dash from suffix
1936 if (name
->c
[0] >= 2 && name
->c
[name
->c
[0]] == '(' && name
->c
[name
->c
[0]-1] == ' ') name
->c
[0] -= 2;
1940 if (name
->c
[0] >= 1 && name
->c
[name
->c
[0]] == '-') name
->c
[0] -= 1;
1946 // appends a numerical suffix to a label, with the number following a whitespace and enclosed
1947 // in parentheses (rich text) or following two consecutive hyphens (RFC 1034 domain label).
1948 mDNSlocal
void AppendLabelSuffix(domainlabel
*name
, mDNSu32 val
, mDNSBool RichText
)
1950 mDNSu32 divisor
= 1, chars
= 2; // Shortest possible RFC1034 name suffix is 3 characters ("-2")
1951 if (RichText
) chars
= 4; // Shortest possible RichText suffix is 4 characters (" (2)")
1953 // Truncate trailing spaces from RichText names
1954 if (RichText
) while (name
->c
[name
->c
[0]] == ' ') name
->c
[0]--;
1956 while (val
>= divisor
* 10) { divisor
*= 10; chars
++; }
1958 if (name
->c
[0] > (mDNSu8
)(MAX_DOMAIN_LABEL
- chars
))
1960 name
->c
[0] = (mDNSu8
)(MAX_DOMAIN_LABEL
- chars
);
1961 // If the following character is a UTF-8 continuation character,
1962 // we just chopped a multi-byte UTF-8 character in the middle, so strip back to a safe truncation point
1963 while (name
->c
[0] > 0 && (name
->c
[name
->c
[0]+1] & 0xC0) == 0x80) name
->c
[0]--;
1966 if (RichText
) { name
->c
[++name
->c
[0]] = ' '; name
->c
[++name
->c
[0]] = '('; }
1967 else { name
->c
[++name
->c
[0]] = '-'; }
1971 name
->c
[++name
->c
[0]] = (mDNSu8
)('0' + val
/ divisor
);
1976 if (RichText
) name
->c
[++name
->c
[0]] = ')';
1979 mDNSexport
void IncrementLabelSuffix(domainlabel
*name
, mDNSBool RichText
)
1983 if (LabelContainsSuffix(name
, RichText
))
1984 val
= RemoveLabelSuffix(name
, RichText
);
1986 // If no existing suffix, start by renaming "Foo" as "Foo (2)" or "Foo-2" as appropriate.
1987 // If existing suffix in the range 2-9, increment it.
1988 // If we've had ten conflicts already, there are probably too many hosts trying to use the same name,
1989 // so add a random increment to improve the chances of finding an available name next time.
1990 if (val
== 0) val
= 2;
1991 else if (val
< 10) val
++;
1992 else val
+= 1 + mDNSRandom(99);
1994 AppendLabelSuffix(name
, val
, RichText
);
1997 // ***************************************************************************
1998 #if COMPILER_LIKES_PRAGMA_MARK
2000 #pragma mark - Resource Record Utility Functions
2003 #define RRIsAddressType(RR) ((RR)->resrec.rrtype == kDNSType_A || (RR)->resrec.rrtype == kDNSType_AAAA)
2005 #define ResourceRecordIsValidAnswer(RR) ( ((RR)-> resrec.RecordType & kDNSRecordTypeActiveMask) && \
2006 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2007 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2008 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
2010 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
2011 (ResourceRecordIsValidAnswer(RR) && \
2012 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
2014 #define RRUniqueOrKnownUnique(RR) ((RR)->RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeKnownUnique))
2016 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
2017 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
2019 // For records that have *never* been announced on the wire, their AnnounceCount will be set to InitialAnnounceCount (10).
2020 // When de-registering these records we do not need to send any goodbye packet because we never announced them in the first
2021 // place. If AnnounceCount is less than InitialAnnounceCount that means we have announced them at least once, so a goodbye
2022 // packet is needed. For this reason, if we ever reset AnnounceCount (e.g. after an interface change) we set it to
2023 // ReannounceCount (9), not InitialAnnounceCount. If we were to reset AnnounceCount back to InitialAnnounceCount that would
2024 // imply that the record had never been announced on the wire (which is false) and if the client were then to immediately
2025 // deregister that record before it had a chance to announce, we'd fail to send its goodbye packet (which would be a bug).
2026 #define InitialAnnounceCount ((mDNSu8)10)
2027 #define ReannounceCount ((mDNSu8)9)
2029 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
2030 // This means that because the announce interval is doubled after sending the first packet, the first
2031 // observed on-the-wire inter-packet interval between announcements is actually one second.
2032 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
2033 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
2034 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
2035 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
2037 #define DefaultAPIntervalForRecordType(X) ((X) & (kDNSRecordTypeAdvisory | kDNSRecordTypeShared ) ? DefaultAnnounceIntervalForTypeShared : \
2038 (X) & (kDNSRecordTypeUnique ) ? DefaultProbeIntervalForTypeUnique : \
2039 (X) & (kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique) ? DefaultAnnounceIntervalForTypeUnique : 0)
2041 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
2042 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
2043 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
2044 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
2046 #define MaxUnansweredQueries 4
2048 mDNSlocal mDNSBool
SameRData(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2050 if (r1
->rrtype
!= r2
->rrtype
) return(mDNSfalse
);
2051 if (r1
->rdlength
!= r2
->rdlength
) return(mDNSfalse
);
2052 if (r1
->rdatahash
!= r2
->rdatahash
) return(mDNSfalse
);
2053 if (r1
->rdnamehash
!= r2
->rdnamehash
) return(mDNSfalse
);
2056 case kDNSType_CNAME
:// Same as PTR
2057 case kDNSType_PTR
: return(SameDomainName(&r1
->rdata
->u
.name
, &r2
->rdata
->u
.name
));
2059 case kDNSType_SRV
: return(mDNSBool
)( r1
->rdata
->u
.srv
.priority
== r2
->rdata
->u
.srv
.priority
&&
2060 r1
->rdata
->u
.srv
.weight
== r2
->rdata
->u
.srv
.weight
&&
2061 r1
->rdata
->u
.srv
.port
.NotAnInteger
== r2
->rdata
->u
.srv
.port
.NotAnInteger
&&
2062 SameDomainName(&r1
->rdata
->u
.srv
.target
, &r2
->rdata
->u
.srv
.target
) );
2064 default: return(mDNSPlatformMemSame(r1
->rdata
->u
.data
, r2
->rdata
->u
.data
, r1
->rdlength
));
2068 mDNSlocal mDNSBool
ResourceRecordAnswersQuestion(const ResourceRecord
*const rr
, const DNSQuestion
*const q
)
2070 if (rr
->InterfaceID
&&
2072 rr
->InterfaceID
!= q
->InterfaceID
) return(mDNSfalse
);
2074 // RR type CNAME matches any query type. QTYPE ANY matches any RR type. QCLASS ANY matches any RR class.
2075 if (rr
->rrtype
!= kDNSType_CNAME
&& rr
->rrtype
!= q
->qtype
&& q
->qtype
!= kDNSQType_ANY
) return(mDNSfalse
);
2076 if ( rr
->rrclass
!= q
->qclass
&& q
->qclass
!= kDNSQClass_ANY
) return(mDNSfalse
);
2077 return(rr
->namehash
== q
->qnamehash
&& SameDomainName(&rr
->name
, &q
->qname
));
2080 mDNSlocal mDNSu32
DomainNameHashValue(const domainname
*const name
)
2085 for (c
= name
->c
; c
[0] != 0 && c
[1] != 0; c
+= 2)
2087 sum
+= ((mDNSIsUpperCase(c
[0]) ? c
[0] + 'a' - 'A' : c
[0]) << 8) |
2088 (mDNSIsUpperCase(c
[1]) ? c
[1] + 'a' - 'A' : c
[1]);
2089 sum
= (sum
<<3) | (sum
>>29);
2091 if (c
[0]) sum
+= ((mDNSIsUpperCase(c
[0]) ? c
[0] + 'a' - 'A' : c
[0]) << 8);
2095 #define HashSlot(X) (DomainNameHashValue(X) % CACHE_HASH_SLOTS)
2097 mDNSlocal mDNSu32
RDataHashValue(mDNSu16
const rdlength
, const RDataBody
*const rdb
)
2101 for (i
=0; i
+1 < rdlength
; i
+=2)
2103 sum
+= (((mDNSu32
)(rdb
->data
[i
])) << 8) | rdb
->data
[i
+1];
2104 sum
= (sum
<<3) | (sum
>>29);
2108 sum
+= ((mDNSu32
)(rdb
->data
[i
])) << 8;
2113 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
2114 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
2115 // TTL and rdata may differ.
2116 // This is used for cache flush management:
2117 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
2118 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
2119 mDNSlocal mDNSBool
SameResourceRecordSignature(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2121 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
2122 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
2123 if (r1
->InterfaceID
&&
2125 r1
->InterfaceID
!= r2
->InterfaceID
) return(mDNSfalse
);
2126 return(mDNSBool
)(r1
->rrtype
== r2
->rrtype
&& r1
->rrclass
== r2
->rrclass
&& r1
->namehash
== r2
->namehash
&& SameDomainName(&r1
->name
, &r2
->name
));
2129 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if the
2130 // authoratative record is in the probing state. Probes are sent with the wildcard type, so a response of
2131 // any type should match, even if it is not the type the client plans to use.
2132 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
2134 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
2135 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
2136 if (pktrr
->resrec
.InterfaceID
&&
2137 authrr
->resrec
.InterfaceID
&&
2138 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
2139 if (authrr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
2140 return(mDNSBool
)(pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&& pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&& SameDomainName(&pktrr
->resrec
.name
, &authrr
->resrec
.name
));
2143 // IdenticalResourceRecord returns true if two resources records have
2144 // the same name, type, class, and identical rdata (InterfaceID and TTL may differ)
2145 mDNSlocal mDNSBool
IdenticalResourceRecord(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2147 if (!r1
) { LogMsg("IdenticalResourceRecord ERROR: r1 is NULL"); return(mDNSfalse
); }
2148 if (!r2
) { LogMsg("IdenticalResourceRecord ERROR: r2 is NULL"); return(mDNSfalse
); }
2149 if (r1
->rrtype
!= r2
->rrtype
|| r1
->rrclass
!= r2
->rrclass
|| r1
->namehash
!= r2
->namehash
|| !SameDomainName(&r1
->name
, &r2
->name
)) return(mDNSfalse
);
2150 return(SameRData(r1
, r2
));
2153 // CacheRecord *ks is the CacheRecord from the known answer list in the query.
2154 // This is the information that the requester believes to be correct.
2155 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
2156 // This is the information that we believe to be correct.
2157 // We've already determined that we plan to give this answer on this interface
2158 // (either the record is non-specific, or it is specific to this interface)
2159 // so now we just need to check the name, type, class, rdata and TTL.
2160 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
2162 // If RR signature is different, or data is different, then don't suppress our answer
2163 if (!IdenticalResourceRecord(&ka
->resrec
,&rr
->resrec
)) return(mDNSfalse
);
2165 // If the requester's indicated TTL is less than half the real TTL,
2166 // we need to give our answer before the requester's copy expires.
2167 // If the requester's indicated TTL is at least half the real TTL,
2168 // then we can suppress our answer this time.
2169 // If the requester's indicated TTL is greater than the TTL we believe,
2170 // then that's okay, and we don't need to do anything about it.
2171 // (If two responders on the network are offering the same information,
2172 // that's okay, and if they are offering the information with different TTLs,
2173 // the one offering the lower TTL should defer to the one offering the higher TTL.)
2174 return(mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
2177 mDNSlocal mDNSu16
GetRDLength(const ResourceRecord
*const rr
, mDNSBool estimate
)
2179 RDataBody
*rd
= &rr
->rdata
->u
;
2180 const domainname
*const name
= estimate
? &rr
->name
: mDNSNULL
;
2183 case kDNSType_A
: return(sizeof(rd
->ip
)); break;
2184 case kDNSType_CNAME
:// Same as PTR
2185 case kDNSType_PTR
: return(CompressedDomainNameLength(&rd
->name
, name
));
2186 case kDNSType_HINFO
:return(mDNSu16
)(2 + (int)rd
->data
[0] + (int)rd
->data
[1 + (int)rd
->data
[0]]);
2187 case kDNSType_NULL
: // Same as TXT -- not self-describing, so have to just trust rdlength
2188 case kDNSType_TXT
: return(rr
->rdlength
); // TXT is not self-describing, so have to just trust rdlength
2189 case kDNSType_AAAA
: return(sizeof(rd
->ipv6
)); break;
2190 case kDNSType_SRV
: return(mDNSu16
)(6 + CompressedDomainNameLength(&rd
->srv
.target
, name
));
2191 default: debugf("Warning! Don't know how to get length of resource type %d", rr
->rrtype
);
2192 return(rr
->rdlength
);
2196 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
2198 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
2200 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
2201 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
2203 else if (rr
->AnnounceCount
&& ResourceRecordIsValidAnswer(rr
))
2205 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
2206 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
2210 #define GetRRDomainNameTarget(RR) ( \
2211 ((RR)->rrtype == kDNSType_CNAME || (RR)->rrtype == kDNSType_PTR) ? &(RR)->rdata->u.name : \
2212 ((RR)->rrtype == kDNSType_SRV ) ? &(RR)->rdata->u.srv.target : mDNSNULL )
2214 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
2216 // To allow us to aggregate probes when a group of services are registered together,
2217 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
2218 // 1/4 second wait; probe
2219 // 1/4 second wait; probe
2220 // 1/4 second wait; probe
2221 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
2223 // If we have no probe suppression time set, or it is in the past, set it now
2224 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
2226 m
->SuppressProbes
= (m
->timenow
+ DefaultProbeIntervalForTypeUnique
) | 1;
2227 // If we already have a probe scheduled to go out sooner, then use that time to get better aggregation
2228 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
2229 m
->SuppressProbes
= m
->NextScheduledProbe
;
2230 // If we already have a query scheduled to go out sooner, then use that time to get better aggregation
2231 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
2232 m
->SuppressProbes
= m
->NextScheduledQuery
;
2235 // We announce to flush stale data from other caches. It is a reasonable assumption that any
2236 // old stale copies will probably have the same TTL we're using, so announcing longer than
2237 // this serves no purpose -- any stale copies of that record will have expired by then anyway.
2238 rr
->AnnounceUntil
= m
->timenow
+ TicksTTL(rr
);
2239 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
2240 // Set LastMCTime to now, to inhibit multicast responses
2241 // (no need to send additional multicast responses when we're announcing anyway)
2242 rr
->LastMCTime
= m
->timenow
;
2243 rr
->LastMCInterface
= mDNSInterfaceMark
;
2245 // If this is a record type that's not going to probe, then delay its first announcement so that
2246 // it will go out synchronized with the first announcement for the other records that *are* probing.
2247 // This is a minor performance tweak that helps keep groups of related records synchronized together.
2248 // The addition of "rr->ThisAPInterval / 2" is to make sure that, in the event that any of the probes are
2249 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
2250 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
2251 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
2252 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
)
2253 rr
->LastAPTime
+= DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
2255 SetNextAnnounceProbeTime(m
, rr
);
2258 mDNSlocal
void SetNewRData(ResourceRecord
*const rr
, RData
*NewRData
, mDNSu16 rdlength
)
2263 rr
->rdata
= NewRData
;
2264 rr
->rdlength
= rdlength
;
2266 // Must not try to get target pointer until after updating rr->rdata
2267 target
= GetRRDomainNameTarget(rr
);
2268 rr
->rdlength
= GetRDLength(rr
, mDNSfalse
);
2269 rr
->rdestimate
= GetRDLength(rr
, mDNStrue
);
2270 rr
->rdatahash
= RDataHashValue(rr
->rdlength
, &rr
->rdata
->u
);
2271 rr
->rdnamehash
= target
? DomainNameHashValue(target
) : 0;
2274 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
2276 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
2278 if (!target
) debugf("SetTargetToHostName: Don't know how to set the target of rrtype %d", rr
->resrec
.rrtype
);
2280 if (target
&& SameDomainName(target
, &m
->hostname
))
2281 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
.c
, target
->c
);
2283 if (target
&& !SameDomainName(target
, &m
->hostname
))
2285 AssignDomainName(*target
, m
->hostname
);
2286 SetNewRData(&rr
->resrec
, mDNSNULL
, 0);
2288 // If we're in the middle of probing this record, we need to start again,
2289 // because changing its rdata may change the outcome of the tie-breaker.
2290 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
2291 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
2293 // If we've announced this record, we really should send a goodbye packet for the old rdata before
2294 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
2295 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
2296 if (rr
->AnnounceCount
< InitialAnnounceCount
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
2297 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2299 if (rr
->AnnounceCount
< ReannounceCount
)
2300 rr
->AnnounceCount
= ReannounceCount
;
2301 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
2302 InitializeLastAPTime(m
,rr
);
2306 mDNSlocal
void CompleteProbing(mDNS
*const m
, AuthRecord
*const rr
)
2308 verbosedebugf("Probing for %##s (%s) complete", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2309 if (!rr
->Acknowledged
&& rr
->RecordCallback
)
2311 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2312 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2313 rr
->Acknowledged
= mDNStrue
;
2314 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2315 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
2316 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2320 #define ValidateDomainName(N) (DomainNameLength(N) <= MAX_DOMAIN_NAME)
2322 mDNSlocal mDNSBool
ValidateRData(const mDNSu16 rrtype
, const mDNSu16 rdlength
, const RData
*const rd
)
2327 case kDNSType_A
: return(rdlength
== sizeof(mDNSv4Addr
));
2329 case kDNSType_NS
: // Same as PTR
2330 case kDNSType_MD
: // Same as PTR
2331 case kDNSType_MF
: // Same as PTR
2332 case kDNSType_CNAME
:// Same as PTR
2333 //case kDNSType_SOA not checked
2334 case kDNSType_MB
: // Same as PTR
2335 case kDNSType_MG
: // Same as PTR
2336 case kDNSType_MR
: // Same as PTR
2337 //case kDNSType_NULL not checked (no specified format, so always valid)
2338 //case kDNSType_WKS not checked
2339 case kDNSType_PTR
: len
= DomainNameLength(&rd
->u
.name
);
2340 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== len
);
2342 case kDNSType_HINFO
:// Same as TXT (roughly)
2343 case kDNSType_MINFO
:// Same as TXT (roughly)
2344 case kDNSType_TXT
: {
2345 const mDNSu8
*ptr
= rd
->u
.txt
.c
;
2346 const mDNSu8
*end
= rd
->u
.txt
.c
+ rdlength
;
2347 while (ptr
< end
) ptr
+= 1 + ptr
[0];
2348 return (ptr
== end
);
2351 case kDNSType_AAAA
: return(rdlength
== sizeof(mDNSv6Addr
));
2353 case kDNSType_MX
: len
= DomainNameLength(&rd
->u
.mx
.exchange
);
2354 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== 2+len
);
2356 case kDNSType_SRV
: len
= DomainNameLength(&rd
->u
.srv
.target
);
2357 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== 6+len
);
2359 default: return(mDNStrue
); // Allow all other types without checking
2363 // Two records qualify to be local duplicates if the RecordTypes are the same, or if one is Unique and the other Verified
2364 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified))
2365 #define RecordIsLocalDuplicate(A,B) ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
2367 mDNSlocal mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
2369 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
2371 AuthRecord
**p
= &m
->ResourceRecords
;
2372 AuthRecord
**d
= &m
->DuplicateRecords
;
2373 AuthRecord
**l
= &m
->LocalOnlyRecords
;
2375 #if TEST_LOCALONLY_FOR_EVERYTHING
2376 rr
->resrec
.InterfaceID
= (mDNSInterfaceID
)~0;
2379 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2380 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
2381 while (*l
&& *l
!= rr
) l
=&(*l
)->next
;
2384 LogMsg("Error! Tried to register a AuthRecord %p %##s (%s) that's already in the list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2385 return(mStatus_AlreadyRegistered
);
2388 if (rr
->DependentOn
)
2390 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
2391 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
2394 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
2395 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2396 return(mStatus_Invalid
);
2398 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
)))
2400 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
2401 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
2402 return(mStatus_Invalid
);
2406 // If this resource record is referencing a specific interface, make sure it exists
2407 if (rr
->resrec
.InterfaceID
&& rr
->resrec
.InterfaceID
!= ((mDNSInterfaceID
)~0))
2409 NetworkInterfaceInfo
*intf
;
2410 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
2411 if (intf
->InterfaceID
== rr
->resrec
.InterfaceID
) break;
2414 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr
->resrec
.InterfaceID
);
2415 return(mStatus_BadReferenceErr
);
2419 rr
->next
= mDNSNULL
;
2421 // Field Group 1: Persistent metadata for Authoritative Records
2422 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2423 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2424 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2425 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2426 // rr->Callback = already set in mDNS_SetupResourceRecord
2427 // rr->Context = already set in mDNS_SetupResourceRecord
2428 // rr->RecordType = already set in mDNS_SetupResourceRecord
2429 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
2431 // Field Group 2: Transient state for Authoritative Records
2432 rr
->Acknowledged
= mDNSfalse
;
2433 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
2434 rr
->AnnounceCount
= InitialAnnounceCount
;
2435 rr
->IncludeInProbe
= mDNSfalse
;
2436 rr
->ImmedAnswer
= mDNSNULL
;
2437 rr
->ImmedAdditional
= mDNSNULL
;
2438 rr
->SendRNow
= mDNSNULL
;
2439 rr
->v4Requester
= zeroIPAddr
;
2440 rr
->v6Requester
= zerov6Addr
;
2441 rr
->NextResponse
= mDNSNULL
;
2442 rr
->NR_AnswerTo
= mDNSNULL
;
2443 rr
->NR_AdditionalTo
= mDNSNULL
;
2444 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
2445 InitializeLastAPTime(m
, rr
);
2446 // rr->AnnounceUntil = Set for us in InitializeLastAPTime()
2447 // rr->LastAPTime = Set for us in InitializeLastAPTime()
2448 // rr->LastMCTime = Set for us in InitializeLastAPTime()
2449 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
2450 rr
->NewRData
= mDNSNULL
;
2451 rr
->newrdlength
= 0;
2452 rr
->UpdateCallback
= mDNSNULL
;
2453 rr
->UpdateCredits
= kMaxUpdateCredits
;
2454 rr
->NextUpdateCredit
= 0;
2455 rr
->UpdateBlocked
= 0;
2457 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
2458 // rr->resrec.name.c = MUST be set by client
2459 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
2460 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
2461 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
2462 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
2466 if (target
) target
->c
[0] = 0;
2467 SetTargetToHostName(m
, rr
); // This also sets rdlength and rdestimate for us
2471 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
2472 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
2475 if (!ValidateDomainName(&rr
->resrec
.name
))
2476 { LogMsg("Attempt to register record with invalid name: %s", GetRRDisplayString(m
, rr
)); return(mStatus_Invalid
); }
2478 // Don't do this until *after* we've set rr->resrec.rdlength
2479 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
2480 { LogMsg("Attempt to register record with invalid rdata: %s", GetRRDisplayString(m
, rr
)); return(mStatus_Invalid
); }
2482 rr
->resrec
.namehash
= DomainNameHashValue(&rr
->resrec
.name
);
2483 rr
->resrec
.rdatahash
= RDataHashValue(rr
->resrec
.rdlength
, &rr
->resrec
.rdata
->u
);
2484 rr
->resrec
.rdnamehash
= target
? DomainNameHashValue(target
) : 0;
2486 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0))
2488 debugf("Adding %p %##s (%s) to LocalOnly list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2490 if (!m
->NewLocalOnlyRecords
) m
->NewLocalOnlyRecords
= rr
;
2491 // If this is supposed to be unique, make sure we don't have any name conflicts
2492 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2494 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
2495 for (r
= m
->LocalOnlyRecords
; r
; r
=r
->next
)
2497 const AuthRecord
*s2
= r
->RRSet
? r
->RRSet
: r
;
2498 if (s1
!= s2
&& SameResourceRecordSignature(&r
->resrec
, &rr
->resrec
) && !SameRData(&r
->resrec
, &rr
->resrec
))
2501 if (r
) // If we found a conflict, set DiscardLocalOnlyRecords so we'll deliver the callback
2503 debugf("Name conflict %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2504 m
->DiscardLocalOnlyRecords
= mDNStrue
;
2506 else // else no conflict, so set ProbeCount to zero and update RecordType as appropriate
2509 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
2515 // Now that's we've finished building our new record, make sure it's not identical to one we already have
2516 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (RecordIsLocalDuplicate(r
, rr
)) break;
2520 debugf("Adding %p %##s (%s) to duplicate list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2522 // If the previous copy of this record is already verified unique,
2523 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
2524 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
2525 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
2526 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
2531 debugf("Adding %p %##s (%s) to active record list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2535 return(mStatus_NoError
);
2538 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
2540 m
->ProbeFailTime
= m
->timenow
;
2541 m
->NumFailedProbes
++;
2542 // If we've had ten or more probe failures, rate-limit to one every five seconds
2543 // The result is ORed with 1 to make sure SuppressProbes is not accidentally set to zero
2544 if (m
->NumFailedProbes
>= 10) m
->SuppressProbes
= (m
->timenow
+ mDNSPlatformOneSecond
* 5) | 1;
2545 if (m
->NumFailedProbes
>= 16)
2546 LogMsg("Name in use: %##s (%s); need to choose another (%d)",
2547 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), m
->NumFailedProbes
);
2550 // mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
2551 // mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
2552 // mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
2553 typedef enum { mDNS_Dereg_normal
, mDNS_Dereg_conflict
, mDNS_Dereg_repeat
} mDNS_Dereg_type
;
2555 // NOTE: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
2556 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2557 mDNSlocal mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
2559 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
2560 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
2561 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0)) p
= &m
->LocalOnlyRecords
;
2562 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2566 // We found our record on the main list. See if there are any duplicates that need special handling.
2567 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
2569 AuthRecord
*r2
= m
->DuplicateRecords
;
2572 if (RecordIsLocalDuplicate(r2
, rr
)) { mDNS_Deregister_internal(m
, r2
, drt
); r2
= m
->DuplicateRecords
; }
2578 // Before we delete the record (and potentially send a goodbye packet)
2579 // first see if we have a record on the duplicate list ready to take over from it.
2580 AuthRecord
**d
= &m
->DuplicateRecords
;
2581 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
2584 AuthRecord
*dup
= *d
;
2585 debugf("Duplicate record %p taking over from %p %##s (%s)", dup
, rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2586 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
2587 dup
->next
= rr
->next
; // And then...
2588 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
2589 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
2590 dup
->ProbeCount
= rr
->ProbeCount
;
2591 dup
->AnnounceCount
= rr
->AnnounceCount
;
2592 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
2593 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
2594 dup
->v4Requester
= rr
->v4Requester
;
2595 dup
->v6Requester
= rr
->v6Requester
;
2596 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
2597 dup
->AnnounceUntil
= rr
->AnnounceUntil
;
2598 dup
->LastAPTime
= rr
->LastAPTime
;
2599 dup
->LastMCTime
= rr
->LastMCTime
;
2600 dup
->LastMCInterface
= rr
->LastMCInterface
;
2601 if (RecordType
== kDNSRecordTypeShared
) rr
->AnnounceCount
= InitialAnnounceCount
;
2607 // We didn't find our record on the main list; try the DuplicateRecords list instead.
2608 p
= &m
->DuplicateRecords
;
2609 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2610 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2611 if (*p
&& RecordType
== kDNSRecordTypeShared
) rr
->AnnounceCount
= InitialAnnounceCount
;
2612 if (*p
) debugf("DNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2617 // No need to log an error message if we already know this is a potentially repeated deregistration
2618 if (drt
!= mDNS_Dereg_repeat
)
2619 debugf("mDNS_Deregister_internal: Record %p %##s (%s) not found in list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2620 return(mStatus_BadReferenceErr
);
2623 // If this is a shared record and we've announced it at least once,
2624 // we need to retract that announcement before we delete the record
2625 if (RecordType
== kDNSRecordTypeShared
&& rr
->AnnounceCount
< InitialAnnounceCount
)
2627 verbosedebugf("mDNS_Deregister_internal: Sending deregister for %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2628 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2629 rr
->resrec
.rroriginalttl
= 0;
2630 rr
->ImmedAnswer
= mDNSInterfaceMark
;
2631 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0))
2632 m
->DiscardLocalOnlyRecords
= mDNStrue
;
2635 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
2636 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
2641 *p
= rr
->next
; // Cut this record from the list
2642 // If someone is about to look at this, bump the pointer forward
2643 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
2644 if (m
->NewLocalOnlyRecords
== rr
) m
->NewLocalOnlyRecords
= rr
->next
;
2645 rr
->next
= mDNSNULL
;
2647 if (RecordType
== kDNSRecordTypeUnregistered
)
2648 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeUnregistered",
2649 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2650 else if (RecordType
== kDNSRecordTypeDeregistering
)
2651 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeDeregistering",
2652 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2655 verbosedebugf("mDNS_Deregister_internal: Deleting record for %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2656 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
2659 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
2660 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2661 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2663 // If we have an update queued up which never executed, give the client a chance to free that memory
2666 RData
*OldRData
= rr
->resrec
.rdata
;
2667 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
2668 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
2669 if (rr
->UpdateCallback
)
2670 rr
->UpdateCallback(m
, rr
, OldRData
); // ... and let the client know
2673 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2674 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2675 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2676 // so any attempt to touch rr after this is likely to lead to a crash.
2677 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2678 if (RecordType
== kDNSRecordTypeShared
)
2680 if (rr
->RecordCallback
)
2681 rr
->RecordCallback(m
, rr
, mStatus_MemFree
);
2683 else if (drt
== mDNS_Dereg_conflict
)
2685 RecordProbeFailure(m
, rr
);
2686 if (rr
->RecordCallback
)
2687 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
);
2689 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2691 return(mStatus_NoError
);
2694 // ***************************************************************************
2695 #if COMPILER_LIKES_PRAGMA_MARK
2698 #pragma mark - DNS Message Creation Functions
2701 mDNSlocal
void InitializeDNSMessage(DNSMessageHeader
*h
, mDNSOpaque16 id
, mDNSOpaque16 flags
)
2705 h
->numQuestions
= 0;
2707 h
->numAuthorities
= 0;
2708 h
->numAdditionals
= 0;
2711 mDNSlocal
const mDNSu8
*FindCompressionPointer(const mDNSu8
*const base
, const mDNSu8
*const end
, const mDNSu8
*const domname
)
2713 const mDNSu8
*result
= end
- *domname
- 1;
2715 if (*domname
== 0) return(mDNSNULL
); // There's no point trying to match just the root label
2717 // This loop examines each possible starting position in packet, starting end of the packet and working backwards
2718 while (result
>= base
)
2720 // If the length byte and first character of the label match, then check further to see
2721 // if this location in the packet will yield a useful name compression pointer.
2722 if (result
[0] == domname
[0] && result
[1] == domname
[1])
2724 const mDNSu8
*name
= domname
;
2725 const mDNSu8
*targ
= result
;
2726 while (targ
+ *name
< end
)
2728 // First see if this label matches
2730 const mDNSu8
*pointertarget
;
2731 for (i
=0; i
<= *name
; i
++) if (targ
[i
] != name
[i
]) break;
2732 if (i
<= *name
) break; // If label did not match, bail out
2733 targ
+= 1 + *name
; // Else, did match, so advance target pointer
2734 name
+= 1 + *name
; // and proceed to check next label
2735 if (*name
== 0 && *targ
== 0) return(result
); // If no more labels, we found a match!
2736 if (*name
== 0) break; // If no more labels to match, we failed, so bail out
2738 // The label matched, so now follow the pointer (if appropriate) and then see if the next label matches
2739 if (targ
[0] < 0x40) continue; // If length value, continue to check next label
2740 if (targ
[0] < 0xC0) break; // If 40-BF, not valid
2741 if (targ
+1 >= end
) break; // Second byte not present!
2742 pointertarget
= base
+ (((mDNSu16
)(targ
[0] & 0x3F)) << 8) + targ
[1];
2743 if (targ
< pointertarget
) break; // Pointertarget must point *backwards* in the packet
2744 if (pointertarget
[0] >= 0x40) break; // Pointertarget must point to a valid length byte
2745 targ
= pointertarget
;
2748 result
--; // We failed to match at this search position, so back up the tentative result pointer and try again
2753 // Put a string of dot-separated labels as length-prefixed labels
2754 // domainname is a fully-qualified name (i.e. assumed to be ending in a dot, even if it doesn't)
2755 // msg points to the message we're building (pass mDNSNULL if we don't want to use compression pointers)
2756 // end points to the end of the message so far
2757 // ptr points to where we want to put the name
2758 // limit points to one byte past the end of the buffer that we must not overrun
2759 // domainname is the name to put
2760 mDNSlocal mDNSu8
*putDomainNameAsLabels(const DNSMessage
*const msg
,
2761 mDNSu8
*ptr
, const mDNSu8
*const limit
, const domainname
*const name
)
2763 const mDNSu8
*const base
= (const mDNSu8
*const)msg
;
2764 const mDNSu8
* np
= name
->c
;
2765 const mDNSu8
*const max
= name
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
2766 const mDNSu8
* pointer
= mDNSNULL
;
2767 const mDNSu8
*const searchlimit
= ptr
;
2769 while (*np
&& ptr
< limit
-1) // While we've got characters in the name, and space to write them in the message...
2771 if (*np
> MAX_DOMAIN_LABEL
)
2772 { LogMsg("Malformed domain name %##s (label more than 63 bytes)", name
->c
); return(mDNSNULL
); }
2774 // This check correctly allows for the final trailing root label:
2776 // Suppose our domain name is exactly 255 bytes long, including the final trailing root label.
2777 // Suppose np is now at name->c[248], and we're about to write our last non-null label ("local").
2778 // We know that max will be at name->c[255]
2779 // That means that np + 1 + 5 == max - 1, so we (just) pass the "if" test below, write our
2780 // six bytes, then exit the loop, write the final terminating root label, and the domain
2781 // name we've written is exactly 255 bytes long, exactly at the correct legal limit.
2782 // If the name is one byte longer, then we fail the "if" test below, and correctly bail out.
2783 if (np
+ 1 + *np
>= max
)
2784 { LogMsg("Malformed domain name %##s (more than 255 bytes)", name
->c
); return(mDNSNULL
); }
2786 if (base
) pointer
= FindCompressionPointer(base
, searchlimit
, np
);
2787 if (pointer
) // Use a compression pointer if we can
2789 mDNSu16 offset
= (mDNSu16
)(pointer
- base
);
2790 *ptr
++ = (mDNSu8
)(0xC0 | (offset
>> 8));
2791 *ptr
++ = (mDNSu8
)( offset
);
2794 else // Else copy one label and try again
2798 if (ptr
+ 1 + len
>= limit
) return(mDNSNULL
);
2800 for (i
=0; i
<len
; i
++) *ptr
++ = *np
++;
2804 if (ptr
< limit
) // If we didn't run out of space
2806 *ptr
++ = 0; // Put the final root label
2807 return(ptr
); // and return
2813 mDNSlocal mDNSu8
*putRData(const DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
, ResourceRecord
*rr
)
2817 case kDNSType_A
: if (rr
->rdlength
!= 4)
2819 debugf("putRData: Illegal length %d for kDNSType_A", rr
->rdlength
);
2822 if (ptr
+ 4 > limit
) return(mDNSNULL
);
2823 *ptr
++ = rr
->rdata
->u
.ip
.b
[0];
2824 *ptr
++ = rr
->rdata
->u
.ip
.b
[1];
2825 *ptr
++ = rr
->rdata
->u
.ip
.b
[2];
2826 *ptr
++ = rr
->rdata
->u
.ip
.b
[3];
2829 case kDNSType_CNAME
:// Same as PTR
2830 case kDNSType_PTR
: return(putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->rdata
->u
.name
));
2832 case kDNSType_HINFO
:// Same as TXT
2833 case kDNSType_TXT
: if (ptr
+ rr
->rdlength
> limit
) return(mDNSNULL
);
2834 mDNSPlatformMemCopy(rr
->rdata
->u
.data
, ptr
, rr
->rdlength
);
2835 return(ptr
+ rr
->rdlength
);
2837 case kDNSType_AAAA
: if (rr
->rdlength
!= sizeof(rr
->rdata
->u
.ipv6
))
2839 debugf("putRData: Illegal length %d for kDNSType_AAAA", rr
->rdlength
);
2842 if (ptr
+ sizeof(rr
->rdata
->u
.ipv6
) > limit
) return(mDNSNULL
);
2843 mDNSPlatformMemCopy(&rr
->rdata
->u
.ipv6
, ptr
, sizeof(rr
->rdata
->u
.ipv6
));
2844 return(ptr
+ sizeof(rr
->rdata
->u
.ipv6
));
2846 case kDNSType_SRV
: if (ptr
+ 6 > limit
) return(mDNSNULL
);
2847 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.priority
>> 8);
2848 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.priority
);
2849 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.weight
>> 8);
2850 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.weight
);
2851 *ptr
++ = rr
->rdata
->u
.srv
.port
.b
[0];
2852 *ptr
++ = rr
->rdata
->u
.srv
.port
.b
[1];
2853 return(putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->rdata
->u
.srv
.target
));
2855 default: if (ptr
+ rr
->rdlength
> limit
) return(mDNSNULL
);
2856 debugf("putRData: Warning! Writing resource type %d as raw data", rr
->rrtype
);
2857 mDNSPlatformMemCopy(rr
->rdata
->u
.data
, ptr
, rr
->rdlength
);
2858 return(ptr
+ rr
->rdlength
);
2862 mDNSlocal mDNSu8
*PutResourceRecordTTL(DNSMessage
*const msg
, mDNSu8
*ptr
, mDNSu16
*count
, ResourceRecord
*rr
, mDNSu32 ttl
)
2865 mDNSu16 actualLength
;
2866 const mDNSu8
*limit
= msg
->data
+ AbsoluteMaxDNSMessageData
;
2868 // If we have a single large record to put in the packet, then we allow the packet to be up to 9K bytes,
2869 // but in the normal case we try to keep the packets below 1500 to avoid IP fragmentation on standard Ethernet
2870 if (msg
->h
.numAnswers
|| msg
->h
.numAuthorities
|| msg
->h
.numAdditionals
)
2871 limit
= msg
->data
+ NormalMaxDNSMessageData
;
2873 if (rr
->RecordType
== kDNSRecordTypeUnregistered
)
2875 LogMsg("PutResourceRecord ERROR! Attempt to put kDNSRecordTypeUnregistered %##s (%s)", rr
->name
.c
, DNSTypeName(rr
->rrtype
));
2879 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->name
);
2880 if (!ptr
|| ptr
+ 10 >= limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2881 ptr
[0] = (mDNSu8
)(rr
->rrtype
>> 8);
2882 ptr
[1] = (mDNSu8
)(rr
->rrtype
);
2883 ptr
[2] = (mDNSu8
)(rr
->rrclass
>> 8);
2884 ptr
[3] = (mDNSu8
)(rr
->rrclass
);
2885 ptr
[4] = (mDNSu8
)(ttl
>> 24);
2886 ptr
[5] = (mDNSu8
)(ttl
>> 16);
2887 ptr
[6] = (mDNSu8
)(ttl
>> 8);
2888 ptr
[7] = (mDNSu8
)(ttl
);
2889 endofrdata
= putRData(msg
, ptr
+10, limit
, rr
);
2890 if (!endofrdata
) { verbosedebugf("Ran out of space in PutResourceRecord for %##s (%s)", rr
->name
.c
, DNSTypeName(rr
->rrtype
)); return(mDNSNULL
); }
2892 // Go back and fill in the actual number of data bytes we wrote
2893 // (actualLength can be less than rdlength when domain name compression is used)
2894 actualLength
= (mDNSu16
)(endofrdata
- ptr
- 10);
2895 ptr
[8] = (mDNSu8
)(actualLength
>> 8);
2896 ptr
[9] = (mDNSu8
)(actualLength
);
2902 #define PutResourceRecord(MSG, P, C, RR) PutResourceRecordTTL((MSG), (P), (C), (RR), (RR)->rroriginalttl)
2904 mDNSlocal mDNSu8
*PutResourceRecordCappedTTL(DNSMessage
*const msg
, mDNSu8
*ptr
, mDNSu16
*count
, ResourceRecord
*rr
, mDNSu32 maxttl
)
2906 if (maxttl
> rr
->rroriginalttl
) maxttl
= rr
->rroriginalttl
;
2907 return(PutResourceRecordTTL(msg
, ptr
, count
, rr
, maxttl
));
2911 mDNSlocal mDNSu8
*putEmptyResourceRecord(DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
,
2912 mDNSu16
*count
, const AuthRecord
*rr
)
2914 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->name
);
2915 if (!ptr
|| ptr
+ 10 > limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2916 ptr
[0] = (mDNSu8
)(rr
->resrec
.rrtype
>> 8); // Put type
2917 ptr
[1] = (mDNSu8
)(rr
->resrec
.rrtype
);
2918 ptr
[2] = (mDNSu8
)(rr
->resrec
.rrclass
>> 8); // Put class
2919 ptr
[3] = (mDNSu8
)(rr
->resrec
.rrclass
);
2920 ptr
[4] = ptr
[5] = ptr
[6] = ptr
[7] = 0; // TTL is zero
2921 ptr
[8] = ptr
[9] = 0; // RDATA length is zero
2927 mDNSlocal mDNSu8
*putQuestion(DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
,
2928 const domainname
*const name
, mDNSu16 rrtype
, mDNSu16 rrclass
)
2930 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, name
);
2931 if (!ptr
|| ptr
+4 >= limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2932 ptr
[0] = (mDNSu8
)(rrtype
>> 8);
2933 ptr
[1] = (mDNSu8
)(rrtype
);
2934 ptr
[2] = (mDNSu8
)(rrclass
>> 8);
2935 ptr
[3] = (mDNSu8
)(rrclass
);
2936 msg
->h
.numQuestions
++;
2940 // ***************************************************************************
2941 #if COMPILER_LIKES_PRAGMA_MARK
2943 #pragma mark - DNS Message Parsing Functions
2946 mDNSlocal
const mDNSu8
*skipDomainName(const DNSMessage
*const msg
, const mDNSu8
*ptr
, const mDNSu8
*const end
)
2950 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
2951 { debugf("skipDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL
); }
2953 while (1) // Read sequence of labels
2955 const mDNSu8 len
= *ptr
++; // Read length of this label
2956 if (len
== 0) return(ptr
); // If length is zero, that means this name is complete
2959 case 0x00: if (ptr
+ len
>= end
) // Remember: expect at least one more byte for the root label
2960 { debugf("skipDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL
); }
2961 if (total
+ 1 + len
>= MAX_DOMAIN_NAME
) // Remember: expect at least one more byte for the root label
2962 { debugf("skipDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL
); }
2967 case 0x40: debugf("skipDomainName: Extended EDNS0 label types 0x%X not supported", len
); return(mDNSNULL
);
2968 case 0x80: debugf("skipDomainName: Illegal label length 0x%X", len
); return(mDNSNULL
);
2969 case 0xC0: return(ptr
+1);
2974 // Routine to fetch an FQDN from the DNS message, following compression pointers if necessary.
2975 mDNSlocal
const mDNSu8
*getDomainName(const DNSMessage
*const msg
, const mDNSu8
*ptr
, const mDNSu8
*const end
,
2976 domainname
*const name
)
2978 const mDNSu8
*nextbyte
= mDNSNULL
; // Record where we got to before we started following pointers
2979 mDNSu8
*np
= name
->c
; // Name pointer
2980 const mDNSu8
*const limit
= np
+ MAX_DOMAIN_NAME
; // Limit so we don't overrun buffer
2982 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
2983 { debugf("getDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL
); }
2985 *np
= 0; // Tentatively place the root label here (may be overwritten if we have more labels)
2987 while (1) // Read sequence of labels
2989 const mDNSu8 len
= *ptr
++; // Read length of this label
2990 if (len
== 0) break; // If length is zero, that means this name is complete
2996 case 0x00: if (ptr
+ len
>= end
) // Remember: expect at least one more byte for the root label
2997 { debugf("getDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL
); }
2998 if (np
+ 1 + len
>= limit
) // Remember: expect at least one more byte for the root label
2999 { debugf("getDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL
); }
3001 for (i
=0; i
<len
; i
++) *np
++ = *ptr
++;
3002 *np
= 0; // Tentatively place the root label here (may be overwritten if we have more labels)
3005 case 0x40: debugf("getDomainName: Extended EDNS0 label types 0x%X not supported in name %##s", len
, name
->c
);
3008 case 0x80: debugf("getDomainName: Illegal label length 0x%X in domain name %##s", len
, name
->c
); return(mDNSNULL
);
3010 case 0xC0: offset
= (mDNSu16
)((((mDNSu16
)(len
& 0x3F)) << 8) | *ptr
++);
3011 if (!nextbyte
) nextbyte
= ptr
; // Record where we got to before we started following pointers
3012 ptr
= (mDNSu8
*)msg
+ offset
;
3013 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
3014 { debugf("getDomainName: Illegal compression pointer not within packet boundaries"); return(mDNSNULL
); }
3016 { debugf("getDomainName: Compression pointer must point to real label"); return(mDNSNULL
); }
3021 if (nextbyte
) return(nextbyte
);
3025 mDNSlocal
const mDNSu8
*skipResourceRecord(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
)
3027 mDNSu16 pktrdlength
;
3029 ptr
= skipDomainName(msg
, ptr
, end
);
3030 if (!ptr
) { debugf("skipResourceRecord: Malformed RR name"); return(mDNSNULL
); }
3032 if (ptr
+ 10 > end
) { debugf("skipResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL
); }
3033 pktrdlength
= (mDNSu16
)((mDNSu16
)ptr
[8] << 8 | ptr
[9]);
3035 if (ptr
+ pktrdlength
> end
) { debugf("skipResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL
); }
3037 return(ptr
+ pktrdlength
);
3040 #define GetLargeResourceRecord(m, msg, p, e, i, t, L) \
3041 (((L)->r.rdatastorage.MaxRDLength = MaximumRDSize), GetResourceRecord((m), (msg), (p), (e), (i), (t), &(L)->r, (RData*)&(L)->r.rdatastorage))
3043 mDNSlocal
const mDNSu8
*GetResourceRecord(mDNS
*const m
, const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
,
3044 const mDNSInterfaceID InterfaceID
, mDNSu8 RecordType
, CacheRecord
*rr
, RData
*RDataStorage
)
3046 mDNSu16 pktrdlength
;
3048 rr
->next
= mDNSNULL
;
3049 rr
->resrec
.RecordType
= RecordType
;
3051 rr
->NextInKAList
= mDNSNULL
;
3052 rr
->TimeRcvd
= m
->timenow
;
3053 rr
->NextRequiredQuery
= m
->timenow
; // Will be updated to the real value when we call SetNextCacheCheckTime()
3054 rr
->LastUsed
= m
->timenow
;
3056 rr
->CRActiveQuestion
= mDNSNULL
;
3057 rr
->UnansweredQueries
= 0;
3058 rr
->LastUnansweredTime
= 0;
3059 rr
->MPUnansweredQ
= 0;
3060 rr
->MPLastUnansweredQT
= 0;
3061 rr
->MPUnansweredKA
= 0;
3062 rr
->MPExpectingKA
= mDNSfalse
;
3063 rr
->NextInCFList
= mDNSNULL
;
3065 rr
->resrec
.InterfaceID
= InterfaceID
;
3066 ptr
= getDomainName(msg
, ptr
, end
, &rr
->resrec
.name
);
3067 if (!ptr
) { debugf("GetResourceRecord: Malformed RR name"); return(mDNSNULL
); }
3069 if (ptr
+ 10 > end
) { debugf("GetResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL
); }
3071 rr
->resrec
.rrtype
= (mDNSu16
) ((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
3072 rr
->resrec
.rrclass
= (mDNSu16
)(((mDNSu16
)ptr
[2] << 8 | ptr
[3]) & kDNSClass_Mask
);
3073 rr
->resrec
.rroriginalttl
= (mDNSu32
) ((mDNSu32
)ptr
[4] << 24 | (mDNSu32
)ptr
[5] << 16 | (mDNSu32
)ptr
[6] << 8 | ptr
[7]);
3074 if (rr
->resrec
.rroriginalttl
> 0x70000000UL
/ mDNSPlatformOneSecond
)
3075 rr
->resrec
.rroriginalttl
= 0x70000000UL
/ mDNSPlatformOneSecond
;
3076 // Note: We don't have to adjust m->NextCacheCheck here -- this is just getting a record into memory for
3077 // us to look at. If we decide to copy it into the cache, then we'll update m->NextCacheCheck accordingly.
3078 pktrdlength
= (mDNSu16
)((mDNSu16
)ptr
[8] << 8 | ptr
[9]);
3079 if (ptr
[2] & (kDNSClass_UniqueRRSet
>> 8))
3080 rr
->resrec
.RecordType
|= kDNSRecordTypePacketUniqueMask
;
3082 if (ptr
+ pktrdlength
> end
) { debugf("GetResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL
); }
3085 rr
->resrec
.rdata
= RDataStorage
;
3088 rr
->resrec
.rdata
= (RData
*)&rr
->rdatastorage
;
3089 rr
->resrec
.rdata
->MaxRDLength
= sizeof(RDataBody
);
3092 switch (rr
->resrec
.rrtype
)
3094 case kDNSType_A
: rr
->resrec
.rdata
->u
.ip
.b
[0] = ptr
[0];
3095 rr
->resrec
.rdata
->u
.ip
.b
[1] = ptr
[1];
3096 rr
->resrec
.rdata
->u
.ip
.b
[2] = ptr
[2];
3097 rr
->resrec
.rdata
->u
.ip
.b
[3] = ptr
[3];
3100 case kDNSType_CNAME
:// Same as PTR
3101 case kDNSType_PTR
: if (!getDomainName(msg
, ptr
, end
, &rr
->resrec
.rdata
->u
.name
))
3102 { debugf("GetResourceRecord: Malformed CNAME/PTR RDATA name"); return(mDNSNULL
); }
3103 //debugf("%##s PTR %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.name.c, pktrdlength);
3106 case kDNSType_NULL
: //Same as TXT
3107 case kDNSType_HINFO
://Same as TXT
3108 case kDNSType_TXT
: if (pktrdlength
> rr
->resrec
.rdata
->MaxRDLength
)
3110 debugf("GetResourceRecord: %s rdata size (%d) exceeds storage (%d)",
3111 DNSTypeName(rr
->resrec
.rrtype
), pktrdlength
, rr
->resrec
.rdata
->MaxRDLength
);
3114 rr
->resrec
.rdlength
= pktrdlength
;
3115 mDNSPlatformMemCopy(ptr
, rr
->resrec
.rdata
->u
.data
, pktrdlength
);
3118 case kDNSType_AAAA
: mDNSPlatformMemCopy(ptr
, &rr
->resrec
.rdata
->u
.ipv6
, sizeof(rr
->resrec
.rdata
->u
.ipv6
));
3121 case kDNSType_SRV
: rr
->resrec
.rdata
->u
.srv
.priority
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
3122 rr
->resrec
.rdata
->u
.srv
.weight
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
3123 rr
->resrec
.rdata
->u
.srv
.port
.b
[0] = ptr
[4];
3124 rr
->resrec
.rdata
->u
.srv
.port
.b
[1] = ptr
[5];
3125 if (!getDomainName(msg
, ptr
+6, end
, &rr
->resrec
.rdata
->u
.srv
.target
))
3126 { debugf("GetResourceRecord: Malformed SRV RDATA name"); return(mDNSNULL
); }
3127 //debugf("%##s SRV %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.srv.target.c, pktrdlength);
3130 default: if (pktrdlength
> rr
->resrec
.rdata
->MaxRDLength
)
3132 debugf("GetResourceRecord: rdata %d (%s) size (%d) exceeds storage (%d)",
3133 rr
->resrec
.rrtype
, DNSTypeName(rr
->resrec
.rrtype
), pktrdlength
, rr
->resrec
.rdata
->MaxRDLength
);
3136 debugf("GetResourceRecord: Warning! Reading resource type %d (%s) as opaque data",
3137 rr
->resrec
.rrtype
, DNSTypeName(rr
->resrec
.rrtype
));
3138 // Note: Just because we don't understand the record type, that doesn't
3139 // mean we fail. The DNS protocol specifies rdlength, so we can
3140 // safely skip over unknown records and ignore them.
3141 // We also grab a binary copy of the rdata anyway, since the caller
3142 // might know how to interpret it even if we don't.
3143 rr
->resrec
.rdlength
= pktrdlength
;
3144 mDNSPlatformMemCopy(ptr
, rr
->resrec
.rdata
->u
.data
, pktrdlength
);
3148 rr
->resrec
.namehash
= DomainNameHashValue(&rr
->resrec
.name
);
3149 SetNewRData(&rr
->resrec
, mDNSNULL
, 0);
3151 return(ptr
+ pktrdlength
);
3154 mDNSlocal
const mDNSu8
*skipQuestion(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
)
3156 ptr
= skipDomainName(msg
, ptr
, end
);
3157 if (!ptr
) { debugf("skipQuestion: Malformed domain name in DNS question section"); return(mDNSNULL
); }
3158 if (ptr
+4 > end
) { debugf("skipQuestion: Malformed DNS question section -- no query type and class!"); return(mDNSNULL
); }
3162 mDNSlocal
const mDNSu8
*getQuestion(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
, const mDNSInterfaceID InterfaceID
,
3163 DNSQuestion
*question
)
3165 question
->InterfaceID
= InterfaceID
;
3166 ptr
= getDomainName(msg
, ptr
, end
, &question
->qname
);
3167 if (!ptr
) { debugf("Malformed domain name in DNS question section"); return(mDNSNULL
); }
3168 if (ptr
+4 > end
) { debugf("Malformed DNS question section -- no query type and class!"); return(mDNSNULL
); }
3170 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
3171 question
->qtype
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]); // Get type
3172 question
->qclass
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]); // and class
3176 mDNSlocal
const mDNSu8
*LocateAnswers(const DNSMessage
*const msg
, const mDNSu8
*const end
)
3179 const mDNSu8
*ptr
= msg
->data
;
3180 for (i
= 0; i
< msg
->h
.numQuestions
&& ptr
; i
++) ptr
= skipQuestion(msg
, ptr
, end
);
3184 mDNSlocal
const mDNSu8
*LocateAuthorities(const DNSMessage
*const msg
, const mDNSu8
*const end
)
3187 const mDNSu8
*ptr
= LocateAnswers(msg
, end
);
3188 for (i
= 0; i
< msg
->h
.numAnswers
&& ptr
; i
++) ptr
= skipResourceRecord(msg
, ptr
, end
);
3192 // ***************************************************************************
3193 #if COMPILER_LIKES_PRAGMA_MARK
3196 #pragma mark - Packet Sending Functions
3199 mDNSlocal mStatus
mDNSSendDNSMessage(const mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
3200 mDNSInterfaceID InterfaceID
, mDNSIPPort srcport
, const mDNSAddr
*dst
, mDNSIPPort dstport
)
3203 mDNSu16 numQuestions
= msg
->h
.numQuestions
;
3204 mDNSu16 numAnswers
= msg
->h
.numAnswers
;
3205 mDNSu16 numAuthorities
= msg
->h
.numAuthorities
;
3206 mDNSu16 numAdditionals
= msg
->h
.numAdditionals
;
3208 // Put all the integer values in IETF byte-order (MSB first, LSB second)
3209 mDNSu8
*ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
3210 *ptr
++ = (mDNSu8
)(numQuestions
>> 8);
3211 *ptr
++ = (mDNSu8
)(numQuestions
);
3212 *ptr
++ = (mDNSu8
)(numAnswers
>> 8);
3213 *ptr
++ = (mDNSu8
)(numAnswers
);
3214 *ptr
++ = (mDNSu8
)(numAuthorities
>> 8);
3215 *ptr
++ = (mDNSu8
)(numAuthorities
);
3216 *ptr
++ = (mDNSu8
)(numAdditionals
>> 8);
3217 *ptr
++ = (mDNSu8
)(numAdditionals
);
3219 // Send the packet on the wire
3220 status
= mDNSPlatformSendUDP(m
, msg
, end
, InterfaceID
, srcport
, dst
, dstport
);
3222 // Put all the integer values back the way they were before we return
3223 msg
->h
.numQuestions
= numQuestions
;
3224 msg
->h
.numAnswers
= numAnswers
;
3225 msg
->h
.numAuthorities
= numAuthorities
;
3226 msg
->h
.numAdditionals
= numAdditionals
;
3231 mDNSlocal
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
3233 // Setting AnnounceCount to InitialAnnounceCount signals mDNS_Deregister_internal()
3234 // that it should go ahead and immediately dispose of this registration
3235 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
3236 rr
->AnnounceCount
= InitialAnnounceCount
;
3237 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
3240 // NOTE: DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback, which may change
3241 // the record list and/or question list.
3242 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3243 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
3245 if (m
->CurrentRecord
) LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set");
3246 m
->CurrentRecord
= m
->ResourceRecords
;
3248 while (m
->CurrentRecord
)
3250 AuthRecord
*rr
= m
->CurrentRecord
;
3251 m
->CurrentRecord
= rr
->next
;
3252 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3253 CompleteDeregistration(m
, rr
);
3257 // Note about acceleration of announcements to facilitate automatic coalescing of
3258 // multiple independent threads of announcements into a single synchronized thread:
3259 // The announcements in the packet may be at different stages of maturity;
3260 // One-second interval, two-second interval, four-second interval, and so on.
3261 // After we've put in all the announcements that are due, we then consider
3262 // whether there are other nearly-due announcements that are worth accelerating.
3263 // To be eligible for acceleration, a record MUST NOT be older (further along
3264 // its timeline) than the most mature record we've already put in the packet.
3265 // In other words, younger records can have their timelines accelerated to catch up
3266 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
3267 // Older records cannot have their timelines accelerated; this would just widen
3268 // the gap between them and their younger bretheren and get them even more out of sync.
3270 // NOTE: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
3271 // the record list and/or question list.
3272 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3273 mDNSlocal
void SendResponses(mDNS
*const m
)
3276 AuthRecord
*rr
, *r2
;
3277 mDNSs32 maxExistingAnnounceInterval
= 0;
3278 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3280 m
->NextScheduledResponse
= m
->timenow
+ 0x78000000;
3283 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
3286 // Run through our list of records, and decide which ones we're going to announce on all interfaces
3287 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3289 if (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0)
3291 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
3292 else rr
->NextUpdateCredit
= (m
->timenow
+ mDNSPlatformOneSecond
* 60) | 1;
3294 if (TimeToAnnounceThisRecord(rr
, m
->timenow
) && ResourceRecordIsValidAnswer(rr
))
3296 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
3297 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
3298 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
3299 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
3303 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
3304 // Eligible records that are more than half-way to their announcement time are accelerated
3305 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3306 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
3307 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
3308 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
3309 ResourceRecordIsValidAnswer(rr
)))
3310 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
3312 // When sending SRV records (particularly when announcing a new service) automatically add the related Address record(s)
3313 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3314 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
3315 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
3316 if (RRIsAddressType(r2
) && // For all address records (A/AAAA) ...
3317 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
3318 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
3319 rr
->resrec
.rdnamehash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
3320 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, &r2
->resrec
.name
) &&
3321 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
3322 r2
->ImmedAnswer
= mDNSInterfaceMark
; // ... then mark this address record for sending too
3324 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
3325 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
3326 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
3327 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
3328 // -- 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
3329 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
3330 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3331 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3333 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
3335 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3336 if (ResourceRecordIsValidAnswer(r2
))
3337 if (r2
->ImmedAnswer
!= mDNSInterfaceMark
&& r2
->ImmedAnswer
!= rr
->ImmedAnswer
&& SameResourceRecordSignature(&r2
->resrec
, &rr
->resrec
))
3338 r2
->ImmedAnswer
= rr
->ImmedAnswer
;
3340 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
3342 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3343 if (ResourceRecordIsValidAnswer(r2
))
3344 if (r2
->ImmedAdditional
!= rr
->ImmedAdditional
&& SameResourceRecordSignature(&r2
->resrec
, &rr
->resrec
))
3345 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
3349 // Now set SendRNow state appropriately
3350 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3352 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
3354 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
3355 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
3356 rr
->LastMCTime
= m
->timenow
;
3357 rr
->LastMCInterface
= rr
->ImmedAnswer
;
3358 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
3359 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
3361 rr
->AnnounceCount
--;
3362 rr
->ThisAPInterval
*= 2;
3363 rr
->LastAPTime
= m
->timenow
;
3364 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- rr
->AnnounceUntil
>= 0) rr
->AnnounceCount
= 0;
3365 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
3368 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
3370 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
3371 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
3372 rr
->LastMCTime
= m
->timenow
;
3373 rr
->LastMCInterface
= rr
->ImmedAnswer
;
3375 SetNextAnnounceProbeTime(m
, rr
);
3379 // *** 2. Loop through interface list, sending records as appropriate
3385 int numAnnounce
= 0;
3387 DNSMessage response
;
3388 mDNSu8
*responseptr
= response
.data
;
3390 InitializeDNSMessage(&response
.h
, zeroID
, ResponseFlags
);
3392 // First Pass. Look for:
3393 // 1. Deregistering records that need to send their goodbye packet
3394 // 2. Updated records that need to retract their old data
3395 // 3. Answers and announcements we need to send
3396 // In all cases, if we fail, and we've put at least one answer, we break out of the for loop so we can
3397 // send this packet and then try again.
3398 // If we have not put even one answer, then we don't bail out. We pretend we succeeded anyway,
3399 // because otherwise we'll end up in an infinite loop trying to send a record that will never fit.
3400 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3401 if (rr
->SendRNow
== intf
->InterfaceID
)
3403 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3405 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, 0);
3406 if (!newptr
&& response
.h
.numAnswers
) break;
3408 responseptr
= newptr
;
3410 else if (rr
->NewRData
) // If we have new data for this record
3412 RData
*OldRData
= rr
->resrec
.rdata
;
3413 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
3414 // See if we should send a courtesy "goodbye" the old data before we replace it.
3415 // We compare with "InitialAnnounceCount-1" instead of "InitialAnnounceCount" because by the time
3416 // we get to this place in this routine we've we've already decremented rr->AnnounceCount
3417 if (ResourceRecordIsValidAnswer(rr
) && rr
->AnnounceCount
< InitialAnnounceCount
-1)
3419 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, 0);
3420 if (!newptr
&& response
.h
.numAnswers
) break;
3422 responseptr
= newptr
;
3424 // Now try to see if we can fit the update in the same packet (not fatal if we can't)
3425 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
3426 newptr
= PutResourceRecord(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
);
3427 if (newptr
) responseptr
= newptr
;
3428 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
3432 // If this record is supposed to be unique, see if we've sent its whole set
3433 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3435 // Try to find another member of this set that we're still planning to send on this interface
3436 const AuthRecord
*a
;
3437 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
3438 if (a
->SendRNow
== intf
->InterfaceID
&& a
!= rr
&& SameResourceRecordSignature(&a
->resrec
, &rr
->resrec
)) break;
3439 if (a
== mDNSNULL
) // If no more members of this set found
3440 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3442 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, m
->SleepState
? 0 : rr
->resrec
.rroriginalttl
);
3443 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3444 if (!newptr
&& response
.h
.numAnswers
) break;
3445 if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++; else numAnswer
++;
3446 responseptr
= newptr
;
3448 // If sending on all interfaces, go to next interface; else we're finished now
3449 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
3450 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
3452 rr
->SendRNow
= mDNSNULL
;
3455 // Second Pass. Add additional records, if there's space.
3456 newptr
= responseptr
;
3457 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3458 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
3460 // Since additionals are optional, we clear ImmedAdditional anyway, even if we subsequently find it doesn't fit in the packet
3461 rr
->ImmedAdditional
= mDNSNULL
;
3462 if (newptr
&& ResourceRecordIsValidAnswer(rr
))
3464 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3466 // Try to find another member of this set that we're still planning to send on this interface
3467 const AuthRecord
*a
;
3468 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
3469 if (a
->ImmedAdditional
== intf
->InterfaceID
&& SameResourceRecordSignature(&a
->resrec
, &rr
->resrec
)) break;
3470 if (a
== mDNSNULL
) // If no more members of this set found
3471 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3473 newptr
= PutResourceRecord(&response
, newptr
, &response
.h
.numAdditionals
, &rr
->resrec
);
3474 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3477 if (newptr
) responseptr
= newptr
;
3479 if (response
.h
.numAnswers
> 0) // We *never* send a packet with only additionals in it
3481 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3482 numDereg
, numDereg
== 1 ? "" : "s",
3483 numAnnounce
, numAnnounce
== 1 ? "" : "s",
3484 numAnswer
, numAnswer
== 1 ? "" : "s",
3485 response
.h
.numAdditionals
, response
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
3486 mDNSSendDNSMessage(m
, &response
, responseptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v4
, MulticastDNSPort
);
3487 mDNSSendDNSMessage(m
, &response
, responseptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v6
, MulticastDNSPort
);
3488 if (!m
->SuppressSending
) m
->SuppressSending
= (m
->timenow
+ mDNSPlatformOneSecond
/10) | 1; // OR with one to ensure non-zero
3489 if (++pktcount
>= 1000)
3490 { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
3491 // There might be more things to send on this interface, so go around one more time and try again.
3493 else // Nothing more to send on this interface; go to next
3495 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3496 #if MDNS_DEBUGMSGS && 0
3497 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3498 debugf(msg
, intf
, next
);
3505 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3508 if (m
->CurrentRecord
) LogMsg("SendResponses: ERROR m->CurrentRecord already set");
3509 m
->CurrentRecord
= m
->ResourceRecords
;
3510 while (m
->CurrentRecord
)
3512 rr
= m
->CurrentRecord
;
3513 m
->CurrentRecord
= rr
->next
;
3517 RData
*OldRData
= rr
->resrec
.rdata
;
3518 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
3519 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
3520 if (rr
->UpdateCallback
)
3521 rr
->UpdateCallback(m
, rr
, OldRData
); // ... and let the client know
3524 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3525 CompleteDeregistration(m
, rr
);
3528 rr
->ImmedAnswer
= mDNSNULL
;
3529 rr
->v4Requester
= zeroIPAddr
;
3530 rr
->v6Requester
= zerov6Addr
;
3533 verbosedebugf("SendResponses: Next in %d ticks", m
->NextScheduledResponse
- m
->timenow
);
3536 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3537 // so we want to be lazy about how frequently we do it.
3538 // 1. If a cache record is currently referenced by *no* active questions,
3539 // then we don't mind expiring it up to a minute late (who will know?)
3540 // 2. Else, if a cache record is due for some of its final expiration queries,
3541 // we'll allow them to be late by up to 2% of the TTL
3542 // 3. Else, if a cache record has completed all its final expiration queries without success,
3543 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3544 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3545 // so allow at most 1/10 second lateness
3546 #define CacheCheckGracePeriod(RR) ( \
3547 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3548 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
3549 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : (mDNSPlatformOneSecond/10))
3551 // Note: MUST call SetNextCacheCheckTime any time we change:
3553 // rr->resrec.rroriginalttl
3554 // rr->UnansweredQueries
3555 // rr->CRActiveQuestion
3556 mDNSlocal
void SetNextCacheCheckTime(mDNS
*const m
, CacheRecord
*const rr
)
3558 rr
->NextRequiredQuery
= RRExpireTime(rr
);
3560 // If we have an active question, then see if we want to schedule a refresher query for this record.
3561 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3562 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3564 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
3565 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
3566 verbosedebugf("SetNextCacheCheckTime: %##s (%s) NextRequiredQuery in %ld sec",
3567 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
);
3570 if (m
->NextCacheCheck
- (rr
->NextRequiredQuery
+ CacheCheckGracePeriod(rr
)) > 0)
3571 m
->NextCacheCheck
= (rr
->NextRequiredQuery
+ CacheCheckGracePeriod(rr
));
3574 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 45)
3575 #define kDefaultReconfirmTimeForCableDisconnect ((mDNSu32)mDNSPlatformOneSecond * 5)
3576 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3578 mDNSlocal mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
3580 if (interval
< kMinimumReconfirmTime
)
3581 interval
= kMinimumReconfirmTime
;
3582 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3583 interval
= 0x10000000;
3585 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3586 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
3588 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3589 interval
+= mDNSRandom(interval
/3);
3590 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
3591 rr
->resrec
.rroriginalttl
= interval
* 4 / mDNSPlatformOneSecond
;
3592 SetNextCacheCheckTime(m
, rr
);
3594 debugf("mDNS_Reconfirm_internal:%5ld ticks to go for %s", RRExpireTime(rr
) - m
->timenow
, GetRRDisplayString(m
, rr
));
3595 return(mStatus_NoError
);
3598 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
3600 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3601 // It also appends to the list of known answer records that need to be included,
3602 // and updates the forcast for the size of the known answer section.
3603 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, DNSMessage
*query
, mDNSu8
**queryptr
, DNSQuestion
*q
,
3604 CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
3606 mDNSBool ucast
= q
->LargeAnswers
|| q
->ThisQInterval
<= InitialQuestionInterval
*2;
3607 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3608 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
3609 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
3612 debugf("BuildQuestion: No more space in this packet for question %##s", q
->qname
.c
);
3615 else if (newptr
+ *answerforecast
>= limit
)
3617 verbosedebugf("BuildQuestion: Retracting question %##s new forecast total %d", q
->qname
.c
, newptr
+ *answerforecast
- query
->data
);
3618 query
->h
.numQuestions
--;
3623 mDNSu32 forecast
= *answerforecast
;
3625 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
3627 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3628 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3629 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not already in the known answer list
3630 rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3631 ResourceRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3632 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3633 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0)// and we'll ask at least once again before NextRequiredQuery
3635 *ka
= rr
; // Link this record into our known answer chain
3636 ka
= &rr
->NextInKAList
;
3637 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3638 forecast
+= 12 + rr
->resrec
.rdestimate
;
3639 // If we're trying to put more than one question in this packet, and it doesn't fit
3640 // then undo that last question and try again next time
3641 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
3643 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
3644 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
);
3645 query
->h
.numQuestions
--;
3646 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3647 while (*ka
) { CacheRecord
*rr
= *ka
; *ka
= mDNSNULL
; ka
= &rr
->NextInKAList
; }
3648 return(mDNSfalse
); // Return false, so we'll try again in the next packet
3652 // Traffic reduction:
3653 // If we already have at least one unique answer in the cache,
3654 // OR we have so many shared answers that the KA list is too big to fit in one packet
3655 // The we suppress queries number 3 and 5:
3656 // Query 1 (immediately; ThisQInterval = 1 sec; request unicast replies)
3657 // Query 2 (after 1 second; ThisQInterval = 2 sec; send normally)
3658 // Query 3 (after 2 seconds; ThisQInterval = 4 sec; may suppress)
3659 // Query 4 (after 4 seconds; ThisQInterval = 8 sec; send normally)
3660 // Query 5 (after 8 seconds; ThisQInterval = 16 sec; may suppress)
3661 // Query 6 (after 16 seconds; ThisQInterval = 32 sec; send normally)
3662 if (q
->UniqueAnswers
|| newptr
+ forecast
>= limit
)
3663 if (q
->ThisQInterval
== InitialQuestionInterval
* 8 || q
->ThisQInterval
== InitialQuestionInterval
* 32)
3665 query
->h
.numQuestions
--;
3666 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3667 while (*ka
) { CacheRecord
*rr
= *ka
; *ka
= mDNSNULL
; ka
= &rr
->NextInKAList
; }
3668 return(mDNStrue
); // Return true: pretend we succeeded, even though we actually suppressed this question
3671 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3672 *queryptr
= newptr
; // Update the packet pointer
3673 *answerforecast
= forecast
; // Update the forecast
3674 *kalistptrptr
= ka
; // Update the known answer list pointer
3675 if (ucast
) m
->ExpectUnicastResponse
= m
->timenow
;
3677 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // For every resource record in our cache,
3678 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3679 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not in the known answer list
3680 ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) // which answers our question
3682 rr
->UnansweredQueries
++; // indicate that we're expecting a response
3683 rr
->LastUnansweredTime
= m
->timenow
;
3684 SetNextCacheCheckTime(m
, rr
);
3691 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, DNSQuestion
*q
)
3696 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3697 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
3698 if ((target
= GetRRDomainNameTarget(&rr
->resrec
)) && rr
->resrec
.rdnamehash
== q
->qnamehash
&& SameDomainName(target
, &q
->qname
))
3699 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
3702 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3703 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
3706 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3709 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
3712 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3715 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
3718 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3719 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3720 for (i
=0; i
<DupSuppressInfoSize
; i
++)
3721 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
3723 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
3724 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
3725 if (v4
&& v6
) return(mDNStrue
);
3730 mDNSlocal
int RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
3734 // See if we have this one in our list somewhere already
3735 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
3737 // If not, find a slot we can re-use
3738 if (i
>= DupSuppressInfoSize
)
3741 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
3742 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
3746 // Record the info about this query we saw
3748 ds
[i
].InterfaceID
= InterfaceID
;
3754 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
3756 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3757 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
3760 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3761 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
3763 // We forecast: qname (n) type (2) class (2)
3764 mDNSu32 forecast
= DomainNameLength(&q
->qname
) + 4;
3766 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3767 if (rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3768 ResourceRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3769 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3770 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0)// and we'll ask at least once again before NextRequiredQuery
3772 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3773 forecast
+= 12 + rr
->resrec
.rdestimate
;
3774 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
3782 // How Standard Queries are generated:
3783 // 1. The Question Section contains the question
3784 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3786 // How Probe Queries are generated:
3787 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3788 // if some other host is already using *any* records with this name, we want to know about it.
3789 // 2. The Authority Section contains the proposed values we intend to use for one or more
3790 // of our records with that name (analogous to the Update section of DNS Update packets)
3791 // because if some other host is probing at the same time, we each want to know what the other is
3792 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3794 mDNSlocal
void SendQueries(mDNS
*const m
)
3798 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3799 mDNSs32 maxExistingQuestionInterval
= 0;
3800 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3801 CacheRecord
*KnownAnswerList
= mDNSNULL
;
3803 // 1. If time for a query, work out what we need to do
3804 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
3808 m
->NextScheduledQuery
= m
->timenow
+ 0x78000000;
3810 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3811 // to their NextRequiredQuery to be worth batching them together with this one
3812 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3813 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
3814 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3815 if (m
->timenow
+ TicksTTL(rr
)/50 - rr
->NextRequiredQuery
>= 0)
3817 q
= rr
->CRActiveQuestion
;
3818 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(rr
)/20, rr
->resrec
.InterfaceID
);
3819 if (q
->SendQNow
== mDNSNULL
) q
->SendQNow
= rr
->resrec
.InterfaceID
;
3820 else if (q
->SendQNow
!= rr
->resrec
.InterfaceID
) q
->SendQNow
= mDNSInterfaceMark
;
3823 // Scan our list of questions to see which ones we're definitely going to send
3824 for (q
= m
->Questions
; q
; q
=q
->next
)
3825 if (TimeToSendThisQuestion(q
, m
->timenow
))
3827 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3828 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3829 maxExistingQuestionInterval
= q
->ThisQInterval
;
3832 // Scan our list of questions
3833 // (a) to see if there are any more that are worth accelerating, and
3834 // (b) to update the state variables for all the questions we're going to send
3835 for (q
= m
->Questions
; q
; q
=q
->next
)
3837 if (q
->SendQNow
|| (ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
)))
3839 // If at least halfway to next query time, advance to next interval
3840 // If less than halfway to next query time, treat this as logically a repeat of the last transmission, without advancing the interval
3841 if (m
->timenow
- (q
->LastQTime
+ q
->ThisQInterval
/2) >= 0)
3843 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3844 q
->ThisQInterval
*= 2;
3845 if (q
->ThisQInterval
> MaxQuestionInterval
)
3846 q
->ThisQInterval
= MaxQuestionInterval
;
3847 else if (q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* 8)
3849 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents", q
->qname
.c
, DNSTypeName(q
->qtype
));
3850 ReconfirmAntecedents(m
, q
); // If sending third query, and no answers yet, time to begin doubting the source
3854 // Mark for sending. (If no active interfaces, then don't even try.)
3855 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3858 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3859 q
->LastQTime
= m
->timenow
;
3862 // If we recorded a duplicate suppression for this question less than half an interval ago,
3863 // then we consider it recent enough that we don't need to do an identical query ourselves.
3864 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3866 q
->LastQTxTime
= m
->timenow
;
3867 q
->RecentAnswers
= 0;
3869 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3870 SetNextQueryTime(m
,q
);
3874 // 2. Scan our authoritative RR list to see what probes we might need to send
3875 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
3877 m
->NextScheduledProbe
= m
->timenow
+ 0x78000000;
3879 if (m
->CurrentRecord
) LogMsg("SendQueries: ERROR m->CurrentRecord already set");
3880 m
->CurrentRecord
= m
->ResourceRecords
;
3881 while (m
->CurrentRecord
)
3883 AuthRecord
*rr
= m
->CurrentRecord
;
3884 m
->CurrentRecord
= rr
->next
;
3885 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3887 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3888 if (m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
3890 SetNextAnnounceProbeTime(m
, rr
);
3892 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3893 else if (rr
->ProbeCount
)
3895 // Mark for sending. (If no active interfaces, then don't even try.)
3896 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
3897 rr
->LastAPTime
= m
->timenow
;
3899 SetNextAnnounceProbeTime(m
, rr
);
3901 // else, if it has now finished probing, move it to state Verified, and update m->NextScheduledResponse so it will be announced
3905 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3906 rr
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3907 rr
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3908 SetNextAnnounceProbeTime(m
, rr
);
3909 // If we have any records on our duplicate list that match this one, they have now also completed probing
3910 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3911 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, rr
))
3913 CompleteProbing(m
, rr
);
3917 m
->CurrentRecord
= m
->DuplicateRecords
;
3918 while (m
->CurrentRecord
)
3920 AuthRecord
*rr
= m
->CurrentRecord
;
3921 m
->CurrentRecord
= rr
->next
;
3922 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& rr
->ProbeCount
== 0)
3923 CompleteProbing(m
, rr
);
3927 // 3. Now we know which queries and probes we're sending, go through our interface list sending the appropriate queries on each interface
3932 mDNSu8
*queryptr
= query
.data
;
3933 InitializeDNSMessage(&query
.h
, zeroID
, QueryFlags
);
3934 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3935 if (!KnownAnswerList
)
3937 // Start a new known-answer list
3938 CacheRecord
**kalistptr
= &KnownAnswerList
;
3939 mDNSu32 answerforecast
= 0;
3941 // Put query questions in this packet
3942 for (q
= m
->Questions
; q
; q
=q
->next
)
3943 if (q
->SendQNow
== intf
->InterfaceID
)
3945 debugf("SendQueries: %s question for %##s (%s) at %lu forecast total %lu",
3946 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3947 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- query
.data
, queryptr
+ answerforecast
- query
.data
);
3948 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3949 if (SuppressOnThisInterface(q
->DupSuppress
, intf
) ||
3950 BuildQuestion(m
, &query
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3951 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3954 // Put probe questions in this packet
3955 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3956 if (rr
->SendRNow
== intf
->InterfaceID
)
3958 mDNSBool ucast
= rr
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1;
3959 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3960 const mDNSu8
*const limit
= query
.data
+ ((query
.h
.numQuestions
) ? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3961 mDNSu8
*newptr
= putQuestion(&query
, queryptr
, limit
, &rr
->resrec
.name
, kDNSQType_ANY
, (mDNSu16
)(rr
->resrec
.rrclass
| ucbit
));
3962 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3963 mDNSu32 forecast
= answerforecast
+ 12 + rr
->resrec
.rdestimate
;
3964 if (newptr
&& newptr
+ forecast
< limit
)
3967 answerforecast
= forecast
;
3968 rr
->SendRNow
= (rr
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3969 rr
->IncludeInProbe
= mDNStrue
;
3970 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->ProbeCount
);
3974 verbosedebugf("SendQueries: Retracting Question %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
3975 query
.h
.numQuestions
--;
3980 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3981 while (KnownAnswerList
)
3983 CacheRecord
*rr
= KnownAnswerList
;
3984 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3985 mDNSu8
*newptr
= PutResourceRecordTTL(&query
, queryptr
, &query
.h
.numAnswers
, &rr
->resrec
, rr
->resrec
.rroriginalttl
- SecsSinceRcvd
);
3988 verbosedebugf("SendQueries: Put %##s (%s) at %lu - %lu", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), queryptr
- query
.data
, newptr
- query
.data
);
3990 KnownAnswerList
= rr
->NextInKAList
;
3991 rr
->NextInKAList
= mDNSNULL
;
3995 // If we ran out of space and we have more than one question in the packet, that's an error --
3996 // we shouldn't have put more than one question if there was a risk of us running out of space.
3997 if (query
.h
.numQuestions
> 1)
3998 LogMsg("SendQueries: Put %d answers; No more space for known answers", query
.h
.numAnswers
);
3999 query
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
4004 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4005 if (rr
->IncludeInProbe
)
4007 mDNSu8
*newptr
= PutResourceRecord(&query
, queryptr
, &query
.h
.numAuthorities
, &rr
->resrec
);
4008 rr
->IncludeInProbe
= mDNSfalse
;
4009 if (newptr
) queryptr
= newptr
;
4010 else LogMsg("SendQueries: How did we fail to have space for the Update record %##s (%s)?",
4011 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4014 if (queryptr
> query
.data
)
4016 if ((query
.h
.flags
.b
[0] & kDNSFlag0_TC
) && query
.h
.numQuestions
> 1)
4017 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet\n", query
.h
.numQuestions
);
4018 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
4019 query
.h
.numQuestions
, query
.h
.numQuestions
== 1 ? "" : "s",
4020 query
.h
.numAnswers
, query
.h
.numAnswers
== 1 ? "" : "s",
4021 query
.h
.numAuthorities
, query
.h
.numAuthorities
== 1 ? "" : "s", intf
->InterfaceID
);
4022 mDNSSendDNSMessage(m
, &query
, queryptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v4
, MulticastDNSPort
);
4023 mDNSSendDNSMessage(m
, &query
, queryptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v6
, MulticastDNSPort
);
4024 if (!m
->SuppressSending
) m
->SuppressSending
= (m
->timenow
+ mDNSPlatformOneSecond
/10) | 1; // OR with one to ensure non-zero
4025 if (++pktcount
>= 1000)
4026 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
4027 // There might be more records left in the known answer list, or more questions to send
4028 // on this interface, so go around one more time and try again.
4030 else // Nothing more to send on this interface; go to next
4032 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
4033 #if MDNS_DEBUGMSGS && 0
4034 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4035 debugf(msg
, intf
, next
);
4042 // ***************************************************************************
4043 #if COMPILER_LIKES_PRAGMA_MARK
4045 #pragma mark - RR List Management & Task Management
4048 // NOTE: AnswerQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4049 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4050 mDNSlocal
void AnswerQuestionWithResourceRecord(mDNS
*const m
, DNSQuestion
*q
, CacheRecord
*rr
, mDNSBool AddRecord
)
4052 verbosedebugf("AnswerQuestionWithResourceRecord:%4lu %s TTL%6lu %##s (%s)",
4053 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", rr
->resrec
.rroriginalttl
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4055 rr
->LastUsed
= m
->timenow
;
4057 if (ActiveQuestion(q
) && rr
->CRActiveQuestion
!= q
)
4059 if (!rr
->CRActiveQuestion
) m
->rrcache_active
++; // If not previously active, increment rrcache_active count
4060 rr
->CRActiveQuestion
= q
; // We know q is non-null
4061 SetNextCacheCheckTime(m
, rr
);
4064 // CAUTION: MUST NOT do anything more with q after calling q->Callback(), because the client's callback function
4065 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
4066 // Right now the only routines that call AnswerQuestionWithResourceRecord() are CacheRecordAdd(), CacheRecordRmv()
4067 // and AnswerNewQuestion(), and all of them use the "m->CurrentQuestion" mechanism to protect against questions
4068 // being deleted out from under them.
4069 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4070 if (q
->QuestionCallback
)
4071 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4072 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4075 // CacheRecordAdd is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4076 // If new questions are created as a result of invoking client callbacks, they will be added to
4077 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4078 // rr is a new CacheRecord just received into our cache
4079 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4080 // NOTE: CacheRecordAdd calls AnswerQuestionWithResourceRecord which can call a user callback,
4081 // which may change the record list and/or question list.
4082 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4083 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*rr
)
4085 if (m
->CurrentQuestion
) LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set");
4086 m
->CurrentQuestion
= m
->Questions
;
4087 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4089 DNSQuestion
*q
= m
->CurrentQuestion
;
4090 m
->CurrentQuestion
= q
->next
;
4091 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4093 // If this question is one that's actively sending queries, and it's received ten answers within one second of sending the last
4094 // query packet, then that indicates some radical network topology change, so reset its exponential backoff back to the start.
4095 // We must be at least at the eight-second interval to do this. If we're at the four-second interval, or less,
4096 // there's not much benefit accelerating because we will anyway send another query within a few seconds.
4097 // The first reset query is sent out randomized over the next four seconds to reduce possible synchronization between machines.
4098 if (ActiveQuestion(q
) && ++q
->RecentAnswers
>= 10 &&
4099 q
->ThisQInterval
> InitialQuestionInterval
*16 && m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
4101 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst; restarting exponential backoff sequence",
4102 q
->qname
.c
, DNSTypeName(q
->qtype
));
4103 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
4104 q
->ThisQInterval
= InitialQuestionInterval
;
4105 SetNextQueryTime(m
,q
);
4107 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
);
4108 q
->CurrentAnswers
++;
4109 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4110 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4111 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4112 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4115 m
->CurrentQuestion
= mDNSNULL
;
4118 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute
4119 // If new questions are created as a result of invoking client callbacks, they will be added to
4120 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4121 // rr is an existing cache CacheRecord that just expired and is being deleted
4122 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4123 // NOTE: CacheRecordRmv calls AnswerQuestionWithResourceRecord which can call a user callback,
4124 // which may change the record list and/or question list.
4125 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4126 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*rr
)
4128 if (m
->CurrentQuestion
) LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set");
4129 m
->CurrentQuestion
= m
->Questions
;
4130 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4132 DNSQuestion
*q
= m
->CurrentQuestion
;
4133 m
->CurrentQuestion
= q
->next
;
4134 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4136 verbosedebugf("CacheRecordRmv %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4137 if (q
->CurrentAnswers
== 0)
4138 LogMsg("CacheRecordRmv ERROR: How can CurrentAnswers already be zero for %p %##s (%s)?", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
4141 q
->CurrentAnswers
--;
4142 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
4143 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
4145 if (q
->CurrentAnswers
== 0)
4147 debugf("CacheRecordRmv: Zero current answers for %##s (%s); will reconfirm antecedents", q
->qname
.c
, DNSTypeName(q
->qtype
));
4148 ReconfirmAntecedents(m
, q
);
4150 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNSfalse
);
4151 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4154 m
->CurrentQuestion
= mDNSNULL
;
4157 mDNSlocal
void ReleaseCacheRR(mDNS
*const m
, CacheRecord
*r
)
4159 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->rdatastorage
)
4160 mDNSPlatformMemFree(r
->resrec
.rdata
);
4161 r
->resrec
.rdata
= mDNSNULL
;
4162 r
->next
= m
->rrcache_free
;
4163 m
->rrcache_free
= r
;
4164 m
->rrcache_totalused
--;
4167 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, mDNSu32 slot
)
4169 CacheRecord
**rp
= &(m
->rrcache_hash
[slot
]);
4171 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4172 m
->lock_rrcache
= 1;
4176 CacheRecord
*const rr
= *rp
;
4177 mDNSs32 event
= RRExpireTime(rr
);
4178 if (m
->timenow
- event
>= 0) // If expired, delete it
4180 *rp
= rr
->next
; // Cut it from the list
4181 verbosedebugf("CheckCacheExpiration: Deleting %s", GetRRDisplayString(m
, rr
));
4182 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
4184 CacheRecordRmv(m
, rr
);
4185 m
->rrcache_active
--;
4187 m
->rrcache_used
[slot
]--;
4188 ReleaseCacheRR(m
, rr
);
4190 else // else, not expired; see if we need to query
4192 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
4194 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
4195 event
= rr
->NextRequiredQuery
; // then just record when we want the next query
4196 else // else trigger our question to go out now
4198 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4199 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4200 m
->NextScheduledQuery
= m
->timenow
;
4201 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTime(),
4202 // which will correctly update m->NextCacheCheck for us
4203 event
= m
->timenow
+ 0x3FFFFFFF;
4206 if (m
->NextCacheCheck
- (event
+ CacheCheckGracePeriod(rr
)) > 0)
4207 m
->NextCacheCheck
= (event
+ CacheCheckGracePeriod(rr
));
4211 m
->lock_rrcache
= 0;
4214 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
4216 mDNSBool ShouldQueryImmediately
= mDNStrue
;
4218 DNSQuestion
*q
= m
->NewQuestions
; // Grab the question we're going to answer
4219 mDNSu32 slot
= HashSlot(&q
->qname
);
4221 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4223 CheckCacheExpiration(m
, slot
);
4224 m
->NewQuestions
= q
->next
; // Advance NewQuestions to the next *after* calling CheckCacheExpiration();
4226 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4227 // This should be safe, because calling the client's question callback may cause the
4228 // question list to be modified, but should not ever cause the rrcache list to be modified.
4229 // If the client's question callback deletes the question, then m->CurrentQuestion will
4230 // be advanced, and we'll exit out of the loop
4231 m
->lock_rrcache
= 1;
4232 if (m
->CurrentQuestion
) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4233 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4234 for (rr
=m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
4235 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4237 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4238 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
4239 if (rr
->resrec
.rroriginalttl
<= SecsSinceRcvd
)
4241 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %##s (%s)",
4242 rr
->resrec
.rroriginalttl
, SecsSinceRcvd
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4243 continue; // Go to next one in loop
4246 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4247 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4248 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ShouldQueryImmediately
= mDNSfalse
;
4249 q
->CurrentAnswers
++;
4250 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4251 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4252 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4253 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4254 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4257 if (ShouldQueryImmediately
&& m
->CurrentQuestion
== q
)
4259 q
->ThisQInterval
= InitialQuestionInterval
;
4260 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4261 m
->NextScheduledQuery
= m
->timenow
;
4263 m
->CurrentQuestion
= mDNSNULL
;
4264 m
->lock_rrcache
= 0;
4267 mDNSlocal
void AnswerLocalOnlyQuestionWithResourceRecord(mDNS
*const m
, DNSQuestion
*q
, AuthRecord
*rr
, mDNSBool AddRecord
)
4269 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
4270 if (AddRecord
) rr
->AnnounceCount
= InitialAnnounceCount
- 1;
4271 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4272 if (q
->QuestionCallback
)
4273 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4274 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4277 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
4279 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
4280 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewQuestions to the next (if any)
4282 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4284 if (m
->CurrentQuestion
) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4285 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4287 m
->CurrentRecord
= m
->LocalOnlyRecords
;
4288 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalOnlyRecords
)
4290 AuthRecord
*rr
= m
->CurrentRecord
;
4291 m
->CurrentRecord
= rr
->next
;
4292 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4294 AnswerLocalOnlyQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4295 // MUST NOT dereference q again after calling AnswerLocalOnlyQuestionWithResourceRecord()
4296 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4300 m
->CurrentQuestion
= mDNSNULL
;
4303 mDNSlocal
void AnswerLocalOnlyQuestions(mDNS
*const m
, AuthRecord
*rr
, mDNSBool AddRecord
)
4305 if (m
->CurrentQuestion
) LogMsg("AnswerLocalOnlyQuestions ERROR m->CurrentQuestion already set");
4306 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
4307 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
4309 DNSQuestion
*q
= m
->CurrentQuestion
;
4310 m
->CurrentQuestion
= q
->next
;
4311 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4313 debugf("AnswerLocalOnlyQuestions %p %##s (%s) %lu", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
);
4314 AnswerLocalOnlyQuestionWithResourceRecord(m
, q
, rr
, AddRecord
);
4315 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4318 m
->CurrentQuestion
= mDNSNULL
;
4321 mDNSlocal
void DiscardLocalOnlyRecords(mDNS
*const m
)
4323 AuthRecord
*rr
= m
->LocalOnlyRecords
;
4326 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
4327 { AnswerLocalOnlyQuestions(m
, rr
, mDNSfalse
); CompleteDeregistration(m
, rr
); return; }
4328 if (rr
->ProbeCount
) { mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
); return; }
4331 m
->DiscardLocalOnlyRecords
= mDNSfalse
;
4334 mDNSlocal
void AnswerForNewLocalOnlyRecords(mDNS
*const m
)
4336 AuthRecord
*rr
= m
->NewLocalOnlyRecords
;
4337 m
->NewLocalOnlyRecords
= m
->NewLocalOnlyRecords
->next
;
4338 AnswerLocalOnlyQuestions(m
, rr
, mDNStrue
);
4341 mDNSlocal CacheRecord
*GetFreeCacheRR(mDNS
*const m
, mDNSu16 RDLength
)
4343 CacheRecord
*r
= mDNSNULL
;
4345 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
4346 m
->lock_rrcache
= 1;
4348 // If we have no free records, ask the client layer to give us some more memory
4349 if (!m
->rrcache_free
&& m
->MainCallback
)
4351 if (m
->rrcache_totalused
!= m
->rrcache_size
)
4352 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4353 m
->rrcache_totalused
, m
->rrcache_size
);
4355 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4356 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4357 // To guard against this, if we're actively using less than 1/32 of our cache, then we
4358 // purge all the unused records and recycle them, instead of allocating more memory.
4359 if (m
->rrcache_size
>= 512 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
4360 debugf("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4361 m
->rrcache_size
, m
->rrcache_active
);
4363 m
->MainCallback(m
, mStatus_GrowCache
);
4366 // If we still have no free records, recycle all the records we can.
4367 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4368 if (!m
->rrcache_free
)
4371 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
4375 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4377 rr
= &(m
->rrcache_hash
[slot
]);
4380 // Records that answer still-active questions are not candidates for deletion
4381 if ((*rr
)->CRActiveQuestion
)
4385 CacheRecord
*r
= *rr
;
4386 *rr
= (*rr
)->next
; // Cut record from list
4387 m
->rrcache_used
[slot
]--; // Decrement counts
4388 ReleaseCacheRR(m
, r
);
4393 debugf("Clear unused records; m->rrcache_totalused was %lu; now %lu", oldtotalused
, m
->rrcache_totalused
);
4397 if (m
->rrcache_free
) // If there are records in the free list, take one
4399 r
= m
->rrcache_free
;
4400 m
->rrcache_free
= r
->next
;
4405 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
4407 debugf("RR Cache now using %ld records", m
->rrcache_totalused
);
4408 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
4409 else m
->rrcache_report
+= 100;
4411 mDNSPlatformMemZero(r
, sizeof(*r
));
4412 r
->resrec
.rdata
= (RData
*)&r
->rdatastorage
; // By default, assume we're usually going to be using local storage
4414 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
4416 r
->resrec
.rdata
= (RData
*)mDNSPlatformMemAllocate(sizeofRDataHeader
+ RDLength
);
4417 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
4418 else { ReleaseCacheRR(m
, r
); r
= mDNSNULL
; }
4422 m
->lock_rrcache
= 0;
4427 mDNSlocal
void PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
4429 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4430 // a positive answer using an expired record (e.g. from an interface that has gone away).
4431 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4432 // summary deletion without giving the proper callback to any questions that are monitoring it.
4433 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4434 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
4435 rr
->UnansweredQueries
= MaxUnansweredQueries
;
4436 rr
->resrec
.rroriginalttl
= 0;
4437 SetNextCacheCheckTime(m
, rr
);
4440 mDNSlocal
void mDNS_Lock(mDNS
*const m
)
4442 // MUST grab the platform lock FIRST!
4443 mDNSPlatformLock(m
);
4445 // Normally, mDNS_reentrancy is zero and so is mDNS_busy
4446 // However, when we call a client callback mDNS_busy is one, and we increment mDNS_reentrancy too
4447 // If that client callback does mDNS API calls, mDNS_reentrancy and mDNS_busy will both be one
4448 // If mDNS_busy != mDNS_reentrancy that's a bad sign
4449 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
4450 LogMsg("mDNS_Lock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4452 // If this is an initial entry into the mDNSCore code, set m->timenow
4453 // else, if this is a re-entrant entry into the mDNSCore code, m->timenow should already be set
4454 if (m
->mDNS_busy
== 0)
4457 LogMsg("mDNS_Lock: m->timenow already set (%ld/%ld)", m
->timenow
, mDNSPlatformTimeNow() + m
->timenow_adjust
);
4458 m
->timenow
= mDNSPlatformTimeNow() + m
->timenow_adjust
;
4459 if (m
->timenow
== 0) m
->timenow
= 1;
4461 else if (m
->timenow
== 0)
4463 LogMsg("mDNS_Lock: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
4464 m
->timenow
= mDNSPlatformTimeNow() + m
->timenow_adjust
;
4465 if (m
->timenow
== 0) m
->timenow
= 1;
4468 if (m
->timenow_last
- m
->timenow
> 0)
4470 m
->timenow_adjust
+= m
->timenow_last
- m
->timenow
;
4471 LogMsg("mDNSPlatformTimeNow went backwards by %ld ticks; setting correction factor to %ld", m
->timenow_last
- m
->timenow
, m
->timenow_adjust
);
4472 m
->timenow
= m
->timenow_last
;
4474 m
->timenow_last
= m
->timenow
;
4476 // Increment mDNS_busy so we'll recognise re-entrant calls
4480 mDNSlocal mDNSs32
GetNextScheduledEvent(const mDNS
*const m
)
4482 mDNSs32 e
= m
->timenow
+ 0x78000000;
4483 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| m
->SleepState
) return(e
);
4484 if (m
->NewQuestions
) return(m
->timenow
);
4485 if (m
->NewLocalOnlyQuestions
) return(m
->timenow
);
4486 if (m
->NewLocalOnlyRecords
) return(m
->timenow
);
4487 if (m
->DiscardLocalOnlyRecords
) return(m
->timenow
);
4488 if (m
->SuppressSending
) return(m
->SuppressSending
);
4489 if (e
- m
->NextCacheCheck
> 0) e
= m
->NextCacheCheck
;
4490 if (e
- m
->NextScheduledQuery
> 0) e
= m
->NextScheduledQuery
;
4491 if (e
- m
->NextScheduledProbe
> 0) e
= m
->NextScheduledProbe
;
4492 if (e
- m
->NextScheduledResponse
> 0) e
= m
->NextScheduledResponse
;
4496 mDNSlocal
void mDNS_Unlock(mDNS
*const m
)
4498 // Decrement mDNS_busy
4501 // Check for locking failures
4502 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
4503 LogMsg("mDNS_Unlock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4505 // If this is a final exit from the mDNSCore code, set m->NextScheduledEvent and clear m->timenow
4506 if (m
->mDNS_busy
== 0)
4508 m
->NextScheduledEvent
= GetNextScheduledEvent(m
);
4509 if (m
->timenow
== 0) LogMsg("mDNS_Unlock: ERROR! m->timenow aready zero");
4513 // MUST release the platform lock LAST!
4514 mDNSPlatformUnlock(m
);
4517 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
4519 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
4521 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
4525 verbosedebugf("mDNS_Execute");
4526 if (m
->CurrentQuestion
) LogMsg("mDNS_Execute: ERROR! m->CurrentQuestion already set");
4528 // 1. If we're past the probe suppression time, we can clear it
4529 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
4531 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4532 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
4534 // 3. Purge our cache of stale old records
4535 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
4538 m
->NextCacheCheck
= m
->timenow
+ 0x3FFFFFFF;
4539 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++) CheckCacheExpiration(m
, slot
);
4542 // 4. See if we can answer any of our new local questions from the cache
4543 for (i
=0; m
->NewQuestions
&& i
<1000; i
++) AnswerNewQuestion(m
);
4544 if (i
>= 1000) debugf("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4546 for (i
=0; m
->DiscardLocalOnlyRecords
&& i
<1000; i
++) DiscardLocalOnlyRecords(m
);
4547 if (i
>= 1000) debugf("mDNS_Execute: DiscardLocalOnlyRecords exceeded loop limit");
4549 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
4550 if (i
>= 1000) debugf("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4552 for (i
=0; m
->NewLocalOnlyRecords
&& i
<1000; i
++) AnswerForNewLocalOnlyRecords(m
);
4553 if (i
>= 1000) debugf("mDNS_Execute: AnswerLocalOnlyQuestions exceeded loop limit");
4555 // 5. See what packets we need to send
4556 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| m
->SleepState
) DiscardDeregistrations(m
);
4557 else if (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0)
4559 // If the platform code is ready, and we're not suppressing packet generation right now
4560 // then send our responses, probes, and questions.
4561 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them
4562 // We send queries next, because there might be final-stage probes that complete their probing here, causing
4563 // them to advance to announcing state, and we want those to be included in any announcements we send out.
4564 // Finally, we send responses, including the previously mentioned records that just completed probing
4565 m
->SuppressSending
= 0;
4567 // 6. Send Query packets. This may cause some probing records to advance to announcing state
4568 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
4569 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
4571 LogMsg("mDNS_Execute: SendQueries didn't send all its queries; will try again in one second");
4572 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
4574 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
4576 LogMsg("mDNS_Execute: SendQueries didn't send all its probes; will try again in one second");
4577 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
4580 // 7. Send Response packets, including probing records just advanced to announcing state
4581 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
4582 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
4584 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4585 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
4589 m
->RandomQueryDelay
= 0; // Clear m->RandomQueryDelay, ready to pick a new different value, when necessary
4592 // Note about multi-threaded systems:
4593 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4594 // performing mDNS API operations that change our next scheduled event time.
4596 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
4597 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4598 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4599 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4600 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4601 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4602 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4603 // without blocking. This avoids the race condition between the signal from the other thread arriving
4604 // just *before* or just *after* the main thread enters the blocking primitive.
4606 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4607 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4608 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4609 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4610 // by the time it gets to the timer callback function).
4612 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4613 return(m
->NextScheduledEvent
);
4616 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
4617 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
4618 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
4619 // Note that sleep/wake calls do not have to be paired one-for-one; it is acceptable to call
4620 // mDNSCoreMachineSleep(m, mDNSfalse) any time there is reason to believe that the machine may have just
4621 // found itself in a new network environment. For example, if the Ethernet hardware indicates that the
4622 // cable has just been connected, the platform support layer should call mDNSCoreMachineSleep(m, mDNSfalse)
4623 // to make mDNSCore re-issue its outstanding queries, probe for record uniqueness, etc.
4624 // While it is safe to call mDNSCoreMachineSleep(m, mDNSfalse) at any time, it does cause extra network
4625 // traffic, so it should only be called when there is legitimate reason to believe the machine
4626 // may have become attached to a new network.
4627 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleepstate
)
4633 m
->SleepState
= sleepstate
;
4634 LogMsg("mDNSResponder %s at %ld", sleepstate
? "Sleeping" : "Waking", m
->timenow
);
4638 // Mark all the records we need to deregister and send them
4639 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4640 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->AnnounceCount
< InitialAnnounceCount
)
4641 rr
->ImmedAnswer
= mDNSInterfaceMark
;
4650 // 1. Retrigger all our questions
4651 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
4652 if (ActiveQuestion(q
))
4654 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
4655 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4656 q
->RecentAnswers
= 0;
4657 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
4658 m
->NextScheduledQuery
= m
->timenow
;
4661 // 2. Re-validate our cache records
4662 m
->NextCacheCheck
= m
->timenow
;
4663 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4664 for (cr
= m
->rrcache_hash
[slot
]; cr
; cr
=cr
->next
)
4665 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForCableDisconnect
);
4667 // 3. Retrigger probing and announcing for all our authoritative records
4668 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4670 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
4671 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
4672 if (rr
->AnnounceCount
< ReannounceCount
)
4673 rr
->AnnounceCount
= ReannounceCount
;
4674 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
4675 InitializeLastAPTime(m
, rr
);
4683 // ***************************************************************************
4684 #if COMPILER_LIKES_PRAGMA_MARK
4686 #pragma mark - Packet Reception Functions
4689 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
4691 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
4694 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
4695 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
4696 // The referenced record will definitely be acceptable (by recursive application of this rule)
4697 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
4698 rr
->NR_AdditionalTo
= add
;
4699 *nrpp
= &rr
->NextResponse
;
4701 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4704 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
4706 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
4707 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
4709 mDNSu8
*responseptr
= response
->data
;
4710 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
4711 const mDNSu8
*ptr
= query
->data
;
4713 mDNSu32 maxttl
= 0x70000000;
4716 // Initialize the response fields so we can answer the questions
4717 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
4720 // *** 1. Write out the list of questions we are actually going to answer with this packet
4725 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4728 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
4729 if (!ptr
) return(mDNSNULL
);
4731 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
4733 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
4734 { // then put the question in the question section
4735 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
4736 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
4737 break; // break out of the ResponseRecords loop, and go on to the next question
4742 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
4746 // *** 2. Write Answers
4748 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4749 if (rr
->NR_AnswerTo
)
4751 mDNSu8
*p
= PutResourceRecordCappedTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
, maxttl
);
4752 if (p
) responseptr
= p
;
4753 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
4757 // *** 3. Write Additionals
4759 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4760 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
4762 mDNSu8
*p
= PutResourceRecordCappedTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
, maxttl
);
4763 if (p
) responseptr
= p
;
4764 else debugf("GenerateUnicastResponse: No more space for additionals");
4767 return(responseptr
);
4770 // AuthRecord *our is our Resource Record
4771 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
4772 // Returns 0 if there is no conflict
4773 // Returns +1 if there was a conflict and we won
4774 // Returns -1 if there was a conflict and we lost and have to rename
4775 mDNSlocal
int CompareRData(AuthRecord
*our
, CacheRecord
*pkt
)
4777 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
4778 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
4779 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
4780 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
4782 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
4783 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
4784 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
4785 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
4787 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
4788 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
4789 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
4790 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
4792 debugf("CompareRData: How did we get here?");
4796 // See if we have an authoritative record that's identical to this packet record,
4797 // whose canonical DependentOn record is the specified master record.
4798 // The DependentOn pointer is typically used for the TXT record of service registrations
4799 // It indicates that there is no inherent conflict detection for the TXT record
4800 // -- it depends on the SRV record to resolve name conflicts
4801 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
4802 // pointer chain (if any) to make sure we reach the canonical DependentOn record
4803 // If the record has no DependentOn, then just return that record's pointer
4804 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4805 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
4807 const AuthRecord
*r1
;
4808 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
4810 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4812 const AuthRecord
*r2
= r1
;
4813 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4814 if (r2
== master
) return(mDNStrue
);
4817 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
4819 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4821 const AuthRecord
*r2
= r1
;
4822 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4823 if (r2
== master
) return(mDNStrue
);
4829 // Find the canonical RRSet pointer for this RR received in a packet.
4830 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
4831 // pointers (if any) to make sure we return the canonical member of this name/type/class
4832 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4833 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
4835 const AuthRecord
*rr
;
4836 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4838 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
4840 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
4847 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
4848 // as one of our records (our) but different rdata.
4849 // 1. If our record is not a type that's supposed to be unique, we don't care.
4850 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
4851 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
4852 // points to our record, ignore this conflict (e.g. the packet record matches one of our
4853 // TXT records, and that record is marked as dependent on 'our', its SRV record).
4854 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
4855 // are members of the same RRSet, then this is not a conflict.
4856 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
4858 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
4860 // If not supposed to be unique, not a conflict
4861 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
4863 // If a dependent record, not a conflict
4864 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
4866 // If the pktrr matches a member of ourset, not a conflict
4867 if (FindRRSet(m
, pktrr
) == ourset
) return(mDNSfalse
);
4869 // Okay, this is a conflict
4873 // NOTE: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
4874 // the record list and/or question list.
4875 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4876 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4877 DNSQuestion
*q
, AuthRecord
*our
)
4880 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
4881 mDNSBool FoundUpdate
= mDNSfalse
;
4883 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
4885 LargeCacheRecord pkt
;
4886 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, 0, &pkt
);
4888 if (ResourceRecordAnswersQuestion(&pkt
.r
.resrec
, q
))
4890 FoundUpdate
= mDNStrue
;
4891 if (PacketRRConflict(m
, our
, &pkt
.r
))
4893 int result
= (int)our
->resrec
.rrclass
- (int)pkt
.r
.resrec
.rrclass
;
4894 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)pkt
.r
.resrec
.rrtype
;
4895 if (!result
) result
= CompareRData(our
, &pkt
.r
);
4898 case 1: debugf("ResolveSimultaneousProbe: %##s (%s): We won", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4901 case -1: debugf("ResolveSimultaneousProbe: %##s (%s): We lost", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4902 mDNS_Deregister_internal(m
, our
, mDNS_Dereg_conflict
);
4909 debugf("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4912 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, ResourceRecord
*pktrr
)
4915 for (rr
= m
->rrcache_hash
[HashSlot(&pktrr
->name
)]; rr
; rr
=rr
->next
)
4916 if (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
&& IdenticalResourceRecord(pktrr
, &rr
->resrec
)) break;
4920 // ProcessQuery examines a received query to see if we have any answers to give
4921 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4922 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
4923 DNSMessage
*const response
)
4925 AuthRecord
*ResponseRecords
= mDNSNULL
;
4926 AuthRecord
**nrp
= &ResponseRecords
;
4927 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
4928 CacheRecord
**eap
= &ExpectedAnswers
;
4929 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
4930 DNSQuestion
**dqp
= &DupQuestions
;
4931 mDNSBool delayresponse
= mDNSfalse
;
4932 mDNSBool HaveUnicastAnswer
= mDNSfalse
;
4933 const mDNSu8
*ptr
= query
->data
;
4934 mDNSu8
*responseptr
= mDNSNULL
;
4935 AuthRecord
*rr
, *rr2
;
4938 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet.
4939 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNStrue
;
4942 // *** 1. Parse Question Section and mark potential answers
4944 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4946 mDNSBool QuestionNeedsMulticastResponse
;
4947 int NumAnswersForThisQuestion
= 0;
4948 DNSQuestion pktq
, *q
;
4949 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
4950 if (!ptr
) goto exit
;
4952 // The only queries that *need* a multicast response are:
4953 // * Queries sent via multicast
4955 // * that don't have the kDNSQClass_UnicastResponse bit set
4956 // These queries need multicast responses because other clients will:
4957 // * suppress their own identical questions when they see these questions, and
4958 // * expire their cache records if they don't see the expected responses
4959 // For other queries, we may still choose to send the occasional multicast response anyway,
4960 // to keep our neighbours caches warm, and for ongoing conflict detection.
4961 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
4962 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
4963 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
4965 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
4966 // can result in user callbacks which may change the record list and/or question list.
4967 // Also note: we just mark potential answer records here, without trying to build the
4968 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
4969 // from that list while we're in the middle of trying to build it.
4970 if (m
->CurrentRecord
) LogMsg("ProcessQuery ERROR m->CurrentRecord already set");
4971 m
->CurrentRecord
= m
->ResourceRecords
;
4972 while (m
->CurrentRecord
)
4974 rr
= m
->CurrentRecord
;
4975 m
->CurrentRecord
= rr
->next
;
4976 if (ResourceRecordAnswersQuestion(&rr
->resrec
, &pktq
))
4978 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
4979 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
4980 else if (ResourceRecordIsValidAnswer(rr
))
4982 NumAnswersForThisQuestion
++;
4984 // NR_AnswerTo pointing into query packet means "answer via unicast"
4985 // (may also choose to do multicast as well)
4986 // NR_AnswerTo == ~0 means "definitely answer via multicast" (can't downgrade to unicast later)
4987 if (QuestionNeedsMulticastResponse
)
4989 // We only mark this question for sending if it is at least one second since the last time we multicast it
4990 // on this interface. If it is more than a second, or LastMCInterface is different, then we should multicast it.
4991 // This is to guard against the case where someone blasts us with queries as fast as they can.
4992 if (m
->timenow
- (rr
->LastMCTime
+ mDNSPlatformOneSecond
) >= 0 ||
4993 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
4994 rr
->NR_AnswerTo
= (mDNSu8
*)~0;
4996 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= ptr
;
5001 // We only do the following accelerated cache expiration processing and duplicate question suppression processing
5002 // for multicast queries with multicast responses.
5003 // For any query generating a unicast response we don't do this because we can't assume we will see the response
5004 if (QuestionNeedsMulticastResponse
)
5007 // If we couldn't answer this question, someone else might be able to,
5008 // so use random delay on response to reduce collisions
5009 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNStrue
;
5011 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5012 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5013 for (rr
= m
->rrcache_hash
[HashSlot(&pktq
.qname
)]; rr
; rr
=rr
->next
)
5014 if (ResourceRecordAnswersQuestion(&rr
->resrec
, &pktq
) && rr
->resrec
.rdlength
<= SmallRecordLimit
)
5015 if (!rr
->NextInKAList
&& eap
!= &rr
->NextInKAList
)
5018 eap
= &rr
->NextInKAList
;
5019 if (rr
->MPUnansweredQ
== 0 || m
->timenow
- rr
->MPLastUnansweredQT
>= mDNSPlatformOneSecond
)
5021 // Although MPUnansweredQ is only really used for multi-packet query processing,
5022 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5023 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5024 rr
->MPUnansweredQ
++;
5025 rr
->MPLastUnansweredQT
= m
->timenow
;
5026 rr
->MPExpectingKA
= mDNStrue
;
5030 // Check if this question is the same as any of mine.
5031 // We only do this for non-truncated queries. Right now it would be too complicated to try
5032 // to keep track of duplicate suppression state between multiple packets, especially when we
5033 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5034 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5035 for (q
= m
->Questions
; q
; q
=q
->next
)
5036 if (ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
5037 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
5038 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
5039 if (q
->qtype
== pktq
.qtype
&& q
->qclass
== pktq
.qclass
&& q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
5040 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
5045 // *** 2. Now we can safely build the list of marked answers
5047 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
5048 if (rr
->NR_AnswerTo
) // If we marked the record...
5050 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
5051 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNStrue
;
5055 // *** 3. Add additional records
5057 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
5059 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
5060 // later in the "for" loop, and we will follow further "additional" links then.)
5061 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
5062 AddRecordToResponseList(&nrp
, rr
->Additional1
, rr
);
5064 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
5065 AddRecordToResponseList(&nrp
, rr
->Additional2
, rr
);
5067 // For SRV records, automatically add the Address record(s) for the target host
5068 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
5069 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
5070 if (RRIsAddressType(rr2
) && // For all address records (A/AAAA) ...
5071 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
5072 rr
->resrec
.rdnamehash
== rr2
->resrec
.namehash
&&
5073 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, &rr2
->resrec
.name
)) // ... whose name is the name of the SRV target
5074 AddRecordToResponseList(&nrp
, rr2
, rr
);
5078 // *** 4. Parse Answer Section and cancel any records disallowed by Known-Answer list
5080 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
5082 // Get the record...
5083 LargeCacheRecord pkt
;
5085 CacheRecord
*ourcacherr
;
5086 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &pkt
);
5087 if (!ptr
) goto exit
;
5089 // See if this Known-Answer suppresses any of our currently planned answers
5090 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5091 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&pkt
.r
, rr
))
5092 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5094 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5095 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
5097 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5098 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&pkt
.r
, rr
))
5100 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5102 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zeroIPAddr
;
5104 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5106 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
5108 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->ImmedAnswer
= mDNSNULL
;
5112 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5113 // even if the TC bit is not set (the TC bit will *not* be set in the *last* packet of a multi-packet KA list).
5114 ourcacherr
= FindIdenticalRecordInCache(m
, &pkt
.r
.resrec
);
5115 if (ourcacherr
&& ourcacherr
->MPExpectingKA
&& m
->timenow
- ourcacherr
->MPLastUnansweredQT
< mDNSPlatformOneSecond
)
5117 ourcacherr
->MPUnansweredKA
++;
5118 ourcacherr
->MPExpectingKA
= mDNSfalse
;
5121 // Having built our ExpectedAnswers list from the questions in this packet, we can definitively
5122 // remove from our ExpectedAnswers list any records that are suppressed in the very same packet.
5123 // For answers that are suppressed in subsequent KA list packets, we rely on the MPQ/MPKA counting to track them.
5124 eap
= &ExpectedAnswers
;
5127 CacheRecord
*rr
= *eap
;
5128 if (rr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&pkt
.r
.resrec
, &rr
->resrec
))
5129 { *eap
= rr
->NextInKAList
; rr
->NextInKAList
= mDNSNULL
; }
5130 else eap
= &rr
->NextInKAList
;
5133 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5136 dqp
= &DupQuestions
;
5139 DNSQuestion
*q
= *dqp
;
5140 if (ResourceRecordAnswersQuestion(&pkt
.r
.resrec
, q
))
5141 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
5142 else dqp
= &q
->NextInDQList
;
5148 // *** 5. Cancel any additionals that were added because of now-deleted records
5150 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5151 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
5152 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5155 // *** 6. Mark the send flags on the records we plan to send
5157 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5159 if (rr
->NR_AnswerTo
)
5161 mDNSBool SendMulticastResponse
= mDNSfalse
;
5163 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
5164 if (m
->timenow
- (rr
->LastMCTime
+ TicksTTL(rr
)/4) >= 0) SendMulticastResponse
= mDNStrue
;
5166 // If the client insists on a multicast response, then we'd better send one
5167 if (rr
->NR_AnswerTo
== (mDNSu8
*)~0) SendMulticastResponse
= mDNStrue
;
5168 else if (rr
->NR_AnswerTo
) HaveUnicastAnswer
= mDNStrue
;
5170 if (SendMulticastResponse
)
5172 // If we're already planning to send this on another interface, just send it on all interfaces
5173 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
5175 rr
->ImmedAnswer
= mDNSInterfaceMark
;
5176 m
->NextScheduledResponse
= m
->timenow
;
5177 debugf("ProcessQuery: %##s (%s) : Will send on all interfaces", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5181 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
5182 m
->NextScheduledResponse
= m
->timenow
;
5183 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5185 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
5186 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
5188 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5190 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
5191 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
5196 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== (mDNSu8
*)~0)
5198 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
5199 // If two clients on different interfaces do queries that invoke the same optional additional answer,
5200 // then the earlier client is out of luck
5201 rr
->ImmedAdditional
= InterfaceID
;
5202 // No need to set m->NextScheduledResponse here
5203 // We'll send these additional records when we send them, or not, as the case may be
5208 // *** 7. If we think other machines are likely to answer these questions, set our packet suppression timer
5210 if (delayresponse
&& !m
->SuppressSending
)
5212 // Pick a random delay between 20ms and 120ms.
5213 m
->SuppressSending
= m
->timenow
+ (mDNSPlatformOneSecond
*2 + (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*10)) / 100;
5214 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
5218 // *** 8. If query is from a legacy client, generate a unicast response too
5220 if (HaveUnicastAnswer
)
5221 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
5225 // *** 9. Finally, clear our link chains ready for use next time
5227 while (ResponseRecords
)
5229 rr
= ResponseRecords
;
5230 ResponseRecords
= rr
->NextResponse
;
5231 rr
->NextResponse
= mDNSNULL
;
5232 rr
->NR_AnswerTo
= mDNSNULL
;
5233 rr
->NR_AdditionalTo
= mDNSNULL
;
5236 while (ExpectedAnswers
)
5239 rr
= ExpectedAnswers
;
5240 ExpectedAnswers
= rr
->NextInKAList
;
5241 rr
->NextInKAList
= mDNSNULL
;
5243 // For non-truncated queries, we can definitively say that we should expect
5244 // to be seeing a response for any records still left in the ExpectedAnswers list
5245 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5246 if (rr
->UnansweredQueries
== 0 || m
->timenow
- rr
->LastUnansweredTime
>= mDNSPlatformOneSecond
)
5248 rr
->UnansweredQueries
++;
5249 rr
->LastUnansweredTime
= m
->timenow
;
5250 if (rr
->UnansweredQueries
> 1)
5251 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
5252 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5253 SetNextCacheCheckTime(m
, rr
);
5256 // If we've seen multiple unanswered queries for this record,
5257 // then mark it to expire in five seconds if we don't get a response by then.
5258 if (rr
->UnansweredQueries
>= MaxUnansweredQueries
)
5260 // Only show debugging message if this record was not about to expire anyway
5261 if (RRExpireTime(rr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5262 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5263 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5264 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
5266 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
5267 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
5268 // possible packet loss of up to 20% of the additional KA packets.)
5269 else if (rr
->MPUnansweredQ
* 4 > rr
->MPUnansweredKA
* 5 + 8)
5271 // We want to do this conservatively.
5272 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
5273 // then we don't want them to all hit the network simultaneously with their final expiration queries.
5274 // By setting the record to expire in four minutes, we achieve two things:
5275 // (a) the 90-95% final expiration queries will be less bunched together
5276 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
5277 mDNSu32 remain
= (mDNSu32
)(RRExpireTime(rr
) - m
->timenow
) / 4;
5278 if (remain
> 240 * (mDNSu32
)mDNSPlatformOneSecond
)
5279 remain
= 240 * (mDNSu32
)mDNSPlatformOneSecond
;
5281 // Only show debugging message if this record was not about to expire anyway
5282 if (RRExpireTime(rr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5283 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5284 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5286 if (remain
<= 60 * (mDNSu32
)mDNSPlatformOneSecond
)
5287 rr
->UnansweredQueries
++; // Treat this as equivalent to one definite unanswered query
5288 rr
->MPUnansweredQ
= 0; // Clear MPQ/MPKA statistics
5289 rr
->MPUnansweredKA
= 0;
5290 rr
->MPExpectingKA
= mDNSfalse
;
5292 if (remain
< kDefaultReconfirmTimeForNoAnswer
)
5293 remain
= kDefaultReconfirmTimeForNoAnswer
;
5294 mDNS_Reconfirm_internal(m
, rr
, remain
);
5298 while (DupQuestions
)
5301 DNSQuestion
*q
= DupQuestions
;
5302 DupQuestions
= q
->NextInDQList
;
5303 q
->NextInDQList
= mDNSNULL
;
5304 i
= RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
5305 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
5306 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6", i
);
5309 return(responseptr
);
5312 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
5313 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
5314 const mDNSInterfaceID InterfaceID
)
5316 DNSMessage response
;
5317 const mDNSu8
*responseend
= mDNSNULL
;
5319 verbosedebugf("Received Query from %#-15a:%d to %#-15a:%d on 0x%.8X with %2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s",
5320 srcaddr
, (mDNSu16
)srcport
.b
[0]<<8 | srcport
.b
[1],
5321 dstaddr
, (mDNSu16
)dstport
.b
[0]<<8 | dstport
.b
[1],
5323 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
5324 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
5325 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5326 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? "" : "s");
5328 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
5329 (srcport
.NotAnInteger
!= MulticastDNSPort
.NotAnInteger
), mDNSAddrIsDNSMulticast(dstaddr
), &response
);
5331 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
5333 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
5334 response
.h
.numQuestions
, response
.h
.numQuestions
== 1 ? "" : "s",
5335 response
.h
.numAnswers
, response
.h
.numAnswers
== 1 ? "" : "s",
5336 response
.h
.numAdditionals
, response
.h
.numAdditionals
== 1 ? "" : "s",
5337 srcaddr
, (mDNSu16
)srcport
.b
[0]<<8 | srcport
.b
[1], InterfaceID
, srcaddr
->type
);
5338 mDNSSendDNSMessage(m
, &response
, responseend
, InterfaceID
, dstport
, srcaddr
, srcport
);
5342 // NOTE: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
5343 // the record list and/or question list.
5344 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5345 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
5346 const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, const mDNSAddr
*dstaddr
,
5347 const mDNSInterfaceID InterfaceID
, mDNSu8 ttl
)
5350 const mDNSu8
*ptr
= LocateAnswers(response
, end
); // We ignore questions (if any) in a DNS response packet
5351 CacheRecord
*CacheFlushRecords
= mDNSNULL
;
5352 CacheRecord
**cfp
= &CacheFlushRecords
;
5354 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
5355 // to guard against spoof responses, then the only credible protection against that is cryptographic
5356 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
5357 int totalrecords
= response
->h
.numAnswers
+ response
->h
.numAuthorities
+ response
->h
.numAdditionals
;
5359 (void)srcaddr
; // Currently used only for display in debugging message
5361 verbosedebugf("Received Response from %#-15a addressed to %#-15a on %p TTL %d with %2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s",
5362 srcaddr
, dstaddr
, InterfaceID
, ttl
,
5363 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5364 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5365 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5366 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5368 // TTL should be 255
5369 // In the case of overlayed subnets that aren't using RFC 3442, some packets may incorrectly
5370 // go to the router first and then come back with a TTL of 254, so we allow that too.
5371 // Anything lower than 254 is a pretty good sign of an off-net spoofing attack.
5372 // Also, if we get a unicast response when we weren't expecting one, then we assume it is someone trying to spoof us
5373 if (ttl
< 254 || (!mDNSAddrIsDNSMulticast(dstaddr
) && (mDNSu32
)(m
->timenow
- m
->ExpectUnicastResponse
) > (mDNSu32
)mDNSPlatformOneSecond
))
5375 debugf("** Ignored apparent spoof mDNS Response from %#-15a to %#-15a TTL %d on %p with %2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s",
5376 srcaddr
, dstaddr
, ttl
, InterfaceID
,
5377 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5378 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5379 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5380 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5384 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
5386 LargeCacheRecord pkt
;
5387 const mDNSu8 RecordType
= (mDNSu8
)((i
< response
->h
.numAnswers
) ? kDNSRecordTypePacketAns
: kDNSRecordTypePacketAdd
);
5388 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &pkt
);
5389 if (!ptr
) break; // Break out of the loop and clean up our CacheFlushRecords list before exiting
5391 // 1. Check that this packet resource record does not conflict with any of ours
5392 if (m
->CurrentRecord
) LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set");
5393 m
->CurrentRecord
= m
->ResourceRecords
;
5394 while (m
->CurrentRecord
)
5396 AuthRecord
*rr
= m
->CurrentRecord
;
5397 m
->CurrentRecord
= rr
->next
;
5398 if (PacketRRMatchesSignature(&pkt
.r
, rr
)) // If interface, name, type (if verified) and class match...
5400 // ... check to see if rdata is identical
5401 if (SameRData(&pkt
.r
.resrec
, &rr
->resrec
))
5403 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
5404 if (pkt
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
5406 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
5407 if (rr
->ImmedAnswer
== InterfaceID
) rr
->ImmedAnswer
= mDNSNULL
;
5411 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
5412 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5417 // else, the packet RR has different rdata -- check to see if this is a conflict
5418 if (pkt
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &pkt
.r
))
5420 debugf("mDNSCoreReceiveResponse: Our Record: %08X %08X %s", rr
-> resrec
.rdatahash
, rr
-> resrec
.rdnamehash
, GetRRDisplayString(m
, rr
));
5421 debugf("mDNSCoreReceiveResponse: Pkt Record: %08X %08X %s", pkt
.r
.resrec
.rdatahash
, pkt
.r
.resrec
.rdnamehash
, GetRRDisplayString(m
, &pkt
.r
));
5423 // If this record is marked DependentOn another record for conflict detection purposes,
5424 // then *that* record has to be bumped back to probing state to resolve the conflict
5425 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
5427 // If we've just whacked this record's ProbeCount, don't need to do it again
5428 if (rr
->ProbeCount
<= DefaultProbeCountForTypeUnique
)
5430 // If we'd previously verified this record, put it back to probing state and try again
5431 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
5433 debugf("mDNSCoreReceiveResponse: Reseting to Probing: %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5434 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5435 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
5436 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(kDNSRecordTypeUnique
);
5437 InitializeLastAPTime(m
, rr
);
5438 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
5440 // If we're probing for this record, we just failed
5441 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
5443 debugf("mDNSCoreReceiveResponse: Will rename %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5444 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5446 // We assumed this record must be unique, but we were wrong.
5447 // (e.g. There are two mDNSResponders on the same machine giving
5448 // different answers for the reverse mapping record.)
5449 // This is simply a misconfiguration, and we don't try to recover from it.
5450 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
5452 debugf("mDNSCoreReceiveResponse: Unexpected conflict on %##s (%s) -- discarding our record",
5453 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5454 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5457 debugf("mDNSCoreReceiveResponse: Unexpected record type %X %##s (%s)",
5458 rr
->resrec
.RecordType
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5461 // Else, matching signature, different rdata, but not a considered a conflict.
5462 // If the packet record has the cache-flush bit set, then we check to see if we have to re-assert our record(s)
5463 // to rescue them (see note about "multi-homing and bridged networks" at the end of this function).
5464 else if ((pkt
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && m
->timenow
- rr
->LastMCTime
> mDNSPlatformOneSecond
/2)
5465 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5470 // 2. See if we want to add this packet resource record to our cache
5471 if (m
->rrcache_size
) // Only try to cache answers if we have a cache to put them in
5473 mDNSu32 slot
= HashSlot(&pkt
.r
.resrec
.name
);
5475 // 2a. Check if this packet resource record is already in our cache
5476 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
5478 // If we found this exact resource record, refresh its TTL
5479 if (rr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&pkt
.r
.resrec
, &rr
->resrec
))
5481 if (pkt
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5482 verbosedebugf("Found record size %5d interface %p already in cache: %s",
5483 pkt
.r
.resrec
.rdlength
, InterfaceID
, GetRRDisplayString(m
, &pkt
.r
));
5484 rr
->TimeRcvd
= m
->timenow
;
5486 if (pkt
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
5488 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
5489 if (rr
->NextInCFList
== mDNSNULL
&& cfp
!= &rr
->NextInCFList
)
5490 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; }
5492 // If this packet record is marked unique, and our previous cached copy was not, then fix it
5493 if (!(rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
5496 for (q
= m
->Questions
; q
; q
=q
->next
) if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) q
->UniqueAnswers
++;
5497 rr
->resrec
.RecordType
= pkt
.r
.resrec
.RecordType
;
5501 if (pkt
.r
.resrec
.rroriginalttl
> 0)
5503 rr
->resrec
.rroriginalttl
= pkt
.r
.resrec
.rroriginalttl
;
5504 rr
->UnansweredQueries
= 0;
5505 rr
->MPUnansweredQ
= 0;
5506 rr
->MPUnansweredKA
= 0;
5507 rr
->MPExpectingKA
= mDNSfalse
;
5511 // If the packet TTL is zero, that means we're deleting this record.
5512 // To give other hosts on the network a chance to protest, we push the deletion
5513 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
5514 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
5515 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
5516 rr
->resrec
.rroriginalttl
= 1;
5517 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5519 SetNextCacheCheckTime(m
, rr
);
5524 // If packet resource record not in our cache, add it now
5525 // (unless it is just a deletion of a record we never had, in which case we don't care)
5526 if (!rr
&& pkt
.r
.resrec
.rroriginalttl
> 0)
5528 rr
= GetFreeCacheRR(m
, pkt
.r
.resrec
.rdlength
);
5529 if (!rr
) debugf("No cache space to add record for %#s", pkt
.r
.resrec
.name
.c
);
5532 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
5534 rr
->resrec
.rdata
= saveptr
; // and then restore it after the structure assignment
5535 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
5536 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; }
5537 // If this is an oversized record with external storage allocated, copy rdata to external storage
5538 if (pkt
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5539 mDNSPlatformMemCopy(pkt
.r
.resrec
.rdata
, rr
->resrec
.rdata
, sizeofRDataHeader
+ pkt
.r
.resrec
.rdlength
);
5540 rr
->next
= m
->rrcache_hash
[slot
];
5541 m
->rrcache_hash
[slot
] = rr
;
5542 m
->rrcache_used
[slot
]++;
5543 //debugf("Adding RR %##s to cache (%d)", pkt.r.name.c, m->rrcache_used);
5544 CacheRecordAdd(m
, rr
);
5545 // MUST do this AFTER CacheRecordAdd(), because that's what sets CRActiveQuestion for us
5546 SetNextCacheCheckTime(m
, rr
);
5552 // If we've just received one or more records with their cache flush bits set,
5553 // then scan that cache slot to see if there are any old stale records we need to flush
5554 while (CacheFlushRecords
)
5556 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
5557 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
5558 r1
->NextInCFList
= mDNSNULL
;
5559 for (r2
= m
->rrcache_hash
[HashSlot(&r1
->resrec
.name
)]; r2
; r2
=r2
->next
)
5560 if (SameResourceRecordSignature(&r1
->resrec
, &r2
->resrec
) && m
->timenow
- r2
->TimeRcvd
> mDNSPlatformOneSecond
)
5562 verbosedebugf("Cache flush %p X %p %##s (%s)", r1
, r2
, r2
->resrec
.name
.c
, DNSTypeName(r2
->resrec
.rrtype
));
5563 // We set stale records to expire in one second.
5564 // This gives the owner a chance to rescue it if necessary.
5565 // This is important in the case of multi-homing and bridged networks:
5566 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
5567 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
5568 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
5569 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
5570 // By delaying the deletion by one second, we give X a change to notice that this bridging has
5571 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
5572 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
5573 // final expiration queries for this record.
5574 r2
->resrec
.rroriginalttl
= 1;
5575 r2
->TimeRcvd
= m
->timenow
;
5576 r2
->UnansweredQueries
= MaxUnansweredQueries
;
5577 SetNextCacheCheckTime(m
, r2
);
5582 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
5583 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*const dstaddr
, const mDNSIPPort dstport
,
5584 const mDNSInterfaceID InterfaceID
, mDNSu8 ttl
)
5586 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
5587 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
5588 const mDNSu8 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
5590 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
5591 mDNSu8
*ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
5592 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
5593 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
5594 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
5595 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
5597 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
5599 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
5600 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
5601 if (!mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
5604 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
5605 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, dstaddr
, InterfaceID
, ttl
);
5606 else debugf("Unknown DNS packet type %02X%02X (ignored)", msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1]);
5608 // Packet reception often causes a change to the task list:
5609 // 1. Inbound queries can cause us to need to send responses
5610 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
5611 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
5612 // 4. Response packets that answer questions may cause our client to issue new questions
5616 // ***************************************************************************
5617 #if COMPILER_LIKES_PRAGMA_MARK
5620 #pragma mark - Searcher Functions
5623 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
5626 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
5627 // This prevents circular references, where two questions are each marked as a duplicate of the other.
5628 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
5629 // further in the list.
5630 for (q
= m
->Questions
; q
&& q
!= question
; q
=q
->next
) // Scan our list of questions
5631 if (q
->InterfaceID
== question
->InterfaceID
&& // for another question with the same InterfaceID,
5632 q
->qtype
== question
->qtype
&& // type,
5633 q
->qclass
== question
->qclass
&& // class,
5634 q
->qnamehash
== question
->qnamehash
&&
5635 SameDomainName(&q
->qname
, &question
->qname
)) // and name
5640 // This is called after a question is deleted, in case other identical questions were being
5641 // suppressed as duplicates
5642 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, const DNSQuestion
*const question
)
5645 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5646 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
5648 q
->ThisQInterval
= question
->ThisQInterval
;
5649 q
->LastQTime
= question
->LastQTime
;
5650 q
->RecentAnswers
= 0;
5651 q
->DuplicateOf
= FindDuplicateQuestion(m
, q
);
5652 q
->LastQTxTime
= question
->LastQTxTime
;
5653 SetNextQueryTime(m
,q
);
5657 mDNSlocal mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
5659 #if TEST_LOCALONLY_FOR_EVERYTHING
5660 question
->InterfaceID
= (mDNSInterfaceID
)~0;
5662 if (m
->rrcache_size
== 0) // Can't do queries if we have no cache space allocated
5663 return(mStatus_NoCache
);
5667 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
5668 DNSQuestion
**q
= &m
->Questions
;
5669 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0)) q
= &m
->LocalOnlyQuestions
;
5670 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
5674 LogMsg("Error! Tried to add a question %##s (%s) that's already in the active list",
5675 question
->qname
.c
, DNSTypeName(question
->qtype
));
5676 return(mStatus_AlreadyRegistered
);
5679 // If this question is referencing a specific interface, make sure it exists
5680 if (question
->InterfaceID
&& question
->InterfaceID
!= ((mDNSInterfaceID
)~0))
5682 NetworkInterfaceInfo
*intf
;
5683 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
5684 if (intf
->InterfaceID
== question
->InterfaceID
) break;
5687 debugf("mDNS_StartQuery_internal: Question %##s InterfaceID %p not found", question
->qname
.c
, question
->InterfaceID
);
5688 return(mStatus_BadReferenceErr
);
5692 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
5693 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
5694 // be a waste. For that reason, we schedule our first query to go out in half a second. If AnswerNewQuestion() finds
5695 // that we have *no* relevant answers currently in our cache, then it will accelerate that to go out immediately.
5696 if (!ValidateDomainName(&question
->qname
))
5698 LogMsg("Attempt to start query with invalid qname %##s %s", question
->qname
.c
, DNSTypeName(question
->qtype
));
5699 return(mStatus_Invalid
);
5702 if (!m
->RandomQueryDelay
) m
->RandomQueryDelay
= 1 + (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
5704 question
->next
= mDNSNULL
;
5705 question
->qnamehash
= DomainNameHashValue(&question
->qname
); // MUST do this before FindDuplicateQuestion()
5706 question
->ThisQInterval
= InitialQuestionInterval
* 2; // MUST be > zero for an active question
5707 question
->LastQTime
= m
->timenow
- m
->RandomQueryDelay
; // Avoid inter-machine synchronization
5708 question
->RecentAnswers
= 0;
5709 question
->CurrentAnswers
= 0;
5710 question
->LargeAnswers
= 0;
5711 question
->UniqueAnswers
= 0;
5712 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
5713 question
->NextInDQList
= mDNSNULL
;
5714 for (i
=0; i
<DupSuppressInfoSize
; i
++)
5715 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
5716 // question->InterfaceID must be already set by caller
5717 question
->SendQNow
= mDNSNULL
;
5718 question
->SendOnAll
= mDNSfalse
;
5719 question
->LastQTxTime
= m
->timenow
;
5721 if (!question
->DuplicateOf
)
5722 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) started",
5723 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, question
);
5725 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) duplicate of (%p)",
5726 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, question
, question
->DuplicateOf
);
5729 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0))
5731 if (!m
->NewLocalOnlyQuestions
) m
->NewLocalOnlyQuestions
= question
;
5735 if (!m
->NewQuestions
) m
->NewQuestions
= question
;
5736 SetNextQueryTime(m
,question
);
5739 return(mStatus_NoError
);
5743 mDNSlocal mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
5746 DNSQuestion
**q
= &m
->Questions
;
5747 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0)) q
= &m
->LocalOnlyQuestions
;
5748 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
5749 if (*q
) *q
= (*q
)->next
;
5752 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
5753 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
5754 question
->qname
.c
, DNSTypeName(question
->qtype
));
5755 return(mStatus_BadReferenceErr
);
5758 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
5759 UpdateQuestionDuplicates(m
, question
);
5760 // But don't trash ThisQInterval until afterwards.
5761 question
->ThisQInterval
= -1;
5763 // If there are any cache records referencing this as their active question, then see if any other
5764 // question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
5765 for (rr
= m
->rrcache_hash
[HashSlot(&question
->qname
)]; rr
; rr
=rr
->next
)
5767 if (rr
->CRActiveQuestion
== question
)
5770 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5771 if (ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
5773 verbosedebugf("mDNS_StopQuery_internal: Cache RR %##s (%s) setting CRActiveQuestion to %X", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), q
);
5774 rr
->CRActiveQuestion
= q
; // Question used to be active; new value may or may not be null
5775 if (!q
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
5779 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv()is about to look at,
5780 // bump its pointer forward one question.
5781 if (m
->CurrentQuestion
== question
)
5783 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
5784 question
->qname
.c
, DNSTypeName(question
->qtype
));
5785 m
->CurrentQuestion
= question
->next
;
5788 if (m
->NewQuestions
== question
)
5790 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
5791 question
->qname
.c
, DNSTypeName(question
->qtype
));
5792 m
->NewQuestions
= question
->next
;
5795 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
5797 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
5798 question
->next
= mDNSNULL
;
5799 return(mStatus_NoError
);
5802 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
5806 status
= mDNS_StartQuery_internal(m
, question
);
5811 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
5815 status
= mDNS_StopQuery_internal(m
, question
);
5820 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const rr
)
5824 status
= mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
5829 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
5831 mStatus status
= mStatus_BadReferenceErr
;
5834 cr
= FindIdenticalRecordInCache(m
, rr
);
5835 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
5840 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
5841 const domainname
*const srv
, const domainname
*const domain
,
5842 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
5844 question
->ThisQInterval
= -1; // Indicate that query is not yet active
5845 question
->InterfaceID
= InterfaceID
;
5846 question
->qtype
= kDNSType_PTR
;
5847 question
->qclass
= kDNSClass_IN
;
5848 question
->QuestionCallback
= Callback
;
5849 question
->QuestionContext
= Context
;
5850 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
)) return(mStatus_BadParamErr
);
5851 return(mDNS_StartQuery(m
, question
));
5854 mDNSlocal
void FoundServiceInfoSRV(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5856 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5857 mDNSBool PortChanged
= (mDNSBool
)(query
->info
->port
.NotAnInteger
!= answer
->rdata
->u
.srv
.port
.NotAnInteger
);
5858 if (!AddRecord
) return;
5859 if (answer
->rrtype
!= kDNSType_SRV
) return;
5861 query
->info
->port
= answer
->rdata
->u
.srv
.port
;
5863 // If this is our first answer, then set the GotSRV flag and start the address query
5866 query
->GotSRV
= mDNStrue
;
5867 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
5868 AssignDomainName(query
->qAv4
.qname
, answer
->rdata
->u
.srv
.target
);
5869 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
5870 AssignDomainName(query
->qAv6
.qname
, answer
->rdata
->u
.srv
.target
);
5871 mDNS_StartQuery_internal(m
, &query
->qAv4
);
5872 mDNS_StartQuery_internal(m
, &query
->qAv6
);
5874 // If this is not our first answer, only re-issue the address query if the target host name has changed
5875 else if ((query
->qAv4
.InterfaceID
!= query
->qSRV
.InterfaceID
&& query
->qAv4
.InterfaceID
!= answer
->InterfaceID
) ||
5876 !SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
))
5878 mDNS_StopQuery_internal(m
, &query
->qAv4
);
5879 mDNS_StopQuery_internal(m
, &query
->qAv6
);
5880 if (SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
) && !PortChanged
)
5882 // If we get here, it means:
5883 // 1. This is not our first SRV answer
5884 // 2. The interface ID is different, but the target host and port are the same
5885 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
5886 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
5887 query
->qAv4
.InterfaceID
= query
->qSRV
.InterfaceID
; // Will be mDNSInterface_Any, or a specific interface
5888 query
->qAv6
.InterfaceID
= query
->qSRV
.InterfaceID
;
5892 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
5893 AssignDomainName(query
->qAv4
.qname
, answer
->rdata
->u
.srv
.target
);
5894 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
5895 AssignDomainName(query
->qAv6
.qname
, answer
->rdata
->u
.srv
.target
);
5897 debugf("FoundServiceInfoSRV: Restarting address queries for %##s", query
->qAv4
.qname
.c
);
5898 mDNS_StartQuery_internal(m
, &query
->qAv4
);
5899 mDNS_StartQuery_internal(m
, &query
->qAv6
);
5901 else if (query
->ServiceInfoQueryCallback
&& query
->GotADD
&& query
->GotTXT
&& PortChanged
)
5903 if (++query
->Answers
>= 100)
5904 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
5905 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.srv
.target
.c
,
5906 ((mDNSu16
)answer
->rdata
->u
.srv
.port
.b
[0] << 8) | answer
->rdata
->u
.srv
.port
.b
[1]);
5907 query
->ServiceInfoQueryCallback(m
, query
);
5909 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5910 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5913 mDNSlocal
void FoundServiceInfoTXT(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5915 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5916 if (!AddRecord
) return;
5917 if (answer
->rrtype
!= kDNSType_TXT
) return;
5918 if (answer
->rdlength
> sizeof(query
->info
->TXTinfo
)) return;
5920 query
->GotTXT
= mDNStrue
;
5921 query
->info
->TXTlen
= answer
->rdlength
;
5922 mDNSPlatformMemCopy(answer
->rdata
->u
.txt
.c
, query
->info
->TXTinfo
, answer
->rdlength
);
5924 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query
->info
->name
.c
, query
->GotADD
);
5926 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5927 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5928 if (query
->ServiceInfoQueryCallback
&& query
->GotADD
)
5930 if (++query
->Answers
>= 100)
5931 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
5932 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.txt
.c
);
5933 query
->ServiceInfoQueryCallback(m
, query
);
5937 mDNSlocal
void FoundServiceInfo(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5939 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5940 if (!AddRecord
) return;
5942 if (answer
->rrtype
== kDNSType_A
)
5944 query
->info
->ip
.type
= mDNSAddrType_IPv4
;
5945 query
->info
->ip
.ip
.v4
= answer
->rdata
->u
.ip
;
5947 else if (answer
->rrtype
== kDNSType_AAAA
)
5949 query
->info
->ip
.type
= mDNSAddrType_IPv6
;
5950 query
->info
->ip
.ip
.v6
= answer
->rdata
->u
.ipv6
;
5954 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer
->name
.c
, answer
->rrtype
, DNSTypeName(answer
->rrtype
));
5958 query
->GotADD
= mDNStrue
;
5959 query
->info
->InterfaceID
= answer
->InterfaceID
;
5961 verbosedebugf("FoundServiceInfo v%d: %##s GotTXT=%d", query
->info
->ip
.type
, query
->info
->name
.c
, query
->GotTXT
);
5963 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5964 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5965 if (query
->ServiceInfoQueryCallback
&& query
->GotTXT
)
5967 if (++query
->Answers
>= 100)
5969 if (answer
->rrtype
== kDNSType_A
)
5970 debugf("**** WARNING **** have given %lu answers for %##s (A) %.4a", query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.ip
);
5972 debugf("**** WARNING **** have given %lu answers for %##s (AAAA) %.16a", query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.ipv6
);
5974 query
->ServiceInfoQueryCallback(m
, query
);
5978 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
5979 // If the query is not interface-specific, then InterfaceID may be zero
5980 // Each time the Callback is invoked, the remainder of the fields will have been filled in
5981 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
5982 mDNSexport mStatus
mDNS_StartResolveService(mDNS
*const m
,
5983 ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
)
5988 query
->qSRV
.ThisQInterval
= -1; // This question not yet in the question list
5989 query
->qSRV
.InterfaceID
= info
->InterfaceID
;
5990 AssignDomainName(query
->qSRV
.qname
, info
->name
);
5991 query
->qSRV
.qtype
= kDNSType_SRV
;
5992 query
->qSRV
.qclass
= kDNSClass_IN
;
5993 query
->qSRV
.QuestionCallback
= FoundServiceInfoSRV
;
5994 query
->qSRV
.QuestionContext
= query
;
5996 query
->qTXT
.ThisQInterval
= -1; // This question not yet in the question list
5997 query
->qTXT
.InterfaceID
= info
->InterfaceID
;
5998 AssignDomainName(query
->qTXT
.qname
, info
->name
);
5999 query
->qTXT
.qtype
= kDNSType_TXT
;
6000 query
->qTXT
.qclass
= kDNSClass_IN
;
6001 query
->qTXT
.QuestionCallback
= FoundServiceInfoTXT
;
6002 query
->qTXT
.QuestionContext
= query
;
6004 query
->qAv4
.ThisQInterval
= -1; // This question not yet in the question list
6005 query
->qAv4
.InterfaceID
= info
->InterfaceID
;
6006 query
->qAv4
.qname
.c
[0] = 0;
6007 query
->qAv4
.qtype
= kDNSType_A
;
6008 query
->qAv4
.qclass
= kDNSClass_IN
;
6009 query
->qAv4
.QuestionCallback
= FoundServiceInfo
;
6010 query
->qAv4
.QuestionContext
= query
;
6012 query
->qAv6
.ThisQInterval
= -1; // This question not yet in the question list
6013 query
->qAv6
.InterfaceID
= info
->InterfaceID
;
6014 query
->qAv6
.qname
.c
[0] = 0;
6015 query
->qAv6
.qtype
= kDNSType_AAAA
;
6016 query
->qAv6
.qclass
= kDNSClass_IN
;
6017 query
->qAv6
.QuestionCallback
= FoundServiceInfo
;
6018 query
->qAv6
.QuestionContext
= query
;
6020 query
->GotSRV
= mDNSfalse
;
6021 query
->GotTXT
= mDNSfalse
;
6022 query
->GotADD
= mDNSfalse
;
6026 query
->ServiceInfoQueryCallback
= Callback
;
6027 query
->ServiceInfoQueryContext
= Context
;
6029 // info->name = Must already be set up by client
6030 // info->interface = Must already be set up by client
6031 info
->ip
= zeroAddr
;
6032 info
->port
= zeroIPPort
;
6035 status
= mDNS_StartQuery_internal(m
, &query
->qSRV
);
6036 if (status
== mStatus_NoError
) status
= mDNS_StartQuery_internal(m
, &query
->qTXT
);
6037 if (status
!= mStatus_NoError
) mDNS_StopResolveService(m
, query
);
6043 mDNSexport
void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*query
)
6046 if (query
->qSRV
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qSRV
);
6047 if (query
->qTXT
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qTXT
);
6048 if (query
->qAv4
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qAv4
);
6049 if (query
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qAv6
);
6053 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
,
6054 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
6056 MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
]);
6057 question
->InterfaceID
= InterfaceID
;
6058 question
->qtype
= kDNSType_PTR
;
6059 question
->qclass
= kDNSClass_IN
;
6060 question
->QuestionCallback
= Callback
;
6061 question
->QuestionContext
= Context
;
6062 return(mDNS_StartQuery(m
, question
));
6065 // ***************************************************************************
6066 #if COMPILER_LIKES_PRAGMA_MARK
6068 #pragma mark - Responder Functions
6071 // Set up a AuthRecord with sensible default values.
6072 // These defaults may be overwritten with new values before mDNS_Register is called
6073 mDNSexport
void mDNS_SetupResourceRecord(AuthRecord
*rr
, RData
*RDataStorage
, mDNSInterfaceID InterfaceID
,
6074 mDNSu16 rrtype
, mDNSu32 ttl
, mDNSu8 RecordType
, mDNSRecordCallback Callback
, void *Context
)
6076 // Don't try to store a TTL bigger than we can represent in platform time units
6077 if (ttl
> 0x7FFFFFFFUL
/ mDNSPlatformOneSecond
)
6078 ttl
= 0x7FFFFFFFUL
/ mDNSPlatformOneSecond
;
6079 else if (ttl
== 0) // And Zero TTL is illegal
6080 ttl
= kDefaultTTLforShared
;
6082 // Field Group 1: Persistent metadata for Authoritative Records
6083 rr
->Additional1
= mDNSNULL
;
6084 rr
->Additional2
= mDNSNULL
;
6085 rr
->DependentOn
= mDNSNULL
;
6086 rr
->RRSet
= mDNSNULL
;
6087 rr
->RecordCallback
= Callback
;
6088 rr
->RecordContext
= Context
;
6090 rr
->resrec
.RecordType
= RecordType
;
6091 rr
->HostTarget
= mDNSfalse
;
6093 // Field Group 2: Transient state for Authoritative Records (set in mDNS_Register_internal)
6094 // Field Group 3: Transient state for Cache Records (set in mDNS_Register_internal)
6096 // Field Group 4: The actual information pertaining to this resource record
6097 rr
->resrec
.InterfaceID
= InterfaceID
;
6098 rr
->resrec
.name
.c
[0] = 0; // MUST be set by client
6099 rr
->resrec
.rrtype
= rrtype
;
6100 rr
->resrec
.rrclass
= kDNSClass_IN
;
6101 rr
->resrec
.rroriginalttl
= ttl
;
6102 // rr->resrec.rdlength = MUST set by client and/or in mDNS_Register_internal
6103 // rr->resrec.rdestimate = set in mDNS_Register_internal
6104 // rr->resrec.rdata = MUST be set by client
6107 rr
->resrec
.rdata
= RDataStorage
;
6110 rr
->resrec
.rdata
= &rr
->rdatastorage
;
6111 rr
->resrec
.rdata
->MaxRDLength
= sizeof(RDataBody
);
6115 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
6119 status
= mDNS_Register_internal(m
, rr
);
6124 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
6125 const mDNSu16 newrdlength
,
6126 RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
6130 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
6131 { LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(m
, &rr
->resrec
, &newrdata
->u
)); return(mStatus_Invalid
); }
6133 // If TTL is unspecified, leave TTL unchanged
6134 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
6136 // If we already have an update queued up which has not gone through yet,
6137 // give the client a chance to free that memory
6140 RData
*n
= rr
->NewRData
;
6141 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
6142 if (rr
->UpdateCallback
)
6143 rr
->UpdateCallback(m
, rr
, n
); // ...and let the client free this memory, if necessary
6146 if (rr
->AnnounceCount
< ReannounceCount
)
6147 rr
->AnnounceCount
= ReannounceCount
;
6148 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
6149 InitializeLastAPTime(m
, rr
);
6150 rr
->NewRData
= newrdata
;
6151 rr
->newrdlength
= newrdlength
;
6152 rr
->UpdateCallback
= Callback
;
6153 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
6154 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= (m
->timenow
+ mDNSPlatformOneSecond
* 60) | 1;
6155 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
6156 if (rr
->UpdateCredits
<= 5)
6158 mDNSs32 delay
= 1 << (5 - rr
->UpdateCredits
);
6159 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= (m
->timenow
+ delay
* mDNSPlatformOneSecond
) | 1;
6160 rr
->LastAPTime
= rr
->UpdateBlocked
;
6161 rr
->ThisAPInterval
*= 4;
6162 LogMsg("Excessive update rate for %##s; delaying announcement by %d seconds", rr
->resrec
.name
.c
, delay
);
6164 rr
->resrec
.rroriginalttl
= newttl
;
6166 return(mStatus_NoError
);
6169 // NOTE: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
6170 // the record list and/or question list.
6171 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6172 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
6176 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6181 mDNSlocal
void HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
6183 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
6185 NetworkInterfaceInfo
*intf
;
6186 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6187 if (intf
->Advertise
) break;
6191 mDNSlocal
void mDNS_AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6194 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
6195 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
6197 mDNS_SetupResourceRecord(&set
->RR_A
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, HostNameCallback
, set
);
6198 mDNS_SetupResourceRecord(&set
->RR_PTR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kDefaultTTLforUnique
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
6199 mDNS_SetupResourceRecord(&set
->RR_HINFO
, mDNSNULL
, set
->InterfaceID
, kDNSType_HINFO
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, mDNSNULL
, mDNSNULL
);
6201 // 1. Set up Address record to map from host name ("foo.local.") to IP address
6202 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
6203 AssignDomainName(set
->RR_A
.resrec
.name
, m
->hostname
);
6204 if (set
->ip
.type
== mDNSAddrType_IPv4
)
6206 set
->RR_A
.resrec
.rrtype
= kDNSType_A
;
6207 set
->RR_A
.resrec
.rdata
->u
.ip
= set
->ip
.ip
.v4
;
6208 // Note: This is reverse order compared to a normal dotted-decimal IP address
6209 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
6210 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
6212 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
6215 set
->RR_A
.resrec
.rrtype
= kDNSType_AAAA
;
6216 set
->RR_A
.resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
6217 for (i
= 0; i
< 16; i
++)
6219 static const char hexValues
[] = "0123456789ABCDEF";
6220 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
6221 buffer
[i
* 4 + 1] = '.';
6222 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
6223 buffer
[i
* 4 + 3] = '.';
6225 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
6228 MakeDomainNameFromDNSNameString(&set
->RR_PTR
.resrec
.name
, buffer
);
6229 set
->RR_PTR
.HostTarget
= mDNStrue
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
6231 set
->RR_A
.RRSet
= &primary
->RR_A
; // May refer to self
6233 mDNS_Register_internal(m
, &set
->RR_A
);
6234 mDNS_Register_internal(m
, &set
->RR_PTR
);
6236 if (m
->HIHardware
.c
[0] > 0 && m
->HISoftware
.c
[0] > 0 && m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0] <= 254)
6238 mDNSu8
*p
= set
->RR_HINFO
.resrec
.rdata
->u
.data
;
6239 AssignDomainName(set
->RR_HINFO
.resrec
.name
, m
->hostname
);
6240 set
->RR_HINFO
.DependentOn
= &set
->RR_A
;
6241 mDNSPlatformMemCopy(&m
->HIHardware
, p
, 1 + (mDNSu32
)m
->HIHardware
.c
[0]);
6243 mDNSPlatformMemCopy(&m
->HISoftware
, p
, 1 + (mDNSu32
)m
->HISoftware
.c
[0]);
6244 mDNS_Register_internal(m
, &set
->RR_HINFO
);
6248 debugf("Not creating HINFO record: platform support layer provided no information");
6249 set
->RR_HINFO
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
6253 mDNSlocal
void mDNS_DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6255 NetworkInterfaceInfo
*intf
;
6256 // If we still have address records referring to this one, update them
6257 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
6258 AuthRecord
*A
= primary
? &primary
->RR_A
: mDNSNULL
;
6259 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6260 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
6261 intf
->RR_A
.RRSet
= A
;
6263 // Unregister these records.
6264 // When doing the mDNS_Close processing, we first call mDNS_DeadvertiseInterface for each interface, so by the time the platform
6265 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
6266 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
6267 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
6268 if (set
->RR_A
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
6269 if (set
->RR_PTR
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
6270 if (set
->RR_HINFO
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_HINFO
, mDNS_Dereg_normal
);
6273 mDNSexport
void mDNS_GenerateFQDN(mDNS
*const m
)
6279 if (!AppendDomainLabel(&newname
, &m
->hostlabel
)) LogMsg("ERROR! Cannot create dot-local hostname");
6280 if (!AppendLiteralLabelString(&newname
, "local")) LogMsg("ERROR! Cannot create dot-local hostname");
6281 if (!SameDomainName(&m
->hostname
, &newname
))
6283 NetworkInterfaceInfo
*intf
;
6286 m
->hostname
= newname
;
6288 // 1. Stop advertising our address records on all interfaces
6289 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6290 if (intf
->Advertise
) mDNS_DeadvertiseInterface(m
, intf
);
6292 // 2. Start advertising our address records using the new name
6293 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6294 if (intf
->Advertise
) mDNS_AdvertiseInterface(m
, intf
);
6296 // 3. Make sure that any SRV records (and the like) that reference our
6297 // host name in their rdata get updated to reference this new host name
6298 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->HostTarget
) SetTargetToHostName(m
, rr
);
6299 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->HostTarget
) SetTargetToHostName(m
, rr
);
6305 mDNSlocal
void HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
6307 (void)rr
; // Unused parameter
6311 char *msg
= "Unknown result";
6312 if (result
== mStatus_NoError
) msg
= "Name registered";
6313 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
6314 debugf("HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
6318 if (result
== mStatus_NoError
)
6320 // Notify the client that the host name is successfully registered
6321 if (m
->MainCallback
)
6322 m
->MainCallback(m
, result
);
6324 else if (result
== mStatus_NameConflict
)
6326 domainlabel oldlabel
= m
->hostlabel
;
6328 // 1. First give the client callback a chance to pick a new name
6329 if (m
->MainCallback
)
6330 m
->MainCallback(m
, mStatus_NameConflict
);
6332 // 2. If the client callback didn't do it, add (or increment) an index ourselves
6333 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
6334 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
6336 // 3. Generate the FQDNs from the hostlabel,
6337 // and make sure all SRV records, etc., are updated to reference our new hostname
6338 mDNS_GenerateFQDN(m
);
6342 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
6344 NetworkInterfaceInfo
*intf
;
6345 active
->IPv4Available
= mDNSfalse
;
6346 active
->IPv6Available
= mDNSfalse
;
6347 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6348 if (intf
->InterfaceID
== active
->InterfaceID
)
6350 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->TxAndRx
) active
->IPv4Available
= mDNStrue
;
6351 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->TxAndRx
) active
->IPv6Available
= mDNStrue
;
6355 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6357 mDNSBool FirstOfType
= mDNStrue
;
6358 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
6361 // Assume this interface will be active
6362 set
->InterfaceActive
= mDNStrue
;
6363 set
->IPv4Available
= (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->TxAndRx
);
6364 set
->IPv6Available
= (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->TxAndRx
);
6370 LogMsg("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
6372 return(mStatus_AlreadyRegistered
);
6375 // This InterfaceID is already in the list, so mark this interface inactive for now
6376 if ((*p
)->InterfaceID
== set
->InterfaceID
)
6378 set
->InterfaceActive
= mDNSfalse
;
6379 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
6380 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->TxAndRx
) (*p
)->IPv4Available
= mDNStrue
;
6381 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->TxAndRx
) (*p
)->IPv6Available
= mDNStrue
;
6387 set
->next
= mDNSNULL
;
6390 debugf("mDNS_RegisterInterface: InterfaceID %p %#a %s", set
->InterfaceID
, &set
->ip
,
6391 set
->InterfaceActive
?
6392 "not represented in list; marking active and retriggering queries" :
6393 "already represented in list; marking inactive for now");
6395 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6396 // giving the false impression that there's an active representative of this interface when there really isn't.
6397 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
6398 // even if we believe that we previously had an active representative of this interface.
6399 if ((m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) || FirstOfType
|| set
->InterfaceActive
)
6401 // Use a small amount of randomness:
6402 // In the case of a network administrator turning on an Ethernet hub so that all the connected machines establish link at
6403 // exactly the same time, we don't want them to all go and hit the network with identical queries at exactly the same moment.
6404 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
6407 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
6408 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
6409 { // then reactivate this question
6410 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
6411 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
6412 q
->RecentAnswers
= 0;
6413 if (ActiveQuestion(q
)) m
->NextScheduledQuery
= m
->timenow
;
6416 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
6417 // we now need them to re-probe if necessary, and then re-announce.
6418 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6419 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6421 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
6422 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
6423 if (rr
->AnnounceCount
< ReannounceCount
)
6424 rr
->AnnounceCount
= ReannounceCount
;
6425 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
6426 InitializeLastAPTime(m
, rr
);
6431 mDNS_AdvertiseInterface(m
, set
);
6434 return(mStatus_NoError
);
6437 // NOTE: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
6438 // the record list and/or question list.
6439 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6440 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6442 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
6444 mDNSBool revalidate
= mDNSfalse
;
6445 // If this platform has the "phantom interfaces" known bug (e.g. Jaguar), we have to revalidate records every
6446 // time an interface goes away. Otherwise, when you disconnect the Ethernet cable, the system reports that it
6447 // still has an IPv6 address, and if we don't revalidate those records don't get deleted in a timely fashion.
6448 if (m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) revalidate
= mDNStrue
;
6452 // Find this record in our list
6453 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
6454 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
6456 // Unlink this record from our list
6458 set
->next
= mDNSNULL
;
6460 if (!set
->InterfaceActive
)
6462 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
6463 NetworkInterfaceInfo
*intf
;
6464 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6465 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
6466 UpdateInterfaceProtocols(m
, intf
);
6470 NetworkInterfaceInfo
*intf
;
6471 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6472 if (intf
->InterfaceID
== set
->InterfaceID
)
6476 debugf("mDNS_DeregisterInterface: Another representative of InterfaceID %p exists; making it active",
6478 intf
->InterfaceActive
= mDNStrue
;
6479 UpdateInterfaceProtocols(m
, intf
);
6481 // See if another representative *of the same type* exists. If not, we mave have gone from
6482 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
6483 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6484 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
6486 if (!intf
) revalidate
= mDNStrue
;
6493 debugf("mDNS_DeregisterInterface: Last representative of InterfaceID %p deregistered; marking questions etc. dormant",
6496 // 1. Deactivate any questions specific to this interface
6497 for (q
= m
->Questions
; q
; q
=q
->next
)
6498 if (q
->InterfaceID
== set
->InterfaceID
)
6499 q
->ThisQInterval
= 0;
6501 // 2. Flush any cache records received on this interface
6502 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
6503 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6504 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
6505 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6506 PurgeCacheResourceRecord(m
, rr
);
6510 // If we were advertising on this interface, deregister those address and reverse-lookup records now
6512 mDNS_DeadvertiseInterface(m
, set
);
6514 // If we have any cache records received on this interface that went away, then re-verify them.
6515 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6516 // giving the false impression that there's an active representative of this interface when there really isn't.
6517 // Don't need to do this when shutting down, because *all* interfaces are about to go away
6518 if (revalidate
&& !m
->mDNS_shutdown
)
6522 m
->NextCacheCheck
= m
->timenow
;
6523 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6524 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
6525 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6526 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForCableDisconnect
);
6532 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
6534 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
6535 (void)m
; // Unused parameter
6539 char *msg
= "Unknown result";
6540 if (result
== mStatus_NoError
) msg
= "Name Registered";
6541 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
6542 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
6543 debugf("ServiceCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
6547 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
6548 if (result
== mStatus_NameConflict
)
6550 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
6551 sr
->RR_PTR
.AnnounceCount
= InitialAnnounceCount
; // Make sure we don't send a goodbye for the PTR record
6552 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
6556 if (result
== mStatus_MemFree
)
6558 // If the PTR record or any of the subtype PTR record are still in the process of deregistering,
6559 // don't pass on the NameConflict/MemFree message until every record is finished cleaning up.
6561 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
6562 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
6564 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
6565 // then we can now report the NameConflict to the client
6566 if (sr
->Conflict
) result
= mStatus_NameConflict
;
6569 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
6570 // function is allowed to do anything, including deregistering this service and freeing its memory.
6571 if (sr
->ServiceCallback
)
6572 sr
->ServiceCallback(m
, sr
, result
);
6576 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
6577 // Type is service type (e.g. "_printer._tcp.")
6578 // Domain is fully qualified domain name (i.e. ending with a null label)
6579 // We always register a TXT, even if it is empty (so that clients are not
6580 // left waiting forever looking for a nonexistent record.)
6581 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
6582 // then the default host name (m->hostname1) is automatically used
6583 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
6584 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
6585 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
6586 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
6587 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
)
6592 sr
->ServiceCallback
= Callback
;
6593 sr
->ServiceContext
= Context
;
6594 sr
->Extras
= mDNSNULL
;
6595 sr
->NumSubTypes
= NumSubTypes
;
6596 sr
->SubTypes
= SubTypes
;
6597 sr
->Conflict
= mDNSfalse
;
6598 if (host
&& host
->c
[0]) sr
->Host
= *host
;
6599 else sr
->Host
.c
[0] = 0;
6601 // Initialize the AuthRecord objects to sane values
6602 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeAdvisory
, ServiceCallback
, sr
);
6603 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
6604 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6605 mDNS_SetupResourceRecord(&sr
->RR_TXT
, mDNSNULL
, InterfaceID
, kDNSType_TXT
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6607 // If the client is registering an oversized TXT record,
6608 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
6609 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
6610 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
6612 // Set up the record names
6613 // For now we only create an advisory record for the main type, not for subtypes
6614 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
6615 if (ConstructServiceName(&sr
->RR_ADV
.resrec
.name
, (domainlabel
*)"\x09_services", (domainname
*)"\x05_mdns\x04_udp", domain
) == mDNSNULL
)
6616 return(mStatus_BadParamErr
);
6617 if (ConstructServiceName(&sr
->RR_PTR
.resrec
.name
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6618 if (ConstructServiceName(&sr
->RR_SRV
.resrec
.name
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6619 AssignDomainName(sr
->RR_TXT
.resrec
.name
, sr
->RR_SRV
.resrec
.name
);
6621 // 1. Set up the ADV record rdata to advertise our service type
6622 AssignDomainName(sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
6624 // 2. Set up the PTR record rdata to point to our service name
6625 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
6626 AssignDomainName(sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
6627 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
6628 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
6630 // 2a. Set up any subtype PTRs to point to our service name
6631 // If the client is using subtypes, it is the client's responsibility to have
6632 // already set the first label of the record name to the subtype being registered
6633 for (i
=0; i
<NumSubTypes
; i
++)
6635 domainlabel s
= *(domainlabel
*)&sr
->SubTypes
[i
].resrec
.name
;
6636 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
6637 if (ConstructServiceName(&sr
->SubTypes
[i
].resrec
.name
, &s
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6638 AssignDomainName(sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
6639 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
6640 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
6643 // 3. Set up the SRV record rdata.
6644 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
6645 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
6646 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
6648 // Setting HostTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
6649 if (sr
->Host
.c
[0]) AssignDomainName(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, sr
->Host
);
6650 else sr
->RR_SRV
.HostTarget
= mDNStrue
;
6652 // 4. Set up the TXT record rdata,
6653 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
6654 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
6655 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
6657 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
6658 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
6659 mDNSPlatformMemCopy(txtinfo
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtlen
);
6661 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
6664 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
6665 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
6666 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
6667 // mDNS_Close, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
6668 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
6669 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
6670 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
6671 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
6672 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
6673 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
6676 if (err
) mDNS_DeregisterService(m
, sr
);
6680 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
6681 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
)
6683 mStatus result
= mStatus_UnknownErr
;
6684 ExtraResourceRecord
**e
= &sr
->Extras
;
6685 while (*e
) e
= &(*e
)->next
;
6687 // If TTL is unspecified, make it the same as the service's TXT and SRV default
6688 if (ttl
== 0) ttl
= kDefaultTTLforUnique
;
6690 extra
->next
= mDNSNULL
;
6691 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
, extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6692 AssignDomainName(extra
->r
.resrec
.name
, sr
->RR_SRV
.resrec
.name
);
6693 extra
->r
.DependentOn
= &sr
->RR_SRV
;
6695 debugf("mDNS_AddRecordToService adding record to %##s", extra
->r
.resrec
.name
.c
);
6697 result
= mDNS_Register(m
, &extra
->r
);
6698 if (!result
) *e
= extra
;
6702 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
)
6704 ExtraResourceRecord
**e
= &sr
->Extras
;
6705 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
6708 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
.c
);
6709 return(mStatus_BadReferenceErr
);
6712 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
.c
);
6715 return(mDNS_Deregister(m
, &extra
->r
));
6718 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
6721 domainname type
, domain
;
6722 domainname
*host
= mDNSNULL
;
6723 ExtraResourceRecord
*extras
= sr
->Extras
;
6726 DeconstructServiceName(&sr
->RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
6729 IncrementLabelSuffix(&name
, mDNStrue
);
6732 debugf("Reregistering as %#s", newname
->c
);
6733 if (sr
->RR_SRV
.HostTarget
== mDNSfalse
&& sr
->Host
.c
[0]) host
= &sr
->Host
;
6735 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
6736 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
6737 sr
->SubTypes
, sr
->NumSubTypes
,
6738 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
);
6740 // mDNS_RegisterService() just reset sr->Extras to NULL.
6741 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
6742 // through the old list of extra records, and re-add them to our freshly created service registration
6743 while (!err
&& extras
)
6745 ExtraResourceRecord
*e
= extras
;
6746 extras
= extras
->next
;
6747 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
);
6753 // NOTE: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
6754 // which may change the record list and/or question list.
6755 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6756 mDNSexport mStatus
mDNS_DeregisterService(mDNS
*const m
, ServiceRecordSet
*sr
)
6758 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
6760 debugf("Service set for %##s already deregistered", sr
->RR_PTR
.resrec
.name
.c
);
6761 return(mStatus_BadReferenceErr
);
6763 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
6765 debugf("Service set for %##s already in the process of deregistering", sr
->RR_PTR
.resrec
.name
.c
);
6766 return(mStatus_NoError
);
6772 ExtraResourceRecord
*e
;
6776 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
6777 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
6778 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
6779 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
6781 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, mDNS_Dereg_normal
);
6783 // We deregister all of the extra records, but we leave the sr->Extras list intact
6784 // in case the client wants to do a RenameAndReregister and reinstate the registration
6787 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
6791 for (i
=0; i
<sr
->NumSubTypes
; i
++)
6792 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], mDNS_Dereg_normal
);
6794 // Be sure to deregister the PTR last!
6795 // Deregistering this record is what triggers the mStatus_MemFree callback to ServiceCallback,
6796 // which in turn passes on the mStatus_MemFree (or mStatus_NameConflict) back to the client callback,
6797 // which is then at liberty to free the ServiceRecordSet memory at will. We need to make sure
6798 // we've deregistered all our records and done any other necessary cleanup before that happens.
6799 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, mDNS_Dereg_normal
);
6805 // Create a registration that asserts that no such service exists with this name.
6806 // This can be useful where there is a given function is available through several protocols.
6807 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
6808 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
6809 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
6810 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
6811 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
6812 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
6813 const domainname
*const host
,
6814 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
)
6816 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, Callback
, Context
);
6817 if (ConstructServiceName(&rr
->resrec
.name
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6818 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
6819 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
6820 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
6821 if (host
&& host
->c
[0]) AssignDomainName(rr
->resrec
.rdata
->u
.srv
.target
, *host
);
6822 else rr
->HostTarget
= mDNStrue
;
6823 return(mDNS_Register(m
, rr
));
6826 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
6827 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
6829 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, mDNSNULL
, mDNSNULL
);
6830 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.name
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
6831 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
6832 return(mDNS_Register(m
, rr
));
6835 // ***************************************************************************
6836 #if COMPILER_LIKES_PRAGMA_MARK
6839 #pragma mark - Startup and Shutdown
6842 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheRecord
*storage
, mDNSu32 numrecords
)
6844 if (storage
&& numrecords
)
6847 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
6848 storage
[numrecords
-1].next
= m
->rrcache_free
;
6849 m
->rrcache_free
= storage
;
6850 m
->rrcache_size
+= numrecords
;
6854 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
6855 CacheRecord
*rrcachestorage
, mDNSu32 rrcachesize
,
6856 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
6860 mStatus result
= mDNSPlatformTimeInit(&timenow
);
6861 if (result
!= mStatus_NoError
) return(result
);
6863 if (!rrcachestorage
) rrcachesize
= 0;
6867 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
6868 m
->mDNSPlatformStatus
= mStatus_Waiting
;
6869 m
->MainCallback
= Callback
;
6870 m
->MainContext
= Context
;
6872 // For debugging: To catch and report locking failures
6874 m
->mDNS_reentrancy
= 0;
6875 m
->mDNS_shutdown
= mDNSfalse
;
6876 m
->lock_rrcache
= 0;
6877 m
->lock_Questions
= 0;
6878 m
->lock_Records
= 0;
6880 // Task Scheduling variables
6881 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
6882 m
->timenow_last
= timenow
;
6883 m
->timenow_adjust
= 0;
6884 m
->NextScheduledEvent
= timenow
;
6885 m
->SuppressSending
= timenow
;
6886 m
->NextCacheCheck
= timenow
+ 0x78000000;
6887 m
->NextScheduledQuery
= timenow
+ 0x78000000;
6888 m
->NextScheduledProbe
= timenow
+ 0x78000000;
6889 m
->NextScheduledResponse
= timenow
+ 0x78000000;
6890 m
->ExpectUnicastResponse
= timenow
+ 0x78000000;
6891 m
->RandomQueryDelay
= 0;
6892 m
->SendDeregistrations
= mDNSfalse
;
6893 m
->SendImmediateAnswers
= mDNSfalse
;
6894 m
->SleepState
= mDNSfalse
;
6896 // These fields only required for mDNS Searcher...
6897 m
->Questions
= mDNSNULL
;
6898 m
->NewQuestions
= mDNSNULL
;
6899 m
->CurrentQuestion
= mDNSNULL
;
6900 m
->LocalOnlyQuestions
= mDNSNULL
;
6901 m
->NewLocalOnlyQuestions
= mDNSNULL
;
6902 m
->rrcache_size
= 0;
6903 m
->rrcache_totalused
= 0;
6904 m
->rrcache_active
= 0;
6905 m
->rrcache_report
= 10;
6906 m
->rrcache_free
= mDNSNULL
;
6908 for (i
= 0; i
< CACHE_HASH_SLOTS
; i
++)
6910 m
->rrcache_hash
[i
] = mDNSNULL
;
6911 m
->rrcache_used
[i
] = 0;
6914 mDNS_GrowCache(m
, rrcachestorage
, rrcachesize
);
6916 // Fields below only required for mDNS Responder...
6917 m
->hostlabel
.c
[0] = 0;
6918 m
->nicelabel
.c
[0] = 0;
6919 m
->hostname
.c
[0] = 0;
6920 m
->HIHardware
.c
[0] = 0;
6921 m
->HISoftware
.c
[0] = 0;
6922 m
->ResourceRecords
= mDNSNULL
;
6923 m
->DuplicateRecords
= mDNSNULL
;
6924 m
->LocalOnlyRecords
= mDNSNULL
;
6925 m
->NewLocalOnlyRecords
= mDNSNULL
;
6926 m
->DiscardLocalOnlyRecords
= mDNSfalse
;
6927 m
->CurrentRecord
= mDNSNULL
;
6928 m
->HostInterfaces
= mDNSNULL
;
6929 m
->ProbeFailTime
= 0;
6930 m
->NumFailedProbes
= 0;
6931 m
->SuppressProbes
= 0;
6933 result
= mDNSPlatformInit(m
);
6938 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
6940 m
->mDNSPlatformStatus
= result
;
6941 if (m
->MainCallback
)
6942 m
->MainCallback(m
, mStatus_NoError
);
6945 mDNSexport
void mDNS_Close(mDNS
*const m
)
6947 mDNSu32 rrcache_active
= 0;
6948 mDNSu32 rrcache_totalused
= 0;
6950 NetworkInterfaceInfo
*intf
;
6953 m
->mDNS_shutdown
= mDNStrue
;
6955 rrcache_totalused
= m
->rrcache_totalused
;
6956 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6957 while (m
->rrcache_hash
[slot
])
6959 CacheRecord
*rr
= m
->rrcache_hash
[slot
];
6960 m
->rrcache_hash
[slot
] = rr
->next
;
6961 if (rr
->CRActiveQuestion
) rrcache_active
++;
6962 m
->rrcache_used
[slot
]--;
6963 ReleaseCacheRR(m
, rr
);
6965 debugf("mDNS_Close: RR Cache was using %ld records, %d active", rrcache_totalused
, rrcache_active
);
6966 if (rrcache_active
!= m
->rrcache_active
)
6967 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active
, m
->rrcache_active
);
6969 m
->Questions
= mDNSNULL
; // We won't be answering any more questions!
6971 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6972 if (intf
->Advertise
)
6973 mDNS_DeadvertiseInterface(m
, intf
);
6975 // Make sure there are nothing but deregistering records remaining in the list
6976 if (m
->CurrentRecord
) LogMsg("mDNS_Close ERROR m->CurrentRecord already set");
6977 m
->CurrentRecord
= m
->ResourceRecords
;
6978 while (m
->CurrentRecord
)
6980 AuthRecord
*rr
= m
->CurrentRecord
;
6981 m
->CurrentRecord
= rr
->next
;
6982 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
6984 debugf("mDNS_Close: Record type %X still in ResourceRecords list %##s", rr
->resrec
.RecordType
, rr
->resrec
.name
.c
);
6985 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6989 if (m
->ResourceRecords
) debugf("mDNS_Close: Sending final packets for deregistering records");
6990 else debugf("mDNS_Close: No deregistering records remain");
6992 // If any deregistering records remain, send their deregistration announcements before we exit
6993 if (m
->mDNSPlatformStatus
!= mStatus_NoError
)
6994 DiscardDeregistrations(m
);
6996 while (m
->ResourceRecords
)
7000 debugf("mDNS_Close: mDNSPlatformClose");
7001 mDNSPlatformClose(m
);
7002 debugf("mDNS_Close: done");