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.2 2003/12/20 01:51:40 cheshire
48 <rdar://problem/3515876>: Error putting additional records into packets
49 Another fix from Rampi: responseptr needs to be updated inside the "for" loop,
50 after every record, not once at the end.
52 Revision 1.307.2.1 2003/12/03 11:20:27 cheshire
53 <rdar://problem/3457718>: Stop and start of a service uses old ip address (with old port number)
55 Revision 1.307 2003/09/09 20:13:30 cheshire
56 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
57 Ammend checkin 1.304: Off-by-one error: By this place in the function we've already decremented
58 rr->AnnounceCount, so the check needs to be for InitialAnnounceCount-1, not InitialAnnounceCount
60 Revision 1.306 2003/09/09 03:00:03 cheshire
61 <rdar://problem/3413099> Services take a long time to disappear when switching networks.
62 Added two constants: kDefaultReconfirmTimeForNoAnswer and kDefaultReconfirmTimeForCableDisconnect
64 Revision 1.305 2003/09/09 02:49:31 cheshire
65 <rdar://problem/3413975> Initial probes and queries not grouped on wake-from-sleep
67 Revision 1.304 2003/09/09 02:41:19 cheshire
68 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
70 Revision 1.303 2003/09/05 19:55:02 cheshire
71 <rdar://problem/3409533> Include address records when announcing SRV records
73 Revision 1.302 2003/09/05 00:01:36 cheshire
74 <rdar://problem/3407549> Don't accelerate queries that have large KA lists
76 Revision 1.301 2003/09/04 22:51:13 cheshire
77 <rdar://problem/3398213> Group probes and goodbyes better
79 Revision 1.300 2003/09/03 02:40:37 cheshire
80 <rdar://problem/3404842> mDNSResponder complains about '_'s
81 Underscores are not supposed to be legal in standard DNS names, but IANA appears
82 to have allowed them in previous service name registrations, so we should too.
84 Revision 1.299 2003/09/03 02:33:09 cheshire
85 <rdar://problem/3404795> CacheRecordRmv ERROR
86 Don't update m->NewQuestions until *after* CheckCacheExpiration();
88 Revision 1.298 2003/09/03 01:47:01 cheshire
89 <rdar://problem/3319418> Rendezvous services always in a state of flux
90 Change mDNS_Reconfirm_internal() minimum timeout from 5 seconds to 45-60 seconds
92 Revision 1.297 2003/08/29 19:44:15 cheshire
93 <rdar://problem/3400967> Traffic reduction: Eliminate synchronized QUs when a new service appears
94 1. Use m->RandomQueryDelay to impose a random delay in the range 0-500ms on queries
95 that already have at least one unique answer in the cache
96 2. For these queries, go straight to QM, skipping QU
98 Revision 1.296 2003/08/29 19:08:21 cheshire
99 <rdar://problem/3400986> Traffic reduction: Eliminate huge KA lists after wake from sleep
100 Known answers are no longer eligible to go in the KA list if they are more than half-way to their expiry time.
102 Revision 1.295 2003/08/28 01:10:59 cheshire
103 <rdar://problem/3396034> Add syslog message to report when query is reset because of immediate answer burst
105 Revision 1.294 2003/08/27 02:30:22 cheshire
106 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
107 One more change: "query->GotTXT" is now a straightforward bi-state boolean again
109 Revision 1.293 2003/08/27 02:25:31 cheshire
110 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
112 Revision 1.292 2003/08/21 19:27:36 cheshire
113 <rdar://problem/3387878> Traffic reduction: No need to announce record for longer than TTL
115 Revision 1.291 2003/08/21 18:57:44 cheshire
116 <rdar://problem/3387140> Synchronized queries on the network
118 Revision 1.290 2003/08/21 02:25:23 cheshire
119 Minor changes to comments and debugf() messages
121 Revision 1.289 2003/08/21 02:21:50 cheshire
122 <rdar://problem/3386473> Efficiency: Reduce repeated queries
124 Revision 1.288 2003/08/20 23:39:30 cheshire
125 <rdar://problem/3344098> Review syslog messages, and remove as appropriate
127 Revision 1.287 2003/08/20 20:47:18 cheshire
130 Revision 1.286 2003/08/20 02:18:51 cheshire
131 <rdar://problem/3344098> Cleanup: Review syslog messages
133 Revision 1.285 2003/08/20 01:59:06 cheshire
134 <rdar://problem/3384478> rdatahash and rdnamehash not updated after changing rdata
135 Made new routine SetNewRData() to update rdlength, rdestimate, rdatahash and rdnamehash in one place
137 Revision 1.284 2003/08/19 22:20:00 cheshire
138 <rdar://problem/3376721> Don't use IPv6 on interfaces that have a routable IPv4 address configured
139 More minor refinements
141 Revision 1.283 2003/08/19 22:16:27 cheshire
142 Minor fix: Add missing "mDNS_Unlock(m);" in mDNS_DeregisterInterface() error case.
144 Revision 1.282 2003/08/19 06:48:25 cheshire
145 <rdar://problem/3376552> Guard against excessive record updates
146 Each record starts with 10 UpdateCredits.
147 Every update consumes one UpdateCredit.
148 UpdateCredits are replenished at a rate of one one per minute, up to a maximum of 10.
149 As the number of UpdateCredits declines, the number of announcements is similarly scaled back.
150 When fewer than 5 UpdateCredits remain, the first announcement is also delayed by an increasing amount.
152 Revision 1.281 2003/08/19 04:49:28 cheshire
153 <rdar://problem/3368159> Interaction between v4, v6 and dual-stack hosts not working quite right
154 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.
155 2. When we see the first v4 (or first v6) member of a group, we re-trigger questions and probes on that interface.
156 3. When we see the last v4 (or v6) member of a group go away, we revalidate all the records received on that interface.
158 Revision 1.280 2003/08/19 02:33:36 cheshire
161 Revision 1.279 2003/08/19 02:31:11 cheshire
162 <rdar://problem/3378386> mDNSResponder overenthusiastic with final expiration queries
163 Final expiration queries now only mark the question for sending on the particular interface
164 pertaining to the record that's expiring.
166 Revision 1.278 2003/08/18 22:53:37 cheshire
167 <rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformTimeNow()
169 Revision 1.277 2003/08/18 19:05:44 cheshire
170 <rdar://problem/3382423> UpdateRecord not working right
171 Added "newrdlength" field to hold new length of updated rdata
173 Revision 1.276 2003/08/16 03:39:00 cheshire
174 <rdar://problem/3338440> InterfaceID -1 indicates "local only"
176 Revision 1.275 2003/08/16 02:51:27 cheshire
177 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
178 Don't try to compute namehash etc, until *after* validating the name
180 Revision 1.274 2003/08/16 01:12:40 cheshire
181 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
182 Now that the minimum rdata object size has been reduced to 64 bytes, it is no longer safe to do a
183 simple C structure assignment of a domainname, because that object is defined to be 256 bytes long,
184 and in the process of copying it, the C compiler may run off the end of the rdata object into
185 unmapped memory. All assignments of domainname objects of uncertain size are now replaced with a
186 call to the macro AssignDomainName(), which is careful to copy only as many bytes as are valid.
188 Revision 1.273 2003/08/15 20:16:02 cheshire
189 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
190 We want to avoid touching the rdata pages, so we don't page them in.
191 1. RDLength was stored with the rdata, which meant touching the page just to find the length.
192 Moved this from the RData to the ResourceRecord object.
193 2. To avoid unnecessarily touching the rdata just to compare it,
194 compute a hash of the rdata and store the hash in the ResourceRecord object.
196 Revision 1.272 2003/08/14 19:29:04 cheshire
197 <rdar://problem/3378473> Include cache records in SIGINFO output
198 Moved declarations of DNSTypeName() and GetRRDisplayString to mDNSClientAPI.h so daemon.c can use them
200 Revision 1.271 2003/08/14 02:17:05 cheshire
201 <rdar://problem/3375491> Split generic ResourceRecord type into two separate types: AuthRecord and CacheRecord
203 Revision 1.270 2003/08/13 17:07:28 ksekar
204 Bug #: <rdar://problem/3376458>: Extra RR linked to list even if registration fails - causes crash
205 Added check to result of mDNS_Register() before linking extra record into list.
207 Revision 1.269 2003/08/12 19:56:23 cheshire
210 Revision 1.268 2003/08/12 15:01:10 cheshire
213 Revision 1.267 2003/08/12 14:59:27 cheshire
214 <rdar://problem/3374490> Rate-limiting blocks some legitimate responses
215 When setting LastMCTime also record LastMCInterface. When checking LastMCTime to determine
216 whether to suppress the response, also check LastMCInterface to see if it matches.
218 Revision 1.266 2003/08/12 12:47:16 cheshire
219 In mDNSCoreMachineSleep debugf message, display value of m->timenow
221 Revision 1.265 2003/08/11 20:04:28 cheshire
222 <rdar://problem/3366553> Improve efficiency by restricting cases where we have to walk the entire cache
224 Revision 1.264 2003/08/09 00:55:02 cheshire
225 <rdar://problem/3366553> mDNSResponder is taking 20-30% of the CPU
226 Don't scan the whole cache after every packet.
228 Revision 1.263 2003/08/09 00:35:29 cheshire
229 Moved AnswerNewQuestion() later in the file, in preparation for next checkin
231 Revision 1.262 2003/08/08 19:50:33 cheshire
232 <rdar://problem/3370332> Remove "Cache size now xxx" messages
234 Revision 1.261 2003/08/08 19:18:45 cheshire
235 <rdar://problem/3271219> Only retrigger questions on platforms with the "PhantomInterfaces" bug
237 Revision 1.260 2003/08/08 18:55:48 cheshire
238 <rdar://problem/3370365> Guard against time going backwards
240 Revision 1.259 2003/08/08 18:36:04 cheshire
241 <rdar://problem/3344154> Only need to revalidate on interface removal on platforms that have the PhantomInterfaces bug
243 Revision 1.258 2003/08/08 16:22:05 cheshire
244 <rdar://problem/3335473> Need to check validity of TXT (and other) records
245 Remove unneeded LogMsg
247 Revision 1.257 2003/08/07 01:41:08 cheshire
248 <rdar://problem/3367346> Ignore packets with invalid source address (all zeroes or all ones)
250 Revision 1.256 2003/08/06 23:25:51 cheshire
251 <rdar://problem/3290674> Increase TTL for A/AAAA/SRV from one minute to four
253 Revision 1.255 2003/08/06 23:22:50 cheshire
254 Add symbolic constants: kDefaultTTLforUnique (one minute) and kDefaultTTLforShared (two hours)
256 Revision 1.254 2003/08/06 21:33:39 cheshire
257 Fix compiler warnings on PocketPC 2003 (Windows CE)
259 Revision 1.253 2003/08/06 20:43:57 cheshire
260 <rdar://problem/3335473> Need to check validity of TXT (and other) records
261 Created ValidateDomainName() and ValidateRData(), used by mDNS_Register_internal() and mDNS_Update()
263 Revision 1.252 2003/08/06 20:35:47 cheshire
264 Enhance debugging routine GetRRDisplayString() so it can also be used to display
265 other RDataBody objects, not just the one currently attached the given ResourceRecord
267 Revision 1.251 2003/08/06 19:07:34 cheshire
268 <rdar://problem/3366251> mDNSResponder not inhibiting multicast responses as much as it should
269 Was checking LastAPTime instead of LastMCTime
271 Revision 1.250 2003/08/06 19:01:55 cheshire
274 Revision 1.249 2003/08/06 00:13:28 cheshire
275 Tidy up debugf messages
277 Revision 1.248 2003/08/05 22:20:15 cheshire
278 <rdar://problem/3330324> Need to check IP TTL on responses
280 Revision 1.247 2003/08/05 00:56:39 cheshire
281 <rdar://problem/3357075> mDNSResponder sending additional records, even after precursor record suppressed
283 Revision 1.246 2003/08/04 19:20:49 cheshire
284 Add kDNSQType_ANY to list in DNSTypeName() so it can be displayed in debugging messages
286 Revision 1.245 2003/08/02 01:56:29 cheshire
287 For debugging: log message if we ever get more than one question in a truncated packet
289 Revision 1.244 2003/08/01 23:55:32 cheshire
290 Fix for compiler warnings on Windows, submitted by Bob Bradley
292 Revision 1.243 2003/07/25 02:26:09 cheshire
293 Typo: FIxed missing semicolon
295 Revision 1.242 2003/07/25 01:18:41 cheshire
296 Fix memory leak on shutdown in mDNS_Close() (detected in Windows version)
298 Revision 1.241 2003/07/23 21:03:42 cheshire
299 Only show "Found record..." debugf message in verbose mode
301 Revision 1.240 2003/07/23 21:01:11 cheshire
302 <rdar://problem/3340584> Need Nagle-style algorithm to coalesce multiple packets into one
303 After sending a packet, suppress further sending for the next 100ms.
305 Revision 1.239 2003/07/22 01:30:05 cheshire
306 <rdar://problem/3329099> Don't try to add the same question to the duplicate-questions list more than once
308 Revision 1.238 2003/07/22 00:10:20 cheshire
309 <rdar://problem/3337355> ConvertDomainLabelToCString() needs to escape escape characters
311 Revision 1.237 2003/07/19 03:23:13 cheshire
312 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
314 Revision 1.236 2003/07/19 03:04:55 cheshire
315 Fix warnings; some debugf message improvements
317 Revision 1.235 2003/07/19 00:03:32 cheshire
318 <rdar://problem/3160248> ScheduleNextTask needs to be smarter after a no-op packet is received
319 ScheduleNextTask is quite an expensive operation.
320 We don't need to do all that work after receiving a no-op packet that didn't change our state.
322 Revision 1.234 2003/07/18 23:52:11 cheshire
323 To improve consistency of field naming, global search-and-replace:
324 NextProbeTime -> NextScheduledProbe
325 NextResponseTime -> NextScheduledResponse
327 Revision 1.233 2003/07/18 00:29:59 cheshire
328 <rdar://problem/3268878> Remove mDNSResponder version from packet header and use HINFO record instead
330 Revision 1.232 2003/07/18 00:11:38 cheshire
331 Add extra case to switch statements to handle HINFO data for Get, Put and Display
332 (In all but GetRDLength(), this is is just a fall-through to kDNSType_TXT)
334 Revision 1.231 2003/07/18 00:06:37 cheshire
335 To make code a little easier to read in GetRDLength(), search-and-replace "rr->rdata->u." with "rd->"
337 Revision 1.230 2003/07/17 18:16:54 cheshire
338 <rdar://problem/3319418> Rendezvous services always in a state of flux
339 In preparation for working on this, made some debugf messages a little more selective
341 Revision 1.229 2003/07/17 17:35:04 cheshire
342 <rdar://problem/3325583> Rate-limit responses, to guard against packet flooding
344 Revision 1.228 2003/07/16 20:50:27 cheshire
345 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
347 Revision 1.227 2003/07/16 05:01:36 cheshire
348 Add fields 'LargeAnswers' and 'ExpectUnicastResponse' in preparation for
349 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
351 Revision 1.226 2003/07/16 04:51:44 cheshire
352 Fix use of constant 'mDNSPlatformOneSecond' where it should have said 'InitialQuestionInterval'
354 Revision 1.225 2003/07/16 04:46:41 cheshire
355 Minor wording cleanup: The correct DNS term is "response", not "reply"
357 Revision 1.224 2003/07/16 04:39:02 cheshire
358 Textual cleanup (no change to functionality):
359 Construct "c >= 'A' && c <= 'Z'" appears in too many places; replaced with macro "mDNSIsUpperCase(c)"
361 Revision 1.223 2003/07/16 00:09:22 cheshire
362 Textual cleanup (no change to functionality):
363 Construct "((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)" appears in too many places;
364 replace with macro "TicksTTL(rr)"
365 Construct "rr->TimeRcvd + ((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)"
366 replaced with macro "RRExpireTime(rr)"
368 Revision 1.222 2003/07/15 23:40:46 cheshire
369 Function rename: UpdateDupSuppressInfo() is more accurately called ExpireDupSuppressInfo()
371 Revision 1.221 2003/07/15 22:17:56 cheshire
372 <rdar://problem/3328394> mDNSResponder is not being efficient when doing certain queries
374 Revision 1.220 2003/07/15 02:12:51 cheshire
375 Slight tidy-up of debugf messages and comments
377 Revision 1.219 2003/07/15 01:55:12 cheshire
378 <rdar://problem/3315777> Need to implement service registration with subtypes
380 Revision 1.218 2003/07/14 16:26:06 cheshire
381 <rdar://problem/3324795> Duplicate query suppression not working right
382 Refinement: Don't record DS information for a question in the first quarter second
383 right after we send it -- in the case where a question happens to be accelerated by
384 the maximum allowed amount, we don't want it to then be suppressed because the previous
385 time *we* sent that question falls (just) within the valid duplicate suppression window.
387 Revision 1.217 2003/07/13 04:43:53 cheshire
388 <rdar://problem/3325169> Services on multiple interfaces not always resolving
389 Minor refinement: No need to make address query broader than the original SRV query that provoked it
391 Revision 1.216 2003/07/13 03:13:17 cheshire
392 <rdar://problem/3325169> Services on multiple interfaces not always resolving
393 If we get an identical SRV on a second interface, convert address queries to non-specific
395 Revision 1.215 2003/07/13 02:28:00 cheshire
396 <rdar://problem/3325166> SendResponses didn't all its responses
397 Delete all references to RRInterfaceActive -- it's now superfluous
399 Revision 1.214 2003/07/13 01:47:53 cheshire
400 Fix one error and one warning in the Windows build
402 Revision 1.213 2003/07/12 04:25:48 cheshire
403 Fix minor signed/unsigned warnings
405 Revision 1.212 2003/07/12 01:59:11 cheshire
406 Minor changes to debugf messages
408 Revision 1.211 2003/07/12 01:47:01 cheshire
409 <rdar://problem/3324495> After name conflict, appended number should be higher than previous number
411 Revision 1.210 2003/07/12 01:43:28 cheshire
412 <rdar://problem/3324795> Duplicate query suppression not working right
413 The correct cutoff time for duplicate query suppression is timenow less one-half the query interval.
414 The code was incorrectly using the last query time plus one-half the query interval.
415 This was only correct in the case where query acceleration was not in effect.
417 Revision 1.209 2003/07/12 01:27:50 cheshire
418 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
419 Fix missing "-1" in RemoveLabelSuffix()
421 Revision 1.208 2003/07/11 01:32:38 cheshire
422 Syntactic cleanup (no change to funcationality): Now that we only have one host name,
423 rename field "hostname1" to "hostname", and field "RR_A1" to "RR_A".
425 Revision 1.207 2003/07/11 01:28:00 cheshire
426 <rdar://problem/3161289> No more local.arpa
428 Revision 1.206 2003/07/11 00:45:02 cheshire
429 <rdar://problem/3321909> Client should get callback confirming successful host name registration
431 Revision 1.205 2003/07/11 00:40:18 cheshire
432 Tidy up debug message in HostNameCallback()
434 Revision 1.204 2003/07/11 00:20:32 cheshire
435 <rdar://problem/3320087> mDNSResponder should log a message after 16 unsuccessful probes
437 Revision 1.203 2003/07/10 23:53:41 cheshire
438 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
440 Revision 1.202 2003/07/04 02:23:20 cheshire
441 <rdar://problem/3311955> Responder too aggressive at flushing stale data
442 Changed mDNSResponder to require four unanswered queries before purging a record, instead of two.
444 Revision 1.201 2003/07/04 01:09:41 cheshire
445 <rdar://problem/3315775> Need to implement subtype queries
446 Modified ConstructServiceName() to allow three-part service types
448 Revision 1.200 2003/07/03 23:55:26 cheshire
449 Minor change to wording of syslog warning messages
451 Revision 1.199 2003/07/03 23:51:13 cheshire
452 <rdar://problem/3315652>: Lots of "have given xxx answers" syslog warnings
453 Added more detailed debugging information
455 Revision 1.198 2003/07/03 22:19:30 cheshire
456 <rdar://problem/3314346> Bug fix in 3274153 breaks TiVo
457 Make exception to allow _tivo_servemedia._tcp.
459 Revision 1.197 2003/07/02 22:33:05 cheshire
460 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
462 When cache is exhausted, verify that rrcache_totalused == rrcache_size and report if not
463 Allow cache to grow to 512 records before considering it a potential denial-of-service attack
465 Revision 1.196 2003/07/02 21:19:45 cheshire
466 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
468 Revision 1.195 2003/07/02 19:56:58 cheshire
469 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
470 Minor refinement: m->rrcache_active was not being decremented when
471 an active record was deleted because its TTL expired
473 Revision 1.194 2003/07/02 18:47:40 cheshire
474 Minor wording change to log messages
476 Revision 1.193 2003/07/02 02:44:13 cheshire
477 Fix warning in non-debug build
479 Revision 1.192 2003/07/02 02:41:23 cheshire
480 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
482 Revision 1.191 2003/07/02 02:30:51 cheshire
483 HashSlot() returns an array index. It can't be negative; hence it should not be signed.
485 Revision 1.190 2003/06/27 00:03:05 vlubet
486 <rdar://problem/3304625> Merge of build failure fix for gcc 3.3
488 Revision 1.189 2003/06/11 19:24:03 cheshire
489 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
490 Slight refinement to previous checkin
492 Revision 1.188 2003/06/10 20:33:28 cheshire
493 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
495 Revision 1.187 2003/06/10 04:30:44 cheshire
496 <rdar://problem/3286234> Need to re-probe/re-announce on configuration change
497 Only interface-specific records were re-probing and re-announcing, not non-specific records.
499 Revision 1.186 2003/06/10 04:24:39 cheshire
500 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
501 Some additional refinements:
502 Don't try to do this for unicast-response queries
503 better tracking of Qs and KAs in multi-packet KA lists
505 Revision 1.185 2003/06/10 03:52:49 cheshire
506 Update comments and debug messages
508 Revision 1.184 2003/06/10 02:26:39 cheshire
509 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
510 Make mDNS_Reconfirm() call mDNS_Lock(), like the other API routines
512 Revision 1.183 2003/06/09 18:53:13 cheshire
513 Simplify some debugf() statements (replaced block of 25 lines with 2 lines)
515 Revision 1.182 2003/06/09 18:38:42 cheshire
516 <rdar://problem/3285082> Need to be more tolerant when there are mDNS proxies on the network
517 Only issue a correction if the TTL in the proxy packet is less than half the correct value.
519 Revision 1.181 2003/06/07 06:45:05 cheshire
520 <rdar://problem/3283666> No need for multiple machines to all be sending the same queries
522 Revision 1.180 2003/06/07 06:31:07 cheshire
523 Create little four-line helper function "FindIdenticalRecordInCache()"
525 Revision 1.179 2003/06/07 06:28:13 cheshire
526 For clarity, change name of "DNSQuestion q" to "DNSQuestion pktq"
528 Revision 1.178 2003/06/07 06:25:12 cheshire
531 Revision 1.177 2003/06/07 04:50:53 cheshire
532 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
534 Revision 1.176 2003/06/07 04:33:26 cheshire
535 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
536 Minor change: Increment/decrement logic for q->CurrentAnswers should be in
537 CacheRecordAdd() and CacheRecordRmv(), not AnswerQuestionWithResourceRecord()
539 Revision 1.175 2003/06/07 04:11:52 cheshire
540 Minor changes to comments and debug messages
542 Revision 1.174 2003/06/07 01:46:38 cheshire
543 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
545 Revision 1.173 2003/06/07 01:22:13 cheshire
546 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
548 Revision 1.172 2003/06/07 00:59:42 cheshire
549 <rdar://problem/3283454> Need some randomness to spread queries on the network
551 Revision 1.171 2003/06/06 21:41:10 cheshire
552 For consistency, mDNS_StopQuery() should return an mStatus result, just like all the other mDNSCore routines
554 Revision 1.170 2003/06/06 21:38:55 cheshire
555 Renamed 'NewData' as 'FreshData' (The data may not be new data, just a refresh of data that we
556 already had in our cache. This refreshes our TTL on the data, but the data itself stays the same.)
558 Revision 1.169 2003/06/06 21:35:55 cheshire
559 Fix mis-named macro: GetRRHostNameTarget is really GetRRDomainNameTarget
560 (the target is a domain name, but not necessarily a host name)
562 Revision 1.168 2003/06/06 21:33:31 cheshire
563 Instead of using (mDNSPlatformOneSecond/2) all over the place, define a constant "InitialQuestionInterval"
565 Revision 1.167 2003/06/06 21:30:42 cheshire
566 <rdar://problem/3282962> Don't delay queries for shared record types
568 Revision 1.166 2003/06/06 17:20:14 cheshire
569 For clarity, rename question fields name/rrtype/rrclass as qname/qtype/qclass
570 (Global search-and-replace; no functional change to code execution.)
572 Revision 1.165 2003/06/04 02:53:21 cheshire
573 Add some "#pragma warning" lines so it compiles clean on Microsoft compilers
575 Revision 1.164 2003/06/04 01:25:33 cheshire
576 <rdar://problem/3274950> Cannot perform multi-packet known-answer suppression messages
577 Display time interval between first and subsequent queries
579 Revision 1.163 2003/06/03 19:58:14 cheshire
580 <rdar://problem/3277665> mDNS_DeregisterService() fixes:
581 When forcibly deregistering after a conflict, ensure we don't send an incorrect goodbye packet.
582 Guard against a couple of possible mDNS_DeregisterService() race conditions.
584 Revision 1.162 2003/06/03 19:30:39 cheshire
585 Minor addition refinements for
586 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
588 Revision 1.161 2003/06/03 18:29:03 cheshire
589 Minor changes to comments and debugf() messages
591 Revision 1.160 2003/06/03 05:02:16 cheshire
592 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
594 Revision 1.159 2003/06/03 03:31:57 cheshire
595 <rdar://problem/3277033> False self-conflict when there are duplicate registrations on one machine
597 Revision 1.158 2003/06/02 22:57:09 cheshire
598 Minor clarifying changes to comments and log messages;
599 IdenticalResourceRecordAnyInterface() is really more accurately called just IdenticalResourceRecord()
601 Revision 1.157 2003/05/31 00:09:49 cheshire
602 <rdar://problem/3274862> Add ability to discover what services are on a network
604 Revision 1.156 2003/05/30 23:56:49 cheshire
605 <rdar://problem/3274847> Crash after error in mDNS_RegisterService()
606 Need to set "sr->Extras = mDNSNULL" before returning
608 Revision 1.155 2003/05/30 23:48:00 cheshire
609 <rdar://problem/3274832> Announcements not properly grouped
610 Due to inconsistent setting of rr->LastAPTime at different places in the
611 code, announcements were not properly grouped into a single packet.
612 Fixed by creating a single routine called InitializeLastAPTime().
614 Revision 1.154 2003/05/30 23:38:14 cheshire
615 <rdar://problem/3274814> Fix error in IPv6 reverse-mapping PTR records
616 Wrote buffer[32] where it should have said buffer[64]
618 Revision 1.153 2003/05/30 19:10:56 cheshire
619 <rdar://problem/3274153> ConstructServiceName needs to be more restrictive
621 Revision 1.152 2003/05/29 22:39:16 cheshire
622 <rdar://problem/3273209> Don't truncate strings in the middle of a UTF-8 character
624 Revision 1.151 2003/05/29 06:35:42 cheshire
625 <rdar://problem/3272221> mDNSCoreReceiveResponse() purging wrong record
627 Revision 1.150 2003/05/29 06:25:45 cheshire
628 <rdar://problem/3272218> Need to call CheckCacheExpiration() *before* AnswerNewQuestion()
630 Revision 1.149 2003/05/29 06:18:39 cheshire
631 <rdar://problem/3272217> Split AnswerLocalQuestions into CacheRecordAdd and CacheRecordRmv
633 Revision 1.148 2003/05/29 06:11:34 cheshire
634 <rdar://problem/3272214> Report if there appear to be too many "Resolve" callbacks
636 Revision 1.147 2003/05/29 06:01:18 cheshire
637 Change some debugf() calls to LogMsg() calls to help with debugging
639 Revision 1.146 2003/05/28 21:00:44 cheshire
640 Re-enable "immediate answer burst" debugf message
642 Revision 1.145 2003/05/28 20:57:44 cheshire
643 <rdar://problem/3271550> mDNSResponder reports "Cannot perform multi-packet
644 known-answer suppression ..." This is a known issue caused by a bug in the OS X 10.2
645 version of mDNSResponder, so for now we should suppress this warning message.
647 Revision 1.144 2003/05/28 18:05:12 cheshire
648 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
649 Fix silly mistake: old logic allowed "TDP" and "UCP" as valid names
651 Revision 1.143 2003/05/28 04:31:29 cheshire
652 <rdar://problem/3270733> mDNSResponder not sending probes at the prescribed time
654 Revision 1.142 2003/05/28 03:13:07 cheshire
655 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
656 Require that the transport protocol be _udp or _tcp
658 Revision 1.141 2003/05/28 02:19:12 cheshire
659 <rdar://problem/3270634> Misleading messages generated by iChat
660 Better fix: Only generate the log message for queries where the TC bit is set.
662 Revision 1.140 2003/05/28 01:55:24 cheshire
663 Minor change to log messages
665 Revision 1.139 2003/05/28 01:52:51 cheshire
666 <rdar://problem/3270634> Misleading messages generated by iChat
668 Revision 1.138 2003/05/27 22:35:00 cheshire
669 <rdar://problem/3270277> mDNS_RegisterInterface needs to retrigger questions
671 Revision 1.137 2003/05/27 20:04:33 cheshire
672 <rdar://problem/3269900> mDNSResponder crash in mDNS_vsnprintf()
674 Revision 1.136 2003/05/27 18:50:07 cheshire
675 <rdar://problem/3269768> mDNS_StartResolveService doesn't inform client of port number changes
677 Revision 1.135 2003/05/26 04:57:28 cheshire
678 <rdar://problem/3268953> Delay queries when there are already answers in the cache
680 Revision 1.134 2003/05/26 04:54:54 cheshire
681 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
682 Accidentally deleted '%' case from the switch statement
684 Revision 1.133 2003/05/26 03:21:27 cheshire
685 Tidy up address structure naming:
686 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
687 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
688 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
690 Revision 1.132 2003/05/26 03:01:26 cheshire
691 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
693 Revision 1.131 2003/05/26 00:42:05 cheshire
694 <rdar://problem/3268876> Temporarily include mDNSResponder version in packets
696 Revision 1.130 2003/05/24 16:39:48 cheshire
697 <rdar://problem/3268631> SendResponses also needs to handle multihoming better
699 Revision 1.129 2003/05/23 02:15:37 cheshire
700 Fixed misleading use of the term "duplicate suppression" where it should have
701 said "known answer suppression". (Duplicate answer suppression is something
702 different, and duplicate question suppression is yet another thing, so the use
703 of the completely vague term "duplicate suppression" was particularly bad.)
705 Revision 1.128 2003/05/23 01:55:13 cheshire
706 <rdar://problem/3267127> After name change, mDNSResponder needs to re-probe for name uniqueness
708 Revision 1.127 2003/05/23 01:02:15 ksekar
709 Bug #: <rdar://problem/3032577>: mDNSResponder needs to include unique id in default name
711 Revision 1.126 2003/05/22 02:29:22 cheshire
712 <rdar://problem/2984918> SendQueries needs to handle multihoming better
713 Complete rewrite of SendQueries. Works much better now :-)
715 Revision 1.125 2003/05/22 01:50:45 cheshire
716 Fix warnings, and improve log messages
718 Revision 1.124 2003/05/22 01:41:50 cheshire
719 DiscardDeregistrations doesn't need InterfaceID parameter
721 Revision 1.123 2003/05/22 01:38:55 cheshire
722 Change bracketing of #pragma mark
724 Revision 1.122 2003/05/21 19:59:04 cheshire
725 <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
726 Minor refinements; make sure we don't truncate in the middle of a multi-byte UTF-8 character
728 Revision 1.121 2003/05/21 17:54:07 ksekar
729 Bug #: <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
730 New rename behavior - domain name "foo" becomes "foo--2" on conflict, richtext name becomes "foo (2)"
732 Revision 1.120 2003/05/19 22:14:14 ksekar
733 <rdar://problem/3162914> mDNS probe denials/conflicts not detected unless conflict is of the same type
735 Revision 1.119 2003/05/16 01:34:10 cheshire
738 Revision 1.118 2003/05/14 18:48:40 cheshire
739 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
740 More minor refinements:
741 CFSocket.c needs to do *all* its mDNS_DeregisterInterface calls before freeing memory
742 mDNS_DeregisterInterface revalidates cache record when *any* representative of an interface goes away
744 Revision 1.117 2003/05/14 07:08:36 cheshire
745 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
746 Previously, when there was any network configuration change, mDNSResponder
747 would tear down the entire list of active interfaces and start again.
748 That was very disruptive, and caused the entire cache to be flushed,
749 and caused lots of extra network traffic. Now it only removes interfaces
750 that have really gone, and only adds new ones that weren't there before.
752 Revision 1.116 2003/05/14 06:51:56 cheshire
753 <rdar://problem/3027144> Rendezvous doesn't refresh server info if changed during sleep
755 Revision 1.115 2003/05/14 06:44:31 cheshire
756 Improve debugging message
758 Revision 1.114 2003/05/07 01:47:03 cheshire
759 <rdar://problem/3250330> Also protect against NULL domainlabels
761 Revision 1.113 2003/05/07 00:28:18 cheshire
762 <rdar://problem/3250330> Need to make mDNSResponder more defensive against bad clients
764 Revision 1.112 2003/05/06 00:00:46 cheshire
765 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
767 Revision 1.111 2003/05/05 23:42:08 cheshire
768 <rdar://problem/3245631> Resolves never succeed
769 Was setting "rr->LastAPTime = timenow - rr->LastAPTime"
770 instead of "rr->LastAPTime = timenow - rr->ThisAPInterval"
772 Revision 1.110 2003/04/30 21:09:59 cheshire
773 <rdar://problem/3244727> mDNS_vsnprintf needs to be more defensive against invalid domain names
775 Revision 1.109 2003/04/26 02:41:56 cheshire
776 <rdar://problem/3241281> Change timenow from a local variable to a structure member
778 Revision 1.108 2003/04/25 01:45:56 cheshire
779 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
781 Revision 1.107 2003/04/25 00:41:31 cheshire
782 <rdar://problem/3239912> Create single routine PurgeCacheResourceRecord(), to avoid bugs in future
784 Revision 1.106 2003/04/22 03:14:45 cheshire
785 <rdar://problem/3232229> Include Include instrumented mDNSResponder in panther now
787 Revision 1.105 2003/04/22 01:07:43 cheshire
788 <rdar://problem/3176248> DNSServiceRegistrationUpdateRecord should support a default ttl
789 If TTL parameter is zero, leave record TTL unchanged
791 Revision 1.104 2003/04/21 19:15:52 cheshire
792 Fix some compiler warnings
794 Revision 1.103 2003/04/19 02:26:35 cheshire
795 Bug #: <rdar://problem/3233804> Incorrect goodbye packet after conflict
797 Revision 1.102 2003/04/17 03:06:28 cheshire
798 Bug #: <rdar://problem/3231321> No need to query again when a service goes away
799 Set UnansweredQueries to 2 when receiving a "goodbye" packet
801 Revision 1.101 2003/04/15 20:58:31 jgraessl
803 Added a hash to lookup records in the cache.
805 Revision 1.100 2003/04/15 18:53:14 cheshire
806 Bug #: <rdar://problem/3229064> Bug in ScheduleNextTask
807 mDNS.c 1.94 incorrectly combined two "if" statements into one.
809 Revision 1.99 2003/04/15 18:09:13 jgraessl
811 Reviewed by: Stuart Cheshire
812 Added code to keep track of when the next cache item will expire so we can
813 call TidyRRCache only when necessary.
815 Revision 1.98 2003/04/03 03:43:55 cheshire
816 <rdar://problem/3216837> Off-by-one error in probe rate limiting
818 Revision 1.97 2003/04/02 01:48:17 cheshire
819 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
820 Additional fix pointed out by Josh:
821 Also set ProbeFailTime when incrementing NumFailedProbes when resetting a record back to probing state
823 Revision 1.96 2003/04/01 23:58:55 cheshire
824 Minor comment changes
826 Revision 1.95 2003/04/01 23:46:05 cheshire
827 <rdar://problem/3214832> mDNSResponder can get stuck in infinite loop after many location cycles
828 mDNS_DeregisterInterface() flushes the RR cache by marking all records received on that interface
829 to expire in one second. However, if a mDNS_StartResolveService() call is made in that one-second
830 window, it can get an SRV answer from one of those soon-to-be-deleted records, resulting in
831 FoundServiceInfoSRV() making an interface-specific query on the interface that was just removed.
833 Revision 1.94 2003/03/29 01:55:19 cheshire
834 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
835 Solution: Major cleanup of packet timing and conflict handling rules
837 Revision 1.93 2003/03/28 01:54:36 cheshire
838 Minor tidyup of IPv6 (AAAA) code
840 Revision 1.92 2003/03/27 03:30:55 cheshire
841 <rdar://problem/3210018> Name conflicts not handled properly, resulting in memory corruption, and eventual crash
842 Problem was that HostNameCallback() was calling mDNS_DeregisterInterface(), which is not safe in a callback
844 1. Make mDNS_DeregisterInterface() safe to call from a callback
845 2. Make HostNameCallback() use mDNS_DeadvertiseInterface() instead
846 (it never really needed to deregister the interface at all)
848 Revision 1.91 2003/03/15 04:40:36 cheshire
849 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
851 Revision 1.90 2003/03/14 20:26:37 cheshire
852 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
854 Revision 1.89 2003/03/12 19:57:50 cheshire
855 Fixed typo in debug message
857 Revision 1.88 2003/03/12 00:17:44 cheshire
858 <rdar://problem/3195426> GetFreeCacheRR needs to be more willing to throw away recent records
860 Revision 1.87 2003/03/11 01:27:20 cheshire
861 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
863 Revision 1.86 2003/03/06 20:44:33 cheshire
866 Revision 1.85 2003/03/05 03:38:35 cheshire
867 Bug #: 3185731 Bogus error message in console: died or deallocated, but no record of client can be found!
868 Fixed by leaving client in list after conflict, until client explicitly deallocates
870 Revision 1.84 2003/03/05 01:27:30 cheshire
871 Bug #: 3185482 Different TTL for multicast versus unicast responses
872 When building unicast responses, record TTLs are capped to 10 seconds
874 Revision 1.83 2003/03/04 23:48:52 cheshire
875 Bug #: 3188865 Double probes after wake from sleep
876 Don't reset record type to kDNSRecordTypeUnique if record is DependentOn another
878 Revision 1.82 2003/03/04 23:38:29 cheshire
879 Bug #: 3099194 mDNSResponder needs performance improvements
880 Only set rr->CRActiveQuestion to point to the
881 currently active representative of a question set
883 Revision 1.81 2003/02/21 03:35:34 cheshire
884 Bug #: 3179007 mDNSResponder needs to include AAAA records in additional answer section
886 Revision 1.80 2003/02/21 02:47:53 cheshire
887 Bug #: 3099194 mDNSResponder needs performance improvements
888 Several places in the code were calling CacheRRActive(), which searched the entire
889 question list every time, to see if this cache resource record answers any question.
890 Instead, we now have a field "CRActiveQuestion" in the resource record structure
892 Revision 1.79 2003/02/21 01:54:07 cheshire
893 Bug #: 3099194 mDNSResponder needs performance improvements
894 Switched to using new "mDNS_Execute" model (see "Implementer Notes.txt")
896 Revision 1.78 2003/02/20 06:48:32 cheshire
897 Bug #: 3169535 Xserve RAID needs to do interface-specific registrations
898 Reviewed by: Josh Graessley, Bob Bradley
900 Revision 1.77 2003/01/31 03:35:59 cheshire
901 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
902 When there were *two* active questions in the list, they were incorrectly
903 finding *each other* and *both* being marked as duplicates of another question
905 Revision 1.76 2003/01/29 02:46:37 cheshire
907 A physical interface is identified solely by its InterfaceID (not by IP and type).
908 On a given InterfaceID, mDNSCore may send both v4 and v6 multicasts.
909 In cases where the requested outbound protocol (v4 or v6) is not supported on
910 that InterfaceID, the platform support layer should simply discard that packet.
912 Revision 1.75 2003/01/29 01:47:40 cheshire
913 Rename 'Active' to 'CRActive' or 'InterfaceActive' for improved clarity
915 Revision 1.74 2003/01/28 05:26:25 cheshire
916 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
917 Add 'Active' flag for interfaces
919 Revision 1.73 2003/01/28 03:45:12 cheshire
920 Fixed missing "not" in "!mDNSAddrIsDNSMulticast(dstaddr)"
922 Revision 1.72 2003/01/28 01:49:48 cheshire
923 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
924 FindDuplicateQuestion() was incorrectly finding the question itself in the list,
925 and incorrectly marking it as a duplicate (of itself), so that it became inactive.
927 Revision 1.71 2003/01/28 01:41:44 cheshire
928 Bug #: 3153091 Race condition when network change causes bad stuff
929 When an interface goes away, interface-specific questions on that interface become orphaned.
930 Orphan questions cause HaveQueries to return true, but there's no interface to send them on.
931 Fix: mDNS_DeregisterInterface() now calls DeActivateInterfaceQuestions()
933 Revision 1.70 2003/01/23 19:00:20 cheshire
934 Protect against infinite loops in mDNS_Execute
936 Revision 1.69 2003/01/21 22:56:32 jgraessl
937 Bug #: 3124348 service name changes are not properly handled
938 Submitted by: Stuart Cheshire
939 Reviewed by: Joshua Graessley
940 Applying changes for 3124348 to main branch. 3124348 changes went in to a
943 Revision 1.68 2003/01/17 04:09:27 cheshire
944 Bug #: 3141038 mDNSResponder Resolves are unreliable on multi-homed hosts
946 Revision 1.67 2003/01/17 03:56:45 cheshire
947 Default 24-hour TTL is far too long. Changing to two hours.
949 Revision 1.66 2003/01/13 23:49:41 jgraessl
950 Merged changes for the following fixes in to top of tree:
951 3086540 computer name changes not handled properly
952 3124348 service name changes are not properly handled
953 3124352 announcements sent in pairs, failing chattiness test
955 Revision 1.65 2002/12/23 22:13:28 jgraessl
956 Reviewed by: Stuart Cheshire
957 Initial IPv6 support for mDNSResponder.
959 Revision 1.64 2002/11/26 20:49:06 cheshire
960 Bug #: 3104543 RFC 1123 allows the first character of a name label to be either a letter or a digit
962 Revision 1.63 2002/09/21 20:44:49 zarzycki
965 Revision 1.62 2002/09/20 03:25:37 cheshire
966 Fix some compiler warnings
968 Revision 1.61 2002/09/20 01:05:24 cheshire
969 Don't kill the Extras list in mDNS_DeregisterService()
971 Revision 1.60 2002/09/19 23:47:35 cheshire
972 Added mDNS_RegisterNoSuchService() function for assertion of non-existance
973 of a particular named service
975 Revision 1.59 2002/09/19 21:25:34 cheshire
976 mDNS_snprintf() doesn't need to be in a separate file
978 Revision 1.58 2002/09/19 04:20:43 cheshire
979 Remove high-ascii characters that confuse some systems
981 Revision 1.57 2002/09/17 01:07:08 cheshire
982 Change mDNS_AdvertiseLocalAddresses to be a parameter to mDNS_Init()
984 Revision 1.56 2002/09/16 19:44:17 cheshire
985 Merge in license terms from Quinn's copy, in preparation for Darwin release
988 #define TEST_LOCALONLY_FOR_EVERYTHING 0
990 #include "mDNSClientAPI.h" // Defines the interface provided to the client layer above
991 #include "mDNSPlatformFunctions.h" // Defines the interface required of the supporting layer below
993 // Disable certain benign warnings with Microsoft compilers
994 #if(defined(_MSC_VER))
995 // Disable "conditional expression is constant" warning for debug macros.
996 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
997 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
998 #pragma warning(disable:4127)
1000 // Disable "const object should be initialized"
1001 // We know that static/globals are defined to be zeroed in ANSI C, and to avoid this warning would require some
1002 // *really* ugly chunk of zeroes and curly braces to initialize zeroRR and mDNSprintf_format_default to all zeroes
1003 #pragma warning(disable:4132)
1005 // Disable "assignment within conditional expression".
1006 // Other compilers understand the convention that if you place the assignment expression within an extra pair
1007 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
1008 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
1009 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
1010 #pragma warning(disable:4706)
1013 // ***************************************************************************
1014 #if COMPILER_LIKES_PRAGMA_MARK
1015 #pragma mark - DNS Protocol Constants
1020 kDNSFlag0_QR_Mask
= 0x80, // Query or response?
1021 kDNSFlag0_QR_Query
= 0x00,
1022 kDNSFlag0_QR_Response
= 0x80,
1024 kDNSFlag0_OP_Mask
= 0x78, // Operation type
1025 kDNSFlag0_OP_StdQuery
= 0x00,
1026 kDNSFlag0_OP_Iquery
= 0x08,
1027 kDNSFlag0_OP_Status
= 0x10,
1028 kDNSFlag0_OP_Unused3
= 0x18,
1029 kDNSFlag0_OP_Notify
= 0x20,
1030 kDNSFlag0_OP_Update
= 0x28,
1032 kDNSFlag0_QROP_Mask
= kDNSFlag0_QR_Mask
| kDNSFlag0_OP_Mask
,
1034 kDNSFlag0_AA
= 0x04, // Authoritative Answer?
1035 kDNSFlag0_TC
= 0x02, // Truncated?
1036 kDNSFlag0_RD
= 0x01, // Recursion Desired?
1037 kDNSFlag1_RA
= 0x80, // Recursion Available?
1039 kDNSFlag1_Zero
= 0x40, // Reserved; must be zero
1040 kDNSFlag1_AD
= 0x20, // Authentic Data [RFC 2535]
1041 kDNSFlag1_CD
= 0x10, // Checking Disabled [RFC 2535]
1043 kDNSFlag1_RC
= 0x0F, // Response code
1044 kDNSFlag1_RC_NoErr
= 0x00,
1045 kDNSFlag1_RC_FmtErr
= 0x01,
1046 kDNSFlag1_RC_SrvErr
= 0x02,
1047 kDNSFlag1_RC_NXDomain
= 0x03,
1048 kDNSFlag1_RC_NotImpl
= 0x04,
1049 kDNSFlag1_RC_Refused
= 0x05,
1050 kDNSFlag1_RC_YXDomain
= 0x06,
1051 kDNSFlag1_RC_YXRRSet
= 0x07,
1052 kDNSFlag1_RC_NXRRSet
= 0x08,
1053 kDNSFlag1_RC_NotAuth
= 0x09,
1054 kDNSFlag1_RC_NotZone
= 0x0A
1057 // ***************************************************************************
1058 #if COMPILER_LIKES_PRAGMA_MARK
1060 #pragma mark - Program Constants
1063 mDNSexport
const ResourceRecord zeroRR
;
1064 mDNSexport
const mDNSIPPort zeroIPPort
= { { 0 } };
1065 mDNSexport
const mDNSv4Addr zeroIPAddr
= { { 0 } };
1066 mDNSexport
const mDNSv6Addr zerov6Addr
= { { 0 } };
1067 mDNSexport
const mDNSv4Addr onesIPv4Addr
= { { 255, 255, 255, 255 } };
1068 mDNSexport
const mDNSv6Addr onesIPv6Addr
= { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } };
1069 mDNSlocal
const mDNSAddr zeroAddr
= { mDNSAddrType_None
, {{{ 0 }}} };
1071 mDNSexport
const mDNSInterfaceID mDNSInterface_Any
= { 0 };
1072 mDNSlocal
const mDNSInterfaceID mDNSInterfaceMark
= { (mDNSInterfaceID
)~0 };
1074 #define UnicastDNSPortAsNumber 53
1075 #define MulticastDNSPortAsNumber 5353
1076 mDNSexport
const mDNSIPPort UnicastDNSPort
= { { UnicastDNSPortAsNumber
>> 8, UnicastDNSPortAsNumber
& 0xFF } };
1077 mDNSexport
const mDNSIPPort MulticastDNSPort
= { { MulticastDNSPortAsNumber
>> 8, MulticastDNSPortAsNumber
& 0xFF } };
1078 mDNSexport
const mDNSv4Addr AllDNSAdminGroup
= { { 239, 255, 255, 251 } };
1079 mDNSexport
const mDNSv4Addr AllDNSLinkGroup
= { { 224, 0, 0, 251 } };
1080 mDNSexport
const mDNSv6Addr AllDNSLinkGroupv6
= { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } };
1081 mDNSexport
const mDNSAddr AllDNSLinkGroup_v4
= { mDNSAddrType_IPv4
, { { { 224, 0, 0, 251 } } } };
1082 mDNSexport
const mDNSAddr AllDNSLinkGroup_v6
= { mDNSAddrType_IPv6
, { { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } } } };
1084 static const mDNSOpaque16 zeroID
= { { 0, 0 } };
1085 static const mDNSOpaque16 QueryFlags
= { { kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
, 0 } };
1086 static const mDNSOpaque16 ResponseFlags
= { { kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
| kDNSFlag0_AA
, 0 } };
1087 #define zeroDomainNamePtr ((domainname*)"")
1089 // Any records bigger than this are considered 'large' records
1090 #define SmallRecordLimit 1024
1092 #define kDefaultTTLforUnique 240
1093 #define kDefaultTTLforShared (2*3600)
1095 #define kMaxUpdateCredits 10
1097 static const char *const mDNS_DomainTypeNames
[] =
1099 "_browse._mdns._udp.local.",
1100 "_default._browse._mdns._udp.local.",
1101 "_register._mdns._udp.local.",
1102 "_default._register._mdns._udp.local."
1105 #define AssignDomainName(DST, SRC) mDNSPlatformMemCopy((SRC).c, (DST).c, DomainNameLength(&(SRC)))
1107 // ***************************************************************************
1108 #if COMPILER_LIKES_PRAGMA_MARK
1110 #pragma mark - Specialized mDNS version of vsnprintf
1113 static const struct mDNSprintf_format
1115 unsigned leftJustify
: 1;
1116 unsigned forceSign
: 1;
1117 unsigned zeroPad
: 1;
1118 unsigned havePrecision
: 1;
1122 char sign
; // +, - or space
1123 unsigned int fieldWidth
;
1124 unsigned int precision
;
1125 } mDNSprintf_format_default
;
1127 mDNSexport mDNSu32
mDNS_vsnprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, va_list arg
)
1129 mDNSu32 nwritten
= 0;
1131 buflen
--; // Pre-reserve one space in the buffer for the terminating nul
1133 for (c
= *fmt
; c
!= 0; c
= *++fmt
)
1137 *sbuffer
++ = (char)c
;
1138 if (++nwritten
>= buflen
) goto exit
;
1142 unsigned int i
=0, j
;
1143 // The mDNS Vsprintf Argument Conversion Buffer is used as a temporary holding area for
1144 // generating decimal numbers, hexdecimal numbers, IP addresses, domain name strings, etc.
1145 // The size needs to be enough for a 256-byte domain name plus some error text.
1146 #define mDNS_VACB_Size 300
1147 char mDNS_VACB
[mDNS_VACB_Size
];
1148 #define mDNS_VACB_Lim (&mDNS_VACB[mDNS_VACB_Size])
1149 #define mDNS_VACB_Remain(s) ((mDNSu32)(mDNS_VACB_Lim - s))
1150 char *s
= mDNS_VACB_Lim
, *digits
;
1151 struct mDNSprintf_format F
= mDNSprintf_format_default
;
1153 while (1) // decode flags
1156 if (c
== '-') F
.leftJustify
= 1;
1157 else if (c
== '+') F
.forceSign
= 1;
1158 else if (c
== ' ') F
.sign
= ' ';
1159 else if (c
== '#') F
.altForm
++;
1160 else if (c
== '0') F
.zeroPad
= 1;
1164 if (c
== '*') // decode field width
1166 int f
= va_arg(arg
, int);
1167 if (f
< 0) { f
= -f
; F
.leftJustify
= 1; }
1168 F
.fieldWidth
= (unsigned int)f
;
1173 for (; c
>= '0' && c
<= '9'; c
= *++fmt
)
1174 F
.fieldWidth
= (10 * F
.fieldWidth
) + (c
- '0');
1177 if (c
== '.') // decode precision
1179 if ((c
= *++fmt
) == '*')
1180 { F
.precision
= va_arg(arg
, unsigned int); c
= *++fmt
; }
1181 else for (; c
>= '0' && c
<= '9'; c
= *++fmt
)
1182 F
.precision
= (10 * F
.precision
) + (c
- '0');
1183 F
.havePrecision
= 1;
1186 if (F
.leftJustify
) F
.zeroPad
= 0;
1189 switch (c
) // perform appropriate conversion
1192 case 'h' : F
.hSize
= 1; c
= *++fmt
; goto conv
;
1193 case 'l' : // fall through
1194 case 'L' : F
.lSize
= 1; c
= *++fmt
; goto conv
;
1196 case 'i' : if (F
.lSize
) n
= (unsigned long)va_arg(arg
, long);
1197 else n
= (unsigned long)va_arg(arg
, int);
1198 if (F
.hSize
) n
= (short) n
;
1199 if ((long) n
< 0) { n
= (unsigned long)-(long)n
; F
.sign
= '-'; }
1200 else if (F
.forceSign
) F
.sign
= '+';
1202 case 'u' : if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1203 else n
= va_arg(arg
, unsigned int);
1204 if (F
.hSize
) n
= (unsigned short) n
;
1207 decimal
: if (!F
.havePrecision
)
1211 F
.precision
= F
.fieldWidth
;
1212 if (F
.sign
) --F
.precision
;
1214 if (F
.precision
< 1) F
.precision
= 1;
1216 if (F
.precision
> mDNS_VACB_Size
- 1)
1217 F
.precision
= mDNS_VACB_Size
- 1;
1218 for (i
= 0; n
; n
/= 10, i
++) *--s
= (char)(n
% 10 + '0');
1219 for (; i
< F
.precision
; i
++) *--s
= '0';
1220 if (F
.sign
) { *--s
= F
.sign
; i
++; }
1223 case 'o' : if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1224 else n
= va_arg(arg
, unsigned int);
1225 if (F
.hSize
) n
= (unsigned short) n
;
1226 if (!F
.havePrecision
)
1228 if (F
.zeroPad
) F
.precision
= F
.fieldWidth
;
1229 if (F
.precision
< 1) F
.precision
= 1;
1231 if (F
.precision
> mDNS_VACB_Size
- 1)
1232 F
.precision
= mDNS_VACB_Size
- 1;
1233 for (i
= 0; n
; n
/= 8, i
++) *--s
= (char)(n
% 8 + '0');
1234 if (F
.altForm
&& i
&& *s
!= '0') { *--s
= '0'; i
++; }
1235 for (; i
< F
.precision
; i
++) *--s
= '0';
1239 unsigned char *a
= va_arg(arg
, unsigned char *);
1240 if (!a
) { static char emsg
[] = "<<NULL>>"; s
= emsg
; i
= sizeof(emsg
)-1; }
1243 unsigned short *w
= (unsigned short *)a
;
1244 s
= mDNS_VACB
; // Adjust s to point to the start of the buffer, not the end
1247 mDNSAddr
*ip
= (mDNSAddr
*)a
;
1248 a
= (unsigned char *)&ip
->ip
.v4
;
1249 w
= (unsigned short *)&ip
->ip
.v6
;
1252 case mDNSAddrType_IPv4
: F
.precision
= 4; break;
1253 case mDNSAddrType_IPv6
: F
.precision
= 16; break;
1254 default: F
.precision
= 0; break;
1257 switch (F
.precision
)
1259 case 4: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%d.%d.%d.%d",
1260 a
[0], a
[1], a
[2], a
[3]); break;
1261 case 6: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%02X:%02X:%02X:%02X:%02X:%02X",
1262 a
[0], a
[1], a
[2], a
[3], a
[4], a
[5]); break;
1263 case 16: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X",
1264 w
[0], w
[1], w
[2], w
[3], w
[4], w
[5], w
[6], w
[7]); break;
1265 default: i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "%s", "<< ERROR: Must specify address size "
1266 "(i.e. %.4a=IPv4, %.6a=Ethernet, %.16a=IPv6) >>"); break;
1272 case 'p' : F
.havePrecision
= F
.lSize
= 1;
1274 case 'X' : digits
= "0123456789ABCDEF";
1276 case 'x' : digits
= "0123456789abcdef";
1277 hexadecimal
:if (F
.lSize
) n
= va_arg(arg
, unsigned long);
1278 else n
= va_arg(arg
, unsigned int);
1279 if (F
.hSize
) n
= (unsigned short) n
;
1280 if (!F
.havePrecision
)
1284 F
.precision
= F
.fieldWidth
;
1285 if (F
.altForm
) F
.precision
-= 2;
1287 if (F
.precision
< 1) F
.precision
= 1;
1289 if (F
.precision
> mDNS_VACB_Size
- 1)
1290 F
.precision
= mDNS_VACB_Size
- 1;
1291 for (i
= 0; n
; n
/= 16, i
++) *--s
= digits
[n
% 16];
1292 for (; i
< F
.precision
; i
++) *--s
= '0';
1293 if (F
.altForm
) { *--s
= (char)c
; *--s
= '0'; i
+= 2; }
1296 case 'c' : *--s
= (char)va_arg(arg
, int); i
= 1; break;
1298 case 's' : s
= va_arg(arg
, char *);
1299 if (!s
) { static char emsg
[] = "<<NULL>>"; s
= emsg
; i
= sizeof(emsg
)-1; }
1300 else switch (F
.altForm
)
1302 case 0: { char *a
=s
; i
=0; while(*a
++) i
++; break; } // C string
1303 case 1: i
= (unsigned char) *s
++; break; // Pascal string
1304 case 2: { // DNS label-sequence name
1305 unsigned char *a
= (unsigned char *)s
;
1306 s
= mDNS_VACB
; // Adjust s to point to the start of the buffer, not the end
1307 if (*a
== 0) *s
++ = '.'; // Special case for root DNS name
1310 if (*a
> 63) { s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "<<INVALID LABEL LENGTH %u>>", *a
); break; }
1311 if (s
+ *a
>= &mDNS_VACB
[254]) { s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "<<NAME TOO LONG>>"); break; }
1312 s
+= mDNS_snprintf(s
, mDNS_VACB_Remain(s
), "%#s.", a
);
1315 i
= (mDNSu32
)(s
- mDNS_VACB
);
1316 s
= mDNS_VACB
; // Reset s back to the start of the buffer
1320 if (F
.havePrecision
&& i
> F
.precision
) // Make sure we don't truncate in the middle of a UTF-8 character
1321 { i
= F
.precision
; while (i
>0 && (s
[i
] & 0xC0) == 0x80) i
--; }
1324 case 'n' : s
= va_arg(arg
, char *);
1325 if (F
.hSize
) * (short *) s
= (short)nwritten
;
1326 else if (F
.lSize
) * (long *) s
= (long)nwritten
;
1327 else * (int *) s
= (int)nwritten
;
1330 default: s
= mDNS_VACB
;
1331 i
= mDNS_snprintf(mDNS_VACB
, sizeof(mDNS_VACB
), "<<UNKNOWN FORMAT CONVERSION CODE %%%c>>", c
);
1333 case '%' : *sbuffer
++ = (char)c
;
1334 if (++nwritten
>= buflen
) goto exit
;
1338 if (i
< F
.fieldWidth
&& !F
.leftJustify
) // Pad on the left
1341 if (++nwritten
>= buflen
) goto exit
;
1342 } while (i
< --F
.fieldWidth
);
1344 if (i
> buflen
- nwritten
) // Make sure we don't truncate in the middle of a UTF-8 character
1345 { i
= buflen
- nwritten
; while (i
>0 && (s
[i
] & 0xC0) == 0x80) i
--; }
1346 for (j
=0; j
<i
; j
++) *sbuffer
++ = *s
++; // Write the converted result
1348 if (nwritten
>= buflen
) goto exit
;
1350 for (; i
< F
.fieldWidth
; i
++) // Pad on the right
1353 if (++nwritten
>= buflen
) goto exit
;
1362 mDNSexport mDNSu32
mDNS_snprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, ...)
1368 length
= mDNS_vsnprintf(sbuffer
, buflen
, fmt
, ptr
);
1374 // ***************************************************************************
1375 #if COMPILER_LIKES_PRAGMA_MARK
1377 #pragma mark - General Utility Functions
1380 mDNSexport
char *DNSTypeName(mDNSu16 rrtype
)
1384 case kDNSType_A
: return("Addr");
1385 case kDNSType_CNAME
:return("CNAME");
1386 case kDNSType_NULL
: return("NULL");
1387 case kDNSType_PTR
: return("PTR");
1388 case kDNSType_HINFO
:return("HINFO");
1389 case kDNSType_TXT
: return("TXT");
1390 case kDNSType_AAAA
: return("AAAA");
1391 case kDNSType_SRV
: return("SRV");
1392 case kDNSQType_ANY
: return("ANY");
1394 static char buffer
[16];
1395 mDNS_snprintf(buffer
, sizeof(buffer
), "(%d)", rrtype
);
1401 mDNSexport
char *GetRRDisplayString_rdb(mDNS
*const m
, const ResourceRecord
*rr
, RDataBody
*rd
)
1403 char *ptr
= m
->MsgBuffer
;
1404 mDNSu32 length
= mDNS_snprintf(m
->MsgBuffer
, 79, "%4d %##s %s ", rr
->rdlength
, rr
->name
.c
, DNSTypeName(rr
->rrtype
));
1407 case kDNSType_A
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%.4a", &rd
->ip
); break;
1408 case kDNSType_CNAME
:// Same as PTR
1409 case kDNSType_PTR
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%##s", &rd
->name
); break;
1410 case kDNSType_HINFO
:// Display this the same as TXT (just show first string)
1411 case kDNSType_TXT
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%#s", rd
->txt
.c
); break;
1412 case kDNSType_AAAA
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%.16a", &rd
->ipv6
); break;
1413 case kDNSType_SRV
: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "%##s", &rd
->srv
.target
); break;
1414 default: mDNS_snprintf(m
->MsgBuffer
+length
, 79-length
, "RDLen %d: %s",
1415 rr
->rdlength
, rd
->data
); break;
1417 for (ptr
= m
->MsgBuffer
; *ptr
; ptr
++) if (*ptr
< ' ') *ptr
='.';
1418 return(m
->MsgBuffer
);
1421 mDNSlocal mDNSu32
mDNSRandom(mDNSu32 max
)
1423 static mDNSu32 seed
= 0;
1426 if (!seed
) seed
= (mDNSu32
)mDNSPlatformTimeNow();
1427 while (mask
< max
) mask
= (mask
<< 1) | 1;
1428 do seed
= seed
* 21 + 1; while ((seed
& mask
) > max
);
1429 return (seed
& mask
);
1432 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
1433 #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])
1435 #define mDNSIPv4AddressIsZero(A) mDNSSameIPv4Address((A), zeroIPAddr)
1436 #define mDNSIPv6AddressIsZero(A) mDNSSameIPv6Address((A), zerov6Addr)
1438 #define mDNSIPv4AddressIsOnes(A) mDNSSameIPv4Address((A), onesIPv4Addr)
1439 #define mDNSIPv6AddressIsOnes(A) mDNSSameIPv6Address((A), onesIPv6Addr)
1441 #define mDNSAddressIsZero(X) ( \
1442 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4)) || \
1443 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6)) )
1445 #define mDNSAddressIsOnes(X) ( \
1446 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4)) || \
1447 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6)) )
1449 #define mDNSAddressIsValid(X) ( \
1450 ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
1451 ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
1453 mDNSexport mDNSBool
mDNSSameAddress(const mDNSAddr
*ip1
, const mDNSAddr
*ip2
)
1455 if (ip1
->type
== ip2
->type
)
1459 case mDNSAddrType_IPv4
: return(mDNSBool
)(mDNSSameIPv4Address(ip1
->ip
.v4
, ip2
->ip
.v4
));
1460 case mDNSAddrType_IPv6
: return(mDNSBool
)(mDNSSameIPv6Address(ip1
->ip
.v6
, ip2
->ip
.v6
));
1466 mDNSlocal mDNSBool
mDNSAddrIsDNSMulticast(const mDNSAddr
*ip
)
1470 case mDNSAddrType_IPv4
: return(mDNSBool
)(ip
->ip
.v4
.NotAnInteger
== AllDNSLinkGroup
.NotAnInteger
);
1471 case mDNSAddrType_IPv6
: return(mDNSBool
)(ip
->ip
.v6
.l
[0] == AllDNSLinkGroupv6
.l
[0] &&
1472 ip
->ip
.v6
.l
[1] == AllDNSLinkGroupv6
.l
[1] &&
1473 ip
->ip
.v6
.l
[2] == AllDNSLinkGroupv6
.l
[2] &&
1474 ip
->ip
.v6
.l
[3] == AllDNSLinkGroupv6
.l
[3] );
1475 default: return(mDNSfalse
);
1479 mDNSlocal
const NetworkInterfaceInfo
*GetFirstActiveInterface(const NetworkInterfaceInfo
*intf
)
1481 while (intf
&& !intf
->InterfaceActive
) intf
= intf
->next
;
1485 mDNSlocal mDNSInterfaceID
GetNextActiveInterfaceID(const NetworkInterfaceInfo
*intf
)
1487 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
1488 if (next
) return(next
->InterfaceID
); else return(mDNSNULL
);
1491 #define InitialQuestionInterval (mDNSPlatformOneSecond/2)
1492 #define ActiveQuestion(Q) ((Q)->ThisQInterval > 0 && !(Q)->DuplicateOf)
1493 #define TimeToSendThisQuestion(Q,time) (ActiveQuestion(Q) && (time) - ((Q)->LastQTime + (Q)->ThisQInterval) >= 0)
1495 mDNSlocal
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
1497 if (ActiveQuestion(q
))
1498 if (m
->NextScheduledQuery
- (q
->LastQTime
+ q
->ThisQInterval
) > 0)
1499 m
->NextScheduledQuery
= (q
->LastQTime
+ q
->ThisQInterval
);
1502 // ***************************************************************************
1503 #if COMPILER_LIKES_PRAGMA_MARK
1505 #pragma mark - Domain Name Utility Functions
1508 #define mdnsIsDigit(X) ((X) >= '0' && (X) <= '9')
1509 #define mDNSIsUpperCase(X) ((X) >= 'A' && (X) <= 'Z')
1510 #define mDNSIsLowerCase(X) ((X) >= 'a' && (X) <= 'z')
1511 #define mdnsIsLetter(X) (mDNSIsUpperCase(X) || mDNSIsLowerCase(X))
1513 mDNSexport mDNSBool
SameDomainLabel(const mDNSu8
*a
, const mDNSu8
*b
)
1516 const int len
= *a
++;
1518 if (len
> MAX_DOMAIN_LABEL
)
1519 { debugf("Malformed label (too long)"); return(mDNSfalse
); }
1521 if (len
!= *b
++) return(mDNSfalse
);
1522 for (i
=0; i
<len
; i
++)
1526 if (mDNSIsUpperCase(ac
)) ac
+= 'a' - 'A';
1527 if (mDNSIsUpperCase(bc
)) bc
+= 'a' - 'A';
1528 if (ac
!= bc
) return(mDNSfalse
);
1533 mDNSexport mDNSBool
SameDomainName(const domainname
*const d1
, const domainname
*const d2
)
1535 const mDNSu8
* a
= d1
->c
;
1536 const mDNSu8
* b
= d2
->c
;
1537 const mDNSu8
*const max
= d1
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
1541 if (a
+ 1 + *a
>= max
)
1542 { debugf("Malformed domain name (more than 255 characters)"); return(mDNSfalse
); }
1543 if (!SameDomainLabel(a
, b
)) return(mDNSfalse
);
1551 // Returns length of a domain name INCLUDING the byte for the final null label
1552 // i.e. for the root label "." it returns one
1553 // For the FQDN "com." it returns 5 (length byte, three data bytes, final zero)
1554 // Legal results are 1 (just root label) to 255 (MAX_DOMAIN_NAME)
1555 // If the given domainname is invalid, result is 256
1556 mDNSexport mDNSu16
DomainNameLength(const domainname
*const name
)
1558 const mDNSu8
*src
= name
->c
;
1561 if (*src
> MAX_DOMAIN_LABEL
) return(MAX_DOMAIN_NAME
+1);
1563 if (src
- name
->c
>= MAX_DOMAIN_NAME
) return(MAX_DOMAIN_NAME
+1);
1565 return((mDNSu16
)(src
- name
->c
+ 1));
1568 // CompressedDomainNameLength returns the length of a domain name INCLUDING the byte
1569 // for the final null label i.e. for the root label "." it returns one.
1570 // E.g. for the FQDN "foo.com." it returns 9
1571 // (length, three data bytes, length, three more data bytes, final zero).
1572 // In the case where a parent domain name is provided, and the given name is a child
1573 // of that parent, CompressedDomainNameLength returns the length of the prefix portion
1574 // of the child name, plus TWO bytes for the compression pointer.
1575 // E.g. for the name "foo.com." with parent "com.", it returns 6
1576 // (length, three data bytes, two-byte compression pointer).
1577 mDNSlocal mDNSu16
CompressedDomainNameLength(const domainname
*const name
, const domainname
*parent
)
1579 const mDNSu8
*src
= name
->c
;
1580 if (parent
&& parent
->c
[0] == 0) parent
= mDNSNULL
;
1583 if (*src
> MAX_DOMAIN_LABEL
) return(MAX_DOMAIN_NAME
+1);
1584 if (parent
&& SameDomainName((domainname
*)src
, parent
)) return((mDNSu16
)(src
- name
->c
+ 2));
1586 if (src
- name
->c
>= MAX_DOMAIN_NAME
) return(MAX_DOMAIN_NAME
+1);
1588 return((mDNSu16
)(src
- name
->c
+ 1));
1591 // AppendLiteralLabelString appends a single label to an existing (possibly empty) domainname.
1592 // The C string contains the label as-is, with no escaping, etc.
1593 // Any dots in the name are literal dots, not label separators
1594 // If successful, AppendLiteralLabelString returns a pointer to the next unused byte
1595 // in the domainname bufer (i.e., the next byte after the terminating zero).
1596 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1597 // AppendLiteralLabelString returns mDNSNULL.
1598 mDNSexport mDNSu8
*AppendLiteralLabelString(domainname
*const name
, const char *cstr
)
1600 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1601 const mDNSu8
*const lim1
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1602 const mDNSu8
*const lim2
= ptr
+ 1 + MAX_DOMAIN_LABEL
;
1603 const mDNSu8
*const lim
= (lim1
< lim2
) ? lim1
: lim2
;
1604 mDNSu8
*lengthbyte
= ptr
++; // Record where the length is going to go
1606 while (*cstr
&& ptr
< lim
) *ptr
++ = (mDNSu8
)*cstr
++; // Copy the data
1607 *lengthbyte
= (mDNSu8
)(ptr
- lengthbyte
- 1); // Fill in the length byte
1608 *ptr
++ = 0; // Put the null root label on the end
1609 if (*cstr
) return(mDNSNULL
); // Failure: We didn't successfully consume all input
1610 else return(ptr
); // Success: return new value of ptr
1613 // AppendDNSNameString appends zero or more labels to an existing (possibly empty) domainname.
1614 // The C string is in conventional DNS syntax:
1615 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1616 // If successful, AppendDNSNameString returns a pointer to the next unused byte
1617 // in the domainname bufer (i.e., the next byte after the terminating zero).
1618 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1619 // AppendDNSNameString returns mDNSNULL.
1620 mDNSexport mDNSu8
*AppendDNSNameString(domainname
*const name
, const char *cstr
)
1622 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1623 const mDNSu8
*const lim
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1624 while (*cstr
&& ptr
< lim
) // While more characters, and space to put them...
1626 mDNSu8
*lengthbyte
= ptr
++; // Record where the length is going to go
1627 while (*cstr
&& *cstr
!= '.' && ptr
< lim
) // While we have characters in the label...
1629 mDNSu8 c
= (mDNSu8
)*cstr
++; // Read the character
1630 if (c
== '\\') // If escape character, check next character
1632 if (*cstr
== '\\' || *cstr
== '.') // If a second escape, or a dot,
1633 c
= (mDNSu8
)*cstr
++; // just use the second character
1634 else if (mdnsIsDigit(cstr
[0]) && mdnsIsDigit(cstr
[1]) && mdnsIsDigit(cstr
[2]))
1635 { // else, if three decimal digits,
1636 int v0
= cstr
[0] - '0'; // then interpret as three-digit decimal
1637 int v1
= cstr
[1] - '0';
1638 int v2
= cstr
[2] - '0';
1639 int val
= v0
* 100 + v1
* 10 + v2
;
1640 if (val
<= 255) { c
= (mDNSu8
)val
; cstr
+= 3; } // If valid value, use it
1643 *ptr
++ = c
; // Write the character
1645 if (*cstr
) cstr
++; // Skip over the trailing dot (if present)
1646 if (ptr
- lengthbyte
- 1 > MAX_DOMAIN_LABEL
) // If illegal label, abort
1648 *lengthbyte
= (mDNSu8
)(ptr
- lengthbyte
- 1); // Fill in the length byte
1651 *ptr
++ = 0; // Put the null root label on the end
1652 if (*cstr
) return(mDNSNULL
); // Failure: We didn't successfully consume all input
1653 else return(ptr
); // Success: return new value of ptr
1656 // AppendDomainLabel appends a single label to a name.
1657 // If successful, AppendDomainLabel returns a pointer to the next unused byte
1658 // in the domainname bufer (i.e., the next byte after the terminating zero).
1659 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1660 // AppendDomainLabel returns mDNSNULL.
1661 mDNSexport mDNSu8
*AppendDomainLabel(domainname
*const name
, const domainlabel
*const label
)
1664 mDNSu8
*ptr
= name
->c
+ DomainNameLength(name
) - 1;
1666 // Check label is legal
1667 if (label
->c
[0] > MAX_DOMAIN_LABEL
) return(mDNSNULL
);
1669 // Check that ptr + length byte + data bytes + final zero does not exceed our limit
1670 if (ptr
+ 1 + label
->c
[0] + 1 > name
->c
+ MAX_DOMAIN_NAME
) return(mDNSNULL
);
1672 for (i
=0; i
<=label
->c
[0]; i
++) *ptr
++ = label
->c
[i
]; // Copy the label data
1673 *ptr
++ = 0; // Put the null root label on the end
1677 mDNSexport mDNSu8
*AppendDomainName(domainname
*const name
, const domainname
*const append
)
1679 mDNSu8
* ptr
= name
->c
+ DomainNameLength(name
) - 1; // Find end of current name
1680 const mDNSu8
*const lim
= name
->c
+ MAX_DOMAIN_NAME
- 1; // Limit of how much we can add (not counting final zero)
1681 const mDNSu8
* src
= append
->c
;
1685 if (ptr
+ 1 + src
[0] > lim
) return(mDNSNULL
);
1686 for (i
=0; i
<=src
[0]; i
++) *ptr
++ = src
[i
];
1687 *ptr
= 0; // Put the null root label on the end
1693 // MakeDomainLabelFromLiteralString makes a single domain label from a single literal C string (with no escaping).
1694 // If successful, MakeDomainLabelFromLiteralString returns mDNStrue.
1695 // If unable to convert the whole string to a legal domain label (i.e. because length is more than 63 bytes) then
1696 // MakeDomainLabelFromLiteralString makes a legal domain label from the first 63 bytes of the string and returns mDNSfalse.
1697 // In some cases silently truncated oversized names to 63 bytes is acceptable, so the return result may be ignored.
1698 // In other cases silent truncation may not be acceptable, so in those cases the calling function needs to check the return result.
1699 mDNSexport mDNSBool
MakeDomainLabelFromLiteralString(domainlabel
*const label
, const char *cstr
)
1701 mDNSu8
* ptr
= label
->c
+ 1; // Where we're putting it
1702 const mDNSu8
*const limit
= label
->c
+ 1 + MAX_DOMAIN_LABEL
; // The maximum we can put
1703 while (*cstr
&& ptr
< limit
) *ptr
++ = (mDNSu8
)*cstr
++; // Copy the label
1704 label
->c
[0] = (mDNSu8
)(ptr
- label
->c
- 1); // Set the length byte
1705 return(*cstr
== 0); // Return mDNStrue if we successfully consumed all input
1708 // MakeDomainNameFromDNSNameString makes a native DNS-format domainname from a C string.
1709 // The C string is in conventional DNS syntax:
1710 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1711 // If successful, MakeDomainNameFromDNSNameString returns a pointer to the next unused byte
1712 // in the domainname bufer (i.e., the next byte after the terminating zero).
1713 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1714 // MakeDomainNameFromDNSNameString returns mDNSNULL.
1715 mDNSexport mDNSu8
*MakeDomainNameFromDNSNameString(domainname
*const name
, const char *cstr
)
1717 name
->c
[0] = 0; // Make an empty domain name
1718 return(AppendDNSNameString(name
, cstr
)); // And then add this string to it
1721 mDNSexport
char *ConvertDomainLabelToCString_withescape(const domainlabel
*const label
, char *ptr
, char esc
)
1723 const mDNSu8
* src
= label
->c
; // Domain label we're reading
1724 const mDNSu8 len
= *src
++; // Read length of this (non-null) label
1725 const mDNSu8
*const end
= src
+ len
; // Work out where the label ends
1726 if (len
> MAX_DOMAIN_LABEL
) return(mDNSNULL
); // If illegal label, abort
1727 while (src
< end
) // While we have characters in the label
1732 if (c
== '.' || c
== esc
) // If character is a dot or the escape character
1733 *ptr
++ = esc
; // Output escape character
1734 else if (c
<= ' ') // If non-printing ascii,
1735 { // Output decimal escape sequence
1737 *ptr
++ = (char) ('0' + (c
/ 100) );
1738 *ptr
++ = (char) ('0' + (c
/ 10) % 10);
1739 c
= (mDNSu8
)('0' + (c
) % 10);
1742 *ptr
++ = (char)c
; // Copy the character
1744 *ptr
= 0; // Null-terminate the string
1745 return(ptr
); // and return
1748 // Note, to guarantee that there will be no possible overrun, cstr must be at least 1005 bytes
1749 // The longest legal domain name is 255 bytes, in the form of three 64-byte labels, one 62-byte label,
1750 // and the null root label.
1751 // If every label character has to be escaped as a four-byte escape sequence, the maximum textual
1752 // ascii display of this is 63*4 + 63*4 + 63*4 + 61*4 = 1000 label characters,
1753 // plus four dots and the null at the end of the C string = 1005
1754 mDNSexport
char *ConvertDomainNameToCString_withescape(const domainname
*const name
, char *ptr
, char esc
)
1756 const mDNSu8
*src
= name
->c
; // Domain name we're reading
1757 const mDNSu8
*const max
= name
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
1759 if (*src
== 0) *ptr
++ = '.'; // Special case: For root, just write a dot
1761 while (*src
) // While more characters in the domain name
1763 if (src
+ 1 + *src
>= max
) return(mDNSNULL
);
1764 ptr
= ConvertDomainLabelToCString_withescape((const domainlabel
*)src
, ptr
, esc
);
1765 if (!ptr
) return(mDNSNULL
);
1767 *ptr
++ = '.'; // Write the dot after the label
1770 *ptr
++ = 0; // Null-terminate the string
1771 return(ptr
); // and return
1775 // Host names must start with a letter, end with a letter or digit,
1776 // and have as interior characters only letters, digits, and hyphen.
1777 // This was subsequently modified in RFC 1123 to allow the first character to be either a letter or a digit
1778 #define mdnsValidHostChar(X, notfirst, notlast) (mdnsIsLetter(X) || mdnsIsDigit(X) || ((notfirst) && (notlast) && (X) == '-') )
1780 mDNSexport
void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name
[], domainlabel
*const hostlabel
)
1782 const mDNSu8
* src
= &UTF8Name
[1];
1783 const mDNSu8
*const end
= &UTF8Name
[1] + UTF8Name
[0];
1784 mDNSu8
* ptr
= &hostlabel
->c
[1];
1785 const mDNSu8
*const lim
= &hostlabel
->c
[1] + MAX_DOMAIN_LABEL
;
1788 // Delete apostrophes from source name
1789 if (src
[0] == '\'') { src
++; continue; } // Standard straight single quote
1790 if (src
+ 2 < end
&& src
[0] == 0xE2 && src
[1] == 0x80 && src
[2] == 0x99)
1791 { src
+= 3; continue; } // Unicode curly apostrophe
1794 if (mdnsValidHostChar(*src
, (ptr
> &hostlabel
->c
[1]), (src
< end
-1))) *ptr
++ = *src
;
1795 else if (ptr
> &hostlabel
->c
[1] && ptr
[-1] != '-') *ptr
++ = '-';
1799 while (ptr
> &hostlabel
->c
[1] && ptr
[-1] == '-') ptr
--; // Truncate trailing '-' marks
1800 hostlabel
->c
[0] = (mDNSu8
)(ptr
- &hostlabel
->c
[1]);
1803 mDNSexport mDNSu8
*ConstructServiceName(domainname
*const fqdn
,
1804 const domainlabel
*name
, const domainname
*type
, const domainname
*const domain
)
1807 mDNSu8
*dst
= fqdn
->c
;
1809 const char *errormsg
;
1811 // In the case where there is no name (and ONLY in that case),
1812 // a single-label subtype is allowed as the first label of a three-part "type"
1815 const mDNSu8
*s2
= type
->c
+ 1 + type
->c
[0];
1816 if (type
->c
[0] > 0 && type
->c
[0] < 0x40 &&
1817 s2
[0] > 0 && s2
[0] < 0x40 &&
1818 s2
[1+s2
[0]] > 0 && s2
[1+s2
[0]] < 0x40)
1820 name
= (domainlabel
*)type
;
1821 type
= (domainname
*)s2
;
1825 if (name
&& name
->c
[0])
1827 src
= name
->c
; // Put the service name into the domain name
1829 if (len
>= 0x40) { errormsg
="Service instance name too long"; goto fail
; }
1830 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1833 name
= (domainlabel
*)""; // Set this up to be non-null, to avoid errors if we have to call LogMsg() below
1835 src
= type
->c
; // Put the service type into the domain name
1837 if (len
< 2 || len
>= 0x40) { errormsg
="Invalid service application protocol name"; goto fail
; }
1838 if (src
[1] != '_') { errormsg
="Service application protocol name must begin with underscore"; goto fail
; }
1839 for (i
=2; i
<=len
; i
++)
1840 if (!mdnsIsLetter(src
[i
]) && !mdnsIsDigit(src
[i
]) && src
[i
] != '-' && src
[i
] != '_')
1841 { errormsg
="Service application protocol name must contain only letters, digits, and hyphens"; goto fail
; }
1842 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1845 //if (len == 0 || len >= 0x40) { errormsg="Invalid service transport protocol name"; goto fail; }
1846 if (!(len
== 4 && src
[1] == '_' &&
1847 (((src
[2] | 0x20) == 'u' && (src
[3] | 0x20) == 'd') || ((src
[2] | 0x20) == 't' && (src
[3] | 0x20) == 'c')) &&
1848 (src
[4] | 0x20) == 'p'))
1849 { errormsg
="Service transport protocol name must be _udp or _tcp"; goto fail
; }
1850 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1852 if (*src
) { errormsg
="Service type must have only two labels"; goto fail
; }
1855 dst
= AppendDomainName(fqdn
, domain
);
1856 if (!dst
) { errormsg
="Service domain too long"; goto fail
; }
1860 LogMsg("ConstructServiceName: %s: %#s.%##s%##s", errormsg
, name
->c
, type
->c
, domain
->c
);
1864 mDNSexport mDNSBool
DeconstructServiceName(const domainname
*const fqdn
,
1865 domainlabel
*const name
, domainname
*const type
, domainname
*const domain
)
1868 const mDNSu8
*src
= fqdn
->c
;
1869 const mDNSu8
*max
= fqdn
->c
+ MAX_DOMAIN_NAME
;
1872 dst
= name
->c
; // Extract the service name from the domain name
1874 if (len
>= 0x40) { debugf("DeconstructServiceName: service name too long"); return(mDNSfalse
); }
1875 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1877 dst
= type
->c
; // Extract the service type from the domain name
1879 if (len
>= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse
); }
1880 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1883 if (len
>= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse
); }
1884 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1885 *dst
++ = 0; // Put the null root label on the end of the service type
1887 dst
= domain
->c
; // Extract the service domain from the domain name
1892 { debugf("DeconstructServiceName: service domain label too long"); return(mDNSfalse
); }
1893 if (src
+ 1 + len
+ 1 >= max
)
1894 { debugf("DeconstructServiceName: service domain too long"); return(mDNSfalse
); }
1895 for (i
=0; i
<=len
; i
++) *dst
++ = *src
++;
1897 *dst
++ = 0; // Put the null root label on the end
1902 // Returns true if a rich text label ends in " (nnn)", or if an RFC 1034
1903 // name ends in "-nnn", where n is some decimal number.
1904 mDNSlocal mDNSBool
LabelContainsSuffix(const domainlabel
*const name
, const mDNSBool RichText
)
1906 mDNSu16 l
= name
->c
[0];
1910 if (l
< 4) return mDNSfalse
; // Need at least " (2)"
1911 if (name
->c
[l
--] != ')') return mDNSfalse
; // Last char must be ')'
1912 if (!mdnsIsDigit(name
->c
[l
])) return mDNSfalse
; // Preceeded by a digit
1914 while (l
> 2 && mdnsIsDigit(name
->c
[l
])) l
--; // Strip off digits
1915 return (name
->c
[l
] == '(' && name
->c
[l
- 1] == ' ');
1919 if (l
< 2) return mDNSfalse
; // Need at least "-2"
1920 if (!mdnsIsDigit(name
->c
[l
])) return mDNSfalse
; // Last char must be a digit
1922 while (l
> 2 && mdnsIsDigit(name
->c
[l
])) l
--; // Strip off digits
1923 return (name
->c
[l
] == '-');
1927 // removes an auto-generated suffix (appended on a name collision) from a label. caller is
1928 // responsible for ensuring that the label does indeed contain a suffix. returns the number
1929 // from the suffix that was removed.
1930 mDNSlocal mDNSu32
RemoveLabelSuffix(domainlabel
*name
, mDNSBool RichText
)
1932 mDNSu32 val
= 0, multiplier
= 1;
1934 // Chop closing parentheses from RichText suffix
1935 if (RichText
&& name
->c
[0] >= 1 && name
->c
[name
->c
[0]] == ')') name
->c
[0]--;
1937 // Get any existing numerical suffix off the name
1938 while (mdnsIsDigit(name
->c
[name
->c
[0]]))
1939 { val
+= (name
->c
[name
->c
[0]] - '0') * multiplier
; multiplier
*= 10; name
->c
[0]--; }
1941 // Chop opening parentheses or dash from suffix
1944 if (name
->c
[0] >= 2 && name
->c
[name
->c
[0]] == '(' && name
->c
[name
->c
[0]-1] == ' ') name
->c
[0] -= 2;
1948 if (name
->c
[0] >= 1 && name
->c
[name
->c
[0]] == '-') name
->c
[0] -= 1;
1954 // appends a numerical suffix to a label, with the number following a whitespace and enclosed
1955 // in parentheses (rich text) or following two consecutive hyphens (RFC 1034 domain label).
1956 mDNSlocal
void AppendLabelSuffix(domainlabel
*name
, mDNSu32 val
, mDNSBool RichText
)
1958 mDNSu32 divisor
= 1, chars
= 2; // Shortest possible RFC1034 name suffix is 3 characters ("-2")
1959 if (RichText
) chars
= 4; // Shortest possible RichText suffix is 4 characters (" (2)")
1961 // Truncate trailing spaces from RichText names
1962 if (RichText
) while (name
->c
[name
->c
[0]] == ' ') name
->c
[0]--;
1964 while (val
>= divisor
* 10) { divisor
*= 10; chars
++; }
1966 if (name
->c
[0] > (mDNSu8
)(MAX_DOMAIN_LABEL
- chars
))
1968 name
->c
[0] = (mDNSu8
)(MAX_DOMAIN_LABEL
- chars
);
1969 // If the following character is a UTF-8 continuation character,
1970 // we just chopped a multi-byte UTF-8 character in the middle, so strip back to a safe truncation point
1971 while (name
->c
[0] > 0 && (name
->c
[name
->c
[0]+1] & 0xC0) == 0x80) name
->c
[0]--;
1974 if (RichText
) { name
->c
[++name
->c
[0]] = ' '; name
->c
[++name
->c
[0]] = '('; }
1975 else { name
->c
[++name
->c
[0]] = '-'; }
1979 name
->c
[++name
->c
[0]] = (mDNSu8
)('0' + val
/ divisor
);
1984 if (RichText
) name
->c
[++name
->c
[0]] = ')';
1987 mDNSexport
void IncrementLabelSuffix(domainlabel
*name
, mDNSBool RichText
)
1991 if (LabelContainsSuffix(name
, RichText
))
1992 val
= RemoveLabelSuffix(name
, RichText
);
1994 // If no existing suffix, start by renaming "Foo" as "Foo (2)" or "Foo-2" as appropriate.
1995 // If existing suffix in the range 2-9, increment it.
1996 // If we've had ten conflicts already, there are probably too many hosts trying to use the same name,
1997 // so add a random increment to improve the chances of finding an available name next time.
1998 if (val
== 0) val
= 2;
1999 else if (val
< 10) val
++;
2000 else val
+= 1 + mDNSRandom(99);
2002 AppendLabelSuffix(name
, val
, RichText
);
2005 // ***************************************************************************
2006 #if COMPILER_LIKES_PRAGMA_MARK
2008 #pragma mark - Resource Record Utility Functions
2011 #define RRIsAddressType(RR) ((RR)->resrec.rrtype == kDNSType_A || (RR)->resrec.rrtype == kDNSType_AAAA)
2012 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
2014 #define ResourceRecordIsValidAnswer(RR) ( ((RR)-> resrec.RecordType & kDNSRecordTypeActiveMask) && \
2015 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2016 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2017 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
2019 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
2020 (ResourceRecordIsValidAnswer(RR) && \
2021 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
2023 #define RRUniqueOrKnownUnique(RR) ((RR)->RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeKnownUnique))
2025 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
2026 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
2028 // For records that have *never* been announced on the wire, their AnnounceCount will be set to InitialAnnounceCount (10).
2029 // When de-registering these records we do not need to send any goodbye packet because we never announced them in the first
2030 // place. If AnnounceCount is less than InitialAnnounceCount that means we have announced them at least once, so a goodbye
2031 // packet is needed. For this reason, if we ever reset AnnounceCount (e.g. after an interface change) we set it to
2032 // ReannounceCount (9), not InitialAnnounceCount. If we were to reset AnnounceCount back to InitialAnnounceCount that would
2033 // imply that the record had never been announced on the wire (which is false) and if the client were then to immediately
2034 // deregister that record before it had a chance to announce, we'd fail to send its goodbye packet (which would be a bug).
2035 #define InitialAnnounceCount ((mDNSu8)10)
2036 #define ReannounceCount ((mDNSu8)9)
2038 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
2039 // This means that because the announce interval is doubled after sending the first packet, the first
2040 // observed on-the-wire inter-packet interval between announcements is actually one second.
2041 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
2042 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
2043 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
2044 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
2046 #define DefaultAPIntervalForRecordType(X) ((X) & (kDNSRecordTypeAdvisory | kDNSRecordTypeShared ) ? DefaultAnnounceIntervalForTypeShared : \
2047 (X) & (kDNSRecordTypeUnique ) ? DefaultProbeIntervalForTypeUnique : \
2048 (X) & (kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique) ? DefaultAnnounceIntervalForTypeUnique : 0)
2050 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
2051 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
2052 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
2053 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
2055 #define MaxUnansweredQueries 4
2057 mDNSlocal mDNSBool
SameRData(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2059 if (r1
->rrtype
!= r2
->rrtype
) return(mDNSfalse
);
2060 if (r1
->rdlength
!= r2
->rdlength
) return(mDNSfalse
);
2061 if (r1
->rdatahash
!= r2
->rdatahash
) return(mDNSfalse
);
2062 if (r1
->rdnamehash
!= r2
->rdnamehash
) return(mDNSfalse
);
2065 case kDNSType_CNAME
:// Same as PTR
2066 case kDNSType_PTR
: return(SameDomainName(&r1
->rdata
->u
.name
, &r2
->rdata
->u
.name
));
2068 case kDNSType_SRV
: return(mDNSBool
)( r1
->rdata
->u
.srv
.priority
== r2
->rdata
->u
.srv
.priority
&&
2069 r1
->rdata
->u
.srv
.weight
== r2
->rdata
->u
.srv
.weight
&&
2070 r1
->rdata
->u
.srv
.port
.NotAnInteger
== r2
->rdata
->u
.srv
.port
.NotAnInteger
&&
2071 SameDomainName(&r1
->rdata
->u
.srv
.target
, &r2
->rdata
->u
.srv
.target
) );
2073 default: return(mDNSPlatformMemSame(r1
->rdata
->u
.data
, r2
->rdata
->u
.data
, r1
->rdlength
));
2077 mDNSlocal mDNSBool
ResourceRecordAnswersQuestion(const ResourceRecord
*const rr
, const DNSQuestion
*const q
)
2079 if (rr
->InterfaceID
&&
2081 rr
->InterfaceID
!= q
->InterfaceID
) return(mDNSfalse
);
2083 // RR type CNAME matches any query type. QTYPE ANY matches any RR type. QCLASS ANY matches any RR class.
2084 if (rr
->rrtype
!= kDNSType_CNAME
&& rr
->rrtype
!= q
->qtype
&& q
->qtype
!= kDNSQType_ANY
) return(mDNSfalse
);
2085 if ( rr
->rrclass
!= q
->qclass
&& q
->qclass
!= kDNSQClass_ANY
) return(mDNSfalse
);
2086 return(rr
->namehash
== q
->qnamehash
&& SameDomainName(&rr
->name
, &q
->qname
));
2089 mDNSlocal mDNSu32
DomainNameHashValue(const domainname
*const name
)
2094 for (c
= name
->c
; c
[0] != 0 && c
[1] != 0; c
+= 2)
2096 sum
+= ((mDNSIsUpperCase(c
[0]) ? c
[0] + 'a' - 'A' : c
[0]) << 8) |
2097 (mDNSIsUpperCase(c
[1]) ? c
[1] + 'a' - 'A' : c
[1]);
2098 sum
= (sum
<<3) | (sum
>>29);
2100 if (c
[0]) sum
+= ((mDNSIsUpperCase(c
[0]) ? c
[0] + 'a' - 'A' : c
[0]) << 8);
2104 #define HashSlot(X) (DomainNameHashValue(X) % CACHE_HASH_SLOTS)
2106 mDNSlocal mDNSu32
RDataHashValue(mDNSu16
const rdlength
, const RDataBody
*const rdb
)
2110 for (i
=0; i
+1 < rdlength
; i
+=2)
2112 sum
+= (((mDNSu32
)(rdb
->data
[i
])) << 8) | rdb
->data
[i
+1];
2113 sum
= (sum
<<3) | (sum
>>29);
2117 sum
+= ((mDNSu32
)(rdb
->data
[i
])) << 8;
2122 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
2123 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
2124 // TTL and rdata may differ.
2125 // This is used for cache flush management:
2126 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
2127 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
2128 mDNSlocal mDNSBool
SameResourceRecordSignature(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2130 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
2131 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
2132 if (r1
->InterfaceID
&&
2134 r1
->InterfaceID
!= r2
->InterfaceID
) return(mDNSfalse
);
2135 return(mDNSBool
)(r1
->rrtype
== r2
->rrtype
&& r1
->rrclass
== r2
->rrclass
&& r1
->namehash
== r2
->namehash
&& SameDomainName(&r1
->name
, &r2
->name
));
2138 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if the
2139 // authoratative record is in the probing state. Probes are sent with the wildcard type, so a response of
2140 // any type should match, even if it is not the type the client plans to use.
2141 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
2143 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
2144 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
2145 if (pktrr
->resrec
.InterfaceID
&&
2146 authrr
->resrec
.InterfaceID
&&
2147 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
2148 if (authrr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
2149 return(mDNSBool
)(pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&& pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&& SameDomainName(&pktrr
->resrec
.name
, &authrr
->resrec
.name
));
2152 // IdenticalResourceRecord returns true if two resources records have
2153 // the same name, type, class, and identical rdata (InterfaceID and TTL may differ)
2154 mDNSlocal mDNSBool
IdenticalResourceRecord(const ResourceRecord
*const r1
, const ResourceRecord
*const r2
)
2156 if (!r1
) { LogMsg("IdenticalResourceRecord ERROR: r1 is NULL"); return(mDNSfalse
); }
2157 if (!r2
) { LogMsg("IdenticalResourceRecord ERROR: r2 is NULL"); return(mDNSfalse
); }
2158 if (r1
->rrtype
!= r2
->rrtype
|| r1
->rrclass
!= r2
->rrclass
|| r1
->namehash
!= r2
->namehash
|| !SameDomainName(&r1
->name
, &r2
->name
)) return(mDNSfalse
);
2159 return(SameRData(r1
, r2
));
2162 // CacheRecord *ks is the CacheRecord from the known answer list in the query.
2163 // This is the information that the requester believes to be correct.
2164 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
2165 // This is the information that we believe to be correct.
2166 // We've already determined that we plan to give this answer on this interface
2167 // (either the record is non-specific, or it is specific to this interface)
2168 // so now we just need to check the name, type, class, rdata and TTL.
2169 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
2171 // If RR signature is different, or data is different, then don't suppress our answer
2172 if (!IdenticalResourceRecord(&ka
->resrec
,&rr
->resrec
)) return(mDNSfalse
);
2174 // If the requester's indicated TTL is less than half the real TTL,
2175 // we need to give our answer before the requester's copy expires.
2176 // If the requester's indicated TTL is at least half the real TTL,
2177 // then we can suppress our answer this time.
2178 // If the requester's indicated TTL is greater than the TTL we believe,
2179 // then that's okay, and we don't need to do anything about it.
2180 // (If two responders on the network are offering the same information,
2181 // that's okay, and if they are offering the information with different TTLs,
2182 // the one offering the lower TTL should defer to the one offering the higher TTL.)
2183 return(mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
2186 mDNSlocal mDNSu16
GetRDLength(const ResourceRecord
*const rr
, mDNSBool estimate
)
2188 RDataBody
*rd
= &rr
->rdata
->u
;
2189 const domainname
*const name
= estimate
? &rr
->name
: mDNSNULL
;
2192 case kDNSType_A
: return(sizeof(rd
->ip
)); break;
2193 case kDNSType_CNAME
:// Same as PTR
2194 case kDNSType_PTR
: return(CompressedDomainNameLength(&rd
->name
, name
));
2195 case kDNSType_HINFO
:return(mDNSu16
)(2 + (int)rd
->data
[0] + (int)rd
->data
[1 + (int)rd
->data
[0]]);
2196 case kDNSType_NULL
: // Same as TXT -- not self-describing, so have to just trust rdlength
2197 case kDNSType_TXT
: return(rr
->rdlength
); // TXT is not self-describing, so have to just trust rdlength
2198 case kDNSType_AAAA
: return(sizeof(rd
->ipv6
)); break;
2199 case kDNSType_SRV
: return(mDNSu16
)(6 + CompressedDomainNameLength(&rd
->srv
.target
, name
));
2200 default: debugf("Warning! Don't know how to get length of resource type %d", rr
->rrtype
);
2201 return(rr
->rdlength
);
2205 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
2207 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
2209 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
2210 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
2212 else if (rr
->AnnounceCount
&& ResourceRecordIsValidAnswer(rr
))
2214 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
2215 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
2219 #define GetRRDomainNameTarget(RR) ( \
2220 ((RR)->rrtype == kDNSType_CNAME || (RR)->rrtype == kDNSType_PTR) ? &(RR)->rdata->u.name : \
2221 ((RR)->rrtype == kDNSType_SRV ) ? &(RR)->rdata->u.srv.target : mDNSNULL )
2223 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
2225 // To allow us to aggregate probes when a group of services are registered together,
2226 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
2227 // 1/4 second wait; probe
2228 // 1/4 second wait; probe
2229 // 1/4 second wait; probe
2230 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
2232 // If we have no probe suppression time set, or it is in the past, set it now
2233 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
2235 m
->SuppressProbes
= (m
->timenow
+ DefaultProbeIntervalForTypeUnique
) | 1;
2236 // If we already have a probe scheduled to go out sooner, then use that time to get better aggregation
2237 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
2238 m
->SuppressProbes
= m
->NextScheduledProbe
;
2239 // If we already have a query scheduled to go out sooner, then use that time to get better aggregation
2240 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
2241 m
->SuppressProbes
= m
->NextScheduledQuery
;
2244 // We announce to flush stale data from other caches. It is a reasonable assumption that any
2245 // old stale copies will probably have the same TTL we're using, so announcing longer than
2246 // this serves no purpose -- any stale copies of that record will have expired by then anyway.
2247 rr
->AnnounceUntil
= m
->timenow
+ TicksTTL(rr
);
2248 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
2249 // Set LastMCTime to now, to inhibit multicast responses
2250 // (no need to send additional multicast responses when we're announcing anyway)
2251 rr
->LastMCTime
= m
->timenow
;
2252 rr
->LastMCInterface
= mDNSInterfaceMark
;
2254 // If this is a record type that's not going to probe, then delay its first announcement so that
2255 // it will go out synchronized with the first announcement for the other records that *are* probing.
2256 // This is a minor performance tweak that helps keep groups of related records synchronized together.
2257 // The addition of "rr->ThisAPInterval / 2" is to make sure that, in the event that any of the probes are
2258 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
2259 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
2260 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
2261 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
)
2262 rr
->LastAPTime
+= DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
2264 SetNextAnnounceProbeTime(m
, rr
);
2267 mDNSlocal
void SetNewRData(ResourceRecord
*const rr
, RData
*NewRData
, mDNSu16 rdlength
)
2272 rr
->rdata
= NewRData
;
2273 rr
->rdlength
= rdlength
;
2275 // Must not try to get target pointer until after updating rr->rdata
2276 target
= GetRRDomainNameTarget(rr
);
2277 rr
->rdlength
= GetRDLength(rr
, mDNSfalse
);
2278 rr
->rdestimate
= GetRDLength(rr
, mDNStrue
);
2279 rr
->rdatahash
= RDataHashValue(rr
->rdlength
, &rr
->rdata
->u
);
2280 rr
->rdnamehash
= target
? DomainNameHashValue(target
) : 0;
2283 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
2285 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
2287 if (!target
) debugf("SetTargetToHostName: Don't know how to set the target of rrtype %d", rr
->resrec
.rrtype
);
2289 if (target
&& SameDomainName(target
, &m
->hostname
))
2290 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
.c
, target
->c
);
2292 if (target
&& !SameDomainName(target
, &m
->hostname
))
2294 AssignDomainName(*target
, m
->hostname
);
2295 SetNewRData(&rr
->resrec
, mDNSNULL
, 0);
2297 // If we're in the middle of probing this record, we need to start again,
2298 // because changing its rdata may change the outcome of the tie-breaker.
2299 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
2300 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
2302 // If we've announced this record, we really should send a goodbye packet for the old rdata before
2303 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
2304 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
2305 if (rr
->AnnounceCount
< InitialAnnounceCount
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
2306 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
));
2308 if (rr
->AnnounceCount
< ReannounceCount
)
2309 rr
->AnnounceCount
= ReannounceCount
;
2310 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
2311 InitializeLastAPTime(m
,rr
);
2315 mDNSlocal
void CompleteProbing(mDNS
*const m
, AuthRecord
*const rr
)
2317 verbosedebugf("Probing for %##s (%s) complete", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2318 if (!rr
->Acknowledged
&& rr
->RecordCallback
)
2320 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2321 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2322 rr
->Acknowledged
= mDNStrue
;
2323 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2324 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
2325 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2329 #define ValidateDomainName(N) (DomainNameLength(N) <= MAX_DOMAIN_NAME)
2331 mDNSlocal mDNSBool
ValidateRData(const mDNSu16 rrtype
, const mDNSu16 rdlength
, const RData
*const rd
)
2336 case kDNSType_A
: return(rdlength
== sizeof(mDNSv4Addr
));
2338 case kDNSType_NS
: // Same as PTR
2339 case kDNSType_MD
: // Same as PTR
2340 case kDNSType_MF
: // Same as PTR
2341 case kDNSType_CNAME
:// Same as PTR
2342 //case kDNSType_SOA not checked
2343 case kDNSType_MB
: // Same as PTR
2344 case kDNSType_MG
: // Same as PTR
2345 case kDNSType_MR
: // Same as PTR
2346 //case kDNSType_NULL not checked (no specified format, so always valid)
2347 //case kDNSType_WKS not checked
2348 case kDNSType_PTR
: len
= DomainNameLength(&rd
->u
.name
);
2349 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== len
);
2351 case kDNSType_HINFO
:// Same as TXT (roughly)
2352 case kDNSType_MINFO
:// Same as TXT (roughly)
2353 case kDNSType_TXT
: {
2354 const mDNSu8
*ptr
= rd
->u
.txt
.c
;
2355 const mDNSu8
*end
= rd
->u
.txt
.c
+ rdlength
;
2356 while (ptr
< end
) ptr
+= 1 + ptr
[0];
2357 return (ptr
== end
);
2360 case kDNSType_AAAA
: return(rdlength
== sizeof(mDNSv6Addr
));
2362 case kDNSType_MX
: len
= DomainNameLength(&rd
->u
.mx
.exchange
);
2363 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== 2+len
);
2365 case kDNSType_SRV
: len
= DomainNameLength(&rd
->u
.srv
.target
);
2366 return(len
<= MAX_DOMAIN_NAME
&& rdlength
== 6+len
);
2368 default: return(mDNStrue
); // Allow all other types without checking
2372 // Two records qualify to be local duplicates if the RecordTypes are the same, or if one is Unique and the other Verified
2373 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified))
2374 #define RecordIsLocalDuplicate(A,B) ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
2376 mDNSlocal mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
2378 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
2380 AuthRecord
**p
= &m
->ResourceRecords
;
2381 AuthRecord
**d
= &m
->DuplicateRecords
;
2382 AuthRecord
**l
= &m
->LocalOnlyRecords
;
2384 #if TEST_LOCALONLY_FOR_EVERYTHING
2385 rr
->resrec
.InterfaceID
= (mDNSInterfaceID
)~0;
2388 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2389 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
2390 while (*l
&& *l
!= rr
) l
=&(*l
)->next
;
2393 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
));
2394 return(mStatus_AlreadyRegistered
);
2397 if (rr
->DependentOn
)
2399 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
2400 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
2403 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
2404 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2405 return(mStatus_Invalid
);
2407 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
)))
2409 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
2410 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
2411 return(mStatus_Invalid
);
2415 // If this resource record is referencing a specific interface, make sure it exists
2416 if (rr
->resrec
.InterfaceID
&& rr
->resrec
.InterfaceID
!= ((mDNSInterfaceID
)~0))
2418 NetworkInterfaceInfo
*intf
;
2419 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
2420 if (intf
->InterfaceID
== rr
->resrec
.InterfaceID
) break;
2423 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr
->resrec
.InterfaceID
);
2424 return(mStatus_BadReferenceErr
);
2428 rr
->next
= mDNSNULL
;
2430 // Field Group 1: Persistent metadata for Authoritative Records
2431 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2432 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2433 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2434 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2435 // rr->Callback = already set in mDNS_SetupResourceRecord
2436 // rr->Context = already set in mDNS_SetupResourceRecord
2437 // rr->RecordType = already set in mDNS_SetupResourceRecord
2438 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
2440 // Field Group 2: Transient state for Authoritative Records
2441 rr
->Acknowledged
= mDNSfalse
;
2442 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
2443 rr
->AnnounceCount
= InitialAnnounceCount
;
2444 rr
->IncludeInProbe
= mDNSfalse
;
2445 rr
->ImmedAnswer
= mDNSNULL
;
2446 rr
->ImmedAdditional
= mDNSNULL
;
2447 rr
->SendRNow
= mDNSNULL
;
2448 rr
->v4Requester
= zeroIPAddr
;
2449 rr
->v6Requester
= zerov6Addr
;
2450 rr
->NextResponse
= mDNSNULL
;
2451 rr
->NR_AnswerTo
= mDNSNULL
;
2452 rr
->NR_AdditionalTo
= mDNSNULL
;
2453 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
2454 InitializeLastAPTime(m
, rr
);
2455 // rr->AnnounceUntil = Set for us in InitializeLastAPTime()
2456 // rr->LastAPTime = Set for us in InitializeLastAPTime()
2457 // rr->LastMCTime = Set for us in InitializeLastAPTime()
2458 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
2459 rr
->NewRData
= mDNSNULL
;
2460 rr
->newrdlength
= 0;
2461 rr
->UpdateCallback
= mDNSNULL
;
2462 rr
->UpdateCredits
= kMaxUpdateCredits
;
2463 rr
->NextUpdateCredit
= 0;
2464 rr
->UpdateBlocked
= 0;
2466 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
2467 // rr->resrec.name.c = MUST be set by client
2468 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
2469 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
2470 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
2471 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
2475 if (target
) target
->c
[0] = 0;
2476 SetTargetToHostName(m
, rr
); // This also sets rdlength and rdestimate for us
2480 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
2481 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
2484 if (!ValidateDomainName(&rr
->resrec
.name
))
2485 { LogMsg("Attempt to register record with invalid name: %s", GetRRDisplayString(m
, rr
)); return(mStatus_Invalid
); }
2487 // Don't do this until *after* we've set rr->resrec.rdlength
2488 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
2489 { LogMsg("Attempt to register record with invalid rdata: %s", GetRRDisplayString(m
, rr
)); return(mStatus_Invalid
); }
2491 rr
->resrec
.namehash
= DomainNameHashValue(&rr
->resrec
.name
);
2492 rr
->resrec
.rdatahash
= RDataHashValue(rr
->resrec
.rdlength
, &rr
->resrec
.rdata
->u
);
2493 rr
->resrec
.rdnamehash
= target
? DomainNameHashValue(target
) : 0;
2495 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0))
2497 debugf("Adding %p %##s (%s) to LocalOnly list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2499 if (!m
->NewLocalOnlyRecords
) m
->NewLocalOnlyRecords
= rr
;
2500 // If this is supposed to be unique, make sure we don't have any name conflicts
2501 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2503 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
2504 for (r
= m
->LocalOnlyRecords
; r
; r
=r
->next
)
2506 const AuthRecord
*s2
= r
->RRSet
? r
->RRSet
: r
;
2507 if (s1
!= s2
&& SameResourceRecordSignature(&r
->resrec
, &rr
->resrec
) && !SameRData(&r
->resrec
, &rr
->resrec
))
2510 if (r
) // If we found a conflict, set DiscardLocalOnlyRecords so we'll deliver the callback
2512 debugf("Name conflict %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2513 m
->DiscardLocalOnlyRecords
= mDNStrue
;
2515 else // else no conflict, so set ProbeCount to zero and update RecordType as appropriate
2518 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
2524 // Now that's we've finished building our new record, make sure it's not identical to one we already have
2525 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (RecordIsLocalDuplicate(r
, rr
)) break;
2529 debugf("Adding %p %##s (%s) to duplicate list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2531 // If the previous copy of this record is already verified unique,
2532 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
2533 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
2534 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
2535 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
2540 debugf("Adding %p %##s (%s) to active record list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2544 return(mStatus_NoError
);
2547 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
2549 m
->ProbeFailTime
= m
->timenow
;
2550 m
->NumFailedProbes
++;
2551 // If we've had ten or more probe failures, rate-limit to one every five seconds
2552 // The result is ORed with 1 to make sure SuppressProbes is not accidentally set to zero
2553 if (m
->NumFailedProbes
>= 10) m
->SuppressProbes
= (m
->timenow
+ mDNSPlatformOneSecond
* 5) | 1;
2554 if (m
->NumFailedProbes
>= 16)
2555 LogMsg("Name in use: %##s (%s); need to choose another (%d)",
2556 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), m
->NumFailedProbes
);
2559 // mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
2560 // mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
2561 // mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
2562 typedef enum { mDNS_Dereg_normal
, mDNS_Dereg_conflict
, mDNS_Dereg_repeat
} mDNS_Dereg_type
;
2564 // NOTE: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
2565 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2566 mDNSlocal mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
2568 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
2569 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
2570 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0)) p
= &m
->LocalOnlyRecords
;
2571 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2575 // We found our record on the main list. See if there are any duplicates that need special handling.
2576 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
2578 AuthRecord
*r2
= m
->DuplicateRecords
;
2581 if (RecordIsLocalDuplicate(r2
, rr
)) { mDNS_Deregister_internal(m
, r2
, drt
); r2
= m
->DuplicateRecords
; }
2587 // Before we delete the record (and potentially send a goodbye packet)
2588 // first see if we have a record on the duplicate list ready to take over from it.
2589 AuthRecord
**d
= &m
->DuplicateRecords
;
2590 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
2593 AuthRecord
*dup
= *d
;
2594 debugf("Duplicate record %p taking over from %p %##s (%s)", dup
, rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2595 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
2596 dup
->next
= rr
->next
; // And then...
2597 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
2598 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
2599 dup
->ProbeCount
= rr
->ProbeCount
;
2600 dup
->AnnounceCount
= rr
->AnnounceCount
;
2601 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
2602 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
2603 dup
->v4Requester
= rr
->v4Requester
;
2604 dup
->v6Requester
= rr
->v6Requester
;
2605 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
2606 dup
->AnnounceUntil
= rr
->AnnounceUntil
;
2607 dup
->LastAPTime
= rr
->LastAPTime
;
2608 dup
->LastMCTime
= rr
->LastMCTime
;
2609 dup
->LastMCInterface
= rr
->LastMCInterface
;
2610 if (RecordType
== kDNSRecordTypeShared
) rr
->AnnounceCount
= InitialAnnounceCount
;
2616 // We didn't find our record on the main list; try the DuplicateRecords list instead.
2617 p
= &m
->DuplicateRecords
;
2618 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2619 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2620 if (*p
&& RecordType
== kDNSRecordTypeShared
) rr
->AnnounceCount
= InitialAnnounceCount
;
2621 if (*p
) debugf("DNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2626 // No need to log an error message if we already know this is a potentially repeated deregistration
2627 if (drt
!= mDNS_Dereg_repeat
)
2628 debugf("mDNS_Deregister_internal: Record %p %##s (%s) not found in list", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2629 return(mStatus_BadReferenceErr
);
2632 // If this is a shared record and we've announced it at least once,
2633 // we need to retract that announcement before we delete the record
2634 if (RecordType
== kDNSRecordTypeShared
&& rr
->AnnounceCount
< InitialAnnounceCount
)
2636 verbosedebugf("mDNS_Deregister_internal: Sending deregister for %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2637 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2638 rr
->resrec
.rroriginalttl
= 0;
2639 rr
->ImmedAnswer
= mDNSInterfaceMark
;
2640 if (rr
->resrec
.InterfaceID
== ((mDNSInterfaceID
)~0))
2641 m
->DiscardLocalOnlyRecords
= mDNStrue
;
2644 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
2645 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
2650 *p
= rr
->next
; // Cut this record from the list
2651 // If someone is about to look at this, bump the pointer forward
2652 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
2653 if (m
->NewLocalOnlyRecords
== rr
) m
->NewLocalOnlyRecords
= rr
->next
;
2654 rr
->next
= mDNSNULL
;
2656 if (RecordType
== kDNSRecordTypeUnregistered
)
2657 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeUnregistered",
2658 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2659 else if (RecordType
== kDNSRecordTypeDeregistering
)
2660 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeDeregistering",
2661 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2664 verbosedebugf("mDNS_Deregister_internal: Deleting record for %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2665 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
2668 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
2669 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2670 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
2672 // If we have an update queued up which never executed, give the client a chance to free that memory
2675 RData
*OldRData
= rr
->resrec
.rdata
;
2676 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
2677 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
2678 if (rr
->UpdateCallback
)
2679 rr
->UpdateCallback(m
, rr
, OldRData
); // ... and let the client know
2682 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2683 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2684 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2685 // so any attempt to touch rr after this is likely to lead to a crash.
2686 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2687 if (RecordType
== kDNSRecordTypeShared
)
2689 if (rr
->RecordCallback
)
2690 rr
->RecordCallback(m
, rr
, mStatus_MemFree
);
2692 else if (drt
== mDNS_Dereg_conflict
)
2694 RecordProbeFailure(m
, rr
);
2695 if (rr
->RecordCallback
)
2696 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
);
2698 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2700 return(mStatus_NoError
);
2703 // ***************************************************************************
2704 #if COMPILER_LIKES_PRAGMA_MARK
2707 #pragma mark - DNS Message Creation Functions
2710 mDNSlocal
void InitializeDNSMessage(DNSMessageHeader
*h
, mDNSOpaque16 id
, mDNSOpaque16 flags
)
2714 h
->numQuestions
= 0;
2716 h
->numAuthorities
= 0;
2717 h
->numAdditionals
= 0;
2720 mDNSlocal
const mDNSu8
*FindCompressionPointer(const mDNSu8
*const base
, const mDNSu8
*const end
, const mDNSu8
*const domname
)
2722 const mDNSu8
*result
= end
- *domname
- 1;
2724 if (*domname
== 0) return(mDNSNULL
); // There's no point trying to match just the root label
2726 // This loop examines each possible starting position in packet, starting end of the packet and working backwards
2727 while (result
>= base
)
2729 // If the length byte and first character of the label match, then check further to see
2730 // if this location in the packet will yield a useful name compression pointer.
2731 if (result
[0] == domname
[0] && result
[1] == domname
[1])
2733 const mDNSu8
*name
= domname
;
2734 const mDNSu8
*targ
= result
;
2735 while (targ
+ *name
< end
)
2737 // First see if this label matches
2739 const mDNSu8
*pointertarget
;
2740 for (i
=0; i
<= *name
; i
++) if (targ
[i
] != name
[i
]) break;
2741 if (i
<= *name
) break; // If label did not match, bail out
2742 targ
+= 1 + *name
; // Else, did match, so advance target pointer
2743 name
+= 1 + *name
; // and proceed to check next label
2744 if (*name
== 0 && *targ
== 0) return(result
); // If no more labels, we found a match!
2745 if (*name
== 0) break; // If no more labels to match, we failed, so bail out
2747 // The label matched, so now follow the pointer (if appropriate) and then see if the next label matches
2748 if (targ
[0] < 0x40) continue; // If length value, continue to check next label
2749 if (targ
[0] < 0xC0) break; // If 40-BF, not valid
2750 if (targ
+1 >= end
) break; // Second byte not present!
2751 pointertarget
= base
+ (((mDNSu16
)(targ
[0] & 0x3F)) << 8) + targ
[1];
2752 if (targ
< pointertarget
) break; // Pointertarget must point *backwards* in the packet
2753 if (pointertarget
[0] >= 0x40) break; // Pointertarget must point to a valid length byte
2754 targ
= pointertarget
;
2757 result
--; // We failed to match at this search position, so back up the tentative result pointer and try again
2762 // Put a string of dot-separated labels as length-prefixed labels
2763 // domainname is a fully-qualified name (i.e. assumed to be ending in a dot, even if it doesn't)
2764 // msg points to the message we're building (pass mDNSNULL if we don't want to use compression pointers)
2765 // end points to the end of the message so far
2766 // ptr points to where we want to put the name
2767 // limit points to one byte past the end of the buffer that we must not overrun
2768 // domainname is the name to put
2769 mDNSlocal mDNSu8
*putDomainNameAsLabels(const DNSMessage
*const msg
,
2770 mDNSu8
*ptr
, const mDNSu8
*const limit
, const domainname
*const name
)
2772 const mDNSu8
*const base
= (const mDNSu8
*const)msg
;
2773 const mDNSu8
* np
= name
->c
;
2774 const mDNSu8
*const max
= name
->c
+ MAX_DOMAIN_NAME
; // Maximum that's valid
2775 const mDNSu8
* pointer
= mDNSNULL
;
2776 const mDNSu8
*const searchlimit
= ptr
;
2778 while (*np
&& ptr
< limit
-1) // While we've got characters in the name, and space to write them in the message...
2780 if (*np
> MAX_DOMAIN_LABEL
)
2781 { LogMsg("Malformed domain name %##s (label more than 63 bytes)", name
->c
); return(mDNSNULL
); }
2783 // This check correctly allows for the final trailing root label:
2785 // Suppose our domain name is exactly 255 bytes long, including the final trailing root label.
2786 // Suppose np is now at name->c[248], and we're about to write our last non-null label ("local").
2787 // We know that max will be at name->c[255]
2788 // That means that np + 1 + 5 == max - 1, so we (just) pass the "if" test below, write our
2789 // six bytes, then exit the loop, write the final terminating root label, and the domain
2790 // name we've written is exactly 255 bytes long, exactly at the correct legal limit.
2791 // If the name is one byte longer, then we fail the "if" test below, and correctly bail out.
2792 if (np
+ 1 + *np
>= max
)
2793 { LogMsg("Malformed domain name %##s (more than 255 bytes)", name
->c
); return(mDNSNULL
); }
2795 if (base
) pointer
= FindCompressionPointer(base
, searchlimit
, np
);
2796 if (pointer
) // Use a compression pointer if we can
2798 mDNSu16 offset
= (mDNSu16
)(pointer
- base
);
2799 *ptr
++ = (mDNSu8
)(0xC0 | (offset
>> 8));
2800 *ptr
++ = (mDNSu8
)( offset
);
2803 else // Else copy one label and try again
2807 if (ptr
+ 1 + len
>= limit
) return(mDNSNULL
);
2809 for (i
=0; i
<len
; i
++) *ptr
++ = *np
++;
2813 if (ptr
< limit
) // If we didn't run out of space
2815 *ptr
++ = 0; // Put the final root label
2816 return(ptr
); // and return
2822 mDNSlocal mDNSu8
*putRData(const DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
, ResourceRecord
*rr
)
2826 case kDNSType_A
: if (rr
->rdlength
!= 4)
2828 debugf("putRData: Illegal length %d for kDNSType_A", rr
->rdlength
);
2831 if (ptr
+ 4 > limit
) return(mDNSNULL
);
2832 *ptr
++ = rr
->rdata
->u
.ip
.b
[0];
2833 *ptr
++ = rr
->rdata
->u
.ip
.b
[1];
2834 *ptr
++ = rr
->rdata
->u
.ip
.b
[2];
2835 *ptr
++ = rr
->rdata
->u
.ip
.b
[3];
2838 case kDNSType_CNAME
:// Same as PTR
2839 case kDNSType_PTR
: return(putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->rdata
->u
.name
));
2841 case kDNSType_HINFO
:// Same as TXT
2842 case kDNSType_TXT
: if (ptr
+ rr
->rdlength
> limit
) return(mDNSNULL
);
2843 mDNSPlatformMemCopy(rr
->rdata
->u
.data
, ptr
, rr
->rdlength
);
2844 return(ptr
+ rr
->rdlength
);
2846 case kDNSType_AAAA
: if (rr
->rdlength
!= sizeof(rr
->rdata
->u
.ipv6
))
2848 debugf("putRData: Illegal length %d for kDNSType_AAAA", rr
->rdlength
);
2851 if (ptr
+ sizeof(rr
->rdata
->u
.ipv6
) > limit
) return(mDNSNULL
);
2852 mDNSPlatformMemCopy(&rr
->rdata
->u
.ipv6
, ptr
, sizeof(rr
->rdata
->u
.ipv6
));
2853 return(ptr
+ sizeof(rr
->rdata
->u
.ipv6
));
2855 case kDNSType_SRV
: if (ptr
+ 6 > limit
) return(mDNSNULL
);
2856 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.priority
>> 8);
2857 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.priority
);
2858 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.weight
>> 8);
2859 *ptr
++ = (mDNSu8
)(rr
->rdata
->u
.srv
.weight
);
2860 *ptr
++ = rr
->rdata
->u
.srv
.port
.b
[0];
2861 *ptr
++ = rr
->rdata
->u
.srv
.port
.b
[1];
2862 return(putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->rdata
->u
.srv
.target
));
2864 default: if (ptr
+ rr
->rdlength
> limit
) return(mDNSNULL
);
2865 debugf("putRData: Warning! Writing resource type %d as raw data", rr
->rrtype
);
2866 mDNSPlatformMemCopy(rr
->rdata
->u
.data
, ptr
, rr
->rdlength
);
2867 return(ptr
+ rr
->rdlength
);
2871 mDNSlocal mDNSu8
*PutResourceRecordTTL(DNSMessage
*const msg
, mDNSu8
*ptr
, mDNSu16
*count
, ResourceRecord
*rr
, mDNSu32 ttl
)
2874 mDNSu16 actualLength
;
2875 const mDNSu8
*limit
= msg
->data
+ AbsoluteMaxDNSMessageData
;
2877 // If we have a single large record to put in the packet, then we allow the packet to be up to 9K bytes,
2878 // but in the normal case we try to keep the packets below 1500 to avoid IP fragmentation on standard Ethernet
2879 if (msg
->h
.numAnswers
|| msg
->h
.numAuthorities
|| msg
->h
.numAdditionals
)
2880 limit
= msg
->data
+ NormalMaxDNSMessageData
;
2882 if (rr
->RecordType
== kDNSRecordTypeUnregistered
)
2884 LogMsg("PutResourceRecord ERROR! Attempt to put kDNSRecordTypeUnregistered %##s (%s)", rr
->name
.c
, DNSTypeName(rr
->rrtype
));
2888 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->name
);
2889 if (!ptr
|| ptr
+ 10 >= limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2890 ptr
[0] = (mDNSu8
)(rr
->rrtype
>> 8);
2891 ptr
[1] = (mDNSu8
)(rr
->rrtype
);
2892 ptr
[2] = (mDNSu8
)(rr
->rrclass
>> 8);
2893 ptr
[3] = (mDNSu8
)(rr
->rrclass
);
2894 ptr
[4] = (mDNSu8
)(ttl
>> 24);
2895 ptr
[5] = (mDNSu8
)(ttl
>> 16);
2896 ptr
[6] = (mDNSu8
)(ttl
>> 8);
2897 ptr
[7] = (mDNSu8
)(ttl
);
2898 endofrdata
= putRData(msg
, ptr
+10, limit
, rr
);
2899 if (!endofrdata
) { verbosedebugf("Ran out of space in PutResourceRecord for %##s (%s)", rr
->name
.c
, DNSTypeName(rr
->rrtype
)); return(mDNSNULL
); }
2901 // Go back and fill in the actual number of data bytes we wrote
2902 // (actualLength can be less than rdlength when domain name compression is used)
2903 actualLength
= (mDNSu16
)(endofrdata
- ptr
- 10);
2904 ptr
[8] = (mDNSu8
)(actualLength
>> 8);
2905 ptr
[9] = (mDNSu8
)(actualLength
);
2911 #define PutResourceRecord(MSG, P, C, RR) PutResourceRecordTTL((MSG), (P), (C), (RR), (RR)->rroriginalttl)
2913 mDNSlocal mDNSu8
*PutResourceRecordCappedTTL(DNSMessage
*const msg
, mDNSu8
*ptr
, mDNSu16
*count
, ResourceRecord
*rr
, mDNSu32 maxttl
)
2915 if (maxttl
> rr
->rroriginalttl
) maxttl
= rr
->rroriginalttl
;
2916 return(PutResourceRecordTTL(msg
, ptr
, count
, rr
, maxttl
));
2920 mDNSlocal mDNSu8
*putEmptyResourceRecord(DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
,
2921 mDNSu16
*count
, const AuthRecord
*rr
)
2923 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, &rr
->name
);
2924 if (!ptr
|| ptr
+ 10 > limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2925 ptr
[0] = (mDNSu8
)(rr
->resrec
.rrtype
>> 8); // Put type
2926 ptr
[1] = (mDNSu8
)(rr
->resrec
.rrtype
);
2927 ptr
[2] = (mDNSu8
)(rr
->resrec
.rrclass
>> 8); // Put class
2928 ptr
[3] = (mDNSu8
)(rr
->resrec
.rrclass
);
2929 ptr
[4] = ptr
[5] = ptr
[6] = ptr
[7] = 0; // TTL is zero
2930 ptr
[8] = ptr
[9] = 0; // RDATA length is zero
2936 mDNSlocal mDNSu8
*putQuestion(DNSMessage
*const msg
, mDNSu8
*ptr
, const mDNSu8
*const limit
,
2937 const domainname
*const name
, mDNSu16 rrtype
, mDNSu16 rrclass
)
2939 ptr
= putDomainNameAsLabels(msg
, ptr
, limit
, name
);
2940 if (!ptr
|| ptr
+4 >= limit
) return(mDNSNULL
); // If we're out-of-space, return mDNSNULL
2941 ptr
[0] = (mDNSu8
)(rrtype
>> 8);
2942 ptr
[1] = (mDNSu8
)(rrtype
);
2943 ptr
[2] = (mDNSu8
)(rrclass
>> 8);
2944 ptr
[3] = (mDNSu8
)(rrclass
);
2945 msg
->h
.numQuestions
++;
2949 // ***************************************************************************
2950 #if COMPILER_LIKES_PRAGMA_MARK
2952 #pragma mark - DNS Message Parsing Functions
2955 mDNSlocal
const mDNSu8
*skipDomainName(const DNSMessage
*const msg
, const mDNSu8
*ptr
, const mDNSu8
*const end
)
2959 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
2960 { debugf("skipDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL
); }
2962 while (1) // Read sequence of labels
2964 const mDNSu8 len
= *ptr
++; // Read length of this label
2965 if (len
== 0) return(ptr
); // If length is zero, that means this name is complete
2968 case 0x00: if (ptr
+ len
>= end
) // Remember: expect at least one more byte for the root label
2969 { debugf("skipDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL
); }
2970 if (total
+ 1 + len
>= MAX_DOMAIN_NAME
) // Remember: expect at least one more byte for the root label
2971 { debugf("skipDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL
); }
2976 case 0x40: debugf("skipDomainName: Extended EDNS0 label types 0x%X not supported", len
); return(mDNSNULL
);
2977 case 0x80: debugf("skipDomainName: Illegal label length 0x%X", len
); return(mDNSNULL
);
2978 case 0xC0: return(ptr
+1);
2983 // Routine to fetch an FQDN from the DNS message, following compression pointers if necessary.
2984 mDNSlocal
const mDNSu8
*getDomainName(const DNSMessage
*const msg
, const mDNSu8
*ptr
, const mDNSu8
*const end
,
2985 domainname
*const name
)
2987 const mDNSu8
*nextbyte
= mDNSNULL
; // Record where we got to before we started following pointers
2988 mDNSu8
*np
= name
->c
; // Name pointer
2989 const mDNSu8
*const limit
= np
+ MAX_DOMAIN_NAME
; // Limit so we don't overrun buffer
2991 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
2992 { debugf("getDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL
); }
2994 *np
= 0; // Tentatively place the root label here (may be overwritten if we have more labels)
2996 while (1) // Read sequence of labels
2998 const mDNSu8 len
= *ptr
++; // Read length of this label
2999 if (len
== 0) break; // If length is zero, that means this name is complete
3005 case 0x00: if (ptr
+ len
>= end
) // Remember: expect at least one more byte for the root label
3006 { debugf("getDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL
); }
3007 if (np
+ 1 + len
>= limit
) // Remember: expect at least one more byte for the root label
3008 { debugf("getDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL
); }
3010 for (i
=0; i
<len
; i
++) *np
++ = *ptr
++;
3011 *np
= 0; // Tentatively place the root label here (may be overwritten if we have more labels)
3014 case 0x40: debugf("getDomainName: Extended EDNS0 label types 0x%X not supported in name %##s", len
, name
->c
);
3017 case 0x80: debugf("getDomainName: Illegal label length 0x%X in domain name %##s", len
, name
->c
); return(mDNSNULL
);
3019 case 0xC0: offset
= (mDNSu16
)((((mDNSu16
)(len
& 0x3F)) << 8) | *ptr
++);
3020 if (!nextbyte
) nextbyte
= ptr
; // Record where we got to before we started following pointers
3021 ptr
= (mDNSu8
*)msg
+ offset
;
3022 if (ptr
< (mDNSu8
*)msg
|| ptr
>= end
)
3023 { debugf("getDomainName: Illegal compression pointer not within packet boundaries"); return(mDNSNULL
); }
3025 { debugf("getDomainName: Compression pointer must point to real label"); return(mDNSNULL
); }
3030 if (nextbyte
) return(nextbyte
);
3034 mDNSlocal
const mDNSu8
*skipResourceRecord(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
)
3036 mDNSu16 pktrdlength
;
3038 ptr
= skipDomainName(msg
, ptr
, end
);
3039 if (!ptr
) { debugf("skipResourceRecord: Malformed RR name"); return(mDNSNULL
); }
3041 if (ptr
+ 10 > end
) { debugf("skipResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL
); }
3042 pktrdlength
= (mDNSu16
)((mDNSu16
)ptr
[8] << 8 | ptr
[9]);
3044 if (ptr
+ pktrdlength
> end
) { debugf("skipResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL
); }
3046 return(ptr
+ pktrdlength
);
3049 #define GetLargeResourceRecord(m, msg, p, e, i, t, L) \
3050 (((L)->r.rdatastorage.MaxRDLength = MaximumRDSize), GetResourceRecord((m), (msg), (p), (e), (i), (t), &(L)->r, (RData*)&(L)->r.rdatastorage))
3052 mDNSlocal
const mDNSu8
*GetResourceRecord(mDNS
*const m
, const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
,
3053 const mDNSInterfaceID InterfaceID
, mDNSu8 RecordType
, CacheRecord
*rr
, RData
*RDataStorage
)
3055 mDNSu16 pktrdlength
;
3057 rr
->next
= mDNSNULL
;
3058 rr
->resrec
.RecordType
= RecordType
;
3060 rr
->NextInKAList
= mDNSNULL
;
3061 rr
->TimeRcvd
= m
->timenow
;
3062 rr
->NextRequiredQuery
= m
->timenow
; // Will be updated to the real value when we call SetNextCacheCheckTime()
3063 rr
->LastUsed
= m
->timenow
;
3065 rr
->CRActiveQuestion
= mDNSNULL
;
3066 rr
->UnansweredQueries
= 0;
3067 rr
->LastUnansweredTime
= 0;
3068 rr
->MPUnansweredQ
= 0;
3069 rr
->MPLastUnansweredQT
= 0;
3070 rr
->MPUnansweredKA
= 0;
3071 rr
->MPExpectingKA
= mDNSfalse
;
3072 rr
->NextInCFList
= mDNSNULL
;
3074 rr
->resrec
.InterfaceID
= InterfaceID
;
3075 ptr
= getDomainName(msg
, ptr
, end
, &rr
->resrec
.name
);
3076 if (!ptr
) { debugf("GetResourceRecord: Malformed RR name"); return(mDNSNULL
); }
3078 if (ptr
+ 10 > end
) { debugf("GetResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL
); }
3080 rr
->resrec
.rrtype
= (mDNSu16
) ((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
3081 rr
->resrec
.rrclass
= (mDNSu16
)(((mDNSu16
)ptr
[2] << 8 | ptr
[3]) & kDNSClass_Mask
);
3082 rr
->resrec
.rroriginalttl
= (mDNSu32
) ((mDNSu32
)ptr
[4] << 24 | (mDNSu32
)ptr
[5] << 16 | (mDNSu32
)ptr
[6] << 8 | ptr
[7]);
3083 if (rr
->resrec
.rroriginalttl
> 0x70000000UL
/ mDNSPlatformOneSecond
)
3084 rr
->resrec
.rroriginalttl
= 0x70000000UL
/ mDNSPlatformOneSecond
;
3085 // Note: We don't have to adjust m->NextCacheCheck here -- this is just getting a record into memory for
3086 // us to look at. If we decide to copy it into the cache, then we'll update m->NextCacheCheck accordingly.
3087 pktrdlength
= (mDNSu16
)((mDNSu16
)ptr
[8] << 8 | ptr
[9]);
3088 if (ptr
[2] & (kDNSClass_UniqueRRSet
>> 8))
3089 rr
->resrec
.RecordType
|= kDNSRecordTypePacketUniqueMask
;
3091 if (ptr
+ pktrdlength
> end
) { debugf("GetResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL
); }
3094 rr
->resrec
.rdata
= RDataStorage
;
3097 rr
->resrec
.rdata
= (RData
*)&rr
->rdatastorage
;
3098 rr
->resrec
.rdata
->MaxRDLength
= sizeof(RDataBody
);
3101 switch (rr
->resrec
.rrtype
)
3103 case kDNSType_A
: rr
->resrec
.rdata
->u
.ip
.b
[0] = ptr
[0];
3104 rr
->resrec
.rdata
->u
.ip
.b
[1] = ptr
[1];
3105 rr
->resrec
.rdata
->u
.ip
.b
[2] = ptr
[2];
3106 rr
->resrec
.rdata
->u
.ip
.b
[3] = ptr
[3];
3109 case kDNSType_CNAME
:// Same as PTR
3110 case kDNSType_PTR
: if (!getDomainName(msg
, ptr
, end
, &rr
->resrec
.rdata
->u
.name
))
3111 { debugf("GetResourceRecord: Malformed CNAME/PTR RDATA name"); return(mDNSNULL
); }
3112 //debugf("%##s PTR %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.name.c, pktrdlength);
3115 case kDNSType_NULL
: //Same as TXT
3116 case kDNSType_HINFO
://Same as TXT
3117 case kDNSType_TXT
: if (pktrdlength
> rr
->resrec
.rdata
->MaxRDLength
)
3119 debugf("GetResourceRecord: %s rdata size (%d) exceeds storage (%d)",
3120 DNSTypeName(rr
->resrec
.rrtype
), pktrdlength
, rr
->resrec
.rdata
->MaxRDLength
);
3123 rr
->resrec
.rdlength
= pktrdlength
;
3124 mDNSPlatformMemCopy(ptr
, rr
->resrec
.rdata
->u
.data
, pktrdlength
);
3127 case kDNSType_AAAA
: mDNSPlatformMemCopy(ptr
, &rr
->resrec
.rdata
->u
.ipv6
, sizeof(rr
->resrec
.rdata
->u
.ipv6
));
3130 case kDNSType_SRV
: rr
->resrec
.rdata
->u
.srv
.priority
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
3131 rr
->resrec
.rdata
->u
.srv
.weight
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
3132 rr
->resrec
.rdata
->u
.srv
.port
.b
[0] = ptr
[4];
3133 rr
->resrec
.rdata
->u
.srv
.port
.b
[1] = ptr
[5];
3134 if (!getDomainName(msg
, ptr
+6, end
, &rr
->resrec
.rdata
->u
.srv
.target
))
3135 { debugf("GetResourceRecord: Malformed SRV RDATA name"); return(mDNSNULL
); }
3136 //debugf("%##s SRV %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.srv.target.c, pktrdlength);
3139 default: if (pktrdlength
> rr
->resrec
.rdata
->MaxRDLength
)
3141 debugf("GetResourceRecord: rdata %d (%s) size (%d) exceeds storage (%d)",
3142 rr
->resrec
.rrtype
, DNSTypeName(rr
->resrec
.rrtype
), pktrdlength
, rr
->resrec
.rdata
->MaxRDLength
);
3145 debugf("GetResourceRecord: Warning! Reading resource type %d (%s) as opaque data",
3146 rr
->resrec
.rrtype
, DNSTypeName(rr
->resrec
.rrtype
));
3147 // Note: Just because we don't understand the record type, that doesn't
3148 // mean we fail. The DNS protocol specifies rdlength, so we can
3149 // safely skip over unknown records and ignore them.
3150 // We also grab a binary copy of the rdata anyway, since the caller
3151 // might know how to interpret it even if we don't.
3152 rr
->resrec
.rdlength
= pktrdlength
;
3153 mDNSPlatformMemCopy(ptr
, rr
->resrec
.rdata
->u
.data
, pktrdlength
);
3157 rr
->resrec
.namehash
= DomainNameHashValue(&rr
->resrec
.name
);
3158 SetNewRData(&rr
->resrec
, mDNSNULL
, 0);
3160 return(ptr
+ pktrdlength
);
3163 mDNSlocal
const mDNSu8
*skipQuestion(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
)
3165 ptr
= skipDomainName(msg
, ptr
, end
);
3166 if (!ptr
) { debugf("skipQuestion: Malformed domain name in DNS question section"); return(mDNSNULL
); }
3167 if (ptr
+4 > end
) { debugf("skipQuestion: Malformed DNS question section -- no query type and class!"); return(mDNSNULL
); }
3171 mDNSlocal
const mDNSu8
*getQuestion(const DNSMessage
*msg
, const mDNSu8
*ptr
, const mDNSu8
*end
, const mDNSInterfaceID InterfaceID
,
3172 DNSQuestion
*question
)
3174 question
->InterfaceID
= InterfaceID
;
3175 ptr
= getDomainName(msg
, ptr
, end
, &question
->qname
);
3176 if (!ptr
) { debugf("Malformed domain name in DNS question section"); return(mDNSNULL
); }
3177 if (ptr
+4 > end
) { debugf("Malformed DNS question section -- no query type and class!"); return(mDNSNULL
); }
3179 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
3180 question
->qtype
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]); // Get type
3181 question
->qclass
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]); // and class
3185 mDNSlocal
const mDNSu8
*LocateAnswers(const DNSMessage
*const msg
, const mDNSu8
*const end
)
3188 const mDNSu8
*ptr
= msg
->data
;
3189 for (i
= 0; i
< msg
->h
.numQuestions
&& ptr
; i
++) ptr
= skipQuestion(msg
, ptr
, end
);
3193 mDNSlocal
const mDNSu8
*LocateAuthorities(const DNSMessage
*const msg
, const mDNSu8
*const end
)
3196 const mDNSu8
*ptr
= LocateAnswers(msg
, end
);
3197 for (i
= 0; i
< msg
->h
.numAnswers
&& ptr
; i
++) ptr
= skipResourceRecord(msg
, ptr
, end
);
3201 // ***************************************************************************
3202 #if COMPILER_LIKES_PRAGMA_MARK
3205 #pragma mark - Packet Sending Functions
3208 mDNSlocal mStatus
mDNSSendDNSMessage(const mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
3209 mDNSInterfaceID InterfaceID
, mDNSIPPort srcport
, const mDNSAddr
*dst
, mDNSIPPort dstport
)
3212 mDNSu16 numQuestions
= msg
->h
.numQuestions
;
3213 mDNSu16 numAnswers
= msg
->h
.numAnswers
;
3214 mDNSu16 numAuthorities
= msg
->h
.numAuthorities
;
3215 mDNSu16 numAdditionals
= msg
->h
.numAdditionals
;
3217 // Put all the integer values in IETF byte-order (MSB first, LSB second)
3218 mDNSu8
*ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
3219 *ptr
++ = (mDNSu8
)(numQuestions
>> 8);
3220 *ptr
++ = (mDNSu8
)(numQuestions
);
3221 *ptr
++ = (mDNSu8
)(numAnswers
>> 8);
3222 *ptr
++ = (mDNSu8
)(numAnswers
);
3223 *ptr
++ = (mDNSu8
)(numAuthorities
>> 8);
3224 *ptr
++ = (mDNSu8
)(numAuthorities
);
3225 *ptr
++ = (mDNSu8
)(numAdditionals
>> 8);
3226 *ptr
++ = (mDNSu8
)(numAdditionals
);
3228 // Send the packet on the wire
3229 status
= mDNSPlatformSendUDP(m
, msg
, end
, InterfaceID
, srcport
, dst
, dstport
);
3231 // Put all the integer values back the way they were before we return
3232 msg
->h
.numQuestions
= numQuestions
;
3233 msg
->h
.numAnswers
= numAnswers
;
3234 msg
->h
.numAuthorities
= numAuthorities
;
3235 msg
->h
.numAdditionals
= numAdditionals
;
3240 mDNSlocal
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
3242 // Setting AnnounceCount to InitialAnnounceCount signals mDNS_Deregister_internal()
3243 // that it should go ahead and immediately dispose of this registration
3244 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
3245 rr
->AnnounceCount
= InitialAnnounceCount
;
3246 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
3249 // NOTE: DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback, which may change
3250 // the record list and/or question list.
3251 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3252 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
3254 if (m
->CurrentRecord
) LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set");
3255 m
->CurrentRecord
= m
->ResourceRecords
;
3257 while (m
->CurrentRecord
)
3259 AuthRecord
*rr
= m
->CurrentRecord
;
3260 m
->CurrentRecord
= rr
->next
;
3261 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3262 CompleteDeregistration(m
, rr
);
3266 mDNSlocal mDNSBool
HaveSentEntireRRSet(const mDNS
*const m
, const AuthRecord
*const rr
, mDNSInterfaceID InterfaceID
)
3268 // Try to find another member of this set that we're still planning to send on this interface
3269 const AuthRecord
*a
;
3270 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
3271 if (a
->SendRNow
== InterfaceID
&& a
!= rr
&& SameResourceRecordSignature(&a
->resrec
, &rr
->resrec
)) break;
3272 return (a
== mDNSNULL
); // If no more members of this set found, then we should set the cache flush bit
3275 // Note about acceleration of announcements to facilitate automatic coalescing of
3276 // multiple independent threads of announcements into a single synchronized thread:
3277 // The announcements in the packet may be at different stages of maturity;
3278 // One-second interval, two-second interval, four-second interval, and so on.
3279 // After we've put in all the announcements that are due, we then consider
3280 // whether there are other nearly-due announcements that are worth accelerating.
3281 // To be eligible for acceleration, a record MUST NOT be older (further along
3282 // its timeline) than the most mature record we've already put in the packet.
3283 // In other words, younger records can have their timelines accelerated to catch up
3284 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
3285 // Older records cannot have their timelines accelerated; this would just widen
3286 // the gap between them and their younger bretheren and get them even more out of sync.
3288 // NOTE: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
3289 // the record list and/or question list.
3290 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3291 mDNSlocal
void SendResponses(mDNS
*const m
)
3294 AuthRecord
*rr
, *r2
;
3295 mDNSs32 maxExistingAnnounceInterval
= 0;
3296 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3298 m
->NextScheduledResponse
= m
->timenow
+ 0x78000000;
3301 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
3304 // Run through our list of records, and decide which ones we're going to announce on all interfaces
3305 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3307 if (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0)
3309 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
3310 else rr
->NextUpdateCredit
= (m
->timenow
+ mDNSPlatformOneSecond
* 60) | 1;
3312 if (TimeToAnnounceThisRecord(rr
, m
->timenow
) && ResourceRecordIsValidAnswer(rr
))
3314 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
3315 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
3316 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
3317 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
3321 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
3322 // Eligible records that are more than half-way to their announcement time are accelerated
3323 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3324 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
3325 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
3326 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
3327 ResourceRecordIsValidAnswer(rr
)))
3328 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
3330 // When sending SRV records (particularly when announcing a new service) automatically add the related Address record(s)
3331 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3332 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
3333 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
3334 if (RRIsAddressType(r2
) && // For all address records (A/AAAA) ...
3335 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
3336 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
3337 rr
->resrec
.rdnamehash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
3338 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, &r2
->resrec
.name
) &&
3339 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
3340 r2
->ImmedAnswer
= mDNSInterfaceMark
; // ... then mark this address record for sending too
3342 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
3343 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
3344 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
3345 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
3346 // -- 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
3347 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
3348 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3349 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3351 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
3353 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3354 if (ResourceRecordIsValidAnswer(r2
))
3355 if (r2
->ImmedAnswer
!= mDNSInterfaceMark
&& r2
->ImmedAnswer
!= rr
->ImmedAnswer
&& SameResourceRecordSignature(&r2
->resrec
, &rr
->resrec
))
3356 r2
->ImmedAnswer
= rr
->ImmedAnswer
;
3358 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
3360 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3361 if (ResourceRecordIsValidAnswer(r2
))
3362 if (r2
->ImmedAdditional
!= rr
->ImmedAdditional
&& SameResourceRecordSignature(&r2
->resrec
, &rr
->resrec
))
3363 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
3367 // Now set SendRNow state appropriately
3368 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3370 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
3372 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
3373 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
3374 rr
->LastMCTime
= m
->timenow
;
3375 rr
->LastMCInterface
= rr
->ImmedAnswer
;
3376 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
3377 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
3379 rr
->AnnounceCount
--;
3380 rr
->ThisAPInterval
*= 2;
3381 rr
->LastAPTime
= m
->timenow
;
3382 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- rr
->AnnounceUntil
>= 0) rr
->AnnounceCount
= 0;
3383 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
3386 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
3388 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
3389 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
3390 rr
->LastMCTime
= m
->timenow
;
3391 rr
->LastMCInterface
= rr
->ImmedAnswer
;
3393 SetNextAnnounceProbeTime(m
, rr
);
3397 // *** 2. Loop through interface list, sending records as appropriate
3403 int numAnnounce
= 0;
3405 DNSMessage response
;
3406 mDNSu8
*responseptr
= response
.data
;
3408 InitializeDNSMessage(&response
.h
, zeroID
, ResponseFlags
);
3410 // First Pass. Look for:
3411 // 1. Deregistering records that need to send their goodbye packet
3412 // 2. Updated records that need to retract their old data
3413 // 3. Answers and announcements we need to send
3414 // In all cases, if we fail, and we've put at least one answer, we break out of the for loop so we can
3415 // send this packet and then try again.
3416 // If we have not put even one answer, then we don't bail out. We pretend we succeeded anyway,
3417 // because otherwise we'll end up in an infinite loop trying to send a record that will never fit.
3418 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3419 if (rr
->SendRNow
== intf
->InterfaceID
)
3421 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3423 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, 0);
3424 if (!newptr
&& response
.h
.numAnswers
) break;
3426 responseptr
= newptr
;
3428 else if (rr
->NewRData
) // If we have new data for this record
3430 RData
*OldRData
= rr
->resrec
.rdata
;
3431 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
3432 // See if we should send a courtesy "goodbye" the old data before we replace it.
3433 // We compare with "InitialAnnounceCount-1" instead of "InitialAnnounceCount" because by the time
3434 // we get to this place in this routine we've we've already decremented rr->AnnounceCount
3435 if (ResourceRecordIsValidAnswer(rr
) && rr
->AnnounceCount
< InitialAnnounceCount
-1)
3437 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, 0);
3438 if (!newptr
&& response
.h
.numAnswers
) break;
3440 responseptr
= newptr
;
3442 // Now try to see if we can fit the update in the same packet (not fatal if we can't)
3443 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
3444 if ((rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && HaveSentEntireRRSet(m
, rr
, intf
->InterfaceID
))
3445 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3446 newptr
= PutResourceRecord(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
);
3447 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3448 if (newptr
) responseptr
= newptr
;
3449 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
3453 if ((rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && HaveSentEntireRRSet(m
, rr
, intf
->InterfaceID
))
3454 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3455 newptr
= PutResourceRecordTTL(&response
, responseptr
, &response
.h
.numAnswers
, &rr
->resrec
, m
->SleepState
? 0 : rr
->resrec
.rroriginalttl
);
3456 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3457 if (!newptr
&& response
.h
.numAnswers
) break;
3458 if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++; else numAnswer
++;
3459 responseptr
= newptr
;
3461 // If sending on all interfaces, go to next interface; else we're finished now
3462 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
3463 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
3465 rr
->SendRNow
= mDNSNULL
;
3468 // Second Pass. Add additional records, if there's space.
3469 newptr
= responseptr
;
3470 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3471 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
3473 // Since additionals are optional, we clear ImmedAdditional anyway, even if we subsequently find it doesn't fit in the packet
3474 rr
->ImmedAdditional
= mDNSNULL
;
3475 if (newptr
&& ResourceRecordIsValidAnswer(rr
))
3477 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3479 // Try to find another member of this set that we're still planning to send on this interface
3480 const AuthRecord
*a
;
3481 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
3482 if (a
->ImmedAdditional
== intf
->InterfaceID
&& SameResourceRecordSignature(&a
->resrec
, &rr
->resrec
)) break;
3483 if (a
== mDNSNULL
) // If no more members of this set found
3484 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3486 newptr
= PutResourceRecord(&response
, newptr
, &response
.h
.numAdditionals
, &rr
->resrec
);
3487 if (newptr
) responseptr
= newptr
;
3488 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3492 if (response
.h
.numAnswers
> 0) // We *never* send a packet with only additionals in it
3494 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3495 numDereg
, numDereg
== 1 ? "" : "s",
3496 numAnnounce
, numAnnounce
== 1 ? "" : "s",
3497 numAnswer
, numAnswer
== 1 ? "" : "s",
3498 response
.h
.numAdditionals
, response
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
3499 mDNSSendDNSMessage(m
, &response
, responseptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v4
, MulticastDNSPort
);
3500 mDNSSendDNSMessage(m
, &response
, responseptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v6
, MulticastDNSPort
);
3501 if (!m
->SuppressSending
) m
->SuppressSending
= (m
->timenow
+ mDNSPlatformOneSecond
/10) | 1; // OR with one to ensure non-zero
3502 if (++pktcount
>= 1000)
3503 { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
3504 // There might be more things to send on this interface, so go around one more time and try again.
3506 else // Nothing more to send on this interface; go to next
3508 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3509 #if MDNS_DEBUGMSGS && 0
3510 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3511 debugf(msg
, intf
, next
);
3518 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3521 if (m
->CurrentRecord
) LogMsg("SendResponses: ERROR m->CurrentRecord already set");
3522 m
->CurrentRecord
= m
->ResourceRecords
;
3523 while (m
->CurrentRecord
)
3525 rr
= m
->CurrentRecord
;
3526 m
->CurrentRecord
= rr
->next
;
3530 RData
*OldRData
= rr
->resrec
.rdata
;
3531 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
3532 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
3533 if (rr
->UpdateCallback
)
3534 rr
->UpdateCallback(m
, rr
, OldRData
); // ... and let the client know
3537 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3538 CompleteDeregistration(m
, rr
);
3541 rr
->ImmedAnswer
= mDNSNULL
;
3542 rr
->v4Requester
= zeroIPAddr
;
3543 rr
->v6Requester
= zerov6Addr
;
3546 verbosedebugf("SendResponses: Next in %d ticks", m
->NextScheduledResponse
- m
->timenow
);
3549 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3550 // so we want to be lazy about how frequently we do it.
3551 // 1. If a cache record is currently referenced by *no* active questions,
3552 // then we don't mind expiring it up to a minute late (who will know?)
3553 // 2. Else, if a cache record is due for some of its final expiration queries,
3554 // we'll allow them to be late by up to 2% of the TTL
3555 // 3. Else, if a cache record has completed all its final expiration queries without success,
3556 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3557 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3558 // so allow at most 1/10 second lateness
3559 #define CacheCheckGracePeriod(RR) ( \
3560 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3561 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
3562 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : (mDNSPlatformOneSecond/10))
3564 // Note: MUST call SetNextCacheCheckTime any time we change:
3566 // rr->resrec.rroriginalttl
3567 // rr->UnansweredQueries
3568 // rr->CRActiveQuestion
3569 mDNSlocal
void SetNextCacheCheckTime(mDNS
*const m
, CacheRecord
*const rr
)
3571 rr
->NextRequiredQuery
= RRExpireTime(rr
);
3573 // If we have an active question, then see if we want to schedule a refresher query for this record.
3574 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3575 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3577 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
3578 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
3579 verbosedebugf("SetNextCacheCheckTime: %##s (%s) NextRequiredQuery in %ld sec",
3580 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
);
3583 if (m
->NextCacheCheck
- (rr
->NextRequiredQuery
+ CacheCheckGracePeriod(rr
)) > 0)
3584 m
->NextCacheCheck
= (rr
->NextRequiredQuery
+ CacheCheckGracePeriod(rr
));
3587 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 45)
3588 #define kDefaultReconfirmTimeForCableDisconnect ((mDNSu32)mDNSPlatformOneSecond * 5)
3589 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3591 mDNSlocal mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
3593 if (interval
< kMinimumReconfirmTime
)
3594 interval
= kMinimumReconfirmTime
;
3595 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3596 interval
= 0x10000000;
3598 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3599 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
3601 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3602 interval
+= mDNSRandom(interval
/3);
3603 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
3604 rr
->resrec
.rroriginalttl
= interval
* 4 / mDNSPlatformOneSecond
;
3605 SetNextCacheCheckTime(m
, rr
);
3607 debugf("mDNS_Reconfirm_internal:%5ld ticks to go for %s", RRExpireTime(rr
) - m
->timenow
, GetRRDisplayString(m
, rr
));
3608 return(mStatus_NoError
);
3611 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
3613 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3614 // It also appends to the list of known answer records that need to be included,
3615 // and updates the forcast for the size of the known answer section.
3616 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, DNSMessage
*query
, mDNSu8
**queryptr
, DNSQuestion
*q
,
3617 CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
3619 mDNSBool ucast
= q
->LargeAnswers
|| q
->ThisQInterval
<= InitialQuestionInterval
*2;
3620 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3621 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
3622 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
3625 debugf("BuildQuestion: No more space in this packet for question %##s", q
->qname
.c
);
3628 else if (newptr
+ *answerforecast
>= limit
)
3630 verbosedebugf("BuildQuestion: Retracting question %##s new forecast total %d", q
->qname
.c
, newptr
+ *answerforecast
- query
->data
);
3631 query
->h
.numQuestions
--;
3636 mDNSu32 forecast
= *answerforecast
;
3638 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
3640 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3641 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3642 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not already in the known answer list
3643 rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3644 ResourceRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3645 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3646 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0)// and we'll ask at least once again before NextRequiredQuery
3648 *ka
= rr
; // Link this record into our known answer chain
3649 ka
= &rr
->NextInKAList
;
3650 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3651 forecast
+= 12 + rr
->resrec
.rdestimate
;
3652 // If we're trying to put more than one question in this packet, and it doesn't fit
3653 // then undo that last question and try again next time
3654 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
3656 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
3657 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
);
3658 query
->h
.numQuestions
--;
3659 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3660 while (*ka
) { CacheRecord
*rr
= *ka
; *ka
= mDNSNULL
; ka
= &rr
->NextInKAList
; }
3661 return(mDNSfalse
); // Return false, so we'll try again in the next packet
3665 // Traffic reduction:
3666 // If we already have at least one unique answer in the cache,
3667 // OR we have so many shared answers that the KA list is too big to fit in one packet
3668 // The we suppress queries number 3 and 5:
3669 // Query 1 (immediately; ThisQInterval = 1 sec; request unicast replies)
3670 // Query 2 (after 1 second; ThisQInterval = 2 sec; send normally)
3671 // Query 3 (after 2 seconds; ThisQInterval = 4 sec; may suppress)
3672 // Query 4 (after 4 seconds; ThisQInterval = 8 sec; send normally)
3673 // Query 5 (after 8 seconds; ThisQInterval = 16 sec; may suppress)
3674 // Query 6 (after 16 seconds; ThisQInterval = 32 sec; send normally)
3675 if (q
->UniqueAnswers
|| newptr
+ forecast
>= limit
)
3676 if (q
->ThisQInterval
== InitialQuestionInterval
* 8 || q
->ThisQInterval
== InitialQuestionInterval
* 32)
3678 query
->h
.numQuestions
--;
3679 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3680 while (*ka
) { CacheRecord
*rr
= *ka
; *ka
= mDNSNULL
; ka
= &rr
->NextInKAList
; }
3681 return(mDNStrue
); // Return true: pretend we succeeded, even though we actually suppressed this question
3684 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3685 *queryptr
= newptr
; // Update the packet pointer
3686 *answerforecast
= forecast
; // Update the forecast
3687 *kalistptrptr
= ka
; // Update the known answer list pointer
3688 if (ucast
) m
->ExpectUnicastResponse
= m
->timenow
;
3690 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // For every resource record in our cache,
3691 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3692 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not in the known answer list
3693 ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) // which answers our question
3695 rr
->UnansweredQueries
++; // indicate that we're expecting a response
3696 rr
->LastUnansweredTime
= m
->timenow
;
3697 SetNextCacheCheckTime(m
, rr
);
3704 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, DNSQuestion
*q
)
3709 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3710 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
3711 if ((target
= GetRRDomainNameTarget(&rr
->resrec
)) && rr
->resrec
.rdnamehash
== q
->qnamehash
&& SameDomainName(target
, &q
->qname
))
3712 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
3715 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3716 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
3719 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3722 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
3725 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3728 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
3731 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3732 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3733 for (i
=0; i
<DupSuppressInfoSize
; i
++)
3734 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
3736 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
3737 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
3738 if (v4
&& v6
) return(mDNStrue
);
3743 mDNSlocal
int RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
3747 // See if we have this one in our list somewhere already
3748 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
3750 // If not, find a slot we can re-use
3751 if (i
>= DupSuppressInfoSize
)
3754 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
3755 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
3759 // Record the info about this query we saw
3761 ds
[i
].InterfaceID
= InterfaceID
;
3767 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
3769 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3770 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
3773 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3774 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
3776 // We forecast: qname (n) type (2) class (2)
3777 mDNSu32 forecast
= DomainNameLength(&q
->qname
) + 4;
3779 for (rr
=m
->rrcache_hash
[HashSlot(&q
->qname
)]; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3780 if (rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3781 ResourceRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3782 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3783 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0)// and we'll ask at least once again before NextRequiredQuery
3785 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3786 forecast
+= 12 + rr
->resrec
.rdestimate
;
3787 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
3795 // How Standard Queries are generated:
3796 // 1. The Question Section contains the question
3797 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3799 // How Probe Queries are generated:
3800 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3801 // if some other host is already using *any* records with this name, we want to know about it.
3802 // 2. The Authority Section contains the proposed values we intend to use for one or more
3803 // of our records with that name (analogous to the Update section of DNS Update packets)
3804 // because if some other host is probing at the same time, we each want to know what the other is
3805 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3807 mDNSlocal
void SendQueries(mDNS
*const m
)
3811 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3812 mDNSs32 maxExistingQuestionInterval
= 0;
3813 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3814 CacheRecord
*KnownAnswerList
= mDNSNULL
;
3816 // 1. If time for a query, work out what we need to do
3817 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
3821 m
->NextScheduledQuery
= m
->timenow
+ 0x78000000;
3823 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3824 // to their NextRequiredQuery to be worth batching them together with this one
3825 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3826 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
3827 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3828 if (m
->timenow
+ TicksTTL(rr
)/50 - rr
->NextRequiredQuery
>= 0)
3830 q
= rr
->CRActiveQuestion
;
3831 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(rr
)/20, rr
->resrec
.InterfaceID
);
3832 if (q
->SendQNow
== mDNSNULL
) q
->SendQNow
= rr
->resrec
.InterfaceID
;
3833 else if (q
->SendQNow
!= rr
->resrec
.InterfaceID
) q
->SendQNow
= mDNSInterfaceMark
;
3836 // Scan our list of questions to see which ones we're definitely going to send
3837 for (q
= m
->Questions
; q
; q
=q
->next
)
3838 if (TimeToSendThisQuestion(q
, m
->timenow
))
3840 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3841 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3842 maxExistingQuestionInterval
= q
->ThisQInterval
;
3845 // Scan our list of questions
3846 // (a) to see if there are any more that are worth accelerating, and
3847 // (b) to update the state variables for all the questions we're going to send
3848 for (q
= m
->Questions
; q
; q
=q
->next
)
3850 if (q
->SendQNow
|| (ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
)))
3852 // If at least halfway to next query time, advance to next interval
3853 // If less than halfway to next query time, treat this as logically a repeat of the last transmission, without advancing the interval
3854 if (m
->timenow
- (q
->LastQTime
+ q
->ThisQInterval
/2) >= 0)
3856 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3857 q
->ThisQInterval
*= 2;
3858 if (q
->ThisQInterval
> MaxQuestionInterval
)
3859 q
->ThisQInterval
= MaxQuestionInterval
;
3860 else if (q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* 8)
3862 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents", q
->qname
.c
, DNSTypeName(q
->qtype
));
3863 ReconfirmAntecedents(m
, q
); // If sending third query, and no answers yet, time to begin doubting the source
3867 // Mark for sending. (If no active interfaces, then don't even try.)
3868 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3871 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3872 q
->LastQTime
= m
->timenow
;
3875 // If we recorded a duplicate suppression for this question less than half an interval ago,
3876 // then we consider it recent enough that we don't need to do an identical query ourselves.
3877 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3879 q
->LastQTxTime
= m
->timenow
;
3880 q
->RecentAnswers
= 0;
3882 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3883 SetNextQueryTime(m
,q
);
3887 // 2. Scan our authoritative RR list to see what probes we might need to send
3888 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
3890 m
->NextScheduledProbe
= m
->timenow
+ 0x78000000;
3892 if (m
->CurrentRecord
) LogMsg("SendQueries: ERROR m->CurrentRecord already set");
3893 m
->CurrentRecord
= m
->ResourceRecords
;
3894 while (m
->CurrentRecord
)
3896 AuthRecord
*rr
= m
->CurrentRecord
;
3897 m
->CurrentRecord
= rr
->next
;
3898 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3900 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3901 if (m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
3903 SetNextAnnounceProbeTime(m
, rr
);
3905 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3906 else if (rr
->ProbeCount
)
3908 // Mark for sending. (If no active interfaces, then don't even try.)
3909 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
3910 rr
->LastAPTime
= m
->timenow
;
3912 SetNextAnnounceProbeTime(m
, rr
);
3914 // else, if it has now finished probing, move it to state Verified, and update m->NextScheduledResponse so it will be announced
3918 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3919 rr
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3920 rr
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3921 SetNextAnnounceProbeTime(m
, rr
);
3922 // If we have any records on our duplicate list that match this one, they have now also completed probing
3923 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3924 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, rr
))
3926 CompleteProbing(m
, rr
);
3930 m
->CurrentRecord
= m
->DuplicateRecords
;
3931 while (m
->CurrentRecord
)
3933 AuthRecord
*rr
= m
->CurrentRecord
;
3934 m
->CurrentRecord
= rr
->next
;
3935 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& rr
->ProbeCount
== 0)
3936 CompleteProbing(m
, rr
);
3940 // 3. Now we know which queries and probes we're sending, go through our interface list sending the appropriate queries on each interface
3945 mDNSu8
*queryptr
= query
.data
;
3946 InitializeDNSMessage(&query
.h
, zeroID
, QueryFlags
);
3947 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3948 if (!KnownAnswerList
)
3950 // Start a new known-answer list
3951 CacheRecord
**kalistptr
= &KnownAnswerList
;
3952 mDNSu32 answerforecast
= 0;
3954 // Put query questions in this packet
3955 for (q
= m
->Questions
; q
; q
=q
->next
)
3956 if (q
->SendQNow
== intf
->InterfaceID
)
3958 debugf("SendQueries: %s question for %##s (%s) at %lu forecast total %lu",
3959 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3960 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- query
.data
, queryptr
+ answerforecast
- query
.data
);
3961 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3962 if (SuppressOnThisInterface(q
->DupSuppress
, intf
) ||
3963 BuildQuestion(m
, &query
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3964 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3967 // Put probe questions in this packet
3968 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3969 if (rr
->SendRNow
== intf
->InterfaceID
)
3971 mDNSBool ucast
= rr
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1;
3972 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3973 const mDNSu8
*const limit
= query
.data
+ ((query
.h
.numQuestions
) ? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3974 mDNSu8
*newptr
= putQuestion(&query
, queryptr
, limit
, &rr
->resrec
.name
, kDNSQType_ANY
, (mDNSu16
)(rr
->resrec
.rrclass
| ucbit
));
3975 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3976 mDNSu32 forecast
= answerforecast
+ 12 + rr
->resrec
.rdestimate
;
3977 if (newptr
&& newptr
+ forecast
< limit
)
3980 answerforecast
= forecast
;
3981 rr
->SendRNow
= (rr
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3982 rr
->IncludeInProbe
= mDNStrue
;
3983 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->ProbeCount
);
3987 verbosedebugf("SendQueries: Retracting Question %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
3988 query
.h
.numQuestions
--;
3993 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3994 while (KnownAnswerList
)
3996 CacheRecord
*rr
= KnownAnswerList
;
3997 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3998 mDNSu8
*newptr
= PutResourceRecordTTL(&query
, queryptr
, &query
.h
.numAnswers
, &rr
->resrec
, rr
->resrec
.rroriginalttl
- SecsSinceRcvd
);
4001 verbosedebugf("SendQueries: Put %##s (%s) at %lu - %lu", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), queryptr
- query
.data
, newptr
- query
.data
);
4003 KnownAnswerList
= rr
->NextInKAList
;
4004 rr
->NextInKAList
= mDNSNULL
;
4008 // If we ran out of space and we have more than one question in the packet, that's an error --
4009 // we shouldn't have put more than one question if there was a risk of us running out of space.
4010 if (query
.h
.numQuestions
> 1)
4011 LogMsg("SendQueries: Put %d answers; No more space for known answers", query
.h
.numAnswers
);
4012 query
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
4017 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4018 if (rr
->IncludeInProbe
)
4020 mDNSu8
*newptr
= PutResourceRecord(&query
, queryptr
, &query
.h
.numAuthorities
, &rr
->resrec
);
4021 rr
->IncludeInProbe
= mDNSfalse
;
4022 if (newptr
) queryptr
= newptr
;
4023 else LogMsg("SendQueries: How did we fail to have space for the Update record %##s (%s)?",
4024 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4027 if (queryptr
> query
.data
)
4029 if ((query
.h
.flags
.b
[0] & kDNSFlag0_TC
) && query
.h
.numQuestions
> 1)
4030 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet\n", query
.h
.numQuestions
);
4031 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
4032 query
.h
.numQuestions
, query
.h
.numQuestions
== 1 ? "" : "s",
4033 query
.h
.numAnswers
, query
.h
.numAnswers
== 1 ? "" : "s",
4034 query
.h
.numAuthorities
, query
.h
.numAuthorities
== 1 ? "" : "s", intf
->InterfaceID
);
4035 mDNSSendDNSMessage(m
, &query
, queryptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v4
, MulticastDNSPort
);
4036 mDNSSendDNSMessage(m
, &query
, queryptr
, intf
->InterfaceID
, MulticastDNSPort
, &AllDNSLinkGroup_v6
, MulticastDNSPort
);
4037 if (!m
->SuppressSending
) m
->SuppressSending
= (m
->timenow
+ mDNSPlatformOneSecond
/10) | 1; // OR with one to ensure non-zero
4038 if (++pktcount
>= 1000)
4039 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
4040 // There might be more records left in the known answer list, or more questions to send
4041 // on this interface, so go around one more time and try again.
4043 else // Nothing more to send on this interface; go to next
4045 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
4046 #if MDNS_DEBUGMSGS && 0
4047 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4048 debugf(msg
, intf
, next
);
4055 // ***************************************************************************
4056 #if COMPILER_LIKES_PRAGMA_MARK
4058 #pragma mark - RR List Management & Task Management
4061 // NOTE: AnswerQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4062 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4063 mDNSlocal
void AnswerQuestionWithResourceRecord(mDNS
*const m
, DNSQuestion
*q
, CacheRecord
*rr
, mDNSBool AddRecord
)
4065 verbosedebugf("AnswerQuestionWithResourceRecord:%4lu %s TTL%6lu %##s (%s)",
4066 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", rr
->resrec
.rroriginalttl
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4068 rr
->LastUsed
= m
->timenow
;
4070 if (ActiveQuestion(q
) && rr
->CRActiveQuestion
!= q
)
4072 if (!rr
->CRActiveQuestion
) m
->rrcache_active
++; // If not previously active, increment rrcache_active count
4073 rr
->CRActiveQuestion
= q
; // We know q is non-null
4074 SetNextCacheCheckTime(m
, rr
);
4077 // CAUTION: MUST NOT do anything more with q after calling q->Callback(), because the client's callback function
4078 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
4079 // Right now the only routines that call AnswerQuestionWithResourceRecord() are CacheRecordAdd(), CacheRecordRmv()
4080 // and AnswerNewQuestion(), and all of them use the "m->CurrentQuestion" mechanism to protect against questions
4081 // being deleted out from under them.
4082 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4083 if (q
->QuestionCallback
)
4084 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4085 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4088 // CacheRecordAdd is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4089 // If new questions are created as a result of invoking client callbacks, they will be added to
4090 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4091 // rr is a new CacheRecord just received into our cache
4092 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4093 // NOTE: CacheRecordAdd calls AnswerQuestionWithResourceRecord which can call a user callback,
4094 // which may change the record list and/or question list.
4095 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4096 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*rr
)
4098 if (m
->CurrentQuestion
) LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set");
4099 m
->CurrentQuestion
= m
->Questions
;
4100 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4102 DNSQuestion
*q
= m
->CurrentQuestion
;
4103 m
->CurrentQuestion
= q
->next
;
4104 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4106 // If this question is one that's actively sending queries, and it's received ten answers within one second of sending the last
4107 // query packet, then that indicates some radical network topology change, so reset its exponential backoff back to the start.
4108 // We must be at least at the eight-second interval to do this. If we're at the four-second interval, or less,
4109 // there's not much benefit accelerating because we will anyway send another query within a few seconds.
4110 // The first reset query is sent out randomized over the next four seconds to reduce possible synchronization between machines.
4111 if (ActiveQuestion(q
) && ++q
->RecentAnswers
>= 10 &&
4112 q
->ThisQInterval
> InitialQuestionInterval
*16 && m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
4114 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst; restarting exponential backoff sequence",
4115 q
->qname
.c
, DNSTypeName(q
->qtype
));
4116 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
4117 q
->ThisQInterval
= InitialQuestionInterval
;
4118 SetNextQueryTime(m
,q
);
4120 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
);
4121 q
->CurrentAnswers
++;
4122 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4123 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4124 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4125 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4128 m
->CurrentQuestion
= mDNSNULL
;
4131 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute
4132 // If new questions are created as a result of invoking client callbacks, they will be added to
4133 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4134 // rr is an existing cache CacheRecord that just expired and is being deleted
4135 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4136 // NOTE: CacheRecordRmv calls AnswerQuestionWithResourceRecord which can call a user callback,
4137 // which may change the record list and/or question list.
4138 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4139 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*rr
)
4141 if (m
->CurrentQuestion
) LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set");
4142 m
->CurrentQuestion
= m
->Questions
;
4143 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4145 DNSQuestion
*q
= m
->CurrentQuestion
;
4146 m
->CurrentQuestion
= q
->next
;
4147 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4149 verbosedebugf("CacheRecordRmv %p %##s (%s)", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4150 if (q
->CurrentAnswers
== 0)
4151 LogMsg("CacheRecordRmv ERROR: How can CurrentAnswers already be zero for %p %##s (%s)?", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
4154 q
->CurrentAnswers
--;
4155 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
4156 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
4158 if (q
->CurrentAnswers
== 0)
4160 debugf("CacheRecordRmv: Zero current answers for %##s (%s); will reconfirm antecedents", q
->qname
.c
, DNSTypeName(q
->qtype
));
4161 ReconfirmAntecedents(m
, q
);
4163 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNSfalse
);
4164 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4167 m
->CurrentQuestion
= mDNSNULL
;
4170 mDNSlocal
void ReleaseCacheRR(mDNS
*const m
, CacheRecord
*r
)
4172 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->rdatastorage
)
4173 mDNSPlatformMemFree(r
->resrec
.rdata
);
4174 r
->resrec
.rdata
= mDNSNULL
;
4175 r
->next
= m
->rrcache_free
;
4176 m
->rrcache_free
= r
;
4177 m
->rrcache_totalused
--;
4180 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, mDNSu32 slot
)
4182 CacheRecord
**rp
= &(m
->rrcache_hash
[slot
]);
4184 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4185 m
->lock_rrcache
= 1;
4189 CacheRecord
*const rr
= *rp
;
4190 mDNSs32 event
= RRExpireTime(rr
);
4191 if (m
->timenow
- event
>= 0) // If expired, delete it
4193 *rp
= rr
->next
; // Cut it from the list
4194 verbosedebugf("CheckCacheExpiration: Deleting %s", GetRRDisplayString(m
, rr
));
4195 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
4197 CacheRecordRmv(m
, rr
);
4198 m
->rrcache_active
--;
4200 m
->rrcache_used
[slot
]--;
4201 ReleaseCacheRR(m
, rr
);
4203 else // else, not expired; see if we need to query
4205 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
4207 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
4208 event
= rr
->NextRequiredQuery
; // then just record when we want the next query
4209 else // else trigger our question to go out now
4211 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4212 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4213 m
->NextScheduledQuery
= m
->timenow
;
4214 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTime(),
4215 // which will correctly update m->NextCacheCheck for us
4216 event
= m
->timenow
+ 0x3FFFFFFF;
4219 if (m
->NextCacheCheck
- (event
+ CacheCheckGracePeriod(rr
)) > 0)
4220 m
->NextCacheCheck
= (event
+ CacheCheckGracePeriod(rr
));
4224 if (m
->rrcache_tail
[slot
] != rp
) debugf("CheckCacheExpiration: Updating m->rrcache_tail[%d] from %p to %p", slot
, m
->rrcache_tail
[slot
], rp
);
4225 m
->rrcache_tail
[slot
] = rp
;
4226 m
->lock_rrcache
= 0;
4229 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
4231 mDNSBool ShouldQueryImmediately
= mDNStrue
;
4233 DNSQuestion
*q
= m
->NewQuestions
; // Grab the question we're going to answer
4234 mDNSu32 slot
= HashSlot(&q
->qname
);
4236 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4238 CheckCacheExpiration(m
, slot
);
4239 m
->NewQuestions
= q
->next
; // Advance NewQuestions to the next *after* calling CheckCacheExpiration();
4241 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4242 // This should be safe, because calling the client's question callback may cause the
4243 // question list to be modified, but should not ever cause the rrcache list to be modified.
4244 // If the client's question callback deletes the question, then m->CurrentQuestion will
4245 // be advanced, and we'll exit out of the loop
4246 m
->lock_rrcache
= 1;
4247 if (m
->CurrentQuestion
) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4248 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4249 for (rr
=m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
4250 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4252 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4253 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
4254 if (rr
->resrec
.rroriginalttl
<= SecsSinceRcvd
)
4256 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %##s (%s)",
4257 rr
->resrec
.rroriginalttl
, SecsSinceRcvd
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4258 continue; // Go to next one in loop
4261 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4262 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4263 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ShouldQueryImmediately
= mDNSfalse
;
4264 q
->CurrentAnswers
++;
4265 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4266 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4267 AnswerQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4268 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4269 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4271 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
4272 if (rr
->resrec
.namehash
== q
->qnamehash
&& SameDomainName(&rr
->resrec
.name
, &q
->qname
))
4273 ShouldQueryImmediately
= mDNSfalse
;
4275 if (ShouldQueryImmediately
&& m
->CurrentQuestion
== q
)
4277 q
->ThisQInterval
= InitialQuestionInterval
;
4278 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4279 m
->NextScheduledQuery
= m
->timenow
;
4281 m
->CurrentQuestion
= mDNSNULL
;
4282 m
->lock_rrcache
= 0;
4285 mDNSlocal
void AnswerLocalOnlyQuestionWithResourceRecord(mDNS
*const m
, DNSQuestion
*q
, AuthRecord
*rr
, mDNSBool AddRecord
)
4287 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
4288 if (AddRecord
) rr
->AnnounceCount
= InitialAnnounceCount
- 1;
4289 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4290 if (q
->QuestionCallback
)
4291 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4292 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4295 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
4297 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
4298 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewQuestions to the next (if any)
4300 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4302 if (m
->CurrentQuestion
) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4303 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4305 m
->CurrentRecord
= m
->LocalOnlyRecords
;
4306 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalOnlyRecords
)
4308 AuthRecord
*rr
= m
->CurrentRecord
;
4309 m
->CurrentRecord
= rr
->next
;
4310 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4312 AnswerLocalOnlyQuestionWithResourceRecord(m
, q
, rr
, mDNStrue
);
4313 // MUST NOT dereference q again after calling AnswerLocalOnlyQuestionWithResourceRecord()
4314 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4318 m
->CurrentQuestion
= mDNSNULL
;
4321 mDNSlocal
void AnswerLocalOnlyQuestions(mDNS
*const m
, AuthRecord
*rr
, mDNSBool AddRecord
)
4323 if (m
->CurrentQuestion
) LogMsg("AnswerLocalOnlyQuestions ERROR m->CurrentQuestion already set");
4324 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
4325 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
4327 DNSQuestion
*q
= m
->CurrentQuestion
;
4328 m
->CurrentQuestion
= q
->next
;
4329 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4331 debugf("AnswerLocalOnlyQuestions %p %##s (%s) %lu", rr
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
);
4332 AnswerLocalOnlyQuestionWithResourceRecord(m
, q
, rr
, AddRecord
);
4333 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4336 m
->CurrentQuestion
= mDNSNULL
;
4339 mDNSlocal
void DiscardLocalOnlyRecords(mDNS
*const m
)
4341 AuthRecord
*rr
= m
->LocalOnlyRecords
;
4344 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
4345 { AnswerLocalOnlyQuestions(m
, rr
, mDNSfalse
); CompleteDeregistration(m
, rr
); return; }
4346 if (rr
->ProbeCount
) { mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
); return; }
4349 m
->DiscardLocalOnlyRecords
= mDNSfalse
;
4352 mDNSlocal
void AnswerForNewLocalOnlyRecords(mDNS
*const m
)
4354 AuthRecord
*rr
= m
->NewLocalOnlyRecords
;
4355 m
->NewLocalOnlyRecords
= m
->NewLocalOnlyRecords
->next
;
4356 AnswerLocalOnlyQuestions(m
, rr
, mDNStrue
);
4359 mDNSlocal CacheRecord
*GetFreeCacheRR(mDNS
*const m
, mDNSu16 RDLength
)
4361 CacheRecord
*r
= mDNSNULL
;
4363 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
4364 m
->lock_rrcache
= 1;
4366 // If we have no free records, ask the client layer to give us some more memory
4367 if (!m
->rrcache_free
&& m
->MainCallback
)
4369 if (m
->rrcache_totalused
!= m
->rrcache_size
)
4370 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4371 m
->rrcache_totalused
, m
->rrcache_size
);
4373 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4374 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4375 // To guard against this, if we're actively using less than 1/32 of our cache, then we
4376 // purge all the unused records and recycle them, instead of allocating more memory.
4377 if (m
->rrcache_size
>= 512 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
4378 debugf("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4379 m
->rrcache_size
, m
->rrcache_active
);
4381 m
->MainCallback(m
, mStatus_GrowCache
);
4384 // If we still have no free records, recycle all the records we can.
4385 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4386 if (!m
->rrcache_free
)
4389 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
4392 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4394 CacheRecord
**rp
= &(m
->rrcache_hash
[slot
]);
4397 // Records that answer still-active questions are not candidates for deletion
4398 if ((*rp
)->CRActiveQuestion
)
4402 CacheRecord
*rr
= *rp
;
4403 *rp
= (*rp
)->next
; // Cut record from list
4404 m
->rrcache_used
[slot
]--; // Decrement counts
4405 ReleaseCacheRR(m
, rr
);
4408 if (m
->rrcache_tail
[slot
] != rp
) debugf("GetFreeCacheRR: Updating m->rrcache_tail[%d] from %p to %p", slot
, m
->rrcache_tail
[slot
], rp
);
4409 m
->rrcache_tail
[slot
] = rp
;
4412 debugf("Clear unused records; m->rrcache_totalused was %lu; now %lu", oldtotalused
, m
->rrcache_totalused
);
4416 if (m
->rrcache_free
) // If there are records in the free list, take one
4418 r
= m
->rrcache_free
;
4419 m
->rrcache_free
= r
->next
;
4424 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
4426 debugf("RR Cache now using %ld records", m
->rrcache_totalused
);
4427 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
4428 else m
->rrcache_report
+= 100;
4430 mDNSPlatformMemZero(r
, sizeof(*r
));
4431 r
->resrec
.rdata
= (RData
*)&r
->rdatastorage
; // By default, assume we're usually going to be using local storage
4433 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
4435 r
->resrec
.rdata
= (RData
*)mDNSPlatformMemAllocate(sizeofRDataHeader
+ RDLength
);
4436 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
4437 else { ReleaseCacheRR(m
, r
); r
= mDNSNULL
; }
4441 m
->lock_rrcache
= 0;
4446 mDNSlocal
void PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
4448 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4449 // a positive answer using an expired record (e.g. from an interface that has gone away).
4450 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4451 // summary deletion without giving the proper callback to any questions that are monitoring it.
4452 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4453 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
4454 rr
->UnansweredQueries
= MaxUnansweredQueries
;
4455 rr
->resrec
.rroriginalttl
= 0;
4456 SetNextCacheCheckTime(m
, rr
);
4459 mDNSlocal
void mDNS_Lock(mDNS
*const m
)
4461 // MUST grab the platform lock FIRST!
4462 mDNSPlatformLock(m
);
4464 // Normally, mDNS_reentrancy is zero and so is mDNS_busy
4465 // However, when we call a client callback mDNS_busy is one, and we increment mDNS_reentrancy too
4466 // If that client callback does mDNS API calls, mDNS_reentrancy and mDNS_busy will both be one
4467 // If mDNS_busy != mDNS_reentrancy that's a bad sign
4468 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
4469 LogMsg("mDNS_Lock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4471 // If this is an initial entry into the mDNSCore code, set m->timenow
4472 // else, if this is a re-entrant entry into the mDNSCore code, m->timenow should already be set
4473 if (m
->mDNS_busy
== 0)
4476 LogMsg("mDNS_Lock: m->timenow already set (%ld/%ld)", m
->timenow
, mDNSPlatformTimeNow() + m
->timenow_adjust
);
4477 m
->timenow
= mDNSPlatformTimeNow() + m
->timenow_adjust
;
4478 if (m
->timenow
== 0) m
->timenow
= 1;
4480 else if (m
->timenow
== 0)
4482 LogMsg("mDNS_Lock: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
4483 m
->timenow
= mDNSPlatformTimeNow() + m
->timenow_adjust
;
4484 if (m
->timenow
== 0) m
->timenow
= 1;
4487 if (m
->timenow_last
- m
->timenow
> 0)
4489 m
->timenow_adjust
+= m
->timenow_last
- m
->timenow
;
4490 LogMsg("mDNSPlatformTimeNow went backwards by %ld ticks; setting correction factor to %ld", m
->timenow_last
- m
->timenow
, m
->timenow_adjust
);
4491 m
->timenow
= m
->timenow_last
;
4493 m
->timenow_last
= m
->timenow
;
4495 // Increment mDNS_busy so we'll recognise re-entrant calls
4499 mDNSlocal mDNSs32
GetNextScheduledEvent(const mDNS
*const m
)
4501 mDNSs32 e
= m
->timenow
+ 0x78000000;
4502 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| m
->SleepState
) return(e
);
4503 if (m
->NewQuestions
) return(m
->timenow
);
4504 if (m
->NewLocalOnlyQuestions
) return(m
->timenow
);
4505 if (m
->NewLocalOnlyRecords
) return(m
->timenow
);
4506 if (m
->DiscardLocalOnlyRecords
) return(m
->timenow
);
4507 if (m
->SuppressSending
) return(m
->SuppressSending
);
4508 if (e
- m
->NextCacheCheck
> 0) e
= m
->NextCacheCheck
;
4509 if (e
- m
->NextScheduledQuery
> 0) e
= m
->NextScheduledQuery
;
4510 if (e
- m
->NextScheduledProbe
> 0) e
= m
->NextScheduledProbe
;
4511 if (e
- m
->NextScheduledResponse
> 0) e
= m
->NextScheduledResponse
;
4515 mDNSlocal
void mDNS_Unlock(mDNS
*const m
)
4517 // Decrement mDNS_busy
4520 // Check for locking failures
4521 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
)
4522 LogMsg("mDNS_Unlock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4524 // If this is a final exit from the mDNSCore code, set m->NextScheduledEvent and clear m->timenow
4525 if (m
->mDNS_busy
== 0)
4527 m
->NextScheduledEvent
= GetNextScheduledEvent(m
);
4528 if (m
->timenow
== 0) LogMsg("mDNS_Unlock: ERROR! m->timenow aready zero");
4532 // MUST release the platform lock LAST!
4533 mDNSPlatformUnlock(m
);
4536 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
4538 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
4540 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
4544 verbosedebugf("mDNS_Execute");
4545 if (m
->CurrentQuestion
) LogMsg("mDNS_Execute: ERROR! m->CurrentQuestion already set");
4547 // 1. If we're past the probe suppression time, we can clear it
4548 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
4550 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4551 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
4553 // 3. Purge our cache of stale old records
4554 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
4557 m
->NextCacheCheck
= m
->timenow
+ 0x3FFFFFFF;
4558 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++) CheckCacheExpiration(m
, slot
);
4561 // 4. See if we can answer any of our new local questions from the cache
4562 for (i
=0; m
->NewQuestions
&& i
<1000; i
++) AnswerNewQuestion(m
);
4563 if (i
>= 1000) debugf("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4565 for (i
=0; m
->DiscardLocalOnlyRecords
&& i
<1000; i
++) DiscardLocalOnlyRecords(m
);
4566 if (i
>= 1000) debugf("mDNS_Execute: DiscardLocalOnlyRecords exceeded loop limit");
4568 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
4569 if (i
>= 1000) debugf("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4571 for (i
=0; m
->NewLocalOnlyRecords
&& i
<1000; i
++) AnswerForNewLocalOnlyRecords(m
);
4572 if (i
>= 1000) debugf("mDNS_Execute: AnswerLocalOnlyQuestions exceeded loop limit");
4574 // 5. See what packets we need to send
4575 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| m
->SleepState
) DiscardDeregistrations(m
);
4576 else if (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0)
4578 // If the platform code is ready, and we're not suppressing packet generation right now
4579 // then send our responses, probes, and questions.
4580 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them
4581 // We send queries next, because there might be final-stage probes that complete their probing here, causing
4582 // them to advance to announcing state, and we want those to be included in any announcements we send out.
4583 // Finally, we send responses, including the previously mentioned records that just completed probing
4584 m
->SuppressSending
= 0;
4586 // 6. Send Query packets. This may cause some probing records to advance to announcing state
4587 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
4588 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
4590 LogMsg("mDNS_Execute: SendQueries didn't send all its queries; will try again in one second");
4591 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
4593 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
4595 LogMsg("mDNS_Execute: SendQueries didn't send all its probes; will try again in one second");
4596 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
4599 // 7. Send Response packets, including probing records just advanced to announcing state
4600 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
4601 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
4603 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4604 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
4608 m
->RandomQueryDelay
= 0; // Clear m->RandomQueryDelay, ready to pick a new different value, when necessary
4611 // Note about multi-threaded systems:
4612 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4613 // performing mDNS API operations that change our next scheduled event time.
4615 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
4616 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4617 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4618 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4619 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4620 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4621 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4622 // without blocking. This avoids the race condition between the signal from the other thread arriving
4623 // just *before* or just *after* the main thread enters the blocking primitive.
4625 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4626 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4627 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4628 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4629 // by the time it gets to the timer callback function).
4631 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4632 return(m
->NextScheduledEvent
);
4635 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
4636 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
4637 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
4638 // Note that sleep/wake calls do not have to be paired one-for-one; it is acceptable to call
4639 // mDNSCoreMachineSleep(m, mDNSfalse) any time there is reason to believe that the machine may have just
4640 // found itself in a new network environment. For example, if the Ethernet hardware indicates that the
4641 // cable has just been connected, the platform support layer should call mDNSCoreMachineSleep(m, mDNSfalse)
4642 // to make mDNSCore re-issue its outstanding queries, probe for record uniqueness, etc.
4643 // While it is safe to call mDNSCoreMachineSleep(m, mDNSfalse) at any time, it does cause extra network
4644 // traffic, so it should only be called when there is legitimate reason to believe the machine
4645 // may have become attached to a new network.
4646 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleepstate
)
4652 m
->SleepState
= sleepstate
;
4653 LogMsg("mDNSResponder %s at %ld", sleepstate
? "Sleeping" : "Waking", m
->timenow
);
4657 // Mark all the records we need to deregister and send them
4658 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4659 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->AnnounceCount
< InitialAnnounceCount
)
4660 rr
->ImmedAnswer
= mDNSInterfaceMark
;
4669 // 1. Retrigger all our questions
4670 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
4671 if (ActiveQuestion(q
))
4673 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
4674 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4675 q
->RecentAnswers
= 0;
4676 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
4677 m
->NextScheduledQuery
= m
->timenow
;
4680 // 2. Re-validate our cache records
4681 m
->NextCacheCheck
= m
->timenow
;
4682 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4683 for (cr
= m
->rrcache_hash
[slot
]; cr
; cr
=cr
->next
)
4684 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForCableDisconnect
);
4686 // 3. Retrigger probing and announcing for all our authoritative records
4687 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4689 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
4690 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
4691 if (rr
->AnnounceCount
< ReannounceCount
)
4692 rr
->AnnounceCount
= ReannounceCount
;
4693 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
4694 InitializeLastAPTime(m
, rr
);
4702 // ***************************************************************************
4703 #if COMPILER_LIKES_PRAGMA_MARK
4705 #pragma mark - Packet Reception Functions
4708 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
4710 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
4713 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
4714 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
4715 // The referenced record will definitely be acceptable (by recursive application of this rule)
4716 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
4717 rr
->NR_AdditionalTo
= add
;
4718 *nrpp
= &rr
->NextResponse
;
4720 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
4723 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
4725 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
4726 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
4728 mDNSu8
*responseptr
= response
->data
;
4729 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
4730 const mDNSu8
*ptr
= query
->data
;
4732 mDNSu32 maxttl
= 0x70000000;
4735 // Initialize the response fields so we can answer the questions
4736 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
4739 // *** 1. Write out the list of questions we are actually going to answer with this packet
4744 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4747 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
4748 if (!ptr
) return(mDNSNULL
);
4750 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
4752 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
4753 { // then put the question in the question section
4754 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
4755 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
4756 break; // break out of the ResponseRecords loop, and go on to the next question
4761 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
4765 // *** 2. Write Answers
4767 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4768 if (rr
->NR_AnswerTo
)
4770 mDNSu8
*p
= PutResourceRecordCappedTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
, maxttl
);
4771 if (p
) responseptr
= p
;
4772 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
4776 // *** 3. Write Additionals
4778 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4779 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
4781 mDNSu8
*p
= PutResourceRecordCappedTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
, maxttl
);
4782 if (p
) responseptr
= p
;
4783 else debugf("GenerateUnicastResponse: No more space for additionals");
4786 return(responseptr
);
4789 // AuthRecord *our is our Resource Record
4790 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
4791 // Returns 0 if there is no conflict
4792 // Returns +1 if there was a conflict and we won
4793 // Returns -1 if there was a conflict and we lost and have to rename
4794 mDNSlocal
int CompareRData(AuthRecord
*our
, CacheRecord
*pkt
)
4796 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
4797 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
4798 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
4799 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
4801 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
4802 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
4803 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
4804 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
4806 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
4807 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
4808 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
4809 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
4811 debugf("CompareRData: How did we get here?");
4815 // See if we have an authoritative record that's identical to this packet record,
4816 // whose canonical DependentOn record is the specified master record.
4817 // The DependentOn pointer is typically used for the TXT record of service registrations
4818 // It indicates that there is no inherent conflict detection for the TXT record
4819 // -- it depends on the SRV record to resolve name conflicts
4820 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
4821 // pointer chain (if any) to make sure we reach the canonical DependentOn record
4822 // If the record has no DependentOn, then just return that record's pointer
4823 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4824 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
4826 const AuthRecord
*r1
;
4827 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
4829 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4831 const AuthRecord
*r2
= r1
;
4832 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4833 if (r2
== master
) return(mDNStrue
);
4836 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
4838 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4840 const AuthRecord
*r2
= r1
;
4841 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4842 if (r2
== master
) return(mDNStrue
);
4848 // Find the canonical RRSet pointer for this RR received in a packet.
4849 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
4850 // pointers (if any) to make sure we return the canonical member of this name/type/class
4851 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4852 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
4854 const AuthRecord
*rr
;
4855 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4857 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
4859 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
4866 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
4867 // as one of our records (our) but different rdata.
4868 // 1. If our record is not a type that's supposed to be unique, we don't care.
4869 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
4870 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
4871 // points to our record, ignore this conflict (e.g. the packet record matches one of our
4872 // TXT records, and that record is marked as dependent on 'our', its SRV record).
4873 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
4874 // are members of the same RRSet, then this is not a conflict.
4875 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
4877 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
4879 // If not supposed to be unique, not a conflict
4880 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
4882 // If a dependent record, not a conflict
4883 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
4885 // If the pktrr matches a member of ourset, not a conflict
4886 if (FindRRSet(m
, pktrr
) == ourset
) return(mDNSfalse
);
4888 // Okay, this is a conflict
4892 // NOTE: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
4893 // the record list and/or question list.
4894 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4895 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4896 DNSQuestion
*q
, AuthRecord
*our
)
4899 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
4900 mDNSBool FoundUpdate
= mDNSfalse
;
4902 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
4904 LargeCacheRecord pkt
;
4905 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, 0, &pkt
);
4907 if (ResourceRecordAnswersQuestion(&pkt
.r
.resrec
, q
))
4909 FoundUpdate
= mDNStrue
;
4910 if (PacketRRConflict(m
, our
, &pkt
.r
))
4912 int result
= (int)our
->resrec
.rrclass
- (int)pkt
.r
.resrec
.rrclass
;
4913 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)pkt
.r
.resrec
.rrtype
;
4914 if (!result
) result
= CompareRData(our
, &pkt
.r
);
4917 case 1: debugf("ResolveSimultaneousProbe: %##s (%s): We won", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4920 case -1: debugf("ResolveSimultaneousProbe: %##s (%s): We lost", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4921 mDNS_Deregister_internal(m
, our
, mDNS_Dereg_conflict
);
4928 debugf("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
.c
, DNSTypeName(our
->resrec
.rrtype
));
4931 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, ResourceRecord
*pktrr
)
4934 for (rr
= m
->rrcache_hash
[HashSlot(&pktrr
->name
)]; rr
; rr
=rr
->next
)
4935 if (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
&& IdenticalResourceRecord(pktrr
, &rr
->resrec
)) break;
4939 // ProcessQuery examines a received query to see if we have any answers to give
4940 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4941 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
4942 DNSMessage
*const response
)
4944 AuthRecord
*ResponseRecords
= mDNSNULL
;
4945 AuthRecord
**nrp
= &ResponseRecords
;
4946 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
4947 CacheRecord
**eap
= &ExpectedAnswers
;
4948 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
4949 DNSQuestion
**dqp
= &DupQuestions
;
4950 mDNSBool delayresponse
= mDNSfalse
;
4951 mDNSBool HaveUnicastAnswer
= mDNSfalse
;
4952 const mDNSu8
*ptr
= query
->data
;
4953 mDNSu8
*responseptr
= mDNSNULL
;
4954 AuthRecord
*rr
, *rr2
;
4957 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet.
4958 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNStrue
;
4961 // *** 1. Parse Question Section and mark potential answers
4963 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4965 mDNSBool QuestionNeedsMulticastResponse
;
4966 int NumAnswersForThisQuestion
= 0;
4967 DNSQuestion pktq
, *q
;
4968 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
4969 if (!ptr
) goto exit
;
4971 // The only queries that *need* a multicast response are:
4972 // * Queries sent via multicast
4974 // * that don't have the kDNSQClass_UnicastResponse bit set
4975 // These queries need multicast responses because other clients will:
4976 // * suppress their own identical questions when they see these questions, and
4977 // * expire their cache records if they don't see the expected responses
4978 // For other queries, we may still choose to send the occasional multicast response anyway,
4979 // to keep our neighbours caches warm, and for ongoing conflict detection.
4980 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
4981 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
4982 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
4984 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
4985 // can result in user callbacks which may change the record list and/or question list.
4986 // Also note: we just mark potential answer records here, without trying to build the
4987 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
4988 // from that list while we're in the middle of trying to build it.
4989 if (m
->CurrentRecord
) LogMsg("ProcessQuery ERROR m->CurrentRecord already set");
4990 m
->CurrentRecord
= m
->ResourceRecords
;
4991 while (m
->CurrentRecord
)
4993 rr
= m
->CurrentRecord
;
4994 m
->CurrentRecord
= rr
->next
;
4995 if (ResourceRecordAnswersQuestion(&rr
->resrec
, &pktq
))
4997 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
4998 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
4999 else if (ResourceRecordIsValidAnswer(rr
))
5001 NumAnswersForThisQuestion
++;
5003 // NR_AnswerTo pointing into query packet means "answer via unicast"
5004 // (may also choose to do multicast as well)
5005 // NR_AnswerTo == ~0 means "definitely answer via multicast" (can't downgrade to unicast later)
5006 if (QuestionNeedsMulticastResponse
)
5008 // We only mark this question for sending if it is at least one second since the last time we multicast it
5009 // on this interface. If it is more than a second, or LastMCInterface is different, then we should multicast it.
5010 // This is to guard against the case where someone blasts us with queries as fast as they can.
5011 if (m
->timenow
- (rr
->LastMCTime
+ mDNSPlatformOneSecond
) >= 0 ||
5012 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
5013 rr
->NR_AnswerTo
= (mDNSu8
*)~0;
5015 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= ptr
;
5020 // We only do the following accelerated cache expiration processing and duplicate question suppression processing
5021 // for multicast queries with multicast responses.
5022 // For any query generating a unicast response we don't do this because we can't assume we will see the response
5023 if (QuestionNeedsMulticastResponse
)
5026 // If we couldn't answer this question, someone else might be able to,
5027 // so use random delay on response to reduce collisions
5028 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNStrue
;
5030 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5031 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5032 for (rr
= m
->rrcache_hash
[HashSlot(&pktq
.qname
)]; rr
; rr
=rr
->next
)
5033 if (ResourceRecordAnswersQuestion(&rr
->resrec
, &pktq
) && rr
->resrec
.rdlength
<= SmallRecordLimit
)
5034 if (!rr
->NextInKAList
&& eap
!= &rr
->NextInKAList
)
5037 eap
= &rr
->NextInKAList
;
5038 if (rr
->MPUnansweredQ
== 0 || m
->timenow
- rr
->MPLastUnansweredQT
>= mDNSPlatformOneSecond
)
5040 // Although MPUnansweredQ is only really used for multi-packet query processing,
5041 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5042 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5043 rr
->MPUnansweredQ
++;
5044 rr
->MPLastUnansweredQT
= m
->timenow
;
5045 rr
->MPExpectingKA
= mDNStrue
;
5049 // Check if this question is the same as any of mine.
5050 // We only do this for non-truncated queries. Right now it would be too complicated to try
5051 // to keep track of duplicate suppression state between multiple packets, especially when we
5052 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5053 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5054 for (q
= m
->Questions
; q
; q
=q
->next
)
5055 if (ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
5056 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
5057 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
5058 if (q
->qtype
== pktq
.qtype
&& q
->qclass
== pktq
.qclass
&& q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
5059 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
5064 // *** 2. Now we can safely build the list of marked answers
5066 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
5067 if (rr
->NR_AnswerTo
) // If we marked the record...
5069 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
5070 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNStrue
;
5074 // *** 3. Add additional records
5076 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
5078 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
5079 // later in the "for" loop, and we will follow further "additional" links then.)
5080 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
5081 AddRecordToResponseList(&nrp
, rr
->Additional1
, rr
);
5083 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
5084 AddRecordToResponseList(&nrp
, rr
->Additional2
, rr
);
5086 // For SRV records, automatically add the Address record(s) for the target host
5087 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
5088 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
5089 if (RRIsAddressType(rr2
) && // For all address records (A/AAAA) ...
5090 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
5091 rr
->resrec
.rdnamehash
== rr2
->resrec
.namehash
&&
5092 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, &rr2
->resrec
.name
)) // ... whose name is the name of the SRV target
5093 AddRecordToResponseList(&nrp
, rr2
, rr
);
5097 // *** 4. Parse Answer Section and cancel any records disallowed by Known-Answer list
5099 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
5101 // Get the record...
5102 LargeCacheRecord pkt
;
5104 CacheRecord
*ourcacherr
;
5105 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &pkt
);
5106 if (!ptr
) goto exit
;
5108 // See if this Known-Answer suppresses any of our currently planned answers
5109 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5110 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&pkt
.r
, rr
))
5111 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5113 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5114 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
5116 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5117 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&pkt
.r
, rr
))
5119 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5121 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zeroIPAddr
;
5123 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5125 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
5127 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->ImmedAnswer
= mDNSNULL
;
5131 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5132 // 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).
5133 ourcacherr
= FindIdenticalRecordInCache(m
, &pkt
.r
.resrec
);
5134 if (ourcacherr
&& ourcacherr
->MPExpectingKA
&& m
->timenow
- ourcacherr
->MPLastUnansweredQT
< mDNSPlatformOneSecond
)
5136 ourcacherr
->MPUnansweredKA
++;
5137 ourcacherr
->MPExpectingKA
= mDNSfalse
;
5140 // Having built our ExpectedAnswers list from the questions in this packet, we can definitively
5141 // remove from our ExpectedAnswers list any records that are suppressed in the very same packet.
5142 // For answers that are suppressed in subsequent KA list packets, we rely on the MPQ/MPKA counting to track them.
5143 eap
= &ExpectedAnswers
;
5146 CacheRecord
*rr
= *eap
;
5147 if (rr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&pkt
.r
.resrec
, &rr
->resrec
))
5148 { *eap
= rr
->NextInKAList
; rr
->NextInKAList
= mDNSNULL
; }
5149 else eap
= &rr
->NextInKAList
;
5152 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5155 dqp
= &DupQuestions
;
5158 DNSQuestion
*q
= *dqp
;
5159 if (ResourceRecordAnswersQuestion(&pkt
.r
.resrec
, q
))
5160 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
5161 else dqp
= &q
->NextInDQList
;
5167 // *** 5. Cancel any additionals that were added because of now-deleted records
5169 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5170 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
5171 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5174 // *** 6. Mark the send flags on the records we plan to send
5176 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5178 if (rr
->NR_AnswerTo
)
5180 mDNSBool SendMulticastResponse
= mDNSfalse
;
5182 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
5183 if (m
->timenow
- (rr
->LastMCTime
+ TicksTTL(rr
)/4) >= 0) SendMulticastResponse
= mDNStrue
;
5185 // If the client insists on a multicast response, then we'd better send one
5186 if (rr
->NR_AnswerTo
== (mDNSu8
*)~0) SendMulticastResponse
= mDNStrue
;
5187 else if (rr
->NR_AnswerTo
) HaveUnicastAnswer
= mDNStrue
;
5189 if (SendMulticastResponse
)
5191 // If we're already planning to send this on another interface, just send it on all interfaces
5192 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
5194 rr
->ImmedAnswer
= mDNSInterfaceMark
;
5195 m
->NextScheduledResponse
= m
->timenow
;
5196 debugf("ProcessQuery: %##s (%s) : Will send on all interfaces", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5200 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
5201 m
->NextScheduledResponse
= m
->timenow
;
5202 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5204 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
5205 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
5207 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5209 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
5210 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
5215 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== (mDNSu8
*)~0)
5217 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
5218 // If two clients on different interfaces do queries that invoke the same optional additional answer,
5219 // then the earlier client is out of luck
5220 rr
->ImmedAdditional
= InterfaceID
;
5221 // No need to set m->NextScheduledResponse here
5222 // We'll send these additional records when we send them, or not, as the case may be
5227 // *** 7. If we think other machines are likely to answer these questions, set our packet suppression timer
5229 if (delayresponse
&& !m
->SuppressSending
)
5231 // Pick a random delay between 20ms and 120ms.
5232 m
->SuppressSending
= m
->timenow
+ (mDNSPlatformOneSecond
*2 + (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*10)) / 100;
5233 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
5237 // *** 8. If query is from a legacy client, generate a unicast response too
5239 if (HaveUnicastAnswer
)
5240 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
5244 // *** 9. Finally, clear our link chains ready for use next time
5246 while (ResponseRecords
)
5248 rr
= ResponseRecords
;
5249 ResponseRecords
= rr
->NextResponse
;
5250 rr
->NextResponse
= mDNSNULL
;
5251 rr
->NR_AnswerTo
= mDNSNULL
;
5252 rr
->NR_AdditionalTo
= mDNSNULL
;
5255 while (ExpectedAnswers
)
5258 rr
= ExpectedAnswers
;
5259 ExpectedAnswers
= rr
->NextInKAList
;
5260 rr
->NextInKAList
= mDNSNULL
;
5262 // For non-truncated queries, we can definitively say that we should expect
5263 // to be seeing a response for any records still left in the ExpectedAnswers list
5264 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5265 if (rr
->UnansweredQueries
== 0 || m
->timenow
- rr
->LastUnansweredTime
>= mDNSPlatformOneSecond
)
5267 rr
->UnansweredQueries
++;
5268 rr
->LastUnansweredTime
= m
->timenow
;
5269 if (rr
->UnansweredQueries
> 1)
5270 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
5271 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5272 SetNextCacheCheckTime(m
, rr
);
5275 // If we've seen multiple unanswered queries for this record,
5276 // then mark it to expire in five seconds if we don't get a response by then.
5277 if (rr
->UnansweredQueries
>= MaxUnansweredQueries
)
5279 // Only show debugging message if this record was not about to expire anyway
5280 if (RRExpireTime(rr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5281 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5282 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5283 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
5285 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
5286 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
5287 // possible packet loss of up to 20% of the additional KA packets.)
5288 else if (rr
->MPUnansweredQ
* 4 > rr
->MPUnansweredKA
* 5 + 8)
5290 // We want to do this conservatively.
5291 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
5292 // then we don't want them to all hit the network simultaneously with their final expiration queries.
5293 // By setting the record to expire in four minutes, we achieve two things:
5294 // (a) the 90-95% final expiration queries will be less bunched together
5295 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
5296 mDNSu32 remain
= (mDNSu32
)(RRExpireTime(rr
) - m
->timenow
) / 4;
5297 if (remain
> 240 * (mDNSu32
)mDNSPlatformOneSecond
)
5298 remain
= 240 * (mDNSu32
)mDNSPlatformOneSecond
;
5300 // Only show debugging message if this record was not about to expire anyway
5301 if (RRExpireTime(rr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5302 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5303 rr
->UnansweredQueries
, rr
->MPUnansweredQ
, rr
->MPUnansweredKA
, GetRRDisplayString(m
, rr
));
5305 if (remain
<= 60 * (mDNSu32
)mDNSPlatformOneSecond
)
5306 rr
->UnansweredQueries
++; // Treat this as equivalent to one definite unanswered query
5307 rr
->MPUnansweredQ
= 0; // Clear MPQ/MPKA statistics
5308 rr
->MPUnansweredKA
= 0;
5309 rr
->MPExpectingKA
= mDNSfalse
;
5311 if (remain
< kDefaultReconfirmTimeForNoAnswer
)
5312 remain
= kDefaultReconfirmTimeForNoAnswer
;
5313 mDNS_Reconfirm_internal(m
, rr
, remain
);
5317 while (DupQuestions
)
5320 DNSQuestion
*q
= DupQuestions
;
5321 DupQuestions
= q
->NextInDQList
;
5322 q
->NextInDQList
= mDNSNULL
;
5323 i
= RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
5324 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
5325 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6", i
);
5328 return(responseptr
);
5331 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
5332 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
5333 const mDNSInterfaceID InterfaceID
)
5335 DNSMessage response
;
5336 const mDNSu8
*responseend
= mDNSNULL
;
5338 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",
5339 srcaddr
, (mDNSu16
)srcport
.b
[0]<<8 | srcport
.b
[1],
5340 dstaddr
, (mDNSu16
)dstport
.b
[0]<<8 | dstport
.b
[1],
5342 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
5343 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
5344 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5345 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? "" : "s");
5347 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
5348 (srcport
.NotAnInteger
!= MulticastDNSPort
.NotAnInteger
), mDNSAddrIsDNSMulticast(dstaddr
), &response
);
5350 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
5352 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
5353 response
.h
.numQuestions
, response
.h
.numQuestions
== 1 ? "" : "s",
5354 response
.h
.numAnswers
, response
.h
.numAnswers
== 1 ? "" : "s",
5355 response
.h
.numAdditionals
, response
.h
.numAdditionals
== 1 ? "" : "s",
5356 srcaddr
, (mDNSu16
)srcport
.b
[0]<<8 | srcport
.b
[1], InterfaceID
, srcaddr
->type
);
5357 mDNSSendDNSMessage(m
, &response
, responseend
, InterfaceID
, dstport
, srcaddr
, srcport
);
5361 // NOTE: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
5362 // the record list and/or question list.
5363 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5364 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
5365 const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, const mDNSAddr
*dstaddr
,
5366 const mDNSInterfaceID InterfaceID
, mDNSu8 ttl
)
5369 const mDNSu8
*ptr
= LocateAnswers(response
, end
); // We ignore questions (if any) in a DNS response packet
5370 CacheRecord
*CacheFlushRecords
= mDNSNULL
;
5371 CacheRecord
**cfp
= &CacheFlushRecords
;
5373 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
5374 // to guard against spoof responses, then the only credible protection against that is cryptographic
5375 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
5376 int totalrecords
= response
->h
.numAnswers
+ response
->h
.numAuthorities
+ response
->h
.numAdditionals
;
5378 (void)srcaddr
; // Currently used only for display in debugging message
5380 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",
5381 srcaddr
, dstaddr
, InterfaceID
, ttl
,
5382 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5383 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5384 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5385 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5387 // TTL should be 255
5388 // In the case of overlayed subnets that aren't using RFC 3442, some packets may incorrectly
5389 // go to the router first and then come back with a TTL of 254, so we allow that too.
5390 // Anything lower than 254 is a pretty good sign of an off-net spoofing attack.
5391 // Also, if we get a unicast response when we weren't expecting one, then we assume it is someone trying to spoof us
5392 if (ttl
< 254 || (!mDNSAddrIsDNSMulticast(dstaddr
) && (mDNSu32
)(m
->timenow
- m
->ExpectUnicastResponse
) > (mDNSu32
)mDNSPlatformOneSecond
))
5394 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",
5395 srcaddr
, dstaddr
, ttl
, InterfaceID
,
5396 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5397 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5398 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5399 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5403 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
5405 LargeCacheRecord pkt
;
5406 const mDNSu8 RecordType
= (mDNSu8
)((i
< response
->h
.numAnswers
) ? kDNSRecordTypePacketAns
: kDNSRecordTypePacketAdd
);
5407 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &pkt
);
5408 if (!ptr
) break; // Break out of the loop and clean up our CacheFlushRecords list before exiting
5410 // 1. Check that this packet resource record does not conflict with any of ours
5411 if (m
->CurrentRecord
) LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set");
5412 m
->CurrentRecord
= m
->ResourceRecords
;
5413 while (m
->CurrentRecord
)
5415 AuthRecord
*rr
= m
->CurrentRecord
;
5416 m
->CurrentRecord
= rr
->next
;
5417 if (PacketRRMatchesSignature(&pkt
.r
, rr
)) // If interface, name, type (if verified) and class match...
5419 // ... check to see if rdata is identical
5420 if (SameRData(&pkt
.r
.resrec
, &rr
->resrec
))
5422 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
5423 if (pkt
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
5425 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
5426 if (rr
->ImmedAnswer
== InterfaceID
) rr
->ImmedAnswer
= mDNSNULL
;
5430 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
5431 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5436 // else, the packet RR has different rdata -- check to see if this is a conflict
5437 if (pkt
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &pkt
.r
))
5439 debugf("mDNSCoreReceiveResponse: Our Record: %08X %08X %s", rr
-> resrec
.rdatahash
, rr
-> resrec
.rdnamehash
, GetRRDisplayString(m
, rr
));
5440 debugf("mDNSCoreReceiveResponse: Pkt Record: %08X %08X %s", pkt
.r
.resrec
.rdatahash
, pkt
.r
.resrec
.rdnamehash
, GetRRDisplayString(m
, &pkt
.r
));
5442 // If this record is marked DependentOn another record for conflict detection purposes,
5443 // then *that* record has to be bumped back to probing state to resolve the conflict
5444 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
5446 // If we've just whacked this record's ProbeCount, don't need to do it again
5447 if (rr
->ProbeCount
<= DefaultProbeCountForTypeUnique
)
5449 // If we'd previously verified this record, put it back to probing state and try again
5450 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
5452 debugf("mDNSCoreReceiveResponse: Reseting to Probing: %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5453 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5454 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
5455 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(kDNSRecordTypeUnique
);
5456 InitializeLastAPTime(m
, rr
);
5457 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
5459 // If we're probing for this record, we just failed
5460 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
5462 debugf("mDNSCoreReceiveResponse: Will rename %##s (%s)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5463 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5465 // We assumed this record must be unique, but we were wrong.
5466 // (e.g. There are two mDNSResponders on the same machine giving
5467 // different answers for the reverse mapping record.)
5468 // This is simply a misconfiguration, and we don't try to recover from it.
5469 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
5471 debugf("mDNSCoreReceiveResponse: Unexpected conflict on %##s (%s) -- discarding our record",
5472 rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5473 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5476 debugf("mDNSCoreReceiveResponse: Unexpected record type %X %##s (%s)",
5477 rr
->resrec
.RecordType
, rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
));
5480 // Else, matching signature, different rdata, but not a considered a conflict.
5481 // If the packet record has the cache-flush bit set, then we check to see if we have to re-assert our record(s)
5482 // to rescue them (see note about "multi-homing and bridged networks" at the end of this function).
5483 else if ((pkt
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && m
->timenow
- rr
->LastMCTime
> mDNSPlatformOneSecond
/2)
5484 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5489 // 2. See if we want to add this packet resource record to our cache
5490 if (m
->rrcache_size
) // Only try to cache answers if we have a cache to put them in
5492 mDNSu32 slot
= HashSlot(&pkt
.r
.resrec
.name
);
5494 // 2a. Check if this packet resource record is already in our cache
5495 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
5497 // If we found this exact resource record, refresh its TTL
5498 if (rr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&pkt
.r
.resrec
, &rr
->resrec
))
5500 if (pkt
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5501 verbosedebugf("Found record size %5d interface %p already in cache: %s",
5502 pkt
.r
.resrec
.rdlength
, InterfaceID
, GetRRDisplayString(m
, &pkt
.r
));
5503 rr
->TimeRcvd
= m
->timenow
;
5505 if (pkt
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
5507 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
5508 if (rr
->NextInCFList
== mDNSNULL
&& cfp
!= &rr
->NextInCFList
)
5509 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; }
5511 // If this packet record is marked unique, and our previous cached copy was not, then fix it
5512 if (!(rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
5515 for (q
= m
->Questions
; q
; q
=q
->next
) if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) q
->UniqueAnswers
++;
5516 rr
->resrec
.RecordType
= pkt
.r
.resrec
.RecordType
;
5520 if (pkt
.r
.resrec
.rroriginalttl
> 0)
5522 rr
->resrec
.rroriginalttl
= pkt
.r
.resrec
.rroriginalttl
;
5523 rr
->UnansweredQueries
= 0;
5524 rr
->MPUnansweredQ
= 0;
5525 rr
->MPUnansweredKA
= 0;
5526 rr
->MPExpectingKA
= mDNSfalse
;
5530 // If the packet TTL is zero, that means we're deleting this record.
5531 // To give other hosts on the network a chance to protest, we push the deletion
5532 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
5533 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
5534 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
5535 rr
->resrec
.rroriginalttl
= 1;
5536 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5538 SetNextCacheCheckTime(m
, rr
);
5543 // If packet resource record not in our cache, add it now
5544 // (unless it is just a deletion of a record we never had, in which case we don't care)
5545 if (!rr
&& pkt
.r
.resrec
.rroriginalttl
> 0)
5547 rr
= GetFreeCacheRR(m
, pkt
.r
.resrec
.rdlength
);
5548 if (!rr
) debugf("No cache space to add record for %#s", pkt
.r
.resrec
.name
.c
);
5551 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
5553 rr
->resrec
.rdata
= saveptr
; // and then restore it after the structure assignment
5554 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
5555 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; }
5556 // If this is an oversized record with external storage allocated, copy rdata to external storage
5557 if (pkt
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5558 mDNSPlatformMemCopy(pkt
.r
.resrec
.rdata
, rr
->resrec
.rdata
, sizeofRDataHeader
+ pkt
.r
.resrec
.rdlength
);
5559 rr
->next
= mDNSNULL
; // Clear 'next' pointer
5560 *(m
->rrcache_tail
[slot
]) = rr
; // Append this record to tail of cache slot list
5561 m
->rrcache_tail
[slot
] = &(rr
->next
); // Advance tail pointer
5562 m
->rrcache_used
[slot
]++;
5563 //debugf("Adding RR %##s to cache (%d)", pkt.r.name.c, m->rrcache_used);
5564 CacheRecordAdd(m
, rr
);
5565 // MUST do this AFTER CacheRecordAdd(), because that's what sets CRActiveQuestion for us
5566 SetNextCacheCheckTime(m
, rr
);
5572 // If we've just received one or more records with their cache flush bits set,
5573 // then scan that cache slot to see if there are any old stale records we need to flush
5574 while (CacheFlushRecords
)
5576 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
5577 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
5578 r1
->NextInCFList
= mDNSNULL
;
5579 for (r2
= m
->rrcache_hash
[HashSlot(&r1
->resrec
.name
)]; r2
; r2
=r2
->next
)
5580 if (SameResourceRecordSignature(&r1
->resrec
, &r2
->resrec
) && m
->timenow
- r2
->TimeRcvd
> mDNSPlatformOneSecond
)
5582 verbosedebugf("Cache flush %p X %p %##s (%s)", r1
, r2
, r2
->resrec
.name
.c
, DNSTypeName(r2
->resrec
.rrtype
));
5583 // We set stale records to expire in one second.
5584 // This gives the owner a chance to rescue it if necessary.
5585 // This is important in the case of multi-homing and bridged networks:
5586 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
5587 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
5588 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
5589 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
5590 // By delaying the deletion by one second, we give X a change to notice that this bridging has
5591 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
5592 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
5593 // final expiration queries for this record.
5594 r2
->resrec
.rroriginalttl
= 1;
5595 r2
->TimeRcvd
= m
->timenow
;
5596 r2
->UnansweredQueries
= MaxUnansweredQueries
;
5597 SetNextCacheCheckTime(m
, r2
);
5602 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
5603 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*const dstaddr
, const mDNSIPPort dstport
,
5604 const mDNSInterfaceID InterfaceID
, mDNSu8 ttl
)
5606 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
5607 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
5608 const mDNSu8 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
5610 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
5611 mDNSu8
*ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
5612 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
5613 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
5614 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
5615 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
5617 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
5619 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
5620 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
5621 if (!mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
5624 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
5625 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, dstaddr
, InterfaceID
, ttl
);
5626 else debugf("Unknown DNS packet type %02X%02X (ignored)", msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1]);
5628 // Packet reception often causes a change to the task list:
5629 // 1. Inbound queries can cause us to need to send responses
5630 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
5631 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
5632 // 4. Response packets that answer questions may cause our client to issue new questions
5636 // ***************************************************************************
5637 #if COMPILER_LIKES_PRAGMA_MARK
5640 #pragma mark - Searcher Functions
5643 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
5646 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
5647 // This prevents circular references, where two questions are each marked as a duplicate of the other.
5648 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
5649 // further in the list.
5650 for (q
= m
->Questions
; q
&& q
!= question
; q
=q
->next
) // Scan our list of questions
5651 if (q
->InterfaceID
== question
->InterfaceID
&& // for another question with the same InterfaceID,
5652 q
->qtype
== question
->qtype
&& // type,
5653 q
->qclass
== question
->qclass
&& // class,
5654 q
->qnamehash
== question
->qnamehash
&&
5655 SameDomainName(&q
->qname
, &question
->qname
)) // and name
5660 // This is called after a question is deleted, in case other identical questions were being
5661 // suppressed as duplicates
5662 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, const DNSQuestion
*const question
)
5665 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5666 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
5668 q
->ThisQInterval
= question
->ThisQInterval
;
5669 q
->LastQTime
= question
->LastQTime
;
5670 q
->RecentAnswers
= 0;
5671 q
->DuplicateOf
= FindDuplicateQuestion(m
, q
);
5672 q
->LastQTxTime
= question
->LastQTxTime
;
5673 SetNextQueryTime(m
,q
);
5677 mDNSlocal mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
5679 #if TEST_LOCALONLY_FOR_EVERYTHING
5680 question
->InterfaceID
= (mDNSInterfaceID
)~0;
5682 if (m
->rrcache_size
== 0) // Can't do queries if we have no cache space allocated
5683 return(mStatus_NoCache
);
5687 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
5688 DNSQuestion
**q
= &m
->Questions
;
5689 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0)) q
= &m
->LocalOnlyQuestions
;
5690 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
5694 LogMsg("Error! Tried to add a question %##s (%s) that's already in the active list",
5695 question
->qname
.c
, DNSTypeName(question
->qtype
));
5696 return(mStatus_AlreadyRegistered
);
5699 // If this question is referencing a specific interface, make sure it exists
5700 if (question
->InterfaceID
&& question
->InterfaceID
!= ((mDNSInterfaceID
)~0))
5702 NetworkInterfaceInfo
*intf
;
5703 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
5704 if (intf
->InterfaceID
== question
->InterfaceID
) break;
5707 debugf("mDNS_StartQuery_internal: Question %##s InterfaceID %p not found", question
->qname
.c
, question
->InterfaceID
);
5708 return(mStatus_BadReferenceErr
);
5712 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
5713 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
5714 // be a waste. For that reason, we schedule our first query to go out in half a second. If AnswerNewQuestion() finds
5715 // that we have *no* relevant answers currently in our cache, then it will accelerate that to go out immediately.
5716 if (!ValidateDomainName(&question
->qname
))
5718 LogMsg("Attempt to start query with invalid qname %##s %s", question
->qname
.c
, DNSTypeName(question
->qtype
));
5719 return(mStatus_Invalid
);
5722 if (!m
->RandomQueryDelay
) m
->RandomQueryDelay
= 1 + (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
5724 question
->next
= mDNSNULL
;
5725 question
->qnamehash
= DomainNameHashValue(&question
->qname
); // MUST do this before FindDuplicateQuestion()
5726 question
->ThisQInterval
= InitialQuestionInterval
* 2; // MUST be > zero for an active question
5727 question
->LastQTime
= m
->timenow
- m
->RandomQueryDelay
; // Avoid inter-machine synchronization
5728 question
->RecentAnswers
= 0;
5729 question
->CurrentAnswers
= 0;
5730 question
->LargeAnswers
= 0;
5731 question
->UniqueAnswers
= 0;
5732 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
5733 question
->NextInDQList
= mDNSNULL
;
5734 for (i
=0; i
<DupSuppressInfoSize
; i
++)
5735 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
5736 // question->InterfaceID must be already set by caller
5737 question
->SendQNow
= mDNSNULL
;
5738 question
->SendOnAll
= mDNSfalse
;
5739 question
->LastQTxTime
= m
->timenow
;
5741 if (!question
->DuplicateOf
)
5742 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) started",
5743 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, question
);
5745 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) duplicate of (%p)",
5746 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, question
, question
->DuplicateOf
);
5749 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0))
5751 if (!m
->NewLocalOnlyQuestions
) m
->NewLocalOnlyQuestions
= question
;
5755 if (!m
->NewQuestions
) m
->NewQuestions
= question
;
5756 SetNextQueryTime(m
,question
);
5759 return(mStatus_NoError
);
5763 mDNSlocal mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
5766 DNSQuestion
**q
= &m
->Questions
;
5767 if (question
->InterfaceID
== ((mDNSInterfaceID
)~0)) q
= &m
->LocalOnlyQuestions
;
5768 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
5769 if (*q
) *q
= (*q
)->next
;
5772 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
5773 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
5774 question
->qname
.c
, DNSTypeName(question
->qtype
));
5775 return(mStatus_BadReferenceErr
);
5778 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
5779 UpdateQuestionDuplicates(m
, question
);
5780 // But don't trash ThisQInterval until afterwards.
5781 question
->ThisQInterval
= -1;
5783 // If there are any cache records referencing this as their active question, then see if any other
5784 // question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
5785 for (rr
= m
->rrcache_hash
[HashSlot(&question
->qname
)]; rr
; rr
=rr
->next
)
5787 if (rr
->CRActiveQuestion
== question
)
5790 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5791 if (ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
5793 verbosedebugf("mDNS_StopQuery_internal: Cache RR %##s (%s) setting CRActiveQuestion to %X", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), q
);
5794 rr
->CRActiveQuestion
= q
; // Question used to be active; new value may or may not be null
5795 if (!q
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
5799 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv()is about to look at,
5800 // bump its pointer forward one question.
5801 if (m
->CurrentQuestion
== question
)
5803 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
5804 question
->qname
.c
, DNSTypeName(question
->qtype
));
5805 m
->CurrentQuestion
= question
->next
;
5808 if (m
->NewQuestions
== question
)
5810 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
5811 question
->qname
.c
, DNSTypeName(question
->qtype
));
5812 m
->NewQuestions
= question
->next
;
5815 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
5817 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
5818 question
->next
= mDNSNULL
;
5819 return(mStatus_NoError
);
5822 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
5826 status
= mDNS_StartQuery_internal(m
, question
);
5831 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
5835 status
= mDNS_StopQuery_internal(m
, question
);
5840 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const rr
)
5844 status
= mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForNoAnswer
);
5849 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
5851 mStatus status
= mStatus_BadReferenceErr
;
5854 cr
= FindIdenticalRecordInCache(m
, rr
);
5855 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
5860 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
5861 const domainname
*const srv
, const domainname
*const domain
,
5862 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
5864 question
->ThisQInterval
= -1; // Indicate that query is not yet active
5865 question
->InterfaceID
= InterfaceID
;
5866 question
->qtype
= kDNSType_PTR
;
5867 question
->qclass
= kDNSClass_IN
;
5868 question
->QuestionCallback
= Callback
;
5869 question
->QuestionContext
= Context
;
5870 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
)) return(mStatus_BadParamErr
);
5871 return(mDNS_StartQuery(m
, question
));
5874 mDNSlocal
void FoundServiceInfoSRV(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5876 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5877 mDNSBool PortChanged
= (mDNSBool
)(query
->info
->port
.NotAnInteger
!= answer
->rdata
->u
.srv
.port
.NotAnInteger
);
5878 if (!AddRecord
) return;
5879 if (answer
->rrtype
!= kDNSType_SRV
) return;
5881 query
->info
->port
= answer
->rdata
->u
.srv
.port
;
5883 // If this is our first answer, then set the GotSRV flag and start the address query
5886 query
->GotSRV
= mDNStrue
;
5887 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
5888 AssignDomainName(query
->qAv4
.qname
, answer
->rdata
->u
.srv
.target
);
5889 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
5890 AssignDomainName(query
->qAv6
.qname
, answer
->rdata
->u
.srv
.target
);
5891 mDNS_StartQuery_internal(m
, &query
->qAv4
);
5892 mDNS_StartQuery_internal(m
, &query
->qAv6
);
5894 // If this is not our first answer, only re-issue the address query if the target host name has changed
5895 else if ((query
->qAv4
.InterfaceID
!= query
->qSRV
.InterfaceID
&& query
->qAv4
.InterfaceID
!= answer
->InterfaceID
) ||
5896 !SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
))
5898 mDNS_StopQuery_internal(m
, &query
->qAv4
);
5899 mDNS_StopQuery_internal(m
, &query
->qAv6
);
5900 if (SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
) && !PortChanged
)
5902 // If we get here, it means:
5903 // 1. This is not our first SRV answer
5904 // 2. The interface ID is different, but the target host and port are the same
5905 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
5906 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
5907 query
->qAv4
.InterfaceID
= query
->qSRV
.InterfaceID
; // Will be mDNSInterface_Any, or a specific interface
5908 query
->qAv6
.InterfaceID
= query
->qSRV
.InterfaceID
;
5912 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
5913 AssignDomainName(query
->qAv4
.qname
, answer
->rdata
->u
.srv
.target
);
5914 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
5915 AssignDomainName(query
->qAv6
.qname
, answer
->rdata
->u
.srv
.target
);
5917 debugf("FoundServiceInfoSRV: Restarting address queries for %##s", query
->qAv4
.qname
.c
);
5918 mDNS_StartQuery_internal(m
, &query
->qAv4
);
5919 mDNS_StartQuery_internal(m
, &query
->qAv6
);
5921 else if (query
->ServiceInfoQueryCallback
&& query
->GotADD
&& query
->GotTXT
&& PortChanged
)
5923 if (++query
->Answers
>= 100)
5924 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
5925 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.srv
.target
.c
,
5926 ((mDNSu16
)answer
->rdata
->u
.srv
.port
.b
[0] << 8) | answer
->rdata
->u
.srv
.port
.b
[1]);
5927 query
->ServiceInfoQueryCallback(m
, query
);
5929 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5930 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5933 mDNSlocal
void FoundServiceInfoTXT(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5935 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5936 if (!AddRecord
) return;
5937 if (answer
->rrtype
!= kDNSType_TXT
) return;
5938 if (answer
->rdlength
> sizeof(query
->info
->TXTinfo
)) return;
5940 query
->GotTXT
= mDNStrue
;
5941 query
->info
->TXTlen
= answer
->rdlength
;
5942 mDNSPlatformMemCopy(answer
->rdata
->u
.txt
.c
, query
->info
->TXTinfo
, answer
->rdlength
);
5944 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query
->info
->name
.c
, query
->GotADD
);
5946 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5947 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5948 if (query
->ServiceInfoQueryCallback
&& query
->GotADD
)
5950 if (++query
->Answers
>= 100)
5951 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
5952 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.txt
.c
);
5953 query
->ServiceInfoQueryCallback(m
, query
);
5957 mDNSlocal
void FoundServiceInfo(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
5959 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
5960 if (!AddRecord
) return;
5962 if (answer
->rrtype
== kDNSType_A
)
5964 query
->info
->ip
.type
= mDNSAddrType_IPv4
;
5965 query
->info
->ip
.ip
.v4
= answer
->rdata
->u
.ip
;
5967 else if (answer
->rrtype
== kDNSType_AAAA
)
5969 query
->info
->ip
.type
= mDNSAddrType_IPv6
;
5970 query
->info
->ip
.ip
.v6
= answer
->rdata
->u
.ipv6
;
5974 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer
->name
.c
, answer
->rrtype
, DNSTypeName(answer
->rrtype
));
5978 query
->GotADD
= mDNStrue
;
5979 query
->info
->InterfaceID
= answer
->InterfaceID
;
5981 verbosedebugf("FoundServiceInfo v%d: %##s GotTXT=%d", query
->info
->ip
.type
, query
->info
->name
.c
, query
->GotTXT
);
5983 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
5984 // callback function is allowed to do anything, including deleting this query and freeing its memory.
5985 if (query
->ServiceInfoQueryCallback
&& query
->GotTXT
)
5987 if (++query
->Answers
>= 100)
5989 if (answer
->rrtype
== kDNSType_A
)
5990 debugf("**** WARNING **** have given %lu answers for %##s (A) %.4a", query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.ip
);
5992 debugf("**** WARNING **** have given %lu answers for %##s (AAAA) %.16a", query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.ipv6
);
5994 query
->ServiceInfoQueryCallback(m
, query
);
5998 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
5999 // If the query is not interface-specific, then InterfaceID may be zero
6000 // Each time the Callback is invoked, the remainder of the fields will have been filled in
6001 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
6002 mDNSexport mStatus
mDNS_StartResolveService(mDNS
*const m
,
6003 ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
)
6008 query
->qSRV
.ThisQInterval
= -1; // This question not yet in the question list
6009 query
->qSRV
.InterfaceID
= info
->InterfaceID
;
6010 AssignDomainName(query
->qSRV
.qname
, info
->name
);
6011 query
->qSRV
.qtype
= kDNSType_SRV
;
6012 query
->qSRV
.qclass
= kDNSClass_IN
;
6013 query
->qSRV
.QuestionCallback
= FoundServiceInfoSRV
;
6014 query
->qSRV
.QuestionContext
= query
;
6016 query
->qTXT
.ThisQInterval
= -1; // This question not yet in the question list
6017 query
->qTXT
.InterfaceID
= info
->InterfaceID
;
6018 AssignDomainName(query
->qTXT
.qname
, info
->name
);
6019 query
->qTXT
.qtype
= kDNSType_TXT
;
6020 query
->qTXT
.qclass
= kDNSClass_IN
;
6021 query
->qTXT
.QuestionCallback
= FoundServiceInfoTXT
;
6022 query
->qTXT
.QuestionContext
= query
;
6024 query
->qAv4
.ThisQInterval
= -1; // This question not yet in the question list
6025 query
->qAv4
.InterfaceID
= info
->InterfaceID
;
6026 query
->qAv4
.qname
.c
[0] = 0;
6027 query
->qAv4
.qtype
= kDNSType_A
;
6028 query
->qAv4
.qclass
= kDNSClass_IN
;
6029 query
->qAv4
.QuestionCallback
= FoundServiceInfo
;
6030 query
->qAv4
.QuestionContext
= query
;
6032 query
->qAv6
.ThisQInterval
= -1; // This question not yet in the question list
6033 query
->qAv6
.InterfaceID
= info
->InterfaceID
;
6034 query
->qAv6
.qname
.c
[0] = 0;
6035 query
->qAv6
.qtype
= kDNSType_AAAA
;
6036 query
->qAv6
.qclass
= kDNSClass_IN
;
6037 query
->qAv6
.QuestionCallback
= FoundServiceInfo
;
6038 query
->qAv6
.QuestionContext
= query
;
6040 query
->GotSRV
= mDNSfalse
;
6041 query
->GotTXT
= mDNSfalse
;
6042 query
->GotADD
= mDNSfalse
;
6046 query
->ServiceInfoQueryCallback
= Callback
;
6047 query
->ServiceInfoQueryContext
= Context
;
6049 // info->name = Must already be set up by client
6050 // info->interface = Must already be set up by client
6051 info
->ip
= zeroAddr
;
6052 info
->port
= zeroIPPort
;
6055 status
= mDNS_StartQuery_internal(m
, &query
->qSRV
);
6056 if (status
== mStatus_NoError
) status
= mDNS_StartQuery_internal(m
, &query
->qTXT
);
6057 if (status
!= mStatus_NoError
) mDNS_StopResolveService(m
, query
);
6063 mDNSexport
void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*query
)
6066 if (query
->qSRV
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qSRV
);
6067 if (query
->qTXT
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qTXT
);
6068 if (query
->qAv4
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qAv4
);
6069 if (query
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &query
->qAv6
);
6073 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
,
6074 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
6076 MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
]);
6077 question
->InterfaceID
= InterfaceID
;
6078 question
->qtype
= kDNSType_PTR
;
6079 question
->qclass
= kDNSClass_IN
;
6080 question
->QuestionCallback
= Callback
;
6081 question
->QuestionContext
= Context
;
6082 return(mDNS_StartQuery(m
, question
));
6085 // ***************************************************************************
6086 #if COMPILER_LIKES_PRAGMA_MARK
6088 #pragma mark - Responder Functions
6091 // Set up a AuthRecord with sensible default values.
6092 // These defaults may be overwritten with new values before mDNS_Register is called
6093 mDNSexport
void mDNS_SetupResourceRecord(AuthRecord
*rr
, RData
*RDataStorage
, mDNSInterfaceID InterfaceID
,
6094 mDNSu16 rrtype
, mDNSu32 ttl
, mDNSu8 RecordType
, mDNSRecordCallback Callback
, void *Context
)
6096 // Don't try to store a TTL bigger than we can represent in platform time units
6097 if (ttl
> 0x7FFFFFFFUL
/ mDNSPlatformOneSecond
)
6098 ttl
= 0x7FFFFFFFUL
/ mDNSPlatformOneSecond
;
6099 else if (ttl
== 0) // And Zero TTL is illegal
6100 ttl
= kDefaultTTLforShared
;
6102 // Field Group 1: Persistent metadata for Authoritative Records
6103 rr
->Additional1
= mDNSNULL
;
6104 rr
->Additional2
= mDNSNULL
;
6105 rr
->DependentOn
= mDNSNULL
;
6106 rr
->RRSet
= mDNSNULL
;
6107 rr
->RecordCallback
= Callback
;
6108 rr
->RecordContext
= Context
;
6110 rr
->resrec
.RecordType
= RecordType
;
6111 rr
->HostTarget
= mDNSfalse
;
6113 // Field Group 2: Transient state for Authoritative Records (set in mDNS_Register_internal)
6114 // Field Group 3: Transient state for Cache Records (set in mDNS_Register_internal)
6116 // Field Group 4: The actual information pertaining to this resource record
6117 rr
->resrec
.InterfaceID
= InterfaceID
;
6118 rr
->resrec
.name
.c
[0] = 0; // MUST be set by client
6119 rr
->resrec
.rrtype
= rrtype
;
6120 rr
->resrec
.rrclass
= kDNSClass_IN
;
6121 rr
->resrec
.rroriginalttl
= ttl
;
6122 // rr->resrec.rdlength = MUST set by client and/or in mDNS_Register_internal
6123 // rr->resrec.rdestimate = set in mDNS_Register_internal
6124 // rr->resrec.rdata = MUST be set by client
6127 rr
->resrec
.rdata
= RDataStorage
;
6130 rr
->resrec
.rdata
= &rr
->rdatastorage
;
6131 rr
->resrec
.rdata
->MaxRDLength
= sizeof(RDataBody
);
6135 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
6139 status
= mDNS_Register_internal(m
, rr
);
6144 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
6145 const mDNSu16 newrdlength
,
6146 RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
6150 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
6151 { LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(m
, &rr
->resrec
, &newrdata
->u
)); return(mStatus_Invalid
); }
6153 // If TTL is unspecified, leave TTL unchanged
6154 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
6156 // If we already have an update queued up which has not gone through yet,
6157 // give the client a chance to free that memory
6160 RData
*n
= rr
->NewRData
;
6161 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
6162 if (rr
->UpdateCallback
)
6163 rr
->UpdateCallback(m
, rr
, n
); // ...and let the client free this memory, if necessary
6166 if (rr
->AnnounceCount
< ReannounceCount
)
6167 rr
->AnnounceCount
= ReannounceCount
;
6168 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
6169 InitializeLastAPTime(m
, rr
);
6170 rr
->NewRData
= newrdata
;
6171 rr
->newrdlength
= newrdlength
;
6172 rr
->UpdateCallback
= Callback
;
6173 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
6174 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= (m
->timenow
+ mDNSPlatformOneSecond
* 60) | 1;
6175 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
6176 if (rr
->UpdateCredits
<= 5)
6178 mDNSs32 delay
= 1 << (5 - rr
->UpdateCredits
);
6179 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= (m
->timenow
+ delay
* mDNSPlatformOneSecond
) | 1;
6180 rr
->LastAPTime
= rr
->UpdateBlocked
;
6181 rr
->ThisAPInterval
*= 4;
6182 LogMsg("Excessive update rate for %##s; delaying announcement by %d seconds", rr
->resrec
.name
.c
, delay
);
6184 rr
->resrec
.rroriginalttl
= newttl
;
6186 return(mStatus_NoError
);
6189 // NOTE: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
6190 // the record list and/or question list.
6191 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6192 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
6196 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6201 mDNSlocal
void HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
6203 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
6205 NetworkInterfaceInfo
*intf
;
6206 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6207 if (intf
->Advertise
) break;
6211 mDNSlocal
void mDNS_AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6214 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
6215 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
6217 mDNS_SetupResourceRecord(&set
->RR_A
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, HostNameCallback
, set
);
6218 mDNS_SetupResourceRecord(&set
->RR_PTR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kDefaultTTLforUnique
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
6219 mDNS_SetupResourceRecord(&set
->RR_HINFO
, mDNSNULL
, set
->InterfaceID
, kDNSType_HINFO
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, mDNSNULL
, mDNSNULL
);
6221 // 1. Set up Address record to map from host name ("foo.local.") to IP address
6222 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
6223 AssignDomainName(set
->RR_A
.resrec
.name
, m
->hostname
);
6224 if (set
->ip
.type
== mDNSAddrType_IPv4
)
6226 set
->RR_A
.resrec
.rrtype
= kDNSType_A
;
6227 set
->RR_A
.resrec
.rdata
->u
.ip
= set
->ip
.ip
.v4
;
6228 // Note: This is reverse order compared to a normal dotted-decimal IP address
6229 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
6230 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
6232 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
6235 set
->RR_A
.resrec
.rrtype
= kDNSType_AAAA
;
6236 set
->RR_A
.resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
6237 for (i
= 0; i
< 16; i
++)
6239 static const char hexValues
[] = "0123456789ABCDEF";
6240 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
6241 buffer
[i
* 4 + 1] = '.';
6242 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
6243 buffer
[i
* 4 + 3] = '.';
6245 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
6248 MakeDomainNameFromDNSNameString(&set
->RR_PTR
.resrec
.name
, buffer
);
6249 set
->RR_PTR
.HostTarget
= mDNStrue
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
6251 set
->RR_A
.RRSet
= &primary
->RR_A
; // May refer to self
6253 mDNS_Register_internal(m
, &set
->RR_A
);
6254 mDNS_Register_internal(m
, &set
->RR_PTR
);
6256 if (m
->HIHardware
.c
[0] > 0 && m
->HISoftware
.c
[0] > 0 && m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0] <= 254)
6258 mDNSu8
*p
= set
->RR_HINFO
.resrec
.rdata
->u
.data
;
6259 AssignDomainName(set
->RR_HINFO
.resrec
.name
, m
->hostname
);
6260 set
->RR_HINFO
.DependentOn
= &set
->RR_A
;
6261 mDNSPlatformMemCopy(&m
->HIHardware
, p
, 1 + (mDNSu32
)m
->HIHardware
.c
[0]);
6263 mDNSPlatformMemCopy(&m
->HISoftware
, p
, 1 + (mDNSu32
)m
->HISoftware
.c
[0]);
6264 mDNS_Register_internal(m
, &set
->RR_HINFO
);
6268 debugf("Not creating HINFO record: platform support layer provided no information");
6269 set
->RR_HINFO
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
6273 mDNSlocal
void mDNS_DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6275 NetworkInterfaceInfo
*intf
;
6276 // If we still have address records referring to this one, update them
6277 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
6278 AuthRecord
*A
= primary
? &primary
->RR_A
: mDNSNULL
;
6279 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6280 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
6281 intf
->RR_A
.RRSet
= A
;
6283 // Unregister these records.
6284 // When doing the mDNS_Close processing, we first call mDNS_DeadvertiseInterface for each interface, so by the time the platform
6285 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
6286 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
6287 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
6288 if (set
->RR_A
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
6289 if (set
->RR_PTR
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
6290 if (set
->RR_HINFO
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_HINFO
, mDNS_Dereg_normal
);
6293 mDNSexport
void mDNS_GenerateFQDN(mDNS
*const m
)
6299 if (!AppendDomainLabel(&newname
, &m
->hostlabel
)) LogMsg("ERROR! Cannot create dot-local hostname");
6300 if (!AppendLiteralLabelString(&newname
, "local")) LogMsg("ERROR! Cannot create dot-local hostname");
6301 if (!SameDomainName(&m
->hostname
, &newname
))
6303 NetworkInterfaceInfo
*intf
;
6306 m
->hostname
= newname
;
6308 // 1. Stop advertising our address records on all interfaces
6309 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6310 if (intf
->Advertise
) mDNS_DeadvertiseInterface(m
, intf
);
6312 // 2. Start advertising our address records using the new name
6313 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6314 if (intf
->Advertise
) mDNS_AdvertiseInterface(m
, intf
);
6316 // 3. Make sure that any SRV records (and the like) that reference our
6317 // host name in their rdata get updated to reference this new host name
6318 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->HostTarget
) SetTargetToHostName(m
, rr
);
6319 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->HostTarget
) SetTargetToHostName(m
, rr
);
6325 mDNSlocal
void HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
6327 (void)rr
; // Unused parameter
6331 char *msg
= "Unknown result";
6332 if (result
== mStatus_NoError
) msg
= "Name registered";
6333 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
6334 debugf("HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
6338 if (result
== mStatus_NoError
)
6340 // Notify the client that the host name is successfully registered
6341 if (m
->MainCallback
)
6342 m
->MainCallback(m
, result
);
6344 else if (result
== mStatus_NameConflict
)
6346 domainlabel oldlabel
= m
->hostlabel
;
6348 // 1. First give the client callback a chance to pick a new name
6349 if (m
->MainCallback
)
6350 m
->MainCallback(m
, mStatus_NameConflict
);
6352 // 2. If the client callback didn't do it, add (or increment) an index ourselves
6353 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
6354 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
6356 // 3. Generate the FQDNs from the hostlabel,
6357 // and make sure all SRV records, etc., are updated to reference our new hostname
6358 mDNS_GenerateFQDN(m
);
6362 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
6364 NetworkInterfaceInfo
*intf
;
6365 active
->IPv4Available
= mDNSfalse
;
6366 active
->IPv6Available
= mDNSfalse
;
6367 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6368 if (intf
->InterfaceID
== active
->InterfaceID
)
6370 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->TxAndRx
) active
->IPv4Available
= mDNStrue
;
6371 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->TxAndRx
) active
->IPv6Available
= mDNStrue
;
6375 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6377 mDNSBool FirstOfType
= mDNStrue
;
6378 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
6381 // Assume this interface will be active
6382 set
->InterfaceActive
= mDNStrue
;
6383 set
->IPv4Available
= (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->TxAndRx
);
6384 set
->IPv6Available
= (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->TxAndRx
);
6390 LogMsg("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
6392 return(mStatus_AlreadyRegistered
);
6395 // This InterfaceID is already in the list, so mark this interface inactive for now
6396 if ((*p
)->InterfaceID
== set
->InterfaceID
)
6398 set
->InterfaceActive
= mDNSfalse
;
6399 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
6400 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->TxAndRx
) (*p
)->IPv4Available
= mDNStrue
;
6401 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->TxAndRx
) (*p
)->IPv6Available
= mDNStrue
;
6407 set
->next
= mDNSNULL
;
6410 debugf("mDNS_RegisterInterface: InterfaceID %p %#a %s", set
->InterfaceID
, &set
->ip
,
6411 set
->InterfaceActive
?
6412 "not represented in list; marking active and retriggering queries" :
6413 "already represented in list; marking inactive for now");
6415 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6416 // giving the false impression that there's an active representative of this interface when there really isn't.
6417 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
6418 // even if we believe that we previously had an active representative of this interface.
6419 if ((m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) || FirstOfType
|| set
->InterfaceActive
)
6423 // Use a small amount of randomness:
6424 // In the case of a network administrator turning on an Ethernet hub so that all the connected machines establish link at
6425 // exactly the same time, we don't want them to all go and hit the network with identical queries at exactly the same moment.
6426 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
6427 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
6428 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
6429 { // then reactivate this question
6430 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
6431 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
6432 q
->RecentAnswers
= 0;
6433 if (ActiveQuestion(q
)) m
->NextScheduledQuery
= m
->timenow
;
6436 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
6437 // we now need them to re-probe if necessary, and then re-announce.
6438 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6439 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6441 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
6442 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
6443 if (rr
->AnnounceCount
< ReannounceCount
)
6444 rr
->AnnounceCount
= ReannounceCount
;
6445 rr
->ThisAPInterval
= DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
6446 InitializeLastAPTime(m
, rr
);
6451 mDNS_AdvertiseInterface(m
, set
);
6454 return(mStatus_NoError
);
6457 // NOTE: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
6458 // the record list and/or question list.
6459 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6460 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
6462 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
6464 mDNSBool revalidate
= mDNSfalse
;
6465 // If this platform has the "phantom interfaces" known bug (e.g. Jaguar), we have to revalidate records every
6466 // time an interface goes away. Otherwise, when you disconnect the Ethernet cable, the system reports that it
6467 // still has an IPv6 address, and if we don't revalidate those records don't get deleted in a timely fashion.
6468 if (m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) revalidate
= mDNStrue
;
6472 // Find this record in our list
6473 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
6474 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
6476 // Unlink this record from our list
6478 set
->next
= mDNSNULL
;
6480 if (!set
->InterfaceActive
)
6482 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
6483 NetworkInterfaceInfo
*intf
;
6484 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6485 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
6486 UpdateInterfaceProtocols(m
, intf
);
6490 NetworkInterfaceInfo
*intf
;
6491 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6492 if (intf
->InterfaceID
== set
->InterfaceID
)
6496 debugf("mDNS_DeregisterInterface: Another representative of InterfaceID %p exists; making it active",
6498 intf
->InterfaceActive
= mDNStrue
;
6499 UpdateInterfaceProtocols(m
, intf
);
6501 // See if another representative *of the same type* exists. If not, we mave have gone from
6502 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
6503 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6504 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
6506 if (!intf
) revalidate
= mDNStrue
;
6513 debugf("mDNS_DeregisterInterface: Last representative of InterfaceID %p deregistered; marking questions etc. dormant",
6516 // 1. Deactivate any questions specific to this interface
6517 for (q
= m
->Questions
; q
; q
=q
->next
)
6518 if (q
->InterfaceID
== set
->InterfaceID
)
6519 q
->ThisQInterval
= 0;
6521 // 2. Flush any cache records received on this interface
6522 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
6523 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6524 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
6525 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6526 PurgeCacheResourceRecord(m
, rr
);
6530 // If we were advertising on this interface, deregister those address and reverse-lookup records now
6532 mDNS_DeadvertiseInterface(m
, set
);
6534 // If we have any cache records received on this interface that went away, then re-verify them.
6535 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6536 // giving the false impression that there's an active representative of this interface when there really isn't.
6537 // Don't need to do this when shutting down, because *all* interfaces are about to go away
6538 if (revalidate
&& !m
->mDNS_shutdown
)
6542 m
->NextCacheCheck
= m
->timenow
;
6543 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6544 for (rr
= m
->rrcache_hash
[slot
]; rr
; rr
=rr
->next
)
6545 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
6546 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForCableDisconnect
);
6552 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
6554 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
6555 (void)m
; // Unused parameter
6559 char *msg
= "Unknown result";
6560 if (result
== mStatus_NoError
) msg
= "Name Registered";
6561 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
6562 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
6563 debugf("ServiceCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
.c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
6567 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
6568 if (result
== mStatus_NameConflict
)
6570 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
6571 sr
->RR_PTR
.AnnounceCount
= InitialAnnounceCount
; // Make sure we don't send a goodbye for the PTR record
6572 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
6576 if (result
== mStatus_MemFree
)
6578 // If the PTR record or any of the subtype PTR record are still in the process of deregistering,
6579 // don't pass on the NameConflict/MemFree message until every record is finished cleaning up.
6581 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
6582 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
6584 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
6585 // then we can now report the NameConflict to the client
6586 if (sr
->Conflict
) result
= mStatus_NameConflict
;
6589 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
6590 // function is allowed to do anything, including deregistering this service and freeing its memory.
6591 if (sr
->ServiceCallback
)
6592 sr
->ServiceCallback(m
, sr
, result
);
6596 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
6597 // Type is service type (e.g. "_printer._tcp.")
6598 // Domain is fully qualified domain name (i.e. ending with a null label)
6599 // We always register a TXT, even if it is empty (so that clients are not
6600 // left waiting forever looking for a nonexistent record.)
6601 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
6602 // then the default host name (m->hostname1) is automatically used
6603 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
6604 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
6605 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
6606 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
6607 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
)
6612 sr
->ServiceCallback
= Callback
;
6613 sr
->ServiceContext
= Context
;
6614 sr
->Extras
= mDNSNULL
;
6615 sr
->NumSubTypes
= NumSubTypes
;
6616 sr
->SubTypes
= SubTypes
;
6617 sr
->Conflict
= mDNSfalse
;
6618 if (host
&& host
->c
[0]) sr
->Host
= *host
;
6619 else sr
->Host
.c
[0] = 0;
6621 // Initialize the AuthRecord objects to sane values
6622 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeAdvisory
, ServiceCallback
, sr
);
6623 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
6624 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6625 mDNS_SetupResourceRecord(&sr
->RR_TXT
, mDNSNULL
, InterfaceID
, kDNSType_TXT
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6627 // If the client is registering an oversized TXT record,
6628 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
6629 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
6630 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
6632 // Set up the record names
6633 // For now we only create an advisory record for the main type, not for subtypes
6634 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
6635 if (ConstructServiceName(&sr
->RR_ADV
.resrec
.name
, (domainlabel
*)"\x09_services", (domainname
*)"\x05_mdns\x04_udp", domain
) == mDNSNULL
)
6636 return(mStatus_BadParamErr
);
6637 if (ConstructServiceName(&sr
->RR_PTR
.resrec
.name
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6638 if (ConstructServiceName(&sr
->RR_SRV
.resrec
.name
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6639 AssignDomainName(sr
->RR_TXT
.resrec
.name
, sr
->RR_SRV
.resrec
.name
);
6641 // 1. Set up the ADV record rdata to advertise our service type
6642 AssignDomainName(sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
6644 // 2. Set up the PTR record rdata to point to our service name
6645 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
6646 AssignDomainName(sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
6647 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
6648 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
6650 // 2a. Set up any subtype PTRs to point to our service name
6651 // If the client is using subtypes, it is the client's responsibility to have
6652 // already set the first label of the record name to the subtype being registered
6653 for (i
=0; i
<NumSubTypes
; i
++)
6655 domainlabel s
= *(domainlabel
*)&sr
->SubTypes
[i
].resrec
.name
;
6656 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
6657 if (ConstructServiceName(&sr
->SubTypes
[i
].resrec
.name
, &s
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6658 AssignDomainName(sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
6659 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
6660 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
6663 // 3. Set up the SRV record rdata.
6664 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
6665 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
6666 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
6668 // Setting HostTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
6669 if (sr
->Host
.c
[0]) AssignDomainName(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, sr
->Host
);
6670 else sr
->RR_SRV
.HostTarget
= mDNStrue
;
6672 // 4. Set up the TXT record rdata,
6673 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
6674 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
6675 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
6677 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
6678 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
6679 mDNSPlatformMemCopy(txtinfo
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtlen
);
6681 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
6684 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
6685 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
6686 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
6687 // mDNS_Close, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
6688 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
6689 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
6690 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
6691 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
6692 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
6693 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
6696 if (err
) mDNS_DeregisterService(m
, sr
);
6700 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
6701 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
)
6703 mStatus result
= mStatus_UnknownErr
;
6704 ExtraResourceRecord
**e
= &sr
->Extras
;
6705 while (*e
) e
= &(*e
)->next
;
6707 // If TTL is unspecified, make it the same as the service's TXT and SRV default
6708 if (ttl
== 0) ttl
= kDefaultTTLforUnique
;
6710 extra
->next
= mDNSNULL
;
6711 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
, extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
6712 AssignDomainName(extra
->r
.resrec
.name
, sr
->RR_SRV
.resrec
.name
);
6713 extra
->r
.DependentOn
= &sr
->RR_SRV
;
6715 debugf("mDNS_AddRecordToService adding record to %##s", extra
->r
.resrec
.name
.c
);
6717 result
= mDNS_Register(m
, &extra
->r
);
6718 if (!result
) *e
= extra
;
6722 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
)
6724 ExtraResourceRecord
**e
= &sr
->Extras
;
6725 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
6728 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
.c
);
6729 return(mStatus_BadReferenceErr
);
6732 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
.c
);
6735 return(mDNS_Deregister(m
, &extra
->r
));
6738 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
6741 domainname type
, domain
;
6742 domainname
*host
= mDNSNULL
;
6743 ExtraResourceRecord
*extras
= sr
->Extras
;
6746 DeconstructServiceName(&sr
->RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
6749 IncrementLabelSuffix(&name
, mDNStrue
);
6752 debugf("Reregistering as %#s", newname
->c
);
6753 if (sr
->RR_SRV
.HostTarget
== mDNSfalse
&& sr
->Host
.c
[0]) host
= &sr
->Host
;
6755 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
6756 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
6757 sr
->SubTypes
, sr
->NumSubTypes
,
6758 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
);
6760 // mDNS_RegisterService() just reset sr->Extras to NULL.
6761 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
6762 // through the old list of extra records, and re-add them to our freshly created service registration
6763 while (!err
&& extras
)
6765 ExtraResourceRecord
*e
= extras
;
6766 extras
= extras
->next
;
6767 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
);
6773 // NOTE: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
6774 // which may change the record list and/or question list.
6775 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6776 mDNSexport mStatus
mDNS_DeregisterService(mDNS
*const m
, ServiceRecordSet
*sr
)
6778 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
6780 debugf("Service set for %##s already deregistered", sr
->RR_PTR
.resrec
.name
.c
);
6781 return(mStatus_BadReferenceErr
);
6783 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
6785 debugf("Service set for %##s already in the process of deregistering", sr
->RR_PTR
.resrec
.name
.c
);
6786 return(mStatus_NoError
);
6792 ExtraResourceRecord
*e
;
6796 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
6797 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
6798 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
6799 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
6801 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, mDNS_Dereg_normal
);
6803 // We deregister all of the extra records, but we leave the sr->Extras list intact
6804 // in case the client wants to do a RenameAndReregister and reinstate the registration
6807 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
6811 for (i
=0; i
<sr
->NumSubTypes
; i
++)
6812 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], mDNS_Dereg_normal
);
6814 // Be sure to deregister the PTR last!
6815 // Deregistering this record is what triggers the mStatus_MemFree callback to ServiceCallback,
6816 // which in turn passes on the mStatus_MemFree (or mStatus_NameConflict) back to the client callback,
6817 // which is then at liberty to free the ServiceRecordSet memory at will. We need to make sure
6818 // we've deregistered all our records and done any other necessary cleanup before that happens.
6819 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, mDNS_Dereg_normal
);
6825 // Create a registration that asserts that no such service exists with this name.
6826 // This can be useful where there is a given function is available through several protocols.
6827 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
6828 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
6829 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
6830 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
6831 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
6832 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
6833 const domainname
*const host
,
6834 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
)
6836 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kDefaultTTLforUnique
, kDNSRecordTypeUnique
, Callback
, Context
);
6837 if (ConstructServiceName(&rr
->resrec
.name
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
6838 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
6839 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
6840 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
6841 if (host
&& host
->c
[0]) AssignDomainName(rr
->resrec
.rdata
->u
.srv
.target
, *host
);
6842 else rr
->HostTarget
= mDNStrue
;
6843 return(mDNS_Register(m
, rr
));
6846 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
6847 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
6849 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kDefaultTTLforShared
, kDNSRecordTypeShared
, mDNSNULL
, mDNSNULL
);
6850 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.name
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
6851 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
6852 return(mDNS_Register(m
, rr
));
6855 // ***************************************************************************
6856 #if COMPILER_LIKES_PRAGMA_MARK
6859 #pragma mark - Startup and Shutdown
6862 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheRecord
*storage
, mDNSu32 numrecords
)
6864 if (storage
&& numrecords
)
6867 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
6868 storage
[numrecords
-1].next
= m
->rrcache_free
;
6869 m
->rrcache_free
= storage
;
6870 m
->rrcache_size
+= numrecords
;
6874 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
6875 CacheRecord
*rrcachestorage
, mDNSu32 rrcachesize
,
6876 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
6880 mStatus result
= mDNSPlatformTimeInit(&timenow
);
6881 if (result
!= mStatus_NoError
) return(result
);
6883 if (!rrcachestorage
) rrcachesize
= 0;
6887 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
6888 m
->mDNSPlatformStatus
= mStatus_Waiting
;
6889 m
->MainCallback
= Callback
;
6890 m
->MainContext
= Context
;
6892 // For debugging: To catch and report locking failures
6894 m
->mDNS_reentrancy
= 0;
6895 m
->mDNS_shutdown
= mDNSfalse
;
6896 m
->lock_rrcache
= 0;
6897 m
->lock_Questions
= 0;
6898 m
->lock_Records
= 0;
6900 // Task Scheduling variables
6901 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
6902 m
->timenow_last
= timenow
;
6903 m
->timenow_adjust
= 0;
6904 m
->NextScheduledEvent
= timenow
;
6905 m
->SuppressSending
= timenow
;
6906 m
->NextCacheCheck
= timenow
+ 0x78000000;
6907 m
->NextScheduledQuery
= timenow
+ 0x78000000;
6908 m
->NextScheduledProbe
= timenow
+ 0x78000000;
6909 m
->NextScheduledResponse
= timenow
+ 0x78000000;
6910 m
->ExpectUnicastResponse
= timenow
+ 0x78000000;
6911 m
->RandomQueryDelay
= 0;
6912 m
->SendDeregistrations
= mDNSfalse
;
6913 m
->SendImmediateAnswers
= mDNSfalse
;
6914 m
->SleepState
= mDNSfalse
;
6916 // These fields only required for mDNS Searcher...
6917 m
->Questions
= mDNSNULL
;
6918 m
->NewQuestions
= mDNSNULL
;
6919 m
->CurrentQuestion
= mDNSNULL
;
6920 m
->LocalOnlyQuestions
= mDNSNULL
;
6921 m
->NewLocalOnlyQuestions
= mDNSNULL
;
6922 m
->rrcache_size
= 0;
6923 m
->rrcache_totalused
= 0;
6924 m
->rrcache_active
= 0;
6925 m
->rrcache_report
= 10;
6926 m
->rrcache_free
= mDNSNULL
;
6928 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6930 m
->rrcache_hash
[slot
] = mDNSNULL
;
6931 m
->rrcache_tail
[slot
] = &m
->rrcache_hash
[slot
];
6932 m
->rrcache_used
[slot
] = 0;
6935 mDNS_GrowCache(m
, rrcachestorage
, rrcachesize
);
6937 // Fields below only required for mDNS Responder...
6938 m
->hostlabel
.c
[0] = 0;
6939 m
->nicelabel
.c
[0] = 0;
6940 m
->hostname
.c
[0] = 0;
6941 m
->HIHardware
.c
[0] = 0;
6942 m
->HISoftware
.c
[0] = 0;
6943 m
->ResourceRecords
= mDNSNULL
;
6944 m
->DuplicateRecords
= mDNSNULL
;
6945 m
->LocalOnlyRecords
= mDNSNULL
;
6946 m
->NewLocalOnlyRecords
= mDNSNULL
;
6947 m
->DiscardLocalOnlyRecords
= mDNSfalse
;
6948 m
->CurrentRecord
= mDNSNULL
;
6949 m
->HostInterfaces
= mDNSNULL
;
6950 m
->ProbeFailTime
= 0;
6951 m
->NumFailedProbes
= 0;
6952 m
->SuppressProbes
= 0;
6954 result
= mDNSPlatformInit(m
);
6959 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
6961 m
->mDNSPlatformStatus
= result
;
6962 if (m
->MainCallback
)
6963 m
->MainCallback(m
, mStatus_NoError
);
6966 mDNSexport
void mDNS_Close(mDNS
*const m
)
6968 mDNSu32 rrcache_active
= 0;
6969 mDNSu32 rrcache_totalused
= 0;
6971 NetworkInterfaceInfo
*intf
;
6974 m
->mDNS_shutdown
= mDNStrue
;
6976 rrcache_totalused
= m
->rrcache_totalused
;
6977 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
6979 while (m
->rrcache_hash
[slot
])
6981 CacheRecord
*rr
= m
->rrcache_hash
[slot
];
6982 m
->rrcache_hash
[slot
] = rr
->next
;
6983 if (rr
->CRActiveQuestion
) rrcache_active
++;
6984 m
->rrcache_used
[slot
]--;
6985 ReleaseCacheRR(m
, rr
);
6987 // 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)
6988 m
->rrcache_tail
[slot
] = &m
->rrcache_hash
[slot
];
6990 debugf("mDNS_Close: RR Cache was using %ld records, %d active", rrcache_totalused
, rrcache_active
);
6991 if (rrcache_active
!= m
->rrcache_active
)
6992 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active
, m
->rrcache_active
);
6994 m
->Questions
= mDNSNULL
; // We won't be answering any more questions!
6996 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
6997 if (intf
->Advertise
)
6998 mDNS_DeadvertiseInterface(m
, intf
);
7000 // Make sure there are nothing but deregistering records remaining in the list
7001 if (m
->CurrentRecord
) LogMsg("mDNS_Close ERROR m->CurrentRecord already set");
7002 m
->CurrentRecord
= m
->ResourceRecords
;
7003 while (m
->CurrentRecord
)
7005 AuthRecord
*rr
= m
->CurrentRecord
;
7006 m
->CurrentRecord
= rr
->next
;
7007 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
7009 debugf("mDNS_Close: Record type %X still in ResourceRecords list %##s", rr
->resrec
.RecordType
, rr
->resrec
.name
.c
);
7010 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7014 if (m
->ResourceRecords
) debugf("mDNS_Close: Sending final packets for deregistering records");
7015 else debugf("mDNS_Close: No deregistering records remain");
7017 // If any deregistering records remain, send their deregistration announcements before we exit
7018 if (m
->mDNSPlatformStatus
!= mStatus_NoError
)
7019 DiscardDeregistrations(m
);
7021 while (m
->ResourceRecords
)
7025 debugf("mDNS_Close: mDNSPlatformClose");
7026 mDNSPlatformClose(m
);
7027 debugf("mDNS_Close: done");