]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-58.8.1.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
1 /*
2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 *
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.
25 *
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).
30
31 * Formatting notes:
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.)
43
44 Change History (most recent first):
45
46 $Log: mDNS.c,v $
47 Revision 1.307.2.13 2005/01/28 05:39:12 cheshire
48 Remove LogMsg()
49
50 Revision 1.307.2.12 2005/01/28 05:02:05 cheshire
51 <rdar://problem/3770559> SUPan: Replace IP TTL 255 check with local-subnet check
52
53 Revision 1.307.2.11 2005/01/28 04:03:23 cheshire
54 <rdar://problem/3759302> SUPan: Current method of doing subtypes causes name collisions
55 Summary: Pulled in ConstructServiceName, CountSubTypes and AllocateSubTypes from Tiger version.
56
57 Revision 1.307.2.10 2004/06/18 17:28:18 cheshire
58 <rdar://problem/3588761> Current method of doing subtypes causes name collisions
59
60 Revision 1.307.2.9 2004/06/18 00:31:51 cheshire
61 <rdar://problem/3617655> mDNSResponder escape handling inconsistent with BIND
62 (Prerequisite for fixing <rdar://problem/3588761>)
63
64 Revision 1.307.2.8 2004/04/03 05:18:19 bradley
65 Added cast to fix signed/unsigned warning due to int promotion.
66
67 Revision 1.307.2.7 2004/03/30 06:46:24 cheshire
68 Compiler warning fixes from Don Woodward at Roku Labs
69
70 Revision 1.307.2.6 2004/03/09 03:03:38 cheshire
71 <rdar://problem/3581961> Don't take lock until after mDNS_Update() has validated that the data is good
72
73 Revision 1.307.2.5 2004/03/02 02:55:24 cheshire
74 <rdar://problem/3549576> Properly support "_services._dns-sd._udp" meta-queries
75
76 Revision 1.307.2.4 2004/02/18 01:55:08 cheshire
77 <rdar://problem/3553472>: Increase delay to 400ms when answering queries with multi-packet KA lists
78
79 Revision 1.307.2.3 2004/01/28 23:08:45 cheshire
80 <rdar://problem/3488559>: Hard code domain enumeration functions to return ".local" only
81
82 Revision 1.307.2.2 2003/12/20 01:51:40 cheshire
83 <rdar://problem/3515876>: Error putting additional records into packets
84 Another fix from Rampi: responseptr needs to be updated inside the "for" loop,
85 after every record, not once at the end.
86
87 Revision 1.307.2.1 2003/12/03 11:20:27 cheshire
88 <rdar://problem/3457718>: Stop and start of a service uses old ip address (with old port number)
89
90 Revision 1.307 2003/09/09 20:13:30 cheshire
91 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
92 Ammend checkin 1.304: Off-by-one error: By this place in the function we've already decremented
93 rr->AnnounceCount, so the check needs to be for InitialAnnounceCount-1, not InitialAnnounceCount
94
95 Revision 1.306 2003/09/09 03:00:03 cheshire
96 <rdar://problem/3413099> Services take a long time to disappear when switching networks.
97 Added two constants: kDefaultReconfirmTimeForNoAnswer and kDefaultReconfirmTimeForCableDisconnect
98
99 Revision 1.305 2003/09/09 02:49:31 cheshire
100 <rdar://problem/3413975> Initial probes and queries not grouped on wake-from-sleep
101
102 Revision 1.304 2003/09/09 02:41:19 cheshire
103 <rdar://problem/3411105> Don't send a Goodbye record if we never announced it
104
105 Revision 1.303 2003/09/05 19:55:02 cheshire
106 <rdar://problem/3409533> Include address records when announcing SRV records
107
108 Revision 1.302 2003/09/05 00:01:36 cheshire
109 <rdar://problem/3407549> Don't accelerate queries that have large KA lists
110
111 Revision 1.301 2003/09/04 22:51:13 cheshire
112 <rdar://problem/3398213> Group probes and goodbyes better
113
114 Revision 1.300 2003/09/03 02:40:37 cheshire
115 <rdar://problem/3404842> mDNSResponder complains about '_'s
116 Underscores are not supposed to be legal in standard DNS names, but IANA appears
117 to have allowed them in previous service name registrations, so we should too.
118
119 Revision 1.299 2003/09/03 02:33:09 cheshire
120 <rdar://problem/3404795> CacheRecordRmv ERROR
121 Don't update m->NewQuestions until *after* CheckCacheExpiration();
122
123 Revision 1.298 2003/09/03 01:47:01 cheshire
124 <rdar://problem/3319418> Rendezvous services always in a state of flux
125 Change mDNS_Reconfirm_internal() minimum timeout from 5 seconds to 45-60 seconds
126
127 Revision 1.297 2003/08/29 19:44:15 cheshire
128 <rdar://problem/3400967> Traffic reduction: Eliminate synchronized QUs when a new service appears
129 1. Use m->RandomQueryDelay to impose a random delay in the range 0-500ms on queries
130 that already have at least one unique answer in the cache
131 2. For these queries, go straight to QM, skipping QU
132
133 Revision 1.296 2003/08/29 19:08:21 cheshire
134 <rdar://problem/3400986> Traffic reduction: Eliminate huge KA lists after wake from sleep
135 Known answers are no longer eligible to go in the KA list if they are more than half-way to their expiry time.
136
137 Revision 1.295 2003/08/28 01:10:59 cheshire
138 <rdar://problem/3396034> Add syslog message to report when query is reset because of immediate answer burst
139
140 Revision 1.294 2003/08/27 02:30:22 cheshire
141 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
142 One more change: "query->GotTXT" is now a straightforward bi-state boolean again
143
144 Revision 1.293 2003/08/27 02:25:31 cheshire
145 <rdar://problem/3395909> Traffic Reduction: Inefficiencies in DNSServiceResolverResolve()
146
147 Revision 1.292 2003/08/21 19:27:36 cheshire
148 <rdar://problem/3387878> Traffic reduction: No need to announce record for longer than TTL
149
150 Revision 1.291 2003/08/21 18:57:44 cheshire
151 <rdar://problem/3387140> Synchronized queries on the network
152
153 Revision 1.290 2003/08/21 02:25:23 cheshire
154 Minor changes to comments and debugf() messages
155
156 Revision 1.289 2003/08/21 02:21:50 cheshire
157 <rdar://problem/3386473> Efficiency: Reduce repeated queries
158
159 Revision 1.288 2003/08/20 23:39:30 cheshire
160 <rdar://problem/3344098> Review syslog messages, and remove as appropriate
161
162 Revision 1.287 2003/08/20 20:47:18 cheshire
163 Fix compiler warning
164
165 Revision 1.286 2003/08/20 02:18:51 cheshire
166 <rdar://problem/3344098> Cleanup: Review syslog messages
167
168 Revision 1.285 2003/08/20 01:59:06 cheshire
169 <rdar://problem/3384478> rdatahash and rdnamehash not updated after changing rdata
170 Made new routine SetNewRData() to update rdlength, rdestimate, rdatahash and rdnamehash in one place
171
172 Revision 1.284 2003/08/19 22:20:00 cheshire
173 <rdar://problem/3376721> Don't use IPv6 on interfaces that have a routable IPv4 address configured
174 More minor refinements
175
176 Revision 1.283 2003/08/19 22:16:27 cheshire
177 Minor fix: Add missing "mDNS_Unlock(m);" in mDNS_DeregisterInterface() error case.
178
179 Revision 1.282 2003/08/19 06:48:25 cheshire
180 <rdar://problem/3376552> Guard against excessive record updates
181 Each record starts with 10 UpdateCredits.
182 Every update consumes one UpdateCredit.
183 UpdateCredits are replenished at a rate of one one per minute, up to a maximum of 10.
184 As the number of UpdateCredits declines, the number of announcements is similarly scaled back.
185 When fewer than 5 UpdateCredits remain, the first announcement is also delayed by an increasing amount.
186
187 Revision 1.281 2003/08/19 04:49:28 cheshire
188 <rdar://problem/3368159> Interaction between v4, v6 and dual-stack hosts not working quite right
189 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.
190 2. When we see the first v4 (or first v6) member of a group, we re-trigger questions and probes on that interface.
191 3. When we see the last v4 (or v6) member of a group go away, we revalidate all the records received on that interface.
192
193 Revision 1.280 2003/08/19 02:33:36 cheshire
194 Update comments
195
196 Revision 1.279 2003/08/19 02:31:11 cheshire
197 <rdar://problem/3378386> mDNSResponder overenthusiastic with final expiration queries
198 Final expiration queries now only mark the question for sending on the particular interface
199 pertaining to the record that's expiring.
200
201 Revision 1.278 2003/08/18 22:53:37 cheshire
202 <rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformTimeNow()
203
204 Revision 1.277 2003/08/18 19:05:44 cheshire
205 <rdar://problem/3382423> UpdateRecord not working right
206 Added "newrdlength" field to hold new length of updated rdata
207
208 Revision 1.276 2003/08/16 03:39:00 cheshire
209 <rdar://problem/3338440> InterfaceID -1 indicates "local only"
210
211 Revision 1.275 2003/08/16 02:51:27 cheshire
212 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
213 Don't try to compute namehash etc, until *after* validating the name
214
215 Revision 1.274 2003/08/16 01:12:40 cheshire
216 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
217 Now that the minimum rdata object size has been reduced to 64 bytes, it is no longer safe to do a
218 simple C structure assignment of a domainname, because that object is defined to be 256 bytes long,
219 and in the process of copying it, the C compiler may run off the end of the rdata object into
220 unmapped memory. All assignments of domainname objects of uncertain size are now replaced with a
221 call to the macro AssignDomainName(), which is careful to copy only as many bytes as are valid.
222
223 Revision 1.273 2003/08/15 20:16:02 cheshire
224 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
225 We want to avoid touching the rdata pages, so we don't page them in.
226 1. RDLength was stored with the rdata, which meant touching the page just to find the length.
227 Moved this from the RData to the ResourceRecord object.
228 2. To avoid unnecessarily touching the rdata just to compare it,
229 compute a hash of the rdata and store the hash in the ResourceRecord object.
230
231 Revision 1.272 2003/08/14 19:29:04 cheshire
232 <rdar://problem/3378473> Include cache records in SIGINFO output
233 Moved declarations of DNSTypeName() and GetRRDisplayString to mDNSClientAPI.h so daemon.c can use them
234
235 Revision 1.271 2003/08/14 02:17:05 cheshire
236 <rdar://problem/3375491> Split generic ResourceRecord type into two separate types: AuthRecord and CacheRecord
237
238 Revision 1.270 2003/08/13 17:07:28 ksekar
239 Bug #: <rdar://problem/3376458>: Extra RR linked to list even if registration fails - causes crash
240 Added check to result of mDNS_Register() before linking extra record into list.
241
242 Revision 1.269 2003/08/12 19:56:23 cheshire
243 Update to APSL 2.0
244
245 Revision 1.268 2003/08/12 15:01:10 cheshire
246 Add comments
247
248 Revision 1.267 2003/08/12 14:59:27 cheshire
249 <rdar://problem/3374490> Rate-limiting blocks some legitimate responses
250 When setting LastMCTime also record LastMCInterface. When checking LastMCTime to determine
251 whether to suppress the response, also check LastMCInterface to see if it matches.
252
253 Revision 1.266 2003/08/12 12:47:16 cheshire
254 In mDNSCoreMachineSleep debugf message, display value of m->timenow
255
256 Revision 1.265 2003/08/11 20:04:28 cheshire
257 <rdar://problem/3366553> Improve efficiency by restricting cases where we have to walk the entire cache
258
259 Revision 1.264 2003/08/09 00:55:02 cheshire
260 <rdar://problem/3366553> mDNSResponder is taking 20-30% of the CPU
261 Don't scan the whole cache after every packet.
262
263 Revision 1.263 2003/08/09 00:35:29 cheshire
264 Moved AnswerNewQuestion() later in the file, in preparation for next checkin
265
266 Revision 1.262 2003/08/08 19:50:33 cheshire
267 <rdar://problem/3370332> Remove "Cache size now xxx" messages
268
269 Revision 1.261 2003/08/08 19:18:45 cheshire
270 <rdar://problem/3271219> Only retrigger questions on platforms with the "PhantomInterfaces" bug
271
272 Revision 1.260 2003/08/08 18:55:48 cheshire
273 <rdar://problem/3370365> Guard against time going backwards
274
275 Revision 1.259 2003/08/08 18:36:04 cheshire
276 <rdar://problem/3344154> Only need to revalidate on interface removal on platforms that have the PhantomInterfaces bug
277
278 Revision 1.258 2003/08/08 16:22:05 cheshire
279 <rdar://problem/3335473> Need to check validity of TXT (and other) records
280 Remove unneeded LogMsg
281
282 Revision 1.257 2003/08/07 01:41:08 cheshire
283 <rdar://problem/3367346> Ignore packets with invalid source address (all zeroes or all ones)
284
285 Revision 1.256 2003/08/06 23:25:51 cheshire
286 <rdar://problem/3290674> Increase TTL for A/AAAA/SRV from one minute to four
287
288 Revision 1.255 2003/08/06 23:22:50 cheshire
289 Add symbolic constants: kDefaultTTLforUnique (one minute) and kDefaultTTLforShared (two hours)
290
291 Revision 1.254 2003/08/06 21:33:39 cheshire
292 Fix compiler warnings on PocketPC 2003 (Windows CE)
293
294 Revision 1.253 2003/08/06 20:43:57 cheshire
295 <rdar://problem/3335473> Need to check validity of TXT (and other) records
296 Created ValidateDomainName() and ValidateRData(), used by mDNS_Register_internal() and mDNS_Update()
297
298 Revision 1.252 2003/08/06 20:35:47 cheshire
299 Enhance debugging routine GetRRDisplayString() so it can also be used to display
300 other RDataBody objects, not just the one currently attached the given ResourceRecord
301
302 Revision 1.251 2003/08/06 19:07:34 cheshire
303 <rdar://problem/3366251> mDNSResponder not inhibiting multicast responses as much as it should
304 Was checking LastAPTime instead of LastMCTime
305
306 Revision 1.250 2003/08/06 19:01:55 cheshire
307 Update comments
308
309 Revision 1.249 2003/08/06 00:13:28 cheshire
310 Tidy up debugf messages
311
312 Revision 1.248 2003/08/05 22:20:15 cheshire
313 <rdar://problem/3330324> Need to check IP TTL on responses
314
315 Revision 1.247 2003/08/05 00:56:39 cheshire
316 <rdar://problem/3357075> mDNSResponder sending additional records, even after precursor record suppressed
317
318 Revision 1.246 2003/08/04 19:20:49 cheshire
319 Add kDNSQType_ANY to list in DNSTypeName() so it can be displayed in debugging messages
320
321 Revision 1.245 2003/08/02 01:56:29 cheshire
322 For debugging: log message if we ever get more than one question in a truncated packet
323
324 Revision 1.244 2003/08/01 23:55:32 cheshire
325 Fix for compiler warnings on Windows, submitted by Bob Bradley
326
327 Revision 1.243 2003/07/25 02:26:09 cheshire
328 Typo: FIxed missing semicolon
329
330 Revision 1.242 2003/07/25 01:18:41 cheshire
331 Fix memory leak on shutdown in mDNS_Close() (detected in Windows version)
332
333 Revision 1.241 2003/07/23 21:03:42 cheshire
334 Only show "Found record..." debugf message in verbose mode
335
336 Revision 1.240 2003/07/23 21:01:11 cheshire
337 <rdar://problem/3340584> Need Nagle-style algorithm to coalesce multiple packets into one
338 After sending a packet, suppress further sending for the next 100ms.
339
340 Revision 1.239 2003/07/22 01:30:05 cheshire
341 <rdar://problem/3329099> Don't try to add the same question to the duplicate-questions list more than once
342
343 Revision 1.238 2003/07/22 00:10:20 cheshire
344 <rdar://problem/3337355> ConvertDomainLabelToCString() needs to escape escape characters
345
346 Revision 1.237 2003/07/19 03:23:13 cheshire
347 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
348
349 Revision 1.236 2003/07/19 03:04:55 cheshire
350 Fix warnings; some debugf message improvements
351
352 Revision 1.235 2003/07/19 00:03:32 cheshire
353 <rdar://problem/3160248> ScheduleNextTask needs to be smarter after a no-op packet is received
354 ScheduleNextTask is quite an expensive operation.
355 We don't need to do all that work after receiving a no-op packet that didn't change our state.
356
357 Revision 1.234 2003/07/18 23:52:11 cheshire
358 To improve consistency of field naming, global search-and-replace:
359 NextProbeTime -> NextScheduledProbe
360 NextResponseTime -> NextScheduledResponse
361
362 Revision 1.233 2003/07/18 00:29:59 cheshire
363 <rdar://problem/3268878> Remove mDNSResponder version from packet header and use HINFO record instead
364
365 Revision 1.232 2003/07/18 00:11:38 cheshire
366 Add extra case to switch statements to handle HINFO data for Get, Put and Display
367 (In all but GetRDLength(), this is is just a fall-through to kDNSType_TXT)
368
369 Revision 1.231 2003/07/18 00:06:37 cheshire
370 To make code a little easier to read in GetRDLength(), search-and-replace "rr->rdata->u." with "rd->"
371
372 Revision 1.230 2003/07/17 18:16:54 cheshire
373 <rdar://problem/3319418> Rendezvous services always in a state of flux
374 In preparation for working on this, made some debugf messages a little more selective
375
376 Revision 1.229 2003/07/17 17:35:04 cheshire
377 <rdar://problem/3325583> Rate-limit responses, to guard against packet flooding
378
379 Revision 1.228 2003/07/16 20:50:27 cheshire
380 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
381
382 Revision 1.227 2003/07/16 05:01:36 cheshire
383 Add fields 'LargeAnswers' and 'ExpectUnicastResponse' in preparation for
384 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
385
386 Revision 1.226 2003/07/16 04:51:44 cheshire
387 Fix use of constant 'mDNSPlatformOneSecond' where it should have said 'InitialQuestionInterval'
388
389 Revision 1.225 2003/07/16 04:46:41 cheshire
390 Minor wording cleanup: The correct DNS term is "response", not "reply"
391
392 Revision 1.224 2003/07/16 04:39:02 cheshire
393 Textual cleanup (no change to functionality):
394 Construct "c >= 'A' && c <= 'Z'" appears in too many places; replaced with macro "mDNSIsUpperCase(c)"
395
396 Revision 1.223 2003/07/16 00:09:22 cheshire
397 Textual cleanup (no change to functionality):
398 Construct "((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)" appears in too many places;
399 replace with macro "TicksTTL(rr)"
400 Construct "rr->TimeRcvd + ((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond)"
401 replaced with macro "RRExpireTime(rr)"
402
403 Revision 1.222 2003/07/15 23:40:46 cheshire
404 Function rename: UpdateDupSuppressInfo() is more accurately called ExpireDupSuppressInfo()
405
406 Revision 1.221 2003/07/15 22:17:56 cheshire
407 <rdar://problem/3328394> mDNSResponder is not being efficient when doing certain queries
408
409 Revision 1.220 2003/07/15 02:12:51 cheshire
410 Slight tidy-up of debugf messages and comments
411
412 Revision 1.219 2003/07/15 01:55:12 cheshire
413 <rdar://problem/3315777> Need to implement service registration with subtypes
414
415 Revision 1.218 2003/07/14 16:26:06 cheshire
416 <rdar://problem/3324795> Duplicate query suppression not working right
417 Refinement: Don't record DS information for a question in the first quarter second
418 right after we send it -- in the case where a question happens to be accelerated by
419 the maximum allowed amount, we don't want it to then be suppressed because the previous
420 time *we* sent that question falls (just) within the valid duplicate suppression window.
421
422 Revision 1.217 2003/07/13 04:43:53 cheshire
423 <rdar://problem/3325169> Services on multiple interfaces not always resolving
424 Minor refinement: No need to make address query broader than the original SRV query that provoked it
425
426 Revision 1.216 2003/07/13 03:13:17 cheshire
427 <rdar://problem/3325169> Services on multiple interfaces not always resolving
428 If we get an identical SRV on a second interface, convert address queries to non-specific
429
430 Revision 1.215 2003/07/13 02:28:00 cheshire
431 <rdar://problem/3325166> SendResponses didn't all its responses
432 Delete all references to RRInterfaceActive -- it's now superfluous
433
434 Revision 1.214 2003/07/13 01:47:53 cheshire
435 Fix one error and one warning in the Windows build
436
437 Revision 1.213 2003/07/12 04:25:48 cheshire
438 Fix minor signed/unsigned warnings
439
440 Revision 1.212 2003/07/12 01:59:11 cheshire
441 Minor changes to debugf messages
442
443 Revision 1.211 2003/07/12 01:47:01 cheshire
444 <rdar://problem/3324495> After name conflict, appended number should be higher than previous number
445
446 Revision 1.210 2003/07/12 01:43:28 cheshire
447 <rdar://problem/3324795> Duplicate query suppression not working right
448 The correct cutoff time for duplicate query suppression is timenow less one-half the query interval.
449 The code was incorrectly using the last query time plus one-half the query interval.
450 This was only correct in the case where query acceleration was not in effect.
451
452 Revision 1.209 2003/07/12 01:27:50 cheshire
453 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
454 Fix missing "-1" in RemoveLabelSuffix()
455
456 Revision 1.208 2003/07/11 01:32:38 cheshire
457 Syntactic cleanup (no change to funcationality): Now that we only have one host name,
458 rename field "hostname1" to "hostname", and field "RR_A1" to "RR_A".
459
460 Revision 1.207 2003/07/11 01:28:00 cheshire
461 <rdar://problem/3161289> No more local.arpa
462
463 Revision 1.206 2003/07/11 00:45:02 cheshire
464 <rdar://problem/3321909> Client should get callback confirming successful host name registration
465
466 Revision 1.205 2003/07/11 00:40:18 cheshire
467 Tidy up debug message in HostNameCallback()
468
469 Revision 1.204 2003/07/11 00:20:32 cheshire
470 <rdar://problem/3320087> mDNSResponder should log a message after 16 unsuccessful probes
471
472 Revision 1.203 2003/07/10 23:53:41 cheshire
473 <rdar://problem/3320079> Hostname conflict naming should not use two hyphens
474
475 Revision 1.202 2003/07/04 02:23:20 cheshire
476 <rdar://problem/3311955> Responder too aggressive at flushing stale data
477 Changed mDNSResponder to require four unanswered queries before purging a record, instead of two.
478
479 Revision 1.201 2003/07/04 01:09:41 cheshire
480 <rdar://problem/3315775> Need to implement subtype queries
481 Modified ConstructServiceName() to allow three-part service types
482
483 Revision 1.200 2003/07/03 23:55:26 cheshire
484 Minor change to wording of syslog warning messages
485
486 Revision 1.199 2003/07/03 23:51:13 cheshire
487 <rdar://problem/3315652>: Lots of "have given xxx answers" syslog warnings
488 Added more detailed debugging information
489
490 Revision 1.198 2003/07/03 22:19:30 cheshire
491 <rdar://problem/3314346> Bug fix in 3274153 breaks TiVo
492 Make exception to allow _tivo_servemedia._tcp.
493
494 Revision 1.197 2003/07/02 22:33:05 cheshire
495 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
496 Minor refinements:
497 When cache is exhausted, verify that rrcache_totalused == rrcache_size and report if not
498 Allow cache to grow to 512 records before considering it a potential denial-of-service attack
499
500 Revision 1.196 2003/07/02 21:19:45 cheshire
501 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
502
503 Revision 1.195 2003/07/02 19:56:58 cheshire
504 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
505 Minor refinement: m->rrcache_active was not being decremented when
506 an active record was deleted because its TTL expired
507
508 Revision 1.194 2003/07/02 18:47:40 cheshire
509 Minor wording change to log messages
510
511 Revision 1.193 2003/07/02 02:44:13 cheshire
512 Fix warning in non-debug build
513
514 Revision 1.192 2003/07/02 02:41:23 cheshire
515 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
516
517 Revision 1.191 2003/07/02 02:30:51 cheshire
518 HashSlot() returns an array index. It can't be negative; hence it should not be signed.
519
520 Revision 1.190 2003/06/27 00:03:05 vlubet
521 <rdar://problem/3304625> Merge of build failure fix for gcc 3.3
522
523 Revision 1.189 2003/06/11 19:24:03 cheshire
524 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
525 Slight refinement to previous checkin
526
527 Revision 1.188 2003/06/10 20:33:28 cheshire
528 <rdar://problem/3287141> Crash in SendQueries/SendResponses when no active interfaces
529
530 Revision 1.187 2003/06/10 04:30:44 cheshire
531 <rdar://problem/3286234> Need to re-probe/re-announce on configuration change
532 Only interface-specific records were re-probing and re-announcing, not non-specific records.
533
534 Revision 1.186 2003/06/10 04:24:39 cheshire
535 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
536 Some additional refinements:
537 Don't try to do this for unicast-response queries
538 better tracking of Qs and KAs in multi-packet KA lists
539
540 Revision 1.185 2003/06/10 03:52:49 cheshire
541 Update comments and debug messages
542
543 Revision 1.184 2003/06/10 02:26:39 cheshire
544 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
545 Make mDNS_Reconfirm() call mDNS_Lock(), like the other API routines
546
547 Revision 1.183 2003/06/09 18:53:13 cheshire
548 Simplify some debugf() statements (replaced block of 25 lines with 2 lines)
549
550 Revision 1.182 2003/06/09 18:38:42 cheshire
551 <rdar://problem/3285082> Need to be more tolerant when there are mDNS proxies on the network
552 Only issue a correction if the TTL in the proxy packet is less than half the correct value.
553
554 Revision 1.181 2003/06/07 06:45:05 cheshire
555 <rdar://problem/3283666> No need for multiple machines to all be sending the same queries
556
557 Revision 1.180 2003/06/07 06:31:07 cheshire
558 Create little four-line helper function "FindIdenticalRecordInCache()"
559
560 Revision 1.179 2003/06/07 06:28:13 cheshire
561 For clarity, change name of "DNSQuestion q" to "DNSQuestion pktq"
562
563 Revision 1.178 2003/06/07 06:25:12 cheshire
564 Update some comments
565
566 Revision 1.177 2003/06/07 04:50:53 cheshire
567 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
568
569 Revision 1.176 2003/06/07 04:33:26 cheshire
570 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
571 Minor change: Increment/decrement logic for q->CurrentAnswers should be in
572 CacheRecordAdd() and CacheRecordRmv(), not AnswerQuestionWithResourceRecord()
573
574 Revision 1.175 2003/06/07 04:11:52 cheshire
575 Minor changes to comments and debug messages
576
577 Revision 1.174 2003/06/07 01:46:38 cheshire
578 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
579
580 Revision 1.173 2003/06/07 01:22:13 cheshire
581 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
582
583 Revision 1.172 2003/06/07 00:59:42 cheshire
584 <rdar://problem/3283454> Need some randomness to spread queries on the network
585
586 Revision 1.171 2003/06/06 21:41:10 cheshire
587 For consistency, mDNS_StopQuery() should return an mStatus result, just like all the other mDNSCore routines
588
589 Revision 1.170 2003/06/06 21:38:55 cheshire
590 Renamed 'NewData' as 'FreshData' (The data may not be new data, just a refresh of data that we
591 already had in our cache. This refreshes our TTL on the data, but the data itself stays the same.)
592
593 Revision 1.169 2003/06/06 21:35:55 cheshire
594 Fix mis-named macro: GetRRHostNameTarget is really GetRRDomainNameTarget
595 (the target is a domain name, but not necessarily a host name)
596
597 Revision 1.168 2003/06/06 21:33:31 cheshire
598 Instead of using (mDNSPlatformOneSecond/2) all over the place, define a constant "InitialQuestionInterval"
599
600 Revision 1.167 2003/06/06 21:30:42 cheshire
601 <rdar://problem/3282962> Don't delay queries for shared record types
602
603 Revision 1.166 2003/06/06 17:20:14 cheshire
604 For clarity, rename question fields name/rrtype/rrclass as qname/qtype/qclass
605 (Global search-and-replace; no functional change to code execution.)
606
607 Revision 1.165 2003/06/04 02:53:21 cheshire
608 Add some "#pragma warning" lines so it compiles clean on Microsoft compilers
609
610 Revision 1.164 2003/06/04 01:25:33 cheshire
611 <rdar://problem/3274950> Cannot perform multi-packet known-answer suppression messages
612 Display time interval between first and subsequent queries
613
614 Revision 1.163 2003/06/03 19:58:14 cheshire
615 <rdar://problem/3277665> mDNS_DeregisterService() fixes:
616 When forcibly deregistering after a conflict, ensure we don't send an incorrect goodbye packet.
617 Guard against a couple of possible mDNS_DeregisterService() race conditions.
618
619 Revision 1.162 2003/06/03 19:30:39 cheshire
620 Minor addition refinements for
621 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
622
623 Revision 1.161 2003/06/03 18:29:03 cheshire
624 Minor changes to comments and debugf() messages
625
626 Revision 1.160 2003/06/03 05:02:16 cheshire
627 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
628
629 Revision 1.159 2003/06/03 03:31:57 cheshire
630 <rdar://problem/3277033> False self-conflict when there are duplicate registrations on one machine
631
632 Revision 1.158 2003/06/02 22:57:09 cheshire
633 Minor clarifying changes to comments and log messages;
634 IdenticalResourceRecordAnyInterface() is really more accurately called just IdenticalResourceRecord()
635
636 Revision 1.157 2003/05/31 00:09:49 cheshire
637 <rdar://problem/3274862> Add ability to discover what services are on a network
638
639 Revision 1.156 2003/05/30 23:56:49 cheshire
640 <rdar://problem/3274847> Crash after error in mDNS_RegisterService()
641 Need to set "sr->Extras = mDNSNULL" before returning
642
643 Revision 1.155 2003/05/30 23:48:00 cheshire
644 <rdar://problem/3274832> Announcements not properly grouped
645 Due to inconsistent setting of rr->LastAPTime at different places in the
646 code, announcements were not properly grouped into a single packet.
647 Fixed by creating a single routine called InitializeLastAPTime().
648
649 Revision 1.154 2003/05/30 23:38:14 cheshire
650 <rdar://problem/3274814> Fix error in IPv6 reverse-mapping PTR records
651 Wrote buffer[32] where it should have said buffer[64]
652
653 Revision 1.153 2003/05/30 19:10:56 cheshire
654 <rdar://problem/3274153> ConstructServiceName needs to be more restrictive
655
656 Revision 1.152 2003/05/29 22:39:16 cheshire
657 <rdar://problem/3273209> Don't truncate strings in the middle of a UTF-8 character
658
659 Revision 1.151 2003/05/29 06:35:42 cheshire
660 <rdar://problem/3272221> mDNSCoreReceiveResponse() purging wrong record
661
662 Revision 1.150 2003/05/29 06:25:45 cheshire
663 <rdar://problem/3272218> Need to call CheckCacheExpiration() *before* AnswerNewQuestion()
664
665 Revision 1.149 2003/05/29 06:18:39 cheshire
666 <rdar://problem/3272217> Split AnswerLocalQuestions into CacheRecordAdd and CacheRecordRmv
667
668 Revision 1.148 2003/05/29 06:11:34 cheshire
669 <rdar://problem/3272214> Report if there appear to be too many "Resolve" callbacks
670
671 Revision 1.147 2003/05/29 06:01:18 cheshire
672 Change some debugf() calls to LogMsg() calls to help with debugging
673
674 Revision 1.146 2003/05/28 21:00:44 cheshire
675 Re-enable "immediate answer burst" debugf message
676
677 Revision 1.145 2003/05/28 20:57:44 cheshire
678 <rdar://problem/3271550> mDNSResponder reports "Cannot perform multi-packet
679 known-answer suppression ..." This is a known issue caused by a bug in the OS X 10.2
680 version of mDNSResponder, so for now we should suppress this warning message.
681
682 Revision 1.144 2003/05/28 18:05:12 cheshire
683 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
684 Fix silly mistake: old logic allowed "TDP" and "UCP" as valid names
685
686 Revision 1.143 2003/05/28 04:31:29 cheshire
687 <rdar://problem/3270733> mDNSResponder not sending probes at the prescribed time
688
689 Revision 1.142 2003/05/28 03:13:07 cheshire
690 <rdar://problem/3009899> mDNSResponder allows invalid service registrations
691 Require that the transport protocol be _udp or _tcp
692
693 Revision 1.141 2003/05/28 02:19:12 cheshire
694 <rdar://problem/3270634> Misleading messages generated by iChat
695 Better fix: Only generate the log message for queries where the TC bit is set.
696
697 Revision 1.140 2003/05/28 01:55:24 cheshire
698 Minor change to log messages
699
700 Revision 1.139 2003/05/28 01:52:51 cheshire
701 <rdar://problem/3270634> Misleading messages generated by iChat
702
703 Revision 1.138 2003/05/27 22:35:00 cheshire
704 <rdar://problem/3270277> mDNS_RegisterInterface needs to retrigger questions
705
706 Revision 1.137 2003/05/27 20:04:33 cheshire
707 <rdar://problem/3269900> mDNSResponder crash in mDNS_vsnprintf()
708
709 Revision 1.136 2003/05/27 18:50:07 cheshire
710 <rdar://problem/3269768> mDNS_StartResolveService doesn't inform client of port number changes
711
712 Revision 1.135 2003/05/26 04:57:28 cheshire
713 <rdar://problem/3268953> Delay queries when there are already answers in the cache
714
715 Revision 1.134 2003/05/26 04:54:54 cheshire
716 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
717 Accidentally deleted '%' case from the switch statement
718
719 Revision 1.133 2003/05/26 03:21:27 cheshire
720 Tidy up address structure naming:
721 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
722 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
723 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
724
725 Revision 1.132 2003/05/26 03:01:26 cheshire
726 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
727
728 Revision 1.131 2003/05/26 00:42:05 cheshire
729 <rdar://problem/3268876> Temporarily include mDNSResponder version in packets
730
731 Revision 1.130 2003/05/24 16:39:48 cheshire
732 <rdar://problem/3268631> SendResponses also needs to handle multihoming better
733
734 Revision 1.129 2003/05/23 02:15:37 cheshire
735 Fixed misleading use of the term "duplicate suppression" where it should have
736 said "known answer suppression". (Duplicate answer suppression is something
737 different, and duplicate question suppression is yet another thing, so the use
738 of the completely vague term "duplicate suppression" was particularly bad.)
739
740 Revision 1.128 2003/05/23 01:55:13 cheshire
741 <rdar://problem/3267127> After name change, mDNSResponder needs to re-probe for name uniqueness
742
743 Revision 1.127 2003/05/23 01:02:15 ksekar
744 Bug #: <rdar://problem/3032577>: mDNSResponder needs to include unique id in default name
745
746 Revision 1.126 2003/05/22 02:29:22 cheshire
747 <rdar://problem/2984918> SendQueries needs to handle multihoming better
748 Complete rewrite of SendQueries. Works much better now :-)
749
750 Revision 1.125 2003/05/22 01:50:45 cheshire
751 Fix warnings, and improve log messages
752
753 Revision 1.124 2003/05/22 01:41:50 cheshire
754 DiscardDeregistrations doesn't need InterfaceID parameter
755
756 Revision 1.123 2003/05/22 01:38:55 cheshire
757 Change bracketing of #pragma mark
758
759 Revision 1.122 2003/05/21 19:59:04 cheshire
760 <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
761 Minor refinements; make sure we don't truncate in the middle of a multi-byte UTF-8 character
762
763 Revision 1.121 2003/05/21 17:54:07 ksekar
764 Bug #: <rdar://problem/3148431> ER: Tweak responder's default name conflict behavior
765 New rename behavior - domain name "foo" becomes "foo--2" on conflict, richtext name becomes "foo (2)"
766
767 Revision 1.120 2003/05/19 22:14:14 ksekar
768 <rdar://problem/3162914> mDNS probe denials/conflicts not detected unless conflict is of the same type
769
770 Revision 1.119 2003/05/16 01:34:10 cheshire
771 Fix some warnings
772
773 Revision 1.118 2003/05/14 18:48:40 cheshire
774 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
775 More minor refinements:
776 CFSocket.c needs to do *all* its mDNS_DeregisterInterface calls before freeing memory
777 mDNS_DeregisterInterface revalidates cache record when *any* representative of an interface goes away
778
779 Revision 1.117 2003/05/14 07:08:36 cheshire
780 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
781 Previously, when there was any network configuration change, mDNSResponder
782 would tear down the entire list of active interfaces and start again.
783 That was very disruptive, and caused the entire cache to be flushed,
784 and caused lots of extra network traffic. Now it only removes interfaces
785 that have really gone, and only adds new ones that weren't there before.
786
787 Revision 1.116 2003/05/14 06:51:56 cheshire
788 <rdar://problem/3027144> Rendezvous doesn't refresh server info if changed during sleep
789
790 Revision 1.115 2003/05/14 06:44:31 cheshire
791 Improve debugging message
792
793 Revision 1.114 2003/05/07 01:47:03 cheshire
794 <rdar://problem/3250330> Also protect against NULL domainlabels
795
796 Revision 1.113 2003/05/07 00:28:18 cheshire
797 <rdar://problem/3250330> Need to make mDNSResponder more defensive against bad clients
798
799 Revision 1.112 2003/05/06 00:00:46 cheshire
800 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
801
802 Revision 1.111 2003/05/05 23:42:08 cheshire
803 <rdar://problem/3245631> Resolves never succeed
804 Was setting "rr->LastAPTime = timenow - rr->LastAPTime"
805 instead of "rr->LastAPTime = timenow - rr->ThisAPInterval"
806
807 Revision 1.110 2003/04/30 21:09:59 cheshire
808 <rdar://problem/3244727> mDNS_vsnprintf needs to be more defensive against invalid domain names
809
810 Revision 1.109 2003/04/26 02:41:56 cheshire
811 <rdar://problem/3241281> Change timenow from a local variable to a structure member
812
813 Revision 1.108 2003/04/25 01:45:56 cheshire
814 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
815
816 Revision 1.107 2003/04/25 00:41:31 cheshire
817 <rdar://problem/3239912> Create single routine PurgeCacheResourceRecord(), to avoid bugs in future
818
819 Revision 1.106 2003/04/22 03:14:45 cheshire
820 <rdar://problem/3232229> Include Include instrumented mDNSResponder in panther now
821
822 Revision 1.105 2003/04/22 01:07:43 cheshire
823 <rdar://problem/3176248> DNSServiceRegistrationUpdateRecord should support a default ttl
824 If TTL parameter is zero, leave record TTL unchanged
825
826 Revision 1.104 2003/04/21 19:15:52 cheshire
827 Fix some compiler warnings
828
829 Revision 1.103 2003/04/19 02:26:35 cheshire
830 Bug #: <rdar://problem/3233804> Incorrect goodbye packet after conflict
831
832 Revision 1.102 2003/04/17 03:06:28 cheshire
833 Bug #: <rdar://problem/3231321> No need to query again when a service goes away
834 Set UnansweredQueries to 2 when receiving a "goodbye" packet
835
836 Revision 1.101 2003/04/15 20:58:31 jgraessl
837 Bug #: 3229014
838 Added a hash to lookup records in the cache.
839
840 Revision 1.100 2003/04/15 18:53:14 cheshire
841 Bug #: <rdar://problem/3229064> Bug in ScheduleNextTask
842 mDNS.c 1.94 incorrectly combined two "if" statements into one.
843
844 Revision 1.99 2003/04/15 18:09:13 jgraessl
845 Bug #: 3228892
846 Reviewed by: Stuart Cheshire
847 Added code to keep track of when the next cache item will expire so we can
848 call TidyRRCache only when necessary.
849
850 Revision 1.98 2003/04/03 03:43:55 cheshire
851 <rdar://problem/3216837> Off-by-one error in probe rate limiting
852
853 Revision 1.97 2003/04/02 01:48:17 cheshire
854 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
855 Additional fix pointed out by Josh:
856 Also set ProbeFailTime when incrementing NumFailedProbes when resetting a record back to probing state
857
858 Revision 1.96 2003/04/01 23:58:55 cheshire
859 Minor comment changes
860
861 Revision 1.95 2003/04/01 23:46:05 cheshire
862 <rdar://problem/3214832> mDNSResponder can get stuck in infinite loop after many location cycles
863 mDNS_DeregisterInterface() flushes the RR cache by marking all records received on that interface
864 to expire in one second. However, if a mDNS_StartResolveService() call is made in that one-second
865 window, it can get an SRV answer from one of those soon-to-be-deleted records, resulting in
866 FoundServiceInfoSRV() making an interface-specific query on the interface that was just removed.
867
868 Revision 1.94 2003/03/29 01:55:19 cheshire
869 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
870 Solution: Major cleanup of packet timing and conflict handling rules
871
872 Revision 1.93 2003/03/28 01:54:36 cheshire
873 Minor tidyup of IPv6 (AAAA) code
874
875 Revision 1.92 2003/03/27 03:30:55 cheshire
876 <rdar://problem/3210018> Name conflicts not handled properly, resulting in memory corruption, and eventual crash
877 Problem was that HostNameCallback() was calling mDNS_DeregisterInterface(), which is not safe in a callback
878 Fixes:
879 1. Make mDNS_DeregisterInterface() safe to call from a callback
880 2. Make HostNameCallback() use mDNS_DeadvertiseInterface() instead
881 (it never really needed to deregister the interface at all)
882
883 Revision 1.91 2003/03/15 04:40:36 cheshire
884 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
885
886 Revision 1.90 2003/03/14 20:26:37 cheshire
887 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
888
889 Revision 1.89 2003/03/12 19:57:50 cheshire
890 Fixed typo in debug message
891
892 Revision 1.88 2003/03/12 00:17:44 cheshire
893 <rdar://problem/3195426> GetFreeCacheRR needs to be more willing to throw away recent records
894
895 Revision 1.87 2003/03/11 01:27:20 cheshire
896 Reduce debugging messages (reclassify some "debugf" as "verbosedebugf")
897
898 Revision 1.86 2003/03/06 20:44:33 cheshire
899 Comment tidyup
900
901 Revision 1.85 2003/03/05 03:38:35 cheshire
902 Bug #: 3185731 Bogus error message in console: died or deallocated, but no record of client can be found!
903 Fixed by leaving client in list after conflict, until client explicitly deallocates
904
905 Revision 1.84 2003/03/05 01:27:30 cheshire
906 Bug #: 3185482 Different TTL for multicast versus unicast responses
907 When building unicast responses, record TTLs are capped to 10 seconds
908
909 Revision 1.83 2003/03/04 23:48:52 cheshire
910 Bug #: 3188865 Double probes after wake from sleep
911 Don't reset record type to kDNSRecordTypeUnique if record is DependentOn another
912
913 Revision 1.82 2003/03/04 23:38:29 cheshire
914 Bug #: 3099194 mDNSResponder needs performance improvements
915 Only set rr->CRActiveQuestion to point to the
916 currently active representative of a question set
917
918 Revision 1.81 2003/02/21 03:35:34 cheshire
919 Bug #: 3179007 mDNSResponder needs to include AAAA records in additional answer section
920
921 Revision 1.80 2003/02/21 02:47:53 cheshire
922 Bug #: 3099194 mDNSResponder needs performance improvements
923 Several places in the code were calling CacheRRActive(), which searched the entire
924 question list every time, to see if this cache resource record answers any question.
925 Instead, we now have a field "CRActiveQuestion" in the resource record structure
926
927 Revision 1.79 2003/02/21 01:54:07 cheshire
928 Bug #: 3099194 mDNSResponder needs performance improvements
929 Switched to using new "mDNS_Execute" model (see "Implementer Notes.txt")
930
931 Revision 1.78 2003/02/20 06:48:32 cheshire
932 Bug #: 3169535 Xserve RAID needs to do interface-specific registrations
933 Reviewed by: Josh Graessley, Bob Bradley
934
935 Revision 1.77 2003/01/31 03:35:59 cheshire
936 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
937 When there were *two* active questions in the list, they were incorrectly
938 finding *each other* and *both* being marked as duplicates of another question
939
940 Revision 1.76 2003/01/29 02:46:37 cheshire
941 Fix for IPv6:
942 A physical interface is identified solely by its InterfaceID (not by IP and type).
943 On a given InterfaceID, mDNSCore may send both v4 and v6 multicasts.
944 In cases where the requested outbound protocol (v4 or v6) is not supported on
945 that InterfaceID, the platform support layer should simply discard that packet.
946
947 Revision 1.75 2003/01/29 01:47:40 cheshire
948 Rename 'Active' to 'CRActive' or 'InterfaceActive' for improved clarity
949
950 Revision 1.74 2003/01/28 05:26:25 cheshire
951 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
952 Add 'Active' flag for interfaces
953
954 Revision 1.73 2003/01/28 03:45:12 cheshire
955 Fixed missing "not" in "!mDNSAddrIsDNSMulticast(dstaddr)"
956
957 Revision 1.72 2003/01/28 01:49:48 cheshire
958 Bug #: 3147097 mDNSResponder sometimes fails to find the correct results
959 FindDuplicateQuestion() was incorrectly finding the question itself in the list,
960 and incorrectly marking it as a duplicate (of itself), so that it became inactive.
961
962 Revision 1.71 2003/01/28 01:41:44 cheshire
963 Bug #: 3153091 Race condition when network change causes bad stuff
964 When an interface goes away, interface-specific questions on that interface become orphaned.
965 Orphan questions cause HaveQueries to return true, but there's no interface to send them on.
966 Fix: mDNS_DeregisterInterface() now calls DeActivateInterfaceQuestions()
967
968 Revision 1.70 2003/01/23 19:00:20 cheshire
969 Protect against infinite loops in mDNS_Execute
970
971 Revision 1.69 2003/01/21 22:56:32 jgraessl
972 Bug #: 3124348 service name changes are not properly handled
973 Submitted by: Stuart Cheshire
974 Reviewed by: Joshua Graessley
975 Applying changes for 3124348 to main branch. 3124348 changes went in to a
976 branch for SU.
977
978 Revision 1.68 2003/01/17 04:09:27 cheshire
979 Bug #: 3141038 mDNSResponder Resolves are unreliable on multi-homed hosts
980
981 Revision 1.67 2003/01/17 03:56:45 cheshire
982 Default 24-hour TTL is far too long. Changing to two hours.
983
984 Revision 1.66 2003/01/13 23:49:41 jgraessl
985 Merged changes for the following fixes in to top of tree:
986 3086540 computer name changes not handled properly
987 3124348 service name changes are not properly handled
988 3124352 announcements sent in pairs, failing chattiness test
989
990 Revision 1.65 2002/12/23 22:13:28 jgraessl
991 Reviewed by: Stuart Cheshire
992 Initial IPv6 support for mDNSResponder.
993
994 Revision 1.64 2002/11/26 20:49:06 cheshire
995 Bug #: 3104543 RFC 1123 allows the first character of a name label to be either a letter or a digit
996
997 Revision 1.63 2002/09/21 20:44:49 zarzycki
998 Added APSL info
999
1000 Revision 1.62 2002/09/20 03:25:37 cheshire
1001 Fix some compiler warnings
1002
1003 Revision 1.61 2002/09/20 01:05:24 cheshire
1004 Don't kill the Extras list in mDNS_DeregisterService()
1005
1006 Revision 1.60 2002/09/19 23:47:35 cheshire
1007 Added mDNS_RegisterNoSuchService() function for assertion of non-existence
1008 of a particular named service
1009
1010 Revision 1.59 2002/09/19 21:25:34 cheshire
1011 mDNS_snprintf() doesn't need to be in a separate file
1012
1013 Revision 1.58 2002/09/19 04:20:43 cheshire
1014 Remove high-ascii characters that confuse some systems
1015
1016 Revision 1.57 2002/09/17 01:07:08 cheshire
1017 Change mDNS_AdvertiseLocalAddresses to be a parameter to mDNS_Init()
1018
1019 Revision 1.56 2002/09/16 19:44:17 cheshire
1020 Merge in license terms from Quinn's copy, in preparation for Darwin release
1021 */
1022
1023 #define TEST_LOCALONLY_FOR_EVERYTHING 0
1024
1025 #include "mDNSClientAPI.h" // Defines the interface provided to the client layer above
1026 #include "mDNSPlatformFunctions.h" // Defines the interface required of the supporting layer below
1027
1028 // Disable certain benign warnings with Microsoft compilers
1029 #if(defined(_MSC_VER))
1030 // Disable "conditional expression is constant" warning for debug macros.
1031 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
1032 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
1033 #pragma warning(disable:4127)
1034
1035 // Disable "const object should be initialized"
1036 // We know that static/globals are defined to be zeroed in ANSI C, and to avoid this warning would require some
1037 // *really* ugly chunk of zeroes and curly braces to initialize zeroRR and mDNSprintf_format_default to all zeroes
1038 #pragma warning(disable:4132)
1039
1040 // Disable "assignment within conditional expression".
1041 // Other compilers understand the convention that if you place the assignment expression within an extra pair
1042 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
1043 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
1044 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
1045 #pragma warning(disable:4706)
1046 #endif
1047
1048 // ***************************************************************************
1049 #if COMPILER_LIKES_PRAGMA_MARK
1050 #pragma mark - DNS Protocol Constants
1051 #endif
1052
1053 typedef enum
1054 {
1055 kDNSFlag0_QR_Mask = 0x80, // Query or response?
1056 kDNSFlag0_QR_Query = 0x00,
1057 kDNSFlag0_QR_Response = 0x80,
1058
1059 kDNSFlag0_OP_Mask = 0x78, // Operation type
1060 kDNSFlag0_OP_StdQuery = 0x00,
1061 kDNSFlag0_OP_Iquery = 0x08,
1062 kDNSFlag0_OP_Status = 0x10,
1063 kDNSFlag0_OP_Unused3 = 0x18,
1064 kDNSFlag0_OP_Notify = 0x20,
1065 kDNSFlag0_OP_Update = 0x28,
1066
1067 kDNSFlag0_QROP_Mask = kDNSFlag0_QR_Mask | kDNSFlag0_OP_Mask,
1068
1069 kDNSFlag0_AA = 0x04, // Authoritative Answer?
1070 kDNSFlag0_TC = 0x02, // Truncated?
1071 kDNSFlag0_RD = 0x01, // Recursion Desired?
1072 kDNSFlag1_RA = 0x80, // Recursion Available?
1073
1074 kDNSFlag1_Zero = 0x40, // Reserved; must be zero
1075 kDNSFlag1_AD = 0x20, // Authentic Data [RFC 2535]
1076 kDNSFlag1_CD = 0x10, // Checking Disabled [RFC 2535]
1077
1078 kDNSFlag1_RC = 0x0F, // Response code
1079 kDNSFlag1_RC_NoErr = 0x00,
1080 kDNSFlag1_RC_FmtErr = 0x01,
1081 kDNSFlag1_RC_SrvErr = 0x02,
1082 kDNSFlag1_RC_NXDomain = 0x03,
1083 kDNSFlag1_RC_NotImpl = 0x04,
1084 kDNSFlag1_RC_Refused = 0x05,
1085 kDNSFlag1_RC_YXDomain = 0x06,
1086 kDNSFlag1_RC_YXRRSet = 0x07,
1087 kDNSFlag1_RC_NXRRSet = 0x08,
1088 kDNSFlag1_RC_NotAuth = 0x09,
1089 kDNSFlag1_RC_NotZone = 0x0A
1090 } DNS_Flags;
1091
1092 // ***************************************************************************
1093 #if COMPILER_LIKES_PRAGMA_MARK
1094 #pragma mark -
1095 #pragma mark - Program Constants
1096 #endif
1097
1098 mDNSexport const ResourceRecord zeroRR;
1099 mDNSexport const mDNSIPPort zeroIPPort = { { 0 } };
1100 mDNSexport const mDNSv4Addr zeroIPAddr = { { 0 } };
1101 mDNSexport const mDNSv6Addr zerov6Addr = { { 0 } };
1102 mDNSexport const mDNSv4Addr onesIPv4Addr = { { 255, 255, 255, 255 } };
1103 mDNSexport const mDNSv6Addr onesIPv6Addr = { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } };
1104 mDNSlocal const mDNSAddr zeroAddr = { mDNSAddrType_None, {{{ 0 }}} };
1105
1106 mDNSexport const mDNSInterfaceID mDNSInterface_Any = { 0 };
1107 mDNSlocal const mDNSInterfaceID mDNSInterfaceMark = { (mDNSInterfaceID)~0 };
1108
1109 #define UnicastDNSPortAsNumber 53
1110 #define MulticastDNSPortAsNumber 5353
1111 mDNSexport const mDNSIPPort UnicastDNSPort = { { UnicastDNSPortAsNumber >> 8, UnicastDNSPortAsNumber & 0xFF } };
1112 mDNSexport const mDNSIPPort MulticastDNSPort = { { MulticastDNSPortAsNumber >> 8, MulticastDNSPortAsNumber & 0xFF } };
1113 mDNSexport const mDNSv4Addr AllDNSAdminGroup = { { 239, 255, 255, 251 } };
1114 mDNSexport const mDNSv4Addr AllDNSLinkGroup = { { 224, 0, 0, 251 } };
1115 mDNSexport const mDNSv6Addr AllDNSLinkGroupv6 = { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } };
1116 mDNSexport const mDNSAddr AllDNSLinkGroup_v4 = { mDNSAddrType_IPv4, { { { 224, 0, 0, 251 } } } };
1117 mDNSexport const mDNSAddr AllDNSLinkGroup_v6 = { mDNSAddrType_IPv6, { { { 0xFF,0x02,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xFB } } } };
1118
1119 static const mDNSOpaque16 zeroID = { { 0, 0 } };
1120 static const mDNSOpaque16 QueryFlags = { { kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery, 0 } };
1121 static const mDNSOpaque16 ResponseFlags = { { kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery | kDNSFlag0_AA, 0 } };
1122 #define zeroDomainNamePtr ((domainname*)"")
1123
1124 // Any records bigger than this are considered 'large' records
1125 #define SmallRecordLimit 1024
1126
1127 #define kDefaultTTLforUnique 240
1128 #define kDefaultTTLforShared (2*3600)
1129
1130 #define kMaxUpdateCredits 10
1131
1132 static const char *const mDNS_DomainTypeNames[] =
1133 {
1134 "_browse._dns-sd._udp.local.",
1135 "_default._browse._dns-sd._udp.local.",
1136 "_register._dns-sd._udp.local.",
1137 "_default._register._dns-sd._udp.local."
1138 };
1139
1140 #define AssignDomainName(DST, SRC) mDNSPlatformMemCopy((SRC).c, (DST).c, DomainNameLength(&(SRC)))
1141
1142 // ***************************************************************************
1143 #if COMPILER_LIKES_PRAGMA_MARK
1144 #pragma mark -
1145 #pragma mark - Specialized mDNS version of vsnprintf
1146 #endif
1147
1148 static const struct mDNSprintf_format
1149 {
1150 unsigned leftJustify : 1;
1151 unsigned forceSign : 1;
1152 unsigned zeroPad : 1;
1153 unsigned havePrecision : 1;
1154 unsigned hSize : 1;
1155 unsigned lSize : 1;
1156 char altForm;
1157 char sign; // +, - or space
1158 unsigned int fieldWidth;
1159 unsigned int precision;
1160 } mDNSprintf_format_default;
1161
1162 mDNSexport mDNSu32 mDNS_vsnprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, va_list arg)
1163 {
1164 mDNSu32 nwritten = 0;
1165 int c;
1166 buflen--; // Pre-reserve one space in the buffer for the terminating nul
1167
1168 for (c = *fmt; c != 0; c = *++fmt)
1169 {
1170 if (c != '%')
1171 {
1172 *sbuffer++ = (char)c;
1173 if (++nwritten >= buflen) goto exit;
1174 }
1175 else
1176 {
1177 unsigned int i=0, j;
1178 // The mDNS Vsprintf Argument Conversion Buffer is used as a temporary holding area for
1179 // generating decimal numbers, hexdecimal numbers, IP addresses, domain name strings, etc.
1180 // The size needs to be enough for a 256-byte domain name plus some error text.
1181 #define mDNS_VACB_Size 300
1182 char mDNS_VACB[mDNS_VACB_Size];
1183 #define mDNS_VACB_Lim (&mDNS_VACB[mDNS_VACB_Size])
1184 #define mDNS_VACB_Remain(s) ((mDNSu32)(mDNS_VACB_Lim - s))
1185 char *s = mDNS_VACB_Lim, *digits;
1186 struct mDNSprintf_format F = mDNSprintf_format_default;
1187
1188 while (1) // decode flags
1189 {
1190 c = *++fmt;
1191 if (c == '-') F.leftJustify = 1;
1192 else if (c == '+') F.forceSign = 1;
1193 else if (c == ' ') F.sign = ' ';
1194 else if (c == '#') F.altForm++;
1195 else if (c == '0') F.zeroPad = 1;
1196 else break;
1197 }
1198
1199 if (c == '*') // decode field width
1200 {
1201 int f = va_arg(arg, int);
1202 if (f < 0) { f = -f; F.leftJustify = 1; }
1203 F.fieldWidth = (unsigned int)f;
1204 c = *++fmt;
1205 }
1206 else
1207 {
1208 for (; c >= '0' && c <= '9'; c = *++fmt)
1209 F.fieldWidth = (10 * F.fieldWidth) + (c - '0');
1210 }
1211
1212 if (c == '.') // decode precision
1213 {
1214 if ((c = *++fmt) == '*')
1215 { F.precision = va_arg(arg, unsigned int); c = *++fmt; }
1216 else for (; c >= '0' && c <= '9'; c = *++fmt)
1217 F.precision = (10 * F.precision) + (c - '0');
1218 F.havePrecision = 1;
1219 }
1220
1221 if (F.leftJustify) F.zeroPad = 0;
1222
1223 conv:
1224 switch (c) // perform appropriate conversion
1225 {
1226 unsigned long n;
1227 case 'h' : F.hSize = 1; c = *++fmt; goto conv;
1228 case 'l' : // fall through
1229 case 'L' : F.lSize = 1; c = *++fmt; goto conv;
1230 case 'd' :
1231 case 'i' : if (F.lSize) n = (unsigned long)va_arg(arg, long);
1232 else n = (unsigned long)va_arg(arg, int);
1233 if (F.hSize) n = (short) n;
1234 if ((long) n < 0) { n = (unsigned long)-(long)n; F.sign = '-'; }
1235 else if (F.forceSign) F.sign = '+';
1236 goto decimal;
1237 case 'u' : if (F.lSize) n = va_arg(arg, unsigned long);
1238 else n = va_arg(arg, unsigned int);
1239 if (F.hSize) n = (unsigned short) n;
1240 F.sign = 0;
1241 goto decimal;
1242 decimal: if (!F.havePrecision)
1243 {
1244 if (F.zeroPad)
1245 {
1246 F.precision = F.fieldWidth;
1247 if (F.sign) --F.precision;
1248 }
1249 if (F.precision < 1) F.precision = 1;
1250 }
1251 if (F.precision > mDNS_VACB_Size - 1)
1252 F.precision = mDNS_VACB_Size - 1;
1253 for (i = 0; n; n /= 10, i++) *--s = (char)(n % 10 + '0');
1254 for (; i < F.precision; i++) *--s = '0';
1255 if (F.sign) { *--s = F.sign; i++; }
1256 break;
1257
1258 case 'o' : if (F.lSize) n = va_arg(arg, unsigned long);
1259 else n = va_arg(arg, unsigned int);
1260 if (F.hSize) n = (unsigned short) n;
1261 if (!F.havePrecision)
1262 {
1263 if (F.zeroPad) F.precision = F.fieldWidth;
1264 if (F.precision < 1) F.precision = 1;
1265 }
1266 if (F.precision > mDNS_VACB_Size - 1)
1267 F.precision = mDNS_VACB_Size - 1;
1268 for (i = 0; n; n /= 8, i++) *--s = (char)(n % 8 + '0');
1269 if (F.altForm && i && *s != '0') { *--s = '0'; i++; }
1270 for (; i < F.precision; i++) *--s = '0';
1271 break;
1272
1273 case 'a' : {
1274 unsigned char *a = va_arg(arg, unsigned char *);
1275 if (!a) { static char emsg[] = "<<NULL>>"; s = emsg; i = sizeof(emsg)-1; }
1276 else
1277 {
1278 unsigned short *w = (unsigned short *)a;
1279 s = mDNS_VACB; // Adjust s to point to the start of the buffer, not the end
1280 if (F.altForm)
1281 {
1282 mDNSAddr *ip = (mDNSAddr*)a;
1283 a = (unsigned char *)&ip->ip.v4;
1284 w = (unsigned short *)&ip->ip.v6;
1285 switch (ip->type)
1286 {
1287 case mDNSAddrType_IPv4: F.precision = 4; break;
1288 case mDNSAddrType_IPv6: F.precision = 16; break;
1289 default: F.precision = 0; break;
1290 }
1291 }
1292 switch (F.precision)
1293 {
1294 case 4: i = mDNS_snprintf(mDNS_VACB, sizeof(mDNS_VACB), "%d.%d.%d.%d",
1295 a[0], a[1], a[2], a[3]); break;
1296 case 6: i = mDNS_snprintf(mDNS_VACB, sizeof(mDNS_VACB), "%02X:%02X:%02X:%02X:%02X:%02X",
1297 a[0], a[1], a[2], a[3], a[4], a[5]); break;
1298 case 16: i = mDNS_snprintf(mDNS_VACB, sizeof(mDNS_VACB), "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X",
1299 w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); break;
1300 default: i = mDNS_snprintf(mDNS_VACB, sizeof(mDNS_VACB), "%s", "<< ERROR: Must specify address size "
1301 "(i.e. %.4a=IPv4, %.6a=Ethernet, %.16a=IPv6) >>"); break;
1302 }
1303 }
1304 }
1305 break;
1306
1307 case 'p' : F.havePrecision = F.lSize = 1;
1308 F.precision = 8;
1309 case 'X' : digits = "0123456789ABCDEF";
1310 goto hexadecimal;
1311 case 'x' : digits = "0123456789abcdef";
1312 hexadecimal:if (F.lSize) n = va_arg(arg, unsigned long);
1313 else n = va_arg(arg, unsigned int);
1314 if (F.hSize) n = (unsigned short) n;
1315 if (!F.havePrecision)
1316 {
1317 if (F.zeroPad)
1318 {
1319 F.precision = F.fieldWidth;
1320 if (F.altForm) F.precision -= 2;
1321 }
1322 if (F.precision < 1) F.precision = 1;
1323 }
1324 if (F.precision > mDNS_VACB_Size - 1)
1325 F.precision = mDNS_VACB_Size - 1;
1326 for (i = 0; n; n /= 16, i++) *--s = digits[n % 16];
1327 for (; i < F.precision; i++) *--s = '0';
1328 if (F.altForm) { *--s = (char)c; *--s = '0'; i += 2; }
1329 break;
1330
1331 case 'c' : *--s = (char)va_arg(arg, int); i = 1; break;
1332
1333 case 's' : s = va_arg(arg, char *);
1334 if (!s) { static char emsg[] = "<<NULL>>"; s = emsg; i = sizeof(emsg)-1; }
1335 else switch (F.altForm)
1336 {
1337 case 0: { char *a=s; i=0; while(*a++) i++; break; } // C string
1338 case 1: i = (unsigned char) *s++; break; // Pascal string
1339 case 2: { // DNS label-sequence name
1340 unsigned char *a = (unsigned char *)s;
1341 s = mDNS_VACB; // Adjust s to point to the start of the buffer, not the end
1342 if (*a == 0) *s++ = '.'; // Special case for root DNS name
1343 while (*a)
1344 {
1345 if (*a > 63) { s += mDNS_snprintf(s, mDNS_VACB_Remain(s), "<<INVALID LABEL LENGTH %u>>", *a); break; }
1346 if (s + *a >= &mDNS_VACB[254]) { s += mDNS_snprintf(s, mDNS_VACB_Remain(s), "<<NAME TOO LONG>>"); break; }
1347 s += mDNS_snprintf(s, mDNS_VACB_Remain(s), "%#s.", a);
1348 a += 1 + *a;
1349 }
1350 i = (mDNSu32)(s - mDNS_VACB);
1351 s = mDNS_VACB; // Reset s back to the start of the buffer
1352 break;
1353 }
1354 }
1355 if (F.havePrecision && i > F.precision) // Make sure we don't truncate in the middle of a UTF-8 character
1356 { i = F.precision; while (i>0 && (s[i] & 0xC0) == 0x80) i--; }
1357 break;
1358
1359 case 'n' : s = va_arg(arg, char *);
1360 if (F.hSize) * (short *) s = (short)nwritten;
1361 else if (F.lSize) * (long *) s = (long)nwritten;
1362 else * (int *) s = (int)nwritten;
1363 continue;
1364
1365 default: s = mDNS_VACB;
1366 i = mDNS_snprintf(mDNS_VACB, sizeof(mDNS_VACB), "<<UNKNOWN FORMAT CONVERSION CODE %%%c>>", c);
1367
1368 case '%' : *sbuffer++ = (char)c;
1369 if (++nwritten >= buflen) goto exit;
1370 break;
1371 }
1372
1373 if (i < F.fieldWidth && !F.leftJustify) // Pad on the left
1374 do {
1375 *sbuffer++ = ' ';
1376 if (++nwritten >= buflen) goto exit;
1377 } while (i < --F.fieldWidth);
1378
1379 if (i > buflen - nwritten) // Make sure we don't truncate in the middle of a UTF-8 character
1380 { i = buflen - nwritten; while (i>0 && (s[i] & 0xC0) == 0x80) i--; }
1381 for (j=0; j<i; j++) *sbuffer++ = *s++; // Write the converted result
1382 nwritten += i;
1383 if (nwritten >= buflen) goto exit;
1384
1385 for (; i < F.fieldWidth; i++) // Pad on the right
1386 {
1387 *sbuffer++ = ' ';
1388 if (++nwritten >= buflen) goto exit;
1389 }
1390 }
1391 }
1392 exit:
1393 *sbuffer++ = 0;
1394 return(nwritten);
1395 }
1396
1397 mDNSexport mDNSu32 mDNS_snprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, ...)
1398 {
1399 mDNSu32 length;
1400
1401 va_list ptr;
1402 va_start(ptr,fmt);
1403 length = mDNS_vsnprintf(sbuffer, buflen, fmt, ptr);
1404 va_end(ptr);
1405
1406 return(length);
1407 }
1408
1409 // ***************************************************************************
1410 #if COMPILER_LIKES_PRAGMA_MARK
1411 #pragma mark -
1412 #pragma mark - General Utility Functions
1413 #endif
1414
1415 mDNSexport char *DNSTypeName(mDNSu16 rrtype)
1416 {
1417 switch (rrtype)
1418 {
1419 case kDNSType_A: return("Addr");
1420 case kDNSType_CNAME:return("CNAME");
1421 case kDNSType_NULL: return("NULL");
1422 case kDNSType_PTR: return("PTR");
1423 case kDNSType_HINFO:return("HINFO");
1424 case kDNSType_TXT: return("TXT");
1425 case kDNSType_AAAA: return("AAAA");
1426 case kDNSType_SRV: return("SRV");
1427 case kDNSQType_ANY: return("ANY");
1428 default: {
1429 static char buffer[16];
1430 mDNS_snprintf(buffer, sizeof(buffer), "(%d)", rrtype);
1431 return(buffer);
1432 }
1433 }
1434 }
1435
1436 mDNSexport char *GetRRDisplayString_rdb(mDNS *const m, const ResourceRecord *rr, RDataBody *rd)
1437 {
1438 char *ptr = m->MsgBuffer;
1439 mDNSu32 length = mDNS_snprintf(m->MsgBuffer, 79, "%4d %##s %s ", rr->rdlength, rr->name.c, DNSTypeName(rr->rrtype));
1440 switch (rr->rrtype)
1441 {
1442 case kDNSType_A: mDNS_snprintf(m->MsgBuffer+length, 79-length, "%.4a", &rd->ip); break;
1443 case kDNSType_CNAME:// Same as PTR
1444 case kDNSType_PTR: mDNS_snprintf(m->MsgBuffer+length, 79-length, "%##s", &rd->name); break;
1445 case kDNSType_HINFO:// Display this the same as TXT (just show first string)
1446 case kDNSType_TXT: mDNS_snprintf(m->MsgBuffer+length, 79-length, "%#s", rd->txt.c); break;
1447 case kDNSType_AAAA: mDNS_snprintf(m->MsgBuffer+length, 79-length, "%.16a", &rd->ipv6); break;
1448 case kDNSType_SRV: mDNS_snprintf(m->MsgBuffer+length, 79-length, "%##s", &rd->srv.target); break;
1449 default: mDNS_snprintf(m->MsgBuffer+length, 79-length, "RDLen %d: %s",
1450 rr->rdlength, rd->data); break;
1451 }
1452 for (ptr = m->MsgBuffer; *ptr; ptr++) if (*ptr < ' ') *ptr='.';
1453 return(m->MsgBuffer);
1454 }
1455
1456 mDNSlocal mDNSu32 mDNSRandom(mDNSu32 max)
1457 {
1458 static mDNSu32 seed = 0;
1459 mDNSu32 mask = 1;
1460
1461 if (!seed) seed = (mDNSu32)mDNSPlatformTimeNow();
1462 while (mask < max) mask = (mask << 1) | 1;
1463 do seed = seed * 21 + 1; while ((seed & mask) > max);
1464 return (seed & mask);
1465 }
1466
1467 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
1468 #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])
1469
1470 #define mDNSIPv4AddressIsZero(A) mDNSSameIPv4Address((A), zeroIPAddr)
1471 #define mDNSIPv6AddressIsZero(A) mDNSSameIPv6Address((A), zerov6Addr)
1472
1473 #define mDNSIPv4AddressIsOnes(A) mDNSSameIPv4Address((A), onesIPv4Addr)
1474 #define mDNSIPv6AddressIsOnes(A) mDNSSameIPv6Address((A), onesIPv6Addr)
1475
1476 #define mDNSAddressIsZero(X) ( \
1477 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4)) || \
1478 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6)) )
1479
1480 #define mDNSAddressIsOnes(X) ( \
1481 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4)) || \
1482 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6)) )
1483
1484 #define mDNSAddressIsValid(X) ( \
1485 ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
1486 ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
1487
1488 mDNSexport mDNSBool mDNSSameAddress(const mDNSAddr *ip1, const mDNSAddr *ip2)
1489 {
1490 if (ip1->type == ip2->type)
1491 {
1492 switch (ip1->type)
1493 {
1494 case mDNSAddrType_IPv4 : return(mDNSBool)(mDNSSameIPv4Address(ip1->ip.v4, ip2->ip.v4));
1495 case mDNSAddrType_IPv6 : return(mDNSBool)(mDNSSameIPv6Address(ip1->ip.v6, ip2->ip.v6));
1496 }
1497 }
1498 return(mDNSfalse);
1499 }
1500
1501 mDNSexport mDNSBool mDNSAddrIsDNSMulticast(const mDNSAddr *ip)
1502 {
1503 switch(ip->type)
1504 {
1505 case mDNSAddrType_IPv4: return(mDNSBool)(ip->ip.v4.NotAnInteger == AllDNSLinkGroup.NotAnInteger);
1506 case mDNSAddrType_IPv6: return(mDNSBool)(ip->ip.v6.l[0] == AllDNSLinkGroupv6.l[0] &&
1507 ip->ip.v6.l[1] == AllDNSLinkGroupv6.l[1] &&
1508 ip->ip.v6.l[2] == AllDNSLinkGroupv6.l[2] &&
1509 ip->ip.v6.l[3] == AllDNSLinkGroupv6.l[3] );
1510 default: return(mDNSfalse);
1511 }
1512 }
1513
1514 mDNSlocal const NetworkInterfaceInfo *GetFirstActiveInterface(const NetworkInterfaceInfo *intf)
1515 {
1516 while (intf && !intf->InterfaceActive) intf = intf->next;
1517 return(intf);
1518 }
1519
1520 mDNSlocal mDNSInterfaceID GetNextActiveInterfaceID(const NetworkInterfaceInfo *intf)
1521 {
1522 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
1523 if (next) return(next->InterfaceID); else return(mDNSNULL);
1524 }
1525
1526 #define InitialQuestionInterval (mDNSPlatformOneSecond/2)
1527 #define ActiveQuestion(Q) ((Q)->ThisQInterval > 0 && !(Q)->DuplicateOf)
1528 #define TimeToSendThisQuestion(Q,time) (ActiveQuestion(Q) && (time) - ((Q)->LastQTime + (Q)->ThisQInterval) >= 0)
1529
1530 mDNSlocal void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
1531 {
1532 if (ActiveQuestion(q))
1533 if (m->NextScheduledQuery - (q->LastQTime + q->ThisQInterval) > 0)
1534 m->NextScheduledQuery = (q->LastQTime + q->ThisQInterval);
1535 }
1536
1537 // ***************************************************************************
1538 #if COMPILER_LIKES_PRAGMA_MARK
1539 #pragma mark -
1540 #pragma mark - Domain Name Utility Functions
1541 #endif
1542
1543 #define mdnsIsDigit(X) ((X) >= '0' && (X) <= '9')
1544 #define mDNSIsUpperCase(X) ((X) >= 'A' && (X) <= 'Z')
1545 #define mDNSIsLowerCase(X) ((X) >= 'a' && (X) <= 'z')
1546 #define mdnsIsLetter(X) (mDNSIsUpperCase(X) || mDNSIsLowerCase(X))
1547
1548 mDNSexport mDNSBool SameDomainLabel(const mDNSu8 *a, const mDNSu8 *b)
1549 {
1550 int i;
1551 const int len = *a++;
1552
1553 if (len > MAX_DOMAIN_LABEL)
1554 { debugf("Malformed label (too long)"); return(mDNSfalse); }
1555
1556 if (len != *b++) return(mDNSfalse);
1557 for (i=0; i<len; i++)
1558 {
1559 mDNSu8 ac = *a++;
1560 mDNSu8 bc = *b++;
1561 if (mDNSIsUpperCase(ac)) ac += 'a' - 'A';
1562 if (mDNSIsUpperCase(bc)) bc += 'a' - 'A';
1563 if (ac != bc) return(mDNSfalse);
1564 }
1565 return(mDNStrue);
1566 }
1567
1568 mDNSexport mDNSBool SameDomainName(const domainname *const d1, const domainname *const d2)
1569 {
1570 const mDNSu8 * a = d1->c;
1571 const mDNSu8 * b = d2->c;
1572 const mDNSu8 *const max = d1->c + MAX_DOMAIN_NAME; // Maximum that's valid
1573
1574 while (*a || *b)
1575 {
1576 if (a + 1 + *a >= max)
1577 { debugf("Malformed domain name (more than 255 characters)"); return(mDNSfalse); }
1578 if (!SameDomainLabel(a, b)) return(mDNSfalse);
1579 a += 1 + *a;
1580 b += 1 + *b;
1581 }
1582
1583 return(mDNStrue);
1584 }
1585
1586 // Returns length of a domain name INCLUDING the byte for the final null label
1587 // i.e. for the root label "." it returns one
1588 // For the FQDN "com." it returns 5 (length byte, three data bytes, final zero)
1589 // Legal results are 1 (just root label) to 255 (MAX_DOMAIN_NAME)
1590 // If the given domainname is invalid, result is 256
1591 mDNSexport mDNSu16 DomainNameLength(const domainname *const name)
1592 {
1593 const mDNSu8 *src = name->c;
1594 while (*src)
1595 {
1596 if (*src > MAX_DOMAIN_LABEL) return(MAX_DOMAIN_NAME+1);
1597 src += 1 + *src;
1598 if (src - name->c >= MAX_DOMAIN_NAME) return(MAX_DOMAIN_NAME+1);
1599 }
1600 return((mDNSu16)(src - name->c + 1));
1601 }
1602
1603 // CompressedDomainNameLength returns the length of a domain name INCLUDING the byte
1604 // for the final null label i.e. for the root label "." it returns one.
1605 // E.g. for the FQDN "foo.com." it returns 9
1606 // (length, three data bytes, length, three more data bytes, final zero).
1607 // In the case where a parent domain name is provided, and the given name is a child
1608 // of that parent, CompressedDomainNameLength returns the length of the prefix portion
1609 // of the child name, plus TWO bytes for the compression pointer.
1610 // E.g. for the name "foo.com." with parent "com.", it returns 6
1611 // (length, three data bytes, two-byte compression pointer).
1612 mDNSlocal mDNSu16 CompressedDomainNameLength(const domainname *const name, const domainname *parent)
1613 {
1614 const mDNSu8 *src = name->c;
1615 if (parent && parent->c[0] == 0) parent = mDNSNULL;
1616 while (*src)
1617 {
1618 if (*src > MAX_DOMAIN_LABEL) return(MAX_DOMAIN_NAME+1);
1619 if (parent && SameDomainName((domainname *)src, parent)) return((mDNSu16)(src - name->c + 2));
1620 src += 1 + *src;
1621 if (src - name->c >= MAX_DOMAIN_NAME) return(MAX_DOMAIN_NAME+1);
1622 }
1623 return((mDNSu16)(src - name->c + 1));
1624 }
1625
1626 // AppendLiteralLabelString appends a single label to an existing (possibly empty) domainname.
1627 // The C string contains the label as-is, with no escaping, etc.
1628 // Any dots in the name are literal dots, not label separators
1629 // If successful, AppendLiteralLabelString returns a pointer to the next unused byte
1630 // in the domainname bufer (i.e., the next byte after the terminating zero).
1631 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1632 // AppendLiteralLabelString returns mDNSNULL.
1633 mDNSexport mDNSu8 *AppendLiteralLabelString(domainname *const name, const char *cstr)
1634 {
1635 mDNSu8 * ptr = name->c + DomainNameLength(name) - 1; // Find end of current name
1636 const mDNSu8 *const lim1 = name->c + MAX_DOMAIN_NAME - 1; // Limit of how much we can add (not counting final zero)
1637 const mDNSu8 *const lim2 = ptr + 1 + MAX_DOMAIN_LABEL;
1638 const mDNSu8 *const lim = (lim1 < lim2) ? lim1 : lim2;
1639 mDNSu8 *lengthbyte = ptr++; // Record where the length is going to go
1640
1641 while (*cstr && ptr < lim) *ptr++ = (mDNSu8)*cstr++; // Copy the data
1642 *lengthbyte = (mDNSu8)(ptr - lengthbyte - 1); // Fill in the length byte
1643 *ptr++ = 0; // Put the null root label on the end
1644 if (*cstr) return(mDNSNULL); // Failure: We didn't successfully consume all input
1645 else return(ptr); // Success: return new value of ptr
1646 }
1647
1648 // AppendDNSNameString appends zero or more labels to an existing (possibly empty) domainname.
1649 // The C string is in conventional DNS syntax:
1650 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1651 // If successful, AppendDNSNameString returns a pointer to the next unused byte
1652 // in the domainname bufer (i.e., the next byte after the terminating zero).
1653 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1654 // AppendDNSNameString returns mDNSNULL.
1655 mDNSexport mDNSu8 *AppendDNSNameString(domainname *const name, const char *cstr)
1656 {
1657 mDNSu8 * ptr = name->c + DomainNameLength(name) - 1; // Find end of current name
1658 const mDNSu8 *const lim = name->c + MAX_DOMAIN_NAME - 1; // Limit of how much we can add (not counting final zero)
1659 while (*cstr && ptr < lim) // While more characters, and space to put them...
1660 {
1661 mDNSu8 *lengthbyte = ptr++; // Record where the length is going to go
1662 while (*cstr && *cstr != '.' && ptr < lim) // While we have characters in the label...
1663 {
1664 mDNSu8 c = (mDNSu8)*cstr++; // Read the character
1665 if (c == '\\') // If escape character, check next character
1666 {
1667 c = (mDNSu8)*cstr++; // Assume we'll just take the next character
1668 if (mdnsIsDigit(cstr[-1]) && mdnsIsDigit(cstr[0]) && mdnsIsDigit(cstr[1]))
1669 { // If three decimal digits,
1670 int v0 = cstr[-1] - '0'; // then interpret as three-digit decimal
1671 int v1 = cstr[ 0] - '0';
1672 int v2 = cstr[ 1] - '0';
1673 int val = v0 * 100 + v1 * 10 + v2;
1674 if (val <= 255) { c = (mDNSu8)val; cstr += 2; } // If valid three-digit decimal value, use it
1675 }
1676 }
1677 *ptr++ = c; // Write the character
1678 }
1679 if (*cstr) cstr++; // Skip over the trailing dot (if present)
1680 if (ptr - lengthbyte - 1 > MAX_DOMAIN_LABEL) // If illegal label, abort
1681 return(mDNSNULL);
1682 *lengthbyte = (mDNSu8)(ptr - lengthbyte - 1); // Fill in the length byte
1683 }
1684
1685 *ptr++ = 0; // Put the null root label on the end
1686 if (*cstr) return(mDNSNULL); // Failure: We didn't successfully consume all input
1687 else return(ptr); // Success: return new value of ptr
1688 }
1689
1690 // AppendDomainLabel appends a single label to a name.
1691 // If successful, AppendDomainLabel returns a pointer to the next unused byte
1692 // in the domainname bufer (i.e., the next byte after the terminating zero).
1693 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1694 // AppendDomainLabel returns mDNSNULL.
1695 mDNSexport mDNSu8 *AppendDomainLabel(domainname *const name, const domainlabel *const label)
1696 {
1697 int i;
1698 mDNSu8 *ptr = name->c + DomainNameLength(name) - 1;
1699
1700 // Check label is legal
1701 if (label->c[0] > MAX_DOMAIN_LABEL) return(mDNSNULL);
1702
1703 // Check that ptr + length byte + data bytes + final zero does not exceed our limit
1704 if (ptr + 1 + label->c[0] + 1 > name->c + MAX_DOMAIN_NAME) return(mDNSNULL);
1705
1706 for (i=0; i<=label->c[0]; i++) *ptr++ = label->c[i]; // Copy the label data
1707 *ptr++ = 0; // Put the null root label on the end
1708 return(ptr);
1709 }
1710
1711 mDNSexport mDNSu8 *AppendDomainName(domainname *const name, const domainname *const append)
1712 {
1713 mDNSu8 * ptr = name->c + DomainNameLength(name) - 1; // Find end of current name
1714 const mDNSu8 *const lim = name->c + MAX_DOMAIN_NAME - 1; // Limit of how much we can add (not counting final zero)
1715 const mDNSu8 * src = append->c;
1716 while(src[0])
1717 {
1718 int i;
1719 if (ptr + 1 + src[0] > lim) return(mDNSNULL);
1720 for (i=0; i<=src[0]; i++) *ptr++ = src[i];
1721 *ptr = 0; // Put the null root label on the end
1722 src += i;
1723 }
1724 return(ptr);
1725 }
1726
1727 // MakeDomainLabelFromLiteralString makes a single domain label from a single literal C string (with no escaping).
1728 // If successful, MakeDomainLabelFromLiteralString returns mDNStrue.
1729 // If unable to convert the whole string to a legal domain label (i.e. because length is more than 63 bytes) then
1730 // MakeDomainLabelFromLiteralString makes a legal domain label from the first 63 bytes of the string and returns mDNSfalse.
1731 // In some cases silently truncated oversized names to 63 bytes is acceptable, so the return result may be ignored.
1732 // In other cases silent truncation may not be acceptable, so in those cases the calling function needs to check the return result.
1733 mDNSexport mDNSBool MakeDomainLabelFromLiteralString(domainlabel *const label, const char *cstr)
1734 {
1735 mDNSu8 * ptr = label->c + 1; // Where we're putting it
1736 const mDNSu8 *const limit = label->c + 1 + MAX_DOMAIN_LABEL; // The maximum we can put
1737 while (*cstr && ptr < limit) *ptr++ = (mDNSu8)*cstr++; // Copy the label
1738 label->c[0] = (mDNSu8)(ptr - label->c - 1); // Set the length byte
1739 return(*cstr == 0); // Return mDNStrue if we successfully consumed all input
1740 }
1741
1742 // MakeDomainNameFromDNSNameString makes a native DNS-format domainname from a C string.
1743 // The C string is in conventional DNS syntax:
1744 // Textual labels, escaped as necessary using the usual DNS '\' notation, separated by dots.
1745 // If successful, MakeDomainNameFromDNSNameString returns a pointer to the next unused byte
1746 // in the domainname bufer (i.e., the next byte after the terminating zero).
1747 // If unable to construct a legal domain name (i.e. label more than 63 bytes, or total more than 255 bytes)
1748 // MakeDomainNameFromDNSNameString returns mDNSNULL.
1749 mDNSexport mDNSu8 *MakeDomainNameFromDNSNameString(domainname *const name, const char *cstr)
1750 {
1751 name->c[0] = 0; // Make an empty domain name
1752 return(AppendDNSNameString(name, cstr)); // And then add this string to it
1753 }
1754
1755 mDNSexport char *ConvertDomainLabelToCString_withescape(const domainlabel *const label, char *ptr, char esc)
1756 {
1757 const mDNSu8 * src = label->c; // Domain label we're reading
1758 const mDNSu8 len = *src++; // Read length of this (non-null) label
1759 const mDNSu8 *const end = src + len; // Work out where the label ends
1760 if (len > MAX_DOMAIN_LABEL) return(mDNSNULL); // If illegal label, abort
1761 while (src < end) // While we have characters in the label
1762 {
1763 mDNSu8 c = *src++;
1764 if (esc)
1765 {
1766 if (c == '.' || c == esc) // If character is a dot or the escape character
1767 *ptr++ = esc; // Output escape character
1768 else if (c <= ' ') // If non-printing ascii,
1769 { // Output decimal escape sequence
1770 *ptr++ = esc;
1771 *ptr++ = (char) ('0' + (c / 100) );
1772 *ptr++ = (char) ('0' + (c / 10) % 10);
1773 c = (mDNSu8)('0' + (c ) % 10);
1774 }
1775 }
1776 *ptr++ = (char)c; // Copy the character
1777 }
1778 *ptr = 0; // Null-terminate the string
1779 return(ptr); // and return
1780 }
1781
1782 // Note, to guarantee that there will be no possible overrun, cstr must be at least 1005 bytes
1783 // The longest legal domain name is 255 bytes, in the form of three 64-byte labels, one 62-byte label,
1784 // and the null root label.
1785 // If every label character has to be escaped as a four-byte escape sequence, the maximum textual
1786 // ascii display of this is 63*4 + 63*4 + 63*4 + 61*4 = 1000 label characters,
1787 // plus four dots and the null at the end of the C string = 1005
1788 mDNSexport char *ConvertDomainNameToCString_withescape(const domainname *const name, char *ptr, char esc)
1789 {
1790 const mDNSu8 *src = name->c; // Domain name we're reading
1791 const mDNSu8 *const max = name->c + MAX_DOMAIN_NAME; // Maximum that's valid
1792
1793 if (*src == 0) *ptr++ = '.'; // Special case: For root, just write a dot
1794
1795 while (*src) // While more characters in the domain name
1796 {
1797 if (src + 1 + *src >= max) return(mDNSNULL);
1798 ptr = ConvertDomainLabelToCString_withescape((const domainlabel *)src, ptr, esc);
1799 if (!ptr) return(mDNSNULL);
1800 src += 1 + *src;
1801 *ptr++ = '.'; // Write the dot after the label
1802 }
1803
1804 *ptr++ = 0; // Null-terminate the string
1805 return(ptr); // and return
1806 }
1807
1808 // RFC 1034 rules:
1809 // Host names must start with a letter, end with a letter or digit,
1810 // and have as interior characters only letters, digits, and hyphen.
1811 // This was subsequently modified in RFC 1123 to allow the first character to be either a letter or a digit
1812 #define mdnsValidHostChar(X, notfirst, notlast) (mdnsIsLetter(X) || mdnsIsDigit(X) || ((notfirst) && (notlast) && (X) == '-') )
1813
1814 mDNSexport void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name[], domainlabel *const hostlabel)
1815 {
1816 const mDNSu8 * src = &UTF8Name[1];
1817 const mDNSu8 *const end = &UTF8Name[1] + UTF8Name[0];
1818 mDNSu8 * ptr = &hostlabel->c[1];
1819 const mDNSu8 *const lim = &hostlabel->c[1] + MAX_DOMAIN_LABEL;
1820 while (src < end)
1821 {
1822 // Delete apostrophes from source name
1823 if (src[0] == '\'') { src++; continue; } // Standard straight single quote
1824 if (src + 2 < end && src[0] == 0xE2 && src[1] == 0x80 && src[2] == 0x99)
1825 { src += 3; continue; } // Unicode curly apostrophe
1826 if (ptr < lim)
1827 {
1828 if (mdnsValidHostChar(*src, (ptr > &hostlabel->c[1]), (src < end-1))) *ptr++ = *src;
1829 else if (ptr > &hostlabel->c[1] && ptr[-1] != '-') *ptr++ = '-';
1830 }
1831 src++;
1832 }
1833 while (ptr > &hostlabel->c[1] && ptr[-1] == '-') ptr--; // Truncate trailing '-' marks
1834 hostlabel->c[0] = (mDNSu8)(ptr - &hostlabel->c[1]);
1835 }
1836
1837 mDNSexport mDNSu8 *ConstructServiceName(domainname *const fqdn,
1838 const domainlabel *name, const domainname *type, const domainname *const domain)
1839 {
1840 int i, len;
1841 mDNSu8 *dst = fqdn->c;
1842 const mDNSu8 *src;
1843 const char *errormsg;
1844
1845 // In the case where there is no name (and ONLY in that case),
1846 // a single-label subtype is allowed as the first label of a three-part "type"
1847 if (!name && type)
1848 {
1849 const mDNSu8 *s0 = type->c;
1850 if (s0[0] && s0[0] < 0x40) // If legal first label (at least one character, and no more than 63)
1851 {
1852 const mDNSu8 * s1 = s0 + 1 + s0[0];
1853 if (s1[0] && s1[0] < 0x40) // and legal second label (at least one character, and no more than 63)
1854 {
1855 const mDNSu8 *s2 = s1 + 1 + s1[0];
1856 if (s2[0] && s2[0] < 0x40 && s2[1+s2[0]] == 0) // and we have three and only three labels
1857 {
1858 static const mDNSu8 SubTypeLabel[5] = "\x04_sub";
1859 src = s0; // Copy the first label
1860 len = *src;
1861 for (i=0; i <= len; i++) *dst++ = *src++;
1862 for (i=0; i < (int)sizeof(SubTypeLabel); i++) *dst++ = SubTypeLabel[i];
1863 type = (domainname *)s1;
1864
1865 // Special support for queries done by older versions of "Rendezvous Browser"
1866 // For these queries, we retract the "._sub" we just added between the subtype and the main type
1867 if (SameDomainName((domainname*)s0, (domainname*)"\x09_services\x07_dns-sd\x04_udp") ||
1868 SameDomainName((domainname*)s0, (domainname*)"\x09_services\x05_mdns\x04_udp"))
1869 dst -= sizeof(SubTypeLabel);
1870 }
1871 }
1872 }
1873 }
1874
1875 if (name && name->c[0])
1876 {
1877 src = name->c; // Put the service name into the domain name
1878 len = *src;
1879 if (len >= 0x40) { errormsg="Service instance name too long"; goto fail; }
1880 for (i=0; i<=len; i++) *dst++ = *src++;
1881 }
1882 else
1883 name = (domainlabel*)""; // Set this up to be non-null, to avoid errors if we have to call LogMsg() below
1884
1885 src = type->c; // Put the service type into the domain name
1886 len = *src;
1887 if (len < 2 || len >= 0x40 || (len > 15 && !SameDomainName(domain, (domainname*)"\x05" "local")))
1888 {
1889 errormsg="Application protocol name must be underscore plus 1-14 characters. See <http://www.dns-sd.org/ServiceTypes.html>";
1890 goto fail;
1891 }
1892 if (src[1] != '_') { errormsg="Application protocol name must begin with underscore"; goto fail; }
1893 for (i=2; i<=len; i++)
1894 if (!mdnsIsLetter(src[i]) && !mdnsIsDigit(src[i]) && src[i] != '-' && src[i] != '_')
1895 { errormsg="Application protocol name must contain only letters, digits, and hyphens"; goto fail; }
1896 for (i=0; i<=len; i++) *dst++ = *src++;
1897
1898 len = *src;
1899 if (!(len == 4 && src[1] == '_' &&
1900 (((src[2] | 0x20) == 'u' && (src[3] | 0x20) == 'd') || ((src[2] | 0x20) == 't' && (src[3] | 0x20) == 'c')) &&
1901 (src[4] | 0x20) == 'p'))
1902 { errormsg="Transport protocol name must be _udp or _tcp"; goto fail; }
1903 for (i=0; i<=len; i++) *dst++ = *src++;
1904
1905 if (*src) { errormsg="Service type must have only two labels"; goto fail; }
1906
1907 *dst = 0;
1908 dst = AppendDomainName(fqdn, domain);
1909 if (!dst) { errormsg="Service domain too long"; goto fail; }
1910 return(dst);
1911
1912 fail:
1913 LogMsg("ConstructServiceName: %s: %#s.%##s%##s", errormsg, name->c, type->c, domain->c);
1914 return(mDNSNULL);
1915 }
1916
1917 mDNSexport mDNSBool DeconstructServiceName(const domainname *const fqdn,
1918 domainlabel *const name, domainname *const type, domainname *const domain)
1919 {
1920 int i, len;
1921 const mDNSu8 *src = fqdn->c;
1922 const mDNSu8 *max = fqdn->c + MAX_DOMAIN_NAME;
1923 mDNSu8 *dst;
1924
1925 dst = name->c; // Extract the service name from the domain name
1926 len = *src;
1927 if (len >= 0x40) { debugf("DeconstructServiceName: service name too long"); return(mDNSfalse); }
1928 for (i=0; i<=len; i++) *dst++ = *src++;
1929
1930 dst = type->c; // Extract the service type from the domain name
1931 len = *src;
1932 if (len >= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse); }
1933 for (i=0; i<=len; i++) *dst++ = *src++;
1934
1935 len = *src;
1936 if (len >= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse); }
1937 for (i=0; i<=len; i++) *dst++ = *src++;
1938 *dst++ = 0; // Put the null root label on the end of the service type
1939
1940 dst = domain->c; // Extract the service domain from the domain name
1941 while (*src)
1942 {
1943 len = *src;
1944 if (len >= 0x40)
1945 { debugf("DeconstructServiceName: service domain label too long"); return(mDNSfalse); }
1946 if (src + 1 + len + 1 >= max)
1947 { debugf("DeconstructServiceName: service domain too long"); return(mDNSfalse); }
1948 for (i=0; i<=len; i++) *dst++ = *src++;
1949 }
1950 *dst++ = 0; // Put the null root label on the end
1951
1952 return(mDNStrue);
1953 }
1954
1955 // Returns true if a rich text label ends in " (nnn)", or if an RFC 1034
1956 // name ends in "-nnn", where n is some decimal number.
1957 mDNSlocal mDNSBool LabelContainsSuffix(const domainlabel *const name, const mDNSBool RichText)
1958 {
1959 mDNSu16 l = name->c[0];
1960
1961 if (RichText)
1962 {
1963 if (l < 4) return mDNSfalse; // Need at least " (2)"
1964 if (name->c[l--] != ')') return mDNSfalse; // Last char must be ')'
1965 if (!mdnsIsDigit(name->c[l])) return mDNSfalse; // Preceeded by a digit
1966 l--;
1967 while (l > 2 && mdnsIsDigit(name->c[l])) l--; // Strip off digits
1968 return (name->c[l] == '(' && name->c[l - 1] == ' ');
1969 }
1970 else
1971 {
1972 if (l < 2) return mDNSfalse; // Need at least "-2"
1973 if (!mdnsIsDigit(name->c[l])) return mDNSfalse; // Last char must be a digit
1974 l--;
1975 while (l > 2 && mdnsIsDigit(name->c[l])) l--; // Strip off digits
1976 return (name->c[l] == '-');
1977 }
1978 }
1979
1980 // removes an auto-generated suffix (appended on a name collision) from a label. caller is
1981 // responsible for ensuring that the label does indeed contain a suffix. returns the number
1982 // from the suffix that was removed.
1983 mDNSlocal mDNSu32 RemoveLabelSuffix(domainlabel *name, mDNSBool RichText)
1984 {
1985 mDNSu32 val = 0, multiplier = 1;
1986
1987 // Chop closing parentheses from RichText suffix
1988 if (RichText && name->c[0] >= 1 && name->c[name->c[0]] == ')') name->c[0]--;
1989
1990 // Get any existing numerical suffix off the name
1991 while (mdnsIsDigit(name->c[name->c[0]]))
1992 { val += (name->c[name->c[0]] - '0') * multiplier; multiplier *= 10; name->c[0]--; }
1993
1994 // Chop opening parentheses or dash from suffix
1995 if (RichText)
1996 {
1997 if (name->c[0] >= 2 && name->c[name->c[0]] == '(' && name->c[name->c[0]-1] == ' ') name->c[0] -= 2;
1998 }
1999 else
2000 {
2001 if (name->c[0] >= 1 && name->c[name->c[0]] == '-') name->c[0] -= 1;
2002 }
2003
2004 return(val);
2005 }
2006
2007 // appends a numerical suffix to a label, with the number following a whitespace and enclosed
2008 // in parentheses (rich text) or following two consecutive hyphens (RFC 1034 domain label).
2009 mDNSlocal void AppendLabelSuffix(domainlabel *name, mDNSu32 val, mDNSBool RichText)
2010 {
2011 mDNSu32 divisor = 1, chars = 2; // Shortest possible RFC1034 name suffix is 3 characters ("-2")
2012 if (RichText) chars = 4; // Shortest possible RichText suffix is 4 characters (" (2)")
2013
2014 // Truncate trailing spaces from RichText names
2015 if (RichText) while (name->c[name->c[0]] == ' ') name->c[0]--;
2016
2017 while (val >= divisor * 10) { divisor *= 10; chars++; }
2018
2019 if (name->c[0] > (mDNSu8)(MAX_DOMAIN_LABEL - chars))
2020 {
2021 name->c[0] = (mDNSu8)(MAX_DOMAIN_LABEL - chars);
2022 // If the following character is a UTF-8 continuation character,
2023 // we just chopped a multi-byte UTF-8 character in the middle, so strip back to a safe truncation point
2024 while (name->c[0] > 0 && (name->c[name->c[0]+1] & 0xC0) == 0x80) name->c[0]--;
2025 }
2026
2027 if (RichText) { name->c[++name->c[0]] = ' '; name->c[++name->c[0]] = '('; }
2028 else { name->c[++name->c[0]] = '-'; }
2029
2030 while (divisor)
2031 {
2032 name->c[++name->c[0]] = (mDNSu8)('0' + val / divisor);
2033 val %= divisor;
2034 divisor /= 10;
2035 }
2036
2037 if (RichText) name->c[++name->c[0]] = ')';
2038 }
2039
2040 mDNSexport void IncrementLabelSuffix(domainlabel *name, mDNSBool RichText)
2041 {
2042 mDNSu32 val = 0;
2043
2044 if (LabelContainsSuffix(name, RichText))
2045 val = RemoveLabelSuffix(name, RichText);
2046
2047 // If no existing suffix, start by renaming "Foo" as "Foo (2)" or "Foo-2" as appropriate.
2048 // If existing suffix in the range 2-9, increment it.
2049 // If we've had ten conflicts already, there are probably too many hosts trying to use the same name,
2050 // so add a random increment to improve the chances of finding an available name next time.
2051 if (val == 0) val = 2;
2052 else if (val < 10) val++;
2053 else val += 1 + mDNSRandom(99);
2054
2055 AppendLabelSuffix(name, val, RichText);
2056 }
2057
2058 // ***************************************************************************
2059 #if COMPILER_LIKES_PRAGMA_MARK
2060 #pragma mark -
2061 #pragma mark - Resource Record Utility Functions
2062 #endif
2063
2064 #define RRIsAddressType(RR) ((RR)->resrec.rrtype == kDNSType_A || (RR)->resrec.rrtype == kDNSType_AAAA)
2065 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
2066
2067 #define ResourceRecordIsValidAnswer(RR) ( ((RR)-> resrec.RecordType & kDNSRecordTypeActiveMask) && \
2068 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2069 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
2070 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
2071
2072 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
2073 (ResourceRecordIsValidAnswer(RR) && \
2074 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
2075
2076 #define RRUniqueOrKnownUnique(RR) ((RR)->RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeKnownUnique))
2077
2078 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
2079 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
2080
2081 // For records that have *never* been announced on the wire, their AnnounceCount will be set to InitialAnnounceCount (10).
2082 // When de-registering these records we do not need to send any goodbye packet because we never announced them in the first
2083 // place. If AnnounceCount is less than InitialAnnounceCount that means we have announced them at least once, so a goodbye
2084 // packet is needed. For this reason, if we ever reset AnnounceCount (e.g. after an interface change) we set it to
2085 // ReannounceCount (9), not InitialAnnounceCount. If we were to reset AnnounceCount back to InitialAnnounceCount that would
2086 // imply that the record had never been announced on the wire (which is false) and if the client were then to immediately
2087 // deregister that record before it had a chance to announce, we'd fail to send its goodbye packet (which would be a bug).
2088 #define InitialAnnounceCount ((mDNSu8)10)
2089 #define ReannounceCount ((mDNSu8)9)
2090
2091 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
2092 // This means that because the announce interval is doubled after sending the first packet, the first
2093 // observed on-the-wire inter-packet interval between announcements is actually one second.
2094 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
2095 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
2096 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
2097 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
2098
2099 #define DefaultAPIntervalForRecordType(X) ((X) & (kDNSRecordTypeAdvisory | kDNSRecordTypeShared ) ? DefaultAnnounceIntervalForTypeShared : \
2100 (X) & (kDNSRecordTypeUnique ) ? DefaultProbeIntervalForTypeUnique : \
2101 (X) & (kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique) ? DefaultAnnounceIntervalForTypeUnique : 0)
2102
2103 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
2104 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
2105 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
2106 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
2107
2108 #define MaxUnansweredQueries 4
2109
2110 mDNSlocal mDNSBool SameRData(const ResourceRecord *const r1, const ResourceRecord *const r2)
2111 {
2112 if (r1->rrtype != r2->rrtype) return(mDNSfalse);
2113 if (r1->rdlength != r2->rdlength) return(mDNSfalse);
2114 if (r1->rdatahash != r2->rdatahash) return(mDNSfalse);
2115 if (r1->rdnamehash != r2->rdnamehash) return(mDNSfalse);
2116 switch(r1->rrtype)
2117 {
2118 case kDNSType_CNAME:// Same as PTR
2119 case kDNSType_PTR: return(SameDomainName(&r1->rdata->u.name, &r2->rdata->u.name));
2120
2121 case kDNSType_SRV: return(mDNSBool)( r1->rdata->u.srv.priority == r2->rdata->u.srv.priority &&
2122 r1->rdata->u.srv.weight == r2->rdata->u.srv.weight &&
2123 r1->rdata->u.srv.port.NotAnInteger == r2->rdata->u.srv.port.NotAnInteger &&
2124 SameDomainName(&r1->rdata->u.srv.target, &r2->rdata->u.srv.target) );
2125
2126 default: return(mDNSPlatformMemSame(r1->rdata->u.data, r2->rdata->u.data, r1->rdlength));
2127 }
2128 }
2129
2130 mDNSlocal mDNSBool ResourceRecordAnswersQuestion(const ResourceRecord *const rr, const DNSQuestion *const q)
2131 {
2132 if (rr->InterfaceID &&
2133 q ->InterfaceID &&
2134 rr->InterfaceID != q->InterfaceID) return(mDNSfalse);
2135
2136 // RR type CNAME matches any query type. QTYPE ANY matches any RR type. QCLASS ANY matches any RR class.
2137 if (rr->rrtype != kDNSType_CNAME && rr->rrtype != q->qtype && q->qtype != kDNSQType_ANY ) return(mDNSfalse);
2138 if ( rr->rrclass != q->qclass && q->qclass != kDNSQClass_ANY) return(mDNSfalse);
2139 return(rr->namehash == q->qnamehash && SameDomainName(&rr->name, &q->qname));
2140 }
2141
2142 mDNSlocal mDNSu32 DomainNameHashValue(const domainname *const name)
2143 {
2144 mDNSu32 sum = 0;
2145 const mDNSu8 *c;
2146
2147 for (c = name->c; c[0] != 0 && c[1] != 0; c += 2)
2148 {
2149 sum += ((mDNSIsUpperCase(c[0]) ? c[0] + 'a' - 'A' : c[0]) << 8) |
2150 (mDNSIsUpperCase(c[1]) ? c[1] + 'a' - 'A' : c[1]);
2151 sum = (sum<<3) | (sum>>29);
2152 }
2153 if (c[0]) sum += ((mDNSIsUpperCase(c[0]) ? c[0] + 'a' - 'A' : c[0]) << 8);
2154 return(sum);
2155 }
2156
2157 #define HashSlot(X) (DomainNameHashValue(X) % CACHE_HASH_SLOTS)
2158
2159 mDNSlocal mDNSu32 RDataHashValue(mDNSu16 const rdlength, const RDataBody *const rdb)
2160 {
2161 mDNSu32 sum = 0;
2162 int i;
2163 for (i=0; i+1 < rdlength; i+=2)
2164 {
2165 sum += (((mDNSu32)(rdb->data[i])) << 8) | rdb->data[i+1];
2166 sum = (sum<<3) | (sum>>29);
2167 }
2168 if (i < rdlength)
2169 {
2170 sum += ((mDNSu32)(rdb->data[i])) << 8;
2171 }
2172 return(sum);
2173 }
2174
2175 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
2176 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
2177 // TTL and rdata may differ.
2178 // This is used for cache flush management:
2179 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
2180 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
2181 mDNSlocal mDNSBool SameResourceRecordSignature(const ResourceRecord *const r1, const ResourceRecord *const r2)
2182 {
2183 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
2184 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
2185 if (r1->InterfaceID &&
2186 r2->InterfaceID &&
2187 r1->InterfaceID != r2->InterfaceID) return(mDNSfalse);
2188 return(mDNSBool)(r1->rrtype == r2->rrtype && r1->rrclass == r2->rrclass && r1->namehash == r2->namehash && SameDomainName(&r1->name, &r2->name));
2189 }
2190
2191 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if the
2192 // authoratative record is in the probing state. Probes are sent with the wildcard type, so a response of
2193 // any type should match, even if it is not the type the client plans to use.
2194 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
2195 {
2196 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
2197 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
2198 if (pktrr->resrec.InterfaceID &&
2199 authrr->resrec.InterfaceID &&
2200 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
2201 if (authrr->resrec.RecordType != kDNSRecordTypeUnique && pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
2202 return(mDNSBool)(pktrr->resrec.rrclass == authrr->resrec.rrclass && pktrr->resrec.namehash == authrr->resrec.namehash && SameDomainName(&pktrr->resrec.name, &authrr->resrec.name));
2203 }
2204
2205 // IdenticalResourceRecord returns true if two resources records have
2206 // the same name, type, class, and identical rdata (InterfaceID and TTL may differ)
2207 mDNSlocal mDNSBool IdenticalResourceRecord(const ResourceRecord *const r1, const ResourceRecord *const r2)
2208 {
2209 if (!r1) { LogMsg("IdenticalResourceRecord ERROR: r1 is NULL"); return(mDNSfalse); }
2210 if (!r2) { LogMsg("IdenticalResourceRecord ERROR: r2 is NULL"); return(mDNSfalse); }
2211 if (r1->rrtype != r2->rrtype || r1->rrclass != r2->rrclass || r1->namehash != r2->namehash || !SameDomainName(&r1->name, &r2->name)) return(mDNSfalse);
2212 return(SameRData(r1, r2));
2213 }
2214
2215 // CacheRecord *ks is the CacheRecord from the known answer list in the query.
2216 // This is the information that the requester believes to be correct.
2217 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
2218 // This is the information that we believe to be correct.
2219 // We've already determined that we plan to give this answer on this interface
2220 // (either the record is non-specific, or it is specific to this interface)
2221 // so now we just need to check the name, type, class, rdata and TTL.
2222 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
2223 {
2224 // If RR signature is different, or data is different, then don't suppress our answer
2225 if (!IdenticalResourceRecord(&ka->resrec,&rr->resrec)) return(mDNSfalse);
2226
2227 // If the requester's indicated TTL is less than half the real TTL,
2228 // we need to give our answer before the requester's copy expires.
2229 // If the requester's indicated TTL is at least half the real TTL,
2230 // then we can suppress our answer this time.
2231 // If the requester's indicated TTL is greater than the TTL we believe,
2232 // then that's okay, and we don't need to do anything about it.
2233 // (If two responders on the network are offering the same information,
2234 // that's okay, and if they are offering the information with different TTLs,
2235 // the one offering the lower TTL should defer to the one offering the higher TTL.)
2236 return(mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
2237 }
2238
2239 mDNSlocal mDNSu16 GetRDLength(const ResourceRecord *const rr, mDNSBool estimate)
2240 {
2241 RDataBody *rd = &rr->rdata->u;
2242 const domainname *const name = estimate ? &rr->name : mDNSNULL;
2243 switch (rr->rrtype)
2244 {
2245 case kDNSType_A: return(sizeof(rd->ip));
2246 case kDNSType_CNAME:// Same as PTR
2247 case kDNSType_PTR: return(CompressedDomainNameLength(&rd->name, name));
2248 case kDNSType_HINFO:return(mDNSu16)(2 + (int)rd->data[0] + (int)rd->data[1 + (int)rd->data[0]]);
2249 case kDNSType_NULL: // Same as TXT -- not self-describing, so have to just trust rdlength
2250 case kDNSType_TXT: return(rr->rdlength); // TXT is not self-describing, so have to just trust rdlength
2251 case kDNSType_AAAA: return(sizeof(rd->ipv6));
2252 case kDNSType_SRV: return(mDNSu16)(6 + CompressedDomainNameLength(&rd->srv.target, name));
2253 default: debugf("Warning! Don't know how to get length of resource type %d", rr->rrtype);
2254 return(rr->rdlength);
2255 }
2256 }
2257
2258 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
2259 {
2260 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
2261 {
2262 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
2263 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
2264 }
2265 else if (rr->AnnounceCount && ResourceRecordIsValidAnswer(rr))
2266 {
2267 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
2268 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
2269 }
2270 }
2271
2272 #define GetRRDomainNameTarget(RR) ( \
2273 ((RR)->rrtype == kDNSType_CNAME || (RR)->rrtype == kDNSType_PTR) ? &(RR)->rdata->u.name : \
2274 ((RR)->rrtype == kDNSType_SRV ) ? &(RR)->rdata->u.srv.target : mDNSNULL )
2275
2276 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
2277 {
2278 // To allow us to aggregate probes when a group of services are registered together,
2279 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
2280 // 1/4 second wait; probe
2281 // 1/4 second wait; probe
2282 // 1/4 second wait; probe
2283 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
2284
2285 // If we have no probe suppression time set, or it is in the past, set it now
2286 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
2287 {
2288 m->SuppressProbes = (m->timenow + DefaultProbeIntervalForTypeUnique) | 1;
2289 // If we already have a probe scheduled to go out sooner, then use that time to get better aggregation
2290 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
2291 m->SuppressProbes = m->NextScheduledProbe;
2292 // If we already have a query scheduled to go out sooner, then use that time to get better aggregation
2293 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
2294 m->SuppressProbes = m->NextScheduledQuery;
2295 }
2296
2297 // We announce to flush stale data from other caches. It is a reasonable assumption that any
2298 // old stale copies will probably have the same TTL we're using, so announcing longer than
2299 // this serves no purpose -- any stale copies of that record will have expired by then anyway.
2300 rr->AnnounceUntil = m->timenow + TicksTTL(rr);
2301 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
2302 // Set LastMCTime to now, to inhibit multicast responses
2303 // (no need to send additional multicast responses when we're announcing anyway)
2304 rr->LastMCTime = m->timenow;
2305 rr->LastMCInterface = mDNSInterfaceMark;
2306
2307 // If this is a record type that's not going to probe, then delay its first announcement so that
2308 // it will go out synchronized with the first announcement for the other records that *are* probing.
2309 // This is a minor performance tweak that helps keep groups of related records synchronized together.
2310 // The addition of "rr->ThisAPInterval / 2" is to make sure that, in the event that any of the probes are
2311 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
2312 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
2313 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
2314 if (rr->resrec.RecordType != kDNSRecordTypeUnique)
2315 rr->LastAPTime += DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
2316
2317 SetNextAnnounceProbeTime(m, rr);
2318 }
2319
2320 mDNSlocal void SetNewRData(ResourceRecord *const rr, RData *NewRData, mDNSu16 rdlength)
2321 {
2322 domainname *target;
2323 if (NewRData)
2324 {
2325 rr->rdata = NewRData;
2326 rr->rdlength = rdlength;
2327 }
2328 // Must not try to get target pointer until after updating rr->rdata
2329 target = GetRRDomainNameTarget(rr);
2330 rr->rdlength = GetRDLength(rr, mDNSfalse);
2331 rr->rdestimate = GetRDLength(rr, mDNStrue);
2332 rr->rdatahash = RDataHashValue(rr->rdlength, &rr->rdata->u);
2333 rr->rdnamehash = target ? DomainNameHashValue(target) : 0;
2334 }
2335
2336 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
2337 {
2338 domainname *target = GetRRDomainNameTarget(&rr->resrec);
2339
2340 if (!target) debugf("SetTargetToHostName: Don't know how to set the target of rrtype %d", rr->resrec.rrtype);
2341
2342 if (target && SameDomainName(target, &m->hostname))
2343 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name.c, target->c);
2344
2345 if (target && !SameDomainName(target, &m->hostname))
2346 {
2347 AssignDomainName(*target, m->hostname);
2348 SetNewRData(&rr->resrec, mDNSNULL, 0);
2349
2350 // If we're in the middle of probing this record, we need to start again,
2351 // because changing its rdata may change the outcome of the tie-breaker.
2352 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
2353 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
2354
2355 // If we've announced this record, we really should send a goodbye packet for the old rdata before
2356 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
2357 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
2358 if (rr->AnnounceCount < InitialAnnounceCount && rr->resrec.RecordType == kDNSRecordTypeShared)
2359 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));
2360
2361 if (rr->AnnounceCount < ReannounceCount)
2362 rr->AnnounceCount = ReannounceCount;
2363 rr->ThisAPInterval = DefaultAPIntervalForRecordType(rr->resrec.RecordType);
2364 InitializeLastAPTime(m,rr);
2365 }
2366 }
2367
2368 mDNSlocal void CompleteProbing(mDNS *const m, AuthRecord *const rr)
2369 {
2370 verbosedebugf("Probing for %##s (%s) complete", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2371 if (!rr->Acknowledged && rr->RecordCallback)
2372 {
2373 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2374 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2375 rr->Acknowledged = mDNStrue;
2376 m->mDNS_reentrancy++; // Increment to allow client to legally make mDNS API calls from the callback
2377 rr->RecordCallback(m, rr, mStatus_NoError);
2378 m->mDNS_reentrancy--; // Decrement to block mDNS API calls again
2379 }
2380 }
2381
2382 #define ValidateDomainName(N) (DomainNameLength(N) <= MAX_DOMAIN_NAME)
2383
2384 mDNSlocal mDNSBool ValidateRData(const mDNSu16 rrtype, const mDNSu16 rdlength, const RData *const rd)
2385 {
2386 mDNSu16 len;
2387 switch(rrtype)
2388 {
2389 case kDNSType_A: return(rdlength == sizeof(mDNSv4Addr));
2390
2391 case kDNSType_NS: // Same as PTR
2392 case kDNSType_MD: // Same as PTR
2393 case kDNSType_MF: // Same as PTR
2394 case kDNSType_CNAME:// Same as PTR
2395 //case kDNSType_SOA not checked
2396 case kDNSType_MB: // Same as PTR
2397 case kDNSType_MG: // Same as PTR
2398 case kDNSType_MR: // Same as PTR
2399 //case kDNSType_NULL not checked (no specified format, so always valid)
2400 //case kDNSType_WKS not checked
2401 case kDNSType_PTR: len = DomainNameLength(&rd->u.name);
2402 return(len <= MAX_DOMAIN_NAME && rdlength == len);
2403
2404 case kDNSType_HINFO:// Same as TXT (roughly)
2405 case kDNSType_MINFO:// Same as TXT (roughly)
2406 case kDNSType_TXT: {
2407 const mDNSu8 *ptr = rd->u.txt.c;
2408 const mDNSu8 *end = rd->u.txt.c + rdlength;
2409 while (ptr < end) ptr += 1 + ptr[0];
2410 return (ptr == end);
2411 }
2412
2413 case kDNSType_AAAA: return(rdlength == sizeof(mDNSv6Addr));
2414
2415 case kDNSType_MX: len = DomainNameLength(&rd->u.mx.exchange);
2416 return(len <= MAX_DOMAIN_NAME && rdlength == 2+len);
2417
2418 case kDNSType_SRV: len = DomainNameLength(&rd->u.srv.target);
2419 return(len <= MAX_DOMAIN_NAME && rdlength == 6+len);
2420
2421 default: return(mDNStrue); // Allow all other types without checking
2422 }
2423 }
2424
2425 // Two records qualify to be local duplicates if the RecordTypes are the same, or if one is Unique and the other Verified
2426 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified))
2427 #define RecordIsLocalDuplicate(A,B) ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
2428
2429 mDNSlocal mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
2430 {
2431 domainname *target = GetRRDomainNameTarget(&rr->resrec);
2432 AuthRecord *r;
2433 AuthRecord **p = &m->ResourceRecords;
2434 AuthRecord **d = &m->DuplicateRecords;
2435 AuthRecord **l = &m->LocalOnlyRecords;
2436
2437 #if TEST_LOCALONLY_FOR_EVERYTHING
2438 rr->resrec.InterfaceID = (mDNSInterfaceID)~0;
2439 #endif
2440
2441 while (*p && *p != rr) p=&(*p)->next;
2442 while (*d && *d != rr) d=&(*d)->next;
2443 while (*l && *l != rr) l=&(*l)->next;
2444 if (*d || *p || *l)
2445 {
2446 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));
2447 return(mStatus_AlreadyRegistered);
2448 }
2449
2450 if (rr->DependentOn)
2451 {
2452 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
2453 rr->resrec.RecordType = kDNSRecordTypeVerified;
2454 else
2455 {
2456 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
2457 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2458 return(mStatus_Invalid);
2459 }
2460 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified)))
2461 {
2462 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
2463 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
2464 return(mStatus_Invalid);
2465 }
2466 }
2467
2468 // If this resource record is referencing a specific interface, make sure it exists
2469 if (rr->resrec.InterfaceID && rr->resrec.InterfaceID != ((mDNSInterfaceID)~0))
2470 {
2471 NetworkInterfaceInfo *intf;
2472 for (intf = m->HostInterfaces; intf; intf = intf->next)
2473 if (intf->InterfaceID == rr->resrec.InterfaceID) break;
2474 if (!intf)
2475 {
2476 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr->resrec.InterfaceID);
2477 return(mStatus_BadReferenceErr);
2478 }
2479 }
2480
2481 rr->next = mDNSNULL;
2482
2483 // Field Group 1: Persistent metadata for Authoritative Records
2484 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2485 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2486 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2487 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
2488 // rr->Callback = already set in mDNS_SetupResourceRecord
2489 // rr->Context = already set in mDNS_SetupResourceRecord
2490 // rr->RecordType = already set in mDNS_SetupResourceRecord
2491 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
2492
2493 // Field Group 2: Transient state for Authoritative Records
2494 rr->Acknowledged = mDNSfalse;
2495 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
2496 rr->AnnounceCount = InitialAnnounceCount;
2497 rr->IncludeInProbe = mDNSfalse;
2498 rr->ImmedAnswer = mDNSNULL;
2499 rr->ImmedAdditional = mDNSNULL;
2500 rr->SendRNow = mDNSNULL;
2501 rr->v4Requester = zeroIPAddr;
2502 rr->v6Requester = zerov6Addr;
2503 rr->NextResponse = mDNSNULL;
2504 rr->NR_AnswerTo = mDNSNULL;
2505 rr->NR_AdditionalTo = mDNSNULL;
2506 rr->ThisAPInterval = DefaultAPIntervalForRecordType(rr->resrec.RecordType);
2507 InitializeLastAPTime(m, rr);
2508 // rr->AnnounceUntil = Set for us in InitializeLastAPTime()
2509 // rr->LastAPTime = Set for us in InitializeLastAPTime()
2510 // rr->LastMCTime = Set for us in InitializeLastAPTime()
2511 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
2512 rr->NewRData = mDNSNULL;
2513 rr->newrdlength = 0;
2514 rr->UpdateCallback = mDNSNULL;
2515 rr->UpdateCredits = kMaxUpdateCredits;
2516 rr->NextUpdateCredit = 0;
2517 rr->UpdateBlocked = 0;
2518
2519 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
2520 // rr->resrec.name.c = MUST be set by client
2521 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
2522 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
2523 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
2524 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
2525
2526 if (rr->HostTarget)
2527 {
2528 if (target) target->c[0] = 0;
2529 SetTargetToHostName(m, rr); // This also sets rdlength and rdestimate for us
2530 }
2531 else
2532 {
2533 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
2534 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
2535 }
2536
2537 if (!ValidateDomainName(&rr->resrec.name))
2538 { LogMsg("Attempt to register record with invalid name: %s", GetRRDisplayString(m, rr)); return(mStatus_Invalid); }
2539
2540 // Don't do this until *after* we've set rr->resrec.rdlength
2541 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
2542 { LogMsg("Attempt to register record with invalid rdata: %s", GetRRDisplayString(m, rr)); return(mStatus_Invalid); }
2543
2544 rr->resrec.namehash = DomainNameHashValue(&rr->resrec.name);
2545 rr->resrec.rdatahash = RDataHashValue(rr->resrec.rdlength, &rr->resrec.rdata->u);
2546 rr->resrec.rdnamehash = target ? DomainNameHashValue(target) : 0;
2547
2548 if (rr->resrec.InterfaceID == ((mDNSInterfaceID)~0))
2549 {
2550 debugf("Adding %p %##s (%s) to LocalOnly list", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2551 *l = rr;
2552 if (!m->NewLocalOnlyRecords) m->NewLocalOnlyRecords = rr;
2553 // If this is supposed to be unique, make sure we don't have any name conflicts
2554 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2555 {
2556 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
2557 for (r = m->LocalOnlyRecords; r; r=r->next)
2558 {
2559 const AuthRecord *s2 = r->RRSet ? r->RRSet : r;
2560 if (s1 != s2 && SameResourceRecordSignature(&r->resrec, &rr->resrec) && !SameRData(&r->resrec, &rr->resrec))
2561 break;
2562 }
2563 if (r) // If we found a conflict, set DiscardLocalOnlyRecords so we'll deliver the callback
2564 {
2565 debugf("Name conflict %p %##s (%s)", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2566 m->DiscardLocalOnlyRecords = mDNStrue;
2567 }
2568 else // else no conflict, so set ProbeCount to zero and update RecordType as appropriate
2569 {
2570 rr->ProbeCount = 0;
2571 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
2572 }
2573 }
2574 }
2575 else
2576 {
2577 // Now that's we've finished building our new record, make sure it's not identical to one we already have
2578 for (r = m->ResourceRecords; r; r=r->next) if (RecordIsLocalDuplicate(r, rr)) break;
2579
2580 if (r)
2581 {
2582 debugf("Adding %p %##s (%s) to duplicate list", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2583 *d = rr;
2584 // If the previous copy of this record is already verified unique,
2585 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
2586 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
2587 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
2588 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
2589 rr->ProbeCount = 0;
2590 }
2591 else
2592 {
2593 debugf("Adding %p %##s (%s) to active record list", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2594 *p = rr;
2595 }
2596 }
2597 return(mStatus_NoError);
2598 }
2599
2600 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
2601 {
2602 m->ProbeFailTime = m->timenow;
2603 m->NumFailedProbes++;
2604 // If we've had ten or more probe failures, rate-limit to one every five seconds
2605 // The result is ORed with 1 to make sure SuppressProbes is not accidentally set to zero
2606 if (m->NumFailedProbes >= 10) m->SuppressProbes = (m->timenow + mDNSPlatformOneSecond * 5) | 1;
2607 if (m->NumFailedProbes >= 16)
2608 LogMsg("Name in use: %##s (%s); need to choose another (%d)",
2609 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), m->NumFailedProbes);
2610 }
2611
2612 // mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
2613 // mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
2614 // mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
2615 typedef enum { mDNS_Dereg_normal, mDNS_Dereg_conflict, mDNS_Dereg_repeat } mDNS_Dereg_type;
2616
2617 // NOTE: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
2618 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2619 mDNSlocal mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
2620 {
2621 mDNSu8 RecordType = rr->resrec.RecordType;
2622 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
2623 if (rr->resrec.InterfaceID == ((mDNSInterfaceID)~0)) p = &m->LocalOnlyRecords;
2624 while (*p && *p != rr) p=&(*p)->next;
2625
2626 if (*p)
2627 {
2628 // We found our record on the main list. See if there are any duplicates that need special handling.
2629 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
2630 {
2631 AuthRecord *r2 = m->DuplicateRecords;
2632 while (r2)
2633 {
2634 if (RecordIsLocalDuplicate(r2, rr)) { mDNS_Deregister_internal(m, r2, drt); r2 = m->DuplicateRecords; }
2635 else r2=r2->next;
2636 }
2637 }
2638 else
2639 {
2640 // Before we delete the record (and potentially send a goodbye packet)
2641 // first see if we have a record on the duplicate list ready to take over from it.
2642 AuthRecord **d = &m->DuplicateRecords;
2643 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
2644 if (*d)
2645 {
2646 AuthRecord *dup = *d;
2647 debugf("Duplicate record %p taking over from %p %##s (%s)", dup, rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2648 *d = dup->next; // Cut replacement record from DuplicateRecords list
2649 dup->next = rr->next; // And then...
2650 rr->next = dup; // ... splice it in right after the record we're about to delete
2651 dup->resrec.RecordType = rr->resrec.RecordType;
2652 dup->ProbeCount = rr->ProbeCount;
2653 dup->AnnounceCount = rr->AnnounceCount;
2654 dup->ImmedAnswer = rr->ImmedAnswer;
2655 dup->ImmedAdditional = rr->ImmedAdditional;
2656 dup->v4Requester = rr->v4Requester;
2657 dup->v6Requester = rr->v6Requester;
2658 dup->ThisAPInterval = rr->ThisAPInterval;
2659 dup->AnnounceUntil = rr->AnnounceUntil;
2660 dup->LastAPTime = rr->LastAPTime;
2661 dup->LastMCTime = rr->LastMCTime;
2662 dup->LastMCInterface = rr->LastMCInterface;
2663 if (RecordType == kDNSRecordTypeShared) rr->AnnounceCount = InitialAnnounceCount;
2664 }
2665 }
2666 }
2667 else
2668 {
2669 // We didn't find our record on the main list; try the DuplicateRecords list instead.
2670 p = &m->DuplicateRecords;
2671 while (*p && *p != rr) p=&(*p)->next;
2672 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2673 if (*p && RecordType == kDNSRecordTypeShared) rr->AnnounceCount = InitialAnnounceCount;
2674 if (*p) debugf("DNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2675 }
2676
2677 if (!*p)
2678 {
2679 // No need to log an error message if we already know this is a potentially repeated deregistration
2680 if (drt != mDNS_Dereg_repeat)
2681 debugf("mDNS_Deregister_internal: Record %p %##s (%s) not found in list", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2682 return(mStatus_BadReferenceErr);
2683 }
2684
2685 // If this is a shared record and we've announced it at least once,
2686 // we need to retract that announcement before we delete the record
2687 if (RecordType == kDNSRecordTypeShared && rr->AnnounceCount < InitialAnnounceCount)
2688 {
2689 verbosedebugf("mDNS_Deregister_internal: Sending deregister for %##s (%s)", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2690 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2691 rr->resrec.rroriginalttl = 0;
2692 rr->ImmedAnswer = mDNSInterfaceMark;
2693 if (rr->resrec.InterfaceID == ((mDNSInterfaceID)~0))
2694 m->DiscardLocalOnlyRecords = mDNStrue;
2695 else
2696 {
2697 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
2698 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
2699 }
2700 }
2701 else
2702 {
2703 *p = rr->next; // Cut this record from the list
2704 // If someone is about to look at this, bump the pointer forward
2705 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
2706 if (m->NewLocalOnlyRecords == rr) m->NewLocalOnlyRecords = rr->next;
2707 rr->next = mDNSNULL;
2708
2709 if (RecordType == kDNSRecordTypeUnregistered)
2710 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeUnregistered",
2711 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2712 else if (RecordType == kDNSRecordTypeDeregistering)
2713 debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeDeregistering",
2714 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2715 else
2716 {
2717 verbosedebugf("mDNS_Deregister_internal: Deleting record for %##s (%s)", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2718 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
2719 }
2720
2721 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
2722 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2723 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
2724
2725 // If we have an update queued up which never executed, give the client a chance to free that memory
2726 if (rr->NewRData)
2727 {
2728 RData *OldRData = rr->resrec.rdata;
2729 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
2730 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
2731 if (rr->UpdateCallback)
2732 rr->UpdateCallback(m, rr, OldRData); // ... and let the client know
2733 }
2734
2735 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2736 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2737 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2738 // so any attempt to touch rr after this is likely to lead to a crash.
2739 m->mDNS_reentrancy++; // Increment to allow client to legally make mDNS API calls from the callback
2740 if (RecordType == kDNSRecordTypeShared)
2741 {
2742 if (rr->RecordCallback)
2743 rr->RecordCallback(m, rr, mStatus_MemFree);
2744 }
2745 else if (drt == mDNS_Dereg_conflict)
2746 {
2747 RecordProbeFailure(m, rr);
2748 if (rr->RecordCallback)
2749 rr->RecordCallback(m, rr, mStatus_NameConflict);
2750 }
2751 m->mDNS_reentrancy--; // Decrement to block mDNS API calls again
2752 }
2753 return(mStatus_NoError);
2754 }
2755
2756 // ***************************************************************************
2757 #if COMPILER_LIKES_PRAGMA_MARK
2758 #pragma mark -
2759 #pragma mark -
2760 #pragma mark - DNS Message Creation Functions
2761 #endif
2762
2763 mDNSlocal void InitializeDNSMessage(DNSMessageHeader *h, mDNSOpaque16 id, mDNSOpaque16 flags)
2764 {
2765 h->id = id;
2766 h->flags = flags;
2767 h->numQuestions = 0;
2768 h->numAnswers = 0;
2769 h->numAuthorities = 0;
2770 h->numAdditionals = 0;
2771 }
2772
2773 mDNSlocal const mDNSu8 *FindCompressionPointer(const mDNSu8 *const base, const mDNSu8 *const end, const mDNSu8 *const domname)
2774 {
2775 const mDNSu8 *result = end - *domname - 1;
2776
2777 if (*domname == 0) return(mDNSNULL); // There's no point trying to match just the root label
2778
2779 // This loop examines each possible starting position in packet, starting end of the packet and working backwards
2780 while (result >= base)
2781 {
2782 // If the length byte and first character of the label match, then check further to see
2783 // if this location in the packet will yield a useful name compression pointer.
2784 if (result[0] == domname[0] && result[1] == domname[1])
2785 {
2786 const mDNSu8 *name = domname;
2787 const mDNSu8 *targ = result;
2788 while (targ + *name < end)
2789 {
2790 // First see if this label matches
2791 int i;
2792 const mDNSu8 *pointertarget;
2793 for (i=0; i <= *name; i++) if (targ[i] != name[i]) break;
2794 if (i <= *name) break; // If label did not match, bail out
2795 targ += 1 + *name; // Else, did match, so advance target pointer
2796 name += 1 + *name; // and proceed to check next label
2797 if (*name == 0 && *targ == 0) return(result); // If no more labels, we found a match!
2798 if (*name == 0) break; // If no more labels to match, we failed, so bail out
2799
2800 // The label matched, so now follow the pointer (if appropriate) and then see if the next label matches
2801 if (targ[0] < 0x40) continue; // If length value, continue to check next label
2802 if (targ[0] < 0xC0) break; // If 40-BF, not valid
2803 if (targ+1 >= end) break; // Second byte not present!
2804 pointertarget = base + (((mDNSu16)(targ[0] & 0x3F)) << 8) + targ[1];
2805 if (targ < pointertarget) break; // Pointertarget must point *backwards* in the packet
2806 if (pointertarget[0] >= 0x40) break; // Pointertarget must point to a valid length byte
2807 targ = pointertarget;
2808 }
2809 }
2810 result--; // We failed to match at this search position, so back up the tentative result pointer and try again
2811 }
2812 return(mDNSNULL);
2813 }
2814
2815 // Put a string of dot-separated labels as length-prefixed labels
2816 // domainname is a fully-qualified name (i.e. assumed to be ending in a dot, even if it doesn't)
2817 // msg points to the message we're building (pass mDNSNULL if we don't want to use compression pointers)
2818 // end points to the end of the message so far
2819 // ptr points to where we want to put the name
2820 // limit points to one byte past the end of the buffer that we must not overrun
2821 // domainname is the name to put
2822 mDNSlocal mDNSu8 *putDomainNameAsLabels(const DNSMessage *const msg,
2823 mDNSu8 *ptr, const mDNSu8 *const limit, const domainname *const name)
2824 {
2825 const mDNSu8 *const base = (const mDNSu8 *)msg;
2826 const mDNSu8 * np = name->c;
2827 const mDNSu8 *const max = name->c + MAX_DOMAIN_NAME; // Maximum that's valid
2828 const mDNSu8 * pointer = mDNSNULL;
2829 const mDNSu8 *const searchlimit = ptr;
2830
2831 while (*np && ptr < limit-1) // While we've got characters in the name, and space to write them in the message...
2832 {
2833 if (*np > MAX_DOMAIN_LABEL)
2834 { LogMsg("Malformed domain name %##s (label more than 63 bytes)", name->c); return(mDNSNULL); }
2835
2836 // This check correctly allows for the final trailing root label:
2837 // e.g.
2838 // Suppose our domain name is exactly 255 bytes long, including the final trailing root label.
2839 // Suppose np is now at name->c[248], and we're about to write our last non-null label ("local").
2840 // We know that max will be at name->c[255]
2841 // That means that np + 1 + 5 == max - 1, so we (just) pass the "if" test below, write our
2842 // six bytes, then exit the loop, write the final terminating root label, and the domain
2843 // name we've written is exactly 255 bytes long, exactly at the correct legal limit.
2844 // If the name is one byte longer, then we fail the "if" test below, and correctly bail out.
2845 if (np + 1 + *np >= max)
2846 { LogMsg("Malformed domain name %##s (more than 255 bytes)", name->c); return(mDNSNULL); }
2847
2848 if (base) pointer = FindCompressionPointer(base, searchlimit, np);
2849 if (pointer) // Use a compression pointer if we can
2850 {
2851 mDNSu16 offset = (mDNSu16)(pointer - base);
2852 *ptr++ = (mDNSu8)(0xC0 | (offset >> 8));
2853 *ptr++ = (mDNSu8)( offset );
2854 return(ptr);
2855 }
2856 else // Else copy one label and try again
2857 {
2858 int i;
2859 mDNSu8 len = *np++;
2860 if (ptr + 1 + len >= limit) return(mDNSNULL);
2861 *ptr++ = len;
2862 for (i=0; i<len; i++) *ptr++ = *np++;
2863 }
2864 }
2865
2866 if (ptr < limit) // If we didn't run out of space
2867 {
2868 *ptr++ = 0; // Put the final root label
2869 return(ptr); // and return
2870 }
2871
2872 return(mDNSNULL);
2873 }
2874
2875 mDNSlocal mDNSu8 *putRData(const DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit, ResourceRecord *rr)
2876 {
2877 switch (rr->rrtype)
2878 {
2879 case kDNSType_A: if (rr->rdlength != 4)
2880 {
2881 debugf("putRData: Illegal length %d for kDNSType_A", rr->rdlength);
2882 return(mDNSNULL);
2883 }
2884 if (ptr + 4 > limit) return(mDNSNULL);
2885 *ptr++ = rr->rdata->u.ip.b[0];
2886 *ptr++ = rr->rdata->u.ip.b[1];
2887 *ptr++ = rr->rdata->u.ip.b[2];
2888 *ptr++ = rr->rdata->u.ip.b[3];
2889 return(ptr);
2890
2891 case kDNSType_CNAME:// Same as PTR
2892 case kDNSType_PTR: return(putDomainNameAsLabels(msg, ptr, limit, &rr->rdata->u.name));
2893
2894 case kDNSType_HINFO:// Same as TXT
2895 case kDNSType_TXT: if (ptr + rr->rdlength > limit) return(mDNSNULL);
2896 mDNSPlatformMemCopy(rr->rdata->u.data, ptr, rr->rdlength);
2897 return(ptr + rr->rdlength);
2898
2899 case kDNSType_AAAA: if (rr->rdlength != sizeof(rr->rdata->u.ipv6))
2900 {
2901 debugf("putRData: Illegal length %d for kDNSType_AAAA", rr->rdlength);
2902 return(mDNSNULL);
2903 }
2904 if (ptr + sizeof(rr->rdata->u.ipv6) > limit) return(mDNSNULL);
2905 mDNSPlatformMemCopy(&rr->rdata->u.ipv6, ptr, sizeof(rr->rdata->u.ipv6));
2906 return(ptr + sizeof(rr->rdata->u.ipv6));
2907
2908 case kDNSType_SRV: if (ptr + 6 > limit) return(mDNSNULL);
2909 *ptr++ = (mDNSu8)(rr->rdata->u.srv.priority >> 8);
2910 *ptr++ = (mDNSu8)(rr->rdata->u.srv.priority );
2911 *ptr++ = (mDNSu8)(rr->rdata->u.srv.weight >> 8);
2912 *ptr++ = (mDNSu8)(rr->rdata->u.srv.weight );
2913 *ptr++ = rr->rdata->u.srv.port.b[0];
2914 *ptr++ = rr->rdata->u.srv.port.b[1];
2915 return(putDomainNameAsLabels(msg, ptr, limit, &rr->rdata->u.srv.target));
2916
2917 default: if (ptr + rr->rdlength > limit) return(mDNSNULL);
2918 debugf("putRData: Warning! Writing resource type %d as raw data", rr->rrtype);
2919 mDNSPlatformMemCopy(rr->rdata->u.data, ptr, rr->rdlength);
2920 return(ptr + rr->rdlength);
2921 }
2922 }
2923
2924 mDNSlocal mDNSu8 *PutResourceRecordTTL(DNSMessage *const msg, mDNSu8 *ptr, mDNSu16 *count, ResourceRecord *rr, mDNSu32 ttl)
2925 {
2926 mDNSu8 *endofrdata;
2927 mDNSu16 actualLength;
2928 const mDNSu8 *limit = msg->data + AbsoluteMaxDNSMessageData;
2929
2930 // If we have a single large record to put in the packet, then we allow the packet to be up to 9K bytes,
2931 // but in the normal case we try to keep the packets below 1500 to avoid IP fragmentation on standard Ethernet
2932 if (msg->h.numAnswers || msg->h.numAuthorities || msg->h.numAdditionals)
2933 limit = msg->data + NormalMaxDNSMessageData;
2934
2935 if (rr->RecordType == kDNSRecordTypeUnregistered)
2936 {
2937 LogMsg("PutResourceRecord ERROR! Attempt to put kDNSRecordTypeUnregistered %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype));
2938 return(ptr);
2939 }
2940
2941 ptr = putDomainNameAsLabels(msg, ptr, limit, &rr->name);
2942 if (!ptr || ptr + 10 >= limit) return(mDNSNULL); // If we're out-of-space, return mDNSNULL
2943 ptr[0] = (mDNSu8)(rr->rrtype >> 8);
2944 ptr[1] = (mDNSu8)(rr->rrtype );
2945 ptr[2] = (mDNSu8)(rr->rrclass >> 8);
2946 ptr[3] = (mDNSu8)(rr->rrclass );
2947 ptr[4] = (mDNSu8)(ttl >> 24);
2948 ptr[5] = (mDNSu8)(ttl >> 16);
2949 ptr[6] = (mDNSu8)(ttl >> 8);
2950 ptr[7] = (mDNSu8)(ttl );
2951 endofrdata = putRData(msg, ptr+10, limit, rr);
2952 if (!endofrdata) { verbosedebugf("Ran out of space in PutResourceRecord for %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype)); return(mDNSNULL); }
2953
2954 // Go back and fill in the actual number of data bytes we wrote
2955 // (actualLength can be less than rdlength when domain name compression is used)
2956 actualLength = (mDNSu16)(endofrdata - ptr - 10);
2957 ptr[8] = (mDNSu8)(actualLength >> 8);
2958 ptr[9] = (mDNSu8)(actualLength );
2959
2960 (*count)++;
2961 return(endofrdata);
2962 }
2963
2964 #define PutResourceRecord(MSG, P, C, RR) PutResourceRecordTTL((MSG), (P), (C), (RR), (RR)->rroriginalttl)
2965
2966 mDNSlocal mDNSu8 *PutResourceRecordCappedTTL(DNSMessage *const msg, mDNSu8 *ptr, mDNSu16 *count, ResourceRecord *rr, mDNSu32 maxttl)
2967 {
2968 if (maxttl > rr->rroriginalttl) maxttl = rr->rroriginalttl;
2969 return(PutResourceRecordTTL(msg, ptr, count, rr, maxttl));
2970 }
2971
2972 #if 0
2973 mDNSlocal mDNSu8 *putEmptyResourceRecord(DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit,
2974 mDNSu16 *count, const AuthRecord *rr)
2975 {
2976 ptr = putDomainNameAsLabels(msg, ptr, limit, &rr->name);
2977 if (!ptr || ptr + 10 > limit) return(mDNSNULL); // If we're out-of-space, return mDNSNULL
2978 ptr[0] = (mDNSu8)(rr->resrec.rrtype >> 8); // Put type
2979 ptr[1] = (mDNSu8)(rr->resrec.rrtype );
2980 ptr[2] = (mDNSu8)(rr->resrec.rrclass >> 8); // Put class
2981 ptr[3] = (mDNSu8)(rr->resrec.rrclass );
2982 ptr[4] = ptr[5] = ptr[6] = ptr[7] = 0; // TTL is zero
2983 ptr[8] = ptr[9] = 0; // RDATA length is zero
2984 (*count)++;
2985 return(ptr + 10);
2986 }
2987 #endif
2988
2989 mDNSlocal mDNSu8 *putQuestion(DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit,
2990 const domainname *const name, mDNSu16 rrtype, mDNSu16 rrclass)
2991 {
2992 ptr = putDomainNameAsLabels(msg, ptr, limit, name);
2993 if (!ptr || ptr+4 >= limit) return(mDNSNULL); // If we're out-of-space, return mDNSNULL
2994 ptr[0] = (mDNSu8)(rrtype >> 8);
2995 ptr[1] = (mDNSu8)(rrtype );
2996 ptr[2] = (mDNSu8)(rrclass >> 8);
2997 ptr[3] = (mDNSu8)(rrclass );
2998 msg->h.numQuestions++;
2999 return(ptr+4);
3000 }
3001
3002 // ***************************************************************************
3003 #if COMPILER_LIKES_PRAGMA_MARK
3004 #pragma mark -
3005 #pragma mark - DNS Message Parsing Functions
3006 #endif
3007
3008 mDNSlocal const mDNSu8 *skipDomainName(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *const end)
3009 {
3010 mDNSu16 total = 0;
3011
3012 if (ptr < (mDNSu8*)msg || ptr >= end)
3013 { debugf("skipDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL); }
3014
3015 while (1) // Read sequence of labels
3016 {
3017 const mDNSu8 len = *ptr++; // Read length of this label
3018 if (len == 0) return(ptr); // If length is zero, that means this name is complete
3019 switch (len & 0xC0)
3020 {
3021 case 0x00: if (ptr + len >= end) // Remember: expect at least one more byte for the root label
3022 { debugf("skipDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL); }
3023 if (total + 1 + len >= MAX_DOMAIN_NAME) // Remember: expect at least one more byte for the root label
3024 { debugf("skipDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL); }
3025 ptr += len;
3026 total += 1 + len;
3027 break;
3028
3029 case 0x40: debugf("skipDomainName: Extended EDNS0 label types 0x%X not supported", len); return(mDNSNULL);
3030 case 0x80: debugf("skipDomainName: Illegal label length 0x%X", len); return(mDNSNULL);
3031 case 0xC0: return(ptr+1);
3032 }
3033 }
3034 }
3035
3036 // Routine to fetch an FQDN from the DNS message, following compression pointers if necessary.
3037 mDNSlocal const mDNSu8 *getDomainName(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *const end,
3038 domainname *const name)
3039 {
3040 const mDNSu8 *nextbyte = mDNSNULL; // Record where we got to before we started following pointers
3041 mDNSu8 *np = name->c; // Name pointer
3042 const mDNSu8 *const limit = np + MAX_DOMAIN_NAME; // Limit so we don't overrun buffer
3043
3044 if (ptr < (mDNSu8*)msg || ptr >= end)
3045 { debugf("getDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL); }
3046
3047 *np = 0; // Tentatively place the root label here (may be overwritten if we have more labels)
3048
3049 while (1) // Read sequence of labels
3050 {
3051 const mDNSu8 len = *ptr++; // Read length of this label
3052 if (len == 0) break; // If length is zero, that means this name is complete
3053 switch (len & 0xC0)
3054 {
3055 int i;
3056 mDNSu16 offset;
3057
3058 case 0x00: if (ptr + len >= end) // Remember: expect at least one more byte for the root label
3059 { debugf("getDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL); }
3060 if (np + 1 + len >= limit) // Remember: expect at least one more byte for the root label
3061 { debugf("getDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL); }
3062 *np++ = len;
3063 for (i=0; i<len; i++) *np++ = *ptr++;
3064 *np = 0; // Tentatively place the root label here (may be overwritten if we have more labels)
3065 break;
3066
3067 case 0x40: debugf("getDomainName: Extended EDNS0 label types 0x%X not supported in name %##s", len, name->c);
3068 return(mDNSNULL);
3069
3070 case 0x80: debugf("getDomainName: Illegal label length 0x%X in domain name %##s", len, name->c); return(mDNSNULL);
3071
3072 case 0xC0: offset = (mDNSu16)((((mDNSu16)(len & 0x3F)) << 8) | *ptr++);
3073 if (!nextbyte) nextbyte = ptr; // Record where we got to before we started following pointers
3074 ptr = (mDNSu8 *)msg + offset;
3075 if (ptr < (mDNSu8*)msg || ptr >= end)
3076 { debugf("getDomainName: Illegal compression pointer not within packet boundaries"); return(mDNSNULL); }
3077 if (*ptr & 0xC0)
3078 { debugf("getDomainName: Compression pointer must point to real label"); return(mDNSNULL); }
3079 break;
3080 }
3081 }
3082
3083 if (nextbyte) return(nextbyte);
3084 else return(ptr);
3085 }
3086
3087 mDNSlocal const mDNSu8 *skipResourceRecord(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end)
3088 {
3089 mDNSu16 pktrdlength;
3090
3091 ptr = skipDomainName(msg, ptr, end);
3092 if (!ptr) { debugf("skipResourceRecord: Malformed RR name"); return(mDNSNULL); }
3093
3094 if (ptr + 10 > end) { debugf("skipResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL); }
3095 pktrdlength = (mDNSu16)((mDNSu16)ptr[8] << 8 | ptr[9]);
3096 ptr += 10;
3097 if (ptr + pktrdlength > end) { debugf("skipResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL); }
3098
3099 return(ptr + pktrdlength);
3100 }
3101
3102 #define GetLargeResourceRecord(m, msg, p, e, i, t, L) \
3103 (((L)->r.rdatastorage.MaxRDLength = MaximumRDSize), GetResourceRecord((m), (msg), (p), (e), (i), (t), &(L)->r, (RData*)&(L)->r.rdatastorage))
3104
3105 mDNSlocal const mDNSu8 *GetResourceRecord(mDNS *const m, const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end,
3106 const mDNSInterfaceID InterfaceID, mDNSu8 RecordType, CacheRecord *rr, RData *RDataStorage)
3107 {
3108 mDNSu16 pktrdlength;
3109
3110 rr->next = mDNSNULL;
3111 rr->resrec.RecordType = RecordType;
3112
3113 rr->NextInKAList = mDNSNULL;
3114 rr->TimeRcvd = m->timenow;
3115 rr->NextRequiredQuery = m->timenow; // Will be updated to the real value when we call SetNextCacheCheckTime()
3116 rr->LastUsed = m->timenow;
3117 rr->UseCount = 0;
3118 rr->CRActiveQuestion = mDNSNULL;
3119 rr->UnansweredQueries = 0;
3120 rr->LastUnansweredTime= 0;
3121 rr->MPUnansweredQ = 0;
3122 rr->MPLastUnansweredQT= 0;
3123 rr->MPUnansweredKA = 0;
3124 rr->MPExpectingKA = mDNSfalse;
3125 rr->NextInCFList = mDNSNULL;
3126
3127 rr->resrec.InterfaceID = InterfaceID;
3128 ptr = getDomainName(msg, ptr, end, &rr->resrec.name);
3129 if (!ptr) { debugf("GetResourceRecord: Malformed RR name"); return(mDNSNULL); }
3130
3131 if (ptr + 10 > end) { debugf("GetResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL); }
3132
3133 rr->resrec.rrtype = (mDNSu16) ((mDNSu16)ptr[0] << 8 | ptr[1]);
3134 rr->resrec.rrclass = (mDNSu16)(((mDNSu16)ptr[2] << 8 | ptr[3]) & kDNSClass_Mask);
3135 rr->resrec.rroriginalttl = (mDNSu32) ((mDNSu32)ptr[4] << 24 | (mDNSu32)ptr[5] << 16 | (mDNSu32)ptr[6] << 8 | ptr[7]);
3136 if (rr->resrec.rroriginalttl > 0x70000000UL / mDNSPlatformOneSecond)
3137 rr->resrec.rroriginalttl = 0x70000000UL / mDNSPlatformOneSecond;
3138 // Note: We don't have to adjust m->NextCacheCheck here -- this is just getting a record into memory for
3139 // us to look at. If we decide to copy it into the cache, then we'll update m->NextCacheCheck accordingly.
3140 pktrdlength = (mDNSu16)((mDNSu16)ptr[8] << 8 | ptr[9]);
3141 if (ptr[2] & (kDNSClass_UniqueRRSet >> 8))
3142 rr->resrec.RecordType |= kDNSRecordTypePacketUniqueMask;
3143 ptr += 10;
3144 if (ptr + pktrdlength > end) { debugf("GetResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL); }
3145
3146 if (RDataStorage)
3147 rr->resrec.rdata = RDataStorage;
3148 else
3149 {
3150 rr->resrec.rdata = (RData*)&rr->rdatastorage;
3151 rr->resrec.rdata->MaxRDLength = sizeof(RDataBody);
3152 }
3153
3154 switch (rr->resrec.rrtype)
3155 {
3156 case kDNSType_A: rr->resrec.rdata->u.ip.b[0] = ptr[0];
3157 rr->resrec.rdata->u.ip.b[1] = ptr[1];
3158 rr->resrec.rdata->u.ip.b[2] = ptr[2];
3159 rr->resrec.rdata->u.ip.b[3] = ptr[3];
3160 break;
3161
3162 case kDNSType_CNAME:// Same as PTR
3163 case kDNSType_PTR: if (!getDomainName(msg, ptr, end, &rr->resrec.rdata->u.name))
3164 { debugf("GetResourceRecord: Malformed CNAME/PTR RDATA name"); return(mDNSNULL); }
3165 //debugf("%##s PTR %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.name.c, pktrdlength);
3166 break;
3167
3168 case kDNSType_NULL: //Same as TXT
3169 case kDNSType_HINFO://Same as TXT
3170 case kDNSType_TXT: if (pktrdlength > rr->resrec.rdata->MaxRDLength)
3171 {
3172 debugf("GetResourceRecord: %s rdata size (%d) exceeds storage (%d)",
3173 DNSTypeName(rr->resrec.rrtype), pktrdlength, rr->resrec.rdata->MaxRDLength);
3174 return(mDNSNULL);
3175 }
3176 rr->resrec.rdlength = pktrdlength;
3177 mDNSPlatformMemCopy(ptr, rr->resrec.rdata->u.data, pktrdlength);
3178 break;
3179
3180 case kDNSType_AAAA: mDNSPlatformMemCopy(ptr, &rr->resrec.rdata->u.ipv6, sizeof(rr->resrec.rdata->u.ipv6));
3181 break;
3182
3183 case kDNSType_SRV: rr->resrec.rdata->u.srv.priority = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
3184 rr->resrec.rdata->u.srv.weight = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
3185 rr->resrec.rdata->u.srv.port.b[0] = ptr[4];
3186 rr->resrec.rdata->u.srv.port.b[1] = ptr[5];
3187 if (!getDomainName(msg, ptr+6, end, &rr->resrec.rdata->u.srv.target))
3188 { debugf("GetResourceRecord: Malformed SRV RDATA name"); return(mDNSNULL); }
3189 //debugf("%##s SRV %##s rdlen %d", rr->resrec.name.c, rr->resrec.rdata->u.srv.target.c, pktrdlength);
3190 break;
3191
3192 default: if (pktrdlength > rr->resrec.rdata->MaxRDLength)
3193 {
3194 debugf("GetResourceRecord: rdata %d (%s) size (%d) exceeds storage (%d)",
3195 rr->resrec.rrtype, DNSTypeName(rr->resrec.rrtype), pktrdlength, rr->resrec.rdata->MaxRDLength);
3196 return(mDNSNULL);
3197 }
3198 debugf("GetResourceRecord: Warning! Reading resource type %d (%s) as opaque data",
3199 rr->resrec.rrtype, DNSTypeName(rr->resrec.rrtype));
3200 // Note: Just because we don't understand the record type, that doesn't
3201 // mean we fail. The DNS protocol specifies rdlength, so we can
3202 // safely skip over unknown records and ignore them.
3203 // We also grab a binary copy of the rdata anyway, since the caller
3204 // might know how to interpret it even if we don't.
3205 rr->resrec.rdlength = pktrdlength;
3206 mDNSPlatformMemCopy(ptr, rr->resrec.rdata->u.data, pktrdlength);
3207 break;
3208 }
3209
3210 rr->resrec.namehash = DomainNameHashValue(&rr->resrec.name);
3211 SetNewRData(&rr->resrec, mDNSNULL, 0);
3212
3213 return(ptr + pktrdlength);
3214 }
3215
3216 mDNSlocal const mDNSu8 *skipQuestion(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end)
3217 {
3218 ptr = skipDomainName(msg, ptr, end);
3219 if (!ptr) { debugf("skipQuestion: Malformed domain name in DNS question section"); return(mDNSNULL); }
3220 if (ptr+4 > end) { debugf("skipQuestion: Malformed DNS question section -- no query type and class!"); return(mDNSNULL); }
3221 return(ptr+4);
3222 }
3223
3224 mDNSlocal const mDNSu8 *getQuestion(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end, const mDNSInterfaceID InterfaceID,
3225 DNSQuestion *question)
3226 {
3227 question->InterfaceID = InterfaceID;
3228 ptr = getDomainName(msg, ptr, end, &question->qname);
3229 if (!ptr) { debugf("Malformed domain name in DNS question section"); return(mDNSNULL); }
3230 if (ptr+4 > end) { debugf("Malformed DNS question section -- no query type and class!"); return(mDNSNULL); }
3231
3232 question->qnamehash = DomainNameHashValue(&question->qname);
3233 question->qtype = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]); // Get type
3234 question->qclass = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]); // and class
3235 return(ptr+4);
3236 }
3237
3238 mDNSlocal const mDNSu8 *LocateAnswers(const DNSMessage *const msg, const mDNSu8 *const end)
3239 {
3240 int i;
3241 const mDNSu8 *ptr = msg->data;
3242 for (i = 0; i < msg->h.numQuestions && ptr; i++) ptr = skipQuestion(msg, ptr, end);
3243 return(ptr);
3244 }
3245
3246 mDNSlocal const mDNSu8 *LocateAuthorities(const DNSMessage *const msg, const mDNSu8 *const end)
3247 {
3248 int i;
3249 const mDNSu8 *ptr = LocateAnswers(msg, end);
3250 for (i = 0; i < msg->h.numAnswers && ptr; i++) ptr = skipResourceRecord(msg, ptr, end);
3251 return(ptr);
3252 }
3253
3254 // ***************************************************************************
3255 #if COMPILER_LIKES_PRAGMA_MARK
3256 #pragma mark -
3257 #pragma mark -
3258 #pragma mark - Packet Sending Functions
3259 #endif
3260
3261 mDNSlocal mStatus mDNSSendDNSMessage(const mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
3262 mDNSInterfaceID InterfaceID, mDNSIPPort srcport, const mDNSAddr *dst, mDNSIPPort dstport)
3263 {
3264 mStatus status;
3265 mDNSu16 numQuestions = msg->h.numQuestions;
3266 mDNSu16 numAnswers = msg->h.numAnswers;
3267 mDNSu16 numAuthorities = msg->h.numAuthorities;
3268 mDNSu16 numAdditionals = msg->h.numAdditionals;
3269
3270 // Put all the integer values in IETF byte-order (MSB first, LSB second)
3271 mDNSu8 *ptr = (mDNSu8 *)&msg->h.numQuestions;
3272 *ptr++ = (mDNSu8)(numQuestions >> 8);
3273 *ptr++ = (mDNSu8)(numQuestions );
3274 *ptr++ = (mDNSu8)(numAnswers >> 8);
3275 *ptr++ = (mDNSu8)(numAnswers );
3276 *ptr++ = (mDNSu8)(numAuthorities >> 8);
3277 *ptr++ = (mDNSu8)(numAuthorities );
3278 *ptr++ = (mDNSu8)(numAdditionals >> 8);
3279 *ptr++ = (mDNSu8)(numAdditionals );
3280
3281 // Send the packet on the wire
3282 status = mDNSPlatformSendUDP(m, msg, end, InterfaceID, srcport, dst, dstport);
3283
3284 // Put all the integer values back the way they were before we return
3285 msg->h.numQuestions = numQuestions;
3286 msg->h.numAnswers = numAnswers;
3287 msg->h.numAuthorities = numAuthorities;
3288 msg->h.numAdditionals = numAdditionals;
3289
3290 return(status);
3291 }
3292
3293 mDNSlocal void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
3294 {
3295 // Setting AnnounceCount to InitialAnnounceCount signals mDNS_Deregister_internal()
3296 // that it should go ahead and immediately dispose of this registration
3297 rr->resrec.RecordType = kDNSRecordTypeShared;
3298 rr->AnnounceCount = InitialAnnounceCount;
3299 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
3300 }
3301
3302 // NOTE: DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback, which may change
3303 // the record list and/or question list.
3304 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3305 mDNSlocal void DiscardDeregistrations(mDNS *const m)
3306 {
3307 if (m->CurrentRecord) LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set");
3308 m->CurrentRecord = m->ResourceRecords;
3309
3310 while (m->CurrentRecord)
3311 {
3312 AuthRecord *rr = m->CurrentRecord;
3313 m->CurrentRecord = rr->next;
3314 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3315 CompleteDeregistration(m, rr);
3316 }
3317 }
3318
3319 mDNSlocal mDNSBool HaveSentEntireRRSet(const mDNS *const m, const AuthRecord *const rr, mDNSInterfaceID InterfaceID)
3320 {
3321 // Try to find another member of this set that we're still planning to send on this interface
3322 const AuthRecord *a;
3323 for (a = m->ResourceRecords; a; a=a->next)
3324 if (a->SendRNow == InterfaceID && a != rr && SameResourceRecordSignature(&a->resrec, &rr->resrec)) break;
3325 return (a == mDNSNULL); // If no more members of this set found, then we should set the cache flush bit
3326 }
3327
3328 // Note about acceleration of announcements to facilitate automatic coalescing of
3329 // multiple independent threads of announcements into a single synchronized thread:
3330 // The announcements in the packet may be at different stages of maturity;
3331 // One-second interval, two-second interval, four-second interval, and so on.
3332 // After we've put in all the announcements that are due, we then consider
3333 // whether there are other nearly-due announcements that are worth accelerating.
3334 // To be eligible for acceleration, a record MUST NOT be older (further along
3335 // its timeline) than the most mature record we've already put in the packet.
3336 // In other words, younger records can have their timelines accelerated to catch up
3337 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
3338 // Older records cannot have their timelines accelerated; this would just widen
3339 // the gap between them and their younger bretheren and get them even more out of sync.
3340
3341 // NOTE: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
3342 // the record list and/or question list.
3343 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3344 mDNSlocal void SendResponses(mDNS *const m)
3345 {
3346 int pktcount = 0;
3347 AuthRecord *rr, *r2;
3348 mDNSs32 maxExistingAnnounceInterval = 0;
3349 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3350
3351 m->NextScheduledResponse = m->timenow + 0x78000000;
3352
3353 // ***
3354 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
3355 // ***
3356
3357 // Run through our list of records, and decide which ones we're going to announce on all interfaces
3358 for (rr = m->ResourceRecords; rr; rr=rr->next)
3359 {
3360 if (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0)
3361 {
3362 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
3363 else rr->NextUpdateCredit = (m->timenow + mDNSPlatformOneSecond * 60) | 1;
3364 }
3365 if (TimeToAnnounceThisRecord(rr, m->timenow) && ResourceRecordIsValidAnswer(rr))
3366 {
3367 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
3368 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
3369 maxExistingAnnounceInterval = rr->ThisAPInterval;
3370 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
3371 }
3372 }
3373
3374 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
3375 // Eligible records that are more than half-way to their announcement time are accelerated
3376 for (rr = m->ResourceRecords; rr; rr=rr->next)
3377 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
3378 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
3379 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
3380 ResourceRecordIsValidAnswer(rr)))
3381 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
3382
3383 // When sending SRV records (particularly when announcing a new service) automatically add the related Address record(s)
3384 for (rr = m->ResourceRecords; rr; rr=rr->next)
3385 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
3386 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
3387 if (RRIsAddressType(r2) && // For all address records (A/AAAA) ...
3388 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
3389 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
3390 rr->resrec.rdnamehash == r2->resrec.namehash && // ... whose name is the name of the SRV target
3391 SameDomainName(&rr->resrec.rdata->u.srv.target, &r2->resrec.name) &&
3392 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
3393 r2->ImmedAnswer = mDNSInterfaceMark; // ... then mark this address record for sending too
3394
3395 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
3396 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
3397 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
3398 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
3399 // -- 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
3400 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
3401 for (rr = m->ResourceRecords; rr; rr=rr->next)
3402 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
3403 {
3404 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
3405 {
3406 for (r2 = m->ResourceRecords; r2; r2=r2->next)
3407 if (ResourceRecordIsValidAnswer(r2))
3408 if (r2->ImmedAnswer != mDNSInterfaceMark && r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(&r2->resrec, &rr->resrec))
3409 r2->ImmedAnswer = rr->ImmedAnswer;
3410 }
3411 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
3412 {
3413 for (r2 = m->ResourceRecords; r2; r2=r2->next)
3414 if (ResourceRecordIsValidAnswer(r2))
3415 if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(&r2->resrec, &rr->resrec))
3416 r2->ImmedAdditional = rr->ImmedAdditional;
3417 }
3418 }
3419
3420 // Now set SendRNow state appropriately
3421 for (rr = m->ResourceRecords; rr; rr=rr->next)
3422 {
3423 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
3424 {
3425 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
3426 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
3427 rr->LastMCTime = m->timenow;
3428 rr->LastMCInterface = rr->ImmedAnswer;
3429 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
3430 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
3431 {
3432 rr->AnnounceCount--;
3433 rr->ThisAPInterval *= 2;
3434 rr->LastAPTime = m->timenow;
3435 if (rr->LastAPTime + rr->ThisAPInterval - rr->AnnounceUntil >= 0) rr->AnnounceCount = 0;
3436 debugf("Announcing %##s (%s) %d", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
3437 }
3438 }
3439 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
3440 {
3441 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
3442 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
3443 rr->LastMCTime = m->timenow;
3444 rr->LastMCInterface = rr->ImmedAnswer;
3445 }
3446 SetNextAnnounceProbeTime(m, rr);
3447 }
3448
3449 // ***
3450 // *** 2. Loop through interface list, sending records as appropriate
3451 // ***
3452
3453 while (intf)
3454 {
3455 int numDereg = 0;
3456 int numAnnounce = 0;
3457 int numAnswer = 0;
3458 DNSMessage response;
3459 mDNSu8 *responseptr = response.data;
3460 mDNSu8 *newptr;
3461 InitializeDNSMessage(&response.h, zeroID, ResponseFlags);
3462
3463 // First Pass. Look for:
3464 // 1. Deregistering records that need to send their goodbye packet
3465 // 2. Updated records that need to retract their old data
3466 // 3. Answers and announcements we need to send
3467 // In all cases, if we fail, and we've put at least one answer, we break out of the for loop so we can
3468 // send this packet and then try again.
3469 // If we have not put even one answer, then we don't bail out. We pretend we succeeded anyway,
3470 // because otherwise we'll end up in an infinite loop trying to send a record that will never fit.
3471 for (rr = m->ResourceRecords; rr; rr=rr->next)
3472 if (rr->SendRNow == intf->InterfaceID)
3473 {
3474 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3475 {
3476 newptr = PutResourceRecordTTL(&response, responseptr, &response.h.numAnswers, &rr->resrec, 0);
3477 if (!newptr && response.h.numAnswers) break;
3478 numDereg++;
3479 responseptr = newptr;
3480 }
3481 else if (rr->NewRData) // If we have new data for this record
3482 {
3483 RData *OldRData = rr->resrec.rdata;
3484 mDNSu16 oldrdlength = rr->resrec.rdlength;
3485 // See if we should send a courtesy "goodbye" the old data before we replace it.
3486 // We compare with "InitialAnnounceCount-1" instead of "InitialAnnounceCount" because by the time
3487 // we get to this place in this routine we've we've already decremented rr->AnnounceCount
3488 if (ResourceRecordIsValidAnswer(rr) && rr->AnnounceCount < InitialAnnounceCount-1)
3489 {
3490 newptr = PutResourceRecordTTL(&response, responseptr, &response.h.numAnswers, &rr->resrec, 0);
3491 if (!newptr && response.h.numAnswers) break;
3492 numDereg++;
3493 responseptr = newptr;
3494 }
3495 // Now try to see if we can fit the update in the same packet (not fatal if we can't)
3496 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
3497 if ((rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && HaveSentEntireRRSet(m, rr, intf->InterfaceID))
3498 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
3499 newptr = PutResourceRecord(&response, responseptr, &response.h.numAnswers, &rr->resrec);
3500 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
3501 if (newptr) responseptr = newptr;
3502 SetNewRData(&rr->resrec, OldRData, oldrdlength);
3503 }
3504 else
3505 {
3506 if ((rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && HaveSentEntireRRSet(m, rr, intf->InterfaceID))
3507 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
3508 newptr = PutResourceRecordTTL(&response, responseptr, &response.h.numAnswers, &rr->resrec, m->SleepState ? 0 : rr->resrec.rroriginalttl);
3509 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
3510 if (!newptr && response.h.numAnswers) break;
3511 if (rr->LastAPTime == m->timenow) numAnnounce++; else numAnswer++;
3512 responseptr = newptr;
3513 }
3514 // If sending on all interfaces, go to next interface; else we're finished now
3515 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
3516 rr->SendRNow = GetNextActiveInterfaceID(intf);
3517 else
3518 rr->SendRNow = mDNSNULL;
3519 }
3520
3521 // Second Pass. Add additional records, if there's space.
3522 newptr = responseptr;
3523 for (rr = m->ResourceRecords; rr; rr=rr->next)
3524 if (rr->ImmedAdditional == intf->InterfaceID)
3525 {
3526 // Since additionals are optional, we clear ImmedAdditional anyway, even if we subsequently find it doesn't fit in the packet
3527 rr->ImmedAdditional = mDNSNULL;
3528 if (newptr && ResourceRecordIsValidAnswer(rr))
3529 {
3530 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
3531 {
3532 // Try to find another member of this set that we're still planning to send on this interface
3533 const AuthRecord *a;
3534 for (a = m->ResourceRecords; a; a=a->next)
3535 if (a->ImmedAdditional == intf->InterfaceID && SameResourceRecordSignature(&a->resrec, &rr->resrec)) break;
3536 if (a == mDNSNULL) // If no more members of this set found
3537 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
3538 }
3539 newptr = PutResourceRecord(&response, newptr, &response.h.numAdditionals, &rr->resrec);
3540 if (newptr) responseptr = newptr;
3541 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
3542 }
3543 }
3544
3545 if (response.h.numAnswers > 0) // We *never* send a packet with only additionals in it
3546 {
3547 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3548 numDereg, numDereg == 1 ? "" : "s",
3549 numAnnounce, numAnnounce == 1 ? "" : "s",
3550 numAnswer, numAnswer == 1 ? "" : "s",
3551 response.h.numAdditionals, response.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
3552 mDNSSendDNSMessage(m, &response, responseptr, intf->InterfaceID, MulticastDNSPort, &AllDNSLinkGroup_v4, MulticastDNSPort);
3553 mDNSSendDNSMessage(m, &response, responseptr, intf->InterfaceID, MulticastDNSPort, &AllDNSLinkGroup_v6, MulticastDNSPort);
3554 if (!m->SuppressSending) m->SuppressSending = (m->timenow + mDNSPlatformOneSecond/10) | 1; // OR with one to ensure non-zero
3555 if (++pktcount >= 1000)
3556 { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
3557 // There might be more things to send on this interface, so go around one more time and try again.
3558 }
3559 else // Nothing more to send on this interface; go to next
3560 {
3561 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3562 #if MDNS_DEBUGMSGS && 0
3563 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3564 debugf(msg, intf, next);
3565 #endif
3566 intf = next;
3567 }
3568 }
3569
3570 // ***
3571 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3572 // ***
3573
3574 if (m->CurrentRecord) LogMsg("SendResponses: ERROR m->CurrentRecord already set");
3575 m->CurrentRecord = m->ResourceRecords;
3576 while (m->CurrentRecord)
3577 {
3578 rr = m->CurrentRecord;
3579 m->CurrentRecord = rr->next;
3580
3581 if (rr->NewRData)
3582 {
3583 RData *OldRData = rr->resrec.rdata;
3584 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
3585 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
3586 if (rr->UpdateCallback)
3587 rr->UpdateCallback(m, rr, OldRData); // ... and let the client know
3588 }
3589
3590 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3591 CompleteDeregistration(m, rr);
3592 else
3593 {
3594 rr->ImmedAnswer = mDNSNULL;
3595 rr->v4Requester = zeroIPAddr;
3596 rr->v6Requester = zerov6Addr;
3597 }
3598 }
3599 verbosedebugf("SendResponses: Next in %d ticks", m->NextScheduledResponse - m->timenow);
3600 }
3601
3602 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3603 // so we want to be lazy about how frequently we do it.
3604 // 1. If a cache record is currently referenced by *no* active questions,
3605 // then we don't mind expiring it up to a minute late (who will know?)
3606 // 2. Else, if a cache record is due for some of its final expiration queries,
3607 // we'll allow them to be late by up to 2% of the TTL
3608 // 3. Else, if a cache record has completed all its final expiration queries without success,
3609 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3610 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3611 // so allow at most 1/10 second lateness
3612 #define CacheCheckGracePeriod(RR) ( \
3613 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3614 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
3615 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : (mDNSPlatformOneSecond/10))
3616
3617 // Note: MUST call SetNextCacheCheckTime any time we change:
3618 // rr->TimeRcvd
3619 // rr->resrec.rroriginalttl
3620 // rr->UnansweredQueries
3621 // rr->CRActiveQuestion
3622 mDNSlocal void SetNextCacheCheckTime(mDNS *const m, CacheRecord *const rr)
3623 {
3624 rr->NextRequiredQuery = RRExpireTime(rr);
3625
3626 // If we have an active question, then see if we want to schedule a refresher query for this record.
3627 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3628 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3629 {
3630 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
3631 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
3632 verbosedebugf("SetNextCacheCheckTime: %##s (%s) NextRequiredQuery in %ld sec",
3633 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond);
3634 }
3635
3636 if (m->NextCacheCheck - (rr->NextRequiredQuery + CacheCheckGracePeriod(rr)) > 0)
3637 m->NextCacheCheck = (rr->NextRequiredQuery + CacheCheckGracePeriod(rr));
3638 }
3639
3640 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 45)
3641 #define kDefaultReconfirmTimeForCableDisconnect ((mDNSu32)mDNSPlatformOneSecond * 5)
3642 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3643
3644 mDNSlocal mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
3645 {
3646 if (interval < kMinimumReconfirmTime)
3647 interval = kMinimumReconfirmTime;
3648 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3649 interval = 0x10000000;
3650
3651 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3652 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
3653 {
3654 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3655 interval += mDNSRandom(interval/3);
3656 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
3657 rr->resrec.rroriginalttl = interval * 4 / mDNSPlatformOneSecond;
3658 SetNextCacheCheckTime(m, rr);
3659 }
3660 debugf("mDNS_Reconfirm_internal:%5ld ticks to go for %s", RRExpireTime(rr) - m->timenow, GetRRDisplayString(m, rr));
3661 return(mStatus_NoError);
3662 }
3663
3664 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
3665
3666 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3667 // It also appends to the list of known answer records that need to be included,
3668 // and updates the forcast for the size of the known answer section.
3669 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
3670 CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
3671 {
3672 mDNSBool ucast = q->LargeAnswers || q->ThisQInterval <= InitialQuestionInterval*2;
3673 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3674 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
3675 mDNSu8 *newptr = putQuestion(query, *queryptr, limit, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
3676 if (!newptr)
3677 {
3678 debugf("BuildQuestion: No more space in this packet for question %##s", q->qname.c);
3679 return(mDNSfalse);
3680 }
3681 else if (newptr + *answerforecast >= limit)
3682 {
3683 verbosedebugf("BuildQuestion: Retracting question %##s new forecast total %d", q->qname.c, newptr + *answerforecast - query->data);
3684 query->h.numQuestions--;
3685 return(mDNSfalse);
3686 }
3687 else
3688 {
3689 mDNSu32 forecast = *answerforecast;
3690 CacheRecord *rr;
3691 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
3692
3693 for (rr=m->rrcache_hash[HashSlot(&q->qname)]; rr; rr=rr->next) // If we have a resource record in our cache,
3694 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
3695 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not already in the known answer list
3696 rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3697 ResourceRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
3698 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
3699 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0)// and we'll ask at least once again before NextRequiredQuery
3700 {
3701 *ka = rr; // Link this record into our known answer chain
3702 ka = &rr->NextInKAList;
3703 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3704 forecast += 12 + rr->resrec.rdestimate;
3705 // If we're trying to put more than one question in this packet, and it doesn't fit
3706 // then undo that last question and try again next time
3707 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3708 {
3709 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
3710 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data);
3711 query->h.numQuestions--;
3712 ka = *kalistptrptr; // Go back to where we started and retract these answer records
3713 while (*ka) { CacheRecord *rr = *ka; *ka = mDNSNULL; ka = &rr->NextInKAList; }
3714 return(mDNSfalse); // Return false, so we'll try again in the next packet
3715 }
3716 }
3717
3718 // Traffic reduction:
3719 // If we already have at least one unique answer in the cache,
3720 // OR we have so many shared answers that the KA list is too big to fit in one packet
3721 // The we suppress queries number 3 and 5:
3722 // Query 1 (immediately; ThisQInterval = 1 sec; request unicast replies)
3723 // Query 2 (after 1 second; ThisQInterval = 2 sec; send normally)
3724 // Query 3 (after 2 seconds; ThisQInterval = 4 sec; may suppress)
3725 // Query 4 (after 4 seconds; ThisQInterval = 8 sec; send normally)
3726 // Query 5 (after 8 seconds; ThisQInterval = 16 sec; may suppress)
3727 // Query 6 (after 16 seconds; ThisQInterval = 32 sec; send normally)
3728 if (q->UniqueAnswers || newptr + forecast >= limit)
3729 if (q->ThisQInterval == InitialQuestionInterval * 8 || q->ThisQInterval == InitialQuestionInterval * 32)
3730 {
3731 query->h.numQuestions--;
3732 ka = *kalistptrptr; // Go back to where we started and retract these answer records
3733 while (*ka) { CacheRecord *rr = *ka; *ka = mDNSNULL; ka = &rr->NextInKAList; }
3734 return(mDNStrue); // Return true: pretend we succeeded, even though we actually suppressed this question
3735 }
3736
3737 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3738 *queryptr = newptr; // Update the packet pointer
3739 *answerforecast = forecast; // Update the forecast
3740 *kalistptrptr = ka; // Update the known answer list pointer
3741 if (ucast) m->ExpectUnicastResponse = m->timenow;
3742
3743 for (rr=m->rrcache_hash[HashSlot(&q->qname)]; rr; rr=rr->next) // For every resource record in our cache,
3744 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
3745 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not in the known answer list
3746 ResourceRecordAnswersQuestion(&rr->resrec, q)) // which answers our question
3747 {
3748 rr->UnansweredQueries++; // indicate that we're expecting a response
3749 rr->LastUnansweredTime = m->timenow;
3750 SetNextCacheCheckTime(m, rr);
3751 }
3752
3753 return(mDNStrue);
3754 }
3755 }
3756
3757 mDNSlocal void ReconfirmAntecedents(mDNS *const m, DNSQuestion *q)
3758 {
3759 mDNSu32 slot;
3760 CacheRecord *rr;
3761 domainname *target;
3762 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
3763 for (rr = m->rrcache_hash[slot]; rr; rr=rr->next)
3764 if ((target = GetRRDomainNameTarget(&rr->resrec)) && rr->resrec.rdnamehash == q->qnamehash && SameDomainName(target, &q->qname))
3765 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForNoAnswer);
3766 }
3767
3768 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3769 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3770 {
3771 int i;
3772 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3773 }
3774
3775 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3776 {
3777 int i;
3778 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3779 }
3780
3781 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3782 {
3783 int i;
3784 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3785 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3786 for (i=0; i<DupSuppressInfoSize; i++)
3787 if (ds[i].InterfaceID == intf->InterfaceID)
3788 {
3789 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3790 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3791 if (v4 && v6) return(mDNStrue);
3792 }
3793 return(mDNSfalse);
3794 }
3795
3796 mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3797 {
3798 int i, j;
3799
3800 // See if we have this one in our list somewhere already
3801 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3802
3803 // If not, find a slot we can re-use
3804 if (i >= DupSuppressInfoSize)
3805 {
3806 i = 0;
3807 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3808 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3809 i = j;
3810 }
3811
3812 // Record the info about this query we saw
3813 ds[i].Time = Time;
3814 ds[i].InterfaceID = InterfaceID;
3815 ds[i].Type = Type;
3816
3817 return(i);
3818 }
3819
3820 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3821 {
3822 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3823 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3824 return(mDNStrue);
3825
3826 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3827 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3828 {
3829 // We forecast: qname (n) type (2) class (2)
3830 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3831 CacheRecord *rr;
3832 for (rr=m->rrcache_hash[HashSlot(&q->qname)]; rr; rr=rr->next) // If we have a resource record in our cache,
3833 if (rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3834 ResourceRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
3835 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
3836 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0)// and we'll ask at least once again before NextRequiredQuery
3837 {
3838 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3839 forecast += 12 + rr->resrec.rdestimate;
3840 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3841 }
3842 return(mDNStrue);
3843 }
3844
3845 return(mDNSfalse);
3846 }
3847
3848 // How Standard Queries are generated:
3849 // 1. The Question Section contains the question
3850 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3851
3852 // How Probe Queries are generated:
3853 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3854 // if some other host is already using *any* records with this name, we want to know about it.
3855 // 2. The Authority Section contains the proposed values we intend to use for one or more
3856 // of our records with that name (analogous to the Update section of DNS Update packets)
3857 // because if some other host is probing at the same time, we each want to know what the other is
3858 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3859
3860 mDNSlocal void SendQueries(mDNS *const m)
3861 {
3862 int pktcount = 0;
3863 DNSQuestion *q;
3864 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3865 mDNSs32 maxExistingQuestionInterval = 0;
3866 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3867 CacheRecord *KnownAnswerList = mDNSNULL;
3868
3869 // 1. If time for a query, work out what we need to do
3870 if (m->timenow - m->NextScheduledQuery >= 0)
3871 {
3872 mDNSu32 slot;
3873 CacheRecord *rr;
3874 m->NextScheduledQuery = m->timenow + 0x78000000;
3875
3876 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3877 // to their NextRequiredQuery to be worth batching them together with this one
3878 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
3879 for (rr = m->rrcache_hash[slot]; rr; rr=rr->next)
3880 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3881 if (m->timenow + TicksTTL(rr)/50 - rr->NextRequiredQuery >= 0)
3882 {
3883 q = rr->CRActiveQuestion;
3884 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(rr)/20, rr->resrec.InterfaceID);
3885 if (q->SendQNow == mDNSNULL) q->SendQNow = rr->resrec.InterfaceID;
3886 else if (q->SendQNow != rr->resrec.InterfaceID) q->SendQNow = mDNSInterfaceMark;
3887 }
3888
3889 // Scan our list of questions to see which ones we're definitely going to send
3890 for (q = m->Questions; q; q=q->next)
3891 if (TimeToSendThisQuestion(q, m->timenow))
3892 {
3893 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3894 if (maxExistingQuestionInterval < q->ThisQInterval)
3895 maxExistingQuestionInterval = q->ThisQInterval;
3896 }
3897
3898 // Scan our list of questions
3899 // (a) to see if there are any more that are worth accelerating, and
3900 // (b) to update the state variables for all the questions we're going to send
3901 for (q = m->Questions; q; q=q->next)
3902 {
3903 if (q->SendQNow || (ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q)))
3904 {
3905 // If at least halfway to next query time, advance to next interval
3906 // If less than halfway to next query time, treat this as logically a repeat of the last transmission, without advancing the interval
3907 if (m->timenow - (q->LastQTime + q->ThisQInterval/2) >= 0)
3908 {
3909 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3910 q->ThisQInterval *= 2;
3911 if (q->ThisQInterval > MaxQuestionInterval)
3912 q->ThisQInterval = MaxQuestionInterval;
3913 else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * 8)
3914 {
3915 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents", q->qname.c, DNSTypeName(q->qtype));
3916 ReconfirmAntecedents(m, q); // If sending third query, and no answers yet, time to begin doubting the source
3917 }
3918 }
3919
3920 // Mark for sending. (If no active interfaces, then don't even try.)
3921 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3922 if (q->SendOnAll)
3923 {
3924 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3925 q->LastQTime = m->timenow;
3926 }
3927
3928 // If we recorded a duplicate suppression for this question less than half an interval ago,
3929 // then we consider it recent enough that we don't need to do an identical query ourselves.
3930 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3931
3932 q->LastQTxTime = m->timenow;
3933 q->RecentAnswers = 0;
3934 }
3935 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3936 SetNextQueryTime(m,q);
3937 }
3938 }
3939
3940 // 2. Scan our authoritative RR list to see what probes we might need to send
3941 if (m->timenow - m->NextScheduledProbe >= 0)
3942 {
3943 m->NextScheduledProbe = m->timenow + 0x78000000;
3944
3945 if (m->CurrentRecord) LogMsg("SendQueries: ERROR m->CurrentRecord already set");
3946 m->CurrentRecord = m->ResourceRecords;
3947 while (m->CurrentRecord)
3948 {
3949 AuthRecord *rr = m->CurrentRecord;
3950 m->CurrentRecord = rr->next;
3951 if (rr->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
3952 {
3953 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3954 if (m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
3955 {
3956 SetNextAnnounceProbeTime(m, rr);
3957 }
3958 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3959 else if (rr->ProbeCount)
3960 {
3961 // Mark for sending. (If no active interfaces, then don't even try.)
3962 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
3963 rr->LastAPTime = m->timenow;
3964 rr->ProbeCount--;
3965 SetNextAnnounceProbeTime(m, rr);
3966 }
3967 // else, if it has now finished probing, move it to state Verified, and update m->NextScheduledResponse so it will be announced
3968 else
3969 {
3970 AuthRecord *r2;
3971 rr->resrec.RecordType = kDNSRecordTypeVerified;
3972 rr->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3973 rr->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3974 SetNextAnnounceProbeTime(m, rr);
3975 // If we have any records on our duplicate list that match this one, they have now also completed probing
3976 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3977 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, rr))
3978 r2->ProbeCount = 0;
3979 CompleteProbing(m, rr);
3980 }
3981 }
3982 }
3983 m->CurrentRecord = m->DuplicateRecords;
3984 while (m->CurrentRecord)
3985 {
3986 AuthRecord *rr = m->CurrentRecord;
3987 m->CurrentRecord = rr->next;
3988 if (rr->resrec.RecordType == kDNSRecordTypeUnique && rr->ProbeCount == 0)
3989 CompleteProbing(m, rr);
3990 }
3991 }
3992
3993 // 3. Now we know which queries and probes we're sending, go through our interface list sending the appropriate queries on each interface
3994 while (intf)
3995 {
3996 AuthRecord *rr;
3997 DNSMessage query;
3998 mDNSu8 *queryptr = query.data;
3999 InitializeDNSMessage(&query.h, zeroID, QueryFlags);
4000 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
4001 if (!KnownAnswerList)
4002 {
4003 // Start a new known-answer list
4004 CacheRecord **kalistptr = &KnownAnswerList;
4005 mDNSu32 answerforecast = 0;
4006
4007 // Put query questions in this packet
4008 for (q = m->Questions; q; q=q->next)
4009 if (q->SendQNow == intf->InterfaceID)
4010 {
4011 debugf("SendQueries: %s question for %##s (%s) at %lu forecast total %lu",
4012 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
4013 q->qname.c, DNSTypeName(q->qtype), queryptr - query.data, queryptr + answerforecast - query.data);
4014 // If we're suppressing this question, or we successfully put it, update its SendQNow state
4015 if (SuppressOnThisInterface(q->DupSuppress, intf) ||
4016 BuildQuestion(m, &query, &queryptr, q, &kalistptr, &answerforecast))
4017 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
4018 }
4019
4020 // Put probe questions in this packet
4021 for (rr = m->ResourceRecords; rr; rr=rr->next)
4022 if (rr->SendRNow == intf->InterfaceID)
4023 {
4024 mDNSBool ucast = rr->ProbeCount >= DefaultProbeCountForTypeUnique-1;
4025 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
4026 const mDNSu8 *const limit = query.data + ((query.h.numQuestions) ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
4027 mDNSu8 *newptr = putQuestion(&query, queryptr, limit, &rr->resrec.name, kDNSQType_ANY, (mDNSu16)(rr->resrec.rrclass | ucbit));
4028 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
4029 mDNSu32 forecast = answerforecast + 12 + rr->resrec.rdestimate;
4030 if (newptr && newptr + forecast < limit)
4031 {
4032 queryptr = newptr;
4033 answerforecast = forecast;
4034 rr->SendRNow = (rr->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
4035 rr->IncludeInProbe = mDNStrue;
4036 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), rr->ProbeCount);
4037 }
4038 else
4039 {
4040 verbosedebugf("SendQueries: Retracting Question %##s (%s)", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
4041 query.h.numQuestions--;
4042 }
4043 }
4044 }
4045
4046 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
4047 while (KnownAnswerList)
4048 {
4049 CacheRecord *rr = KnownAnswerList;
4050 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
4051 mDNSu8 *newptr = PutResourceRecordTTL(&query, queryptr, &query.h.numAnswers, &rr->resrec, rr->resrec.rroriginalttl - SecsSinceRcvd);
4052 if (newptr)
4053 {
4054 verbosedebugf("SendQueries: Put %##s (%s) at %lu - %lu", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), queryptr - query.data, newptr - query.data);
4055 queryptr = newptr;
4056 KnownAnswerList = rr->NextInKAList;
4057 rr->NextInKAList = mDNSNULL;
4058 }
4059 else
4060 {
4061 // If we ran out of space and we have more than one question in the packet, that's an error --
4062 // we shouldn't have put more than one question if there was a risk of us running out of space.
4063 if (query.h.numQuestions > 1)
4064 LogMsg("SendQueries: Put %d answers; No more space for known answers", query.h.numAnswers);
4065 query.h.flags.b[0] |= kDNSFlag0_TC;
4066 break;
4067 }
4068 }
4069
4070 for (rr = m->ResourceRecords; rr; rr=rr->next)
4071 if (rr->IncludeInProbe)
4072 {
4073 mDNSu8 *newptr = PutResourceRecord(&query, queryptr, &query.h.numAuthorities, &rr->resrec);
4074 rr->IncludeInProbe = mDNSfalse;
4075 if (newptr) queryptr = newptr;
4076 else LogMsg("SendQueries: How did we fail to have space for the Update record %##s (%s)?",
4077 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
4078 }
4079
4080 if (queryptr > query.data)
4081 {
4082 if ((query.h.flags.b[0] & kDNSFlag0_TC) && query.h.numQuestions > 1)
4083 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet\n", query.h.numQuestions);
4084 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
4085 query.h.numQuestions, query.h.numQuestions == 1 ? "" : "s",
4086 query.h.numAnswers, query.h.numAnswers == 1 ? "" : "s",
4087 query.h.numAuthorities, query.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
4088 mDNSSendDNSMessage(m, &query, queryptr, intf->InterfaceID, MulticastDNSPort, &AllDNSLinkGroup_v4, MulticastDNSPort);
4089 mDNSSendDNSMessage(m, &query, queryptr, intf->InterfaceID, MulticastDNSPort, &AllDNSLinkGroup_v6, MulticastDNSPort);
4090 if (!m->SuppressSending) m->SuppressSending = (m->timenow + mDNSPlatformOneSecond/10) | 1; // OR with one to ensure non-zero
4091 if (++pktcount >= 1000)
4092 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
4093 // There might be more records left in the known answer list, or more questions to send
4094 // on this interface, so go around one more time and try again.
4095 }
4096 else // Nothing more to send on this interface; go to next
4097 {
4098 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
4099 #if MDNS_DEBUGMSGS && 0
4100 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4101 debugf(msg, intf, next);
4102 #endif
4103 intf = next;
4104 }
4105 }
4106 }
4107
4108 // ***************************************************************************
4109 #if COMPILER_LIKES_PRAGMA_MARK
4110 #pragma mark -
4111 #pragma mark - RR List Management & Task Management
4112 #endif
4113
4114 // NOTE: AnswerQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4115 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4116 mDNSlocal void AnswerQuestionWithResourceRecord(mDNS *const m, DNSQuestion *q, CacheRecord *rr, mDNSBool AddRecord)
4117 {
4118 verbosedebugf("AnswerQuestionWithResourceRecord:%4lu %s TTL%6lu %##s (%s)",
4119 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
4120
4121 rr->LastUsed = m->timenow;
4122 rr->UseCount++;
4123 if (ActiveQuestion(q) && rr->CRActiveQuestion != q)
4124 {
4125 if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
4126 rr->CRActiveQuestion = q; // We know q is non-null
4127 SetNextCacheCheckTime(m, rr);
4128 }
4129
4130 // CAUTION: MUST NOT do anything more with q after calling q->Callback(), because the client's callback function
4131 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
4132 // Right now the only routines that call AnswerQuestionWithResourceRecord() are CacheRecordAdd(), CacheRecordRmv()
4133 // and AnswerNewQuestion(), and all of them use the "m->CurrentQuestion" mechanism to protect against questions
4134 // being deleted out from under them.
4135 m->mDNS_reentrancy++; // Increment to allow client to legally make mDNS API calls from the callback
4136 if (q->QuestionCallback)
4137 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4138 m->mDNS_reentrancy--; // Decrement to block mDNS API calls again
4139 }
4140
4141 // CacheRecordAdd is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4142 // If new questions are created as a result of invoking client callbacks, they will be added to
4143 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4144 // rr is a new CacheRecord just received into our cache
4145 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4146 // NOTE: CacheRecordAdd calls AnswerQuestionWithResourceRecord which can call a user callback,
4147 // which may change the record list and/or question list.
4148 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4149 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
4150 {
4151 if (m->CurrentQuestion) LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set");
4152 m->CurrentQuestion = m->Questions;
4153 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4154 {
4155 DNSQuestion *q = m->CurrentQuestion;
4156 m->CurrentQuestion = q->next;
4157 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4158 {
4159 // If this question is one that's actively sending queries, and it's received ten answers within one second of sending the last
4160 // query packet, then that indicates some radical network topology change, so reset its exponential backoff back to the start.
4161 // We must be at least at the eight-second interval to do this. If we're at the four-second interval, or less,
4162 // there's not much benefit accelerating because we will anyway send another query within a few seconds.
4163 // The first reset query is sent out randomized over the next four seconds to reduce possible synchronization between machines.
4164 if (ActiveQuestion(q) && ++q->RecentAnswers >= 10 &&
4165 q->ThisQInterval > InitialQuestionInterval*16 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4166 {
4167 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst; restarting exponential backoff sequence",
4168 q->qname.c, DNSTypeName(q->qtype));
4169 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4170 q->ThisQInterval = InitialQuestionInterval;
4171 SetNextQueryTime(m,q);
4172 }
4173 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl);
4174 q->CurrentAnswers++;
4175 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4176 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4177 AnswerQuestionWithResourceRecord(m, q, rr, mDNStrue);
4178 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4179 }
4180 }
4181 m->CurrentQuestion = mDNSNULL;
4182 }
4183
4184 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute
4185 // If new questions are created as a result of invoking client callbacks, they will be added to
4186 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4187 // rr is an existing cache CacheRecord that just expired and is being deleted
4188 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4189 // NOTE: CacheRecordRmv calls AnswerQuestionWithResourceRecord which can call a user callback,
4190 // which may change the record list and/or question list.
4191 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4192 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
4193 {
4194 if (m->CurrentQuestion) LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set");
4195 m->CurrentQuestion = m->Questions;
4196 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4197 {
4198 DNSQuestion *q = m->CurrentQuestion;
4199 m->CurrentQuestion = q->next;
4200 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4201 {
4202 verbosedebugf("CacheRecordRmv %p %##s (%s)", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
4203 if (q->CurrentAnswers == 0)
4204 LogMsg("CacheRecordRmv ERROR: How can CurrentAnswers already be zero for %p %##s (%s)?", q, q->qname.c, DNSTypeName(q->qtype));
4205 else
4206 {
4207 q->CurrentAnswers--;
4208 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4209 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4210 }
4211 if (q->CurrentAnswers == 0)
4212 {
4213 debugf("CacheRecordRmv: Zero current answers for %##s (%s); will reconfirm antecedents", q->qname.c, DNSTypeName(q->qtype));
4214 ReconfirmAntecedents(m, q);
4215 }
4216 AnswerQuestionWithResourceRecord(m, q, rr, mDNSfalse);
4217 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4218 }
4219 }
4220 m->CurrentQuestion = mDNSNULL;
4221 }
4222
4223 mDNSlocal void ReleaseCacheRR(mDNS *const m, CacheRecord *r)
4224 {
4225 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->rdatastorage)
4226 mDNSPlatformMemFree(r->resrec.rdata);
4227 r->resrec.rdata = mDNSNULL;
4228 r->next = m->rrcache_free;
4229 m->rrcache_free = r;
4230 m->rrcache_totalused--;
4231 }
4232
4233 mDNSlocal void CheckCacheExpiration(mDNS *const m, mDNSu32 slot)
4234 {
4235 CacheRecord **rp = &(m->rrcache_hash[slot]);
4236
4237 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4238 m->lock_rrcache = 1;
4239
4240 while (*rp)
4241 {
4242 CacheRecord *const rr = *rp;
4243 mDNSs32 event = RRExpireTime(rr);
4244 if (m->timenow - event >= 0) // If expired, delete it
4245 {
4246 *rp = rr->next; // Cut it from the list
4247 verbosedebugf("CheckCacheExpiration: Deleting %s", GetRRDisplayString(m, rr));
4248 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
4249 {
4250 CacheRecordRmv(m, rr);
4251 m->rrcache_active--;
4252 }
4253 m->rrcache_used[slot]--;
4254 ReleaseCacheRR(m, rr);
4255 }
4256 else // else, not expired; see if we need to query
4257 {
4258 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4259 {
4260 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
4261 event = rr->NextRequiredQuery; // then just record when we want the next query
4262 else // else trigger our question to go out now
4263 {
4264 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4265 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4266 m->NextScheduledQuery = m->timenow;
4267 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTime(),
4268 // which will correctly update m->NextCacheCheck for us
4269 event = m->timenow + 0x3FFFFFFF;
4270 }
4271 }
4272 if (m->NextCacheCheck - (event + CacheCheckGracePeriod(rr)) > 0)
4273 m->NextCacheCheck = (event + CacheCheckGracePeriod(rr));
4274 rp = &rr->next;
4275 }
4276 }
4277 if (m->rrcache_tail[slot] != rp) debugf("CheckCacheExpiration: Updating m->rrcache_tail[%d] from %p to %p", slot, m->rrcache_tail[slot], rp);
4278 m->rrcache_tail[slot] = rp;
4279 m->lock_rrcache = 0;
4280 }
4281
4282 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4283 {
4284 mDNSBool ShouldQueryImmediately = mDNStrue;
4285 CacheRecord *rr;
4286 DNSQuestion *q = m->NewQuestions; // Grab the question we're going to answer
4287 mDNSu32 slot = HashSlot(&q->qname);
4288
4289 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4290
4291 CheckCacheExpiration(m, slot);
4292 m->NewQuestions = q->next; // Advance NewQuestions to the next *after* calling CheckCacheExpiration();
4293
4294 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4295 // This should be safe, because calling the client's question callback may cause the
4296 // question list to be modified, but should not ever cause the rrcache list to be modified.
4297 // If the client's question callback deletes the question, then m->CurrentQuestion will
4298 // be advanced, and we'll exit out of the loop
4299 m->lock_rrcache = 1;
4300 if (m->CurrentQuestion) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4301 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4302 for (rr=m->rrcache_hash[slot]; rr; rr=rr->next)
4303 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4304 {
4305 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4306 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
4307 if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
4308 {
4309 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %##s (%s)",
4310 rr->resrec.rroriginalttl, SecsSinceRcvd, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
4311 continue; // Go to next one in loop
4312 }
4313
4314 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4315 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4316 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ShouldQueryImmediately = mDNSfalse;
4317 q->CurrentAnswers++;
4318 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4319 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4320 AnswerQuestionWithResourceRecord(m, q, rr, mDNStrue);
4321 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4322 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4323 }
4324 else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
4325 if (rr->resrec.namehash == q->qnamehash && SameDomainName(&rr->resrec.name, &q->qname))
4326 ShouldQueryImmediately = mDNSfalse;
4327
4328 if (ShouldQueryImmediately && m->CurrentQuestion == q)
4329 {
4330 q->ThisQInterval = InitialQuestionInterval;
4331 q->LastQTime = m->timenow - q->ThisQInterval;
4332 m->NextScheduledQuery = m->timenow;
4333 }
4334 m->CurrentQuestion = mDNSNULL;
4335 m->lock_rrcache = 0;
4336 }
4337
4338 mDNSlocal void AnswerLocalOnlyQuestionWithResourceRecord(mDNS *const m, DNSQuestion *q, AuthRecord *rr, mDNSBool AddRecord)
4339 {
4340 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
4341 if (AddRecord) rr->AnnounceCount = InitialAnnounceCount - 1;
4342 m->mDNS_reentrancy++; // Increment to allow client to legally make mDNS API calls from the callback
4343 if (q->QuestionCallback)
4344 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4345 m->mDNS_reentrancy--; // Decrement to block mDNS API calls again
4346 }
4347
4348 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
4349 {
4350 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
4351 m->NewLocalOnlyQuestions = q->next; // Advance NewQuestions to the next (if any)
4352
4353 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4354
4355 if (m->CurrentQuestion) LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set");
4356 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4357
4358 m->CurrentRecord = m->LocalOnlyRecords;
4359 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalOnlyRecords)
4360 {
4361 AuthRecord *rr = m->CurrentRecord;
4362 m->CurrentRecord = rr->next;
4363 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4364 {
4365 AnswerLocalOnlyQuestionWithResourceRecord(m, q, rr, mDNStrue);
4366 // MUST NOT dereference q again after calling AnswerLocalOnlyQuestionWithResourceRecord()
4367 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
4368 }
4369 }
4370
4371 m->CurrentQuestion = mDNSNULL;
4372 }
4373
4374 mDNSlocal void AnswerLocalOnlyQuestions(mDNS *const m, AuthRecord *rr, mDNSBool AddRecord)
4375 {
4376 if (m->CurrentQuestion) LogMsg("AnswerLocalOnlyQuestions ERROR m->CurrentQuestion already set");
4377 m->CurrentQuestion = m->LocalOnlyQuestions;
4378 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
4379 {
4380 DNSQuestion *q = m->CurrentQuestion;
4381 m->CurrentQuestion = q->next;
4382 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4383 {
4384 debugf("AnswerLocalOnlyQuestions %p %##s (%s) %lu", rr, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl);
4385 AnswerLocalOnlyQuestionWithResourceRecord(m, q, rr, AddRecord);
4386 // MUST NOT dereference q again after calling AnswerQuestionWithResourceRecord()
4387 }
4388 }
4389 m->CurrentQuestion = mDNSNULL;
4390 }
4391
4392 mDNSlocal void DiscardLocalOnlyRecords(mDNS *const m)
4393 {
4394 AuthRecord *rr = m->LocalOnlyRecords;
4395 while (rr)
4396 {
4397 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
4398 { AnswerLocalOnlyQuestions(m, rr, mDNSfalse); CompleteDeregistration(m, rr); return; }
4399 if (rr->ProbeCount) { mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict); return; }
4400 rr=rr->next;
4401 }
4402 m->DiscardLocalOnlyRecords = mDNSfalse;
4403 }
4404
4405 mDNSlocal void AnswerForNewLocalOnlyRecords(mDNS *const m)
4406 {
4407 AuthRecord *rr = m->NewLocalOnlyRecords;
4408 m->NewLocalOnlyRecords = m->NewLocalOnlyRecords->next;
4409 AnswerLocalOnlyQuestions(m, rr, mDNStrue);
4410 }
4411
4412 mDNSlocal CacheRecord *GetFreeCacheRR(mDNS *const m, mDNSu16 RDLength)
4413 {
4414 CacheRecord *r = mDNSNULL;
4415
4416 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
4417 m->lock_rrcache = 1;
4418
4419 // If we have no free records, ask the client layer to give us some more memory
4420 if (!m->rrcache_free && m->MainCallback)
4421 {
4422 if (m->rrcache_totalused != m->rrcache_size)
4423 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4424 m->rrcache_totalused, m->rrcache_size);
4425
4426 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4427 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4428 // To guard against this, if we're actively using less than 1/32 of our cache, then we
4429 // purge all the unused records and recycle them, instead of allocating more memory.
4430 if (m->rrcache_size >= 512 && m->rrcache_size / 32 > m->rrcache_active)
4431 debugf("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4432 m->rrcache_size, m->rrcache_active);
4433 else
4434 m->MainCallback(m, mStatus_GrowCache);
4435 }
4436
4437 // If we still have no free records, recycle all the records we can.
4438 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4439 if (!m->rrcache_free)
4440 {
4441 #if MDNS_DEBUGMSGS
4442 mDNSu32 oldtotalused = m->rrcache_totalused;
4443 #endif
4444 mDNSu32 slot;
4445 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4446 {
4447 CacheRecord **rp = &(m->rrcache_hash[slot]);
4448 while (*rp)
4449 {
4450 // Records that answer still-active questions are not candidates for deletion
4451 if ((*rp)->CRActiveQuestion)
4452 rp=&(*rp)->next;
4453 else
4454 {
4455 CacheRecord *rr = *rp;
4456 *rp = (*rp)->next; // Cut record from list
4457 m->rrcache_used[slot]--; // Decrement counts
4458 ReleaseCacheRR(m, rr);
4459 }
4460 }
4461 if (m->rrcache_tail[slot] != rp) debugf("GetFreeCacheRR: Updating m->rrcache_tail[%d] from %p to %p", slot, m->rrcache_tail[slot], rp);
4462 m->rrcache_tail[slot] = rp;
4463 }
4464 #if MDNS_DEBUGMSGS
4465 debugf("Clear unused records; m->rrcache_totalused was %lu; now %lu", oldtotalused, m->rrcache_totalused);
4466 #endif
4467 }
4468
4469 if (m->rrcache_free) // If there are records in the free list, take one
4470 {
4471 r = m->rrcache_free;
4472 m->rrcache_free = r->next;
4473 }
4474
4475 if (r)
4476 {
4477 if (++m->rrcache_totalused >= m->rrcache_report)
4478 {
4479 debugf("RR Cache now using %ld records", m->rrcache_totalused);
4480 if (m->rrcache_report < 100) m->rrcache_report += 10;
4481 else m->rrcache_report += 100;
4482 }
4483 mDNSPlatformMemZero(r, sizeof(*r));
4484 r->resrec.rdata = (RData*)&r->rdatastorage; // By default, assume we're usually going to be using local storage
4485
4486 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
4487 {
4488 r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
4489 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
4490 else { ReleaseCacheRR(m, r); r = mDNSNULL; }
4491 }
4492 }
4493
4494 m->lock_rrcache = 0;
4495
4496 return(r);
4497 }
4498
4499 mDNSlocal void PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
4500 {
4501 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4502 // a positive answer using an expired record (e.g. from an interface that has gone away).
4503 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4504 // summary deletion without giving the proper callback to any questions that are monitoring it.
4505 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4506 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
4507 rr->UnansweredQueries = MaxUnansweredQueries;
4508 rr->resrec.rroriginalttl = 0;
4509 SetNextCacheCheckTime(m, rr);
4510 }
4511
4512 mDNSlocal void mDNS_Lock(mDNS *const m)
4513 {
4514 // MUST grab the platform lock FIRST!
4515 mDNSPlatformLock(m);
4516
4517 // Normally, mDNS_reentrancy is zero and so is mDNS_busy
4518 // However, when we call a client callback mDNS_busy is one, and we increment mDNS_reentrancy too
4519 // If that client callback does mDNS API calls, mDNS_reentrancy and mDNS_busy will both be one
4520 // If mDNS_busy != mDNS_reentrancy that's a bad sign
4521 if (m->mDNS_busy != m->mDNS_reentrancy)
4522 LogMsg("mDNS_Lock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
4523
4524 // If this is an initial entry into the mDNSCore code, set m->timenow
4525 // else, if this is a re-entrant entry into the mDNSCore code, m->timenow should already be set
4526 if (m->mDNS_busy == 0)
4527 {
4528 if (m->timenow)
4529 LogMsg("mDNS_Lock: m->timenow already set (%ld/%ld)", m->timenow, mDNSPlatformTimeNow() + m->timenow_adjust);
4530 m->timenow = mDNSPlatformTimeNow() + m->timenow_adjust;
4531 if (m->timenow == 0) m->timenow = 1;
4532 }
4533 else if (m->timenow == 0)
4534 {
4535 LogMsg("mDNS_Lock: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
4536 m->timenow = mDNSPlatformTimeNow() + m->timenow_adjust;
4537 if (m->timenow == 0) m->timenow = 1;
4538 }
4539
4540 if (m->timenow_last - m->timenow > 0)
4541 {
4542 m->timenow_adjust += m->timenow_last - m->timenow;
4543 LogMsg("mDNSPlatformTimeNow went backwards by %ld ticks; setting correction factor to %ld", m->timenow_last - m->timenow, m->timenow_adjust);
4544 m->timenow = m->timenow_last;
4545 }
4546 m->timenow_last = m->timenow;
4547
4548 // Increment mDNS_busy so we'll recognise re-entrant calls
4549 m->mDNS_busy++;
4550 }
4551
4552 mDNSlocal mDNSs32 GetNextScheduledEvent(const mDNS *const m)
4553 {
4554 mDNSs32 e = m->timenow + 0x78000000;
4555 if (m->mDNSPlatformStatus != mStatus_NoError || m->SleepState) return(e);
4556 if (m->NewQuestions) return(m->timenow);
4557 if (m->NewLocalOnlyQuestions) return(m->timenow);
4558 if (m->NewLocalOnlyRecords) return(m->timenow);
4559 if (m->DiscardLocalOnlyRecords) return(m->timenow);
4560 if (m->SuppressSending) return(m->SuppressSending);
4561 if (e - m->NextCacheCheck > 0) e = m->NextCacheCheck;
4562 if (e - m->NextScheduledQuery > 0) e = m->NextScheduledQuery;
4563 if (e - m->NextScheduledProbe > 0) e = m->NextScheduledProbe;
4564 if (e - m->NextScheduledResponse > 0) e = m->NextScheduledResponse;
4565 return(e);
4566 }
4567
4568 mDNSlocal void mDNS_Unlock(mDNS *const m)
4569 {
4570 // Decrement mDNS_busy
4571 m->mDNS_busy--;
4572
4573 // Check for locking failures
4574 if (m->mDNS_busy != m->mDNS_reentrancy)
4575 LogMsg("mDNS_Unlock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
4576
4577 // If this is a final exit from the mDNSCore code, set m->NextScheduledEvent and clear m->timenow
4578 if (m->mDNS_busy == 0)
4579 {
4580 m->NextScheduledEvent = GetNextScheduledEvent(m);
4581 if (m->timenow == 0) LogMsg("mDNS_Unlock: ERROR! m->timenow aready zero");
4582 m->timenow = 0;
4583 }
4584
4585 // MUST release the platform lock LAST!
4586 mDNSPlatformUnlock(m);
4587 }
4588
4589 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
4590 {
4591 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
4592
4593 if (m->timenow - m->NextScheduledEvent >= 0)
4594 {
4595 int i;
4596
4597 verbosedebugf("mDNS_Execute");
4598 if (m->CurrentQuestion) LogMsg("mDNS_Execute: ERROR! m->CurrentQuestion already set");
4599
4600 // 1. If we're past the probe suppression time, we can clear it
4601 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
4602
4603 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4604 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
4605
4606 // 3. Purge our cache of stale old records
4607 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
4608 {
4609 mDNSu32 slot;
4610 m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
4611 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) CheckCacheExpiration(m, slot);
4612 }
4613
4614 // 4. See if we can answer any of our new local questions from the cache
4615 for (i=0; m->NewQuestions && i<1000; i++) AnswerNewQuestion(m);
4616 if (i >= 1000) debugf("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4617
4618 for (i=0; m->DiscardLocalOnlyRecords && i<1000; i++) DiscardLocalOnlyRecords(m);
4619 if (i >= 1000) debugf("mDNS_Execute: DiscardLocalOnlyRecords exceeded loop limit");
4620
4621 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
4622 if (i >= 1000) debugf("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4623
4624 for (i=0; m->NewLocalOnlyRecords && i<1000; i++) AnswerForNewLocalOnlyRecords(m);
4625 if (i >= 1000) debugf("mDNS_Execute: AnswerLocalOnlyQuestions exceeded loop limit");
4626
4627 // 5. See what packets we need to send
4628 if (m->mDNSPlatformStatus != mStatus_NoError || m->SleepState) DiscardDeregistrations(m);
4629 else if (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0)
4630 {
4631 // If the platform code is ready, and we're not suppressing packet generation right now
4632 // then send our responses, probes, and questions.
4633 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them
4634 // We send queries next, because there might be final-stage probes that complete their probing here, causing
4635 // them to advance to announcing state, and we want those to be included in any announcements we send out.
4636 // Finally, we send responses, including the previously mentioned records that just completed probing
4637 m->SuppressSending = 0;
4638
4639 // 6. Send Query packets. This may cause some probing records to advance to announcing state
4640 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
4641 if (m->timenow - m->NextScheduledQuery >= 0)
4642 {
4643 LogMsg("mDNS_Execute: SendQueries didn't send all its queries; will try again in one second");
4644 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
4645 }
4646 if (m->timenow - m->NextScheduledProbe >= 0)
4647 {
4648 LogMsg("mDNS_Execute: SendQueries didn't send all its probes; will try again in one second");
4649 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
4650 }
4651
4652 // 7. Send Response packets, including probing records just advanced to announcing state
4653 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
4654 if (m->timenow - m->NextScheduledResponse >= 0)
4655 {
4656 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4657 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
4658 }
4659 }
4660
4661 m->RandomQueryDelay = 0; // Clear m->RandomQueryDelay, ready to pick a new different value, when necessary
4662 }
4663
4664 // Note about multi-threaded systems:
4665 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4666 // performing mDNS API operations that change our next scheduled event time.
4667 //
4668 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
4669 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4670 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4671 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4672 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4673 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4674 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4675 // without blocking. This avoids the race condition between the signal from the other thread arriving
4676 // just *before* or just *after* the main thread enters the blocking primitive.
4677 //
4678 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4679 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4680 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4681 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4682 // by the time it gets to the timer callback function).
4683
4684 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4685 return(m->NextScheduledEvent);
4686 }
4687
4688 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
4689 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
4690 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
4691 // Note that sleep/wake calls do not have to be paired one-for-one; it is acceptable to call
4692 // mDNSCoreMachineSleep(m, mDNSfalse) any time there is reason to believe that the machine may have just
4693 // found itself in a new network environment. For example, if the Ethernet hardware indicates that the
4694 // cable has just been connected, the platform support layer should call mDNSCoreMachineSleep(m, mDNSfalse)
4695 // to make mDNSCore re-issue its outstanding queries, probe for record uniqueness, etc.
4696 // While it is safe to call mDNSCoreMachineSleep(m, mDNSfalse) at any time, it does cause extra network
4697 // traffic, so it should only be called when there is legitimate reason to believe the machine
4698 // may have become attached to a new network.
4699 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleepstate)
4700 {
4701 AuthRecord *rr;
4702
4703 mDNS_Lock(m);
4704
4705 m->SleepState = sleepstate;
4706 LogMsg("mDNSResponder %s at %ld", sleepstate ? "Sleeping" : "Waking", m->timenow);
4707
4708 if (sleepstate)
4709 {
4710 // Mark all the records we need to deregister and send them
4711 for (rr = m->ResourceRecords; rr; rr=rr->next)
4712 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->AnnounceCount < InitialAnnounceCount)
4713 rr->ImmedAnswer = mDNSInterfaceMark;
4714 SendResponses(m);
4715 }
4716 else
4717 {
4718 DNSQuestion *q;
4719 mDNSu32 slot;
4720 CacheRecord *cr;
4721
4722 // 1. Retrigger all our questions
4723 for (q = m->Questions; q; q=q->next) // Scan our list of questions
4724 if (ActiveQuestion(q))
4725 {
4726 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
4727 q->LastQTime = m->timenow - q->ThisQInterval;
4728 q->RecentAnswers = 0;
4729 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
4730 m->NextScheduledQuery = m->timenow;
4731 }
4732
4733 // 2. Re-validate our cache records
4734 m->NextCacheCheck = m->timenow;
4735 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4736 for (cr = m->rrcache_hash[slot]; cr; cr=cr->next)
4737 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForCableDisconnect);
4738
4739 // 3. Retrigger probing and announcing for all our authoritative records
4740 for (rr = m->ResourceRecords; rr; rr=rr->next)
4741 {
4742 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
4743 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
4744 if (rr->AnnounceCount < ReannounceCount)
4745 rr->AnnounceCount = ReannounceCount;
4746 rr->ThisAPInterval = DefaultAPIntervalForRecordType(rr->resrec.RecordType);
4747 InitializeLastAPTime(m, rr);
4748 }
4749
4750 }
4751
4752 mDNS_Unlock(m);
4753 }
4754
4755 // ***************************************************************************
4756 #if COMPILER_LIKES_PRAGMA_MARK
4757 #pragma mark -
4758 #pragma mark - Packet Reception Functions
4759 #endif
4760
4761 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
4762 {
4763 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
4764 {
4765 **nrpp = rr;
4766 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
4767 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
4768 // The referenced record will definitely be acceptable (by recursive application of this rule)
4769 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
4770 rr->NR_AdditionalTo = add;
4771 *nrpp = &rr->NextResponse;
4772 }
4773 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
4774 }
4775
4776 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
4777
4778 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
4779 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
4780 {
4781 mDNSu8 *responseptr = response->data;
4782 const mDNSu8 *const limit = response->data + sizeof(response->data);
4783 const mDNSu8 *ptr = query->data;
4784 AuthRecord *rr;
4785 mDNSu32 maxttl = 0x70000000;
4786 int i;
4787
4788 // Initialize the response fields so we can answer the questions
4789 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
4790
4791 // ***
4792 // *** 1. Write out the list of questions we are actually going to answer with this packet
4793 // ***
4794 if (LegacyQuery)
4795 {
4796 maxttl = 10;
4797 for (i=0; i<query->h.numQuestions; i++) // For each question...
4798 {
4799 DNSQuestion q;
4800 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
4801 if (!ptr) return(mDNSNULL);
4802
4803 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
4804 {
4805 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
4806 { // then put the question in the question section
4807 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
4808 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
4809 break; // break out of the ResponseRecords loop, and go on to the next question
4810 }
4811 }
4812 }
4813
4814 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
4815 }
4816
4817 // ***
4818 // *** 2. Write Answers
4819 // ***
4820 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
4821 if (rr->NR_AnswerTo)
4822 {
4823 mDNSu8 *p = PutResourceRecordCappedTTL(response, responseptr, &response->h.numAnswers, &rr->resrec, maxttl);
4824 if (p) responseptr = p;
4825 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
4826 }
4827
4828 // ***
4829 // *** 3. Write Additionals
4830 // ***
4831 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
4832 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
4833 {
4834 mDNSu8 *p = PutResourceRecordCappedTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec, maxttl);
4835 if (p) responseptr = p;
4836 else debugf("GenerateUnicastResponse: No more space for additionals");
4837 }
4838
4839 return(responseptr);
4840 }
4841
4842 // AuthRecord *our is our Resource Record
4843 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
4844 // Returns 0 if there is no conflict
4845 // Returns +1 if there was a conflict and we won
4846 // Returns -1 if there was a conflict and we lost and have to rename
4847 mDNSlocal int CompareRData(AuthRecord *our, CacheRecord *pkt)
4848 {
4849 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
4850 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
4851 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
4852 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
4853
4854 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
4855 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
4856 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
4857 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
4858
4859 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
4860 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
4861 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
4862 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
4863
4864 debugf("CompareRData: How did we get here?");
4865 return(-1);
4866 }
4867
4868 // See if we have an authoritative record that's identical to this packet record,
4869 // whose canonical DependentOn record is the specified master record.
4870 // The DependentOn pointer is typically used for the TXT record of service registrations
4871 // It indicates that there is no inherent conflict detection for the TXT record
4872 // -- it depends on the SRV record to resolve name conflicts
4873 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
4874 // pointer chain (if any) to make sure we reach the canonical DependentOn record
4875 // If the record has no DependentOn, then just return that record's pointer
4876 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4877 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
4878 {
4879 const AuthRecord *r1;
4880 for (r1 = m->ResourceRecords; r1; r1=r1->next)
4881 {
4882 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
4883 {
4884 const AuthRecord *r2 = r1;
4885 while (r2->DependentOn) r2 = r2->DependentOn;
4886 if (r2 == master) return(mDNStrue);
4887 }
4888 }
4889 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
4890 {
4891 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
4892 {
4893 const AuthRecord *r2 = r1;
4894 while (r2->DependentOn) r2 = r2->DependentOn;
4895 if (r2 == master) return(mDNStrue);
4896 }
4897 }
4898 return(mDNSfalse);
4899 }
4900
4901 // Find the canonical RRSet pointer for this RR received in a packet.
4902 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
4903 // pointers (if any) to make sure we return the canonical member of this name/type/class
4904 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4905 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
4906 {
4907 const AuthRecord *rr;
4908 for (rr = m->ResourceRecords; rr; rr=rr->next)
4909 {
4910 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
4911 {
4912 while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
4913 return(rr);
4914 }
4915 }
4916 return(mDNSNULL);
4917 }
4918
4919 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
4920 // as one of our records (our) but different rdata.
4921 // 1. If our record is not a type that's supposed to be unique, we don't care.
4922 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
4923 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
4924 // points to our record, ignore this conflict (e.g. the packet record matches one of our
4925 // TXT records, and that record is marked as dependent on 'our', its SRV record).
4926 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
4927 // are members of the same RRSet, then this is not a conflict.
4928 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
4929 {
4930 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
4931
4932 // If not supposed to be unique, not a conflict
4933 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
4934
4935 // If a dependent record, not a conflict
4936 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
4937
4938 // If the pktrr matches a member of ourset, not a conflict
4939 if (FindRRSet(m, pktrr) == ourset) return(mDNSfalse);
4940
4941 // Okay, this is a conflict
4942 return(mDNStrue);
4943 }
4944
4945 // NOTE: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
4946 // the record list and/or question list.
4947 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4948 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
4949 DNSQuestion *q, AuthRecord *our)
4950 {
4951 int i;
4952 const mDNSu8 *ptr = LocateAuthorities(query, end);
4953 mDNSBool FoundUpdate = mDNSfalse;
4954
4955 for (i = 0; i < query->h.numAuthorities; i++)
4956 {
4957 LargeCacheRecord pkt;
4958 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, 0, &pkt);
4959 if (!ptr) break;
4960 if (ResourceRecordAnswersQuestion(&pkt.r.resrec, q))
4961 {
4962 FoundUpdate = mDNStrue;
4963 if (PacketRRConflict(m, our, &pkt.r))
4964 {
4965 int result = (int)our->resrec.rrclass - (int)pkt.r.resrec.rrclass;
4966 if (!result) result = (int)our->resrec.rrtype - (int)pkt.r.resrec.rrtype;
4967 if (!result) result = CompareRData(our, &pkt.r);
4968 switch (result)
4969 {
4970 case 1: debugf("ResolveSimultaneousProbe: %##s (%s): We won", our->resrec.name.c, DNSTypeName(our->resrec.rrtype));
4971 break;
4972 case 0: break;
4973 case -1: debugf("ResolveSimultaneousProbe: %##s (%s): We lost", our->resrec.name.c, DNSTypeName(our->resrec.rrtype));
4974 mDNS_Deregister_internal(m, our, mDNS_Dereg_conflict);
4975 return;
4976 }
4977 }
4978 }
4979 }
4980 if (!FoundUpdate)
4981 debugf("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name.c, DNSTypeName(our->resrec.rrtype));
4982 }
4983
4984 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, ResourceRecord *pktrr)
4985 {
4986 CacheRecord *rr;
4987 for (rr = m->rrcache_hash[HashSlot(&pktrr->name)]; rr; rr=rr->next)
4988 if (pktrr->InterfaceID == rr->resrec.InterfaceID && IdenticalResourceRecord(pktrr, &rr->resrec)) break;
4989 return(rr);
4990 }
4991
4992 // ProcessQuery examines a received query to see if we have any answers to give
4993 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
4994 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
4995 DNSMessage *const response)
4996 {
4997 AuthRecord *ResponseRecords = mDNSNULL;
4998 AuthRecord **nrp = &ResponseRecords;
4999 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
5000 CacheRecord **eap = &ExpectedAnswers;
5001 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
5002 DNSQuestion **dqp = &DupQuestions;
5003 mDNSs32 delayresponse = 0;
5004 mDNSBool HaveUnicastAnswer = mDNSfalse;
5005 const mDNSu8 *ptr = query->data;
5006 mDNSu8 *responseptr = mDNSNULL;
5007 AuthRecord *rr, *rr2;
5008 int i;
5009
5010 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet.
5011 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
5012
5013 // ***
5014 // *** 1. Parse Question Section and mark potential answers
5015 // ***
5016 for (i=0; i<query->h.numQuestions; i++) // For each question...
5017 {
5018 mDNSBool QuestionNeedsMulticastResponse;
5019 int NumAnswersForThisQuestion = 0;
5020 DNSQuestion pktq, *q;
5021 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
5022 if (!ptr) goto exit;
5023
5024 // The only queries that *need* a multicast response are:
5025 // * Queries sent via multicast
5026 // * from port 5353
5027 // * that don't have the kDNSQClass_UnicastResponse bit set
5028 // These queries need multicast responses because other clients will:
5029 // * suppress their own identical questions when they see these questions, and
5030 // * expire their cache records if they don't see the expected responses
5031 // For other queries, we may still choose to send the occasional multicast response anyway,
5032 // to keep our neighbours caches warm, and for ongoing conflict detection.
5033 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
5034 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
5035 pktq.qclass &= ~kDNSQClass_UnicastResponse;
5036
5037 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
5038 // can result in user callbacks which may change the record list and/or question list.
5039 // Also note: we just mark potential answer records here, without trying to build the
5040 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
5041 // from that list while we're in the middle of trying to build it.
5042 if (m->CurrentRecord) LogMsg("ProcessQuery ERROR m->CurrentRecord already set");
5043 m->CurrentRecord = m->ResourceRecords;
5044 while (m->CurrentRecord)
5045 {
5046 rr = m->CurrentRecord;
5047 m->CurrentRecord = rr->next;
5048 if (ResourceRecordAnswersQuestion(&rr->resrec, &pktq))
5049 {
5050 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
5051 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
5052 else if (ResourceRecordIsValidAnswer(rr))
5053 {
5054 NumAnswersForThisQuestion++;
5055 // Notes:
5056 // NR_AnswerTo pointing into query packet means "answer via unicast"
5057 // (may also choose to do multicast as well)
5058 // NR_AnswerTo == ~0 means "definitely answer via multicast" (can't downgrade to unicast later)
5059 if (QuestionNeedsMulticastResponse)
5060 {
5061 // We only mark this question for sending if it is at least one second since the last time we multicast it
5062 // on this interface. If it is more than a second, or LastMCInterface is different, then we should multicast it.
5063 // This is to guard against the case where someone blasts us with queries as fast as they can.
5064 if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
5065 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
5066 rr->NR_AnswerTo = (mDNSu8*)~0;
5067 }
5068 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = ptr;
5069 }
5070 }
5071 }
5072
5073 // We only do the following accelerated cache expiration processing and duplicate question suppression processing
5074 // for multicast queries with multicast responses.
5075 // For any query generating a unicast response we don't do this because we can't assume we will see the response
5076 if (QuestionNeedsMulticastResponse)
5077 {
5078 CacheRecord *rr;
5079 // If we couldn't answer this question, someone else might be able to,
5080 // so use random delay on response to reduce collisions
5081 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
5082
5083 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5084 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5085 for (rr = m->rrcache_hash[HashSlot(&pktq.qname)]; rr; rr=rr->next)
5086 if (ResourceRecordAnswersQuestion(&rr->resrec, &pktq) && rr->resrec.rdlength <= SmallRecordLimit)
5087 if (!rr->NextInKAList && eap != &rr->NextInKAList)
5088 {
5089 *eap = rr;
5090 eap = &rr->NextInKAList;
5091 if (rr->MPUnansweredQ == 0 || m->timenow - rr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
5092 {
5093 // Although MPUnansweredQ is only really used for multi-packet query processing,
5094 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5095 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5096 rr->MPUnansweredQ++;
5097 rr->MPLastUnansweredQT = m->timenow;
5098 rr->MPExpectingKA = mDNStrue;
5099 }
5100 }
5101
5102 // Check if this question is the same as any of mine.
5103 // We only do this for non-truncated queries. Right now it would be too complicated to try
5104 // to keep track of duplicate suppression state between multiple packets, especially when we
5105 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5106 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5107 for (q = m->Questions; q; q=q->next)
5108 if (ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
5109 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
5110 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
5111 if (q->qtype == pktq.qtype && q->qclass == pktq.qclass && q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
5112 { *dqp = q; dqp = &q->NextInDQList; }
5113 }
5114 }
5115
5116 // ***
5117 // *** 2. Now we can safely build the list of marked answers
5118 // ***
5119 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
5120 if (rr->NR_AnswerTo) // If we marked the record...
5121 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
5122
5123 // ***
5124 // *** 3. Add additional records
5125 // ***
5126 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
5127 {
5128 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
5129 // later in the "for" loop, and we will follow further "additional" links then.)
5130 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
5131 AddRecordToResponseList(&nrp, rr->Additional1, rr);
5132
5133 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
5134 AddRecordToResponseList(&nrp, rr->Additional2, rr);
5135
5136 // For SRV records, automatically add the Address record(s) for the target host
5137 if (rr->resrec.rrtype == kDNSType_SRV)
5138 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
5139 if (RRIsAddressType(rr2) && // For all address records (A/AAAA) ...
5140 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
5141 rr->resrec.rdnamehash == rr2->resrec.namehash &&
5142 SameDomainName(&rr->resrec.rdata->u.srv.target, &rr2->resrec.name)) // ... whose name is the name of the SRV target
5143 AddRecordToResponseList(&nrp, rr2, rr);
5144 }
5145
5146 // ***
5147 // *** 4. Parse Answer Section and cancel any records disallowed by Known-Answer list
5148 // ***
5149 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
5150 {
5151 // Get the record...
5152 LargeCacheRecord pkt;
5153 AuthRecord *rr;
5154 CacheRecord *ourcacherr;
5155 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &pkt);
5156 if (!ptr) goto exit;
5157
5158 // See if this Known-Answer suppresses any of our currently planned answers
5159 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5160 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&pkt.r, rr))
5161 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
5162
5163 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5164 for (rr=m->ResourceRecords; rr; rr=rr->next)
5165 {
5166 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5167 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&pkt.r, rr))
5168 {
5169 if (srcaddr->type == mDNSAddrType_IPv4)
5170 {
5171 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zeroIPAddr;
5172 }
5173 else if (srcaddr->type == mDNSAddrType_IPv6)
5174 {
5175 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
5176 }
5177 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester)) rr->ImmedAnswer = mDNSNULL;
5178 }
5179 }
5180
5181 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5182 // 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).
5183 ourcacherr = FindIdenticalRecordInCache(m, &pkt.r.resrec);
5184 if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
5185 {
5186 ourcacherr->MPUnansweredKA++;
5187 ourcacherr->MPExpectingKA = mDNSfalse;
5188 }
5189
5190 // Having built our ExpectedAnswers list from the questions in this packet, we can definitively
5191 // remove from our ExpectedAnswers list any records that are suppressed in the very same packet.
5192 // For answers that are suppressed in subsequent KA list packets, we rely on the MPQ/MPKA counting to track them.
5193 eap = &ExpectedAnswers;
5194 while (*eap)
5195 {
5196 CacheRecord *rr = *eap;
5197 if (rr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&pkt.r.resrec, &rr->resrec))
5198 { *eap = rr->NextInKAList; rr->NextInKAList = mDNSNULL; }
5199 else eap = &rr->NextInKAList;
5200 }
5201
5202 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5203 if (!ourcacherr)
5204 {
5205 dqp = &DupQuestions;
5206 while (*dqp)
5207 {
5208 DNSQuestion *q = *dqp;
5209 if (ResourceRecordAnswersQuestion(&pkt.r.resrec, q))
5210 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
5211 else dqp = &q->NextInDQList;
5212 }
5213 }
5214 }
5215
5216 // ***
5217 // *** 5. Cancel any additionals that were added because of now-deleted records
5218 // ***
5219 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5220 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
5221 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
5222
5223 // ***
5224 // *** 6. Mark the send flags on the records we plan to send
5225 // ***
5226 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5227 {
5228 if (rr->NR_AnswerTo)
5229 {
5230 mDNSBool SendMulticastResponse = mDNSfalse;
5231
5232 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
5233 if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0) SendMulticastResponse = mDNStrue;
5234
5235 // If the client insists on a multicast response, then we'd better send one
5236 if (rr->NR_AnswerTo == (mDNSu8*)~0) SendMulticastResponse = mDNStrue;
5237 else if (rr->NR_AnswerTo) HaveUnicastAnswer = mDNStrue;
5238
5239 if (SendMulticastResponse)
5240 {
5241 // If we're already planning to send this on another interface, just send it on all interfaces
5242 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
5243 {
5244 rr->ImmedAnswer = mDNSInterfaceMark;
5245 m->NextScheduledResponse = m->timenow;
5246 debugf("ProcessQuery: %##s (%s) : Will send on all interfaces", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
5247 }
5248 else
5249 {
5250 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
5251 m->NextScheduledResponse = m->timenow;
5252 if (srcaddr->type == mDNSAddrType_IPv4)
5253 {
5254 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
5255 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
5256 }
5257 else if (srcaddr->type == mDNSAddrType_IPv6)
5258 {
5259 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
5260 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
5261 }
5262 }
5263 }
5264 if (rr->resrec.RecordType == kDNSRecordTypeShared)
5265 {
5266 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
5267 else delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
5268 }
5269 }
5270 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == (mDNSu8*)~0)
5271 {
5272 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
5273 // If two clients on different interfaces do queries that invoke the same optional additional answer,
5274 // then the earlier client is out of luck
5275 rr->ImmedAdditional = InterfaceID;
5276 // No need to set m->NextScheduledResponse here
5277 // We'll send these additional records when we send them, or not, as the case may be
5278 }
5279 }
5280
5281 // ***
5282 // *** 7. If we think other machines are likely to answer these questions, set our packet suppression timer
5283 // ***
5284 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
5285 {
5286 // Pick a random delay:
5287 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
5288 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
5289 // This is an integer value, with resolution determined by the platform clock rate.
5290 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
5291 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
5292 // The +49 before dividing is to ensure we round up, not down, to ensure that even
5293 // on platforms where the native clock rate is less than fifty ticks per second,
5294 // we still guarantee that the final calculated delay is at least one platform tick.
5295 // We want to make sure we don't ever allow the delay to be zero ticks,
5296 // because if that happens we'll fail the Rendezvous Conformance Test.
5297 // Our final computed delay is 20-120ms for normal delayed replies,
5298 // or 400-500ms in the case of multi-packet known-answer lists.
5299 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
5300 if (m->SuppressSending == 0) m->SuppressSending = 1;
5301 }
5302
5303 // ***
5304 // *** 8. If query is from a legacy client, generate a unicast response too
5305 // ***
5306 if (HaveUnicastAnswer)
5307 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
5308
5309 exit:
5310 // ***
5311 // *** 9. Finally, clear our link chains ready for use next time
5312 // ***
5313 while (ResponseRecords)
5314 {
5315 rr = ResponseRecords;
5316 ResponseRecords = rr->NextResponse;
5317 rr->NextResponse = mDNSNULL;
5318 rr->NR_AnswerTo = mDNSNULL;
5319 rr->NR_AdditionalTo = mDNSNULL;
5320 }
5321
5322 while (ExpectedAnswers)
5323 {
5324 CacheRecord *rr;
5325 rr = ExpectedAnswers;
5326 ExpectedAnswers = rr->NextInKAList;
5327 rr->NextInKAList = mDNSNULL;
5328
5329 // For non-truncated queries, we can definitively say that we should expect
5330 // to be seeing a response for any records still left in the ExpectedAnswers list
5331 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5332 if (rr->UnansweredQueries == 0 || m->timenow - rr->LastUnansweredTime >= mDNSPlatformOneSecond)
5333 {
5334 rr->UnansweredQueries++;
5335 rr->LastUnansweredTime = m->timenow;
5336 if (rr->UnansweredQueries > 1)
5337 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
5338 rr->UnansweredQueries, rr->MPUnansweredQ, rr->MPUnansweredKA, GetRRDisplayString(m, rr));
5339 SetNextCacheCheckTime(m, rr);
5340 }
5341
5342 // If we've seen multiple unanswered queries for this record,
5343 // then mark it to expire in five seconds if we don't get a response by then.
5344 if (rr->UnansweredQueries >= MaxUnansweredQueries)
5345 {
5346 // Only show debugging message if this record was not about to expire anyway
5347 if (RRExpireTime(rr) - m->timenow > 4 * mDNSPlatformOneSecond)
5348 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5349 rr->UnansweredQueries, rr->MPUnansweredQ, rr->MPUnansweredKA, GetRRDisplayString(m, rr));
5350 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForNoAnswer);
5351 }
5352 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
5353 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
5354 // possible packet loss of up to 20% of the additional KA packets.)
5355 else if (rr->MPUnansweredQ * 4 > rr->MPUnansweredKA * 5 + 8)
5356 {
5357 // We want to do this conservatively.
5358 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
5359 // then we don't want them to all hit the network simultaneously with their final expiration queries.
5360 // By setting the record to expire in four minutes, we achieve two things:
5361 // (a) the 90-95% final expiration queries will be less bunched together
5362 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
5363 mDNSu32 remain = (mDNSu32)(RRExpireTime(rr) - m->timenow) / 4;
5364 if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
5365 remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
5366
5367 // Only show debugging message if this record was not about to expire anyway
5368 if (RRExpireTime(rr) - m->timenow > 4 * mDNSPlatformOneSecond)
5369 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5370 rr->UnansweredQueries, rr->MPUnansweredQ, rr->MPUnansweredKA, GetRRDisplayString(m, rr));
5371
5372 if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
5373 rr->UnansweredQueries++; // Treat this as equivalent to one definite unanswered query
5374 rr->MPUnansweredQ = 0; // Clear MPQ/MPKA statistics
5375 rr->MPUnansweredKA = 0;
5376 rr->MPExpectingKA = mDNSfalse;
5377
5378 if (remain < kDefaultReconfirmTimeForNoAnswer)
5379 remain = kDefaultReconfirmTimeForNoAnswer;
5380 mDNS_Reconfirm_internal(m, rr, remain);
5381 }
5382 }
5383
5384 while (DupQuestions)
5385 {
5386 int i;
5387 DNSQuestion *q = DupQuestions;
5388 DupQuestions = q->NextInDQList;
5389 q->NextInDQList = mDNSNULL;
5390 i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
5391 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
5392 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
5393 }
5394
5395 return(responseptr);
5396 }
5397
5398 mDNSlocal mDNSBool AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
5399 {
5400 NetworkInterfaceInfo *intf;
5401
5402 if (addr->type == mDNSAddrType_IPv4)
5403 {
5404 if (addr->ip.v4.b[0] == 169 && addr->ip.v4.b[1] == 254) return(mDNStrue);
5405 for (intf = m->HostInterfaces; intf; intf = intf->next)
5406 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID)
5407 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
5408 return(mDNStrue);
5409 }
5410
5411 if (addr->type == mDNSAddrType_IPv6)
5412 {
5413 if (addr->ip.v6.b[0] == 0xFE && addr->ip.v6.b[1] == 0x80) return(mDNStrue);
5414 for (intf = m->HostInterfaces; intf; intf = intf->next)
5415 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID)
5416 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
5417 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
5418 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
5419 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
5420 return(mDNStrue);
5421 }
5422
5423 return(mDNSfalse);
5424 }
5425
5426 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
5427 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
5428 const mDNSInterfaceID InterfaceID)
5429 {
5430 if (mDNSAddrIsDNSMulticast(dstaddr) || AddressIsLocalSubnet(m, InterfaceID, srcaddr))
5431 {
5432 DNSMessage response;
5433 const mDNSu8 *responseend = mDNSNULL;
5434
5435 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",
5436 srcaddr, (mDNSu16)srcport.b[0]<<8 | srcport.b[1],
5437 dstaddr, (mDNSu16)dstport.b[0]<<8 | dstport.b[1],
5438 InterfaceID,
5439 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
5440 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
5441 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
5442 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? "" : "s");
5443
5444 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
5445 (srcport.NotAnInteger != MulticastDNSPort.NotAnInteger), mDNSAddrIsDNSMulticast(dstaddr), &response);
5446
5447 if (responseend) // If responseend is non-null, that means we built a unicast response packet
5448 {
5449 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
5450 response.h.numQuestions, response.h.numQuestions == 1 ? "" : "s",
5451 response.h.numAnswers, response.h.numAnswers == 1 ? "" : "s",
5452 response.h.numAdditionals, response.h.numAdditionals == 1 ? "" : "s",
5453 srcaddr, (mDNSu16)srcport.b[0]<<8 | srcport.b[1], InterfaceID, srcaddr->type);
5454 mDNSSendDNSMessage(m, &response, responseend, InterfaceID, dstport, srcaddr, srcport);
5455 }
5456 }
5457 }
5458
5459 // NOTE: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
5460 // the record list and/or question list.
5461 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5462 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
5463 const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSAddr *dstaddr,
5464 const mDNSInterfaceID InterfaceID)
5465 {
5466 int i;
5467 const mDNSu8 *ptr = LocateAnswers(response, end); // We ignore questions (if any) in a DNS response packet
5468 CacheRecord *CacheFlushRecords = mDNSNULL;
5469 CacheRecord **cfp = &CacheFlushRecords;
5470
5471 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
5472 // to guard against spoof responses, then the only credible protection against that is cryptographic
5473 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
5474 int totalrecords = response->h.numAnswers + response->h.numAuthorities + response->h.numAdditionals;
5475
5476 (void)srcaddr; // Currently used only for display in debugging message
5477
5478 verbosedebugf("Received Response from %#-15a addressed to %#-15a on %p with %2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s",
5479 srcaddr, dstaddr, InterfaceID,
5480 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
5481 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
5482 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
5483 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
5484
5485 // If we get a unicast response when we weren't expecting one, then we assume it is someone trying to spoof us
5486 if (!mDNSAddrIsDNSMulticast(dstaddr))
5487 if (!AddressIsLocalSubnet(m, InterfaceID, srcaddr) || (mDNSu32)(m->timenow - m->ExpectUnicastResponse) > (mDNSu32)(mDNSPlatformOneSecond*2))
5488 {
5489 debugf("** Ignored apparent spoof mDNS Response from %#-15a to %#-15a on %p with %2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s",
5490 srcaddr, dstaddr, InterfaceID,
5491 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
5492 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
5493 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
5494 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
5495 return;
5496 }
5497
5498 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
5499 {
5500 LargeCacheRecord pkt;
5501 const mDNSu8 RecordType = (mDNSu8)((i < response->h.numAnswers) ? kDNSRecordTypePacketAns : kDNSRecordTypePacketAdd);
5502 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &pkt);
5503 if (!ptr) break; // Break out of the loop and clean up our CacheFlushRecords list before exiting
5504
5505 // 1. Check that this packet resource record does not conflict with any of ours
5506 if (m->CurrentRecord) LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set");
5507 m->CurrentRecord = m->ResourceRecords;
5508 while (m->CurrentRecord)
5509 {
5510 AuthRecord *rr = m->CurrentRecord;
5511 m->CurrentRecord = rr->next;
5512 if (PacketRRMatchesSignature(&pkt.r, rr)) // If interface, name, type (if verified) and class match...
5513 {
5514 // ... check to see if rdata is identical
5515 if (SameRData(&pkt.r.resrec, &rr->resrec))
5516 {
5517 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
5518 if (pkt.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
5519 {
5520 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
5521 if (rr->ImmedAnswer == InterfaceID) rr->ImmedAnswer = mDNSNULL;
5522 }
5523 else
5524 {
5525 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
5526 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
5527 }
5528 }
5529 else
5530 {
5531 // else, the packet RR has different rdata -- check to see if this is a conflict
5532 if (pkt.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &pkt.r))
5533 {
5534 debugf("mDNSCoreReceiveResponse: Our Record: %08X %08X %s", rr-> resrec.rdatahash, rr-> resrec.rdnamehash, GetRRDisplayString(m, rr));
5535 debugf("mDNSCoreReceiveResponse: Pkt Record: %08X %08X %s", pkt.r.resrec.rdatahash, pkt.r.resrec.rdnamehash, GetRRDisplayString(m, &pkt.r));
5536
5537 // If this record is marked DependentOn another record for conflict detection purposes,
5538 // then *that* record has to be bumped back to probing state to resolve the conflict
5539 while (rr->DependentOn) rr = rr->DependentOn;
5540
5541 // If we've just whacked this record's ProbeCount, don't need to do it again
5542 if (rr->ProbeCount <= DefaultProbeCountForTypeUnique)
5543 {
5544 // If we'd previously verified this record, put it back to probing state and try again
5545 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
5546 {
5547 debugf("mDNSCoreReceiveResponse: Reseting to Probing: %##s (%s)", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
5548 rr->resrec.RecordType = kDNSRecordTypeUnique;
5549 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
5550 rr->ThisAPInterval = DefaultAPIntervalForRecordType(kDNSRecordTypeUnique);
5551 InitializeLastAPTime(m, rr);
5552 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
5553 }
5554 // If we're probing for this record, we just failed
5555 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
5556 {
5557 debugf("mDNSCoreReceiveResponse: Will rename %##s (%s)", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
5558 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
5559 }
5560 // We assumed this record must be unique, but we were wrong.
5561 // (e.g. There are two mDNSResponders on the same machine giving
5562 // different answers for the reverse mapping record.)
5563 // This is simply a misconfiguration, and we don't try to recover from it.
5564 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
5565 {
5566 debugf("mDNSCoreReceiveResponse: Unexpected conflict on %##s (%s) -- discarding our record",
5567 rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
5568 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
5569 }
5570 else
5571 debugf("mDNSCoreReceiveResponse: Unexpected record type %X %##s (%s)",
5572 rr->resrec.RecordType, rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype));
5573 }
5574 }
5575 // Else, matching signature, different rdata, but not a considered a conflict.
5576 // If the packet record has the cache-flush bit set, then we check to see if we have to re-assert our record(s)
5577 // to rescue them (see note about "multi-homing and bridged networks" at the end of this function).
5578 else if ((pkt.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
5579 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
5580 }
5581 }
5582 }
5583
5584 // 2. See if we want to add this packet resource record to our cache
5585 if (m->rrcache_size) // Only try to cache answers if we have a cache to put them in
5586 {
5587 mDNSu32 slot = HashSlot(&pkt.r.resrec.name);
5588 CacheRecord *rr;
5589 // 2a. Check if this packet resource record is already in our cache
5590 for (rr = m->rrcache_hash[slot]; rr; rr=rr->next)
5591 {
5592 // If we found this exact resource record, refresh its TTL
5593 if (rr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&pkt.r.resrec, &rr->resrec))
5594 {
5595 if (pkt.r.resrec.rdlength > InlineCacheRDSize)
5596 verbosedebugf("Found record size %5d interface %p already in cache: %s",
5597 pkt.r.resrec.rdlength, InterfaceID, GetRRDisplayString(m, &pkt.r));
5598 rr->TimeRcvd = m->timenow;
5599
5600 if (pkt.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
5601 {
5602 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
5603 if (rr->NextInCFList == mDNSNULL && cfp != &rr->NextInCFList)
5604 { *cfp = rr; cfp = &rr->NextInCFList; }
5605
5606 // If this packet record is marked unique, and our previous cached copy was not, then fix it
5607 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
5608 {
5609 DNSQuestion *q;
5610 for (q = m->Questions; q; q=q->next) if (ResourceRecordAnswersQuestion(&rr->resrec, q)) q->UniqueAnswers++;
5611 rr->resrec.RecordType = pkt.r.resrec.RecordType;
5612 }
5613 }
5614
5615 if (pkt.r.resrec.rroriginalttl > 0)
5616 {
5617 rr->resrec.rroriginalttl = pkt.r.resrec.rroriginalttl;
5618 rr->UnansweredQueries = 0;
5619 rr->MPUnansweredQ = 0;
5620 rr->MPUnansweredKA = 0;
5621 rr->MPExpectingKA = mDNSfalse;
5622 }
5623 else
5624 {
5625 // If the packet TTL is zero, that means we're deleting this record.
5626 // To give other hosts on the network a chance to protest, we push the deletion
5627 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
5628 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
5629 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
5630 rr->resrec.rroriginalttl = 1;
5631 rr->UnansweredQueries = MaxUnansweredQueries;
5632 }
5633 SetNextCacheCheckTime(m, rr);
5634 break;
5635 }
5636 }
5637
5638 // If packet resource record not in our cache, add it now
5639 // (unless it is just a deletion of a record we never had, in which case we don't care)
5640 if (!rr && pkt.r.resrec.rroriginalttl > 0)
5641 {
5642 rr = GetFreeCacheRR(m, pkt.r.resrec.rdlength);
5643 if (!rr) debugf("No cache space to add record for %#s", pkt.r.resrec.name.c);
5644 else
5645 {
5646 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
5647 *rr = pkt.r;
5648 rr->resrec.rdata = saveptr; // and then restore it after the structure assignment
5649 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
5650 { *cfp = rr; cfp = &rr->NextInCFList; }
5651 // If this is an oversized record with external storage allocated, copy rdata to external storage
5652 if (pkt.r.resrec.rdlength > InlineCacheRDSize)
5653 mDNSPlatformMemCopy(pkt.r.resrec.rdata, rr->resrec.rdata, sizeofRDataHeader + pkt.r.resrec.rdlength);
5654 rr->next = mDNSNULL; // Clear 'next' pointer
5655 *(m->rrcache_tail[slot]) = rr; // Append this record to tail of cache slot list
5656 m->rrcache_tail[slot] = &(rr->next); // Advance tail pointer
5657 m->rrcache_used[slot]++;
5658 //debugf("Adding RR %##s to cache (%d)", pkt.r.name.c, m->rrcache_used);
5659 CacheRecordAdd(m, rr);
5660 // MUST do this AFTER CacheRecordAdd(), because that's what sets CRActiveQuestion for us
5661 SetNextCacheCheckTime(m, rr);
5662 }
5663 }
5664 }
5665 }
5666
5667 // If we've just received one or more records with their cache flush bits set,
5668 // then scan that cache slot to see if there are any old stale records we need to flush
5669 while (CacheFlushRecords)
5670 {
5671 CacheRecord *r1 = CacheFlushRecords, *r2;
5672 CacheFlushRecords = CacheFlushRecords->NextInCFList;
5673 r1->NextInCFList = mDNSNULL;
5674 for (r2 = m->rrcache_hash[HashSlot(&r1->resrec.name)]; r2; r2=r2->next)
5675 if (SameResourceRecordSignature(&r1->resrec, &r2->resrec) && m->timenow - r2->TimeRcvd > mDNSPlatformOneSecond)
5676 {
5677 verbosedebugf("Cache flush %p X %p %##s (%s)", r1, r2, r2->resrec.name.c, DNSTypeName(r2->resrec.rrtype));
5678 // We set stale records to expire in one second.
5679 // This gives the owner a chance to rescue it if necessary.
5680 // This is important in the case of multi-homing and bridged networks:
5681 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
5682 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
5683 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
5684 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
5685 // By delaying the deletion by one second, we give X a change to notice that this bridging has
5686 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
5687 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
5688 // final expiration queries for this record.
5689 r2->resrec.rroriginalttl = 1;
5690 r2->TimeRcvd = m->timenow;
5691 r2->UnansweredQueries = MaxUnansweredQueries;
5692 SetNextCacheCheckTime(m, r2);
5693 }
5694 }
5695 }
5696
5697 mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
5698 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *const dstaddr, const mDNSIPPort dstport,
5699 const mDNSInterfaceID InterfaceID, mDNSu8 unusedttl)
5700 {
5701 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
5702 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
5703 const mDNSu8 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
5704
5705 (void)unusedttl;
5706
5707 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
5708 mDNSu8 *ptr = (mDNSu8 *)&msg->h.numQuestions;
5709 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
5710 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
5711 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
5712 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
5713
5714 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
5715
5716 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
5717 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
5718 if (!mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
5719
5720 mDNS_Lock(m);
5721 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
5722 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, dstaddr, InterfaceID);
5723 else debugf("Unknown DNS packet type %02X%02X (ignored)", msg->h.flags.b[0], msg->h.flags.b[1]);
5724
5725 // Packet reception often causes a change to the task list:
5726 // 1. Inbound queries can cause us to need to send responses
5727 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
5728 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
5729 // 4. Response packets that answer questions may cause our client to issue new questions
5730 mDNS_Unlock(m);
5731 }
5732
5733 // ***************************************************************************
5734 #if COMPILER_LIKES_PRAGMA_MARK
5735 #pragma mark -
5736 #pragma mark -
5737 #pragma mark - Searcher Functions
5738 #endif
5739
5740 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
5741 {
5742 DNSQuestion *q;
5743 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
5744 // This prevents circular references, where two questions are each marked as a duplicate of the other.
5745 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
5746 // further in the list.
5747 for (q = m->Questions; q && q != question; q=q->next) // Scan our list of questions
5748 if (q->InterfaceID == question->InterfaceID && // for another question with the same InterfaceID,
5749 q->qtype == question->qtype && // type,
5750 q->qclass == question->qclass && // class,
5751 q->qnamehash == question->qnamehash &&
5752 SameDomainName(&q->qname, &question->qname)) // and name
5753 return(q);
5754 return(mDNSNULL);
5755 }
5756
5757 // This is called after a question is deleted, in case other identical questions were being
5758 // suppressed as duplicates
5759 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, const DNSQuestion *const question)
5760 {
5761 DNSQuestion *q;
5762 for (q = m->Questions; q; q=q->next) // Scan our list of questions
5763 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
5764 {
5765 q->ThisQInterval = question->ThisQInterval;
5766 q->LastQTime = question->LastQTime;
5767 q->RecentAnswers = 0;
5768 q->DuplicateOf = FindDuplicateQuestion(m, q);
5769 q->LastQTxTime = question->LastQTxTime;
5770 SetNextQueryTime(m,q);
5771 }
5772 }
5773
5774 mDNSlocal mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
5775 {
5776 #if TEST_LOCALONLY_FOR_EVERYTHING
5777 question->InterfaceID = (mDNSInterfaceID)~0;
5778 #endif
5779 if (m->rrcache_size == 0) // Can't do queries if we have no cache space allocated
5780 return(mStatus_NoCache);
5781 else
5782 {
5783 int i;
5784 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
5785 DNSQuestion **q = &m->Questions;
5786 if (question->InterfaceID == ((mDNSInterfaceID)~0)) q = &m->LocalOnlyQuestions;
5787 while (*q && *q != question) q=&(*q)->next;
5788
5789 if (*q)
5790 {
5791 LogMsg("Error! Tried to add a question %##s (%s) that's already in the active list",
5792 question->qname.c, DNSTypeName(question->qtype));
5793 return(mStatus_AlreadyRegistered);
5794 }
5795
5796 // If this question is referencing a specific interface, make sure it exists
5797 if (question->InterfaceID && question->InterfaceID != ((mDNSInterfaceID)~0))
5798 {
5799 NetworkInterfaceInfo *intf;
5800 for (intf = m->HostInterfaces; intf; intf = intf->next)
5801 if (intf->InterfaceID == question->InterfaceID) break;
5802 if (!intf)
5803 {
5804 debugf("mDNS_StartQuery_internal: Question %##s InterfaceID %p not found", question->qname.c, question->InterfaceID);
5805 return(mStatus_BadReferenceErr);
5806 }
5807 }
5808
5809 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
5810 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
5811 // be a waste. For that reason, we schedule our first query to go out in half a second. If AnswerNewQuestion() finds
5812 // that we have *no* relevant answers currently in our cache, then it will accelerate that to go out immediately.
5813 if (!ValidateDomainName(&question->qname))
5814 {
5815 LogMsg("Attempt to start query with invalid qname %##s %s", question->qname.c, DNSTypeName(question->qtype));
5816 return(mStatus_Invalid);
5817 }
5818
5819 if (!m->RandomQueryDelay) m->RandomQueryDelay = 1 + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
5820
5821 question->next = mDNSNULL;
5822 question->qnamehash = DomainNameHashValue(&question->qname); // MUST do this before FindDuplicateQuestion()
5823 question->ThisQInterval = InitialQuestionInterval * 2; // MUST be > zero for an active question
5824 question->LastQTime = m->timenow - m->RandomQueryDelay; // Avoid inter-machine synchronization
5825 question->RecentAnswers = 0;
5826 question->CurrentAnswers = 0;
5827 question->LargeAnswers = 0;
5828 question->UniqueAnswers = 0;
5829 question->DuplicateOf = FindDuplicateQuestion(m, question);
5830 question->NextInDQList = mDNSNULL;
5831 for (i=0; i<DupSuppressInfoSize; i++)
5832 question->DupSuppress[i].InterfaceID = mDNSNULL;
5833 // question->InterfaceID must be already set by caller
5834 question->SendQNow = mDNSNULL;
5835 question->SendOnAll = mDNSfalse;
5836 question->LastQTxTime = m->timenow;
5837
5838 if (!question->DuplicateOf)
5839 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) started",
5840 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, question);
5841 else
5842 verbosedebugf("mDNS_StartQuery_internal: Question %##s %s %p (%p) duplicate of (%p)",
5843 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, question, question->DuplicateOf);
5844
5845 *q = question;
5846 if (question->InterfaceID == ((mDNSInterfaceID)~0))
5847 {
5848 if (!m->NewLocalOnlyQuestions) m->NewLocalOnlyQuestions = question;
5849 }
5850 else
5851 {
5852 if (!m->NewQuestions) m->NewQuestions = question;
5853 SetNextQueryTime(m,question);
5854 }
5855
5856 return(mStatus_NoError);
5857 }
5858 }
5859
5860 mDNSlocal mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
5861 {
5862 CacheRecord *rr;
5863 DNSQuestion **q = &m->Questions;
5864 if (question->InterfaceID == ((mDNSInterfaceID)~0)) q = &m->LocalOnlyQuestions;
5865 while (*q && *q != question) q=&(*q)->next;
5866 if (*q) *q = (*q)->next;
5867 else
5868 {
5869 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
5870 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
5871 question->qname.c, DNSTypeName(question->qtype));
5872 return(mStatus_BadReferenceErr);
5873 }
5874
5875 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
5876 UpdateQuestionDuplicates(m, question);
5877 // But don't trash ThisQInterval until afterwards.
5878 question->ThisQInterval = -1;
5879
5880 // If there are any cache records referencing this as their active question, then see if any other
5881 // question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
5882 for (rr = m->rrcache_hash[HashSlot(&question->qname)]; rr; rr=rr->next)
5883 {
5884 if (rr->CRActiveQuestion == question)
5885 {
5886 DNSQuestion *q;
5887 for (q = m->Questions; q; q=q->next) // Scan our list of questions
5888 if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
5889 break;
5890 verbosedebugf("mDNS_StopQuery_internal: Cache RR %##s (%s) setting CRActiveQuestion to %X", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), q);
5891 rr->CRActiveQuestion = q; // Question used to be active; new value may or may not be null
5892 if (!q) m->rrcache_active--; // If no longer active, decrement rrcache_active count
5893 }
5894 }
5895
5896 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv()is about to look at,
5897 // bump its pointer forward one question.
5898 if (m->CurrentQuestion == question)
5899 {
5900 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
5901 question->qname.c, DNSTypeName(question->qtype));
5902 m->CurrentQuestion = question->next;
5903 }
5904
5905 if (m->NewQuestions == question)
5906 {
5907 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
5908 question->qname.c, DNSTypeName(question->qtype));
5909 m->NewQuestions = question->next;
5910 }
5911
5912 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
5913
5914 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
5915 question->next = mDNSNULL;
5916 return(mStatus_NoError);
5917 }
5918
5919 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
5920 {
5921 mStatus status;
5922 mDNS_Lock(m);
5923 status = mDNS_StartQuery_internal(m, question);
5924 mDNS_Unlock(m);
5925 return(status);
5926 }
5927
5928 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
5929 {
5930 mStatus status;
5931 mDNS_Lock(m);
5932 status = mDNS_StopQuery_internal(m, question);
5933 mDNS_Unlock(m);
5934 return(status);
5935 }
5936
5937 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const rr)
5938 {
5939 mStatus status;
5940 mDNS_Lock(m);
5941 status = mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForNoAnswer);
5942 mDNS_Unlock(m);
5943 return(status);
5944 }
5945
5946 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
5947 {
5948 mStatus status = mStatus_BadReferenceErr;
5949 CacheRecord *cr;
5950 mDNS_Lock(m);
5951 cr = FindIdenticalRecordInCache(m, rr);
5952 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
5953 mDNS_Unlock(m);
5954 return(status);
5955 }
5956
5957 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
5958 const domainname *const srv, const domainname *const domain,
5959 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
5960 {
5961 question->ThisQInterval = -1; // Indicate that query is not yet active
5962 question->InterfaceID = InterfaceID;
5963 question->qtype = kDNSType_PTR;
5964 question->qclass = kDNSClass_IN;
5965 question->QuestionCallback = Callback;
5966 question->QuestionContext = Context;
5967 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) return(mStatus_BadParamErr);
5968 return(mDNS_StartQuery(m, question));
5969 }
5970
5971 mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, mDNSBool AddRecord)
5972 {
5973 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
5974 mDNSBool PortChanged = (mDNSBool)(query->info->port.NotAnInteger != answer->rdata->u.srv.port.NotAnInteger);
5975 if (!AddRecord) return;
5976 if (answer->rrtype != kDNSType_SRV) return;
5977
5978 query->info->port = answer->rdata->u.srv.port;
5979
5980 // If this is our first answer, then set the GotSRV flag and start the address query
5981 if (!query->GotSRV)
5982 {
5983 query->GotSRV = mDNStrue;
5984 query->qAv4.InterfaceID = answer->InterfaceID;
5985 AssignDomainName(query->qAv4.qname, answer->rdata->u.srv.target);
5986 query->qAv6.InterfaceID = answer->InterfaceID;
5987 AssignDomainName(query->qAv6.qname, answer->rdata->u.srv.target);
5988 mDNS_StartQuery_internal(m, &query->qAv4);
5989 mDNS_StartQuery_internal(m, &query->qAv6);
5990 }
5991 // If this is not our first answer, only re-issue the address query if the target host name has changed
5992 else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
5993 !SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
5994 {
5995 mDNS_StopQuery_internal(m, &query->qAv4);
5996 mDNS_StopQuery_internal(m, &query->qAv6);
5997 if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
5998 {
5999 // If we get here, it means:
6000 // 1. This is not our first SRV answer
6001 // 2. The interface ID is different, but the target host and port are the same
6002 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
6003 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
6004 query->qAv4.InterfaceID = query->qSRV.InterfaceID; // Will be mDNSInterface_Any, or a specific interface
6005 query->qAv6.InterfaceID = query->qSRV.InterfaceID;
6006 }
6007 else
6008 {
6009 query->qAv4.InterfaceID = answer->InterfaceID;
6010 AssignDomainName(query->qAv4.qname, answer->rdata->u.srv.target);
6011 query->qAv6.InterfaceID = answer->InterfaceID;
6012 AssignDomainName(query->qAv6.qname, answer->rdata->u.srv.target);
6013 }
6014 debugf("FoundServiceInfoSRV: Restarting address queries for %##s", query->qAv4.qname.c);
6015 mDNS_StartQuery_internal(m, &query->qAv4);
6016 mDNS_StartQuery_internal(m, &query->qAv6);
6017 }
6018 else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
6019 {
6020 if (++query->Answers >= 100)
6021 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
6022 query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
6023 ((mDNSu16)answer->rdata->u.srv.port.b[0] << 8) | answer->rdata->u.srv.port.b[1]);
6024 query->ServiceInfoQueryCallback(m, query);
6025 }
6026 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
6027 // callback function is allowed to do anything, including deleting this query and freeing its memory.
6028 }
6029
6030 mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, mDNSBool AddRecord)
6031 {
6032 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
6033 if (!AddRecord) return;
6034 if (answer->rrtype != kDNSType_TXT) return;
6035 if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
6036
6037 query->GotTXT = mDNStrue;
6038 query->info->TXTlen = answer->rdlength;
6039 mDNSPlatformMemCopy(answer->rdata->u.txt.c, query->info->TXTinfo, answer->rdlength);
6040
6041 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
6042
6043 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
6044 // callback function is allowed to do anything, including deleting this query and freeing its memory.
6045 if (query->ServiceInfoQueryCallback && query->GotADD)
6046 {
6047 if (++query->Answers >= 100)
6048 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
6049 query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
6050 query->ServiceInfoQueryCallback(m, query);
6051 }
6052 }
6053
6054 mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, mDNSBool AddRecord)
6055 {
6056 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
6057 if (!AddRecord) return;
6058
6059 if (answer->rrtype == kDNSType_A)
6060 {
6061 query->info->ip.type = mDNSAddrType_IPv4;
6062 query->info->ip.ip.v4 = answer->rdata->u.ip;
6063 }
6064 else if (answer->rrtype == kDNSType_AAAA)
6065 {
6066 query->info->ip.type = mDNSAddrType_IPv6;
6067 query->info->ip.ip.v6 = answer->rdata->u.ipv6;
6068 }
6069 else
6070 {
6071 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name.c, answer->rrtype, DNSTypeName(answer->rrtype));
6072 return;
6073 }
6074
6075 query->GotADD = mDNStrue;
6076 query->info->InterfaceID = answer->InterfaceID;
6077
6078 verbosedebugf("FoundServiceInfo v%d: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
6079
6080 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
6081 // callback function is allowed to do anything, including deleting this query and freeing its memory.
6082 if (query->ServiceInfoQueryCallback && query->GotTXT)
6083 {
6084 if (++query->Answers >= 100)
6085 {
6086 if (answer->rrtype == kDNSType_A)
6087 debugf("**** WARNING **** have given %lu answers for %##s (A) %.4a", query->Answers, query->qSRV.qname.c, &answer->rdata->u.ip);
6088 else
6089 debugf("**** WARNING **** have given %lu answers for %##s (AAAA) %.16a", query->Answers, query->qSRV.qname.c, &answer->rdata->u.ipv6);
6090 }
6091 query->ServiceInfoQueryCallback(m, query);
6092 }
6093 }
6094
6095 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
6096 // If the query is not interface-specific, then InterfaceID may be zero
6097 // Each time the Callback is invoked, the remainder of the fields will have been filled in
6098 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
6099 mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
6100 ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
6101 {
6102 mStatus status;
6103 mDNS_Lock(m);
6104
6105 query->qSRV.ThisQInterval = -1; // This question not yet in the question list
6106 query->qSRV.InterfaceID = info->InterfaceID;
6107 AssignDomainName(query->qSRV.qname, info->name);
6108 query->qSRV.qtype = kDNSType_SRV;
6109 query->qSRV.qclass = kDNSClass_IN;
6110 query->qSRV.QuestionCallback = FoundServiceInfoSRV;
6111 query->qSRV.QuestionContext = query;
6112
6113 query->qTXT.ThisQInterval = -1; // This question not yet in the question list
6114 query->qTXT.InterfaceID = info->InterfaceID;
6115 AssignDomainName(query->qTXT.qname, info->name);
6116 query->qTXT.qtype = kDNSType_TXT;
6117 query->qTXT.qclass = kDNSClass_IN;
6118 query->qTXT.QuestionCallback = FoundServiceInfoTXT;
6119 query->qTXT.QuestionContext = query;
6120
6121 query->qAv4.ThisQInterval = -1; // This question not yet in the question list
6122 query->qAv4.InterfaceID = info->InterfaceID;
6123 query->qAv4.qname.c[0] = 0;
6124 query->qAv4.qtype = kDNSType_A;
6125 query->qAv4.qclass = kDNSClass_IN;
6126 query->qAv4.QuestionCallback = FoundServiceInfo;
6127 query->qAv4.QuestionContext = query;
6128
6129 query->qAv6.ThisQInterval = -1; // This question not yet in the question list
6130 query->qAv6.InterfaceID = info->InterfaceID;
6131 query->qAv6.qname.c[0] = 0;
6132 query->qAv6.qtype = kDNSType_AAAA;
6133 query->qAv6.qclass = kDNSClass_IN;
6134 query->qAv6.QuestionCallback = FoundServiceInfo;
6135 query->qAv6.QuestionContext = query;
6136
6137 query->GotSRV = mDNSfalse;
6138 query->GotTXT = mDNSfalse;
6139 query->GotADD = mDNSfalse;
6140 query->Answers = 0;
6141
6142 query->info = info;
6143 query->ServiceInfoQueryCallback = Callback;
6144 query->ServiceInfoQueryContext = Context;
6145
6146 // info->name = Must already be set up by client
6147 // info->interface = Must already be set up by client
6148 info->ip = zeroAddr;
6149 info->port = zeroIPPort;
6150 info->TXTlen = 0;
6151
6152 status = mDNS_StartQuery_internal(m, &query->qSRV);
6153 if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
6154 if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
6155
6156 mDNS_Unlock(m);
6157 return(status);
6158 }
6159
6160 mDNSexport void mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *query)
6161 {
6162 mDNS_Lock(m);
6163 if (query->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &query->qSRV);
6164 if (query->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &query->qTXT);
6165 if (query->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &query->qAv4);
6166 if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &query->qAv6);
6167 mDNS_Unlock(m);
6168 }
6169
6170 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType,
6171 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
6172 {
6173 MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType]);
6174 question->InterfaceID = InterfaceID;
6175 question->qtype = kDNSType_PTR;
6176 question->qclass = kDNSClass_IN;
6177 question->QuestionCallback = Callback;
6178 question->QuestionContext = Context;
6179
6180 // No sense doing this until we actually support unicast query/update
6181 //return(mDNS_StartQuery(m, question));
6182 (void)m; // Unused
6183 return(mStatus_NoError);
6184 }
6185
6186 // ***************************************************************************
6187 #if COMPILER_LIKES_PRAGMA_MARK
6188 #pragma mark -
6189 #pragma mark - Responder Functions
6190 #endif
6191
6192 // Set up a AuthRecord with sensible default values.
6193 // These defaults may be overwritten with new values before mDNS_Register is called
6194 mDNSexport void mDNS_SetupResourceRecord(AuthRecord *rr, RData *RDataStorage, mDNSInterfaceID InterfaceID,
6195 mDNSu16 rrtype, mDNSu32 ttl, mDNSu8 RecordType, mDNSRecordCallback Callback, void *Context)
6196 {
6197 // Don't try to store a TTL bigger than we can represent in platform time units
6198 if (ttl > 0x7FFFFFFFUL / mDNSPlatformOneSecond)
6199 ttl = 0x7FFFFFFFUL / mDNSPlatformOneSecond;
6200 else if (ttl == 0) // And Zero TTL is illegal
6201 ttl = kDefaultTTLforShared;
6202
6203 // Field Group 1: Persistent metadata for Authoritative Records
6204 rr->Additional1 = mDNSNULL;
6205 rr->Additional2 = mDNSNULL;
6206 rr->DependentOn = mDNSNULL;
6207 rr->RRSet = mDNSNULL;
6208 rr->RecordCallback = Callback;
6209 rr->RecordContext = Context;
6210
6211 rr->resrec.RecordType = RecordType;
6212 rr->HostTarget = mDNSfalse;
6213
6214 // Field Group 2: Transient state for Authoritative Records (set in mDNS_Register_internal)
6215 // Field Group 3: Transient state for Cache Records (set in mDNS_Register_internal)
6216
6217 // Field Group 4: The actual information pertaining to this resource record
6218 rr->resrec.InterfaceID = InterfaceID;
6219 rr->resrec.name.c[0] = 0; // MUST be set by client
6220 rr->resrec.rrtype = rrtype;
6221 rr->resrec.rrclass = kDNSClass_IN;
6222 rr->resrec.rroriginalttl = ttl;
6223 // rr->resrec.rdlength = MUST set by client and/or in mDNS_Register_internal
6224 // rr->resrec.rdestimate = set in mDNS_Register_internal
6225 // rr->resrec.rdata = MUST be set by client
6226
6227 if (RDataStorage)
6228 rr->resrec.rdata = RDataStorage;
6229 else
6230 {
6231 rr->resrec.rdata = &rr->rdatastorage;
6232 rr->resrec.rdata->MaxRDLength = sizeof(RDataBody);
6233 }
6234 }
6235
6236 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
6237 {
6238 mStatus status;
6239 mDNS_Lock(m);
6240 status = mDNS_Register_internal(m, rr);
6241 mDNS_Unlock(m);
6242 return(status);
6243 }
6244
6245 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
6246 const mDNSu16 newrdlength,
6247 RData *const newrdata, mDNSRecordUpdateCallback *Callback)
6248 {
6249 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
6250 { LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(m, &rr->resrec, &newrdata->u)); return(mStatus_Invalid); }
6251
6252 mDNS_Lock(m);
6253
6254 // If TTL is unspecified, leave TTL unchanged
6255 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
6256
6257 // If we already have an update queued up which has not gone through yet,
6258 // give the client a chance to free that memory
6259 if (rr->NewRData)
6260 {
6261 RData *n = rr->NewRData;
6262 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
6263 if (rr->UpdateCallback)
6264 rr->UpdateCallback(m, rr, n); // ...and let the client free this memory, if necessary
6265 }
6266
6267 if (rr->AnnounceCount < ReannounceCount)
6268 rr->AnnounceCount = ReannounceCount;
6269 rr->ThisAPInterval = DefaultAPIntervalForRecordType(rr->resrec.RecordType);
6270 InitializeLastAPTime(m, rr);
6271 rr->NewRData = newrdata;
6272 rr->newrdlength = newrdlength;
6273 rr->UpdateCallback = Callback;
6274 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
6275 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = (m->timenow + mDNSPlatformOneSecond * 60) | 1;
6276 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
6277 if (rr->UpdateCredits <= 5)
6278 {
6279 mDNSs32 delay = 1 << (5 - rr->UpdateCredits);
6280 if (!rr->UpdateBlocked) rr->UpdateBlocked = (m->timenow + delay * mDNSPlatformOneSecond) | 1;
6281 rr->LastAPTime = rr->UpdateBlocked;
6282 rr->ThisAPInterval *= 4;
6283 LogMsg("Excessive update rate for %##s; delaying announcement by %d seconds", rr->resrec.name.c, delay);
6284 }
6285 rr->resrec.rroriginalttl = newttl;
6286 mDNS_Unlock(m);
6287 return(mStatus_NoError);
6288 }
6289
6290 // NOTE: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
6291 // the record list and/or question list.
6292 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6293 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
6294 {
6295 mStatus status;
6296 mDNS_Lock(m);
6297 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
6298 mDNS_Unlock(m);
6299 return(status);
6300 }
6301
6302 mDNSlocal void HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
6303
6304 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
6305 {
6306 NetworkInterfaceInfo *intf;
6307 for (intf = m->HostInterfaces; intf; intf = intf->next)
6308 if (intf->Advertise) break;
6309 return(intf);
6310 }
6311
6312 mDNSlocal void mDNS_AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
6313 {
6314 char buffer[256];
6315 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
6316 if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
6317
6318 mDNS_SetupResourceRecord(&set->RR_A, mDNSNULL, set->InterfaceID, kDNSType_A, kDefaultTTLforUnique, kDNSRecordTypeUnique, HostNameCallback, set);
6319 mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kDefaultTTLforUnique, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
6320 mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kDefaultTTLforUnique, kDNSRecordTypeUnique, mDNSNULL, mDNSNULL);
6321
6322 // 1. Set up Address record to map from host name ("foo.local.") to IP address
6323 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
6324 AssignDomainName(set->RR_A.resrec.name, m->hostname);
6325 if (set->ip.type == mDNSAddrType_IPv4)
6326 {
6327 set->RR_A.resrec.rrtype = kDNSType_A;
6328 set->RR_A.resrec.rdata->u.ip = set->ip.ip.v4;
6329 // Note: This is reverse order compared to a normal dotted-decimal IP address
6330 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
6331 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
6332 }
6333 else if (set->ip.type == mDNSAddrType_IPv6)
6334 {
6335 int i;
6336 set->RR_A.resrec.rrtype = kDNSType_AAAA;
6337 set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
6338 for (i = 0; i < 16; i++)
6339 {
6340 static const char hexValues[] = "0123456789ABCDEF";
6341 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
6342 buffer[i * 4 + 1] = '.';
6343 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
6344 buffer[i * 4 + 3] = '.';
6345 }
6346 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
6347 }
6348
6349 MakeDomainNameFromDNSNameString(&set->RR_PTR.resrec.name, buffer);
6350 set->RR_PTR.HostTarget = mDNStrue; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
6351
6352 set->RR_A.RRSet = &primary->RR_A; // May refer to self
6353
6354 mDNS_Register_internal(m, &set->RR_A);
6355 mDNS_Register_internal(m, &set->RR_PTR);
6356
6357 if (m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
6358 {
6359 mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
6360 AssignDomainName(set->RR_HINFO.resrec.name, m->hostname);
6361 set->RR_HINFO.DependentOn = &set->RR_A;
6362 mDNSPlatformMemCopy(&m->HIHardware, p, 1 + (mDNSu32)m->HIHardware.c[0]);
6363 p += 1 + (int)p[0];
6364 mDNSPlatformMemCopy(&m->HISoftware, p, 1 + (mDNSu32)m->HISoftware.c[0]);
6365 mDNS_Register_internal(m, &set->RR_HINFO);
6366 }
6367 else
6368 {
6369 debugf("Not creating HINFO record: platform support layer provided no information");
6370 set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
6371 }
6372 }
6373
6374 mDNSlocal void mDNS_DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
6375 {
6376 NetworkInterfaceInfo *intf;
6377 // If we still have address records referring to this one, update them
6378 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
6379 AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
6380 for (intf = m->HostInterfaces; intf; intf = intf->next)
6381 if (intf->RR_A.RRSet == &set->RR_A)
6382 intf->RR_A.RRSet = A;
6383
6384 // Unregister these records.
6385 // When doing the mDNS_Close processing, we first call mDNS_DeadvertiseInterface for each interface, so by the time the platform
6386 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
6387 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
6388 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
6389 if (set->RR_A. resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
6390 if (set->RR_PTR. resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
6391 if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
6392 }
6393
6394 mDNSexport void mDNS_GenerateFQDN(mDNS *const m)
6395 {
6396 domainname newname;
6397 mDNS_Lock(m);
6398
6399 newname.c[0] = 0;
6400 if (!AppendDomainLabel(&newname, &m->hostlabel)) LogMsg("ERROR! Cannot create dot-local hostname");
6401 if (!AppendLiteralLabelString(&newname, "local")) LogMsg("ERROR! Cannot create dot-local hostname");
6402 if (!SameDomainName(&m->hostname, &newname))
6403 {
6404 NetworkInterfaceInfo *intf;
6405 AuthRecord *rr;
6406
6407 m->hostname = newname;
6408
6409 // 1. Stop advertising our address records on all interfaces
6410 for (intf = m->HostInterfaces; intf; intf = intf->next)
6411 if (intf->Advertise) mDNS_DeadvertiseInterface(m, intf);
6412
6413 // 2. Start advertising our address records using the new name
6414 for (intf = m->HostInterfaces; intf; intf = intf->next)
6415 if (intf->Advertise) mDNS_AdvertiseInterface(m, intf);
6416
6417 // 3. Make sure that any SRV records (and the like) that reference our
6418 // host name in their rdata get updated to reference this new host name
6419 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->HostTarget) SetTargetToHostName(m, rr);
6420 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->HostTarget) SetTargetToHostName(m, rr);
6421 }
6422
6423 mDNS_Unlock(m);
6424 }
6425
6426 mDNSlocal void HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
6427 {
6428 (void)rr; // Unused parameter
6429
6430 #if MDNS_DEBUGMSGS
6431 {
6432 char *msg = "Unknown result";
6433 if (result == mStatus_NoError) msg = "Name registered";
6434 else if (result == mStatus_NameConflict) msg = "Name conflict";
6435 debugf("HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), msg, result);
6436 }
6437 #endif
6438
6439 if (result == mStatus_NoError)
6440 {
6441 // Notify the client that the host name is successfully registered
6442 if (m->MainCallback)
6443 m->MainCallback(m, result);
6444 }
6445 else if (result == mStatus_NameConflict)
6446 {
6447 domainlabel oldlabel = m->hostlabel;
6448
6449 // 1. First give the client callback a chance to pick a new name
6450 if (m->MainCallback)
6451 m->MainCallback(m, mStatus_NameConflict);
6452
6453 // 2. If the client callback didn't do it, add (or increment) an index ourselves
6454 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
6455 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
6456
6457 // 3. Generate the FQDNs from the hostlabel,
6458 // and make sure all SRV records, etc., are updated to reference our new hostname
6459 mDNS_GenerateFQDN(m);
6460 }
6461 }
6462
6463 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
6464 {
6465 NetworkInterfaceInfo *intf;
6466 active->IPv4Available = mDNSfalse;
6467 active->IPv6Available = mDNSfalse;
6468 for (intf = m->HostInterfaces; intf; intf = intf->next)
6469 if (intf->InterfaceID == active->InterfaceID)
6470 {
6471 if (intf->ip.type == mDNSAddrType_IPv4 && intf->TxAndRx) active->IPv4Available = mDNStrue;
6472 if (intf->ip.type == mDNSAddrType_IPv6 && intf->TxAndRx) active->IPv6Available = mDNStrue;
6473 }
6474 }
6475
6476 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set)
6477 {
6478 mDNSBool FirstOfType = mDNStrue;
6479 NetworkInterfaceInfo **p = &m->HostInterfaces;
6480 mDNS_Lock(m);
6481
6482 // Assume this interface will be active
6483 set->InterfaceActive = mDNStrue;
6484 set->IPv4Available = (set->ip.type == mDNSAddrType_IPv4 && set->TxAndRx);
6485 set->IPv6Available = (set->ip.type == mDNSAddrType_IPv6 && set->TxAndRx);
6486
6487 while (*p)
6488 {
6489 if (*p == set)
6490 {
6491 LogMsg("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
6492 mDNS_Unlock(m);
6493 return(mStatus_AlreadyRegistered);
6494 }
6495
6496 // This InterfaceID is already in the list, so mark this interface inactive for now
6497 if ((*p)->InterfaceID == set->InterfaceID)
6498 {
6499 set->InterfaceActive = mDNSfalse;
6500 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
6501 if (set->ip.type == mDNSAddrType_IPv4 && set->TxAndRx) (*p)->IPv4Available = mDNStrue;
6502 if (set->ip.type == mDNSAddrType_IPv6 && set->TxAndRx) (*p)->IPv6Available = mDNStrue;
6503 }
6504
6505 p=&(*p)->next;
6506 }
6507
6508 set->next = mDNSNULL;
6509 *p = set;
6510
6511 debugf("mDNS_RegisterInterface: InterfaceID %p %#a %s", set->InterfaceID, &set->ip,
6512 set->InterfaceActive ?
6513 "not represented in list; marking active and retriggering queries" :
6514 "already represented in list; marking inactive for now");
6515
6516 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6517 // giving the false impression that there's an active representative of this interface when there really isn't.
6518 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
6519 // even if we believe that we previously had an active representative of this interface.
6520 if ((m->KnownBugs & mDNS_KnownBug_PhantomInterfaces) || FirstOfType || set->InterfaceActive)
6521 {
6522 DNSQuestion *q;
6523 AuthRecord *rr;
6524 // Use a small amount of randomness:
6525 // In the case of a network administrator turning on an Ethernet hub so that all the connected machines establish link at
6526 // exactly the same time, we don't want them to all go and hit the network with identical queries at exactly the same moment.
6527 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
6528 for (q = m->Questions; q; q=q->next) // Scan our list of questions
6529 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
6530 { // then reactivate this question
6531 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
6532 q->LastQTime = m->timenow - q->ThisQInterval;
6533 q->RecentAnswers = 0;
6534 if (ActiveQuestion(q)) m->NextScheduledQuery = m->timenow;
6535 }
6536
6537 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
6538 // we now need them to re-probe if necessary, and then re-announce.
6539 for (rr = m->ResourceRecords; rr; rr=rr->next)
6540 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
6541 {
6542 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
6543 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
6544 if (rr->AnnounceCount < ReannounceCount)
6545 rr->AnnounceCount = ReannounceCount;
6546 rr->ThisAPInterval = DefaultAPIntervalForRecordType(rr->resrec.RecordType);
6547 InitializeLastAPTime(m, rr);
6548 }
6549 }
6550
6551 if (set->Advertise)
6552 mDNS_AdvertiseInterface(m, set);
6553
6554 mDNS_Unlock(m);
6555 return(mStatus_NoError);
6556 }
6557
6558 // NOTE: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
6559 // the record list and/or question list.
6560 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6561 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set)
6562 {
6563 NetworkInterfaceInfo **p = &m->HostInterfaces;
6564
6565 mDNSBool revalidate = mDNSfalse;
6566 // If this platform has the "phantom interfaces" known bug (e.g. Jaguar), we have to revalidate records every
6567 // time an interface goes away. Otherwise, when you disconnect the Ethernet cable, the system reports that it
6568 // still has an IPv6 address, and if we don't revalidate those records don't get deleted in a timely fashion.
6569 if (m->KnownBugs & mDNS_KnownBug_PhantomInterfaces) revalidate = mDNStrue;
6570
6571 mDNS_Lock(m);
6572
6573 // Find this record in our list
6574 while (*p && *p != set) p=&(*p)->next;
6575 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
6576
6577 // Unlink this record from our list
6578 *p = (*p)->next;
6579 set->next = mDNSNULL;
6580
6581 if (!set->InterfaceActive)
6582 {
6583 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
6584 NetworkInterfaceInfo *intf;
6585 for (intf = m->HostInterfaces; intf; intf = intf->next)
6586 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
6587 UpdateInterfaceProtocols(m, intf);
6588 }
6589 else
6590 {
6591 NetworkInterfaceInfo *intf;
6592 for (intf = m->HostInterfaces; intf; intf = intf->next)
6593 if (intf->InterfaceID == set->InterfaceID)
6594 break;
6595 if (intf)
6596 {
6597 debugf("mDNS_DeregisterInterface: Another representative of InterfaceID %p exists; making it active",
6598 set->InterfaceID);
6599 intf->InterfaceActive = mDNStrue;
6600 UpdateInterfaceProtocols(m, intf);
6601
6602 // See if another representative *of the same type* exists. If not, we mave have gone from
6603 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
6604 for (intf = m->HostInterfaces; intf; intf = intf->next)
6605 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
6606 break;
6607 if (!intf) revalidate = mDNStrue;
6608 }
6609 else
6610 {
6611 CacheRecord *rr;
6612 DNSQuestion *q;
6613 mDNSu32 slot;
6614 debugf("mDNS_DeregisterInterface: Last representative of InterfaceID %p deregistered; marking questions etc. dormant",
6615 set->InterfaceID);
6616
6617 // 1. Deactivate any questions specific to this interface
6618 for (q = m->Questions; q; q=q->next)
6619 if (q->InterfaceID == set->InterfaceID)
6620 q->ThisQInterval = 0;
6621
6622 // 2. Flush any cache records received on this interface
6623 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
6624 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
6625 for (rr = m->rrcache_hash[slot]; rr; rr=rr->next)
6626 if (rr->resrec.InterfaceID == set->InterfaceID)
6627 PurgeCacheResourceRecord(m, rr);
6628 }
6629 }
6630
6631 // If we were advertising on this interface, deregister those address and reverse-lookup records now
6632 if (set->Advertise)
6633 mDNS_DeadvertiseInterface(m, set);
6634
6635 // If we have any cache records received on this interface that went away, then re-verify them.
6636 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
6637 // giving the false impression that there's an active representative of this interface when there really isn't.
6638 // Don't need to do this when shutting down, because *all* interfaces are about to go away
6639 if (revalidate && !m->mDNS_shutdown)
6640 {
6641 mDNSu32 slot;
6642 CacheRecord *rr;
6643 m->NextCacheCheck = m->timenow;
6644 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
6645 for (rr = m->rrcache_hash[slot]; rr; rr=rr->next)
6646 if (rr->resrec.InterfaceID == set->InterfaceID)
6647 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForCableDisconnect);
6648 }
6649
6650 mDNS_Unlock(m);
6651 }
6652
6653 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
6654 {
6655 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
6656 (void)m; // Unused parameter
6657
6658 #if MDNS_DEBUGMSGS
6659 {
6660 char *msg = "Unknown result";
6661 if (result == mStatus_NoError) msg = "Name Registered";
6662 else if (result == mStatus_NameConflict) msg = "Name Conflict";
6663 else if (result == mStatus_MemFree) msg = "Memory Free";
6664 debugf("ServiceCallback: %##s (%s) %s (%ld)", rr->resrec.name.c, DNSTypeName(rr->resrec.rrtype), msg, result);
6665 }
6666 #endif
6667
6668 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
6669 if (result == mStatus_NameConflict)
6670 {
6671 sr->Conflict = mDNStrue; // Record that this service set had a conflict
6672 sr->RR_PTR.AnnounceCount = InitialAnnounceCount; // Make sure we don't send a goodbye for the PTR record
6673 mDNS_DeregisterService(m, sr); // Unlink the records from our list
6674 return;
6675 }
6676
6677 if (result == mStatus_MemFree)
6678 {
6679 // If the PTR record or any of the subtype PTR records are still in the process of deregistering,
6680 // don't pass on the NameConflict/MemFree message until every record is finished cleaning up.
6681 mDNSu32 i;
6682 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
6683 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
6684
6685 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
6686 // then we can now report the NameConflict to the client
6687 if (sr->Conflict) result = mStatus_NameConflict;
6688 }
6689
6690 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
6691 // function is allowed to do anything, including deregistering this service and freeing its memory.
6692 if (sr->ServiceCallback)
6693 sr->ServiceCallback(m, sr, result);
6694 }
6695
6696 // Note:
6697 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
6698 // Type is service type (e.g. "_printer._tcp.")
6699 // Domain is fully qualified domain name (i.e. ending with a null label)
6700 // We always register a TXT, even if it is empty (so that clients are not
6701 // left waiting forever looking for a nonexistent record.)
6702 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
6703 // then the default host name (m->hostname1) is automatically used
6704 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
6705 const domainlabel *const name, const domainname *const type, const domainname *const domain,
6706 const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
6707 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
6708 const mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context)
6709 {
6710 mStatus err;
6711 mDNSu32 i;
6712
6713 sr->ServiceCallback = Callback;
6714 sr->ServiceContext = Context;
6715 sr->Extras = mDNSNULL;
6716 sr->NumSubTypes = NumSubTypes;
6717 sr->SubTypes = SubTypes;
6718 sr->Conflict = mDNSfalse;
6719 if (host && host->c[0]) sr->Host = *host;
6720 else sr->Host.c[0] = 0;
6721
6722 // Initialize the AuthRecord objects to sane values
6723 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kDefaultTTLforShared, kDNSRecordTypeAdvisory, ServiceCallback, sr);
6724 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kDefaultTTLforShared, kDNSRecordTypeShared, ServiceCallback, sr);
6725 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kDefaultTTLforUnique, kDNSRecordTypeUnique, ServiceCallback, sr);
6726 mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kDefaultTTLforUnique, kDNSRecordTypeUnique, ServiceCallback, sr);
6727
6728 // If the client is registering an oversized TXT record,
6729 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
6730 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
6731 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
6732
6733 // Set up the record names
6734 // For now we only create an advisory record for the main type, not for subtypes
6735 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
6736 if (ConstructServiceName(&sr->RR_ADV.resrec.name, (domainlabel*)"\x09_services", (domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
6737 return(mStatus_BadParamErr);
6738 if (ConstructServiceName(&sr->RR_PTR.resrec.name, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
6739 if (ConstructServiceName(&sr->RR_SRV.resrec.name, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
6740 AssignDomainName(sr->RR_TXT.resrec.name, sr->RR_SRV.resrec.name);
6741
6742 // 1. Set up the ADV record rdata to advertise our service type
6743 AssignDomainName(sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
6744
6745 // 2. Set up the PTR record rdata to point to our service name
6746 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
6747 AssignDomainName(sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
6748 sr->RR_PTR.Additional1 = &sr->RR_SRV;
6749 sr->RR_PTR.Additional2 = &sr->RR_TXT;
6750
6751 // 2a. Set up any subtype PTRs to point to our service name
6752 // If the client is using subtypes, it is the client's responsibility to have
6753 // already set the first label of the record name to the subtype being registered
6754 for (i=0; i<NumSubTypes; i++)
6755 {
6756 domainname st;
6757 AssignDomainName(st, sr->SubTypes[i].resrec.name);
6758 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
6759 AppendDomainName(&st, type);
6760 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kDefaultTTLforShared, kDNSRecordTypeShared, ServiceCallback, sr);
6761 if (ConstructServiceName(&sr->SubTypes[i].resrec.name, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
6762 AssignDomainName(sr->SubTypes[i].resrec.rdata->u.name, sr->RR_SRV.resrec.name);
6763 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
6764 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
6765 }
6766
6767 // 3. Set up the SRV record rdata.
6768 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
6769 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
6770 sr->RR_SRV.resrec.rdata->u.srv.port = port;
6771
6772 // Setting HostTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
6773 if (sr->Host.c[0]) AssignDomainName(sr->RR_SRV.resrec.rdata->u.srv.target, sr->Host);
6774 else sr->RR_SRV.HostTarget = mDNStrue;
6775
6776 // 4. Set up the TXT record rdata,
6777 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
6778 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
6779 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
6780 {
6781 sr->RR_TXT.resrec.rdlength = txtlen;
6782 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
6783 mDNSPlatformMemCopy(txtinfo, sr->RR_TXT.resrec.rdata->u.txt.c, txtlen);
6784 }
6785 sr->RR_TXT.DependentOn = &sr->RR_SRV;
6786
6787 mDNS_Lock(m);
6788 err = mDNS_Register_internal(m, &sr->RR_SRV);
6789 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
6790 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
6791 // mDNS_Close, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
6792 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
6793 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
6794 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
6795 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
6796 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
6797 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
6798 mDNS_Unlock(m);
6799
6800 if (err) mDNS_DeregisterService(m, sr);
6801 return(err);
6802 }
6803
6804 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
6805 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl)
6806 {
6807 mStatus result = mStatus_UnknownErr;
6808 ExtraResourceRecord **e = &sr->Extras;
6809 while (*e) e = &(*e)->next;
6810
6811 // If TTL is unspecified, make it the same as the service's TXT and SRV default
6812 if (ttl == 0) ttl = kDefaultTTLforUnique;
6813
6814 extra->next = mDNSNULL;
6815 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID, extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, ServiceCallback, sr);
6816 AssignDomainName(extra->r.resrec.name, sr->RR_SRV.resrec.name);
6817 extra->r.DependentOn = &sr->RR_SRV;
6818
6819 debugf("mDNS_AddRecordToService adding record to %##s", extra->r.resrec.name.c);
6820
6821 result = mDNS_Register(m, &extra->r);
6822 if (!result) *e = extra;
6823 return result;
6824 }
6825
6826 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra)
6827 {
6828 ExtraResourceRecord **e = &sr->Extras;
6829 while (*e && *e != extra) e = &(*e)->next;
6830 if (!*e)
6831 {
6832 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name.c);
6833 return(mStatus_BadReferenceErr);
6834 }
6835
6836 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name.c);
6837
6838 *e = (*e)->next;
6839 return(mDNS_Deregister(m, &extra->r));
6840 }
6841
6842 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
6843 {
6844 domainlabel name;
6845 domainname type, domain;
6846 domainname *host = mDNSNULL;
6847 ExtraResourceRecord *extras = sr->Extras;
6848 mStatus err;
6849
6850 DeconstructServiceName(&sr->RR_SRV.resrec.name, &name, &type, &domain);
6851 if (!newname)
6852 {
6853 IncrementLabelSuffix(&name, mDNStrue);
6854 newname = &name;
6855 }
6856 debugf("Reregistering as %#s", newname->c);
6857 if (sr->RR_SRV.HostTarget == mDNSfalse && sr->Host.c[0]) host = &sr->Host;
6858
6859 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
6860 host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
6861 sr->SubTypes, sr->NumSubTypes,
6862 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext);
6863
6864 // mDNS_RegisterService() just reset sr->Extras to NULL.
6865 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
6866 // through the old list of extra records, and re-add them to our freshly created service registration
6867 while (!err && extras)
6868 {
6869 ExtraResourceRecord *e = extras;
6870 extras = extras->next;
6871 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl);
6872 }
6873
6874 return(err);
6875 }
6876
6877 // NOTE: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
6878 // which may change the record list and/or question list.
6879 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6880 mDNSexport mStatus mDNS_DeregisterService(mDNS *const m, ServiceRecordSet *sr)
6881 {
6882 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
6883 {
6884 debugf("Service set for %##s already deregistered", sr->RR_PTR.resrec.name.c);
6885 return(mStatus_BadReferenceErr);
6886 }
6887 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
6888 {
6889 debugf("Service set for %##s already in the process of deregistering", sr->RR_PTR.resrec.name.c);
6890 return(mStatus_NoError);
6891 }
6892 else
6893 {
6894 mDNSu32 i;
6895 mStatus status;
6896 ExtraResourceRecord *e;
6897 mDNS_Lock(m);
6898 e = sr->Extras;
6899
6900 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
6901 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
6902 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
6903 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
6904
6905 mDNS_Deregister_internal(m, &sr->RR_ADV, mDNS_Dereg_normal);
6906
6907 // We deregister all of the extra records, but we leave the sr->Extras list intact
6908 // in case the client wants to do a RenameAndReregister and reinstate the registration
6909 while (e)
6910 {
6911 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
6912 e = e->next;
6913 }
6914
6915 for (i=0; i<sr->NumSubTypes; i++)
6916 mDNS_Deregister_internal(m, &sr->SubTypes[i], mDNS_Dereg_normal);
6917
6918 // Be sure to deregister the PTR last!
6919 // Deregistering this record is what triggers the mStatus_MemFree callback to ServiceCallback,
6920 // which in turn passes on the mStatus_MemFree (or mStatus_NameConflict) back to the client callback,
6921 // which is then at liberty to free the ServiceRecordSet memory at will. We need to make sure
6922 // we've deregistered all our records and done any other necessary cleanup before that happens.
6923 status = mDNS_Deregister_internal(m, &sr->RR_PTR, mDNS_Dereg_normal);
6924 mDNS_Unlock(m);
6925 return(status);
6926 }
6927 }
6928
6929 // Create a registration that asserts that no such service exists with this name.
6930 // This can be useful where there is a given function is available through several protocols.
6931 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
6932 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
6933 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
6934 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
6935 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
6936 const domainlabel *const name, const domainname *const type, const domainname *const domain,
6937 const domainname *const host,
6938 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context)
6939 {
6940 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kDefaultTTLforUnique, kDNSRecordTypeUnique, Callback, Context);
6941 if (ConstructServiceName(&rr->resrec.name, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
6942 rr->resrec.rdata->u.srv.priority = 0;
6943 rr->resrec.rdata->u.srv.weight = 0;
6944 rr->resrec.rdata->u.srv.port = zeroIPPort;
6945 if (host && host->c[0]) AssignDomainName(rr->resrec.rdata->u.srv.target, *host);
6946 else rr->HostTarget = mDNStrue;
6947 return(mDNS_Register(m, rr));
6948 }
6949
6950 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
6951 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
6952 {
6953 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kDefaultTTLforShared, kDNSRecordTypeShared, mDNSNULL, mDNSNULL);
6954 if (!MakeDomainNameFromDNSNameString(&rr->resrec.name, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
6955 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
6956 return(mDNS_Register(m, rr));
6957 }
6958
6959 // ***************************************************************************
6960 #if COMPILER_LIKES_PRAGMA_MARK
6961 #pragma mark -
6962 #pragma mark -
6963 #pragma mark - Startup and Shutdown
6964 #endif
6965
6966 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheRecord *storage, mDNSu32 numrecords)
6967 {
6968 if (storage && numrecords)
6969 {
6970 mDNSu32 i;
6971 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
6972 storage[numrecords-1].next = m->rrcache_free;
6973 m->rrcache_free = storage;
6974 m->rrcache_size += numrecords;
6975 }
6976 }
6977
6978 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
6979 CacheRecord *rrcachestorage, mDNSu32 rrcachesize,
6980 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
6981 {
6982 mDNSu32 slot;
6983 mDNSs32 timenow;
6984 mStatus result = mDNSPlatformTimeInit(&timenow);
6985 if (result != mStatus_NoError) return(result);
6986
6987 if (!rrcachestorage) rrcachesize = 0;
6988
6989 m->p = p;
6990 m->KnownBugs = 0;
6991 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
6992 m->mDNSPlatformStatus = mStatus_Waiting;
6993 m->MainCallback = Callback;
6994 m->MainContext = Context;
6995
6996 // For debugging: To catch and report locking failures
6997 m->mDNS_busy = 0;
6998 m->mDNS_reentrancy = 0;
6999 m->mDNS_shutdown = mDNSfalse;
7000 m->lock_rrcache = 0;
7001 m->lock_Questions = 0;
7002 m->lock_Records = 0;
7003
7004 // Task Scheduling variables
7005 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
7006 m->timenow_last = timenow;
7007 m->timenow_adjust = 0;
7008 m->NextScheduledEvent = timenow;
7009 m->SuppressSending = timenow;
7010 m->NextCacheCheck = timenow + 0x78000000;
7011 m->NextScheduledQuery = timenow + 0x78000000;
7012 m->NextScheduledProbe = timenow + 0x78000000;
7013 m->NextScheduledResponse = timenow + 0x78000000;
7014 m->ExpectUnicastResponse = timenow + 0x78000000;
7015 m->RandomQueryDelay = 0;
7016 m->SendDeregistrations = mDNSfalse;
7017 m->SendImmediateAnswers = mDNSfalse;
7018 m->SleepState = mDNSfalse;
7019
7020 // These fields only required for mDNS Searcher...
7021 m->Questions = mDNSNULL;
7022 m->NewQuestions = mDNSNULL;
7023 m->CurrentQuestion = mDNSNULL;
7024 m->LocalOnlyQuestions = mDNSNULL;
7025 m->NewLocalOnlyQuestions = mDNSNULL;
7026 m->rrcache_size = 0;
7027 m->rrcache_totalused = 0;
7028 m->rrcache_active = 0;
7029 m->rrcache_report = 10;
7030 m->rrcache_free = mDNSNULL;
7031
7032 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
7033 {
7034 m->rrcache_hash[slot] = mDNSNULL;
7035 m->rrcache_tail[slot] = &m->rrcache_hash[slot];
7036 m->rrcache_used[slot] = 0;
7037 }
7038
7039 mDNS_GrowCache(m, rrcachestorage, rrcachesize);
7040
7041 // Fields below only required for mDNS Responder...
7042 m->hostlabel.c[0] = 0;
7043 m->nicelabel.c[0] = 0;
7044 m->hostname.c[0] = 0;
7045 m->HIHardware.c[0] = 0;
7046 m->HISoftware.c[0] = 0;
7047 m->ResourceRecords = mDNSNULL;
7048 m->DuplicateRecords = mDNSNULL;
7049 m->LocalOnlyRecords = mDNSNULL;
7050 m->NewLocalOnlyRecords = mDNSNULL;
7051 m->DiscardLocalOnlyRecords = mDNSfalse;
7052 m->CurrentRecord = mDNSNULL;
7053 m->HostInterfaces = mDNSNULL;
7054 m->ProbeFailTime = 0;
7055 m->NumFailedProbes = 0;
7056 m->SuppressProbes = 0;
7057
7058 result = mDNSPlatformInit(m);
7059
7060 return(result);
7061 }
7062
7063 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
7064 {
7065 m->mDNSPlatformStatus = result;
7066 if (m->MainCallback)
7067 m->MainCallback(m, mStatus_NoError);
7068 }
7069
7070 mDNSexport void mDNS_Close(mDNS *const m)
7071 {
7072 mDNSu32 rrcache_active = 0;
7073 mDNSu32 rrcache_totalused = 0;
7074 mDNSu32 slot;
7075 NetworkInterfaceInfo *intf;
7076 mDNS_Lock(m);
7077
7078 m->mDNS_shutdown = mDNStrue;
7079
7080 rrcache_totalused = m->rrcache_totalused;
7081 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
7082 {
7083 while (m->rrcache_hash[slot])
7084 {
7085 CacheRecord *rr = m->rrcache_hash[slot];
7086 m->rrcache_hash[slot] = rr->next;
7087 if (rr->CRActiveQuestion) rrcache_active++;
7088 m->rrcache_used[slot]--;
7089 ReleaseCacheRR(m, rr);
7090 }
7091 // 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)
7092 m->rrcache_tail[slot] = &m->rrcache_hash[slot];
7093 }
7094 debugf("mDNS_Close: RR Cache was using %ld records, %d active", rrcache_totalused, rrcache_active);
7095 if (rrcache_active != m->rrcache_active)
7096 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
7097
7098 m->Questions = mDNSNULL; // We won't be answering any more questions!
7099
7100 for (intf = m->HostInterfaces; intf; intf = intf->next)
7101 if (intf->Advertise)
7102 mDNS_DeadvertiseInterface(m, intf);
7103
7104 // Make sure there are nothing but deregistering records remaining in the list
7105 if (m->CurrentRecord) LogMsg("mDNS_Close ERROR m->CurrentRecord already set");
7106 m->CurrentRecord = m->ResourceRecords;
7107 while (m->CurrentRecord)
7108 {
7109 AuthRecord *rr = m->CurrentRecord;
7110 m->CurrentRecord = rr->next;
7111 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
7112 {
7113 debugf("mDNS_Close: Record type %X still in ResourceRecords list %##s", rr->resrec.RecordType, rr->resrec.name.c);
7114 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7115 }
7116 }
7117
7118 if (m->ResourceRecords) debugf("mDNS_Close: Sending final packets for deregistering records");
7119 else debugf("mDNS_Close: No deregistering records remain");
7120
7121 // If any deregistering records remain, send their deregistration announcements before we exit
7122 if (m->mDNSPlatformStatus != mStatus_NoError)
7123 DiscardDeregistrations(m);
7124 else
7125 while (m->ResourceRecords)
7126 SendResponses(m);
7127
7128 mDNS_Unlock(m);
7129 debugf("mDNS_Close: mDNSPlatformClose");
7130 mDNSPlatformClose(m);
7131 debugf("mDNS_Close: done");
7132 }