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.2.8 2004/04/03 05:18:19 bradley
48 Added cast to fix signed/unsigned warning due to int promotion.
50 Revision 1.307.2.7 2004/03/30 06:46:24 cheshire
51 Compiler warning fixes from Don Woodward at Roku Labs
53 Revision 1.307.2.6 2004/03/09 03:03:38 cheshire
54 <rdar://problem/3581961> Don't take lock until after mDNS_Update() has validated that the data is good
56 Revision 1.307.2.5 2004/03/02 02:55:24 cheshire
57 <rdar://problem/3549576> Properly support "_services._dns-sd._udp" meta-queries
59 Revision 1.307.2.4 2004/02/18 01:55:08 cheshire
60 <rdar://problem/3553472>: Increase delay to 400ms when answering queries with multi-packet KA lists
62 Revision 1.307.2.3 2004/01/28 23:08:45 cheshire
63 <rdar://problem/3488559>: Hard code domain enumeration functions to return ".local" only
65 Revision 1.307.2.2 2003/12/20 01:51:40 cheshire
66 <rdar://problem/3515876>: Error putting additional records into packets
67 Another fix from Rampi: responseptr needs to be updated inside the "for" loop,
68 after every record, not once at the end.
70 Revision 1.307.2.1 2003/12/03 11:20:27 cheshire
71 <rdar://problem/3457718>: Stop and start of a service uses old ip address (with old port number)
73 Revision 1.307 2003/09/09 20:13:30 cheshire
74 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
75 Ammend checkin 1.304: Off-by-one error: By this place in the function we've already decremented
76 rr->AnnounceCount, so the check needs to be for InitialAnnounceCount-1, not InitialAnnounceCount
78 Revision 1.306 2003/09/09 03:00:03 cheshire
79 <rdar://problem/3413099> Services take a long time to disappear when switching networks.
80 Added two constants: kDefaultReconfirmTimeForNoAnswer and kDefaultReconfirmTimeForCableDisconnect
82 Revision 1.305 2003/09/09 02:49:31 cheshire
83 <rdar://problem/3413975> Initial probes and queries not grouped on wake-from-sleep
85 Revision 1.304 2003/09/09 02:41:19 cheshire
86 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
88 Revision 1.303 2003/09/05 19:55:02 cheshire
89 <rdar://problem/3409533> Include address records when announcing SRV records
91 Revision 1.302 2003/09/05 00:01:36 cheshire
92 <rdar://problem/3407549> Don't accelerate queries that have large KA lists
94 Revision 1.301 2003/09/04 22:51:13 cheshire
95 <rdar://problem/3398213> Group probes and goodbyes better
97 Revision 1.300 2003/09/03 02:40:37 cheshire
98 <rdar://problem/3404842> mDNSResponder complains about '_'s
99 Underscores are not supposed to be legal in standard DNS names, but IANA appears
100 to have allowed them in previous service name registrations, so we should too.
102 Revision 1.299 2003/09/03 02:33:09 cheshire
103 <rdar://problem/3404795> CacheRecordRmv ERROR
104 Don't update m->NewQuestions until *after* CheckCacheExpiration();
106 Revision 1.298 2003/09/03 01:47:01 cheshire
107 <rdar://problem/3319418> Rendezvous services always in a state of flux
108 Change mDNS_Reconfirm_internal() minimum timeout from 5 seconds to 45-60 seconds
110 Revision 1.297 2003/08/29 19:44:15 cheshire
111 <rdar://problem/3400967> Traffic reduction: Eliminate synchronized QUs when a new service appears
112 1. Use m->RandomQueryDelay to impose a random delay in the range 0-500ms on queries
113 that already have at least one unique answer in the cache
114 2. For these queries, go straight to QM, skipping QU
116 Revision 1.296 2003/08/29 19:08:21 cheshire
117 <rdar://problem/3400986> Traffic reduction: Eliminate huge KA lists after wake from sleep
118 Known answers are no longer eligible to go in the KA list if they are more than half-way to their expiry time.
120 Revision 1.295 2003/08/28 01:10:59 cheshire
121 <rdar://problem/3396034> Add syslog message to report when query is reset because of immediate answer burst
123 Revision 1.294 2003/08/27 02:30:22 cheshire
124 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
125 One more change: "query->GotTXT" is now a straightforward bi-state boolean again
127 Revision 1.293 2003/08/27 02:25:31 cheshire
128 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
130 Revision 1.292 2003/08/21 19:27:36 cheshire
131 <rdar://problem/3387878> Traffic reduction: No need to announce record for longer than TTL
133 Revision 1.291 2003/08/21 18:57:44 cheshire
134 <rdar://problem/3387140> Synchronized queries on the network
136 Revision 1.290 2003/08/21 02:25:23 cheshire
137 Minor changes to comments and debugf() messages
139 Revision 1.289 2003/08/21 02:21:50 cheshire
140 <rdar://problem/3386473> Efficiency: Reduce repeated queries
142 Revision 1.288 2003/08/20 23:39:30 cheshire
143 <rdar://problem/3344098> Review syslog messages, and remove as appropriate
145 Revision 1.287 2003/08/20 20:47:18 cheshire
148 Revision 1.286 2003/08/20 02:18:51 cheshire
149 <rdar://problem/3344098> Cleanup: Review syslog messages
151 Revision 1.285 2003/08/20 01:59:06 cheshire
152 <rdar://problem/3384478> rdatahash and rdnamehash not updated after changing rdata
153 Made new routine SetNewRData() to update rdlength, rdestimate, rdatahash and rdnamehash in one place
155 Revision 1.284 2003/08/19 22:20:00 cheshire
156 <rdar://problem/3376721> Don't use IPv6 on interfaces that have a routable IPv4 address configured
157 More minor refinements
159 Revision 1.283 2003/08/19 22:16:27 cheshire
160 Minor fix: Add missing "mDNS_Unlock(m);" in mDNS_DeregisterInterface() error case.
162 Revision 1.282 2003/08/19 06:48:25 cheshire
163 <rdar://problem/3376552> Guard against excessive record updates
164 Each record starts with 10 UpdateCredits.
165 Every update consumes one UpdateCredit.
166 UpdateCredits are replenished at a rate of one one per minute, up to a maximum of 10.
167 As the number of UpdateCredits declines, the number of announcements is similarly scaled back.
168 When fewer than 5 UpdateCredits remain, the first announcement is also delayed by an increasing amount.
170 Revision 1.281 2003/08/19 04:49:28 cheshire
171 <rdar://problem/3368159> Interaction between v4, v6 and dual-stack hosts not working quite right
172 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.
173 2. When we see the first v4 (or first v6) member of a group, we re-trigger questions and probes on that interface.
174 3. When we see the last v4 (or v6) member of a group go away, we revalidate all the records received on that interface.
176 Revision 1.280 2003/08/19 02:33:36 cheshire
179 Revision 1.279 2003/08/19 02:31:11 cheshire
180 <rdar://problem/3378386> mDNSResponder overenthusiastic with final expiration queries
181 Final expiration queries now only mark the question for sending on the particular interface
182 pertaining to the record that's expiring.
184 Revision 1.278 2003/08/18 22:53:37 cheshire
185 <rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformTimeNow()
187 Revision 1.277 2003/08/18 19:05:44 cheshire
188 <rdar://problem/3382423> UpdateRecord not working right
189 Added "newrdlength" field to hold new length of updated rdata
191 Revision 1.276 2003/08/16 03:39:00 cheshire
192 <rdar://problem/3338440> InterfaceID -1 indicates "local only"
194 Revision 1.275 2003/08/16 02:51:27 cheshire
195 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
196 Don't try to compute namehash etc, until *after* validating the name
198 Revision 1.274 2003/08/16 01:12:40 cheshire
199 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
200 Now that the minimum rdata object size has been reduced to 64 bytes, it is no longer safe to do a
201 simple C structure assignment of a domainname, because that object is defined to be 256 bytes long,
202 and in the process of copying it, the C compiler may run off the end of the rdata object into
203 unmapped memory. All assignments of domainname objects of uncertain size are now replaced with a
204 call to the macro AssignDomainName(), which is careful to copy only as many bytes as are valid.
206 Revision 1.273 2003/08/15 20:16:02 cheshire
207 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
208 We want to avoid touching the rdata pages, so we don't page them in.
209 1. RDLength was stored with the rdata, which meant touching the page just to find the length.
210 Moved this from the RData to the ResourceRecord object.
211 2. To avoid unnecessarily touching the rdata just to compare it,
212 compute a hash of the rdata and store the hash in the ResourceRecord object.
214 Revision 1.272 2003/08/14 19:29:04 cheshire
215 <rdar://problem/3378473> Include cache records in SIGINFO output
216 Moved declarations of DNSTypeName() and GetRRDisplayString to mDNSClientAPI.h so daemon.c can use them
218 Revision 1.271 2003/08/14 02:17:05 cheshire
219 <rdar://problem/3375491> Split generic ResourceRecord type into two separate types: AuthRecord and CacheRecord
221 Revision 1.270 2003/08/13 17:07:28 ksekar
222 Bug #: <rdar://problem/3376458>: Extra RR linked to list even if registration fails - causes crash
223 Added check to result of mDNS_Register() before linking extra record into list.
225 Revision 1.269 2003/08/12 19:56:23 cheshire
228 Revision 1.268 2003/08/12 15:01:10 cheshire
231 Revision 1.267 2003/08/12 14:59:27 cheshire
232 <rdar://problem/3374490> Rate-limiting blocks some legitimate responses
233 When setting LastMCTime also record LastMCInterface. When checking LastMCTime to determine
234 whether to suppress the response, also check LastMCInterface to see if it matches.
236 Revision 1.266 2003/08/12 12:47:16 cheshire
237 In mDNSCoreMachineSleep debugf message, display value of m->timenow
239 Revision 1.265 2003/08/11 20:04:28 cheshire
240 <rdar://problem/3366553> Improve efficiency by restricting cases where we have to walk the entire cache
242 Revision 1.264 2003/08/09 00:55:02 cheshire
243 <rdar://problem/3366553> mDNSResponder is taking 20-30% of the CPU
244 Don't scan the whole cache after every packet.
246 Revision 1.263 2003/08/09 00:35:29 cheshire
247 Moved AnswerNewQuestion() later in the file, in preparation for next checkin
249 Revision 1.262 2003/08/08 19:50:33 cheshire
250 <rdar://problem/3370332> Remove "Cache size now xxx" messages
252 Revision 1.261 2003/08/08 19:18:45 cheshire
253 <rdar://problem/3271219> Only retrigger questions on platforms with the "PhantomInterfaces" bug
255 Revision 1.260 2003/08/08 18:55:48 cheshire
256 <rdar://problem/3370365> Guard against time going backwards
258 Revision 1.259 2003/08/08 18:36:04 cheshire
259 <rdar://problem/3344154> Only need to revalidate on interface removal on platforms that have the PhantomInterfaces bug
261 Revision 1.258 2003/08/08 16:22:05 cheshire
262 <rdar://problem/3335473> Need to check validity of TXT (and other) records
263 Remove unneeded LogMsg
265 Revision 1.257 2003/08/07 01:41:08 cheshire
266 <rdar://problem/3367346> Ignore packets with invalid source address (all zeroes or all ones)
268 Revision 1.256 2003/08/06 23:25:51 cheshire
269 <rdar://problem/3290674> Increase TTL for A/AAAA/SRV from one minute to four
271 Revision 1.255 2003/08/06 23:22:50 cheshire
272 Add symbolic constants: kDefaultTTLforUnique (one minute) and kDefaultTTLforShared (two hours)
274 Revision 1.254 2003/08/06 21:33:39 cheshire
275 Fix compiler warnings on PocketPC 2003 (Windows CE)
277 Revision 1.253 2003/08/06 20:43:57 cheshire
278 <rdar://problem/3335473> Need to check validity of TXT (and other) records
279 Created ValidateDomainName() and ValidateRData(), used by mDNS_Register_internal() and mDNS_Update()
281 Revision 1.252 2003/08/06 20:35:47 cheshire
282 Enhance debugging routine GetRRDisplayString() so it can also be used to display
283 other RDataBody objects, not just the one currently attached the given ResourceRecord
285 Revision 1.251 2003/08/06 19:07:34 cheshire
286 <rdar://problem/3366251> mDNSResponder not inhibiting multicast responses as much as it should
287 Was checking LastAPTime instead of LastMCTime
289 Revision 1.250 2003/08/06 19:01:55 cheshire
292 Revision 1.249 2003/08/06 00:13:28 cheshire
293 Tidy up debugf messages
295 Revision 1.248 2003/08/05 22:20:15 cheshire
296 <rdar://problem/3330324> Need to check IP TTL on responses
298 Revision 1.247 2003/08/05 00:56:39 cheshire
299 <rdar://problem/3357075> mDNSResponder sending additional records, even after precursor record suppressed
301 Revision 1.246 2003/08/04 19:20:49 cheshire
302 Add kDNSQType_ANY to list in DNSTypeName() so it can be displayed in debugging messages
304 Revision 1.245 2003/08/02 01:56:29 cheshire
305 For debugging: log message if we ever get more than one question in a truncated packet
307 Revision 1.244 2003/08/01 23:55:32 cheshire
308 Fix for compiler warnings on Windows, submitted by Bob Bradley
310 Revision 1.243 2003/07/25 02:26:09 cheshire
311 Typo: FIxed missing semicolon
313 Revision 1.242 2003/07/25 01:18:41 cheshire
314 Fix memory leak on shutdown in mDNS_Close() (detected in Windows version)
316 Revision 1.241 2003/07/23 21:03:42 cheshire
317 Only show "Found record..." debugf message in verbose mode
319 Revision 1.240 2003/07/23 21:01:11 cheshire
320 <rdar://problem/3340584> Need Nagle-style algorithm to coalesce multiple packets into one
321 After sending a packet, suppress further sending for the next 100ms.
323 Revision 1.239 2003/07/22 01:30:05 cheshire
324 <rdar://problem/3329099> Don't try to add the same question to the duplicate-questions list more than once
326 Revision 1.238 2003/07/22 00:10:20 cheshire
327 <rdar://problem/3337355> ConvertDomainLabelToCString() needs to escape escape characters
329 Revision 1.237 2003/07/19 03:23:13 cheshire
330 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
332 Revision 1.236 2003/07/19 03:04:55 cheshire
333 Fix warnings; some debugf message improvements
335 Revision 1.235 2003/07/19 00:03:32 cheshire
336 <rdar://problem/3160248> ScheduleNextTask needs to be smarter after a no-op packet is received
337 ScheduleNextTask is quite an expensive operation.
338 We don't need to do all that work after receiving a no-op packet that didn't change our state.
340 Revision 1.234 2003/07/18 23:52:11 cheshire
341 To improve consistency of field naming, global search-and-replace:
342 NextProbeTime -> NextScheduledProbe
343 NextResponseTime -> NextScheduledResponse
345 Revision 1.233 2003/07/18 00:29:59 cheshire
346 <rdar://problem/3268878> Remove mDNSResponder version from packet header and use HINFO record instead
348 Revision 1.232 2003/07/18 00:11:38 cheshire
349 Add extra case to switch statements to handle HINFO data for Get, Put and Display
350 (In all but GetRDLength(), this is is just a fall-through to kDNSType_TXT)
352 Revision 1.231 2003/07/18 00:06:37 cheshire
353 To make code a little easier to read in GetRDLength(), search-and-replace "rr->rdata->u." with "rd->"
355 Revision 1.230 2003/07/17 18:16:54 cheshire
356 <rdar://problem/3319418> Rendezvous services always in a state of flux
357 In preparation for working on this, made some debugf messages a little more selective
359 Revision 1.229 2003/07/17 17:35:04 cheshire
360 <rdar://problem/3325583> Rate-limit responses, to guard against packet flooding
362 Revision 1.228 2003/07/16 20:50:27 cheshire
363 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
365 Revision 1.227 2003/07/16 05:01:36 cheshire
366 Add fields 'LargeAnswers' and 'ExpectUnicastResponse' in preparation for
367 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
369 Revision 1.226 2003/07/16 04:51:44 cheshire
370 Fix use of constant 'mDNSPlatformOneSecond' where it should have said 'InitialQuestionInterval'
372 Revision 1.225 2003/07/16 04:46:41 cheshire
373 Minor wording cleanup: The correct DNS term is "response", not "reply"
375 Revision 1.224 2003/07/16 04:39:02 cheshire
376 Textual cleanup (no change to functionality):
377 Construct "c >= 'A' && c <= 'Z'" appears in too many places; replaced with macro "mDNSIsUpperCase(c)"
379 Revision 1.223 2003/07/16 00:09:22 cheshire
380 Textual cleanup (no change to functionality):
381 Construct "((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)" appears in too many places;
382 replace with macro "TicksTTL(rr)"
383 Construct "rr->TimeRcvd + ((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)"
384 replaced with macro "RRExpireTime(rr)"
386 Revision 1.222 2003/07/15 23:40:46 cheshire
387 Function rename: UpdateDupSuppressInfo() is more accurately called ExpireDupSuppressInfo()
389 Revision 1.221 2003/07/15 22:17:56 cheshire
390 <rdar://problem/3328394> mDNSResponder is not being efficient when doing certain queries
392 Revision 1.220 2003/07/15 02:12:51 cheshire
393 Slight tidy-up of debugf messages and comments
395 Revision 1.219 2003/07/15 01:55:12 cheshire
396 <rdar://problem/3315777> Need to implement service registration with subtypes
398 Revision 1.218 2003/07/14 16:26:06 cheshire
399 <rdar://problem/3324795> Duplicate query suppression not working right
400 Refinement: Don't record DS information for a question in the first quarter second
401 right after we send it -- in the case where a question happens to be accelerated by
402 the maximum allowed amount, we don't want it to then be suppressed because the previous
403 time *we* sent that question falls (just) within the valid duplicate suppression window.
405 Revision 1.217 2003/07/13 04:43:53 cheshire
406 <rdar://problem/3325169> Services on multiple interfaces not always resolving
407 Minor refinement: No need to make address query broader than the original SRV query that provoked it
409 Revision 1.216 2003/07/13 03:13:17 cheshire
410 <rdar://problem/3325169> Services on multiple interfaces not always resolving
411 If we get an identical SRV on a second interface, convert address queries to non-specific
413 Revision 1.215 2003/07/13 02:28:00 cheshire
414 <rdar://problem/3325166> SendResponses didn't all its responses
415 Delete all references to RRInterfaceActive -- it's now superfluous
417 Revision 1.214 2003/07/13 01:47:53 cheshire
418 Fix one error and one warning in the Windows build
420 Revision 1.213 2003/07/12 04:25:48 cheshire
421 Fix minor signed/unsigned warnings
423 Revision 1.212 2003/07/12 01:59:11 cheshire
424 Minor changes to debugf messages
426 Revision 1.211 2003/07/12 01:47:01 cheshire
427 <rdar://problem/3324495> After name conflict, appended number should be higher than previous number
429 Revision 1.210 2003/07/12 01:43:28 cheshire
430 <rdar://problem/3324795> Duplicate query suppression not working right
431 The correct cutoff time for duplicate query suppression is timenow less one-half the query interval.
432 The code was incorrectly using the last query time plus one-half the query interval.
433 This was only correct in the case where query acceleration was not in effect.
435 Revision 1.209 2003/07/12 01:27:50 cheshire
436 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
437 Fix missing "-1" in RemoveLabelSuffix()
439 Revision 1.208 2003/07/11 01:32:38 cheshire
440 Syntactic cleanup (no change to funcationality): Now that we only have one host name,
441 rename field "hostname1" to "hostname", and field "RR_A1" to "RR_A".
443 Revision 1.207 2003/07/11 01:28:00 cheshire
444 <rdar://problem/3161289> No more local.arpa
446 Revision 1.206 2003/07/11 00:45:02 cheshire
447 <rdar://problem/3321909> Client should get callback confirming successful host name registration
449 Revision 1.205 2003/07/11 00:40:18 cheshire
450 Tidy up debug message in HostNameCallback()
452 Revision 1.204 2003/07/11 00:20:32 cheshire
453 <rdar://problem/3320087> mDNSResponder should log a message after 16 unsuccessful probes
455 Revision 1.203 2003/07/10 23:53:41 cheshire
456 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
458 Revision 1.202 2003/07/04 02:23:20 cheshire
459 <rdar://problem/3311955> Responder too aggressive at flushing stale data
460 Changed mDNSResponder to require four unanswered queries before purging a record, instead of two.
462 Revision 1.201 2003/07/04 01:09:41 cheshire
463 <rdar://problem/3315775> Need to implement subtype queries
464 Modified ConstructServiceName() to allow three-part service types
466 Revision 1.200 2003/07/03 23:55:26 cheshire
467 Minor change to wording of syslog warning messages
469 Revision 1.199 2003/07/03 23:51:13 cheshire
470 <rdar://problem/3315652>: Lots of "have given xxx answers" syslog warnings
471 Added more detailed debugging information
473 Revision 1.198 2003/07/03 22:19:30 cheshire
474 <rdar://problem/3314346> Bug fix in 3274153 breaks TiVo
475 Make exception to allow _tivo_servemedia._tcp.
477 Revision 1.197 2003/07/02 22:33:05 cheshire
478 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
480 When cache is exhausted, verify that rrcache_totalused == rrcache_size and report if not
481 Allow cache to grow to 512 records before considering it a potential denial-of-service attack
483 Revision 1.196 2003/07/02 21:19:45 cheshire
484 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
486 Revision 1.195 2003/07/02 19:56:58 cheshire
487 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
488 Minor refinement: m->rrcache_active was not being decremented when
489 an active record was deleted because its TTL expired
491 Revision 1.194 2003/07/02 18:47:40 cheshire
492 Minor wording change to log messages
494 Revision 1.193 2003/07/02 02:44:13 cheshire
495 Fix warning in non-debug build
497 Revision 1.192 2003/07/02 02:41:23 cheshire
498 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
500 Revision 1.191 2003/07/02 02:30:51 cheshire
501 HashSlot() returns an array index. It can't be negative; hence it should not be signed.
503 Revision 1.190 2003/06/27 00:03:05 vlubet
504 <rdar://problem/3304625> Merge of build failure fix for gcc 3.3
506 Revision 1.189 2003/06/11 19:24:03 cheshire
507 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
508 Slight refinement to previous checkin
510 Revision 1.188 2003/06/10 20:33:28 cheshire
511 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
513 Revision 1.187 2003/06/10 04:30:44 cheshire
514 <rdar://problem/3286234> Need to re-probe/re-announce on configuration change
515 Only interface-specific records were re-probing and re-announcing, not non-specific records.
517 Revision 1.186 2003/06/10 04:24:39 cheshire
518 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
519 Some additional refinements:
520 Don't try to do this for unicast-response queries
521 better tracking of Qs and KAs in multi-packet KA lists
523 Revision 1.185 2003/06/10 03:52:49 cheshire
524 Update comments and debug messages
526 Revision 1.184 2003/06/10 02:26:39 cheshire
527 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
528 Make mDNS_Reconfirm() call mDNS_Lock(), like the other API routines
530 Revision 1.183 2003/06/09 18:53:13 cheshire
531 Simplify some debugf() statements (replaced block of 25 lines with 2 lines)
533 Revision 1.182 2003/06/09 18:38:42 cheshire
534 <rdar://problem/3285082> Need to be more tolerant when there are mDNS proxies on the network
535 Only issue a correction if the TTL in the proxy packet is less than half the correct value.
537 Revision 1.181 2003/06/07 06:45:05 cheshire
538 <rdar://problem/3283666> No need for multiple machines to all be sending the same queries
540 Revision 1.180 2003/06/07 06:31:07 cheshire
541 Create little four-line helper function "FindIdenticalRecordInCache()"
543 Revision 1.179 2003/06/07 06:28:13 cheshire
544 For clarity, change name of "DNSQuestion q" to "DNSQuestion pktq"
546 Revision 1.178 2003/06/07 06:25:12 cheshire
549 Revision 1.177 2003/06/07 04:50:53 cheshire
550 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
552 Revision 1.176 2003/06/07 04:33:26 cheshire
553 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
554 Minor change: Increment/decrement logic for q->CurrentAnswers should be in
555 CacheRecordAdd() and CacheRecordRmv(), not AnswerQuestionWithResourceRecord()
557 Revision 1.175 2003/06/07 04:11:52 cheshire
558 Minor changes to comments and debug messages
560 Revision 1.174 2003/06/07 01:46:38 cheshire
561 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
563 Revision 1.173 2003/06/07 01:22:13 cheshire
564 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
566 Revision 1.172 2003/06/07 00:59:42 cheshire
567 <rdar://problem/3283454> Need some randomness to spread queries on the network
569 Revision 1.171 2003/06/06 21:41:10 cheshire
570 For consistency, mDNS_StopQuery() should return an mStatus result, just like all the other mDNSCore routines
572 Revision 1.170 2003/06/06 21:38:55 cheshire
573 Renamed 'NewData' as 'FreshData' (The data may not be new data, just a refresh of data that we
574 already had in our cache. This refreshes our TTL on the data, but the data itself stays the same.)
576 Revision 1.169 2003/06/06 21:35:55 cheshire
577 Fix mis-named macro: GetRRHostNameTarget is really GetRRDomainNameTarget
578 (the target is a domain name, but not necessarily a host name)
580 Revision 1.168 2003/06/06 21:33:31 cheshire
581 Instead of using (mDNSPlatformOneSecond/2) all over the place, define a constant "InitialQuestionInterval"
583 Revision 1.167 2003/06/06 21:30:42 cheshire
584 <rdar://problem/3282962> Don't delay queries for shared record types
586 Revision 1.166 2003/06/06 17:20:14 cheshire
587 For clarity, rename question fields name/rrtype/rrclass as qname/qtype/qclass
588 (Global search-and-replace; no functional change to code execution.)
590 Revision 1.165 2003/06/04 02:53:21 cheshire
591 Add some "#pragma warning" lines so it compiles clean on Microsoft compilers
593 Revision 1.164 2003/06/04 01:25:33 cheshire
594 <rdar://problem/3274950> Cannot perform multi-packet known-answer suppression messages
595 Display time interval between first and subsequent queries
597 Revision 1.163 2003/06/03 19:58:14 cheshire
598 <rdar://problem/3277665> mDNS_DeregisterService() fixes:
599 When forcibly deregistering after a conflict, ensure we don't send an incorrect goodbye packet.
600 Guard against a couple of possible mDNS_DeregisterService() race conditions.
602 Revision 1.162 2003/06/03 19:30:39 cheshire
603 Minor addition refinements for
604 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
606 Revision 1.161 2003/06/03 18:29:03 cheshire
607 Minor changes to comments and debugf() messages
609 Revision 1.160 2003/06/03 05:02:16 cheshire
610 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
612 Revision 1.159 2003/06/03 03:31:57 cheshire
613 <rdar://problem/3277033> False self-conflict when there are duplicate registrations on one machine
615 Revision 1.158 2003/06/02 22:57:09 cheshire
616 Minor clarifying changes to comments and log messages;
617 IdenticalResourceRecordAnyInterface() is really more accurately called just IdenticalResourceRecord()
619 Revision 1.157 2003/05/31 00:09:49 cheshire
620 <rdar://problem/3274862> Add ability to discover what services are on a network
622 Revision 1.156 2003/05/30 23:56:49 cheshire
623 <rdar://problem/3274847> Crash after error in mDNS_RegisterService()
624 Need to set "sr->Extras = mDNSNULL" before returning
626 Revision 1.155 2003/05/30 23:48:00 cheshire
627 <rdar://problem/3274832> Announcements not properly grouped
628 Due to inconsistent setting of rr->LastAPTime at different places in the
629 code, announcements were not properly grouped into a single packet.
630 Fixed by creating a single routine called InitializeLastAPTime().
632 Revision 1.154 2003/05/30 23:38:14 cheshire
633 <rdar://problem/3274814> Fix error in IPv6 reverse-mapping PTR records
634 Wrote buffer[32] where it should have said buffer[64]
636 Revision 1.153 2003/05/30 19:10:56 cheshire
637 <rdar://problem/3274153> ConstructServiceName needs to be more restrictive
639 Revision 1.152 2003/05/29 22:39:16 cheshire
640 <rdar://problem/3273209> Don't truncate strings in the middle of a UTF-8 character
642 Revision 1.151 2003/05/29 06:35:42 cheshire
643 <rdar://problem/3272221> mDNSCoreReceiveResponse() purging wrong record
645 Revision 1.150 2003/05/29 06:25:45 cheshire
646 <rdar://problem/3272218> Need to call CheckCacheExpiration() *before* AnswerNewQuestion()
648 Revision 1.149 2003/05/29 06:18:39 cheshire
649 <rdar://problem/3272217> Split AnswerLocalQuestions into CacheRecordAdd and CacheRecordRmv
651 Revision 1.148 2003/05/29 06:11:34 cheshire
652 <rdar://problem/3272214> Report if there appear to be too many "Resolve" callbacks
654 Revision 1.147 2003/05/29 06:01:18 cheshire
655 Change some debugf() calls to LogMsg() calls to help with debugging
657 Revision 1.146 2003/05/28 21:00:44 cheshire
658 Re-enable "immediate answer burst" debugf message
660 Revision 1.145 2003/05/28 20:57:44 cheshire
661 <rdar://problem/3271550> mDNSResponder reports "Cannot perform multi-packet
662 known-answer suppression ..." This is a known issue caused by a bug in the OS X 10.2
663 version of mDNSResponder, so for now we should suppress this warning message.
665 Revision 1.144 2003/05/28 18:05:12 cheshire
666 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
667 Fix silly mistake: old logic allowed "TDP" and "UCP" as valid names
669 Revision 1.143 2003/05/28 04:31:29 cheshire
670 <rdar://problem/3270733> mDNSResponder not sending probes at the prescribed time
672 Revision 1.142 2003/05/28 03:13:07 cheshire
673 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
674 Require that the transport protocol be _udp or _tcp
676 Revision 1.141 2003/05/28 02:19:12 cheshire
677 <rdar://problem/3270634> Misleading messages generated by iChat
678 Better fix: Only generate the log message for queries where the TC bit is set.
680 Revision 1.140 2003/05/28 01:55:24 cheshire
681 Minor change to log messages
683 Revision 1.139 2003/05/28 01:52:51 cheshire
684 <rdar://problem/3270634> Misleading messages generated by iChat
686 Revision 1.138 2003/05/27 22:35:00 cheshire
687 <rdar://problem/3270277> mDNS_RegisterInterface needs to retrigger questions
689 Revision 1.137 2003/05/27 20:04:33 cheshire
690 <rdar://problem/3269900> mDNSResponder crash in mDNS_vsnprintf()
692 Revision 1.136 2003/05/27 18:50:07 cheshire
693 <rdar://problem/3269768> mDNS_StartResolveService doesn't inform client of port number changes
695 Revision 1.135 2003/05/26 04:57:28 cheshire
696 <rdar://problem/3268953> Delay queries when there are already answers in the cache
698 Revision 1.134 2003/05/26 04:54:54 cheshire
699 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
700 Accidentally deleted '%' case from the switch statement
702 Revision 1.133 2003/05/26 03:21:27 cheshire
703 Tidy up address structure naming:
704 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
705 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
706 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
708 Revision 1.132 2003/05/26 03:01:26 cheshire
709 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
711 Revision 1.131 2003/05/26 00:42:05 cheshire
712 <rdar://problem/3268876> Temporarily include mDNSResponder version in packets
714 Revision 1.130 2003/05/24 16:39:48 cheshire
715 <rdar://problem/3268631> SendResponses also needs to handle multihoming better
717 Revision 1.129 2003/05/23 02:15:37 cheshire
718 Fixed misleading use of the term "duplicate suppression" where it should have
719 said "known answer suppression". (Duplicate answer suppression is something
720 different, and duplicate question suppression is yet another thing, so the use
721 of the completely vague term "duplicate suppression" was particularly bad.)
723 Revision 1.128 2003/05/23 01:55:13 cheshire
724 <rdar://problem/3267127> After name change, mDNSResponder needs to re-probe for name uniqueness
726 Revision 1.127 2003/05/23 01:02:15 ksekar
727 Bug #: <rdar://problem/3032577>: mDNSResponder needs to include unique id in default name
729 Revision 1.126 2003/05/22 02:29:22 cheshire
730 <rdar://problem/2984918> SendQueries needs to handle multihoming better
731 Complete rewrite of SendQueries. Works much better now :-)
733 Revision 1.125 2003/05/22 01:50:45 cheshire
734 Fix warnings, and improve log messages
736 Revision 1.124 2003/05/22 01:41:50 cheshire
737 DiscardDeregistrations doesn't need InterfaceID parameter
739 Revision 1.123 2003/05/22 01:38:55 cheshire
740 Change bracketing of #pragma mark
742 Revision 1.122 2003/05/21 19:59:04 cheshire
743 <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
744 Minor refinements; make sure we don't truncate in the middle of a multi-byte UTF-8 character
746 Revision 1.121 2003/05/21 17:54:07 ksekar
747 Bug #: <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
748 New rename behavior - domain name "foo" becomes "foo--2" on conflict, richtext name becomes "foo (2)"
750 Revision 1.120 2003/05/19 22:14:14 ksekar
751 <rdar://problem/3162914> mDNS probe denials/conflicts not detected unless conflict is of the same type
753 Revision 1.119 2003/05/16 01:34:10 cheshire
756 Revision 1.118 2003/05/14 18:48:40 cheshire
757 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
758 More minor refinements:
759 CFSocket.c needs to do *all* its mDNS_DeregisterInterface calls before freeing memory
760 mDNS_DeregisterInterface revalidates cache record when *any* representative of an interface goes away
762 Revision 1.117 2003/05/14 07:08:36 cheshire
763 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
764 Previously, when there was any network configuration change, mDNSResponder
765 would tear down the entire list of active interfaces and start again.
766 That was very disruptive, and caused the entire cache to be flushed,
767 and caused lots of extra network traffic. Now it only removes interfaces
768 that have really gone, and only adds new ones that weren't there before.
770 Revision 1.116 2003/05/14 06:51:56 cheshire
771 <rdar://problem/3027144> Rendezvous doesn't refresh server info if changed during sleep
773 Revision 1.115 2003/05/14 06:44:31 cheshire
774 Improve debugging message
776 Revision 1.114 2003/05/07 01:47:03 cheshire
777 <rdar://problem/3250330> Also protect against NULL domainlabels
779 Revision 1.113 2003/05/07 00:28:18 cheshire
780 <rdar://problem/3250330> Need to make mDNSResponder more defensive against bad clients
782 Revision 1.112 2003/05/06 00:00:46 cheshire
783 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
785 Revision 1.111 2003/05/05 23:42:08 cheshire
786 <rdar://problem/3245631> Resolves never succeed
787 Was setting "rr->LastAPTime = timenow - rr->LastAPTime"
788 instead of "rr->LastAPTime = timenow - rr->ThisAPInterval"
790 Revision 1.110 2003/04/30 21:09:59 cheshire
791 <rdar://problem/3244727> mDNS_vsnprintf needs to be more defensive against invalid domain names
793 Revision 1.109 2003/04/26 02:41:56 cheshire
794 <rdar://problem/3241281> Change timenow from a local variable to a structure member
796 Revision 1.108 2003/04/25 01:45:56 cheshire
797 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
799 Revision 1.107 2003/04/25 00:41:31 cheshire
800 <rdar://problem/3239912> Create single routine PurgeCacheResourceRecord(), to avoid bugs in future
802 Revision 1.106 2003/04/22 03:14:45 cheshire
803 <rdar://problem/3232229> Include Include instrumented mDNSResponder in panther now
805 Revision 1.105 2003/04/22 01:07:43 cheshire
806 <rdar://problem/3176248> DNSServiceRegistrationUpdateRecord should support a default ttl
807 If TTL parameter is zero, leave record TTL unchanged
809 Revision 1.104 2003/04/21 19:15:52 cheshire
810 Fix some compiler warnings
812 Revision 1.103 2003/04/19 02:26:35 cheshire
813 Bug #: <rdar://problem/3233804> Incorrect goodbye packet after conflict
815 Revision 1.102 2003/04/17 03:06:28 cheshire
816 Bug #: <rdar://problem/3231321> No need to query again when a service goes away
817 Set UnansweredQueries to 2 when receiving a "goodbye" packet
819 Revision 1.101 2003/04/15 20:58:31 jgraessl
821 Added a hash to lookup records in the cache.
823 Revision 1.100 2003/04/15 18:53:14 cheshire
824 Bug #: <rdar://problem/3229064> Bug in ScheduleNextTask
825 mDNS.c 1.94 incorrectly combined two "if" statements into one.
827 Revision 1.99 2003/04/15 18:09:13 jgraessl
829 Reviewed by: Stuart Cheshire
830 Added code to keep track of when the next cache item will expire so we can
831 call TidyRRCache only when necessary.
833 Revision 1.98 2003/04/03 03:43:55 cheshire
834 <rdar://problem/3216837> Off-by-one error in probe rate limiting
836 Revision 1.97 2003/04/02 01:48:17 cheshire
837 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
838 Additional fix pointed out by Josh:
839 Also set ProbeFailTime when incrementing NumFailedProbes when resetting a record back to probing state
841 Revision 1.96 2003/04/01 23:58:55 cheshire
842 Minor comment changes
844 Revision 1.95 2003/04/01 23:46:05 cheshire
845 <rdar://problem/3214832> mDNSResponder can get stuck in infinite loop after many location cycles
846 mDNS_DeregisterInterface() flushes the RR cache by marking all records received on that interface
847 to expire in one second. However, if a mDNS_StartResolveService() call is made in that one-second
848 window, it can get an SRV answer from one of those soon-to-be-deleted records, resulting in
849 FoundServiceInfoSRV() making an interface-specific query on the interface that was just removed.
851 Revision 1.94 2003/03/29 01:55:19 cheshire
852 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
853 Solution: Major cleanup of packet timing and conflict handling rules
855 Revision 1.93 2003/03/28 01:54:36 cheshire
856 Minor tidyup of IPv6 (AAAA) code
858 Revision 1.92 2003/03/27 03:30:55 cheshire
859 <rdar://problem/3210018> Name conflicts not handled properly, resulting in memory corruption, and eventual crash
860 Problem was that HostNameCallback() was calling mDNS_DeregisterInterface(), which is not safe in a callback
862 1. Make mDNS_DeregisterInterface() safe to call from a callback
863 2. Make HostNameCallback() use mDNS_DeadvertiseInterface() instead
864 (it never really needed to deregister the interface at all)
866 Revision 1.91 2003/03/15 04:40:36 cheshire
867 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
869 Revision 1.90 2003/03/14 20:26:37 cheshire
870 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
872 Revision 1.89 2003/03/12 19:57:50 cheshire
873 Fixed typo in debug message
875 Revision 1.88 2003/03/12 00:17:44 cheshire
876 <rdar://problem/3195426> GetFreeCacheRR needs to be more willing to throw away recent records
878 Revision 1.87 2003/03/11 01:27:20 cheshire
879 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
881 Revision 1.86 2003/03/06 20:44:33 cheshire
884 Revision 1.85 2003/03/05 03:38:35 cheshire
885 Bug #: 3185731 Bogus error message in console: died or deallocated, but no record of client can be found!
886 Fixed by leaving client in list after conflict, until client explicitly deallocates
888 Revision 1.84 2003/03/05 01:27:30 cheshire
889 Bug #: 3185482 Different TTL for multicast versus unicast responses
890 When building unicast responses, record TTLs are capped to 10 seconds
892 Revision 1.83 2003/03/04 23:48:52 cheshire
893 Bug #: 3188865 Double probes after wake from sleep
894 Don't reset record type to kDNSRecordTypeUnique if record is DependentOn another
896 Revision 1.82 2003/03/04 23:38:29 cheshire
897 Bug #: 3099194 mDNSResponder needs performance improvements
898 Only set rr->CRActiveQuestion to point to the
899 currently active representative of a question set
901 Revision 1.81 2003/02/21 03:35:34 cheshire
902 Bug #: 3179007 mDNSResponder needs to include AAAA records in additional answer section
904 Revision 1.80 2003/02/21 02:47:53 cheshire
905 Bug #: 3099194 mDNSResponder needs performance improvements
906 Several places in the code were calling CacheRRActive(), which searched the entire
907 question list every time, to see if this cache resource record answers any question.
908 Instead, we now have a field "CRActiveQuestion" in the resource record structure
910 Revision 1.79 2003/02/21 01:54:07 cheshire
911 Bug #: 3099194 mDNSResponder needs performance improvements
912 Switched to using new "mDNS_Execute" model (see "Implementer Notes.txt")
914 Revision 1.78 2003/02/20 06:48:32 cheshire
915 Bug #: 3169535 Xserve RAID needs to do interface-specific registrations
916 Reviewed by: Josh Graessley, Bob Bradley
918 Revision 1.77 2003/01/31 03:35:59 cheshire
919 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
920 When there were *two* active questions in the list, they were incorrectly
921 finding *each other* and *both* being marked as duplicates of another question
923 Revision 1.76 2003/01/29 02:46:37 cheshire
925 A physical interface is identified solely by its InterfaceID (not by IP and type).
926 On a given InterfaceID, mDNSCore may send both v4 and v6 multicasts.
927 In cases where the requested outbound protocol (v4 or v6) is not supported on
928 that InterfaceID, the platform support layer should simply discard that packet.
930 Revision 1.75 2003/01/29 01:47:40 cheshire
931 Rename 'Active' to 'CRActive' or 'InterfaceActive' for improved clarity
933 Revision 1.74 2003/01/28 05:26:25 cheshire
934 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
935 Add 'Active' flag for interfaces
937 Revision 1.73 2003/01/28 03:45:12 cheshire
938 Fixed missing "not" in "!mDNSAddrIsDNSMulticast(dstaddr)"
940 Revision 1.72 2003/01/28 01:49:48 cheshire
941 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
942 FindDuplicateQuestion() was incorrectly finding the question itself in the list,
943 and incorrectly marking it as a duplicate (of itself), so that it became inactive.
945 Revision 1.71 2003/01/28 01:41:44 cheshire
946 Bug #: 3153091 Race condition when network change causes bad stuff
947 When an interface goes away, interface-specific questions on that interface become orphaned.
948 Orphan questions cause HaveQueries to return true, but there's no interface to send them on.
949 Fix: mDNS_DeregisterInterface() now calls DeActivateInterfaceQuestions()
951 Revision 1.70 2003/01/23 19:00:20 cheshire
952 Protect against infinite loops in mDNS_Execute
954 Revision 1.69 2003/01/21 22:56:32 jgraessl
955 Bug #: 3124348 service name changes are not properly handled
956 Submitted by: Stuart Cheshire
957 Reviewed by: Joshua Graessley
958 Applying changes for 3124348 to main branch. 3124348 changes went in to a
961 Revision 1.68 2003/01/17 04:09:27 cheshire
962 Bug #: 3141038 mDNSResponder Resolves are unreliable on multi-homed hosts
964 Revision 1.67 2003/01/17 03:56:45 cheshire
965 Default 24-hour TTL is far too long. Changing to two hours.
967 Revision 1.66 2003/01/13 23:49:41 jgraessl
968 Merged changes for the following fixes in to top of tree:
969 3086540 computer name changes not handled properly
970 3124348 service name changes are not properly handled
971 3124352 announcements sent in pairs, failing chattiness test
973 Revision 1.65 2002/12/23 22:13:28 jgraessl
974 Reviewed by: Stuart Cheshire
975 Initial IPv6 support for mDNSResponder.
977 Revision 1.64 2002/11/26 20:49:06 cheshire
978 Bug #: 3104543 RFC 1123 allows the first character of a name label to be either a letter or a digit
980 Revision 1.63 2002/09/21 20:44:49 zarzycki
983 Revision 1.62 2002/09/20 03:25:37 cheshire
984 Fix some compiler warnings
986 Revision 1.61 2002/09/20 01:05:24 cheshire
987 Don't kill the Extras list in mDNS_DeregisterService()
989 Revision 1.60 2002/09/19 23:47:35 cheshire
990 Added mDNS_RegisterNoSuchService() function for assertion of non-existance
991 of a particular named service
993 Revision 1.59 2002/09/19 21:25:34 cheshire
994 mDNS_snprintf() doesn't need to be in a separate file
996 Revision 1.58 2002/09/19 04:20:43 cheshire
997 Remove high-ascii characters that confuse some systems
999 Revision 1.57 2002/09/17 01:07:08 cheshire
1000 Change mDNS_AdvertiseLocalAddresses to be a parameter to mDNS_Init()
1002 Revision 1.56 2002/09/16 19:44:17 cheshire
1003 Merge in license terms from Quinn's copy, in preparation for Darwin release
1006 #define TEST_LOCALONLY_FOR_EVERYTHING 0
1008 #include "mDNSClientAPI.h" // Defines the interface provided to the client layer above
1009 #include "mDNSPlatformFunctions.h" // Defines the interface required of the supporting layer below
1011 // Disable certain benign warnings with Microsoft compilers
1012 #if(defined(_MSC_VER))
1013 // Disable "conditional expression is constant" warning for debug macros.
1014 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
1015 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
1016 #pragma warning(disable:4127)
1018 // Disable "const object should be initialized"
1019 // We know that static/globals are defined to be zeroed in ANSI C, and to avoid this warning would require some
1020 // *really* ugly chunk of zeroes and curly braces to initialize zeroRR and mDNSprintf_format_default to all zeroes
1021 #pragma warning(disable:4132)
1023 // Disable "assignment within conditional expression".
1024 // Other compilers understand the convention that if you place the assignment expression within an extra pair
1025 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
1026 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
1027 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
1028 #pragma warning(disable:4706)
1031 // ***************************************************************************
1032 #if COMPILER_LIKES_PRAGMA_MARK
1033 #pragma mark - DNS Protocol Constants
1038 kDNSFlag0_QR_Mask
= 0x80, // Query or response?
1039 kDNSFlag0_QR_Query
= 0x00,
1040 kDNSFlag0_QR_Response
= 0x80,
1042 kDNSFlag0_OP_Mask
= 0x78, // Operation type
1043 kDNSFlag0_OP_StdQuery
= 0x00,
1044 kDNSFlag0_OP_Iquery
= 0x08,
1045 kDNSFlag0_OP_Status
= 0x10,
1046 kDNSFlag0_OP_Unused3
= 0x18,
1047 kDNSFlag0_OP_Notify
= 0x20,
1048 kDNSFlag0_OP_Update
= 0x28,
1050 kDNSFlag0_QROP_Mask
= kDNSFlag0_QR_Mask
| kDNSFlag0_OP_Mask
,
1052 kDNSFlag0_AA
= 0x04, // Authoritative Answer?
1053 kDNSFlag0_TC
= 0x02, // Truncated?
1054 kDNSFlag0_RD
= 0x01, // Recursion Desired?
1055 kDNSFlag1_RA
= 0x80, // Recursion Available?
1057 kDNSFlag1_Zero
= 0x40, // Reserved; must be zero
1058 kDNSFlag1_AD
= 0x20, // Authentic Data [RFC 2535]
1059 kDNSFlag1_CD
= 0x10, // Checking Disabled [RFC 2535]
1061 kDNSFlag1_RC
= 0x0F, // Response code
1062 kDNSFlag1_RC_NoErr
= 0x00,
1063 kDNSFlag1_RC_FmtErr
= 0x01,
1064 kDNSFlag1_RC_SrvErr
= 0x02,
1065 kDNSFlag1_RC_NXDomain
= 0x03,
1066 kDNSFlag1_RC_NotImpl
= 0x04,
1067 kDNSFlag1_RC_Refused
= 0x05,
1068 kDNSFlag1_RC_YXDomain
= 0x06,
1069 kDNSFlag1_RC_YXRRSet
= 0x07,
1070 kDNSFlag1_RC_NXRRSet
= 0x08,
1071 kDNSFlag1_RC_NotAuth
= 0x09,
1072 kDNSFlag1_RC_NotZone
= 0x0A
1075 // ***************************************************************************
1076 #if COMPILER_LIKES_PRAGMA_MARK
1078 #pragma mark - Program Constants
1081 mDNSexport
const ResourceRecord zeroRR
;
1082 mDNSexport
const mDNSIPPort zeroIPPort
= { { 0 } };
1083 mDNSexport
const mDNSv4Addr zeroIPAddr
= { { 0 } };
1084 mDNSexport
const mDNSv6Addr zerov6Addr
= { { 0 } };
1085 mDNSexport
const mDNSv4Addr onesIPv4Addr
= { { 255, 255, 255, 255 } };
1086 mDNSexport
const mDNSv6Addr onesIPv6Addr
= { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } };
1087 mDNSlocal
const mDNSAddr zeroAddr
= { mDNSAddrType_None
, {{{ 0 }}} };
1089 mDNSexport
const mDNSInterfaceID mDNSInterface_Any
= { 0 };
1090 mDNSlocal
const mDNSInterfaceID mDNSInterfaceMark
= { (mDNSInterfaceID
)~0 };
1092 #define UnicastDNSPortAsNumber 53
1093 #define MulticastDNSPortAsNumber 5353
1094 mDNSexport
const mDNSIPPort UnicastDNSPort
= { { UnicastDNSPortAsNumber
>> 8, UnicastDNSPortAsNumber
& 0xFF } };
1095 mDNSexport
const mDNSIPPort MulticastDNSPort
= { { MulticastDNSPortAsNumber
>> 8, MulticastDNSPortAsNumber
& 0xFF } };
1096 mDNSexport
const mDNSv4Addr AllDNSAdminGroup
= { { 239, 255, 255, 251 } };
1097 mDNSexport
const mDNSv4Addr AllDNSLinkGroup
= { { 224, 0, 0, 251 } };
1098 mDNSexport
const mDNSv6Addr AllDNSLinkGroupv6
= { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } };
1099 mDNSexport
const mDNSAddr AllDNSLinkGroup_v4
= { mDNSAddrType_IPv4
, { { { 224, 0, 0, 251 } } } };
1100 mDNSexport
const mDNSAddr AllDNSLinkGroup_v6
= { mDNSAddrType_IPv6
, { { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } } } };
1102 static const mDNSOpaque16 zeroID
= { { 0, 0 } };
1103 static const mDNSOpaque16 QueryFlags
= { { kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
, 0 } };
1104 static const mDNSOpaque16 ResponseFlags
= { { kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
| kDNSFlag0_AA
, 0 } };
1105 #define zeroDomainNamePtr ((domainname*)"")
1107 // Any records bigger than this are considered 'large' records
1108 #define SmallRecordLimit 1024
1110 #define kDefaultTTLforUnique 240
1111 #define kDefaultTTLforShared (2*3600)
1113 #define kMaxUpdateCredits 10
1115 static const char *const mDNS_DomainTypeNames
[] =
1117 "_browse._dns-sd._udp.local.",
1118 "_default._browse._dns-sd._udp.local.",
1119 "_register._dns-sd._udp.local.",
1120 "_default._register._dns-sd._udp.local."
1123 #define AssignDomainName(DST, SRC) mDNSPlatformMemCopy((SRC).c, (DST).c, DomainNameLength(&(SRC)))
1125 // ***************************************************************************
1126 #if COMPILER_LIKES_PRAGMA_MARK
1128 #pragma mark - Specialized mDNS version of vsnprintf
1131 static const struct mDNSprintf_format
1133 unsigned leftJustify
: 1;
1134 unsigned forceSign
: 1;
1135 unsigned zeroPad
: 1;
1136 unsigned havePrecision
: 1;
1140 char sign
; // +, - or space
1141 unsigned int fieldWidth
;
1142 unsigned int precision
;
1143 } mDNSprintf_format_default
;
1145 mDNSexport mDNSu32
mDNS_vsnprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, va_list arg
)
1147 mDNSu32 nwritten
= 0;
1149 buflen
--; // Pre-reserve one space in the buffer for the terminating nul
1151 for (c
= *fmt
; c
!= 0; c
= *++fmt
)
1155 *sbuffer
++ = (char)c
;
1156 if (++nwritten
>= buflen
) goto exit
;
1160 unsigned int i
=0, j
;
1161 // The mDNS Vsprintf Argument Conversion Buffer is used as a temporary holding area for
1162 // generating decimal numbers, hexdecimal numbers, IP addresses, domain name strings, etc.
1163 // The size needs to be enough for a 256-byte domain name plus some error text.
1164 #define mDNS_VACB_Size 300
1165 char mDNS_VACB
[mDNS_VACB_Size
];
1166 #define mDNS_VACB_Lim (&mDNS_VACB[mDNS_VACB_Size])
1167 #define mDNS_VACB_Remain(s) ((mDNSu32)(mDNS_VACB_Lim - s))
1168 char *s
= mDNS_VACB_Lim
, *digits
;
1169 struct mDNSprintf_format F
= mDNSprintf_format_default
;
1171 while (1) // decode flags
1174 if (c
== '-') F
.leftJustify
= 1;
1175 else if (c
== '+') F
.forceSign
= 1;
1176 else if (c
== ' ') F
.sign
= ' ';
1177 else if (c
== '#') F
.altForm
++;
1178 else if (c
== '0') F
.zeroPad
= 1;
1182 if (c
== '*') // decode field width
1184 int f
= va_arg(arg
, int);
1185 if (f
< 0) { f
= -f
; F
.leftJustify
= 1; }
1186 F
.fieldWidth
= (unsigned int)f
;
1191 for (; c
>= '0' && c
<= '9'; c
= *++fmt
)
1192 F
.fieldWidth
= (10 * F
.fieldWidth
) + (c
- '0');
1195 if (c
== '.') // decode precision
1197 if ((c
= *++fmt
) == '*')
1198 { F
.precision
= va_arg(arg
, unsigned int); c
= *++fmt
; }
1199 else for (; c
>= '0' && c
<= '9'; c
= *++fmt
)
1200 F
.precision
= (10 * F
.precision
) + (c
- '0');
1201 F
.havePrecision
= 1;
1204 if (F
.leftJustify
) F
.zeroPad
= 0;
1207 switch (c
) // perform appropriate conversion
1210 case 'h' : F
.hSize
= 1; c
= *++fmt
; goto conv
;
1211 case 'l' : // fall through
1212 case 'L' : F
.lSize
= 1; c
= *++fmt
; goto conv
;
1214 case 'i' : if (F
.lSize
) n
= (unsigned long)va_arg(arg
, long);
1215 else n
= (unsigned long)va_arg(arg
, int);
1216 if (F
.hSize
) n
= (short) n
;
1217 if ((long) n
< 0) { n
= (unsigned long)-(long)n
; F
.sign
= '-'; }
1218 else if (F
.forceSign
) F
.sign
= '+';
1220 case 'u' : if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1221 else n
= va_arg(arg
, unsigned int);
1222 if (F
.hSize
) n
= (unsigned short) n
;
1225 decimal
: if (!F
.havePrecision
)
1229 F
.precision
= F
.fieldWidth
;
1230 if (F
.sign
) --F
.precision
;
1232 if (F
.precision
< 1) F
.precision
= 1;
1234 if (F
.precision
> mDNS_VACB_Size
- 1)
1235 F
.precision
= mDNS_VACB_Size
- 1;
1236 for (i
= 0; n
; n
/= 10, i
++) *--s
= (char)(n
% 10 + '0');
1237 for (; i
< F
.precision
; i
++) *--s
= '0';
1238 if (F
.sign
) { *--s
= F
.sign
; i
++; }
1241 case 'o' : if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1242 else n
= va_arg(arg
, unsigned int);
1243 if (F
.hSize
) n
= (unsigned short) n
;
1244 if (!F
.havePrecision
)
1246 if (F
.zeroPad
) F
.precision
= F
.fieldWidth
;
1247 if (F
.precision
< 1) F
.precision
= 1;
1249 if (F
.precision
> mDNS_VACB_Size
- 1)
1250 F
.precision
= mDNS_VACB_Size
- 1;
1251 for (i
= 0; n
; n
/= 8, i
++) *--s
= (char)(n
% 8 + '0');
1252 if (F
.altForm
&& i
&& *s
!= '0') { *--s
= '0'; i
++; }
1253 for (; i
< F
.precision
; i
++) *--s
= '0';
1257 unsigned char *a
= va_arg(arg
, unsigned char *);
1258 if (!a
) { static char emsg
[] = "<<NULL>>"; s
= emsg
; i
= sizeof(emsg
)-1; }
1261 unsigned short *w
= (unsigned short *)a
;
1262 s
= mDNS_VACB
; // Adjust s to point to the start of the buffer, not the end
1265 mDNSAddr
*ip
= (mDNSAddr
*)a
;
1266 a
= (unsigned char *)&ip
->ip
.v4
;
1267 w
= (unsigned short *)&ip
->ip
.v6
;
1270 case mDNSAddrType_IPv4
: F
.precision
= 4; break;
1271 case mDNSAddrType_IPv6
: F
.precision
= 16; break;
1272 default: F
.precision
= 0; break;
1275 switch (F
.precision
)
1277 case 4: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%d.%d.%d.%d",
1278 a
[0], a
[1], a
[2], a
[3]); break;
1279 case 6: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%02X:%02X:%02X:%02X:%02X:%02X",
1280 a
[0], a
[1], a
[2], a
[3], a
[4], a
[5]); break;
1281 case 16: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X",
1282 w
[0], w
[1], w
[2], w
[3], w
[4], w
[5], w
[6], w
[7]); break;
1283 default: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%s", "<< ERROR: Must specify address size "
1284 "(i.e. %.4a=IPv4, %.6a=Ethernet, %.16a=IPv6) >>"); break;
1290 case 'p' : F
.havePrecision
= F
.lSize
= 1;
1292 case 'X' : digits
= "0123456789ABCDEF";
1294 case 'x' : digits
= "0123456789abcdef";
1295 hexadecimal
:if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1296 else n
= va_arg(arg
, unsigned int);
1297 if (F
.hSize
) n
= (unsigned short) n
;
1298 if (!F
.havePrecision
)
1302 F
.precision
= F
.fieldWidth
;
1303 if (F
.altForm
) F
.precision
-= 2;
1305 if (F
.precision
< 1) F
.precision
= 1;
1307 if (F
.precision
> mDNS_VACB_Size
- 1)
1308 F
.precision
= mDNS_VACB_Size
- 1;
1309 for (i
= 0; n
; n
/= 16, i
++) *--s
= digits
[n
% 16];
1310 for (; i
< F
.precision
; i
++) *--s
= '0';
1311 if (F
.altForm
) { *--s
= (char)c
; *--s
= '0'; i
+= 2; }
1314 case 'c' : *--s
= (char)va_arg(arg
, int); i
= 1; break;
1316 case 's' : s
= va_arg(arg
, char *);
1317 if (!s
) { static char emsg
[] = "<<NULL>>"; s
= emsg
; i
= sizeof(emsg
)-1; }
1318 else switch (F
.altForm
)
1320 case 0: { char *a
=s
; i
=0; while(*a
++) i
++; break; } // C string
1321 case 1: i
= (unsigned char) *s
++; break; // Pascal string
1322 case 2: { // DNS label-sequence name
1323 unsigned char *a
= (unsigned char *)s
;
1324 s
= mDNS_VACB
; // Adjust s to point to the start of the buffer, not the end
1325 if (*a
== 0) *s
++ = '.'; // Special case for root DNS name
1328 if (*a
> 63) { s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "<<INVALID LABEL LENGTH %u>>", *a
); break; }
1329 if (s
+ *a
>= &mDNS_VACB
[254]) { s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "<<NAME TOO LONG>>"); break; }
1330 s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "%#s.", a
);
1333 i
= (mDNSu32
)(s
- mDNS_VACB
);
1334 s
= mDNS_VACB
; // Reset s back to the start of the buffer
1338 if (F
.havePrecision
&& i
> F
.precision
) // Make sure we don't truncate in the middle of a UTF-8 character
1339 { i
= F
.precision
; while (i
>0 && (s
[i
] & 0xC0) == 0x80) i
--; }
1342 case 'n' : s
= va_arg(arg
, char *);
1343 if (F
.hSize
) * (short *) s
= (short)nwritten
;
1344 else if (F
.lSize
) * (long *) s
= (long)nwritten
;
1345 else * (int *) s
= (int)nwritten
;
1348 default: s
= mDNS_VACB
;
1349 i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "<<UNKNOWN FORMAT CONVERSION CODE %%%c>>", c
);
1351 case '%' : *sbuffer
++ = (char)c
;
1352 if (++nwritten
>= buflen
) goto exit
;
1356 if (i
< F
.fieldWidth
&& !F
.leftJustify
) // Pad on the left
1359 if (++nwritten
>= buflen
) goto exit
;
1360 } while (i
< --F
.fieldWidth
);
1362 if (i
> buflen
- nwritten
) // Make sure we don't truncate in the middle of a UTF-8 character
1363 { i
= buflen
- nwritten
; while (i
>0 && (s
[i
] & 0xC0) == 0x80) i
--; }
1364 for (j
=0; j
<i
; j
++) *sbuffer
++ = *s
++; // Write the converted result
1366 if (nwritten
>= buflen
) goto exit
;
1368 for (; i
< F
.fieldWidth
; i
++) // Pad on the right
1371 if (++nwritten
>= buflen
) goto exit
;
1380 mDNSexport mDNSu32
mDNS_snprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, ...)
1386 length
= mDNS_vsnprintf(sbuffer
, buflen
, fmt
, ptr
);
1392 // ***************************************************************************
1393 #if COMPILER_LIKES_PRAGMA_MARK
1395 #pragma mark - General Utility Functions
1398 mDNSexport
char *DNSTypeName(mDNSu16 rrtype
)
1402 case kDNSType_A
: return("Addr");
1403 case kDNSType_CNAME
:return("CNAME");
1404 case kDNSType_NULL
: return("NULL");
1405 case kDNSType_PTR
: return("PTR");
1406 case kDNSType_HINFO
:return("HINFO");
1407 case kDNSType_TXT
: return("TXT");
1408 case kDNSType_AAAA
: return("AAAA");
1409 case kDNSType_SRV
: return("SRV");
1410 case kDNSQType_ANY
: return("ANY");
1412 static char buffer
[16];
1413 mDNS_snprintf(buffer
, sizeof(buffer
), "(%d)", rrtype
);
1419 mDNSexport
char *GetRRDisplayString_rdb(mDNS
*const m
, const ResourceRecord
*rr
, RDataBody
*rd
)
1421 char *ptr
= m
->MsgBuffer
;
1422 mDNSu32 length
= mDNS_snprintf(m
->MsgBuffer
, 79, "%4d %##s %s ", rr
->rdlength
, rr
->name
.c
, DNSTypeName(rr
->rrtype
));
1425 case kDNSType_A
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%.4a", &rd
->ip
); break;
1426 case kDNSType_CNAME
:// Same as PTR
1427 case kDNSType_PTR
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%##s", &rd
->name
); break;
1428 case kDNSType_HINFO
:// Display this the same as TXT (just show first string)
1429 case kDNSType_TXT
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%#s", rd
->txt
.c
); break;
1430 case kDNSType_AAAA
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%.16a", &rd
->ipv6
); break;
1431 case kDNSType_SRV
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%##s", &rd
->srv
.target
); break;
1432 default: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "RDLen %d: %s",
1433 rr
->rdlength
, rd
->data
); break;
1435 for (ptr
= m
->MsgBuffer
; *ptr
; ptr
++) if (*ptr
< ' ') *ptr
='.';
1436 return(m
->MsgBuffer
);
1439 mDNSlocal mDNSu32
mDNSRandom(mDNSu32 max
)
1441 static mDNSu32 seed
= 0;
1444 if (!seed
) seed
= (mDNSu32
)mDNSPlatformTimeNow();
1445 while (mask
< max
) mask
= (mask
<< 1) | 1;
1446 do seed
= seed
* 21 + 1; while ((seed
& mask
) > max
);
1447 return (seed
& mask
);
1450 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
1451 #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])
1453 #define mDNSIPv4AddressIsZero(A) mDNSSameIPv4Address((A), zeroIPAddr)
1454 #define mDNSIPv6AddressIsZero(A) mDNSSameIPv6Address((A), zerov6Addr)
1456 #define mDNSIPv4AddressIsOnes(A) mDNSSameIPv4Address((A), onesIPv4Addr)
1457 #define mDNSIPv6AddressIsOnes(A) mDNSSameIPv6Address((A), onesIPv6Addr)
1459 #define mDNSAddressIsZero(X) ( \
1460 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4)) || \
1461 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6)) )
1463 #define mDNSAddressIsOnes(X) ( \
1464 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4)) || \
1465 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6)) )
1467 #define mDNSAddressIsValid(X) ( \
1468 ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
1469 ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
1471 mDNSexport mDNSBool
mDNSSameAddress(const mDNSAddr
*ip1
, const mDNSAddr
*ip2
)
1473 if (ip1
->type
== ip2
->type
)
1477 case mDNSAddrType_IPv4
: return(mDNSBool
)(mDNSSameIPv4Address(ip1
->ip
.v4
, ip2
->ip
.v4
));
1478 case mDNSAddrType_IPv6
: return(mDNSBool
)(mDNSSameIPv6Address(ip1
->ip
.v6
, ip2
->ip
.v6
));
1484 mDNSlocal mDNSBool
mDNSAddrIsDNSMulticast(const mDNSAddr
*ip
)
1488 case mDNSAddrType_IPv4
: return(mDNSBool
)(ip
->ip
.v4
.NotAnInteger
== AllDNSLinkGroup
.NotAnInteger
);
1489 case mDNSAddrType_IPv6
: return(mDNSBool
)(ip
->ip
.v6
.l
[0] == AllDNSLinkGroupv6
.l
[0] &&
1490 ip
->ip
.v6
.l
[1] == AllDNSLinkGroupv6
.l
[1] &&
1491 ip
->ip
.v6
.l
[2] == AllDNSLinkGroupv6
.l
[2] &&
1492 ip
->ip
.v6
.l
[3] == AllDNSLinkGroupv6
.l
[3] );
1493 default: return(mDNSfalse
);
1497 mDNSlocal
const NetworkInterfaceInfo
*GetFirstActiveInterface(const NetworkInterfaceInfo
*intf
)
1499 while (intf
&& !intf
->InterfaceActive
) intf
= intf
->next
;
1503 mDNSlocal mDNSInterfaceID
GetNextActiveInterfaceID(const NetworkInterfaceInfo
*intf
)
1505 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
1506 if (next
) return(next
->InterfaceID
); else return(mDNSNULL
);
1509 #define InitialQuestionInterval (mDNSPlatformOneSecond/2)
1510 #define ActiveQuestion(Q) ((Q)->ThisQInterval > 0 && !(Q)->DuplicateOf)
1511 #define TimeToSendThisQuestion(Q,time) (ActiveQuestion(Q) && (time) - ((Q)->LastQTime + (Q)->ThisQInterval) >= 0)
1513 mDNSlocal
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
1515 if (ActiveQuestion(q
))
1516 if (m
->NextScheduledQuery
- (q
->LastQTime
+ q
->ThisQInterval
) > 0)
1517 m
->NextScheduledQuery
= (q
->LastQTime
+ q
->ThisQInterval
);
1520 // ***************************************************************************
1521 #if COMPILER_LIKES_PRAGMA_MARK
1523 #pragma mark - Domain Name Utility Functions
1526 #define mdnsIsDigit(X) ((X) >= '0' && (X) <= '9')
1527 #define mDNSIsUpperCase(X) ((X) >= 'A' && (X) <= 'Z')
1528 #define mDNSIsLowerCase(X) ((X) >= 'a' && (X) <= 'z')
1529 #define mdnsIsLetter(X) (mDNSIsUpperCase(X) || mDNSIsLowerCase(X))
1531 mDNSexport mDNSBool
SameDomainLabel(const mDNSu8
*a
, const mDNSu8
*b
)
1534 const int len
= *a
++;
1536 if (len
> MAX_DOMAIN_LABEL
)
1537 { debugf("Malformed label (too long)"); return(mDNSfalse
); }
1539 if (len
!= *b
++) return(mDNSfalse
);
1540 for (i
=0; i
<len
; i
++)
1544 if (mDNSIsUpperCase(ac
)) ac
+= 'a' - 'A';
1545 if (mDNSIsUpperCase(bc
)) bc
+= 'a' - 'A';
1546 if (ac
!= bc
) return(mDNSfalse
);
1551 mDNSexport mDNSBool
SameDomainName(const domainname
*const d1
, const domainname
*const d2
)
1553 const mDNSu8
* a
= d1
->c
;
1554 const mDNSu8
* b
= d2
->c
;
1555 const mDNSu8
*const max
= d1
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
1559 if (a
+ 1 + *a
>= max
)
1560 { debugf("Malformed domain name (more than 255 characters)"); return(mDNSfalse
); }
1561 if (!SameDomainLabel(a
, b
)) return(mDNSfalse
);
1569 // Returns length of a domain name INCLUDING the byte for the final null label
1570 // i.e. for the root label "." it returns one
1571 // For the FQDN "com." it returns 5 (length byte, three data bytes, final zero)
1572 // Legal results are 1 (just root label) to 255 (MAX_DOMAIN_NAME)
1573 // If the given domainname is invalid, result is 256
1574 mDNSexport mDNSu16
DomainNameLength(const domainname
*const name
)
1576 const mDNSu8
*src
= name
->c
;
1579 if (*src
> MAX_DOMAIN_LABEL
) return(MAX_DOMAIN_NAME
+1);
1581 if (src
- name
->c
>= MAX_DOMAIN_NAME
) return(MAX_DOMAIN_NAME
+1);
1583 return((mDNSu16
)(src
- name
->c
+ 1));
1586 // CompressedDomainNameLength returns the length of a domain name INCLUDING the byte
1587 // for the final null label i.e. for the root label "." it returns one.
1588 // E.g. for the FQDN "foo.com." it returns 9
1589 // (length, three data bytes, length, three more data bytes, final zero).
1590 // In the case where a parent domain name is provided, and the given name is a child
1591 // of that parent, CompressedDomainNameLength returns the length of the prefix portion
1592 // of the child name, plus TWO bytes for the compression pointer.
1593 // E.g. for the name "foo.com." with parent "com.", it returns 6
1594 // (length, three data bytes, two-byte compression pointer).
1595 mDNSlocal mDNSu16
CompressedDomainNameLength(const domainname
*const name
, const domainname
*parent
)
1597 const mDNSu8
*src
= name
->c
;
1598 if (parent
&& parent
->c
[0] == 0) parent
= mDNSNULL
;
1601 if (*src
> MAX_DOMAIN_LABEL
) return(MAX_DOMAIN_NAME
+1);
1602 if (parent
&& SameDomainName((domainname
*)src
, parent
)) return((mDNSu16
)(src
- name
->c
+ 2));
1604 if (src
- name
->c
>= MAX_DOMAIN_NAME
) return(MAX_DOMAIN_NAME
+1);
1606 return((mDNSu16
)(src
- name
->c
+ 1));
1609 // AppendLiteralLabelString appends a single label to an existing (possibly empty) domainname.
1610 // The C string contains the label as-is, with no escaping, etc.
1611 // Any dots in the name are literal dots, not label separators
1612 // If successful, AppendLiteralLabelString returns a pointer to the next unused byte
1613 // in the domainname bufer (i.e., the next byte after the terminating zero).
1614 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1615 // AppendLiteralLabelString returns mDNSNULL.
1616 mDNSexport mDNSu8
*AppendLiteralLabelString(domainname
*const name
, const char *cstr
)
1618 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1619 const mDNSu8
*const lim1
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1620 const mDNSu8
*const lim2
= ptr
+ 1 + MAX_DOMAIN_LABEL
;
1621 const mDNSu8
*const lim
= (lim1
< lim2
) ? lim1
: lim2
;
1622 mDNSu8
*lengthbyte
= ptr
++; // Record where the length is going to go
1624 while (*cstr
&& ptr
< lim
) *ptr
++ = (mDNSu8
)*cstr
++; // Copy the data
1625 *lengthbyte
= (mDNSu8
)(ptr
- lengthbyte
- 1); // Fill in the length byte
1626 *ptr
++ = 0; // Put the null root label on the end
1627 if (*cstr
) return(mDNSNULL
); // Failure: We didn't successfully consume all input
1628 else return(ptr
); // Success: return new value of ptr
1631 // AppendDNSNameString appends zero or more labels to an existing (possibly empty) domainname.
1632 // The C string is in conventional DNS syntax:
1633 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1634 // If successful, AppendDNSNameString returns a pointer to the next unused byte
1635 // in the domainname bufer (i.e., the next byte after the terminating zero).
1636 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1637 // AppendDNSNameString returns mDNSNULL.
1638 mDNSexport mDNSu8
*AppendDNSNameString(domainname
*const name
, const char *cstr
)
1640 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1641 const mDNSu8
*const lim
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1642 while (*cstr
&& ptr
< lim
) // While more characters, and space to put them...
1644 mDNSu8
*lengthbyte
= ptr
++; // Record where the length is going to go
1645 while (*cstr
&& *cstr
!= '.' && ptr
< lim
) // While we have characters in the label...
1647 mDNSu8 c
= (mDNSu8
)*cstr
++; // Read the character
1648 if (c
== '\\') // If escape character, check next character
1650 if (*cstr
== '\\' || *cstr
== '.') // If a second escape, or a dot,
1651 c
= (mDNSu8
)*cstr
++; // just use the second character
1652 else if (mdnsIsDigit(cstr
[0]) && mdnsIsDigit(cstr
[1]) && mdnsIsDigit(cstr
[2]))
1653 { // else, if three decimal digits,
1654 int v0
= cstr
[0] - '0'; // then interpret as three-digit decimal
1655 int v1
= cstr
[1] - '0';
1656 int v2
= cstr
[2] - '0';
1657 int val
= v0
* 100 + v1
* 10 + v2
;
1658 if (val
<= 255) { c
= (mDNSu8
)val
; cstr
+= 3; } // If valid value, use it
1661 *ptr
++ = c
; // Write the character
1663 if (*cstr
) cstr
++; // Skip over the trailing dot (if present)
1664 if (ptr
- lengthbyte
- 1 > MAX_DOMAIN_LABEL
) // If illegal label, abort
1666 *lengthbyte
= (mDNSu8
)(ptr
- lengthbyte
- 1); // Fill in the length byte
1669 *ptr
++ = 0; // Put the null root label on the end
1670 if (*cstr
) return(mDNSNULL
); // Failure: We didn't successfully consume all input
1671 else return(ptr
); // Success: return new value of ptr
1674 // AppendDomainLabel appends a single label to a name.
1675 // If successful, AppendDomainLabel returns a pointer to the next unused byte
1676 // in the domainname bufer (i.e., the next byte after the terminating zero).
1677 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1678 // AppendDomainLabel returns mDNSNULL.
1679 mDNSexport mDNSu8
*AppendDomainLabel(domainname
*const name
, const domainlabel
*const label
)
1682 mDNSu8
*ptr
= name
->c
+ DomainNameLength(name
) - 1;
1684 // Check label is legal
1685 if (label
->c
[0] > MAX_DOMAIN_LABEL
) return(mDNSNULL
);
1687 // Check that ptr + length byte + data bytes + final zero does not exceed our limit
1688 if (ptr
+ 1 + label
->c
[0] + 1 > name
->c
+ MAX_DOMAIN_NAME
) return(mDNSNULL
);
1690 for (i
=0; i
<=label
->c
[0]; i
++) *ptr
++ = label
->c
[i
]; // Copy the label data
1691 *ptr
++ = 0; // Put the null root label on the end
1695 mDNSexport mDNSu8
*AppendDomainName(domainname
*const name
, const domainname
*const append
)
1697 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1698 const mDNSu8
*const lim
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1699 const mDNSu8
* src
= append
->c
;
1703 if (ptr
+ 1 + src
[0] > lim
) return(mDNSNULL
);
1704 for (i
=0; i
<=src
[0]; i
++) *ptr
++ = src
[i
];
1705 *ptr
= 0; // Put the null root label on the end
1711 // MakeDomainLabelFromLiteralString makes a single domain label from a single literal C string (with no escaping).
1712 // If successful, MakeDomainLabelFromLiteralString returns mDNStrue.
1713 // If unable to convert the whole string to a legal domain label (i.e. because length is more than 63 bytes) then
1714 // MakeDomainLabelFromLiteralString makes a legal domain label from the first 63 bytes of the string and returns mDNSfalse.
1715 // In some cases silently truncated oversized names to 63 bytes is acceptable, so the return result may be ignored.
1716 // In other cases silent truncation may not be acceptable, so in those cases the calling function needs to check the return result.
1717 mDNSexport mDNSBool
MakeDomainLabelFromLiteralString(domainlabel
*const label
, const char *cstr
)
1719 mDNSu8
* ptr
= label
->c
+ 1; // Where we're putting it
1720 const mDNSu8
*const limit
= label
->c
+ 1 + MAX_DOMAIN_LABEL
; // The maximum we can put
1721 while (*cstr
&& ptr
< limit
) *ptr
++ = (mDNSu8
)*cstr
++; // Copy the label
1722 label
->c
[0] = (mDNSu8
)(ptr
- label
->c
- 1); // Set the length byte
1723 return(*cstr
== 0); // Return mDNStrue if we successfully consumed all input
1726 // MakeDomainNameFromDNSNameString makes a native DNS-format domainname from a C string.
1727 // The C string is in conventional DNS syntax:
1728 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1729 // If successful, MakeDomainNameFromDNSNameString returns a pointer to the next unused byte
1730 // in the domainname bufer (i.e., the next byte after the terminating zero).
1731 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1732 // MakeDomainNameFromDNSNameString returns mDNSNULL.
1733 mDNSexport mDNSu8
*MakeDomainNameFromDNSNameString(domainname
*const name
, const char *cstr
)
1735 name
->c
[0] = 0; // Make an empty domain name
1736 return(AppendDNSNameString(name
, cstr
)); // And then add this string to it
1739 mDNSexport
char *ConvertDomainLabelToCString_withescape(const domainlabel
*const label
, char *ptr
, char esc
)
1741 const mDNSu8
* src
= label
->c
; // Domain label we're reading
1742 const mDNSu8 len
= *src
++; // Read length of this (non-null) label
1743 const mDNSu8
*const end
= src
+ len
; // Work out where the label ends
1744 if (len
> MAX_DOMAIN_LABEL
) return(mDNSNULL
); // If illegal label, abort
1745 while (src
< end
) // While we have characters in the label
1750 if (c
== '.' || c
== esc
) // If character is a dot or the escape character
1751 *ptr
++ = esc
; // Output escape character
1752 else if (c
<= ' ') // If non-printing ascii,
1753 { // Output decimal escape sequence
1755 *ptr
++ = (char) ('0' + (c
/ 100) );
1756 *ptr
++ = (char) ('0' + (c
/ 10) % 10);
1757 c
= (mDNSu8
)('0' + (c
) % 10);
1760 *ptr
++ = (char)c
; // Copy the character
1762 *ptr
= 0; // Null-terminate the string
1763 return(ptr
); // and return
1766 // Note, to guarantee that there will be no possible overrun, cstr must be at least 1005 bytes
1767 // The longest legal domain name is 255 bytes, in the form of three 64-byte labels, one 62-byte label,
1768 // and the null root label.
1769 // If every label character has to be escaped as a four-byte escape sequence, the maximum textual
1770 // ascii display of this is 63*4 + 63*4 + 63*4 + 61*4 = 1000 label characters,
1771 // plus four dots and the null at the end of the C string = 1005
1772 mDNSexport
char *ConvertDomainNameToCString_withescape(const domainname
*const name
, char *ptr
, char esc
)
1774 const mDNSu8
*src
= name
->c
; // Domain name we're reading
1775 const mDNSu8
*const max
= name
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
1777 if (*src
== 0) *ptr
++ = '.'; // Special case: For root, just write a dot
1779 while (*src
) // While more characters in the domain name
1781 if (src
+ 1 + *src
>= max
) return(mDNSNULL
);
1782 ptr
= ConvertDomainLabelToCString_withescape((const domainlabel
*)src
, ptr
, esc
);
1783 if (!ptr
) return(mDNSNULL
);
1785 *ptr
++ = '.'; // Write the dot after the label
1788 *ptr
++ = 0; // Null-terminate the string
1789 return(ptr
); // and return
1793 // Host names must start with a letter, end with a letter or digit,
1794 // and have as interior characters only letters, digits, and hyphen.
1795 // This was subsequently modified in RFC 1123 to allow the first character to be either a letter or a digit
1796 #define mdnsValidHostChar(X, notfirst, notlast) (mdnsIsLetter(X) || mdnsIsDigit(X) || ((notfirst) && (notlast) && (X) == '-') )
1798 mDNSexport
void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name
[], domainlabel
*const hostlabel
)
1800 const mDNSu8
* src
= &UTF8Name
[1];
1801 const mDNSu8
*const end
= &UTF8Name
[1] + UTF8Name
[0];
1802 mDNSu8
* ptr
= &hostlabel
->c
[1];
1803 const mDNSu8
*const lim
= &hostlabel
->c
[1] + MAX_DOMAIN_LABEL
;
1806 // Delete apostrophes from source name
1807 if (src
[0] == '\'') { src
++; continue; } // Standard straight single quote
1808 if (src
+ 2 < end
&& src
[0] == 0xE2 && src
[1] == 0x80 && src
[2] == 0x99)
1809 { src
+= 3; continue; } // Unicode curly apostrophe
1812 if (mdnsValidHostChar(*src
, (ptr
> &hostlabel
->c
[1]), (src
< end
-1))) *ptr
++ = *src
;
1813 else if (ptr
> &hostlabel
->c
[1] && ptr
[-1] != '-') *ptr
++ = '-';
1817 while (ptr
> &hostlabel
->c
[1] && ptr
[-1] == '-') ptr
--; // Truncate trailing '-' marks
1818 hostlabel
->c
[0] = (mDNSu8
)(ptr
- &hostlabel
->c
[1]);
1821 mDNSexport mDNSu8
*ConstructServiceName(domainname
*const fqdn
,
1822 const domainlabel
*name
, const domainname
*type
, const domainname
*const domain
)
1825 mDNSu8
*dst
= fqdn
->c
;
1827 const char *errormsg
;
1829 // In the case where there is no name (and ONLY in that case),
1830 // a single-label subtype is allowed as the first label of a three-part "type"
1833 const mDNSu8
*s2
= type
->c
+ 1 + type
->c
[0];
1834 if (type
->c
[0] > 0 && type
->c
[0] < 0x40 &&
1835 s2
[0] > 0 && s2
[0] < 0x40 &&
1836 s2
[1+s2
[0]] > 0 && s2
[1+s2
[0]] < 0x40)
1838 name
= (domainlabel
*)type
;
1839 type
= (domainname
*)s2
;
1843 if (name
&& name
->c
[0])
1845 src
= name
->c
; // Put the service name into the domain name
1847 if (len
>= 0x40) { errormsg
="Service instance name too long"; goto fail
; }
1848 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1851 name
= (domainlabel
*)""; // Set this up to be non-null, to avoid errors if we have to call LogMsg() below
1853 src
= type
->c
; // Put the service type into the domain name
1855 if (len
< 2 || len
>= 0x40) { errormsg
="Invalid service application protocol name"; goto fail
; }
1856 if (src
[1] != '_') { errormsg
="Service application protocol name must begin with underscore"; goto fail
; }
1857 for (i
=2; i
<=len
; i
++)
1858 if (!mdnsIsLetter(src
[i
]) && !mdnsIsDigit(src
[i
]) && src
[i
] != '-' && src
[i
] != '_')
1859 { errormsg
="Service application protocol name must contain only letters, digits, and hyphens"; goto fail
; }
1860 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1863 //if (len == 0 || len >= 0x40) { errormsg="Invalid service transport protocol name"; goto fail; }
1864 if (!(len
== 4 && src
[1] == '_' &&
1865 (((src
[2] | 0x20) == 'u' && (src
[3] | 0x20) == 'd') || ((src
[2] | 0x20) == 't' && (src
[3] | 0x20) == 'c')) &&
1866 (src
[4] | 0x20) == 'p'))
1867 { errormsg
="Service transport protocol name must be _udp or _tcp"; goto fail
; }
1868 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1870 if (*src
) { errormsg
="Service type must have only two labels"; goto fail
; }
1873 dst
= AppendDomainName(fqdn
, domain
);
1874 if (!dst
) { errormsg
="Service domain too long"; goto fail
; }
1878 LogMsg("ConstructServiceName: %s: %#s.%##s%##s", errormsg
, name
->c
, type
->c
, domain
->c
);
1882 mDNSexport mDNSBool
DeconstructServiceName(const domainname
*const fqdn
,
1883 domainlabel
*const name
, domainname
*const type
, domainname
*const domain
)
1886 const mDNSu8
*src
= fqdn
->c
;
1887 const mDNSu8
*max
= fqdn
->c
+ MAX_DOMAIN_NAME
;
1890 dst
= name
->c
; // Extract the service name from the domain name
1892 if (len
>= 0x40) { debugf("DeconstructServiceName: service name too long"); return(mDNSfalse
); }
1893 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1895 dst
= type
->c
; // Extract the service type from the domain name
1897 if (len
>= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse
); }
1898 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1901 if (len
>= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse
); }
1902 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1903 *dst
++ = 0; // Put the null root label on the end of the service type
1905 dst
= domain
->c
; // Extract the service domain from the domain name
1910 { debugf("DeconstructServiceName: service domain label too long"); return(mDNSfalse
); }
1911 if (src
+ 1 + len
+ 1 >= max
)
1912 { debugf("DeconstructServiceName: service domain too long"); return(mDNSfalse
); }
1913 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1915 *dst
++ = 0; // Put the null root label on the end
1920 // Returns true if a rich text label ends in " (nnn)", or if an RFC 1034
1921 // name ends in "-nnn", where n is some decimal number.
1922 mDNSlocal mDNSBool
LabelContainsSuffix(const domainlabel
*const name
, const mDNSBool RichText
)
1924 mDNSu16 l
= name
->c
[0];
1928 if (l
< 4) return mDNSfalse
; // Need at least " (2)"
1929 if (name
->c
[l
--] != ')') return mDNSfalse
; // Last char must be ')'
1930 if (!mdnsIsDigit(name
->c
[l
])) return mDNSfalse
; // Preceeded by a digit
1932 while (l
> 2 && mdnsIsDigit(name
->c
[l
])) l
--; // Strip off digits
1933 return (name
->c
[l
] == '(' && name
->c
[l
- 1] == ' ');
1937 if (l
< 2) return mDNSfalse
; // Need at least "-2"
1938 if (!mdnsIsDigit(name
->c
[l
])) return mDNSfalse
; // Last char must be a digit
1940 while (l
> 2 && mdnsIsDigit(name
->c
[l
])) l
--; // Strip off digits
1941 return (name
->c
[l
] == '-');
1945 // removes an auto-generated suffix (appended on a name collision) from a label. caller is
1946 // responsible for ensuring that the label does indeed contain a suffix. returns the number
1947 // from the suffix that was removed.
1948 mDNSlocal mDNSu32
RemoveLabelSuffix(domainlabel
*name
, mDNSBool RichText
)
1950 mDNSu32 val
= 0, multiplier
= 1;
1952 // Chop closing parentheses from RichText suffix
1953 if (RichText
&& name
->c
[0] >= 1 && name
->c
[name
->c
[0]] == ')') name
->c
[0]--;
1955 // Get any existing numerical suffix off the name
1956 while (mdnsIsDigit(name
->c
[name
->c
[0]]))
1957 { val
+= (name
->c
[name
->c
[0]] - '0') * multiplier
; multiplier
*= 10; name
->c
[0]--; }
1959 // Chop opening parentheses or dash from suffix
1962 if (name
->c
[0] >= 2 && name
->c
[name
->c
[0]] == '(' && name
->c
[name
->c
[0]-1] == ' ') name
->c
[0] -= 2;
1966 if (name
->c
[0] >= 1 && name
->c
[name
->c
[0]] == '-') name
->c
[0] -= 1;
1972 // appends a numerical suffix to a label, with the number following a whitespace and enclosed
1973 // in parentheses (rich text) or following two consecutive hyphens (RFC 1034 domain label).
1974 mDNSlocal
void AppendLabelSuffix(domainlabel
*name
, mDNSu32 val
, mDNSBool RichText
)
1976 mDNSu32 divisor
= 1, chars
= 2; // Shortest possible RFC1034 name suffix is 3 characters ("-2")
1977 if (RichText
) chars
= 4; // Shortest possible RichText suffix is 4 characters (" (2)")
1979 // Truncate trailing spaces from RichText names
1980 if (RichText
) while (name
->c
[name
->c
[0]] == ' ') name
->c
[0]--;
1982 while (val
>= divisor
* 10) { divisor
*= 10; chars
++; }
1984 if (name
->c
[0] > (mDNSu8
)(MAX_DOMAIN_LABEL
- chars
))
1986 name
->c
[0] = (mDNSu8
)(MAX_DOMAIN_LABEL
- chars
);
1987 // If the following character is a UTF-8 continuation character,
1988 // we just chopped a multi-byte UTF-8 character in the middle, so strip back to a safe truncation point
1989 while (name
->c
[0] > 0 && (name
->c
[name
->c
[0]+1] & 0xC0) == 0x80) name
->c
[0]--;
1992 if (RichText
) { name
->c
[++name
->c
[0]] = ' '; name
->c
[++name
->c
[0]] = '('; }
1993 else { name
->c
[++name
->c
[0]] = '-'; }
1997 name
->c
[++name
->c
[0]] = (mDNSu8
)('0' + val
/ divisor
);
2002 if (RichText
) name
->c
[++name
->c
[0]] = ')';
2005 mDNSexport
void IncrementLabelSuffix(domainlabel
*name
, mDNSBool RichText
)
2009 if (LabelContainsSuffix(name
, RichText
))
2010 val
= RemoveLabelSuffix(name
, RichText
);
2012 // If no existing suffix, start by renaming "Foo" as "Foo (2)" or "Foo-2" as appropriate.
2013 // If existing suffix in the range 2-9, increment it.
2014 // If we've had ten conflicts already, there are probably too many hosts trying to use the same name,
2015 // so add a random increment to improve the chances of finding an available name next time.
2016 if (val
== 0) val
= 2;
2017 else if (val
< 10) val
++;
2018 else val
+= 1 + mDNSRandom(99);
2020 AppendLabelSuffix(name
, val
, RichText
);
2023 // ***************************************************************************
2024 #if COMPILER_LIKES_PRAGMA_MARK
2026 #pragma mark - Resource Record Utility Functions
2029 #define RRIsAddressType(RR) ((RR)->resrec.rrtype == kDNSType_A || (RR)->resrec.rrtype == kDNSType_AAAA)
2030 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
2032 #define ResourceRecordIsValidAnswer(RR) ( ((RR)-> resrec.RecordType & kDNSRecordTypeActiveMask) && \
2033 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2034 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2035 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
2037 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
2038 (ResourceRecordIsValidAnswer(RR) && \
2039 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
2041 #define RRUniqueOrKnownUnique(RR) ((RR)->RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeKnownUnique))
2043 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
2044 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
2046 // For records that have *never* been announced on the wire, their AnnounceCount will be set to InitialAnnounceCount (10).
2047 // When de-registering these records we do not need to send any goodbye packet because we never announced them in the first
2048 // place. If AnnounceCount is less than InitialAnnounceCount that means we have announced them at least once, so a goodbye
2049 // packet is needed. For this reason, if we ever reset AnnounceCount (e.g. after an interface change) we set it to
2050 // ReannounceCount (9), not InitialAnnounceCount. If we were to reset AnnounceCount back to InitialAnnounceCount that would
2051 // imply that the record had never been announced on the wire (which is false) and if the client were then to immediately
2052 // deregister that record before it had a chance to announce, we'd fail to send its goodbye packet (which would be a bug).
2053 #define InitialAnnounceCount ((mDNSu8)10)
2054 #define ReannounceCount ((mDNSu8)9)
2056 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
2057 // This means that because the announce interval is doubled after sending the first packet, the first
2058 // observed on-the-wire inter-packet interval between announcements is actually one second.
2059 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
2060 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
2061 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
2062 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
2064 #define DefaultAPIntervalForRecordType(X) ((X) & (kDNSRecordTypeAdvisory | kDNSRecordTypeShared ) ? DefaultAnnounceIntervalForTypeShared : \
2065 (X) & (kDNSRecordTypeUnique ) ? DefaultProbeIntervalForTypeUnique : \
2066 (X) & (kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique) ? DefaultAnnounceIntervalForTypeUnique : 0)
2068 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
2069 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
2070 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
2071 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
2073 #define MaxUnansweredQueries 4
2075 mDNSlocal mDNSBool
SameRData(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2077 if (r1
->rrtype
!= r2
->rrtype
) return(mDNSfalse
);
2078 if (r1
->rdlength
!= r2
->rdlength
) return(mDNSfalse
);
2079 if (r1
->rdatahash
!= r2
->rdatahash
) return(mDNSfalse
);
2080 if (r1
->rdnamehash
!= r2
->rdnamehash
) return(mDNSfalse
);
2083 case kDNSType_CNAME
:// Same as PTR
2084 case kDNSType_PTR
: return(SameDomainName(&r1
->rdata
->u
.name
, &r2
->rdata
->u
.name
));
2086 case kDNSType_SRV
: return(mDNSBool
)( r1
->rdata
->u
.srv
.priority
== r2
->rdata
->u
.srv
.priority
&&
2087 r1
->rdata
->u
.srv
.weight
== r2
->rdata
->u
.srv
.weight
&&
2088 r1
->rdata
->u
.srv
.port
.NotAnInteger
== r2
->rdata
->u
.srv
.port
.NotAnInteger
&&
2089 SameDomainName(&r1
->rdata
->u
.srv
.target
, &r2
->rdata
->u
.srv
.target
) );
2091 default: return(mDNSPlatformMemSame(r1
->rdata
->u
.data
, r2
->rdata
->u
.data
, r1
->rdlength
));
2095 mDNSlocal mDNSBool
ResourceRecordAnswersQuestion(const ResourceRecord
*const rr
, const DNSQuestion
*const q
)
2097 if (rr
->InterfaceID
&&
2099 rr
->InterfaceID
!= q
->InterfaceID
) return(mDNSfalse
);
2101 // RR type CNAME matches any query type. QTYPE ANY matches any RR type. QCLASS ANY matches any RR class.
2102 if (rr
->rrtype
!= kDNSType_CNAME
&& rr
->rrtype
!= q
->qtype
&& q
->qtype
!= kDNSQType_ANY
) return(mDNSfalse
);
2103 if ( rr
->rrclass
!= q
->qclass
&& q
->qclass
!= kDNSQClass_ANY
) return(mDNSfalse
);
2104 return(rr
->namehash
== q
->qnamehash
&& SameDomainName(&rr
->name
, &q
->qname
));
2107 mDNSlocal mDNSu32
DomainNameHashValue(const domainname
*const name
)
2112 for (c
= name
->c
; c
[0] != 0 && c
[1] != 0; c
+= 2)
2114 sum
+= ((mDNSIsUpperCase(c
[0]) ? c
[0] + 'a' - 'A' : c
[0]) << 8) |
2115 (mDNSIsUpperCase(c
[1]) ? c
[1] + 'a' - 'A' : c
[1]);
2116 sum
= (sum
<<3) | (sum
>>29);
2118 if (c
[0]) sum
+= ((mDNSIsUpperCase(c
[0]) ? c
[0] + 'a' - 'A' : c
[0]) << 8);
2122 #define HashSlot(X) (DomainNameHashValue(X) % CACHE_HASH_SLOTS)
2124 mDNSlocal mDNSu32
RDataHashValue(mDNSu16
const rdlength
, const RDataBody
*const rdb
)
2128 for (i
=0; i
+1 < rdlength
; i
+=2)
2130 sum
+= (((mDNSu32
)(rdb
->data
[i
])) << 8) | rdb
->data
[i
+1];
2131 sum
= (sum
<<3) | (sum
>>29);
2135 sum
+= ((mDNSu32
)(rdb
->data
[i
])) << 8;
2140 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
2141 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
2142 // TTL and rdata may differ.
2143 // This is used for cache flush management:
2144 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
2145 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
2146 mDNSlocal mDNSBool
SameResourceRecordSignature(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2148 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
2149 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
2150 if (r1
->InterfaceID
&&
2152 r1
->InterfaceID
!= r2
->InterfaceID
) return(mDNSfalse
);
2153 return(mDNSBool
)(r1
->rrtype
== r2
->rrtype
&& r1
->rrclass
== r2
->rrclass
&& r1
->namehash
== r2
->namehash
&& SameDomainName(&r1
->name
, &r2
->name
));
2156 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if the
2157 // authoratative record is in the probing state. Probes are sent with the wildcard type, so a response of
2158 // any type should match, even if it is not the type the client plans to use.
2159 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
2161 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
2162 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
2163 if (pktrr
->resrec
.InterfaceID
&&
2164 authrr
->resrec
.InterfaceID
&&
2165 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
2166 if (authrr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
2167 return(mDNSBool
)(pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&& pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&& SameDomainName(&pktrr
->resrec
.name
, &authrr
->resrec
.name
));
2170 // IdenticalResourceRecord returns true if two resources records have
2171 // the same name, type, class, and identical rdata (InterfaceID and TTL may differ)
2172 mDNSlocal mDNSBool
IdenticalResourceRecord(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2174 if (!r1
) { LogMsg("IdenticalResourceRecord ERROR: r1 is NULL"); return(mDNSfalse
); }
2175 if (!r2
) { LogMsg("IdenticalResourceRecord ERROR: r2 is NULL"); return(mDNSfalse
); }
2176 if (r1
->rrtype
!= r2
->rrtype
|| r1
->rrclass
!= r2
->rrclass
|| r1
->namehash
!= r2
->namehash
|| !SameDomainName(&r1
->name
, &r2
->name
)) return(mDNSfalse
);
2177 return(SameRData(r1
, r2
));
2180 // CacheRecord *ks is the CacheRecord from the known answer list in the query.
2181 // This is the information that the requester believes to be correct.
2182 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
2183 // This is the information that we believe to be correct.
2184 // We've already determined that we plan to give this answer on this interface
2185 // (either the record is non-specific, or it is specific to this interface)
2186 // so now we just need to check the name, type, class, rdata and TTL.
2187 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
2189 // If RR signature is different, or data is different, then don't suppress our answer
2190 if (!IdenticalResourceRecord(&ka
->resrec
,&rr
->resrec
)) return(mDNSfalse
);
2192 // If the requester's indicated TTL is less than half the real TTL,
2193 // we need to give our answer before the requester's copy expires.
2194 // If the requester's indicated TTL is at least half the real TTL,
2195 // then we can suppress our answer this time.
2196 // If the requester's indicated TTL is greater than the TTL we believe,
2197 // then that's okay, and we don't need to do anything about it.
2198 // (If two responders on the network are offering the same information,
2199 // that's okay, and if they are offering the information with different TTLs,
2200 // the one offering the lower TTL should defer to the one offering the higher TTL.)
2201 return(mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
2204 mDNSlocal mDNSu16
GetRDLength(const ResourceRecord
*const rr
, mDNSBool estimate
)
2206 RDataBody
*rd
= &rr
->rdata
->u
;
2207 const domainname
*const name
= estimate
? &rr
->name
: mDNSNULL
;
2210 case kDNSType_A
: return(sizeof(rd
->ip
));
2211 case kDNSType_CNAME
:// Same as PTR
2212 case kDNSType_PTR
: return(CompressedDomainNameLength(&rd
->name
, name
));
2213 case kDNSType_HINFO
:return(mDNSu16
)(2 + (int)rd
->data
[0] + (int)rd
->data
[1 + (int)rd
->data
[0]]);
2214 case kDNSType_NULL
: // Same as TXT -- not self-describing, so have to just trust rdlength
2215 case kDNSType_TXT
: return(rr
->rdlength
); // TXT is not self-describing, so have to just trust rdlength
2216 case kDNSType_AAAA
: return(sizeof(rd
->ipv6
));
2217 case kDNSType_SRV
: return(mDNSu16
)(6 + CompressedDomainNameLength(&rd
->srv
.target
, name
));
2218 default: debugf("Warning! Don't know how to get length of resource type %d", rr
->rrtype
);
2219 return(rr
->rdlength
);
2223 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
2225 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
2227 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
2228 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
2230 else if (rr
->AnnounceCount
&& ResourceRecordIsValidAnswer(rr
))
2232 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
2233 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
2237 #define GetRRDomainNameTarget(RR) ( \
2238 ((RR)->rrtype == kDNSType_CNAME || (RR)->rrtype == kDNSType_PTR) ? &(RR)->rdata->u.name : \
2239 ((RR)->rrtype == kDNSType_SRV ) ? &(RR)->rdata->u.srv.target : mDNSNULL )
2241 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
2243 // To allow us to aggregate probes when a group of services are registered together,
2244 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
2245 // 1/4 second wait; probe
2246 // 1/4 second wait; probe
2247 // 1/4 second wait; probe
2248 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
2250 // If we have no probe suppression time set, or it is in the past, set it now
2251 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
2253 m
->SuppressProbes
= (m
->timenow
+ DefaultProbeIntervalForTypeUnique
) | 1;
2254 // If we already have a probe scheduled to go out sooner, then use that time to get better aggregation
2255 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
2256 m
->SuppressProbes
= m
->NextScheduledProbe
;
2257 // If we already have a query scheduled to go out sooner, then use that time to get better aggregation
2258 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
2259 m
->SuppressProbes
= m
->NextScheduledQuery
;
2262 // We announce to flush stale data from other caches. It is a reasonable assumption that any
2263 // old stale copies will probably have the same TTL we're using, so announcing longer than
2264 // this serves no purpose -- any stale copies of that record will have expired by then anyway.
2265 rr
->AnnounceUntil
= m
->timenow
+ TicksTTL(rr
);
2266 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
2267 // Set LastMCTime to now, to inhibit multicast responses
2268 // (no need to send additional multicast responses when we're announcing anyway)
2269 rr
->LastMCTime
= m
->timenow
;
2270 rr
->LastMCInterface
= mDNSInterfaceMark
;
2272 // If this is a record type that's not going to probe, then delay its first announcement so that
2273 // it will go out synchronized with the first announcement for the other records that *are* probing.
2274 // This is a minor performance tweak that helps keep groups of related records synchronized together.
2275 // The addition of "rr->ThisAPInterval / 2" is to make sure that, in the event that any of the probes are
2276 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
2277 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
2278 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
2279 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
)
2280 rr
->LastAPTime
+= DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
2282 SetNextAnnounceProbeTime(m
, rr
);
2285 mDNSlocal
void SetNewRData(ResourceRecord
*const rr
, RData
*NewRData
, mDNSu16 rdlength
)
2290 rr
->rdata
= NewRData
;
2291 rr
->rdlength
= rdlength
;
2293 // Must not try to get target pointer until after updating rr->rdata
2294 target
= GetRRDomainNameTarget(rr
);
2295 rr
->rdlength
= GetRDLength(rr
, mDNSfalse
);
2296 rr
->rdestimate
= GetRDLength(rr
, mDNStrue
);
2297 rr
->rdatahash
= RDataHashValue(rr
->rdlength
, &rr
->rdata
->u
);
2298 rr
->rdnamehash
= target
? DomainNameHashValue(target
) : 0;
2301 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
2303 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
2305 if (!target
) debugf("SetTargetToHostName: Don't know how to set the target of rrtype %d", rr
->resrec
.rrtype
);
2307 if (target
&& SameDomainName(target
, &m
->hostname
))
2308 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
.c
, target
->c
);
2310 if (target
&& !SameDomainName(target
, &m
->hostname
))
2312 AssignDomainName(*target
, m
->hostname
);
2313 SetNewRData(&rr
->resrec
, mDNSNULL
, 0);
2315 // If we're in the middle of probing this record, we need to start again,
2316 // because changing its rdata may change the outcome of the tie-breaker.
2317 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
2318 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
2320 // If we've announced this record, we really should send a goodbye packet for the old rdata before
2321 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
2322 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
2323 if (rr
->AnnounceCount
< InitialAnnounceCount
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
2324 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
));
2326 if (rr
->AnnounceCount
< ReannounceCount
)
2327 rr
->AnnounceCount
= ReannounceCount
;
2328 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
2329 InitializeLastAPTime(m
,rr
);
2333 mDNSlocal
void CompleteProbing(mDNS
*const m
, AuthRecord
*const rr
)
2335 verbosedebugf("Probing for %##s (%s) complete", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2336 if (!rr
->Acknowledged
&& rr
->RecordCallback
)
2338 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2339 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2340 rr
->Acknowledged
= mDNStrue
;
2341 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2342 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
2343 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2347 #define ValidateDomainName(N) (DomainNameLength(N) <= MAX_DOMAIN_NAME)
2349 mDNSlocal mDNSBool
ValidateRData(const mDNSu16 rrtype
, const mDNSu16 rdlength
, const RData
*const rd
)
2354 case kDNSType_A
: return(rdlength
== sizeof(mDNSv4Addr
));
2356 case kDNSType_NS
: // Same as PTR
2357 case kDNSType_MD
: // Same as PTR
2358 case kDNSType_MF
: // Same as PTR
2359 case kDNSType_CNAME
:// Same as PTR
2360 //case kDNSType_SOA not checked
2361 case kDNSType_MB
: // Same as PTR
2362 case kDNSType_MG
: // Same as PTR
2363 case kDNSType_MR
: // Same as PTR
2364 //case kDNSType_NULL not checked (no specified format, so always valid)
2365 //case kDNSType_WKS not checked
2366 case kDNSType_PTR
: len
= DomainNameLength(&rd
->u
.name
);
2367 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== len
);
2369 case kDNSType_HINFO
:// Same as TXT (roughly)
2370 case kDNSType_MINFO
:// Same as TXT (roughly)
2371 case kDNSType_TXT
: {
2372 const mDNSu8
*ptr
= rd
->u
.txt
.c
;
2373 const mDNSu8
*end
= rd
->u
.txt
.c
+ rdlength
;
2374 while (ptr
< end
) ptr
+= 1 + ptr
[0];
2375 return (ptr
== end
);
2378 case kDNSType_AAAA
: return(rdlength
== sizeof(mDNSv6Addr
));
2380 case kDNSType_MX
: len
= DomainNameLength(&rd
->u
.mx
.exchange
);
2381 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== 2+len
);
2383 case kDNSType_SRV
: len
= DomainNameLength(&rd
->u
.srv
.target
);
2384 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== 6+len
);
2386 default: return(mDNStrue
); // Allow all other types without checking
2390 // Two records qualify to be local duplicates if the RecordTypes are the same, or if one is Unique and the other Verified
2391 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified))
2392 #define RecordIsLocalDuplicate(A,B) ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
2394 mDNSlocal mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
2396 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
2398 AuthRecord
**p
= &m
->ResourceRecords
;
2399 AuthRecord
**d
= &m
->DuplicateRecords
;
2400 AuthRecord
**l
= &m
->LocalOnlyRecords
;
2402 #if TEST_LOCALONLY_FOR_EVERYTHING
2403 rr
->resrec
.InterfaceID
= (mDNSInterfaceID
)~0;
2406 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2407 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
2408 while (*l
&& *l
!= rr
) l
=&(*l
)->next
;
2411 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
));
2412 return(mStatus_AlreadyRegistered
);
2415 if (rr
->DependentOn
)
2417 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
2418 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
2421 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
2422 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2423 return(mStatus_Invalid
);
2425 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
)))
2427 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
2428 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
2429 return(mStatus_Invalid
);
2433 // If this resource record is referencing a specific interface, make sure it exists
2434 if (rr
->resrec
.InterfaceID
&& rr
->resrec
.InterfaceID
!= ((mDNSInterfaceID
)~0))
2436 NetworkInterfaceInfo
*intf
;
2437 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
2438 if (intf
->InterfaceID
== rr
->resrec
.InterfaceID
) break;
2441 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr
->resrec
.InterfaceID
);
2442 return(mStatus_BadReferenceErr
);
2446 rr
->next
= mDNSNULL
;
2448 // Field Group 1: Persistent metadata for Authoritative Records
2449 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2450 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2451 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2452 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2453 // rr->Callback = already set in mDNS_SetupResourceRecord
2454 // rr->Context = already set in mDNS_SetupResourceRecord
2455 // rr->RecordType = already set in mDNS_SetupResourceRecord
2456 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
2458 // Field Group 2: Transient state for Authoritative Records
2459 rr
->Acknowledged
= mDNSfalse
;
2460 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
2461 rr
->AnnounceCount
= InitialAnnounceCount
;
2462 rr
->IncludeInProbe
= mDNSfalse
;
2463 rr
->ImmedAnswer
= mDNSNULL
;
2464 rr
->ImmedAdditional
= mDNSNULL
;
2465 rr
->SendRNow
= mDNSNULL
;
2466 rr
->v4Requester
= zeroIPAddr
;
2467 rr
->v6Requester
= zerov6Addr
;
2468 rr
->NextResponse
= mDNSNULL
;
2469 rr
->NR_AnswerTo
= mDNSNULL
;
2470 rr
->NR_AdditionalTo
= mDNSNULL
;
2471 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
2472 InitializeLastAPTime(m
, rr
);
2473 // rr->AnnounceUntil = Set for us in InitializeLastAPTime()
2474 // rr->LastAPTime = Set for us in InitializeLastAPTime()
2475 // rr->LastMCTime = Set for us in InitializeLastAPTime()
2476 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
2477 rr
->NewRData
= mDNSNULL
;
2478 rr
->newrdlength
= 0;
2479 rr
->UpdateCallback
= mDNSNULL
;
2480 rr
->UpdateCredits
= kMaxUpdateCredits
;
2481 rr
->NextUpdateCredit
= 0;
2482 rr
->UpdateBlocked
= 0;
2484 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
2485 // rr->resrec.name.c = MUST be set by client
2486 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
2487 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
2488 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
2489 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
2493 if (target
) target
->c
[0] = 0;
2494 SetTargetToHostName(m
, rr
); // This also sets rdlength and rdestimate for us
2498 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
2499 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
2502 if (!ValidateDomainName(&rr
->resrec
.name
))
2503 { LogMsg("Attempt to register record with invalid name: %s", GetRRDisplayString(m
, rr
)); return(mStatus_Invalid
); }
2505 // Don't do this until *after* we've set rr->resrec.rdlength
2506 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
2507 { LogMsg("Attempt to register record with invalid rdata: %s", GetRRDisplayString(m
, rr
)); return(mStatus_Invalid
); }
2509 rr
->resrec
.namehash
= DomainNameHashValue(&rr
->resrec
.name
);
2510 rr
->resrec
.rdatahash
= RDataHashValue(rr
->resrec
.rdlength
, &rr
->resrec
.rdata
->u
);
2511 rr
->resrec
.rdnamehash
= target
? DomainNameHashValue(target
) : 0;
2513 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0))
2515 debugf("Adding %p %##s (%s) to LocalOnly list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2517 if (!m
->NewLocalOnlyRecords
) m
->NewLocalOnlyRecords
= rr
;
2518 // If this is supposed to be unique, make sure we don't have any name conflicts
2519 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2521 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
2522 for (r
= m
->LocalOnlyRecords
; r
; r
=r
->next
)
2524 const AuthRecord
*s2
= r
->RRSet
? r
->RRSet
: r
;
2525 if (s1
!= s2
&& SameResourceRecordSignature(&r
->resrec
, &rr
->resrec
) && !SameRData(&r
->resrec
, &rr
->resrec
))
2528 if (r
) // If we found a conflict, set DiscardLocalOnlyRecords so we'll deliver the callback
2530 debugf("Name conflict %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2531 m
->DiscardLocalOnlyRecords
= mDNStrue
;
2533 else // else no conflict, so set ProbeCount to zero and update RecordType as appropriate
2536 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
2542 // Now that's we've finished building our new record, make sure it's not identical to one we already have
2543 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (RecordIsLocalDuplicate(r
, rr
)) break;
2547 debugf("Adding %p %##s (%s) to duplicate list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2549 // If the previous copy of this record is already verified unique,
2550 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
2551 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
2552 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
2553 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
2558 debugf("Adding %p %##s (%s) to active record list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2562 return(mStatus_NoError
);
2565 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
2567 m
->ProbeFailTime
= m
->timenow
;
2568 m
->NumFailedProbes
++;
2569 // If we've had ten or more probe failures, rate-limit to one every five seconds
2570 // The result is ORed with 1 to make sure SuppressProbes is not accidentally set to zero
2571 if (m
->NumFailedProbes
>= 10) m
->SuppressProbes
= (m
->timenow
+ mDNSPlatformOneSecond
* 5) | 1;
2572 if (m
->NumFailedProbes
>= 16)
2573 LogMsg("Name in use: %##s (%s); need to choose another (%d)",
2574 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), m
->NumFailedProbes
);
2577 // mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
2578 // mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
2579 // mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
2580 typedef enum { mDNS_Dereg_normal
, mDNS_Dereg_conflict
, mDNS_Dereg_repeat
} mDNS_Dereg_type
;
2582 // NOTE: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
2583 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2584 mDNSlocal mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
2586 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
2587 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
2588 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0)) p
= &m
->LocalOnlyRecords
;
2589 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2593 // We found our record on the main list. See if there are any duplicates that need special handling.
2594 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
2596 AuthRecord
*r2
= m
->DuplicateRecords
;
2599 if (RecordIsLocalDuplicate(r2
, rr
)) { mDNS_Deregister_internal(m
, r2
, drt
); r2
= m
->DuplicateRecords
; }
2605 // Before we delete the record (and potentially send a goodbye packet)
2606 // first see if we have a record on the duplicate list ready to take over from it.
2607 AuthRecord
**d
= &m
->DuplicateRecords
;
2608 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
2611 AuthRecord
*dup
= *d
;
2612 debugf("Duplicate record %p taking over from %p %##s (%s)", dup
, rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2613 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
2614 dup
->next
= rr
->next
; // And then...
2615 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
2616 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
2617 dup
->ProbeCount
= rr
->ProbeCount
;
2618 dup
->AnnounceCount
= rr
->AnnounceCount
;
2619 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
2620 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
2621 dup
->v4Requester
= rr
->v4Requester
;
2622 dup
->v6Requester
= rr
->v6Requester
;
2623 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
2624 dup
->AnnounceUntil
= rr
->AnnounceUntil
;
2625 dup
->LastAPTime
= rr
->LastAPTime
;
2626 dup
->LastMCTime
= rr
->LastMCTime
;
2627 dup
->LastMCInterface
= rr
->LastMCInterface
;
2628 if (RecordType
== kDNSRecordTypeShared
) rr
->AnnounceCount
= InitialAnnounceCount
;
2634 // We didn't find our record on the main list; try the DuplicateRecords list instead.
2635 p
= &m
->DuplicateRecords
;
2636 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2637 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2638 if (*p
&& RecordType
== kDNSRecordTypeShared
) rr
->AnnounceCount
= InitialAnnounceCount
;
2639 if (*p
) debugf("DNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2644 // No need to log an error message if we already know this is a potentially repeated deregistration
2645 if (drt
!= mDNS_Dereg_repeat
)
2646 debugf("mDNS_Deregister_internal: Record %p %##s (%s) not found in list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2647 return(mStatus_BadReferenceErr
);
2650 // If this is a shared record and we've announced it at least once,
2651 // we need to retract that announcement before we delete the record
2652 if (RecordType
== kDNSRecordTypeShared
&& rr
->AnnounceCount
< InitialAnnounceCount
)
2654 verbosedebugf("mDNS_Deregister_internal: Sending deregister for %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2655 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2656 rr
->resrec
.rroriginalttl
= 0;
2657 rr
->ImmedAnswer
= mDNSInterfaceMark
;
2658 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0))
2659 m
->DiscardLocalOnlyRecords
= mDNStrue
;
2662 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
2663 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
2668 *p
= rr
->next
; // Cut this record from the list
2669 // If someone is about to look at this, bump the pointer forward
2670 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
2671 if (m
->NewLocalOnlyRecords
== rr
) m
->NewLocalOnlyRecords
= rr
->next
;
2672 rr
->next
= mDNSNULL
;
2674 if (RecordType
== kDNSRecordTypeUnregistered
)
2675 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeUnregistered",
2676 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2677 else if (RecordType
== kDNSRecordTypeDeregistering
)
2678 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeDeregistering",
2679 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2682 verbosedebugf("mDNS_Deregister_internal: Deleting record for %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2683 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
2686 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
2687 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2688 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2690 // If we have an update queued up which never executed, give the client a chance to free that memory
2693 RData
*OldRData
= rr
->resrec
.rdata
;
2694 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
2695 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
2696 if (rr
->UpdateCallback
)
2697 rr
->UpdateCallback(m
, rr
, OldRData
); // ... and let the client know
2700 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2701 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2702 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2703 // so any attempt to touch rr after this is likely to lead to a crash.
2704 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2705 if (RecordType
== kDNSRecordTypeShared
)
2707 if (rr
->RecordCallback
)
2708 rr
->RecordCallback(m
, rr
, mStatus_MemFree
);
2710 else if (drt
== mDNS_Dereg_conflict
)
2712 RecordProbeFailure(m
, rr
);
2713 if (rr
->RecordCallback
)
2714 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
);
2716 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2718 return(mStatus_NoError
);
2721 // ***************************************************************************
2722 #if COMPILER_LIKES_PRAGMA_MARK
2725 #pragma mark - DNS Message Creation Functions
2728 mDNSlocal
void InitializeDNSMessage(DNSMessageHeader
*h
, mDNSOpaque16 id
, mDNSOpaque16 flags
)
2732 h
->numQuestions
= 0;
2734 h
->numAuthorities
= 0;
2735 h
->numAdditionals
= 0;
2738 mDNSlocal
const mDNSu8
*FindCompressionPointer(const mDNSu8
*const base
, const mDNSu8
*const end
, const mDNSu8
*const domname
)
2740 const mDNSu8
*result
= end
- *domname
- 1;
2742 if (*domname
== 0) return(mDNSNULL
); // There's no point trying to match just the root label
2744 // This loop examines each possible starting position in packet, starting end of the packet and working backwards
2745 while (result
>= base
)
2747 // If the length byte and first character of the label match, then check further to see
2748 // if this location in the packet will yield a useful name compression pointer.
2749 if (result
[0] == domname
[0] && result
[1] == domname
[1])
2751 const mDNSu8
*name
= domname
;
2752 const mDNSu8
*targ
= result
;
2753 while (targ
+ *name
< end
)
2755 // First see if this label matches
2757 const mDNSu8
*pointertarget
;
2758 for (i
=0; i
<= *name
; i
++) if (targ
[i
] != name
[i
]) break;
2759 if (i
<= *name
) break; // If label did not match, bail out
2760 targ
+= 1 + *name
; // Else, did match, so advance target pointer
2761 name
+= 1 + *name
; // and proceed to check next label
2762 if (*name
== 0 && *targ
== 0) return(result
); // If no more labels, we found a match!
2763 if (*name
== 0) break; // If no more labels to match, we failed, so bail out
2765 // The label matched, so now follow the pointer (if appropriate) and then see if the next label matches
2766 if (targ
[0] < 0x40) continue; // If length value, continue to check next label
2767 if (targ
[0] < 0xC0) break; // If 40-BF, not valid
2768 if (targ
+1 >= end
) break; // Second byte not present!
2769 pointertarget
= base
+ (((mDNSu16
)(targ
[0] & 0x3F)) << 8) + targ
[1];
2770 if (targ
< pointertarget
) break; // Pointertarget must point *backwards* in the packet
2771 if (pointertarget
[0] >= 0x40) break; // Pointertarget must point to a valid length byte
2772 targ
= pointertarget
;
2775 result
--; // We failed to match at this search position, so back up the tentative result pointer and try again
2780 // Put a string of dot-separated labels as length-prefixed labels
2781 // domainname is a fully-qualified name (i.e. assumed to be ending in a dot, even if it doesn't)
2782 // msg points to the message we're building (pass mDNSNULL if we don't want to use compression pointers)
2783 // end points to the end of the message so far
2784 // ptr points to where we want to put the name
2785 // limit points to one byte past the end of the buffer that we must not overrun
2786 // domainname is the name to put
2787 mDNSlocal mDNSu8
*putDomainNameAsLabels(const DNSMessage
*const msg
,
2788 mDNSu8
*ptr
, const mDNSu8
*const limit
, const domainname
*const name
)
2790 const mDNSu8
*const base
= (const mDNSu8
*)msg
;
2791 const mDNSu8
* np
= name
->c
;
2792 const mDNSu8
*const max
= name
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
2793 const mDNSu8
* pointer
= mDNSNULL
;
2794 const mDNSu8
*const searchlimit
= ptr
;
2796 while (*np
&& ptr
< limit
-1) // While we've got characters in the name, and space to write them in the message...
2798 if (*np
> MAX_DOMAIN_LABEL
)
2799 { LogMsg("Malformed domain name %##s (label more than 63 bytes)", name
->c
); return(mDNSNULL
); }
2801 // This check correctly allows for the final trailing root label:
2803 // Suppose our domain name is exactly 255 bytes long, including the final trailing root label.
2804 // Suppose np is now at name->c[248], and we're about to write our last non-null label ("local").
2805 // We know that max will be at name->c[255]
2806 // That means that np + 1 + 5 == max - 1, so we (just) pass the "if" test below, write our
2807 // six bytes, then exit the loop, write the final terminating root label, and the domain
2808 // name we've written is exactly 255 bytes long, exactly at the correct legal limit.
2809 // If the name is one byte longer, then we fail the "if" test below, and correctly bail out.
2810 if (np
+ 1 + *np
>= max
)
2811 { LogMsg("Malformed domain name %##s (more than 255 bytes)", name
->c
); return(mDNSNULL
); }
2813 if (base
) pointer
= FindCompressionPointer(base
, searchlimit
, np
);
2814 if (pointer
) // Use a compression pointer if we can
2816 mDNSu16 offset
= (mDNSu16
)(pointer
- base
);
2817 *ptr
++ = (mDNSu8
)(0xC0 | (offset
>> 8));
2818 *ptr
++ = (mDNSu8
)( offset
);
2821 else // Else copy one label and try again
2825 if (ptr
+ 1 + len
>= limit
) return(mDNSNULL
);
2827 for (i
=0; i
<len
; i
++) *ptr
++ = *np
++;
2831 if (ptr
< limit
) // If we didn't run out of space
2833 *ptr
++ = 0; // Put the final root label
2834 return(ptr
); // and return
2840 mDNSlocal mDNSu8
*putRData(const DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
, ResourceRecord
*rr
)
2844 case kDNSType_A
: if (rr
->rdlength
!= 4)
2846 debugf("putRData: Illegal length %d for kDNSType_A", rr
->rdlength
);
2849 if (ptr
+ 4 > limit
) return(mDNSNULL
);
2850 *ptr
++ = rr
->rdata
->u
.ip
.b
[0];
2851 *ptr
++ = rr
->rdata
->u
.ip
.b
[1];
2852 *ptr
++ = rr
->rdata
->u
.ip
.b
[2];
2853 *ptr
++ = rr
->rdata
->u
.ip
.b
[3];
2856 case kDNSType_CNAME
:// Same as PTR
2857 case kDNSType_PTR
: return(putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->rdata
->u
.name
));
2859 case kDNSType_HINFO
:// Same as TXT
2860 case kDNSType_TXT
: if (ptr
+ rr
->rdlength
> limit
) return(mDNSNULL
);
2861 mDNSPlatformMemCopy(rr
->rdata
->u
.data
, ptr
, rr
->rdlength
);
2862 return(ptr
+ rr
->rdlength
);
2864 case kDNSType_AAAA
: if (rr
->rdlength
!= sizeof(rr
->rdata
->u
.ipv6
))
2866 debugf("putRData: Illegal length %d for kDNSType_AAAA", rr
->rdlength
);
2869 if (ptr
+ sizeof(rr
->rdata
->u
.ipv6
) > limit
) return(mDNSNULL
);
2870 mDNSPlatformMemCopy(&rr
->rdata
->u
.ipv6
, ptr
, sizeof(rr
->rdata
->u
.ipv6
));
2871 return(ptr
+ sizeof(rr
->rdata
->u
.ipv6
));
2873 case kDNSType_SRV
: if (ptr
+ 6 > limit
) return(mDNSNULL
);
2874 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.priority
>> 8);
2875 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.priority
);
2876 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.weight
>> 8);
2877 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.weight
);
2878 *ptr
++ = rr
->rdata
->u
.srv
.port
.b
[0];
2879 *ptr
++ = rr
->rdata
->u
.srv
.port
.b
[1];
2880 return(putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->rdata
->u
.srv
.target
));
2882 default: if (ptr
+ rr
->rdlength
> limit
) return(mDNSNULL
);
2883 debugf("putRData: Warning! Writing resource type %d as raw data", rr
->rrtype
);
2884 mDNSPlatformMemCopy(rr
->rdata
->u
.data
, ptr
, rr
->rdlength
);
2885 return(ptr
+ rr
->rdlength
);
2889 mDNSlocal mDNSu8
*PutResourceRecordTTL(DNSMessage
*const msg
, mDNSu8
*ptr
, mDNSu16
*count
, ResourceRecord
*rr
, mDNSu32 ttl
)
2892 mDNSu16 actualLength
;
2893 const mDNSu8
*limit
= msg
->data
+ AbsoluteMaxDNSMessageData
;
2895 // If we have a single large record to put in the packet, then we allow the packet to be up to 9K bytes,
2896 // but in the normal case we try to keep the packets below 1500 to avoid IP fragmentation on standard Ethernet
2897 if (msg
->h
.numAnswers
|| msg
->h
.numAuthorities
|| msg
->h
.numAdditionals
)
2898 limit
= msg
->data
+ NormalMaxDNSMessageData
;
2900 if (rr
->RecordType
== kDNSRecordTypeUnregistered
)
2902 LogMsg("PutResourceRecord ERROR! Attempt to put kDNSRecordTypeUnregistered %##s (%s)", rr
->name
.c
, DNSTypeName(rr
->rrtype
));
2906 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->name
);
2907 if (!ptr
|| ptr
+ 10 >= limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2908 ptr
[0] = (mDNSu8
)(rr
->rrtype
>> 8);
2909 ptr
[1] = (mDNSu8
)(rr
->rrtype
);
2910 ptr
[2] = (mDNSu8
)(rr
->rrclass
>> 8);
2911 ptr
[3] = (mDNSu8
)(rr
->rrclass
);
2912 ptr
[4] = (mDNSu8
)(ttl
>> 24);
2913 ptr
[5] = (mDNSu8
)(ttl
>> 16);
2914 ptr
[6] = (mDNSu8
)(ttl
>> 8);
2915 ptr
[7] = (mDNSu8
)(ttl
);
2916 endofrdata
= putRData(msg
, ptr
+10, limit
, rr
);
2917 if (!endofrdata
) { verbosedebugf("Ran out of space in PutResourceRecord for %##s (%s)", rr
->name
.c
, DNSTypeName(rr
->rrtype
)); return(mDNSNULL
); }
2919 // Go back and fill in the actual number of data bytes we wrote
2920 // (actualLength can be less than rdlength when domain name compression is used)
2921 actualLength
= (mDNSu16
)(endofrdata
- ptr
- 10);
2922 ptr
[8] = (mDNSu8
)(actualLength
>> 8);
2923 ptr
[9] = (mDNSu8
)(actualLength
);
2929 #define PutResourceRecord(MSG, P, C, RR) PutResourceRecordTTL((MSG), (P), (C), (RR), (RR)->rroriginalttl)
2931 mDNSlocal mDNSu8
*PutResourceRecordCappedTTL(DNSMessage
*const msg
, mDNSu8
*ptr
, mDNSu16
*count
, ResourceRecord
*rr
, mDNSu32 maxttl
)
2933 if (maxttl
> rr
->rroriginalttl
) maxttl
= rr
->rroriginalttl
;
2934 return(PutResourceRecordTTL(msg
, ptr
, count
, rr
, maxttl
));
2938 mDNSlocal mDNSu8
*putEmptyResourceRecord(DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
,
2939 mDNSu16
*count
, const AuthRecord
*rr
)
2941 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->name
);
2942 if (!ptr
|| ptr
+ 10 > limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2943 ptr
[0] = (mDNSu8
)(rr
->resrec
.rrtype
>> 8); // Put type
2944 ptr
[1] = (mDNSu8
)(rr
->resrec
.rrtype
);
2945 ptr
[2] = (mDNSu8
)(rr
->resrec
.rrclass
>> 8); // Put class
2946 ptr
[3] = (mDNSu8
)(rr
->resrec
.rrclass
);
2947 ptr
[4] = ptr
[5] = ptr
[6] = ptr
[7] = 0; // TTL is zero
2948 ptr
[8] = ptr
[9] = 0; // RDATA length is zero
2954 mDNSlocal mDNSu8
*putQuestion(DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
,
2955 const domainname
*const name
, mDNSu16 rrtype
, mDNSu16 rrclass
)
2957 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, name
);
2958 if (!ptr
|| ptr
+4 >= limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2959 ptr
[0] = (mDNSu8
)(rrtype
>> 8);
2960 ptr
[1] = (mDNSu8
)(rrtype
);
2961 ptr
[2] = (mDNSu8
)(rrclass
>> 8);
2962 ptr
[3] = (mDNSu8
)(rrclass
);
2963 msg
->h
.numQuestions
++;
2967 // ***************************************************************************
2968 #if COMPILER_LIKES_PRAGMA_MARK
2970 #pragma mark - DNS Message Parsing Functions
2973 mDNSlocal
const mDNSu8
*skipDomainName(const DNSMessage
*const msg
, const mDNSu8
*ptr
, const mDNSu8
*const end
)
2977 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
2978 { debugf("skipDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL
); }
2980 while (1) // Read sequence of labels
2982 const mDNSu8 len
= *ptr
++; // Read length of this label
2983 if (len
== 0) return(ptr
); // If length is zero, that means this name is complete
2986 case 0x00: if (ptr
+ len
>= end
) // Remember: expect at least one more byte for the root label
2987 { debugf("skipDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL
); }
2988 if (total
+ 1 + len
>= MAX_DOMAIN_NAME
) // Remember: expect at least one more byte for the root label
2989 { debugf("skipDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL
); }
2994 case 0x40: debugf("skipDomainName: Extended EDNS0 label types 0x%X not supported", len
); return(mDNSNULL
);
2995 case 0x80: debugf("skipDomainName: Illegal label length 0x%X", len
); return(mDNSNULL
);
2996 case 0xC0: return(ptr
+1);
3001 // Routine to fetch an FQDN from the DNS message, following compression pointers if necessary.
3002 mDNSlocal
const mDNSu8
*getDomainName(const DNSMessage
*const msg
, const mDNSu8
*ptr
, const mDNSu8
*const end
,
3003 domainname
*const name
)
3005 const mDNSu8
*nextbyte
= mDNSNULL
; // Record where we got to before we started following pointers
3006 mDNSu8
*np
= name
->c
; // Name pointer
3007 const mDNSu8
*const limit
= np
+ MAX_DOMAIN_NAME
; // Limit so we don't overrun buffer
3009 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
3010 { debugf("getDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL
); }
3012 *np
= 0; // Tentatively place the root label here (may be overwritten if we have more labels)
3014 while (1) // Read sequence of labels
3016 const mDNSu8 len
= *ptr
++; // Read length of this label
3017 if (len
== 0) break; // If length is zero, that means this name is complete
3023 case 0x00: if (ptr
+ len
>= end
) // Remember: expect at least one more byte for the root label
3024 { debugf("getDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL
); }
3025 if (np
+ 1 + len
>= limit
) // Remember: expect at least one more byte for the root label
3026 { debugf("getDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL
); }
3028 for (i
=0; i
<len
; i
++) *np
++ = *ptr
++;
3029 *np
= 0; // Tentatively place the root label here (may be overwritten if we have more labels)
3032 case 0x40: debugf("getDomainName: Extended EDNS0 label types 0x%X not supported in name %##s", len
, name
->c
);
3035 case 0x80: debugf("getDomainName: Illegal label length 0x%X in domain name %##s", len
, name
->c
); return(mDNSNULL
);
3037 case 0xC0: offset
= (mDNSu16
)((((mDNSu16
)(len
& 0x3F)) << 8) | *ptr
++);
3038 if (!nextbyte
) nextbyte
= ptr
; // Record where we got to before we started following pointers
3039 ptr
= (mDNSu8
*)msg
+ offset
;
3040 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
3041 { debugf("getDomainName: Illegal compression pointer not within packet boundaries"); return(mDNSNULL
); }
3043 { debugf("getDomainName: Compression pointer must point to real label"); return(mDNSNULL
); }
3048 if (nextbyte
) return(nextbyte
);
3052 mDNSlocal
const mDNSu8
*skipResourceRecord(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
)
3054 mDNSu16 pktrdlength
;
3056 ptr
= skipDomainName(msg
, ptr
, end
);
3057 if (!ptr
) { debugf("skipResourceRecord: Malformed RR name"); return(mDNSNULL
); }
3059 if (ptr
+ 10 > end
) { debugf("skipResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL
); }
3060 pktrdlength
= (mDNSu16
)((mDNSu16
)ptr
[8] << 8 | ptr
[9]);
3062 if (ptr
+ pktrdlength
> end
) { debugf("skipResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL
); }
3064 return(ptr
+ pktrdlength
);
3067 #define GetLargeResourceRecord(m, msg, p, e, i, t, L) \
3068 (((L)->r.rdatastorage.MaxRDLength = MaximumRDSize), GetResourceRecord((m), (msg), (p), (e), (i), (t), &(L)->r, (RData*)&(L)->r.rdatastorage))
3070 mDNSlocal
const mDNSu8
*GetResourceRecord(mDNS
*const m
, const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
,
3071 const mDNSInterfaceID InterfaceID
, mDNSu8 RecordType
, CacheRecord
*rr
, RData
*RDataStorage
)
3073 mDNSu16 pktrdlength
;
3075 rr
->next
= mDNSNULL
;
3076 rr
->resrec
.RecordType
= RecordType
;
3078 rr
->NextInKAList
= mDNSNULL
;
3079 rr
->TimeRcvd
= m
->timenow
;
3080 rr
->NextRequiredQuery
= m
->timenow
; // Will be updated to the real value when we call SetNextCacheCheckTime()
3081 rr
->LastUsed
= m
->timenow
;
3083 rr
->CRActiveQuestion
= mDNSNULL
;
3084 rr
->UnansweredQueries
= 0;
3085 rr
->LastUnansweredTime
= 0;
3086 rr
->MPUnansweredQ
= 0;
3087 rr
->MPLastUnansweredQT
= 0;
3088 rr
->MPUnansweredKA
= 0;
3089 rr
->MPExpectingKA
= mDNSfalse
;
3090 rr
->NextInCFList
= mDNSNULL
;
3092 rr
->resrec
.InterfaceID
= InterfaceID
;
3093 ptr
= getDomainName(msg
, ptr
, end
, &rr
->resrec
.name
);
3094 if (!ptr
) { debugf("GetResourceRecord: Malformed RR name"); return(mDNSNULL
); }
3096 if (ptr
+ 10 > end
) { debugf("GetResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL
); }
3098 rr
->resrec
.rrtype
= (mDNSu16
) ((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
3099 rr
->resrec
.rrclass
= (mDNSu16
)(((mDNSu16
)ptr
[2] << 8 | ptr
[3]) & kDNSClass_Mask
);
3100 rr
->resrec
.rroriginalttl
= (mDNSu32
) ((mDNSu32
)ptr
[4] << 24 | (mDNSu32
)ptr
[5] << 16 | (mDNSu32
)ptr
[6] << 8 | ptr
[7]);
3101 if (rr
->resrec
.rroriginalttl
> 0x70000000UL
/ mDNSPlatformOneSecond
)
3102 rr
->resrec
.rroriginalttl
= 0x70000000UL
/ mDNSPlatformOneSecond
;
3103 // Note: We don't have to adjust m->NextCacheCheck here -- this is just getting a record into memory for
3104 // us to look at. If we decide to copy it into the cache, then we'll update m->NextCacheCheck accordingly.
3105 pktrdlength
= (mDNSu16
)((mDNSu16
)ptr
[8] << 8 | ptr
[9]);
3106 if (ptr
[2] & (kDNSClass_UniqueRRSet
>> 8))
3107 rr
->resrec
.RecordType
|= kDNSRecordTypePacketUniqueMask
;
3109 if (ptr
+ pktrdlength
> end
) { debugf("GetResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL
); }
3112 rr
->resrec
.rdata
= RDataStorage
;
3115 rr
->resrec
.rdata
= (RData
*)&rr
->rdatastorage
;
3116 rr
->resrec
.rdata
->MaxRDLength
= sizeof(RDataBody
);
3119 switch (rr
->resrec
.rrtype
)
3121 case kDNSType_A
: rr
->resrec
.rdata
->u
.ip
.b
[0] = ptr
[0];
3122 rr
->resrec
.rdata
->u
.ip
.b
[1] = ptr
[1];
3123 rr
->resrec
.rdata
->u
.ip
.b
[2] = ptr
[2];
3124 rr
->resrec
.rdata
->u
.ip
.b
[3] = ptr
[3];
3127 case kDNSType_CNAME
:// Same as PTR
3128 case kDNSType_PTR
: if (!getDomainName(msg
, ptr
, end
, &rr
->resrec
.rdata
->u
.name
))
3129 { debugf("GetResourceRecord: Malformed CNAME/PTR RDATA name"); return(mDNSNULL
); }
3130 //debugf("%##s PTR %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.name.c, pktrdlength);
3133 case kDNSType_NULL
: //Same as TXT
3134 case kDNSType_HINFO
://Same as TXT
3135 case kDNSType_TXT
: if (pktrdlength
> rr
->resrec
.rdata
->MaxRDLength
)
3137 debugf("GetResourceRecord: %s rdata size (%d) exceeds storage (%d)",
3138 DNSTypeName(rr
->resrec
.rrtype
), pktrdlength
, rr
->resrec
.rdata
->MaxRDLength
);
3141 rr
->resrec
.rdlength
= pktrdlength
;
3142 mDNSPlatformMemCopy(ptr
, rr
->resrec
.rdata
->u
.data
, pktrdlength
);
3145 case kDNSType_AAAA
: mDNSPlatformMemCopy(ptr
, &rr
->resrec
.rdata
->u
.ipv6
, sizeof(rr
->resrec
.rdata
->u
.ipv6
));
3148 case kDNSType_SRV
: rr
->resrec
.rdata
->u
.srv
.priority
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
3149 rr
->resrec
.rdata
->u
.srv
.weight
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
3150 rr
->resrec
.rdata
->u
.srv
.port
.b
[0] = ptr
[4];
3151 rr
->resrec
.rdata
->u
.srv
.port
.b
[1] = ptr
[5];
3152 if (!getDomainName(msg
, ptr
+6, end
, &rr
->resrec
.rdata
->u
.srv
.target
))
3153 { debugf("GetResourceRecord: Malformed SRV RDATA name"); return(mDNSNULL
); }
3154 //debugf("%##s SRV %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.srv.target.c, pktrdlength);
3157 default: if (pktrdlength
> rr
->resrec
.rdata
->MaxRDLength
)
3159 debugf("GetResourceRecord: rdata %d (%s) size (%d) exceeds storage (%d)",
3160 rr
->resrec
.rrtype
, DNSTypeName(rr
->resrec
.rrtype
), pktrdlength
, rr
->resrec
.rdata
->MaxRDLength
);
3163 debugf("GetResourceRecord: Warning! Reading resource type %d (%s) as opaque data",
3164 rr
->resrec
.rrtype
, DNSTypeName(rr
->resrec
.rrtype
));
3165 // Note: Just because we don't understand the record type, that doesn't
3166 // mean we fail. The DNS protocol specifies rdlength, so we can
3167 // safely skip over unknown records and ignore them.
3168 // We also grab a binary copy of the rdata anyway, since the caller
3169 // might know how to interpret it even if we don't.
3170 rr
->resrec
.rdlength
= pktrdlength
;
3171 mDNSPlatformMemCopy(ptr
, rr
->resrec
.rdata
->u
.data
, pktrdlength
);
3175 rr
->resrec
.namehash
= DomainNameHashValue(&rr
->resrec
.name
);
3176 SetNewRData(&rr
->resrec
, mDNSNULL
, 0);
3178 return(ptr
+ pktrdlength
);
3181 mDNSlocal
const mDNSu8
*skipQuestion(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
)
3183 ptr
= skipDomainName(msg
, ptr
, end
);
3184 if (!ptr
) { debugf("skipQuestion: Malformed domain name in DNS question section"); return(mDNSNULL
); }
3185 if (ptr
+4 > end
) { debugf("skipQuestion: Malformed DNS question section -- no query type and class!"); return(mDNSNULL
); }
3189 mDNSlocal
const mDNSu8
*getQuestion(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
, const mDNSInterfaceID InterfaceID
,
3190 DNSQuestion
*question
)
3192 question
->InterfaceID
= InterfaceID
;
3193 ptr
= getDomainName(msg
, ptr
, end
, &question
->qname
);
3194 if (!ptr
) { debugf("Malformed domain name in DNS question section"); return(mDNSNULL
); }
3195 if (ptr
+4 > end
) { debugf("Malformed DNS question section -- no query type and class!"); return(mDNSNULL
); }
3197 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
3198 question
->qtype
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]); // Get type
3199 question
->qclass
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]); // and class
3203 mDNSlocal
const mDNSu8
*LocateAnswers(const DNSMessage
*const msg
, const mDNSu8
*const end
)
3206 const mDNSu8
*ptr
= msg
->data
;
3207 for (i
= 0; i
< msg
->h
.numQuestions
&& ptr
; i
++) ptr
= skipQuestion(msg
, ptr
, end
);
3211 mDNSlocal
const mDNSu8
*LocateAuthorities(const DNSMessage
*const msg
, const mDNSu8
*const end
)
3214 const mDNSu8
*ptr
= LocateAnswers(msg
, end
);
3215 for (i
= 0; i
< msg
->h
.numAnswers
&& ptr
; i
++) ptr
= skipResourceRecord(msg
, ptr
, end
);
3219 // ***************************************************************************
3220 #if COMPILER_LIKES_PRAGMA_MARK
3223 #pragma mark - Packet Sending Functions
3226 mDNSlocal mStatus
mDNSSendDNSMessage(const mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
3227 mDNSInterfaceID InterfaceID
, mDNSIPPort srcport
, const mDNSAddr
*dst
, mDNSIPPort dstport
)
3230 mDNSu16 numQuestions
= msg
->h
.numQuestions
;
3231 mDNSu16 numAnswers
= msg
->h
.numAnswers
;
3232 mDNSu16 numAuthorities
= msg
->h
.numAuthorities
;
3233 mDNSu16 numAdditionals
= msg
->h
.numAdditionals
;
3235 // Put all the integer values in IETF byte-order (MSB first, LSB second)
3236 mDNSu8
*ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
3237 *ptr
++ = (mDNSu8
)(numQuestions
>> 8);
3238 *ptr
++ = (mDNSu8
)(numQuestions
);
3239 *ptr
++ = (mDNSu8
)(numAnswers
>> 8);
3240 *ptr
++ = (mDNSu8
)(numAnswers
);
3241 *ptr
++ = (mDNSu8
)(numAuthorities
>> 8);
3242 *ptr
++ = (mDNSu8
)(numAuthorities
);
3243 *ptr
++ = (mDNSu8
)(numAdditionals
>> 8);
3244 *ptr
++ = (mDNSu8
)(numAdditionals
);
3246 // Send the packet on the wire
3247 status
= mDNSPlatformSendUDP(m
, msg
, end
, InterfaceID
, srcport
, dst
, dstport
);
3249 // Put all the integer values back the way they were before we return
3250 msg
->h
.numQuestions
= numQuestions
;
3251 msg
->h
.numAnswers
= numAnswers
;
3252 msg
->h
.numAuthorities
= numAuthorities
;
3253 msg
->h
.numAdditionals
= numAdditionals
;
3258 mDNSlocal
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
3260 // Setting AnnounceCount to InitialAnnounceCount signals mDNS_Deregister_internal()
3261 // that it should go ahead and immediately dispose of this registration
3262 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
3263 rr
->AnnounceCount
= InitialAnnounceCount
;
3264 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
3267 // NOTE: DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback, which may change
3268 // the record list and/or question list.
3269 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3270 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
3272 if (m
->CurrentRecord
) LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set");
3273 m
->CurrentRecord
= m
->ResourceRecords
;
3275 while (m
->CurrentRecord
)
3277 AuthRecord
*rr
= m
->CurrentRecord
;
3278 m
->CurrentRecord
= rr
->next
;
3279 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3280 CompleteDeregistration(m
, rr
);
3284 mDNSlocal mDNSBool
HaveSentEntireRRSet(const mDNS
*const m
, const AuthRecord
*const rr
, mDNSInterfaceID InterfaceID
)
3286 // Try to find another member of this set that we're still planning to send on this interface
3287 const AuthRecord
*a
;
3288 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
3289 if (a
->SendRNow
== InterfaceID
&& a
!= rr
&& SameResourceRecordSignature(&a
->resrec
, &rr
->resrec
)) break;
3290 return (a
== mDNSNULL
); // If no more members of this set found, then we should set the cache flush bit
3293 // Note about acceleration of announcements to facilitate automatic coalescing of
3294 // multiple independent threads of announcements into a single synchronized thread:
3295 // The announcements in the packet may be at different stages of maturity;
3296 // One-second interval, two-second interval, four-second interval, and so on.
3297 // After we've put in all the announcements that are due, we then consider
3298 // whether there are other nearly-due announcements that are worth accelerating.
3299 // To be eligible for acceleration, a record MUST NOT be older (further along
3300 // its timeline) than the most mature record we've already put in the packet.
3301 // In other words, younger records can have their timelines accelerated to catch up
3302 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
3303 // Older records cannot have their timelines accelerated; this would just widen
3304 // the gap between them and their younger bretheren and get them even more out of sync.
3306 // NOTE: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
3307 // the record list and/or question list.
3308 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3309 mDNSlocal
void SendResponses(mDNS
*const m
)
3312 AuthRecord
*rr
, *r2
;
3313 mDNSs32 maxExistingAnnounceInterval
= 0;
3314 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3316 m
->NextScheduledResponse
= m
->timenow
+ 0x78000000;
3319 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
3322 // Run through our list of records, and decide which ones we're going to announce on all interfaces
3323 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3325 if (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0)
3327 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
3328 else rr
->NextUpdateCredit
= (m
->timenow
+ mDNSPlatformOneSecond
* 60) | 1;
3330 if (TimeToAnnounceThisRecord(rr
, m
->timenow
) && ResourceRecordIsValidAnswer(rr
))
3332 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
3333 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
3334 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
3335 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
3339 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
3340 // Eligible records that are more than half-way to their announcement time are accelerated
3341 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3342 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
3343 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
3344 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
3345 ResourceRecordIsValidAnswer(rr
)))
3346 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
3348 // When sending SRV records (particularly when announcing a new service) automatically add the related Address record(s)
3349 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3350 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
3351 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
3352 if (RRIsAddressType(r2
) && // For all address records (A/AAAA) ...
3353 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
3354 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
3355 rr
->resrec
.rdnamehash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
3356 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, &r2
->resrec
.name
) &&
3357 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
3358 r2
->ImmedAnswer
= mDNSInterfaceMark
; // ... then mark this address record for sending too
3360 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
3361 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
3362 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
3363 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
3364 // -- 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
3365 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
3366 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3367 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3369 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
3371 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3372 if (ResourceRecordIsValidAnswer(r2
))
3373 if (r2
->ImmedAnswer
!= mDNSInterfaceMark
&& r2
->ImmedAnswer
!= rr
->ImmedAnswer
&& SameResourceRecordSignature(&r2
->resrec
, &rr
->resrec
))
3374 r2
->ImmedAnswer
= rr
->ImmedAnswer
;
3376 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
3378 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3379 if (ResourceRecordIsValidAnswer(r2
))
3380 if (r2
->ImmedAdditional
!= rr
->ImmedAdditional
&& SameResourceRecordSignature(&r2
->resrec
, &rr
->resrec
))
3381 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
3385 // Now set SendRNow state appropriately
3386 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3388 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
3390 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
3391 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
3392 rr
->LastMCTime
= m
->timenow
;
3393 rr
->LastMCInterface
= rr
->ImmedAnswer
;
3394 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
3395 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
3397 rr
->AnnounceCount
--;
3398 rr
->ThisAPInterval
*= 2;
3399 rr
->LastAPTime
= m
->timenow
;
3400 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- rr
->AnnounceUntil
>= 0) rr
->AnnounceCount
= 0;
3401 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
3404 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
3406 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
3407 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
3408 rr
->LastMCTime
= m
->timenow
;
3409 rr
->LastMCInterface
= rr
->ImmedAnswer
;
3411 SetNextAnnounceProbeTime(m
, rr
);
3415 // *** 2. Loop through interface list, sending records as appropriate
3421 int numAnnounce
= 0;
3423 DNSMessage response
;
3424 mDNSu8
*responseptr
= response
.data
;
3426 InitializeDNSMessage(&response
.h
, zeroID
, ResponseFlags
);
3428 // First Pass. Look for:
3429 // 1. Deregistering records that need to send their goodbye packet
3430 // 2. Updated records that need to retract their old data
3431 // 3. Answers and announcements we need to send
3432 // In all cases, if we fail, and we've put at least one answer, we break out of the for loop so we can
3433 // send this packet and then try again.
3434 // If we have not put even one answer, then we don't bail out. We pretend we succeeded anyway,
3435 // because otherwise we'll end up in an infinite loop trying to send a record that will never fit.
3436 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3437 if (rr
->SendRNow
== intf
->InterfaceID
)
3439 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3441 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, 0);
3442 if (!newptr
&& response
.h
.numAnswers
) break;
3444 responseptr
= newptr
;
3446 else if (rr
->NewRData
) // If we have new data for this record
3448 RData
*OldRData
= rr
->resrec
.rdata
;
3449 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
3450 // See if we should send a courtesy "goodbye" the old data before we replace it.
3451 // We compare with "InitialAnnounceCount-1" instead of "InitialAnnounceCount" because by the time
3452 // we get to this place in this routine we've we've already decremented rr->AnnounceCount
3453 if (ResourceRecordIsValidAnswer(rr
) && rr
->AnnounceCount
< InitialAnnounceCount
-1)
3455 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, 0);
3456 if (!newptr
&& response
.h
.numAnswers
) break;
3458 responseptr
= newptr
;
3460 // Now try to see if we can fit the update in the same packet (not fatal if we can't)
3461 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
3462 if ((rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && HaveSentEntireRRSet(m
, rr
, intf
->InterfaceID
))
3463 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3464 newptr
= PutResourceRecord(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
);
3465 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3466 if (newptr
) responseptr
= newptr
;
3467 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
3471 if ((rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && HaveSentEntireRRSet(m
, rr
, intf
->InterfaceID
))
3472 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3473 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, m
->SleepState
? 0 : rr
->resrec
.rroriginalttl
);
3474 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3475 if (!newptr
&& response
.h
.numAnswers
) break;
3476 if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++; else numAnswer
++;
3477 responseptr
= newptr
;
3479 // If sending on all interfaces, go to next interface; else we're finished now
3480 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
3481 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
3483 rr
->SendRNow
= mDNSNULL
;
3486 // Second Pass. Add additional records, if there's space.
3487 newptr
= responseptr
;
3488 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3489 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
3491 // Since additionals are optional, we clear ImmedAdditional anyway, even if we subsequently find it doesn't fit in the packet
3492 rr
->ImmedAdditional
= mDNSNULL
;
3493 if (newptr
&& ResourceRecordIsValidAnswer(rr
))
3495 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3497 // Try to find another member of this set that we're still planning to send on this interface
3498 const AuthRecord
*a
;
3499 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
3500 if (a
->ImmedAdditional
== intf
->InterfaceID
&& SameResourceRecordSignature(&a
->resrec
, &rr
->resrec
)) break;
3501 if (a
== mDNSNULL
) // If no more members of this set found
3502 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3504 newptr
= PutResourceRecord(&response
, newptr
, &response
.h
.numAdditionals
, &rr
->resrec
);
3505 if (newptr
) responseptr
= newptr
;
3506 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3510 if (response
.h
.numAnswers
> 0) // We *never* send a packet with only additionals in it
3512 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3513 numDereg
, numDereg
== 1 ? "" : "s",
3514 numAnnounce
, numAnnounce
== 1 ? "" : "s",
3515 numAnswer
, numAnswer
== 1 ? "" : "s",
3516 response
.h
.numAdditionals
, response
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
3517 mDNSSendDNSMessage(m
, &response
, responseptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v4
, MulticastDNSPort
);
3518 mDNSSendDNSMessage(m
, &response
, responseptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v6
, MulticastDNSPort
);
3519 if (!m
->SuppressSending
) m
->SuppressSending
= (m
->timenow
+ mDNSPlatformOneSecond
/10) | 1; // OR with one to ensure non-zero
3520 if (++pktcount
>= 1000)
3521 { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
3522 // There might be more things to send on this interface, so go around one more time and try again.
3524 else // Nothing more to send on this interface; go to next
3526 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3527 #if MDNS_DEBUGMSGS && 0
3528 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3529 debugf(msg
, intf
, next
);
3536 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3539 if (m
->CurrentRecord
) LogMsg("SendResponses: ERROR m->CurrentRecord already set");
3540 m
->CurrentRecord
= m
->ResourceRecords
;
3541 while (m
->CurrentRecord
)
3543 rr
= m
->CurrentRecord
;
3544 m
->CurrentRecord
= rr
->next
;
3548 RData
*OldRData
= rr
->resrec
.rdata
;
3549 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
3550 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
3551 if (rr
->UpdateCallback
)
3552 rr
->UpdateCallback(m
, rr
, OldRData
); // ... and let the client know
3555 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3556 CompleteDeregistration(m
, rr
);
3559 rr
->ImmedAnswer
= mDNSNULL
;
3560 rr
->v4Requester
= zeroIPAddr
;
3561 rr
->v6Requester
= zerov6Addr
;
3564 verbosedebugf("SendResponses: Next in %d ticks", m
->NextScheduledResponse
- m
->timenow
);
3567 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3568 // so we want to be lazy about how frequently we do it.
3569 // 1. If a cache record is currently referenced by *no* active questions,
3570 // then we don't mind expiring it up to a minute late (who will know?)
3571 // 2. Else, if a cache record is due for some of its final expiration queries,
3572 // we'll allow them to be late by up to 2% of the TTL
3573 // 3. Else, if a cache record has completed all its final expiration queries without success,
3574 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3575 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3576 // so allow at most 1/10 second lateness
3577 #define CacheCheckGracePeriod(RR) ( \
3578 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3579 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
3580 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : (mDNSPlatformOneSecond/10))
3582 // Note: MUST call SetNextCacheCheckTime any time we change:
3584 // rr->resrec.rroriginalttl
3585 // rr->UnansweredQueries
3586 // rr->CRActiveQuestion
3587 mDNSlocal
void SetNextCacheCheckTime(mDNS
*const m
, CacheRecord
*const rr
)
3589 rr
->NextRequiredQuery
= RRExpireTime(rr
);
3591 // If we have an active question, then see if we want to schedule a refresher query for this record.
3592 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3593 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3595 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
3596 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
3597 verbosedebugf("SetNextCacheCheckTime: %##s (%s) NextRequiredQuery in %ld sec",
3598 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
);
3601 if (m
->NextCacheCheck
- (rr
->NextRequiredQuery
+ CacheCheckGracePeriod(rr
)) > 0)
3602 m
->NextCacheCheck
= (rr
->NextRequiredQuery
+ CacheCheckGracePeriod(rr
));
3605 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 45)
3606 #define kDefaultReconfirmTimeForCableDisconnect ((mDNSu32)mDNSPlatformOneSecond * 5)
3607 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3609 mDNSlocal mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
3611 if (interval
< kMinimumReconfirmTime
)
3612 interval
= kMinimumReconfirmTime
;
3613 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3614 interval
= 0x10000000;
3616 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3617 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
3619 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3620 interval
+= mDNSRandom(interval
/3);
3621 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
3622 rr
->resrec
.rroriginalttl
= interval
* 4 / mDNSPlatformOneSecond
;
3623 SetNextCacheCheckTime(m
, rr
);
3625 debugf("mDNS_Reconfirm_internal:%5ld ticks to go for %s", RRExpireTime(rr
) - m
->timenow
, GetRRDisplayString(m
, rr
));
3626 return(mStatus_NoError
);
3629 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
3631 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3632 // It also appends to the list of known answer records that need to be included,
3633 // and updates the forcast for the size of the known answer section.
3634 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, DNSMessage
*query
, mDNSu8
**queryptr
, DNSQuestion
*q
,
3635 CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
3637 mDNSBool ucast
= q
->LargeAnswers
|| q
->ThisQInterval
<= InitialQuestionInterval
*2;
3638 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3639 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
3640 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
3643 debugf("BuildQuestion: No more space in this packet for question %##s", q
->qname
.c
);
3646 else if (newptr
+ *answerforecast
>= limit
)
3648 verbosedebugf("BuildQuestion: Retracting question %##s new forecast total %d", q
->qname
.c
, newptr
+ *answerforecast
- query
->data
);
3649 query
->h
.numQuestions
--;
3654 mDNSu32 forecast
= *answerforecast
;
3656 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
3658 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3659 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3660 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not already in the known answer list
3661 rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3662 ResourceRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3663 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3664 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0)// and we'll ask at least once again before NextRequiredQuery
3666 *ka
= rr
; // Link this record into our known answer chain
3667 ka
= &rr
->NextInKAList
;
3668 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3669 forecast
+= 12 + rr
->resrec
.rdestimate
;
3670 // If we're trying to put more than one question in this packet, and it doesn't fit
3671 // then undo that last question and try again next time
3672 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
3674 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
3675 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
);
3676 query
->h
.numQuestions
--;
3677 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3678 while (*ka
) { CacheRecord
*rr
= *ka
; *ka
= mDNSNULL
; ka
= &rr
->NextInKAList
; }
3679 return(mDNSfalse
); // Return false, so we'll try again in the next packet
3683 // Traffic reduction:
3684 // If we already have at least one unique answer in the cache,
3685 // OR we have so many shared answers that the KA list is too big to fit in one packet
3686 // The we suppress queries number 3 and 5:
3687 // Query 1 (immediately; ThisQInterval = 1 sec; request unicast replies)
3688 // Query 2 (after 1 second; ThisQInterval = 2 sec; send normally)
3689 // Query 3 (after 2 seconds; ThisQInterval = 4 sec; may suppress)
3690 // Query 4 (after 4 seconds; ThisQInterval = 8 sec; send normally)
3691 // Query 5 (after 8 seconds; ThisQInterval = 16 sec; may suppress)
3692 // Query 6 (after 16 seconds; ThisQInterval = 32 sec; send normally)
3693 if (q
->UniqueAnswers
|| newptr
+ forecast
>= limit
)
3694 if (q
->ThisQInterval
== InitialQuestionInterval
* 8 || q
->ThisQInterval
== InitialQuestionInterval
* 32)
3696 query
->h
.numQuestions
--;
3697 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3698 while (*ka
) { CacheRecord
*rr
= *ka
; *ka
= mDNSNULL
; ka
= &rr
->NextInKAList
; }
3699 return(mDNStrue
); // Return true: pretend we succeeded, even though we actually suppressed this question
3702 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3703 *queryptr
= newptr
; // Update the packet pointer
3704 *answerforecast
= forecast
; // Update the forecast
3705 *kalistptrptr
= ka
; // Update the known answer list pointer
3706 if (ucast
) m
->ExpectUnicastResponse
= m
->timenow
;
3708 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // For every resource record in our cache,
3709 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3710 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not in the known answer list
3711 ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) // which answers our question
3713 rr
->UnansweredQueries
++; // indicate that we're expecting a response
3714 rr
->LastUnansweredTime
= m
->timenow
;
3715 SetNextCacheCheckTime(m
, rr
);
3722 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, DNSQuestion
*q
)
3727 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3728 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
3729 if ((target
= GetRRDomainNameTarget(&rr
->resrec
)) && rr
->resrec
.rdnamehash
== q
->qnamehash
&& SameDomainName(target
, &q
->qname
))
3730 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
3733 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3734 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
3737 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3740 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
3743 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3746 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
3749 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3750 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3751 for (i
=0; i
<DupSuppressInfoSize
; i
++)
3752 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
3754 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
3755 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
3756 if (v4
&& v6
) return(mDNStrue
);
3761 mDNSlocal
int RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
3765 // See if we have this one in our list somewhere already
3766 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
3768 // If not, find a slot we can re-use
3769 if (i
>= DupSuppressInfoSize
)
3772 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
3773 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
3777 // Record the info about this query we saw
3779 ds
[i
].InterfaceID
= InterfaceID
;
3785 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
3787 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3788 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
3791 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3792 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
3794 // We forecast: qname (n) type (2) class (2)
3795 mDNSu32 forecast
= (mDNSu32
)DomainNameLength(&q
->qname
) + 4;
3797 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3798 if (rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3799 ResourceRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3800 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3801 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0)// and we'll ask at least once again before NextRequiredQuery
3803 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3804 forecast
+= 12 + rr
->resrec
.rdestimate
;
3805 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
3813 // How Standard Queries are generated:
3814 // 1. The Question Section contains the question
3815 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3817 // How Probe Queries are generated:
3818 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3819 // if some other host is already using *any* records with this name, we want to know about it.
3820 // 2. The Authority Section contains the proposed values we intend to use for one or more
3821 // of our records with that name (analogous to the Update section of DNS Update packets)
3822 // because if some other host is probing at the same time, we each want to know what the other is
3823 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3825 mDNSlocal
void SendQueries(mDNS
*const m
)
3829 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3830 mDNSs32 maxExistingQuestionInterval
= 0;
3831 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3832 CacheRecord
*KnownAnswerList
= mDNSNULL
;
3834 // 1. If time for a query, work out what we need to do
3835 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
3839 m
->NextScheduledQuery
= m
->timenow
+ 0x78000000;
3841 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3842 // to their NextRequiredQuery to be worth batching them together with this one
3843 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3844 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
3845 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3846 if (m
->timenow
+ TicksTTL(rr
)/50 - rr
->NextRequiredQuery
>= 0)
3848 q
= rr
->CRActiveQuestion
;
3849 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(rr
)/20, rr
->resrec
.InterfaceID
);
3850 if (q
->SendQNow
== mDNSNULL
) q
->SendQNow
= rr
->resrec
.InterfaceID
;
3851 else if (q
->SendQNow
!= rr
->resrec
.InterfaceID
) q
->SendQNow
= mDNSInterfaceMark
;
3854 // Scan our list of questions to see which ones we're definitely going to send
3855 for (q
= m
->Questions
; q
; q
=q
->next
)
3856 if (TimeToSendThisQuestion(q
, m
->timenow
))
3858 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3859 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3860 maxExistingQuestionInterval
= q
->ThisQInterval
;
3863 // Scan our list of questions
3864 // (a) to see if there are any more that are worth accelerating, and
3865 // (b) to update the state variables for all the questions we're going to send
3866 for (q
= m
->Questions
; q
; q
=q
->next
)
3868 if (q
->SendQNow
|| (ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
)))
3870 // If at least halfway to next query time, advance to next interval
3871 // If less than halfway to next query time, treat this as logically a repeat of the last transmission, without advancing the interval
3872 if (m
->timenow
- (q
->LastQTime
+ q
->ThisQInterval
/2) >= 0)
3874 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3875 q
->ThisQInterval
*= 2;
3876 if (q
->ThisQInterval
> MaxQuestionInterval
)
3877 q
->ThisQInterval
= MaxQuestionInterval
;
3878 else if (q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* 8)
3880 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents", q
->qname
.c
, DNSTypeName(q
->qtype
));
3881 ReconfirmAntecedents(m
, q
); // If sending third query, and no answers yet, time to begin doubting the source
3885 // Mark for sending. (If no active interfaces, then don't even try.)
3886 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3889 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3890 q
->LastQTime
= m
->timenow
;
3893 // If we recorded a duplicate suppression for this question less than half an interval ago,
3894 // then we consider it recent enough that we don't need to do an identical query ourselves.
3895 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3897 q
->LastQTxTime
= m
->timenow
;
3898 q
->RecentAnswers
= 0;
3900 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3901 SetNextQueryTime(m
,q
);
3905 // 2. Scan our authoritative RR list to see what probes we might need to send
3906 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
3908 m
->NextScheduledProbe
= m
->timenow
+ 0x78000000;
3910 if (m
->CurrentRecord
) LogMsg("SendQueries: ERROR m->CurrentRecord already set");
3911 m
->CurrentRecord
= m
->ResourceRecords
;
3912 while (m
->CurrentRecord
)
3914 AuthRecord
*rr
= m
->CurrentRecord
;
3915 m
->CurrentRecord
= rr
->next
;
3916 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3918 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3919 if (m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
3921 SetNextAnnounceProbeTime(m
, rr
);
3923 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3924 else if (rr
->ProbeCount
)
3926 // Mark for sending. (If no active interfaces, then don't even try.)
3927 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
3928 rr
->LastAPTime
= m
->timenow
;
3930 SetNextAnnounceProbeTime(m
, rr
);
3932 // else, if it has now finished probing, move it to state Verified, and update m->NextScheduledResponse so it will be announced
3936 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3937 rr
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3938 rr
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3939 SetNextAnnounceProbeTime(m
, rr
);
3940 // If we have any records on our duplicate list that match this one, they have now also completed probing
3941 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3942 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, rr
))
3944 CompleteProbing(m
, rr
);
3948 m
->CurrentRecord
= m
->DuplicateRecords
;
3949 while (m
->CurrentRecord
)
3951 AuthRecord
*rr
= m
->CurrentRecord
;
3952 m
->CurrentRecord
= rr
->next
;
3953 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& rr
->ProbeCount
== 0)
3954 CompleteProbing(m
, rr
);
3958 // 3. Now we know which queries and probes we're sending, go through our interface list sending the appropriate queries on each interface
3963 mDNSu8
*queryptr
= query
.data
;
3964 InitializeDNSMessage(&query
.h
, zeroID
, QueryFlags
);
3965 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3966 if (!KnownAnswerList
)
3968 // Start a new known-answer list
3969 CacheRecord
**kalistptr
= &KnownAnswerList
;
3970 mDNSu32 answerforecast
= 0;
3972 // Put query questions in this packet
3973 for (q
= m
->Questions
; q
; q
=q
->next
)
3974 if (q
->SendQNow
== intf
->InterfaceID
)
3976 debugf("SendQueries: %s question for %##s (%s) at %lu forecast total %lu",
3977 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3978 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- query
.data
, queryptr
+ answerforecast
- query
.data
);
3979 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3980 if (SuppressOnThisInterface(q
->DupSuppress
, intf
) ||
3981 BuildQuestion(m
, &query
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3982 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3985 // Put probe questions in this packet
3986 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3987 if (rr
->SendRNow
== intf
->InterfaceID
)
3989 mDNSBool ucast
= rr
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1;
3990 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3991 const mDNSu8
*const limit
= query
.data
+ ((query
.h
.numQuestions
) ? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3992 mDNSu8
*newptr
= putQuestion(&query
, queryptr
, limit
, &rr
->resrec
.name
, kDNSQType_ANY
, (mDNSu16
)(rr
->resrec
.rrclass
| ucbit
));
3993 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3994 mDNSu32 forecast
= answerforecast
+ 12 + rr
->resrec
.rdestimate
;
3995 if (newptr
&& newptr
+ forecast
< limit
)
3998 answerforecast
= forecast
;
3999 rr
->SendRNow
= (rr
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
4000 rr
->IncludeInProbe
= mDNStrue
;
4001 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->ProbeCount
);
4005 verbosedebugf("SendQueries: Retracting Question %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4006 query
.h
.numQuestions
--;
4011 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
4012 while (KnownAnswerList
)
4014 CacheRecord
*rr
= KnownAnswerList
;
4015 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
4016 mDNSu8
*newptr
= PutResourceRecordTTL(&query
, queryptr
, &query
.h
.numAnswers
, &rr
->resrec
, rr
->resrec
.rroriginalttl
- SecsSinceRcvd
);
4019 verbosedebugf("SendQueries: Put %##s (%s) at %lu - %lu", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), queryptr
- query
.data
, newptr
- query
.data
);
4021 KnownAnswerList
= rr
->NextInKAList
;
4022 rr
->NextInKAList
= mDNSNULL
;
4026 // If we ran out of space and we have more than one question in the packet, that's an error --
4027 // we shouldn't have put more than one question if there was a risk of us running out of space.
4028 if (query
.h
.numQuestions
> 1)
4029 LogMsg("SendQueries: Put %d answers; No more space for known answers", query
.h
.numAnswers
);
4030 query
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
4035 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4036 if (rr
->IncludeInProbe
)
4038 mDNSu8
*newptr
= PutResourceRecord(&query
, queryptr
, &query
.h
.numAuthorities
, &rr
->resrec
);
4039 rr
->IncludeInProbe
= mDNSfalse
;
4040 if (newptr
) queryptr
= newptr
;
4041 else LogMsg("SendQueries: How did we fail to have space for the Update record %##s (%s)?",
4042 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4045 if (queryptr
> query
.data
)
4047 if ((query
.h
.flags
.b
[0] & kDNSFlag0_TC
) && query
.h
.numQuestions
> 1)
4048 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet\n", query
.h
.numQuestions
);
4049 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
4050 query
.h
.numQuestions
, query
.h
.numQuestions
== 1 ? "" : "s",
4051 query
.h
.numAnswers
, query
.h
.numAnswers
== 1 ? "" : "s",
4052 query
.h
.numAuthorities
, query
.h
.numAuthorities
== 1 ? "" : "s", intf
->InterfaceID
);
4053 mDNSSendDNSMessage(m
, &query
, queryptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v4
, MulticastDNSPort
);
4054 mDNSSendDNSMessage(m
, &query
, queryptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v6
, MulticastDNSPort
);
4055 if (!m
->SuppressSending
) m
->SuppressSending
= (m
->timenow
+ mDNSPlatformOneSecond
/10) | 1; // OR with one to ensure non-zero
4056 if (++pktcount
>= 1000)
4057 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
4058 // There might be more records left in the known answer list, or more questions to send
4059 // on this interface, so go around one more time and try again.
4061 else // Nothing more to send on this interface; go to next
4063 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
4064 #if MDNS_DEBUGMSGS && 0
4065 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4066 debugf(msg
, intf
, next
);
4073 // ***************************************************************************
4074 #if COMPILER_LIKES_PRAGMA_MARK
4076 #pragma mark - RR List Management & Task Management
4079 // NOTE: AnswerQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4080 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4081 mDNSlocal
void AnswerQuestionWithResourceRecord(mDNS
*const m
, DNSQuestion
*q
, CacheRecord
*rr
, mDNSBool AddRecord
)
4083 verbosedebugf("AnswerQuestionWithResourceRecord:%4lu %s TTL%6lu %##s (%s)",
4084 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", rr
->resrec
.rroriginalttl
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4086 rr
->LastUsed
= m
->timenow
;
4088 if (ActiveQuestion(q
) && rr
->CRActiveQuestion
!= q
)
4090 if (!rr
->CRActiveQuestion
) m
->rrcache_active
++; // If not previously active, increment rrcache_active count
4091 rr
->CRActiveQuestion
= q
; // We know q is non-null
4092 SetNextCacheCheckTime(m
, rr
);
4095 // CAUTION: MUST NOT do anything more with q after calling q->Callback(), because the client's callback function
4096 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
4097 // Right now the only routines that call AnswerQuestionWithResourceRecord() are CacheRecordAdd(), CacheRecordRmv()
4098 // and AnswerNewQuestion(), and all of them use the "m->CurrentQuestion" mechanism to protect against questions
4099 // being deleted out from under them.
4100 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4101 if (q
->QuestionCallback
)
4102 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4103 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4106 // CacheRecordAdd is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4107 // If new questions are created as a result of invoking client callbacks, they will be added to
4108 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4109 // rr is a new CacheRecord just received into our cache
4110 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4111 // NOTE: CacheRecordAdd calls AnswerQuestionWithResourceRecord which can call a user callback,
4112 // which may change the record list and/or question list.
4113 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4114 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*rr
)
4116 if (m
->CurrentQuestion
) LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set");
4117 m
->CurrentQuestion
= m
->Questions
;
4118 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4120 DNSQuestion
*q
= m
->CurrentQuestion
;
4121 m
->CurrentQuestion
= q
->next
;
4122 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4124 // If this question is one that's actively sending queries, and it's received ten answers within one second of sending the last
4125 // query packet, then that indicates some radical network topology change, so reset its exponential backoff back to the start.
4126 // We must be at least at the eight-second interval to do this. If we're at the four-second interval, or less,
4127 // there's not much benefit accelerating because we will anyway send another query within a few seconds.
4128 // The first reset query is sent out randomized over the next four seconds to reduce possible synchronization between machines.
4129 if (ActiveQuestion(q
) && ++q
->RecentAnswers
>= 10 &&
4130 q
->ThisQInterval
> InitialQuestionInterval
*16 && m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
4132 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst; restarting exponential backoff sequence",
4133 q
->qname
.c
, DNSTypeName(q
->qtype
));
4134 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
4135 q
->ThisQInterval
= InitialQuestionInterval
;
4136 SetNextQueryTime(m
,q
);
4138 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
);
4139 q
->CurrentAnswers
++;
4140 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4141 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4142 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4143 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4146 m
->CurrentQuestion
= mDNSNULL
;
4149 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute
4150 // If new questions are created as a result of invoking client callbacks, they will be added to
4151 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4152 // rr is an existing cache CacheRecord that just expired and is being deleted
4153 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4154 // NOTE: CacheRecordRmv calls AnswerQuestionWithResourceRecord which can call a user callback,
4155 // which may change the record list and/or question list.
4156 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4157 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*rr
)
4159 if (m
->CurrentQuestion
) LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set");
4160 m
->CurrentQuestion
= m
->Questions
;
4161 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4163 DNSQuestion
*q
= m
->CurrentQuestion
;
4164 m
->CurrentQuestion
= q
->next
;
4165 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4167 verbosedebugf("CacheRecordRmv %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4168 if (q
->CurrentAnswers
== 0)
4169 LogMsg("CacheRecordRmv ERROR: How can CurrentAnswers already be zero for %p %##s (%s)?", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
4172 q
->CurrentAnswers
--;
4173 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
4174 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
4176 if (q
->CurrentAnswers
== 0)
4178 debugf("CacheRecordRmv: Zero current answers for %##s (%s); will reconfirm antecedents", q
->qname
.c
, DNSTypeName(q
->qtype
));
4179 ReconfirmAntecedents(m
, q
);
4181 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNSfalse
);
4182 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4185 m
->CurrentQuestion
= mDNSNULL
;
4188 mDNSlocal
void ReleaseCacheRR(mDNS
*const m
, CacheRecord
*r
)
4190 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->rdatastorage
)
4191 mDNSPlatformMemFree(r
->resrec
.rdata
);
4192 r
->resrec
.rdata
= mDNSNULL
;
4193 r
->next
= m
->rrcache_free
;
4194 m
->rrcache_free
= r
;
4195 m
->rrcache_totalused
--;
4198 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, mDNSu32 slot
)
4200 CacheRecord
**rp
= &(m
->rrcache_hash
[slot
]);
4202 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4203 m
->lock_rrcache
= 1;
4207 CacheRecord
*const rr
= *rp
;
4208 mDNSs32 event
= RRExpireTime(rr
);
4209 if (m
->timenow
- event
>= 0) // If expired, delete it
4211 *rp
= rr
->next
; // Cut it from the list
4212 verbosedebugf("CheckCacheExpiration: Deleting %s", GetRRDisplayString(m
, rr
));
4213 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
4215 CacheRecordRmv(m
, rr
);
4216 m
->rrcache_active
--;
4218 m
->rrcache_used
[slot
]--;
4219 ReleaseCacheRR(m
, rr
);
4221 else // else, not expired; see if we need to query
4223 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
4225 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
4226 event
= rr
->NextRequiredQuery
; // then just record when we want the next query
4227 else // else trigger our question to go out now
4229 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4230 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4231 m
->NextScheduledQuery
= m
->timenow
;
4232 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTime(),
4233 // which will correctly update m->NextCacheCheck for us
4234 event
= m
->timenow
+ 0x3FFFFFFF;
4237 if (m
->NextCacheCheck
- (event
+ CacheCheckGracePeriod(rr
)) > 0)
4238 m
->NextCacheCheck
= (event
+ CacheCheckGracePeriod(rr
));
4242 if (m
->rrcache_tail
[slot
] != rp
) debugf("CheckCacheExpiration: Updating m->rrcache_tail[%d] from %p to %p", slot
, m
->rrcache_tail
[slot
], rp
);
4243 m
->rrcache_tail
[slot
] = rp
;
4244 m
->lock_rrcache
= 0;
4247 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
4249 mDNSBool ShouldQueryImmediately
= mDNStrue
;
4251 DNSQuestion
*q
= m
->NewQuestions
; // Grab the question we're going to answer
4252 mDNSu32 slot
= HashSlot(&q
->qname
);
4254 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4256 CheckCacheExpiration(m
, slot
);
4257 m
->NewQuestions
= q
->next
; // Advance NewQuestions to the next *after* calling CheckCacheExpiration();
4259 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4260 // This should be safe, because calling the client's question callback may cause the
4261 // question list to be modified, but should not ever cause the rrcache list to be modified.
4262 // If the client's question callback deletes the question, then m->CurrentQuestion will
4263 // be advanced, and we'll exit out of the loop
4264 m
->lock_rrcache
= 1;
4265 if (m
->CurrentQuestion
) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4266 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4267 for (rr
=m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
4268 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4270 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4271 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
4272 if (rr
->resrec
.rroriginalttl
<= SecsSinceRcvd
)
4274 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %##s (%s)",
4275 rr
->resrec
.rroriginalttl
, SecsSinceRcvd
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4276 continue; // Go to next one in loop
4279 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4280 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4281 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ShouldQueryImmediately
= mDNSfalse
;
4282 q
->CurrentAnswers
++;
4283 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4284 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4285 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4286 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4287 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4289 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
4290 if (rr
->resrec
.namehash
== q
->qnamehash
&& SameDomainName(&rr
->resrec
.name
, &q
->qname
))
4291 ShouldQueryImmediately
= mDNSfalse
;
4293 if (ShouldQueryImmediately
&& m
->CurrentQuestion
== q
)
4295 q
->ThisQInterval
= InitialQuestionInterval
;
4296 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4297 m
->NextScheduledQuery
= m
->timenow
;
4299 m
->CurrentQuestion
= mDNSNULL
;
4300 m
->lock_rrcache
= 0;
4303 mDNSlocal
void AnswerLocalOnlyQuestionWithResourceRecord(mDNS
*const m
, DNSQuestion
*q
, AuthRecord
*rr
, mDNSBool AddRecord
)
4305 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
4306 if (AddRecord
) rr
->AnnounceCount
= InitialAnnounceCount
- 1;
4307 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4308 if (q
->QuestionCallback
)
4309 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4310 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4313 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
4315 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
4316 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewQuestions to the next (if any)
4318 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4320 if (m
->CurrentQuestion
) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4321 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4323 m
->CurrentRecord
= m
->LocalOnlyRecords
;
4324 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalOnlyRecords
)
4326 AuthRecord
*rr
= m
->CurrentRecord
;
4327 m
->CurrentRecord
= rr
->next
;
4328 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4330 AnswerLocalOnlyQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4331 // MUST NOT dereference q again after calling AnswerLocalOnlyQuestionWithResourceRecord()
4332 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4336 m
->CurrentQuestion
= mDNSNULL
;
4339 mDNSlocal
void AnswerLocalOnlyQuestions(mDNS
*const m
, AuthRecord
*rr
, mDNSBool AddRecord
)
4341 if (m
->CurrentQuestion
) LogMsg("AnswerLocalOnlyQuestions ERROR m->CurrentQuestion already set");
4342 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
4343 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
4345 DNSQuestion
*q
= m
->CurrentQuestion
;
4346 m
->CurrentQuestion
= q
->next
;
4347 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4349 debugf("AnswerLocalOnlyQuestions %p %##s (%s) %lu", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
);
4350 AnswerLocalOnlyQuestionWithResourceRecord(m
, q
, rr
, AddRecord
);
4351 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4354 m
->CurrentQuestion
= mDNSNULL
;
4357 mDNSlocal
void DiscardLocalOnlyRecords(mDNS
*const m
)
4359 AuthRecord
*rr
= m
->LocalOnlyRecords
;
4362 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
4363 { AnswerLocalOnlyQuestions(m
, rr
, mDNSfalse
); CompleteDeregistration(m
, rr
); return; }
4364 if (rr
->ProbeCount
) { mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
); return; }
4367 m
->DiscardLocalOnlyRecords
= mDNSfalse
;
4370 mDNSlocal
void AnswerForNewLocalOnlyRecords(mDNS
*const m
)
4372 AuthRecord
*rr
= m
->NewLocalOnlyRecords
;
4373 m
->NewLocalOnlyRecords
= m
->NewLocalOnlyRecords
->next
;
4374 AnswerLocalOnlyQuestions(m
, rr
, mDNStrue
);
4377 mDNSlocal CacheRecord
*GetFreeCacheRR(mDNS
*const m
, mDNSu16 RDLength
)
4379 CacheRecord
*r
= mDNSNULL
;
4381 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
4382 m
->lock_rrcache
= 1;
4384 // If we have no free records, ask the client layer to give us some more memory
4385 if (!m
->rrcache_free
&& m
->MainCallback
)
4387 if (m
->rrcache_totalused
!= m
->rrcache_size
)
4388 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4389 m
->rrcache_totalused
, m
->rrcache_size
);
4391 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4392 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4393 // To guard against this, if we're actively using less than 1/32 of our cache, then we
4394 // purge all the unused records and recycle them, instead of allocating more memory.
4395 if (m
->rrcache_size
>= 512 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
4396 debugf("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4397 m
->rrcache_size
, m
->rrcache_active
);
4399 m
->MainCallback(m
, mStatus_GrowCache
);
4402 // If we still have no free records, recycle all the records we can.
4403 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4404 if (!m
->rrcache_free
)
4407 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
4410 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4412 CacheRecord
**rp
= &(m
->rrcache_hash
[slot
]);
4415 // Records that answer still-active questions are not candidates for deletion
4416 if ((*rp
)->CRActiveQuestion
)
4420 CacheRecord
*rr
= *rp
;
4421 *rp
= (*rp
)->next
; // Cut record from list
4422 m
->rrcache_used
[slot
]--; // Decrement counts
4423 ReleaseCacheRR(m
, rr
);
4426 if (m
->rrcache_tail
[slot
] != rp
) debugf("GetFreeCacheRR: Updating m->rrcache_tail[%d] from %p to %p", slot
, m
->rrcache_tail
[slot
], rp
);
4427 m
->rrcache_tail
[slot
] = rp
;
4430 debugf("Clear unused records; m->rrcache_totalused was %lu; now %lu", oldtotalused
, m
->rrcache_totalused
);
4434 if (m
->rrcache_free
) // If there are records in the free list, take one
4436 r
= m
->rrcache_free
;
4437 m
->rrcache_free
= r
->next
;
4442 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
4444 debugf("RR Cache now using %ld records", m
->rrcache_totalused
);
4445 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
4446 else m
->rrcache_report
+= 100;
4448 mDNSPlatformMemZero(r
, sizeof(*r
));
4449 r
->resrec
.rdata
= (RData
*)&r
->rdatastorage
; // By default, assume we're usually going to be using local storage
4451 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
4453 r
->resrec
.rdata
= (RData
*)mDNSPlatformMemAllocate(sizeofRDataHeader
+ RDLength
);
4454 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
4455 else { ReleaseCacheRR(m
, r
); r
= mDNSNULL
; }
4459 m
->lock_rrcache
= 0;
4464 mDNSlocal
void PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
4466 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4467 // a positive answer using an expired record (e.g. from an interface that has gone away).
4468 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4469 // summary deletion without giving the proper callback to any questions that are monitoring it.
4470 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4471 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
4472 rr
->UnansweredQueries
= MaxUnansweredQueries
;
4473 rr
->resrec
.rroriginalttl
= 0;
4474 SetNextCacheCheckTime(m
, rr
);
4477 mDNSlocal
void mDNS_Lock(mDNS
*const m
)
4479 // MUST grab the platform lock FIRST!
4480 mDNSPlatformLock(m
);
4482 // Normally, mDNS_reentrancy is zero and so is mDNS_busy
4483 // However, when we call a client callback mDNS_busy is one, and we increment mDNS_reentrancy too
4484 // If that client callback does mDNS API calls, mDNS_reentrancy and mDNS_busy will both be one
4485 // If mDNS_busy != mDNS_reentrancy that's a bad sign
4486 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
4487 LogMsg("mDNS_Lock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4489 // If this is an initial entry into the mDNSCore code, set m->timenow
4490 // else, if this is a re-entrant entry into the mDNSCore code, m->timenow should already be set
4491 if (m
->mDNS_busy
== 0)
4494 LogMsg("mDNS_Lock: m->timenow already set (%ld/%ld)", m
->timenow
, mDNSPlatformTimeNow() + m
->timenow_adjust
);
4495 m
->timenow
= mDNSPlatformTimeNow() + m
->timenow_adjust
;
4496 if (m
->timenow
== 0) m
->timenow
= 1;
4498 else if (m
->timenow
== 0)
4500 LogMsg("mDNS_Lock: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
4501 m
->timenow
= mDNSPlatformTimeNow() + m
->timenow_adjust
;
4502 if (m
->timenow
== 0) m
->timenow
= 1;
4505 if (m
->timenow_last
- m
->timenow
> 0)
4507 m
->timenow_adjust
+= m
->timenow_last
- m
->timenow
;
4508 LogMsg("mDNSPlatformTimeNow went backwards by %ld ticks; setting correction factor to %ld", m
->timenow_last
- m
->timenow
, m
->timenow_adjust
);
4509 m
->timenow
= m
->timenow_last
;
4511 m
->timenow_last
= m
->timenow
;
4513 // Increment mDNS_busy so we'll recognise re-entrant calls
4517 mDNSlocal mDNSs32
GetNextScheduledEvent(const mDNS
*const m
)
4519 mDNSs32 e
= m
->timenow
+ 0x78000000;
4520 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| m
->SleepState
) return(e
);
4521 if (m
->NewQuestions
) return(m
->timenow
);
4522 if (m
->NewLocalOnlyQuestions
) return(m
->timenow
);
4523 if (m
->NewLocalOnlyRecords
) return(m
->timenow
);
4524 if (m
->DiscardLocalOnlyRecords
) return(m
->timenow
);
4525 if (m
->SuppressSending
) return(m
->SuppressSending
);
4526 if (e
- m
->NextCacheCheck
> 0) e
= m
->NextCacheCheck
;
4527 if (e
- m
->NextScheduledQuery
> 0) e
= m
->NextScheduledQuery
;
4528 if (e
- m
->NextScheduledProbe
> 0) e
= m
->NextScheduledProbe
;
4529 if (e
- m
->NextScheduledResponse
> 0) e
= m
->NextScheduledResponse
;
4533 mDNSlocal
void mDNS_Unlock(mDNS
*const m
)
4535 // Decrement mDNS_busy
4538 // Check for locking failures
4539 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
4540 LogMsg("mDNS_Unlock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4542 // If this is a final exit from the mDNSCore code, set m->NextScheduledEvent and clear m->timenow
4543 if (m
->mDNS_busy
== 0)
4545 m
->NextScheduledEvent
= GetNextScheduledEvent(m
);
4546 if (m
->timenow
== 0) LogMsg("mDNS_Unlock: ERROR! m->timenow aready zero");
4550 // MUST release the platform lock LAST!
4551 mDNSPlatformUnlock(m
);
4554 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
4556 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
4558 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
4562 verbosedebugf("mDNS_Execute");
4563 if (m
->CurrentQuestion
) LogMsg("mDNS_Execute: ERROR! m->CurrentQuestion already set");
4565 // 1. If we're past the probe suppression time, we can clear it
4566 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
4568 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4569 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
4571 // 3. Purge our cache of stale old records
4572 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
4575 m
->NextCacheCheck
= m
->timenow
+ 0x3FFFFFFF;
4576 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++) CheckCacheExpiration(m
, slot
);
4579 // 4. See if we can answer any of our new local questions from the cache
4580 for (i
=0; m
->NewQuestions
&& i
<1000; i
++) AnswerNewQuestion(m
);
4581 if (i
>= 1000) debugf("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4583 for (i
=0; m
->DiscardLocalOnlyRecords
&& i
<1000; i
++) DiscardLocalOnlyRecords(m
);
4584 if (i
>= 1000) debugf("mDNS_Execute: DiscardLocalOnlyRecords exceeded loop limit");
4586 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
4587 if (i
>= 1000) debugf("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4589 for (i
=0; m
->NewLocalOnlyRecords
&& i
<1000; i
++) AnswerForNewLocalOnlyRecords(m
);
4590 if (i
>= 1000) debugf("mDNS_Execute: AnswerLocalOnlyQuestions exceeded loop limit");
4592 // 5. See what packets we need to send
4593 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| m
->SleepState
) DiscardDeregistrations(m
);
4594 else if (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0)
4596 // If the platform code is ready, and we're not suppressing packet generation right now
4597 // then send our responses, probes, and questions.
4598 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them
4599 // We send queries next, because there might be final-stage probes that complete their probing here, causing
4600 // them to advance to announcing state, and we want those to be included in any announcements we send out.
4601 // Finally, we send responses, including the previously mentioned records that just completed probing
4602 m
->SuppressSending
= 0;
4604 // 6. Send Query packets. This may cause some probing records to advance to announcing state
4605 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
4606 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
4608 LogMsg("mDNS_Execute: SendQueries didn't send all its queries; will try again in one second");
4609 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
4611 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
4613 LogMsg("mDNS_Execute: SendQueries didn't send all its probes; will try again in one second");
4614 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
4617 // 7. Send Response packets, including probing records just advanced to announcing state
4618 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
4619 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
4621 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4622 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
4626 m
->RandomQueryDelay
= 0; // Clear m->RandomQueryDelay, ready to pick a new different value, when necessary
4629 // Note about multi-threaded systems:
4630 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4631 // performing mDNS API operations that change our next scheduled event time.
4633 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
4634 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4635 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4636 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4637 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4638 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4639 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4640 // without blocking. This avoids the race condition between the signal from the other thread arriving
4641 // just *before* or just *after* the main thread enters the blocking primitive.
4643 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4644 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4645 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4646 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4647 // by the time it gets to the timer callback function).
4649 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4650 return(m
->NextScheduledEvent
);
4653 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
4654 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
4655 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
4656 // Note that sleep/wake calls do not have to be paired one-for-one; it is acceptable to call
4657 // mDNSCoreMachineSleep(m, mDNSfalse) any time there is reason to believe that the machine may have just
4658 // found itself in a new network environment. For example, if the Ethernet hardware indicates that the
4659 // cable has just been connected, the platform support layer should call mDNSCoreMachineSleep(m, mDNSfalse)
4660 // to make mDNSCore re-issue its outstanding queries, probe for record uniqueness, etc.
4661 // While it is safe to call mDNSCoreMachineSleep(m, mDNSfalse) at any time, it does cause extra network
4662 // traffic, so it should only be called when there is legitimate reason to believe the machine
4663 // may have become attached to a new network.
4664 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleepstate
)
4670 m
->SleepState
= sleepstate
;
4671 LogMsg("mDNSResponder %s at %ld", sleepstate
? "Sleeping" : "Waking", m
->timenow
);
4675 // Mark all the records we need to deregister and send them
4676 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4677 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->AnnounceCount
< InitialAnnounceCount
)
4678 rr
->ImmedAnswer
= mDNSInterfaceMark
;
4687 // 1. Retrigger all our questions
4688 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
4689 if (ActiveQuestion(q
))
4691 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
4692 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4693 q
->RecentAnswers
= 0;
4694 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
4695 m
->NextScheduledQuery
= m
->timenow
;
4698 // 2. Re-validate our cache records
4699 m
->NextCacheCheck
= m
->timenow
;
4700 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4701 for (cr
= m
->rrcache_hash
[slot
]; cr
; cr
=cr
->next
)
4702 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForCableDisconnect
);
4704 // 3. Retrigger probing and announcing for all our authoritative records
4705 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4707 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
4708 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
4709 if (rr
->AnnounceCount
< ReannounceCount
)
4710 rr
->AnnounceCount
= ReannounceCount
;
4711 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
4712 InitializeLastAPTime(m
, rr
);
4720 // ***************************************************************************
4721 #if COMPILER_LIKES_PRAGMA_MARK
4723 #pragma mark - Packet Reception Functions
4726 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
4728 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
4731 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
4732 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
4733 // The referenced record will definitely be acceptable (by recursive application of this rule)
4734 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
4735 rr
->NR_AdditionalTo
= add
;
4736 *nrpp
= &rr
->NextResponse
;
4738 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4741 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
4743 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
4744 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
4746 mDNSu8
*responseptr
= response
->data
;
4747 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
4748 const mDNSu8
*ptr
= query
->data
;
4750 mDNSu32 maxttl
= 0x70000000;
4753 // Initialize the response fields so we can answer the questions
4754 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
4757 // *** 1. Write out the list of questions we are actually going to answer with this packet
4762 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4765 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
4766 if (!ptr
) return(mDNSNULL
);
4768 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
4770 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
4771 { // then put the question in the question section
4772 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
4773 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
4774 break; // break out of the ResponseRecords loop, and go on to the next question
4779 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
4783 // *** 2. Write Answers
4785 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4786 if (rr
->NR_AnswerTo
)
4788 mDNSu8
*p
= PutResourceRecordCappedTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
, maxttl
);
4789 if (p
) responseptr
= p
;
4790 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
4794 // *** 3. Write Additionals
4796 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4797 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
4799 mDNSu8
*p
= PutResourceRecordCappedTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
, maxttl
);
4800 if (p
) responseptr
= p
;
4801 else debugf("GenerateUnicastResponse: No more space for additionals");
4804 return(responseptr
);
4807 // AuthRecord *our is our Resource Record
4808 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
4809 // Returns 0 if there is no conflict
4810 // Returns +1 if there was a conflict and we won
4811 // Returns -1 if there was a conflict and we lost and have to rename
4812 mDNSlocal
int CompareRData(AuthRecord
*our
, CacheRecord
*pkt
)
4814 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
4815 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
4816 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
4817 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
4819 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
4820 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
4821 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
4822 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
4824 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
4825 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
4826 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
4827 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
4829 debugf("CompareRData: How did we get here?");
4833 // See if we have an authoritative record that's identical to this packet record,
4834 // whose canonical DependentOn record is the specified master record.
4835 // The DependentOn pointer is typically used for the TXT record of service registrations
4836 // It indicates that there is no inherent conflict detection for the TXT record
4837 // -- it depends on the SRV record to resolve name conflicts
4838 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
4839 // pointer chain (if any) to make sure we reach the canonical DependentOn record
4840 // If the record has no DependentOn, then just return that record's pointer
4841 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4842 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
4844 const AuthRecord
*r1
;
4845 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
4847 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4849 const AuthRecord
*r2
= r1
;
4850 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4851 if (r2
== master
) return(mDNStrue
);
4854 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
4856 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4858 const AuthRecord
*r2
= r1
;
4859 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4860 if (r2
== master
) return(mDNStrue
);
4866 // Find the canonical RRSet pointer for this RR received in a packet.
4867 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
4868 // pointers (if any) to make sure we return the canonical member of this name/type/class
4869 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4870 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
4872 const AuthRecord
*rr
;
4873 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4875 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
4877 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
4884 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
4885 // as one of our records (our) but different rdata.
4886 // 1. If our record is not a type that's supposed to be unique, we don't care.
4887 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
4888 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
4889 // points to our record, ignore this conflict (e.g. the packet record matches one of our
4890 // TXT records, and that record is marked as dependent on 'our', its SRV record).
4891 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
4892 // are members of the same RRSet, then this is not a conflict.
4893 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
4895 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
4897 // If not supposed to be unique, not a conflict
4898 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
4900 // If a dependent record, not a conflict
4901 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
4903 // If the pktrr matches a member of ourset, not a conflict
4904 if (FindRRSet(m
, pktrr
) == ourset
) return(mDNSfalse
);
4906 // Okay, this is a conflict
4910 // NOTE: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
4911 // the record list and/or question list.
4912 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4913 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4914 DNSQuestion
*q
, AuthRecord
*our
)
4917 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
4918 mDNSBool FoundUpdate
= mDNSfalse
;
4920 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
4922 LargeCacheRecord pkt
;
4923 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, 0, &pkt
);
4925 if (ResourceRecordAnswersQuestion(&pkt
.r
.resrec
, q
))
4927 FoundUpdate
= mDNStrue
;
4928 if (PacketRRConflict(m
, our
, &pkt
.r
))
4930 int result
= (int)our
->resrec
.rrclass
- (int)pkt
.r
.resrec
.rrclass
;
4931 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)pkt
.r
.resrec
.rrtype
;
4932 if (!result
) result
= CompareRData(our
, &pkt
.r
);
4935 case 1: debugf("ResolveSimultaneousProbe: %##s (%s): We won", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4938 case -1: debugf("ResolveSimultaneousProbe: %##s (%s): We lost", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4939 mDNS_Deregister_internal(m
, our
, mDNS_Dereg_conflict
);
4946 debugf("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4949 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, ResourceRecord
*pktrr
)
4952 for (rr
= m
->rrcache_hash
[HashSlot(&pktrr
->name
)]; rr
; rr
=rr
->next
)
4953 if (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
&& IdenticalResourceRecord(pktrr
, &rr
->resrec
)) break;
4957 // ProcessQuery examines a received query to see if we have any answers to give
4958 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4959 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
4960 DNSMessage
*const response
)
4962 AuthRecord
*ResponseRecords
= mDNSNULL
;
4963 AuthRecord
**nrp
= &ResponseRecords
;
4964 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
4965 CacheRecord
**eap
= &ExpectedAnswers
;
4966 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
4967 DNSQuestion
**dqp
= &DupQuestions
;
4968 mDNSs32 delayresponse
= 0;
4969 mDNSBool HaveUnicastAnswer
= mDNSfalse
;
4970 const mDNSu8
*ptr
= query
->data
;
4971 mDNSu8
*responseptr
= mDNSNULL
;
4972 AuthRecord
*rr
, *rr2
;
4975 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet.
4976 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
4979 // *** 1. Parse Question Section and mark potential answers
4981 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4983 mDNSBool QuestionNeedsMulticastResponse
;
4984 int NumAnswersForThisQuestion
= 0;
4985 DNSQuestion pktq
, *q
;
4986 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
4987 if (!ptr
) goto exit
;
4989 // The only queries that *need* a multicast response are:
4990 // * Queries sent via multicast
4992 // * that don't have the kDNSQClass_UnicastResponse bit set
4993 // These queries need multicast responses because other clients will:
4994 // * suppress their own identical questions when they see these questions, and
4995 // * expire their cache records if they don't see the expected responses
4996 // For other queries, we may still choose to send the occasional multicast response anyway,
4997 // to keep our neighbours caches warm, and for ongoing conflict detection.
4998 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
4999 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
5000 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
5002 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
5003 // can result in user callbacks which may change the record list and/or question list.
5004 // Also note: we just mark potential answer records here, without trying to build the
5005 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
5006 // from that list while we're in the middle of trying to build it.
5007 if (m
->CurrentRecord
) LogMsg("ProcessQuery ERROR m->CurrentRecord already set");
5008 m
->CurrentRecord
= m
->ResourceRecords
;
5009 while (m
->CurrentRecord
)
5011 rr
= m
->CurrentRecord
;
5012 m
->CurrentRecord
= rr
->next
;
5013 if (ResourceRecordAnswersQuestion(&rr
->resrec
, &pktq
))
5015 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
5016 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
5017 else if (ResourceRecordIsValidAnswer(rr
))
5019 NumAnswersForThisQuestion
++;
5021 // NR_AnswerTo pointing into query packet means "answer via unicast"
5022 // (may also choose to do multicast as well)
5023 // NR_AnswerTo == ~0 means "definitely answer via multicast" (can't downgrade to unicast later)
5024 if (QuestionNeedsMulticastResponse
)
5026 // We only mark this question for sending if it is at least one second since the last time we multicast it
5027 // on this interface. If it is more than a second, or LastMCInterface is different, then we should multicast it.
5028 // This is to guard against the case where someone blasts us with queries as fast as they can.
5029 if (m
->timenow
- (rr
->LastMCTime
+ mDNSPlatformOneSecond
) >= 0 ||
5030 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
5031 rr
->NR_AnswerTo
= (mDNSu8
*)~0;
5033 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= ptr
;
5038 // We only do the following accelerated cache expiration processing and duplicate question suppression processing
5039 // for multicast queries with multicast responses.
5040 // For any query generating a unicast response we don't do this because we can't assume we will see the response
5041 if (QuestionNeedsMulticastResponse
)
5044 // If we couldn't answer this question, someone else might be able to,
5045 // so use random delay on response to reduce collisions
5046 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
5048 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5049 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5050 for (rr
= m
->rrcache_hash
[HashSlot(&pktq
.qname
)]; rr
; rr
=rr
->next
)
5051 if (ResourceRecordAnswersQuestion(&rr
->resrec
, &pktq
) && rr
->resrec
.rdlength
<= SmallRecordLimit
)
5052 if (!rr
->NextInKAList
&& eap
!= &rr
->NextInKAList
)
5055 eap
= &rr
->NextInKAList
;
5056 if (rr
->MPUnansweredQ
== 0 || m
->timenow
- rr
->MPLastUnansweredQT
>= mDNSPlatformOneSecond
)
5058 // Although MPUnansweredQ is only really used for multi-packet query processing,
5059 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5060 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5061 rr
->MPUnansweredQ
++;
5062 rr
->MPLastUnansweredQT
= m
->timenow
;
5063 rr
->MPExpectingKA
= mDNStrue
;
5067 // Check if this question is the same as any of mine.
5068 // We only do this for non-truncated queries. Right now it would be too complicated to try
5069 // to keep track of duplicate suppression state between multiple packets, especially when we
5070 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5071 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5072 for (q
= m
->Questions
; q
; q
=q
->next
)
5073 if (ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
5074 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
5075 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
5076 if (q
->qtype
== pktq
.qtype
&& q
->qclass
== pktq
.qclass
&& q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
5077 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
5082 // *** 2. Now we can safely build the list of marked answers
5084 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
5085 if (rr
->NR_AnswerTo
) // If we marked the record...
5086 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
5089 // *** 3. Add additional records
5091 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
5093 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
5094 // later in the "for" loop, and we will follow further "additional" links then.)
5095 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
5096 AddRecordToResponseList(&nrp
, rr
->Additional1
, rr
);
5098 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
5099 AddRecordToResponseList(&nrp
, rr
->Additional2
, rr
);
5101 // For SRV records, automatically add the Address record(s) for the target host
5102 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
5103 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
5104 if (RRIsAddressType(rr2
) && // For all address records (A/AAAA) ...
5105 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
5106 rr
->resrec
.rdnamehash
== rr2
->resrec
.namehash
&&
5107 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, &rr2
->resrec
.name
)) // ... whose name is the name of the SRV target
5108 AddRecordToResponseList(&nrp
, rr2
, rr
);
5112 // *** 4. Parse Answer Section and cancel any records disallowed by Known-Answer list
5114 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
5116 // Get the record...
5117 LargeCacheRecord pkt
;
5119 CacheRecord
*ourcacherr
;
5120 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &pkt
);
5121 if (!ptr
) goto exit
;
5123 // See if this Known-Answer suppresses any of our currently planned answers
5124 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5125 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&pkt
.r
, rr
))
5126 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5128 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5129 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
5131 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5132 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&pkt
.r
, rr
))
5134 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5136 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zeroIPAddr
;
5138 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5140 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
5142 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->ImmedAnswer
= mDNSNULL
;
5146 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5147 // 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).
5148 ourcacherr
= FindIdenticalRecordInCache(m
, &pkt
.r
.resrec
);
5149 if (ourcacherr
&& ourcacherr
->MPExpectingKA
&& m
->timenow
- ourcacherr
->MPLastUnansweredQT
< mDNSPlatformOneSecond
)
5151 ourcacherr
->MPUnansweredKA
++;
5152 ourcacherr
->MPExpectingKA
= mDNSfalse
;
5155 // Having built our ExpectedAnswers list from the questions in this packet, we can definitively
5156 // remove from our ExpectedAnswers list any records that are suppressed in the very same packet.
5157 // For answers that are suppressed in subsequent KA list packets, we rely on the MPQ/MPKA counting to track them.
5158 eap
= &ExpectedAnswers
;
5161 CacheRecord
*rr
= *eap
;
5162 if (rr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&pkt
.r
.resrec
, &rr
->resrec
))
5163 { *eap
= rr
->NextInKAList
; rr
->NextInKAList
= mDNSNULL
; }
5164 else eap
= &rr
->NextInKAList
;
5167 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5170 dqp
= &DupQuestions
;
5173 DNSQuestion
*q
= *dqp
;
5174 if (ResourceRecordAnswersQuestion(&pkt
.r
.resrec
, q
))
5175 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
5176 else dqp
= &q
->NextInDQList
;
5182 // *** 5. Cancel any additionals that were added because of now-deleted records
5184 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5185 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
5186 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5189 // *** 6. Mark the send flags on the records we plan to send
5191 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5193 if (rr
->NR_AnswerTo
)
5195 mDNSBool SendMulticastResponse
= mDNSfalse
;
5197 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
5198 if (m
->timenow
- (rr
->LastMCTime
+ TicksTTL(rr
)/4) >= 0) SendMulticastResponse
= mDNStrue
;
5200 // If the client insists on a multicast response, then we'd better send one
5201 if (rr
->NR_AnswerTo
== (mDNSu8
*)~0) SendMulticastResponse
= mDNStrue
;
5202 else if (rr
->NR_AnswerTo
) HaveUnicastAnswer
= mDNStrue
;
5204 if (SendMulticastResponse
)
5206 // If we're already planning to send this on another interface, just send it on all interfaces
5207 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
5209 rr
->ImmedAnswer
= mDNSInterfaceMark
;
5210 m
->NextScheduledResponse
= m
->timenow
;
5211 debugf("ProcessQuery: %##s (%s) : Will send on all interfaces", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5215 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
5216 m
->NextScheduledResponse
= m
->timenow
;
5217 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5219 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
5220 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
5222 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5224 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
5225 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
5229 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
5231 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
5232 else delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
5235 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== (mDNSu8
*)~0)
5237 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
5238 // If two clients on different interfaces do queries that invoke the same optional additional answer,
5239 // then the earlier client is out of luck
5240 rr
->ImmedAdditional
= InterfaceID
;
5241 // No need to set m->NextScheduledResponse here
5242 // We'll send these additional records when we send them, or not, as the case may be
5247 // *** 7. If we think other machines are likely to answer these questions, set our packet suppression timer
5249 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
5251 // Pick a random delay:
5252 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
5253 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
5254 // This is an integer value, with resolution determined by the platform clock rate.
5255 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
5256 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
5257 // The +49 before dividing is to ensure we round up, not down, to ensure that even
5258 // on platforms where the native clock rate is less than fifty ticks per second,
5259 // we still guarantee that the final calculated delay is at least one platform tick.
5260 // We want to make sure we don't ever allow the delay to be zero ticks,
5261 // because if that happens we'll fail the Rendezvous Conformance Test.
5262 // Our final computed delay is 20-120ms for normal delayed replies,
5263 // or 400-500ms in the case of multi-packet known-answer lists.
5264 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
5265 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
5269 // *** 8. If query is from a legacy client, generate a unicast response too
5271 if (HaveUnicastAnswer
)
5272 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
5276 // *** 9. Finally, clear our link chains ready for use next time
5278 while (ResponseRecords
)
5280 rr
= ResponseRecords
;
5281 ResponseRecords
= rr
->NextResponse
;
5282 rr
->NextResponse
= mDNSNULL
;
5283 rr
->NR_AnswerTo
= mDNSNULL
;
5284 rr
->NR_AdditionalTo
= mDNSNULL
;
5287 while (ExpectedAnswers
)
5290 rr
= ExpectedAnswers
;
5291 ExpectedAnswers
= rr
->NextInKAList
;
5292 rr
->NextInKAList
= mDNSNULL
;
5294 // For non-truncated queries, we can definitively say that we should expect
5295 // to be seeing a response for any records still left in the ExpectedAnswers list
5296 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5297 if (rr
->UnansweredQueries
== 0 || m
->timenow
- rr
->LastUnansweredTime
>= mDNSPlatformOneSecond
)
5299 rr
->UnansweredQueries
++;
5300 rr
->LastUnansweredTime
= m
->timenow
;
5301 if (rr
->UnansweredQueries
> 1)
5302 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
5303 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5304 SetNextCacheCheckTime(m
, rr
);
5307 // If we've seen multiple unanswered queries for this record,
5308 // then mark it to expire in five seconds if we don't get a response by then.
5309 if (rr
->UnansweredQueries
>= MaxUnansweredQueries
)
5311 // Only show debugging message if this record was not about to expire anyway
5312 if (RRExpireTime(rr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5313 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5314 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5315 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
5317 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
5318 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
5319 // possible packet loss of up to 20% of the additional KA packets.)
5320 else if (rr
->MPUnansweredQ
* 4 > rr
->MPUnansweredKA
* 5 + 8)
5322 // We want to do this conservatively.
5323 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
5324 // then we don't want them to all hit the network simultaneously with their final expiration queries.
5325 // By setting the record to expire in four minutes, we achieve two things:
5326 // (a) the 90-95% final expiration queries will be less bunched together
5327 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
5328 mDNSu32 remain
= (mDNSu32
)(RRExpireTime(rr
) - m
->timenow
) / 4;
5329 if (remain
> 240 * (mDNSu32
)mDNSPlatformOneSecond
)
5330 remain
= 240 * (mDNSu32
)mDNSPlatformOneSecond
;
5332 // Only show debugging message if this record was not about to expire anyway
5333 if (RRExpireTime(rr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5334 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5335 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5337 if (remain
<= 60 * (mDNSu32
)mDNSPlatformOneSecond
)
5338 rr
->UnansweredQueries
++; // Treat this as equivalent to one definite unanswered query
5339 rr
->MPUnansweredQ
= 0; // Clear MPQ/MPKA statistics
5340 rr
->MPUnansweredKA
= 0;
5341 rr
->MPExpectingKA
= mDNSfalse
;
5343 if (remain
< kDefaultReconfirmTimeForNoAnswer
)
5344 remain
= kDefaultReconfirmTimeForNoAnswer
;
5345 mDNS_Reconfirm_internal(m
, rr
, remain
);
5349 while (DupQuestions
)
5352 DNSQuestion
*q
= DupQuestions
;
5353 DupQuestions
= q
->NextInDQList
;
5354 q
->NextInDQList
= mDNSNULL
;
5355 i
= RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
5356 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
5357 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6", i
);
5360 return(responseptr
);
5363 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
5364 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
5365 const mDNSInterfaceID InterfaceID
)
5367 DNSMessage response
;
5368 const mDNSu8
*responseend
= mDNSNULL
;
5370 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",
5371 srcaddr
, (mDNSu16
)srcport
.b
[0]<<8 | srcport
.b
[1],
5372 dstaddr
, (mDNSu16
)dstport
.b
[0]<<8 | dstport
.b
[1],
5374 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
5375 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
5376 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5377 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? "" : "s");
5379 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
5380 (srcport
.NotAnInteger
!= MulticastDNSPort
.NotAnInteger
), mDNSAddrIsDNSMulticast(dstaddr
), &response
);
5382 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
5384 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
5385 response
.h
.numQuestions
, response
.h
.numQuestions
== 1 ? "" : "s",
5386 response
.h
.numAnswers
, response
.h
.numAnswers
== 1 ? "" : "s",
5387 response
.h
.numAdditionals
, response
.h
.numAdditionals
== 1 ? "" : "s",
5388 srcaddr
, (mDNSu16
)srcport
.b
[0]<<8 | srcport
.b
[1], InterfaceID
, srcaddr
->type
);
5389 mDNSSendDNSMessage(m
, &response
, responseend
, InterfaceID
, dstport
, srcaddr
, srcport
);
5393 // NOTE: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
5394 // the record list and/or question list.
5395 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5396 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
5397 const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, const mDNSAddr
*dstaddr
,
5398 const mDNSInterfaceID InterfaceID
, mDNSu8 ttl
)
5401 const mDNSu8
*ptr
= LocateAnswers(response
, end
); // We ignore questions (if any) in a DNS response packet
5402 CacheRecord
*CacheFlushRecords
= mDNSNULL
;
5403 CacheRecord
**cfp
= &CacheFlushRecords
;
5405 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
5406 // to guard against spoof responses, then the only credible protection against that is cryptographic
5407 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
5408 int totalrecords
= response
->h
.numAnswers
+ response
->h
.numAuthorities
+ response
->h
.numAdditionals
;
5410 (void)srcaddr
; // Currently used only for display in debugging message
5412 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",
5413 srcaddr
, dstaddr
, InterfaceID
, ttl
,
5414 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5415 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5416 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5417 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5419 // TTL should be 255
5420 // In the case of overlayed subnets that aren't using RFC 3442, some packets may incorrectly
5421 // go to the router first and then come back with a TTL of 254, so we allow that too.
5422 // Anything lower than 254 is a pretty good sign of an off-net spoofing attack.
5423 // Also, if we get a unicast response when we weren't expecting one, then we assume it is someone trying to spoof us
5424 if (ttl
< 254 || (!mDNSAddrIsDNSMulticast(dstaddr
) && (mDNSu32
)(m
->timenow
- m
->ExpectUnicastResponse
) > (mDNSu32
)mDNSPlatformOneSecond
))
5426 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",
5427 srcaddr
, dstaddr
, ttl
, InterfaceID
,
5428 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5429 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5430 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5431 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5435 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
5437 LargeCacheRecord pkt
;
5438 const mDNSu8 RecordType
= (mDNSu8
)((i
< response
->h
.numAnswers
) ? kDNSRecordTypePacketAns
: kDNSRecordTypePacketAdd
);
5439 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &pkt
);
5440 if (!ptr
) break; // Break out of the loop and clean up our CacheFlushRecords list before exiting
5442 // 1. Check that this packet resource record does not conflict with any of ours
5443 if (m
->CurrentRecord
) LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set");
5444 m
->CurrentRecord
= m
->ResourceRecords
;
5445 while (m
->CurrentRecord
)
5447 AuthRecord
*rr
= m
->CurrentRecord
;
5448 m
->CurrentRecord
= rr
->next
;
5449 if (PacketRRMatchesSignature(&pkt
.r
, rr
)) // If interface, name, type (if verified) and class match...
5451 // ... check to see if rdata is identical
5452 if (SameRData(&pkt
.r
.resrec
, &rr
->resrec
))
5454 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
5455 if (pkt
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
5457 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
5458 if (rr
->ImmedAnswer
== InterfaceID
) rr
->ImmedAnswer
= mDNSNULL
;
5462 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
5463 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5468 // else, the packet RR has different rdata -- check to see if this is a conflict
5469 if (pkt
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &pkt
.r
))
5471 debugf("mDNSCoreReceiveResponse: Our Record: %08X %08X %s", rr
-> resrec
.rdatahash
, rr
-> resrec
.rdnamehash
, GetRRDisplayString(m
, rr
));
5472 debugf("mDNSCoreReceiveResponse: Pkt Record: %08X %08X %s", pkt
.r
.resrec
.rdatahash
, pkt
.r
.resrec
.rdnamehash
, GetRRDisplayString(m
, &pkt
.r
));
5474 // If this record is marked DependentOn another record for conflict detection purposes,
5475 // then *that* record has to be bumped back to probing state to resolve the conflict
5476 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
5478 // If we've just whacked this record's ProbeCount, don't need to do it again
5479 if (rr
->ProbeCount
<= DefaultProbeCountForTypeUnique
)
5481 // If we'd previously verified this record, put it back to probing state and try again
5482 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
5484 debugf("mDNSCoreReceiveResponse: Reseting to Probing: %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5485 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5486 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
5487 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(kDNSRecordTypeUnique
);
5488 InitializeLastAPTime(m
, rr
);
5489 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
5491 // If we're probing for this record, we just failed
5492 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
5494 debugf("mDNSCoreReceiveResponse: Will rename %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5495 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5497 // We assumed this record must be unique, but we were wrong.
5498 // (e.g. There are two mDNSResponders on the same machine giving
5499 // different answers for the reverse mapping record.)
5500 // This is simply a misconfiguration, and we don't try to recover from it.
5501 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
5503 debugf("mDNSCoreReceiveResponse: Unexpected conflict on %##s (%s) -- discarding our record",
5504 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5505 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5508 debugf("mDNSCoreReceiveResponse: Unexpected record type %X %##s (%s)",
5509 rr
->resrec
.RecordType
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5512 // Else, matching signature, different rdata, but not a considered a conflict.
5513 // If the packet record has the cache-flush bit set, then we check to see if we have to re-assert our record(s)
5514 // to rescue them (see note about "multi-homing and bridged networks" at the end of this function).
5515 else if ((pkt
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && m
->timenow
- rr
->LastMCTime
> mDNSPlatformOneSecond
/2)
5516 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5521 // 2. See if we want to add this packet resource record to our cache
5522 if (m
->rrcache_size
) // Only try to cache answers if we have a cache to put them in
5524 mDNSu32 slot
= HashSlot(&pkt
.r
.resrec
.name
);
5526 // 2a. Check if this packet resource record is already in our cache
5527 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
5529 // If we found this exact resource record, refresh its TTL
5530 if (rr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&pkt
.r
.resrec
, &rr
->resrec
))
5532 if (pkt
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5533 verbosedebugf("Found record size %5d interface %p already in cache: %s",
5534 pkt
.r
.resrec
.rdlength
, InterfaceID
, GetRRDisplayString(m
, &pkt
.r
));
5535 rr
->TimeRcvd
= m
->timenow
;
5537 if (pkt
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
5539 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
5540 if (rr
->NextInCFList
== mDNSNULL
&& cfp
!= &rr
->NextInCFList
)
5541 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; }
5543 // If this packet record is marked unique, and our previous cached copy was not, then fix it
5544 if (!(rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
5547 for (q
= m
->Questions
; q
; q
=q
->next
) if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) q
->UniqueAnswers
++;
5548 rr
->resrec
.RecordType
= pkt
.r
.resrec
.RecordType
;
5552 if (pkt
.r
.resrec
.rroriginalttl
> 0)
5554 rr
->resrec
.rroriginalttl
= pkt
.r
.resrec
.rroriginalttl
;
5555 rr
->UnansweredQueries
= 0;
5556 rr
->MPUnansweredQ
= 0;
5557 rr
->MPUnansweredKA
= 0;
5558 rr
->MPExpectingKA
= mDNSfalse
;
5562 // If the packet TTL is zero, that means we're deleting this record.
5563 // To give other hosts on the network a chance to protest, we push the deletion
5564 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
5565 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
5566 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
5567 rr
->resrec
.rroriginalttl
= 1;
5568 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5570 SetNextCacheCheckTime(m
, rr
);
5575 // If packet resource record not in our cache, add it now
5576 // (unless it is just a deletion of a record we never had, in which case we don't care)
5577 if (!rr
&& pkt
.r
.resrec
.rroriginalttl
> 0)
5579 rr
= GetFreeCacheRR(m
, pkt
.r
.resrec
.rdlength
);
5580 if (!rr
) debugf("No cache space to add record for %#s", pkt
.r
.resrec
.name
.c
);
5583 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
5585 rr
->resrec
.rdata
= saveptr
; // and then restore it after the structure assignment
5586 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
5587 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; }
5588 // If this is an oversized record with external storage allocated, copy rdata to external storage
5589 if (pkt
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5590 mDNSPlatformMemCopy(pkt
.r
.resrec
.rdata
, rr
->resrec
.rdata
, sizeofRDataHeader
+ pkt
.r
.resrec
.rdlength
);
5591 rr
->next
= mDNSNULL
; // Clear 'next' pointer
5592 *(m
->rrcache_tail
[slot
]) = rr
; // Append this record to tail of cache slot list
5593 m
->rrcache_tail
[slot
] = &(rr
->next
); // Advance tail pointer
5594 m
->rrcache_used
[slot
]++;
5595 //debugf("Adding RR %##s to cache (%d)", pkt.r.name.c, m->rrcache_used);
5596 CacheRecordAdd(m
, rr
);
5597 // MUST do this AFTER CacheRecordAdd(), because that's what sets CRActiveQuestion for us
5598 SetNextCacheCheckTime(m
, rr
);
5604 // If we've just received one or more records with their cache flush bits set,
5605 // then scan that cache slot to see if there are any old stale records we need to flush
5606 while (CacheFlushRecords
)
5608 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
5609 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
5610 r1
->NextInCFList
= mDNSNULL
;
5611 for (r2
= m
->rrcache_hash
[HashSlot(&r1
->resrec
.name
)]; r2
; r2
=r2
->next
)
5612 if (SameResourceRecordSignature(&r1
->resrec
, &r2
->resrec
) && m
->timenow
- r2
->TimeRcvd
> mDNSPlatformOneSecond
)
5614 verbosedebugf("Cache flush %p X %p %##s (%s)", r1
, r2
, r2
->resrec
.name
.c
, DNSTypeName(r2
->resrec
.rrtype
));
5615 // We set stale records to expire in one second.
5616 // This gives the owner a chance to rescue it if necessary.
5617 // This is important in the case of multi-homing and bridged networks:
5618 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
5619 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
5620 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
5621 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
5622 // By delaying the deletion by one second, we give X a change to notice that this bridging has
5623 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
5624 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
5625 // final expiration queries for this record.
5626 r2
->resrec
.rroriginalttl
= 1;
5627 r2
->TimeRcvd
= m
->timenow
;
5628 r2
->UnansweredQueries
= MaxUnansweredQueries
;
5629 SetNextCacheCheckTime(m
, r2
);
5634 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
5635 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*const dstaddr
, const mDNSIPPort dstport
,
5636 const mDNSInterfaceID InterfaceID
, mDNSu8 ttl
)
5638 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
5639 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
5640 const mDNSu8 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
5642 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
5643 mDNSu8
*ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
5644 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
5645 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
5646 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
5647 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
5649 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
5651 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
5652 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
5653 if (!mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
5656 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
5657 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, dstaddr
, InterfaceID
, ttl
);
5658 else debugf("Unknown DNS packet type %02X%02X (ignored)", msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1]);
5660 // Packet reception often causes a change to the task list:
5661 // 1. Inbound queries can cause us to need to send responses
5662 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
5663 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
5664 // 4. Response packets that answer questions may cause our client to issue new questions
5668 // ***************************************************************************
5669 #if COMPILER_LIKES_PRAGMA_MARK
5672 #pragma mark - Searcher Functions
5675 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
5678 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
5679 // This prevents circular references, where two questions are each marked as a duplicate of the other.
5680 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
5681 // further in the list.
5682 for (q
= m
->Questions
; q
&& q
!= question
; q
=q
->next
) // Scan our list of questions
5683 if (q
->InterfaceID
== question
->InterfaceID
&& // for another question with the same InterfaceID,
5684 q
->qtype
== question
->qtype
&& // type,
5685 q
->qclass
== question
->qclass
&& // class,
5686 q
->qnamehash
== question
->qnamehash
&&
5687 SameDomainName(&q
->qname
, &question
->qname
)) // and name
5692 // This is called after a question is deleted, in case other identical questions were being
5693 // suppressed as duplicates
5694 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, const DNSQuestion
*const question
)
5697 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5698 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
5700 q
->ThisQInterval
= question
->ThisQInterval
;
5701 q
->LastQTime
= question
->LastQTime
;
5702 q
->RecentAnswers
= 0;
5703 q
->DuplicateOf
= FindDuplicateQuestion(m
, q
);
5704 q
->LastQTxTime
= question
->LastQTxTime
;
5705 SetNextQueryTime(m
,q
);
5709 mDNSlocal mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
5711 #if TEST_LOCALONLY_FOR_EVERYTHING
5712 question
->InterfaceID
= (mDNSInterfaceID
)~0;
5714 if (m
->rrcache_size
== 0) // Can't do queries if we have no cache space allocated
5715 return(mStatus_NoCache
);
5719 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
5720 DNSQuestion
**q
= &m
->Questions
;
5721 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0)) q
= &m
->LocalOnlyQuestions
;
5722 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
5726 LogMsg("Error! Tried to add a question %##s (%s) that's already in the active list",
5727 question
->qname
.c
, DNSTypeName(question
->qtype
));
5728 return(mStatus_AlreadyRegistered
);
5731 // If this question is referencing a specific interface, make sure it exists
5732 if (question
->InterfaceID
&& question
->InterfaceID
!= ((mDNSInterfaceID
)~0))
5734 NetworkInterfaceInfo
*intf
;
5735 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
5736 if (intf
->InterfaceID
== question
->InterfaceID
) break;
5739 debugf("mDNS_StartQuery_internal: Question %##s InterfaceID %p not found", question
->qname
.c
, question
->InterfaceID
);
5740 return(mStatus_BadReferenceErr
);
5744 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
5745 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
5746 // be a waste. For that reason, we schedule our first query to go out in half a second. If AnswerNewQuestion() finds
5747 // that we have *no* relevant answers currently in our cache, then it will accelerate that to go out immediately.
5748 if (!ValidateDomainName(&question
->qname
))
5750 LogMsg("Attempt to start query with invalid qname %##s %s", question
->qname
.c
, DNSTypeName(question
->qtype
));
5751 return(mStatus_Invalid
);
5754 if (!m
->RandomQueryDelay
) m
->RandomQueryDelay
= 1 + (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
5756 question
->next
= mDNSNULL
;
5757 question
->qnamehash
= DomainNameHashValue(&question
->qname
); // MUST do this before FindDuplicateQuestion()
5758 question
->ThisQInterval
= InitialQuestionInterval
* 2; // MUST be > zero for an active question
5759 question
->LastQTime
= m
->timenow
- m
->RandomQueryDelay
; // Avoid inter-machine synchronization
5760 question
->RecentAnswers
= 0;
5761 question
->CurrentAnswers
= 0;
5762 question
->LargeAnswers
= 0;
5763 question
->UniqueAnswers
= 0;
5764 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
5765 question
->NextInDQList
= mDNSNULL
;
5766 for (i
=0; i
<DupSuppressInfoSize
; i
++)
5767 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
5768 // question->InterfaceID must be already set by caller
5769 question
->SendQNow
= mDNSNULL
;
5770 question
->SendOnAll
= mDNSfalse
;
5771 question
->LastQTxTime
= m
->timenow
;
5773 if (!question
->DuplicateOf
)
5774 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) started",
5775 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, question
);
5777 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) duplicate of (%p)",
5778 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, question
, question
->DuplicateOf
);
5781 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0))
5783 if (!m
->NewLocalOnlyQuestions
) m
->NewLocalOnlyQuestions
= question
;
5787 if (!m
->NewQuestions
) m
->NewQuestions
= question
;
5788 SetNextQueryTime(m
,question
);
5791 return(mStatus_NoError
);
5795 mDNSlocal mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
5798 DNSQuestion
**q
= &m
->Questions
;
5799 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0)) q
= &m
->LocalOnlyQuestions
;
5800 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
5801 if (*q
) *q
= (*q
)->next
;
5804 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
5805 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
5806 question
->qname
.c
, DNSTypeName(question
->qtype
));
5807 return(mStatus_BadReferenceErr
);
5810 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
5811 UpdateQuestionDuplicates(m
, question
);
5812 // But don't trash ThisQInterval until afterwards.
5813 question
->ThisQInterval
= -1;
5815 // If there are any cache records referencing this as their active question, then see if any other
5816 // question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
5817 for (rr
= m
->rrcache_hash
[HashSlot(&question
->qname
)]; rr
; rr
=rr
->next
)
5819 if (rr
->CRActiveQuestion
== question
)
5822 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5823 if (ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
5825 verbosedebugf("mDNS_StopQuery_internal: Cache RR %##s (%s) setting CRActiveQuestion to %X", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), q
);
5826 rr
->CRActiveQuestion
= q
; // Question used to be active; new value may or may not be null
5827 if (!q
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
5831 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv()is about to look at,
5832 // bump its pointer forward one question.
5833 if (m
->CurrentQuestion
== question
)
5835 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
5836 question
->qname
.c
, DNSTypeName(question
->qtype
));
5837 m
->CurrentQuestion
= question
->next
;
5840 if (m
->NewQuestions
== question
)
5842 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
5843 question
->qname
.c
, DNSTypeName(question
->qtype
));
5844 m
->NewQuestions
= question
->next
;
5847 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
5849 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
5850 question
->next
= mDNSNULL
;
5851 return(mStatus_NoError
);
5854 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
5858 status
= mDNS_StartQuery_internal(m
, question
);
5863 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
5867 status
= mDNS_StopQuery_internal(m
, question
);
5872 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const rr
)
5876 status
= mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
5881 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
5883 mStatus status
= mStatus_BadReferenceErr
;
5886 cr
= FindIdenticalRecordInCache(m
, rr
);
5887 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
5892 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
5893 const domainname
*const srv
, const domainname
*const domain
,
5894 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
5896 question
->ThisQInterval
= -1; // Indicate that query is not yet active
5897 question
->InterfaceID
= InterfaceID
;
5898 question
->qtype
= kDNSType_PTR
;
5899 question
->qclass
= kDNSClass_IN
;
5900 question
->QuestionCallback
= Callback
;
5901 question
->QuestionContext
= Context
;
5902 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
)) return(mStatus_BadParamErr
);
5903 return(mDNS_StartQuery(m
, question
));
5906 mDNSlocal
void FoundServiceInfoSRV(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5908 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5909 mDNSBool PortChanged
= (mDNSBool
)(query
->info
->port
.NotAnInteger
!= answer
->rdata
->u
.srv
.port
.NotAnInteger
);
5910 if (!AddRecord
) return;
5911 if (answer
->rrtype
!= kDNSType_SRV
) return;
5913 query
->info
->port
= answer
->rdata
->u
.srv
.port
;
5915 // If this is our first answer, then set the GotSRV flag and start the address query
5918 query
->GotSRV
= mDNStrue
;
5919 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
5920 AssignDomainName(query
->qAv4
.qname
, answer
->rdata
->u
.srv
.target
);
5921 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
5922 AssignDomainName(query
->qAv6
.qname
, answer
->rdata
->u
.srv
.target
);
5923 mDNS_StartQuery_internal(m
, &query
->qAv4
);
5924 mDNS_StartQuery_internal(m
, &query
->qAv6
);
5926 // If this is not our first answer, only re-issue the address query if the target host name has changed
5927 else if ((query
->qAv4
.InterfaceID
!= query
->qSRV
.InterfaceID
&& query
->qAv4
.InterfaceID
!= answer
->InterfaceID
) ||
5928 !SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
))
5930 mDNS_StopQuery_internal(m
, &query
->qAv4
);
5931 mDNS_StopQuery_internal(m
, &query
->qAv6
);
5932 if (SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
) && !PortChanged
)
5934 // If we get here, it means:
5935 // 1. This is not our first SRV answer
5936 // 2. The interface ID is different, but the target host and port are the same
5937 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
5938 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
5939 query
->qAv4
.InterfaceID
= query
->qSRV
.InterfaceID
; // Will be mDNSInterface_Any, or a specific interface
5940 query
->qAv6
.InterfaceID
= query
->qSRV
.InterfaceID
;
5944 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
5945 AssignDomainName(query
->qAv4
.qname
, answer
->rdata
->u
.srv
.target
);
5946 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
5947 AssignDomainName(query
->qAv6
.qname
, answer
->rdata
->u
.srv
.target
);
5949 debugf("FoundServiceInfoSRV: Restarting address queries for %##s", query
->qAv4
.qname
.c
);
5950 mDNS_StartQuery_internal(m
, &query
->qAv4
);
5951 mDNS_StartQuery_internal(m
, &query
->qAv6
);
5953 else if (query
->ServiceInfoQueryCallback
&& query
->GotADD
&& query
->GotTXT
&& PortChanged
)
5955 if (++query
->Answers
>= 100)
5956 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
5957 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.srv
.target
.c
,
5958 ((mDNSu16
)answer
->rdata
->u
.srv
.port
.b
[0] << 8) | answer
->rdata
->u
.srv
.port
.b
[1]);
5959 query
->ServiceInfoQueryCallback(m
, query
);
5961 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5962 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5965 mDNSlocal
void FoundServiceInfoTXT(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5967 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5968 if (!AddRecord
) return;
5969 if (answer
->rrtype
!= kDNSType_TXT
) return;
5970 if (answer
->rdlength
> sizeof(query
->info
->TXTinfo
)) return;
5972 query
->GotTXT
= mDNStrue
;
5973 query
->info
->TXTlen
= answer
->rdlength
;
5974 mDNSPlatformMemCopy(answer
->rdata
->u
.txt
.c
, query
->info
->TXTinfo
, answer
->rdlength
);
5976 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query
->info
->name
.c
, query
->GotADD
);
5978 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5979 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5980 if (query
->ServiceInfoQueryCallback
&& query
->GotADD
)
5982 if (++query
->Answers
>= 100)
5983 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
5984 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.txt
.c
);
5985 query
->ServiceInfoQueryCallback(m
, query
);
5989 mDNSlocal
void FoundServiceInfo(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5991 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5992 if (!AddRecord
) return;
5994 if (answer
->rrtype
== kDNSType_A
)
5996 query
->info
->ip
.type
= mDNSAddrType_IPv4
;
5997 query
->info
->ip
.ip
.v4
= answer
->rdata
->u
.ip
;
5999 else if (answer
->rrtype
== kDNSType_AAAA
)
6001 query
->info
->ip
.type
= mDNSAddrType_IPv6
;
6002 query
->info
->ip
.ip
.v6
= answer
->rdata
->u
.ipv6
;
6006 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer
->name
.c
, answer
->rrtype
, DNSTypeName(answer
->rrtype
));
6010 query
->GotADD
= mDNStrue
;
6011 query
->info
->InterfaceID
= answer
->InterfaceID
;
6013 verbosedebugf("FoundServiceInfo v%d: %##s GotTXT=%d", query
->info
->ip
.type
, query
->info
->name
.c
, query
->GotTXT
);
6015 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
6016 // callback function is allowed to do anything, including deleting this query and freeing its memory.
6017 if (query
->ServiceInfoQueryCallback
&& query
->GotTXT
)
6019 if (++query
->Answers
>= 100)
6021 if (answer
->rrtype
== kDNSType_A
)
6022 debugf("**** WARNING **** have given %lu answers for %##s (A) %.4a", query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.ip
);
6024 debugf("**** WARNING **** have given %lu answers for %##s (AAAA) %.16a", query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.ipv6
);
6026 query
->ServiceInfoQueryCallback(m
, query
);
6030 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
6031 // If the query is not interface-specific, then InterfaceID may be zero
6032 // Each time the Callback is invoked, the remainder of the fields will have been filled in
6033 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
6034 mDNSexport mStatus
mDNS_StartResolveService(mDNS
*const m
,
6035 ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
)
6040 query
->qSRV
.ThisQInterval
= -1; // This question not yet in the question list
6041 query
->qSRV
.InterfaceID
= info
->InterfaceID
;
6042 AssignDomainName(query
->qSRV
.qname
, info
->name
);
6043 query
->qSRV
.qtype
= kDNSType_SRV
;
6044 query
->qSRV
.qclass
= kDNSClass_IN
;
6045 query
->qSRV
.QuestionCallback
= FoundServiceInfoSRV
;
6046 query
->qSRV
.QuestionContext
= query
;
6048 query
->qTXT
.ThisQInterval
= -1; // This question not yet in the question list
6049 query
->qTXT
.InterfaceID
= info
->InterfaceID
;
6050 AssignDomainName(query
->qTXT
.qname
, info
->name
);
6051 query
->qTXT
.qtype
= kDNSType_TXT
;
6052 query
->qTXT
.qclass
= kDNSClass_IN
;
6053 query
->qTXT
.QuestionCallback
= FoundServiceInfoTXT
;
6054 query
->qTXT
.QuestionContext
= query
;
6056 query
->qAv4
.ThisQInterval
= -1; // This question not yet in the question list
6057 query
->qAv4
.InterfaceID
= info
->InterfaceID
;
6058 query
->qAv4
.qname
.c
[0] = 0;
6059 query
->qAv4
.qtype
= kDNSType_A
;
6060 query
->qAv4
.qclass
= kDNSClass_IN
;
6061 query
->qAv4
.QuestionCallback
= FoundServiceInfo
;
6062 query
->qAv4
.QuestionContext
= query
;
6064 query
->qAv6
.ThisQInterval
= -1; // This question not yet in the question list
6065 query
->qAv6
.InterfaceID
= info
->InterfaceID
;
6066 query
->qAv6
.qname
.c
[0] = 0;
6067 query
->qAv6
.qtype
= kDNSType_AAAA
;
6068 query
->qAv6
.qclass
= kDNSClass_IN
;
6069 query
->qAv6
.QuestionCallback
= FoundServiceInfo
;
6070 query
->qAv6
.QuestionContext
= query
;
6072 query
->GotSRV
= mDNSfalse
;
6073 query
->GotTXT
= mDNSfalse
;
6074 query
->GotADD
= mDNSfalse
;
6078 query
->ServiceInfoQueryCallback
= Callback
;
6079 query
->ServiceInfoQueryContext
= Context
;
6081 // info->name = Must already be set up by client
6082 // info->interface = Must already be set up by client
6083 info
->ip
= zeroAddr
;
6084 info
->port
= zeroIPPort
;
6087 status
= mDNS_StartQuery_internal(m
, &query
->qSRV
);
6088 if (status
== mStatus_NoError
) status
= mDNS_StartQuery_internal(m
, &query
->qTXT
);
6089 if (status
!= mStatus_NoError
) mDNS_StopResolveService(m
, query
);
6095 mDNSexport
void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*query
)
6098 if (query
->qSRV
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qSRV
);
6099 if (query
->qTXT
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qTXT
);
6100 if (query
->qAv4
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qAv4
);
6101 if (query
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qAv6
);
6105 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
,
6106 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
6108 MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
]);
6109 question
->InterfaceID
= InterfaceID
;
6110 question
->qtype
= kDNSType_PTR
;
6111 question
->qclass
= kDNSClass_IN
;
6112 question
->QuestionCallback
= Callback
;
6113 question
->QuestionContext
= Context
;
6115 // No sense doing this until we actually support unicast query/update
6116 //return(mDNS_StartQuery(m, question));
6118 return(mStatus_NoError
);
6121 // ***************************************************************************
6122 #if COMPILER_LIKES_PRAGMA_MARK
6124 #pragma mark - Responder Functions
6127 // Set up a AuthRecord with sensible default values.
6128 // These defaults may be overwritten with new values before mDNS_Register is called
6129 mDNSexport
void mDNS_SetupResourceRecord(AuthRecord
*rr
, RData
*RDataStorage
, mDNSInterfaceID InterfaceID
,
6130 mDNSu16 rrtype
, mDNSu32 ttl
, mDNSu8 RecordType
, mDNSRecordCallback Callback
, void *Context
)
6132 // Don't try to store a TTL bigger than we can represent in platform time units
6133 if (ttl
> 0x7FFFFFFFUL
/ mDNSPlatformOneSecond
)
6134 ttl
= 0x7FFFFFFFUL
/ mDNSPlatformOneSecond
;
6135 else if (ttl
== 0) // And Zero TTL is illegal
6136 ttl
= kDefaultTTLforShared
;
6138 // Field Group 1: Persistent metadata for Authoritative Records
6139 rr
->Additional1
= mDNSNULL
;
6140 rr
->Additional2
= mDNSNULL
;
6141 rr
->DependentOn
= mDNSNULL
;
6142 rr
->RRSet
= mDNSNULL
;
6143 rr
->RecordCallback
= Callback
;
6144 rr
->RecordContext
= Context
;
6146 rr
->resrec
.RecordType
= RecordType
;
6147 rr
->HostTarget
= mDNSfalse
;
6149 // Field Group 2: Transient state for Authoritative Records (set in mDNS_Register_internal)
6150 // Field Group 3: Transient state for Cache Records (set in mDNS_Register_internal)
6152 // Field Group 4: The actual information pertaining to this resource record
6153 rr
->resrec
.InterfaceID
= InterfaceID
;
6154 rr
->resrec
.name
.c
[0] = 0; // MUST be set by client
6155 rr
->resrec
.rrtype
= rrtype
;
6156 rr
->resrec
.rrclass
= kDNSClass_IN
;
6157 rr
->resrec
.rroriginalttl
= ttl
;
6158 // rr->resrec.rdlength = MUST set by client and/or in mDNS_Register_internal
6159 // rr->resrec.rdestimate = set in mDNS_Register_internal
6160 // rr->resrec.rdata = MUST be set by client
6163 rr
->resrec
.rdata
= RDataStorage
;
6166 rr
->resrec
.rdata
= &rr
->rdatastorage
;
6167 rr
->resrec
.rdata
->MaxRDLength
= sizeof(RDataBody
);
6171 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
6175 status
= mDNS_Register_internal(m
, rr
);
6180 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
6181 const mDNSu16 newrdlength
,
6182 RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
6184 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
6185 { LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(m
, &rr
->resrec
, &newrdata
->u
)); return(mStatus_Invalid
); }
6189 // If TTL is unspecified, leave TTL unchanged
6190 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
6192 // If we already have an update queued up which has not gone through yet,
6193 // give the client a chance to free that memory
6196 RData
*n
= rr
->NewRData
;
6197 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
6198 if (rr
->UpdateCallback
)
6199 rr
->UpdateCallback(m
, rr
, n
); // ...and let the client free this memory, if necessary
6202 if (rr
->AnnounceCount
< ReannounceCount
)
6203 rr
->AnnounceCount
= ReannounceCount
;
6204 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
6205 InitializeLastAPTime(m
, rr
);
6206 rr
->NewRData
= newrdata
;
6207 rr
->newrdlength
= newrdlength
;
6208 rr
->UpdateCallback
= Callback
;
6209 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
6210 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= (m
->timenow
+ mDNSPlatformOneSecond
* 60) | 1;
6211 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
6212 if (rr
->UpdateCredits
<= 5)
6214 mDNSs32 delay
= 1 << (5 - rr
->UpdateCredits
);
6215 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= (m
->timenow
+ delay
* mDNSPlatformOneSecond
) | 1;
6216 rr
->LastAPTime
= rr
->UpdateBlocked
;
6217 rr
->ThisAPInterval
*= 4;
6218 LogMsg("Excessive update rate for %##s; delaying announcement by %d seconds", rr
->resrec
.name
.c
, delay
);
6220 rr
->resrec
.rroriginalttl
= newttl
;
6222 return(mStatus_NoError
);
6225 // NOTE: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
6226 // the record list and/or question list.
6227 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6228 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
6232 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6237 mDNSlocal
void HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
6239 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
6241 NetworkInterfaceInfo
*intf
;
6242 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6243 if (intf
->Advertise
) break;
6247 mDNSlocal
void mDNS_AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6250 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
6251 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
6253 mDNS_SetupResourceRecord(&set
->RR_A
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, HostNameCallback
, set
);
6254 mDNS_SetupResourceRecord(&set
->RR_PTR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kDefaultTTLforUnique
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
6255 mDNS_SetupResourceRecord(&set
->RR_HINFO
, mDNSNULL
, set
->InterfaceID
, kDNSType_HINFO
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, mDNSNULL
, mDNSNULL
);
6257 // 1. Set up Address record to map from host name ("foo.local.") to IP address
6258 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
6259 AssignDomainName(set
->RR_A
.resrec
.name
, m
->hostname
);
6260 if (set
->ip
.type
== mDNSAddrType_IPv4
)
6262 set
->RR_A
.resrec
.rrtype
= kDNSType_A
;
6263 set
->RR_A
.resrec
.rdata
->u
.ip
= set
->ip
.ip
.v4
;
6264 // Note: This is reverse order compared to a normal dotted-decimal IP address
6265 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
6266 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
6268 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
6271 set
->RR_A
.resrec
.rrtype
= kDNSType_AAAA
;
6272 set
->RR_A
.resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
6273 for (i
= 0; i
< 16; i
++)
6275 static const char hexValues
[] = "0123456789ABCDEF";
6276 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
6277 buffer
[i
* 4 + 1] = '.';
6278 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
6279 buffer
[i
* 4 + 3] = '.';
6281 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
6284 MakeDomainNameFromDNSNameString(&set
->RR_PTR
.resrec
.name
, buffer
);
6285 set
->RR_PTR
.HostTarget
= mDNStrue
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
6287 set
->RR_A
.RRSet
= &primary
->RR_A
; // May refer to self
6289 mDNS_Register_internal(m
, &set
->RR_A
);
6290 mDNS_Register_internal(m
, &set
->RR_PTR
);
6292 if (m
->HIHardware
.c
[0] > 0 && m
->HISoftware
.c
[0] > 0 && m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0] <= 254)
6294 mDNSu8
*p
= set
->RR_HINFO
.resrec
.rdata
->u
.data
;
6295 AssignDomainName(set
->RR_HINFO
.resrec
.name
, m
->hostname
);
6296 set
->RR_HINFO
.DependentOn
= &set
->RR_A
;
6297 mDNSPlatformMemCopy(&m
->HIHardware
, p
, 1 + (mDNSu32
)m
->HIHardware
.c
[0]);
6299 mDNSPlatformMemCopy(&m
->HISoftware
, p
, 1 + (mDNSu32
)m
->HISoftware
.c
[0]);
6300 mDNS_Register_internal(m
, &set
->RR_HINFO
);
6304 debugf("Not creating HINFO record: platform support layer provided no information");
6305 set
->RR_HINFO
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
6309 mDNSlocal
void mDNS_DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6311 NetworkInterfaceInfo
*intf
;
6312 // If we still have address records referring to this one, update them
6313 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
6314 AuthRecord
*A
= primary
? &primary
->RR_A
: mDNSNULL
;
6315 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6316 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
6317 intf
->RR_A
.RRSet
= A
;
6319 // Unregister these records.
6320 // When doing the mDNS_Close processing, we first call mDNS_DeadvertiseInterface for each interface, so by the time the platform
6321 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
6322 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
6323 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
6324 if (set
->RR_A
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
6325 if (set
->RR_PTR
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
6326 if (set
->RR_HINFO
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_HINFO
, mDNS_Dereg_normal
);
6329 mDNSexport
void mDNS_GenerateFQDN(mDNS
*const m
)
6335 if (!AppendDomainLabel(&newname
, &m
->hostlabel
)) LogMsg("ERROR! Cannot create dot-local hostname");
6336 if (!AppendLiteralLabelString(&newname
, "local")) LogMsg("ERROR! Cannot create dot-local hostname");
6337 if (!SameDomainName(&m
->hostname
, &newname
))
6339 NetworkInterfaceInfo
*intf
;
6342 m
->hostname
= newname
;
6344 // 1. Stop advertising our address records on all interfaces
6345 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6346 if (intf
->Advertise
) mDNS_DeadvertiseInterface(m
, intf
);
6348 // 2. Start advertising our address records using the new name
6349 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6350 if (intf
->Advertise
) mDNS_AdvertiseInterface(m
, intf
);
6352 // 3. Make sure that any SRV records (and the like) that reference our
6353 // host name in their rdata get updated to reference this new host name
6354 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->HostTarget
) SetTargetToHostName(m
, rr
);
6355 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->HostTarget
) SetTargetToHostName(m
, rr
);
6361 mDNSlocal
void HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
6363 (void)rr
; // Unused parameter
6367 char *msg
= "Unknown result";
6368 if (result
== mStatus_NoError
) msg
= "Name registered";
6369 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
6370 debugf("HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
6374 if (result
== mStatus_NoError
)
6376 // Notify the client that the host name is successfully registered
6377 if (m
->MainCallback
)
6378 m
->MainCallback(m
, result
);
6380 else if (result
== mStatus_NameConflict
)
6382 domainlabel oldlabel
= m
->hostlabel
;
6384 // 1. First give the client callback a chance to pick a new name
6385 if (m
->MainCallback
)
6386 m
->MainCallback(m
, mStatus_NameConflict
);
6388 // 2. If the client callback didn't do it, add (or increment) an index ourselves
6389 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
6390 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
6392 // 3. Generate the FQDNs from the hostlabel,
6393 // and make sure all SRV records, etc., are updated to reference our new hostname
6394 mDNS_GenerateFQDN(m
);
6398 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
6400 NetworkInterfaceInfo
*intf
;
6401 active
->IPv4Available
= mDNSfalse
;
6402 active
->IPv6Available
= mDNSfalse
;
6403 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6404 if (intf
->InterfaceID
== active
->InterfaceID
)
6406 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->TxAndRx
) active
->IPv4Available
= mDNStrue
;
6407 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->TxAndRx
) active
->IPv6Available
= mDNStrue
;
6411 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6413 mDNSBool FirstOfType
= mDNStrue
;
6414 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
6417 // Assume this interface will be active
6418 set
->InterfaceActive
= mDNStrue
;
6419 set
->IPv4Available
= (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->TxAndRx
);
6420 set
->IPv6Available
= (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->TxAndRx
);
6426 LogMsg("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
6428 return(mStatus_AlreadyRegistered
);
6431 // This InterfaceID is already in the list, so mark this interface inactive for now
6432 if ((*p
)->InterfaceID
== set
->InterfaceID
)
6434 set
->InterfaceActive
= mDNSfalse
;
6435 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
6436 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->TxAndRx
) (*p
)->IPv4Available
= mDNStrue
;
6437 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->TxAndRx
) (*p
)->IPv6Available
= mDNStrue
;
6443 set
->next
= mDNSNULL
;
6446 debugf("mDNS_RegisterInterface: InterfaceID %p %#a %s", set
->InterfaceID
, &set
->ip
,
6447 set
->InterfaceActive
?
6448 "not represented in list; marking active and retriggering queries" :
6449 "already represented in list; marking inactive for now");
6451 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6452 // giving the false impression that there's an active representative of this interface when there really isn't.
6453 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
6454 // even if we believe that we previously had an active representative of this interface.
6455 if ((m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) || FirstOfType
|| set
->InterfaceActive
)
6459 // Use a small amount of randomness:
6460 // In the case of a network administrator turning on an Ethernet hub so that all the connected machines establish link at
6461 // exactly the same time, we don't want them to all go and hit the network with identical queries at exactly the same moment.
6462 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
6463 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
6464 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
6465 { // then reactivate this question
6466 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
6467 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
6468 q
->RecentAnswers
= 0;
6469 if (ActiveQuestion(q
)) m
->NextScheduledQuery
= m
->timenow
;
6472 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
6473 // we now need them to re-probe if necessary, and then re-announce.
6474 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6475 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6477 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
6478 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
6479 if (rr
->AnnounceCount
< ReannounceCount
)
6480 rr
->AnnounceCount
= ReannounceCount
;
6481 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
6482 InitializeLastAPTime(m
, rr
);
6487 mDNS_AdvertiseInterface(m
, set
);
6490 return(mStatus_NoError
);
6493 // NOTE: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
6494 // the record list and/or question list.
6495 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6496 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6498 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
6500 mDNSBool revalidate
= mDNSfalse
;
6501 // If this platform has the "phantom interfaces" known bug (e.g. Jaguar), we have to revalidate records every
6502 // time an interface goes away. Otherwise, when you disconnect the Ethernet cable, the system reports that it
6503 // still has an IPv6 address, and if we don't revalidate those records don't get deleted in a timely fashion.
6504 if (m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) revalidate
= mDNStrue
;
6508 // Find this record in our list
6509 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
6510 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
6512 // Unlink this record from our list
6514 set
->next
= mDNSNULL
;
6516 if (!set
->InterfaceActive
)
6518 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
6519 NetworkInterfaceInfo
*intf
;
6520 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6521 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
6522 UpdateInterfaceProtocols(m
, intf
);
6526 NetworkInterfaceInfo
*intf
;
6527 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6528 if (intf
->InterfaceID
== set
->InterfaceID
)
6532 debugf("mDNS_DeregisterInterface: Another representative of InterfaceID %p exists; making it active",
6534 intf
->InterfaceActive
= mDNStrue
;
6535 UpdateInterfaceProtocols(m
, intf
);
6537 // See if another representative *of the same type* exists. If not, we mave have gone from
6538 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
6539 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6540 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
6542 if (!intf
) revalidate
= mDNStrue
;
6549 debugf("mDNS_DeregisterInterface: Last representative of InterfaceID %p deregistered; marking questions etc. dormant",
6552 // 1. Deactivate any questions specific to this interface
6553 for (q
= m
->Questions
; q
; q
=q
->next
)
6554 if (q
->InterfaceID
== set
->InterfaceID
)
6555 q
->ThisQInterval
= 0;
6557 // 2. Flush any cache records received on this interface
6558 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
6559 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6560 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
6561 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6562 PurgeCacheResourceRecord(m
, rr
);
6566 // If we were advertising on this interface, deregister those address and reverse-lookup records now
6568 mDNS_DeadvertiseInterface(m
, set
);
6570 // If we have any cache records received on this interface that went away, then re-verify them.
6571 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6572 // giving the false impression that there's an active representative of this interface when there really isn't.
6573 // Don't need to do this when shutting down, because *all* interfaces are about to go away
6574 if (revalidate
&& !m
->mDNS_shutdown
)
6578 m
->NextCacheCheck
= m
->timenow
;
6579 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6580 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
6581 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6582 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForCableDisconnect
);
6588 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
6590 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
6591 (void)m
; // Unused parameter
6595 char *msg
= "Unknown result";
6596 if (result
== mStatus_NoError
) msg
= "Name Registered";
6597 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
6598 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
6599 debugf("ServiceCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
6603 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
6604 if (result
== mStatus_NameConflict
)
6606 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
6607 sr
->RR_PTR
.AnnounceCount
= InitialAnnounceCount
; // Make sure we don't send a goodbye for the PTR record
6608 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
6612 if (result
== mStatus_MemFree
)
6614 // If the PTR record or any of the subtype PTR record are still in the process of deregistering,
6615 // don't pass on the NameConflict/MemFree message until every record is finished cleaning up.
6617 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
6618 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
6620 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
6621 // then we can now report the NameConflict to the client
6622 if (sr
->Conflict
) result
= mStatus_NameConflict
;
6625 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
6626 // function is allowed to do anything, including deregistering this service and freeing its memory.
6627 if (sr
->ServiceCallback
)
6628 sr
->ServiceCallback(m
, sr
, result
);
6632 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
6633 // Type is service type (e.g. "_printer._tcp.")
6634 // Domain is fully qualified domain name (i.e. ending with a null label)
6635 // We always register a TXT, even if it is empty (so that clients are not
6636 // left waiting forever looking for a nonexistent record.)
6637 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
6638 // then the default host name (m->hostname1) is automatically used
6639 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
6640 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
6641 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
6642 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
6643 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
)
6648 sr
->ServiceCallback
= Callback
;
6649 sr
->ServiceContext
= Context
;
6650 sr
->Extras
= mDNSNULL
;
6651 sr
->NumSubTypes
= NumSubTypes
;
6652 sr
->SubTypes
= SubTypes
;
6653 sr
->Conflict
= mDNSfalse
;
6654 if (host
&& host
->c
[0]) sr
->Host
= *host
;
6655 else sr
->Host
.c
[0] = 0;
6657 // Initialize the AuthRecord objects to sane values
6658 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeAdvisory
, ServiceCallback
, sr
);
6659 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
6660 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6661 mDNS_SetupResourceRecord(&sr
->RR_TXT
, mDNSNULL
, InterfaceID
, kDNSType_TXT
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6663 // If the client is registering an oversized TXT record,
6664 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
6665 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
6666 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
6668 // Set up the record names
6669 // For now we only create an advisory record for the main type, not for subtypes
6670 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
6671 if (ConstructServiceName(&sr
->RR_ADV
.resrec
.name
, (domainlabel
*)"\x09_services", (domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
6672 return(mStatus_BadParamErr
);
6673 if (ConstructServiceName(&sr
->RR_PTR
.resrec
.name
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6674 if (ConstructServiceName(&sr
->RR_SRV
.resrec
.name
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6675 AssignDomainName(sr
->RR_TXT
.resrec
.name
, sr
->RR_SRV
.resrec
.name
);
6677 // 1. Set up the ADV record rdata to advertise our service type
6678 AssignDomainName(sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
6680 // 2. Set up the PTR record rdata to point to our service name
6681 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
6682 AssignDomainName(sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
6683 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
6684 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
6686 // 2a. Set up any subtype PTRs to point to our service name
6687 // If the client is using subtypes, it is the client's responsibility to have
6688 // already set the first label of the record name to the subtype being registered
6689 for (i
=0; i
<NumSubTypes
; i
++)
6691 domainlabel s
= *(domainlabel
*)&sr
->SubTypes
[i
].resrec
.name
;
6692 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
6693 if (ConstructServiceName(&sr
->SubTypes
[i
].resrec
.name
, &s
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6694 AssignDomainName(sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
6695 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
6696 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
6699 // 3. Set up the SRV record rdata.
6700 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
6701 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
6702 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
6704 // Setting HostTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
6705 if (sr
->Host
.c
[0]) AssignDomainName(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, sr
->Host
);
6706 else sr
->RR_SRV
.HostTarget
= mDNStrue
;
6708 // 4. Set up the TXT record rdata,
6709 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
6710 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
6711 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
6713 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
6714 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
6715 mDNSPlatformMemCopy(txtinfo
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtlen
);
6717 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
6720 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
6721 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
6722 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
6723 // mDNS_Close, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
6724 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
6725 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
6726 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
6727 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
6728 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
6729 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
6732 if (err
) mDNS_DeregisterService(m
, sr
);
6736 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
6737 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
)
6739 mStatus result
= mStatus_UnknownErr
;
6740 ExtraResourceRecord
**e
= &sr
->Extras
;
6741 while (*e
) e
= &(*e
)->next
;
6743 // If TTL is unspecified, make it the same as the service's TXT and SRV default
6744 if (ttl
== 0) ttl
= kDefaultTTLforUnique
;
6746 extra
->next
= mDNSNULL
;
6747 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
, extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6748 AssignDomainName(extra
->r
.resrec
.name
, sr
->RR_SRV
.resrec
.name
);
6749 extra
->r
.DependentOn
= &sr
->RR_SRV
;
6751 debugf("mDNS_AddRecordToService adding record to %##s", extra
->r
.resrec
.name
.c
);
6753 result
= mDNS_Register(m
, &extra
->r
);
6754 if (!result
) *e
= extra
;
6758 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
)
6760 ExtraResourceRecord
**e
= &sr
->Extras
;
6761 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
6764 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
.c
);
6765 return(mStatus_BadReferenceErr
);
6768 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
.c
);
6771 return(mDNS_Deregister(m
, &extra
->r
));
6774 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
6777 domainname type
, domain
;
6778 domainname
*host
= mDNSNULL
;
6779 ExtraResourceRecord
*extras
= sr
->Extras
;
6782 DeconstructServiceName(&sr
->RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
6785 IncrementLabelSuffix(&name
, mDNStrue
);
6788 debugf("Reregistering as %#s", newname
->c
);
6789 if (sr
->RR_SRV
.HostTarget
== mDNSfalse
&& sr
->Host
.c
[0]) host
= &sr
->Host
;
6791 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
6792 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
6793 sr
->SubTypes
, sr
->NumSubTypes
,
6794 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
);
6796 // mDNS_RegisterService() just reset sr->Extras to NULL.
6797 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
6798 // through the old list of extra records, and re-add them to our freshly created service registration
6799 while (!err
&& extras
)
6801 ExtraResourceRecord
*e
= extras
;
6802 extras
= extras
->next
;
6803 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
);
6809 // NOTE: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
6810 // which may change the record list and/or question list.
6811 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6812 mDNSexport mStatus
mDNS_DeregisterService(mDNS
*const m
, ServiceRecordSet
*sr
)
6814 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
6816 debugf("Service set for %##s already deregistered", sr
->RR_PTR
.resrec
.name
.c
);
6817 return(mStatus_BadReferenceErr
);
6819 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
6821 debugf("Service set for %##s already in the process of deregistering", sr
->RR_PTR
.resrec
.name
.c
);
6822 return(mStatus_NoError
);
6828 ExtraResourceRecord
*e
;
6832 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
6833 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
6834 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
6835 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
6837 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, mDNS_Dereg_normal
);
6839 // We deregister all of the extra records, but we leave the sr->Extras list intact
6840 // in case the client wants to do a RenameAndReregister and reinstate the registration
6843 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
6847 for (i
=0; i
<sr
->NumSubTypes
; i
++)
6848 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], mDNS_Dereg_normal
);
6850 // Be sure to deregister the PTR last!
6851 // Deregistering this record is what triggers the mStatus_MemFree callback to ServiceCallback,
6852 // which in turn passes on the mStatus_MemFree (or mStatus_NameConflict) back to the client callback,
6853 // which is then at liberty to free the ServiceRecordSet memory at will. We need to make sure
6854 // we've deregistered all our records and done any other necessary cleanup before that happens.
6855 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, mDNS_Dereg_normal
);
6861 // Create a registration that asserts that no such service exists with this name.
6862 // This can be useful where there is a given function is available through several protocols.
6863 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
6864 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
6865 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
6866 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
6867 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
6868 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
6869 const domainname
*const host
,
6870 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
)
6872 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, Callback
, Context
);
6873 if (ConstructServiceName(&rr
->resrec
.name
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6874 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
6875 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
6876 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
6877 if (host
&& host
->c
[0]) AssignDomainName(rr
->resrec
.rdata
->u
.srv
.target
, *host
);
6878 else rr
->HostTarget
= mDNStrue
;
6879 return(mDNS_Register(m
, rr
));
6882 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
6883 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
6885 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, mDNSNULL
, mDNSNULL
);
6886 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.name
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
6887 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
6888 return(mDNS_Register(m
, rr
));
6891 // ***************************************************************************
6892 #if COMPILER_LIKES_PRAGMA_MARK
6895 #pragma mark - Startup and Shutdown
6898 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheRecord
*storage
, mDNSu32 numrecords
)
6900 if (storage
&& numrecords
)
6903 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
6904 storage
[numrecords
-1].next
= m
->rrcache_free
;
6905 m
->rrcache_free
= storage
;
6906 m
->rrcache_size
+= numrecords
;
6910 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
6911 CacheRecord
*rrcachestorage
, mDNSu32 rrcachesize
,
6912 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
6916 mStatus result
= mDNSPlatformTimeInit(&timenow
);
6917 if (result
!= mStatus_NoError
) return(result
);
6919 if (!rrcachestorage
) rrcachesize
= 0;
6923 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
6924 m
->mDNSPlatformStatus
= mStatus_Waiting
;
6925 m
->MainCallback
= Callback
;
6926 m
->MainContext
= Context
;
6928 // For debugging: To catch and report locking failures
6930 m
->mDNS_reentrancy
= 0;
6931 m
->mDNS_shutdown
= mDNSfalse
;
6932 m
->lock_rrcache
= 0;
6933 m
->lock_Questions
= 0;
6934 m
->lock_Records
= 0;
6936 // Task Scheduling variables
6937 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
6938 m
->timenow_last
= timenow
;
6939 m
->timenow_adjust
= 0;
6940 m
->NextScheduledEvent
= timenow
;
6941 m
->SuppressSending
= timenow
;
6942 m
->NextCacheCheck
= timenow
+ 0x78000000;
6943 m
->NextScheduledQuery
= timenow
+ 0x78000000;
6944 m
->NextScheduledProbe
= timenow
+ 0x78000000;
6945 m
->NextScheduledResponse
= timenow
+ 0x78000000;
6946 m
->ExpectUnicastResponse
= timenow
+ 0x78000000;
6947 m
->RandomQueryDelay
= 0;
6948 m
->SendDeregistrations
= mDNSfalse
;
6949 m
->SendImmediateAnswers
= mDNSfalse
;
6950 m
->SleepState
= mDNSfalse
;
6952 // These fields only required for mDNS Searcher...
6953 m
->Questions
= mDNSNULL
;
6954 m
->NewQuestions
= mDNSNULL
;
6955 m
->CurrentQuestion
= mDNSNULL
;
6956 m
->LocalOnlyQuestions
= mDNSNULL
;
6957 m
->NewLocalOnlyQuestions
= mDNSNULL
;
6958 m
->rrcache_size
= 0;
6959 m
->rrcache_totalused
= 0;
6960 m
->rrcache_active
= 0;
6961 m
->rrcache_report
= 10;
6962 m
->rrcache_free
= mDNSNULL
;
6964 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6966 m
->rrcache_hash
[slot
] = mDNSNULL
;
6967 m
->rrcache_tail
[slot
] = &m
->rrcache_hash
[slot
];
6968 m
->rrcache_used
[slot
] = 0;
6971 mDNS_GrowCache(m
, rrcachestorage
, rrcachesize
);
6973 // Fields below only required for mDNS Responder...
6974 m
->hostlabel
.c
[0] = 0;
6975 m
->nicelabel
.c
[0] = 0;
6976 m
->hostname
.c
[0] = 0;
6977 m
->HIHardware
.c
[0] = 0;
6978 m
->HISoftware
.c
[0] = 0;
6979 m
->ResourceRecords
= mDNSNULL
;
6980 m
->DuplicateRecords
= mDNSNULL
;
6981 m
->LocalOnlyRecords
= mDNSNULL
;
6982 m
->NewLocalOnlyRecords
= mDNSNULL
;
6983 m
->DiscardLocalOnlyRecords
= mDNSfalse
;
6984 m
->CurrentRecord
= mDNSNULL
;
6985 m
->HostInterfaces
= mDNSNULL
;
6986 m
->ProbeFailTime
= 0;
6987 m
->NumFailedProbes
= 0;
6988 m
->SuppressProbes
= 0;
6990 result
= mDNSPlatformInit(m
);
6995 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
6997 m
->mDNSPlatformStatus
= result
;
6998 if (m
->MainCallback
)
6999 m
->MainCallback(m
, mStatus_NoError
);
7002 mDNSexport
void mDNS_Close(mDNS
*const m
)
7004 mDNSu32 rrcache_active
= 0;
7005 mDNSu32 rrcache_totalused
= 0;
7007 NetworkInterfaceInfo
*intf
;
7010 m
->mDNS_shutdown
= mDNStrue
;
7012 rrcache_totalused
= m
->rrcache_totalused
;
7013 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
7015 while (m
->rrcache_hash
[slot
])
7017 CacheRecord
*rr
= m
->rrcache_hash
[slot
];
7018 m
->rrcache_hash
[slot
] = rr
->next
;
7019 if (rr
->CRActiveQuestion
) rrcache_active
++;
7020 m
->rrcache_used
[slot
]--;
7021 ReleaseCacheRR(m
, rr
);
7023 // Reset tail pointer back to empty state (not that it really matters on exit, but we'll do it anyway, for the sake of completeness)
7024 m
->rrcache_tail
[slot
] = &m
->rrcache_hash
[slot
];
7026 debugf("mDNS_Close: RR Cache was using %ld records, %d active", rrcache_totalused
, rrcache_active
);
7027 if (rrcache_active
!= m
->rrcache_active
)
7028 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active
, m
->rrcache_active
);
7030 m
->Questions
= mDNSNULL
; // We won't be answering any more questions!
7032 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
7033 if (intf
->Advertise
)
7034 mDNS_DeadvertiseInterface(m
, intf
);
7036 // Make sure there are nothing but deregistering records remaining in the list
7037 if (m
->CurrentRecord
) LogMsg("mDNS_Close ERROR m->CurrentRecord already set");
7038 m
->CurrentRecord
= m
->ResourceRecords
;
7039 while (m
->CurrentRecord
)
7041 AuthRecord
*rr
= m
->CurrentRecord
;
7042 m
->CurrentRecord
= rr
->next
;
7043 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
7045 debugf("mDNS_Close: Record type %X still in ResourceRecords list %##s", rr
->resrec
.RecordType
, rr
->resrec
.name
.c
);
7046 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7050 if (m
->ResourceRecords
) debugf("mDNS_Close: Sending final packets for deregistering records");
7051 else debugf("mDNS_Close: No deregistering records remain");
7053 // If any deregistering records remain, send their deregistration announcements before we exit
7054 if (m
->mDNSPlatformStatus
!= mStatus_NoError
)
7055 DiscardDeregistrations(m
);
7057 while (m
->ResourceRecords
)
7061 debugf("mDNS_Close: mDNSPlatformClose");
7062 mDNSPlatformClose(m
);
7063 debugf("mDNS_Close: done");