2 * Copyright (c) 2002-2004 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
23 Change History (most recent first):
26 Revision 1.183 2005/01/27 22:57:55 cheshire
27 Fix compile errors on gcc4
29 Revision 1.182 2005/01/25 18:55:05 ksekar
32 Revision 1.181 2005/01/25 02:17:32 cheshire
33 <rdar://problem/3971263> Don't use query ID zero in uDNS queries
35 Revision 1.180 2005/01/19 21:01:54 ksekar
36 <rdar://problem/3955355> uDNS needs to support subtype registration and browsing
38 Revision 1.179 2005/01/19 19:15:35 ksekar
39 Refinement to <rdar://problem/3954575> - Simplify mDNS_PurgeResultsForDomain logic and move into daemon layer
41 Revision 1.178 2005/01/17 23:47:58 cheshire
42 <rdar://problem/3904954> Wide-area services not found on little-endian
44 Revision 1.177 2005/01/17 23:41:26 cheshire
47 Revision 1.176 2005/01/17 21:03:04 cheshire
48 <rdar://problem/3904954> Wide-area services not found on little-endian
50 Revision 1.175 2005/01/15 00:56:41 ksekar
51 <rdar://problem/3954575> Unicast services don't disappear when logging
54 Revision 1.174 2005/01/14 18:44:28 ksekar
55 <rdar://problem/3954609> mDNSResponder is crashing when changing domains
57 Revision 1.173 2005/01/14 18:34:22 ksekar
58 <rdar://problem/3954571> Services registered outside of firewall don't succeed after location change
60 Revision 1.172 2005/01/11 22:50:52 ksekar
61 Fixed constant naming (was using kLLQ_DefLease for update leases)
63 Revision 1.171 2005/01/10 04:52:49 ksekar
64 Changed LogMsg to debugf
66 Revision 1.170 2005/01/08 00:50:05 ksekar
67 Fixed spelling mistake in log msg
69 Revision 1.169 2005/01/08 00:42:18 ksekar
70 <rdar://problem/3922758> Clean up syslog messages
72 Revision 1.168 2004/12/23 23:22:47 ksekar
73 <rdar://problem/3933606> Unicast known answers "name" pointers point to garbage stack memory
75 Revision 1.167 2004/12/22 22:25:47 ksekar
76 <rdar://problem/3734265> NATPMP: handle location changes
78 Revision 1.166 2004/12/22 00:04:12 ksekar
79 <rdar://problem/3930324> mDNSResponder crashing in ReceivePortMapReply
81 Revision 1.165 2004/12/18 03:14:22 cheshire
84 Revision 1.164 2004/12/17 03:55:40 ksekar
85 Don't use -1 as special meaning for expiration timer (it is a valid
86 value, and is redundant with our state variables)
88 Revision 1.163 2004/12/17 03:51:53 ksekar
89 <rdar://problem/3920991> Don't update TXT record if service registration fails
91 Revision 1.162 2004/12/17 01:29:11 ksekar
92 <rdar://problem/3920598> Questions can go deaf on location changes
94 Revision 1.161 2004/12/16 20:42:02 cheshire
97 Revision 1.160 2004/12/16 20:13:00 cheshire
98 <rdar://problem/3324626> Cache memory management improvements
100 Revision 1.159 2004/12/15 02:11:22 ksekar
101 <rdar://problem/3917317> Don't check for Dynamic DNS hostname uniqueness
103 Revision 1.158 2004/12/15 02:04:28 ksekar
104 Refinement to previous checkin - we should still return NatTraversal error when the port mapping fails
106 Revision 1.157 2004/12/15 01:39:21 ksekar
107 Refinement to previous checkin - we should still return NatTraversal error when the port mapping fails
109 Revision 1.156 2004/12/15 01:18:57 ksekar
110 <rdar://problem/3825979> Call DeregisterService on nat port map failure
112 Revision 1.155 2004/12/14 21:21:20 ksekar
113 <rdar://problem/3825979> NAT-PMP: Update response format to contain "Seconds Since Boot"
115 Revision 1.154 2004/12/14 20:52:27 cheshire
116 Add question->qnamehash and cr->resrec.namehash to log message
118 Revision 1.153 2004/12/14 20:45:02 cheshire
119 Improved error logging in "unexpected answer" message
121 Revision 1.152 2004/12/14 03:02:10 ksekar
122 <rdar://problem/3919016> Rare race condition can cause crash
124 Revision 1.151 2004/12/13 21:45:08 ksekar
125 uDNS_DeregisterService should return NoError if called twice (to follow mDNS behavior expected by daemon layer)
127 Revision 1.150 2004/12/13 20:42:41 ksekar
130 Revision 1.149 2004/12/13 18:10:03 ksekar
133 Revision 1.148 2004/12/13 01:18:04 ksekar
134 Fixed unused variable warning for non-debug builds
136 Revision 1.147 2004/12/12 23:51:42 ksekar
137 <rdar://problem/3845683> Wide-area registrations should fallback to using DHCP hostname as target
139 Revision 1.146 2004/12/12 23:30:40 ksekar
140 <rdar://problem/3916987> Extra RRs not properly unlinked when parent service registration fails
142 Revision 1.145 2004/12/12 22:56:29 ksekar
143 <rdar://problem/3668508> Need to properly handle duplicate long-lived queries
145 Revision 1.144 2004/12/11 20:55:29 ksekar
146 <rdar://problem/3916479> Clean up registration state machines
148 Revision 1.143 2004/12/10 01:21:27 cheshire
149 <rdar://problem/3914089> Get rid of "LLQ Responses over TCP not currently supported" message
151 Revision 1.142 2004/12/08 02:03:31 ksekar
152 <rdar://problem/3865124> Looping on NAT Traversal error - check for
155 Revision 1.141 2004/12/07 01:39:28 cheshire
156 Don't fail if the same server is responsible for more than one domain
157 (e.g. the same DNS server may be responsible for both apple.com. and 17.in-addr.arpa.)
159 Revision 1.140 2004/12/06 21:15:22 ksekar
160 <rdar://problem/3884386> mDNSResponder crashed in CheckServiceRegistrations
162 Revision 1.139 2004/12/06 19:08:03 cheshire
163 Add clarifying comment -- CountLabels() excludes the final root label.
165 Revision 1.138 2004/12/06 01:45:54 ksekar
166 Correct wording in LogMsg
168 Revision 1.137 2004/12/03 20:40:35 ksekar
169 <rdar://problem/3865124> Looping on NAT Traversal error
171 Revision 1.136 2004/12/03 07:20:50 ksekar
172 <rdar://problem/3674208> Wide-Area: Registration of large TXT record fails
174 Revision 1.135 2004/12/03 05:18:33 ksekar
175 <rdar://problem/3810596> mDNSResponder needs to return more specific TSIG errors
177 Revision 1.134 2004/12/02 20:03:49 ksekar
178 <rdar://problem/3889647> Rendezvous still publishes wide-area domains even after switching to a local subnet
180 Revision 1.133 2004/12/02 18:37:52 ksekar
181 <rdar://problem/3758233> Registering with port number zero should not create a port mapping
183 Revision 1.132 2004/12/01 20:57:19 ksekar
184 <rdar://problem/3873921> Wide Area Rendezvous must be split-DNS aware
186 Revision 1.131 2004/12/01 19:59:27 cheshire
187 <rdar://problem/3882643> Crash in mDNSPlatformTCPConnect
188 If a TCP response has the TC bit set, don't respond by just trying another TCP connection
190 Revision 1.130 2004/12/01 02:43:23 cheshire
191 Don't call StatusCallback if function pointer is null
193 Revision 1.129 2004/11/30 23:51:06 cheshire
194 Remove double semicolons
196 Revision 1.128 2004/11/25 01:48:30 ksekar
197 <rdar://problem/3878991> Logging into VPN does not trigger registration of address record
199 Revision 1.127 2004/11/25 01:41:36 ksekar
200 Changed unnecessary LogMsgs to debugfs
202 Revision 1.126 2004/11/23 23:54:17 ksekar
203 <rdar://problem/3890318> Wide-Area DNSServiceRegisterRecord() failures
204 can crash mDNSResponder
206 Revision 1.125 2004/11/23 04:16:48 cheshire
207 Removed receiveMsg() routine.
209 Revision 1.124 2004/11/23 04:06:51 cheshire
210 Get rid of floating point constant -- in a small embedded device, bringing in all
211 the floating point libraries just to halve an integer value is a bit too heavyweight.
213 Revision 1.123 2004/11/22 17:16:20 ksekar
214 <rdar://problem/3854298> Unicast services don't disappear when you disable all networking
216 Revision 1.122 2004/11/19 18:00:34 ksekar
217 <rdar://problem/3682646> Security: use random ID for one-shot unicast queries
219 Revision 1.121 2004/11/19 04:24:08 ksekar
220 <rdar://problem/3682609> Security: Enforce a "window" on one-shot wide-area queries
222 Revision 1.120 2004/11/19 02:32:43 ksekar
223 <rdar://problem/3682608> Wide-Area Rendezvous Security: Add LLQ-ID to events
225 Revision 1.119 2004/11/18 23:21:24 ksekar
226 <rdar://problem/3764544> LLQ Security: Need to verify src port/address for LLQ handshake
228 Revision 1.118 2004/11/18 22:58:37 ksekar
231 Revision 1.117 2004/11/18 18:04:21 ksekar
232 Restore checkins lost due to repository disk failure: Update comments & <rdar://problem/3880688>
234 Revision 1.xxx 2004/11/17 06:17:57 cheshire
235 Update comments to show correct SRV names: _dns-update._udp.<zone>. and _dns-llq._udp.<zone>.
237 Revision 1.xxx 2004/11/17 00:45:28 ksekar
238 <rdar://problem/3880688> Result of putUpdateLease not error-checked
240 Revision 1.116 2004/11/16 01:41:47 ksekar
243 Revision 1.115 2004/11/15 20:09:24 ksekar
244 <rdar://problem/3719050> Wide Area support for Add/Remove record
246 Revision 1.114 2004/11/13 02:32:47 ksekar
247 <rdar://problem/3868216> LLQ mobility fragile on non-primary interface
248 - fixed incorrect state comparison in CheckQueries
250 Revision 1.113 2004/11/13 02:29:52 ksekar
251 <rdar://problem/3878386> LLQ refreshes not reliable
253 Revision 1.112 2004/11/11 20:45:14 ksekar
254 <rdar://problem/3876052> self-conflict test not compatible with some BIND servers
256 Revision 1.111 2004/11/11 20:14:55 ksekar
257 <rdar://problem/3719574> Wide-Area registrations not deregistered on sleep
259 Revision 1.110 2004/11/10 23:53:53 ksekar
260 Remove no longer relevant comment
262 Revision 1.109 2004/11/10 20:40:53 ksekar
263 <rdar://problem/3868216> LLQ mobility fragile on non-primary interface
265 Revision 1.108 2004/11/01 20:36:16 ksekar
266 <rdar://problem/3802395> mDNSResponder should not receive Keychain Notifications
268 Revision 1.107 2004/10/26 06:11:41 cheshire
269 Add improved logging to aid in diagnosis of <rdar://problem/3842714> mDNSResponder crashed
271 Revision 1.106 2004/10/26 03:52:03 cheshire
272 Update checkin comments
274 Revision 1.105 2004/10/26 01:15:06 cheshire
275 Use "#if 0" instead of commenting out code
277 Revision 1.104 2004/10/25 21:41:38 ksekar
278 <rdar://problem/3852958> wide-area name conflicts can cause crash
280 Revision 1.103 2004/10/25 19:30:52 ksekar
281 <rdar://problem/3827956> Simplify dynamic host name structures
283 Revision 1.102 2004/10/23 01:16:00 cheshire
284 <rdar://problem/3851677> uDNS operations not always reliable on multi-homed hosts
286 Revision 1.101 2004/10/22 20:52:07 ksekar
287 <rdar://problem/3799260> Create NAT port mappings for Long Lived Queries
289 Revision 1.100 2004/10/20 02:16:41 cheshire
290 Improve "could not confirm existence of NS record" error message
291 Don't call newRR->RecordCallback if it is NULL
293 Revision 1.99 2004/10/19 21:33:18 cheshire
294 <rdar://problem/3844991> Cannot resolve non-local registrations using the mach API
295 Added flag 'kDNSServiceFlagsForceMulticast'. Passing through an interface id for a unicast name
296 doesn't force multicast unless you set this flag to indicate explicitly that this is what you want
298 Revision 1.98 2004/10/16 00:16:59 cheshire
299 <rdar://problem/3770558> Replace IP TTL 255 check with local subnet source address check
301 Revision 1.97 2004/10/15 23:00:18 ksekar
302 <rdar://problem/3799242> Need to update LLQs on location changes
304 Revision 1.96 2004/10/12 23:30:44 ksekar
305 <rdar://problem/3609944> mDNSResponder needs to follow CNAME referrals
307 Revision 1.95 2004/10/12 03:15:09 ksekar
308 <rdar://problem/3835612> mDNS_StartQuery shouldn't return transient no-server error
310 Revision 1.94 2004/10/12 02:49:20 ksekar
311 <rdar://problem/3831228> Clean up LLQ sleep/wake, error handling
313 Revision 1.93 2004/10/08 04:17:25 ksekar
314 <rdar://problem/3831819> Don't use DNS extensions if the server does not advertise required SRV record
316 Revision 1.92 2004/10/08 03:54:35 ksekar
317 <rdar://problem/3831802> Refine unicast polling intervals
319 Revision 1.91 2004/09/30 17:45:34 ksekar
320 <rdar://problem/3821119> lots of log messages: mDNS_SetPrimaryIP: IP address unchanged
322 Revision 1.90 2004/09/25 00:22:13 ksekar
323 <rdar://problem/3815534> Crash in uDNS_RegisterService
325 Revision 1.89 2004/09/24 19:14:53 cheshire
326 Remove unused "extern mDNS mDNSStorage"
328 Revision 1.88 2004/09/23 20:48:15 ksekar
329 Clarify retransmission debugf messages.
331 Revision 1.87 2004/09/22 00:41:59 cheshire
332 Move tcp connection status codes into the legal range allocated for mDNS use
334 Revision 1.86 2004/09/21 23:40:11 ksekar
335 <rdar://problem/3810349> mDNSResponder to return errors on NAT traversal failure
337 Revision 1.85 2004/09/21 22:38:27 ksekar
338 <rdar://problem/3810286> PrimaryIP type uninitialized
340 Revision 1.84 2004/09/18 00:30:39 cheshire
341 <rdar://problem/3806643> Infinite loop in CheckServiceRegistrations
343 Revision 1.83 2004/09/17 00:31:51 cheshire
344 For consistency with ipv6, renamed rdata field 'ip' to 'ipv4'
346 Revision 1.82 2004/09/16 21:36:36 cheshire
347 <rdar://problem/3803162> Fix unsafe use of mDNSPlatformTimeNow()
348 Changes to add necessary locking calls around unicast DNS operations
350 Revision 1.81 2004/09/16 02:29:39 cheshire
351 Moved mDNS_Lock/mDNS_Unlock to DNSCommon.c; Added necessary locking around
352 uDNS_ReceiveMsg, uDNS_StartQuery, uDNS_UpdateRecord, uDNS_RegisterService
354 Revision 1.80 2004/09/16 01:58:21 cheshire
355 Fix compiler warnings
357 Revision 1.79 2004/09/16 00:24:48 cheshire
358 <rdar://problem/3803162> Fix unsafe use of mDNSPlatformTimeNow()
360 Revision 1.78 2004/09/15 01:16:57 ksekar
361 <rdar://problem/3797598> mDNSResponder printing too many messages
363 Revision 1.77 2004/09/14 23:27:47 cheshire
366 Revision 1.76 2004/09/14 22:22:00 ksekar
367 <rdar://problem/3800920> Legacy browses broken against some BIND versions
369 Revision 1.75 2004/09/03 19:23:05 ksekar
370 <rdar://problem/3788460>: Need retransmission mechanism for wide-area service registrations
372 Revision 1.74 2004/09/02 17:49:04 ksekar
373 <rdar://problem/3785135>: 8A246: mDNSResponder crash while logging on restart
374 Fixed incorrect conversions, changed %s to %##s for all domain names.
376 Revision 1.73 2004/09/02 01:39:40 cheshire
377 For better readability, follow consistent convention that QR bit comes first, followed by OP bits
379 Revision 1.72 2004/09/01 03:59:29 ksekar
380 <rdar://problem/3783453>: Conditionally compile out uDNS code on Windows
382 Revision 1.71 2004/08/27 17:51:53 ksekar
383 Replaced unnecessary LogMsg with debugf.
385 Revision 1.70 2004/08/25 00:37:27 ksekar
386 <rdar://problem/3774635>: Cleanup DynDNS hostname registration code
388 Revision 1.69 2004/08/18 17:35:41 ksekar
389 <rdar://problem/3651443>: Feature #9586: Need support for Legacy NAT gateways
391 Revision 1.68 2004/08/14 03:22:41 cheshire
392 <rdar://problem/3762579> Dynamic DNS UI <-> mDNSResponder glue
393 Add GetUserSpecifiedDDNSName() routine
394 Convert ServiceRegDomain to domainname instead of C string
395 Replace mDNS_GenerateFQDN/mDNS_GenerateGlobalFQDN with mDNS_SetFQDNs
397 Revision 1.67 2004/08/13 23:46:58 cheshire
398 "asyncronous" -> "asynchronous"
400 Revision 1.66 2004/08/13 23:37:02 cheshire
401 Now that we do both uDNS and mDNS, global replace "uDNS_info.hostname" with
402 "uDNS_info.UnicastHostname" for clarity
404 Revision 1.65 2004/08/13 23:12:32 cheshire
405 Don't use strcpy() and strlen() on "struct domainname" objects;
406 use AssignDomainName() and DomainNameLength() instead
407 (A "struct domainname" is a collection of packed pascal strings, not a C string.)
409 Revision 1.64 2004/08/13 23:01:05 cheshire
410 Use platform-independent mDNSNULL instead of NULL
412 Revision 1.63 2004/08/12 00:32:36 ksekar
413 <rdar://problem/3759567>: LLQ Refreshes never terminate if unanswered
415 Revision 1.62 2004/08/10 23:19:14 ksekar
416 <rdar://problem/3722542>: DNS Extension daemon for Wide Area Rendezvous
417 Moved routines/constants to allow extern access for garbage collection daemon
419 Revision 1.61 2004/07/30 17:40:06 ksekar
420 <rdar://problem/3739115>: TXT Record updates not available for wide-area services
422 Revision 1.60 2004/07/29 19:40:05 ksekar
423 NATPMP Support - minor fixes and cleanup
425 Revision 1.59 2004/07/29 19:27:15 ksekar
426 NATPMP Support - minor fixes and cleanup
428 Revision 1.58 2004/07/27 07:35:38 shersche
429 fix syntax error, variables declared in the middle of a block
431 Revision 1.57 2004/07/26 22:49:30 ksekar
432 <rdar://problem/3651409>: Feature #9516: Need support for NATPMP in client
434 Revision 1.56 2004/07/26 19:14:44 ksekar
435 <rdar://problem/3737814>: 8A210: mDNSResponder crashed in startLLQHandshakeCallback
437 Revision 1.55 2004/07/15 19:01:33 ksekar
438 <rdar://problem/3681029>: Check for incorrect time comparisons
440 Revision 1.54 2004/06/22 02:10:53 ksekar
441 <rdar://problem/3705433>: Lighthouse failure causes packet flood to DNS
443 Revision 1.53 2004/06/17 20:49:09 ksekar
444 <rdar://problem/3690436>: mDNSResponder crash while location cycling
446 Revision 1.52 2004/06/17 01:13:11 ksekar
447 <rdar://problem/3696616>: polling interval too short
449 Revision 1.51 2004/06/10 04:36:44 cheshire
452 Revision 1.50 2004/06/10 00:55:13 ksekar
453 <rdar://problem/3686213>: crash on network reconnect
455 Revision 1.49 2004/06/10 00:10:50 ksekar
456 <rdar://problem/3686174>: Infinite Loop in uDNS_Execute()
458 Revision 1.48 2004/06/09 20:03:37 ksekar
459 <rdar://problem/3686163>: Incorrect copying of resource record in deregistration
461 Revision 1.47 2004/06/09 03:48:28 ksekar
462 <rdar://problem/3685226>: nameserver address fails with prod. Lighthouse server
464 Revision 1.46 2004/06/09 01:44:30 ksekar
465 <rdar://problem/3681378> reworked Cache Record copy code
467 Revision 1.45 2004/06/08 18:54:47 ksekar
468 <rdar://problem/3681378>: mDNSResponder leaks after exploring in Printer Setup Utility
470 Revision 1.44 2004/06/05 00:33:51 cheshire
471 <rdar://problem/3681029>: Check for incorrect time comparisons
473 Revision 1.43 2004/06/05 00:14:44 cheshire
474 Fix signed/unsigned and other compiler warnings
476 Revision 1.42 2004/06/04 22:36:16 ksekar
477 Properly set u->nextevent in uDNS_Execute
479 Revision 1.41 2004/06/04 08:58:29 ksekar
480 <rdar://problem/3668624>: Keychain integration for secure dynamic update
482 Revision 1.40 2004/06/03 03:09:58 ksekar
483 <rdar://problem/3668626>: Garbage Collection for Dynamic Updates
485 Revision 1.39 2004/06/01 23:46:50 ksekar
486 <rdar://problem/3675149>: DynDNS: dynamically look up LLQ/Update ports
488 Revision 1.38 2004/05/31 22:19:44 ksekar
489 <rdar://problem/3258021>: Feature: DNS server->client notification on
490 record changes (#7805) - revert to polling mode on setup errors
492 Revision 1.37 2004/05/28 23:42:37 ksekar
493 <rdar://problem/3258021>: Feature: DNS server->client notification on record changes (#7805)
495 Revision 1.36 2004/05/18 23:51:25 cheshire
496 Tidy up all checkin comments to use consistent "<rdar://problem/xxxxxxx>" format for bug numbers
498 Revision 1.35 2004/05/07 23:01:04 ksekar
499 Cleaned up list traversal in deriveGoodbyes - removed unnecessary
500 conditional assignment.
502 Revision 1.34 2004/05/05 18:26:12 ksekar
503 Periodically re-transmit questions if the send() fails. Include
504 internal questions in retransmission.
506 Revision 1.33 2004/05/05 17:40:06 ksekar
507 Removed prerequisite from deregistration update - it does not work for
508 shared records, and is unnecessary until we have more sophisticated
509 name conflict management.
511 Revision 1.32 2004/05/05 17:32:18 ksekar
512 Prevent registration of loopback interface caused by removal of
513 Multicast flag in interface structure.
515 Revision 1.31 2004/05/05 17:05:02 ksekar
516 Use LargeCacheRecord structs when pulling records off packets
518 Revision 1.30 2004/04/16 21:33:27 ksekar
519 Fixed bug in processing GetZoneData responses that do not use BIND formatting.
521 Revision 1.29 2004/04/15 20:03:13 ksekar
522 Clarified log message when pulling bad resource records off packet.
524 Revision 1.28 2004/04/15 00:51:28 bradley
525 Minor tweaks for Windows and C++ builds. Added casts for signed/unsigned integers and 64-bit pointers.
526 Prefix some functions with mDNS to avoid conflicts. Disable benign warnings on Microsoft compilers.
528 Revision 1.27 2004/04/14 23:09:28 ksekar
529 Support for TSIG signed dynamic updates.
531 Revision 1.26 2004/04/14 19:36:05 ksekar
532 Fixed memory corruption error in deriveGoodbyes.
534 Revision 1.25 2004/04/14 04:07:11 ksekar
535 Fixed crash in IsActiveUnicastQuery(). Removed redundant checks in routine.
537 Revision 1.24 2004/04/08 09:41:40 bradley
538 Added const to AuthRecord in deadvertiseIfCallback to match callback typedef.
540 Revision 1.23 2004/03/24 00:29:45 ksekar
541 Make it safe to call StopQuery in a unicast question callback
543 Revision 1.22 2004/03/19 10:11:09 bradley
544 Added AuthRecord * cast from umalloc for C++ builds.
546 Revision 1.21 2004/03/15 02:03:45 bradley
547 Added const to params where needed to match prototypes. Changed SetNewRData calls to use 0 instead
548 of -1 for unused size to fix warning. Disable assignment within conditional warnings with Visual C++.
550 Revision 1.20 2004/03/13 02:07:26 ksekar
551 <rdar://problem/3192546>: DynDNS: Dynamic update of service records
553 Revision 1.19 2004/03/13 01:57:33 ksekar
554 <rdar://problem/3192546>: DynDNS: Dynamic update of service records
556 Revision 1.18 2004/02/21 08:34:15 bradley
557 Added casts from void * to specific type for C++ builds. Changed void * l-value cast
558 r-value cast to fix problems with VC++ builds. Removed empty switch to fix VC++ error.
560 Revision 1.17 2004/02/21 02:06:24 cheshire
561 Can't use anonymous unions -- they're non-standard and don't work on all compilers
563 Revision 1.16 2004/02/12 01:51:45 cheshire
564 Don't try to send uDNS queries unless we have at least one uDNS server available
566 Revision 1.15 2004/02/10 03:02:46 cheshire
569 Revision 1.14 2004/02/06 23:04:19 ksekar
570 Basic Dynamic Update support via mDNS_Register (dissabled via
571 UNICAST_REGISTRATION #define)
573 Revision 1.13 2004/02/03 22:15:01 ksekar
574 Fixed nameToAddr error check: don't abort state machine on nxdomain error.
576 Revision 1.12 2004/02/03 19:47:36 ksekar
577 Added an asynchronous state machine mechanism to uDNS.c, including
578 calls to find the parent zone for a domain name. Changes include code
579 in repository previously dissabled via "#if 0 incomplete". Codepath
580 is currently unused, and will be called to create update records, etc.
582 Revision 1.11 2004/01/30 02:12:30 ksekar
583 Changed uDNS_ReceiveMsg() to correctly return void.
585 Revision 1.10 2004/01/29 02:59:17 ksekar
586 Unicast DNS: Changed from a resource record oriented question/response
587 matching to packet based matching. New callback architecture allows
588 collections of records in a response to be processed differently
589 depending on the nature of the request, and allows the same structure
590 to be used for internal and client-driven queries with different processing needs.
592 Revision 1.9 2004/01/28 20:20:45 ksekar
593 Unified ActiveQueries and ActiveInternalQueries lists, using a flag to
594 demux them. Check-in includes work-in-progress code, #ifdef'd out.
596 Revision 1.8 2004/01/28 02:30:07 ksekar
597 Added default Search Domains to unicast browsing, controlled via
598 Networking sharing prefs pane. Stopped sending unicast messages on
599 every interface. Fixed unicast resolving via mach-port API.
601 Revision 1.7 2004/01/27 20:15:22 cheshire
602 <rdar://problem/3541288>: Time to prune obsolete code for listening on port 53
604 Revision 1.6 2004/01/24 23:47:17 cheshire
605 Use mDNSOpaque16fromIntVal() instead of shifting and masking
607 Revision 1.5 2004/01/24 04:59:15 cheshire
608 Fixes so that Posix/Linux, OS9, Windows, and VxWorks targets build again
610 Revision 1.4 2004/01/24 04:19:26 cheshire
611 Restore overwritten checkin 1.2
613 Revision 1.3 2004/01/23 23:23:15 ksekar
614 Added TCP support for truncated unicast messages.
616 Revision 1.2 2004/01/22 03:48:41 cheshire
617 Make sure uDNS client doesn't accidentally use query ID zero
619 Revision 1.1 2003/12/13 03:05:27 ksekar
620 <rdar://problem/3192548>: DynDNS: Unicast query of service records
626 #if(defined(_MSC_VER))
627 // Disable "assignment within conditional expression".
628 // Other compilers understand the convention that if you place the assignment expression within an extra pair
629 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
630 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
631 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
632 #pragma warning(disable:4706)
635 #define umalloc(x) mDNSPlatformMemAllocate(x) // short hands for common routines
636 #define ufree(x) mDNSPlatformMemFree(x)
637 #define ubzero(x,y) mDNSPlatformMemZero(x,y)
638 #define umemcpy(x, y, l) mDNSPlatformMemCopy(y, x, l) // uses memcpy(2) arg ordering
640 // Asynchronous operation types
645 // other async. operation names go here
651 mDNSAddr primaryAddr
;
654 mDNSIPPort updatePort
;
657 // other async. result struct defs go here
661 AsyncOpResultType type
;
663 // other async result structs go here
666 typedef void AsyncOpCallback(mStatus err
, mDNS
*const m
, void *info
, const AsyncOpResult
*result
);
669 // Private Function Prototypes
670 // Note: In general, functions are ordered such that they do not require forward declarations.
671 // However, prototypes are used where cyclic call graphs exist (e.g. foo calls bar, and bar calls
672 // foo), or when they aid in the grouping or readability of code (e.g. state machine code that is easier
673 // read top-to-bottom.)
675 mDNSlocal mDNSBool
FreeNATInfo(mDNS
*m
, NATTraversalInfo
*n
);
676 mDNSlocal
void hndlTruncatedAnswer(DNSQuestion
*question
, const mDNSAddr
*src
, mDNS
*m
);
677 mDNSlocal mStatus
startGetZoneData(domainname
*name
, mDNS
*m
, mDNSBool findUpdatePort
, mDNSBool findLLQPort
, AsyncOpCallback callback
, void *callbackInfo
);
678 mDNSlocal mDNSBool
recvLLQResponse(mDNS
*m
, DNSMessage
*msg
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, mDNSIPPort srcport
, const mDNSInterfaceID InterfaceID
);
679 mDNSlocal
void sendRecordRegistration(mDNS
*const m
, AuthRecord
*rr
);
680 mDNSlocal
void SendServiceRegistration(mDNS
*m
, ServiceRecordSet
*srs
);
681 mDNSlocal
void SendServiceDeregistration(mDNS
*m
, ServiceRecordSet
*srs
);
682 mDNSlocal
void serviceRegistrationCallback(mStatus err
, mDNS
*const m
, void *srsPtr
, const AsyncOpResult
*result
);
683 mDNSlocal
void SendRecordUpdate(mDNS
*m
, AuthRecord
*rr
, uDNS_RegInfo
*info
);
684 mDNSlocal
void SuspendLLQs(mDNS
*m
, mDNSBool DeregisterActive
);
685 mDNSlocal
void RestartQueries(mDNS
*m
);
686 mDNSlocal
void startLLQHandshake(mDNS
*m
, LLQ_Info
*info
, mDNSBool defer
);
687 mDNSlocal
void llqResponseHndlr(mDNS
* const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
, void *context
);
689 // ***************************************************************************
690 #if COMPILER_LIKES_PRAGMA_MARK
691 #pragma mark - Temporary workaround
694 // 17 Places in this file directly call mDNSPlatformTimeNow(), which is unsafe
695 // The platform function is now called mDNSPlatformRawTime(), and
696 // mDNSPlatformTimeNow() is defined here as a temporary workaround.
697 // This is a gross hack, and after this change has been tested for a while,
698 // all these calls should be replaced by simple references to m->timenow
700 mDNSlocal mDNSs32
mDNSPlatformTimeNow(mDNS
*m
)
702 if (m
->mDNS_busy
&& m
->timenow
) return(m
->timenow
);
703 LogMsg("ERROR: uDNS.c code executing without holding main mDNS lock");
705 // To get a quick and easy stack trace to find out *how* this routine
706 // is being called without holding main mDNS lock, uncomment the line below:
709 return(mDNS_TimeNow(m
));
712 // ***************************************************************************
713 #if COMPILER_LIKES_PRAGMA_MARK
714 #pragma mark - General Utility Functions
717 // CountLabels() returns number of labels in name, excluding final root label
718 // (e.g. for "apple.com." CountLabels returns 2.)
719 mDNSlocal
int CountLabels(const domainname
*d
)
724 for (ptr
= d
->c
; *ptr
; ptr
= ptr
+ ptr
[0] + 1) count
++;
728 mDNSlocal mDNSOpaque16
newMessageID(uDNS_GlobalInfo
*u
)
730 static mDNSBool randomized
= mDNSfalse
;
732 if (!randomized
) { u
->NextMessageID
= (mDNSu16
)mDNSRandom(0xFFFF); randomized
= mDNStrue
; }
733 if (u
->NextMessageID
== 0) u
->NextMessageID
++;
734 return mDNSOpaque16fromIntVal(u
->NextMessageID
++);
737 // unlink an AuthRecord from a linked list
738 mDNSlocal mStatus
unlinkAR(AuthRecord
**list
, AuthRecord
*const rr
)
740 AuthRecord
*rptr
, *prev
= mDNSNULL
;
742 for (rptr
= *list
; rptr
; rptr
= rptr
->next
)
746 if (prev
) prev
->next
= rptr
->next
;
747 else *list
= rptr
->next
;
748 rptr
->next
= mDNSNULL
;
749 return mStatus_NoError
;
753 LogMsg("ERROR: unlinkAR - no such active record");
754 return mStatus_UnknownErr
;
757 mDNSlocal
void unlinkSRS(mDNS
*m
, ServiceRecordSet
*srs
)
759 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
760 ServiceRecordSet
**p
;
761 NATTraversalInfo
*n
= u
->NATTraversals
;
763 // verify that no NAT objects reference this service
766 if (n
->reg
.ServiceRegistration
== srs
)
768 NATTraversalInfo
*tmp
= n
;
770 LogMsg("ERROR: Unlinking service record set %##s still referenced by NAT traversal object!", srs
->RR_SRV
.resrec
.name
->c
);
776 for (p
= &u
->ServiceRegistrations
; *p
; p
= &(*p
)->next
)
777 if (*p
== srs
) { *p
= srs
->next
; srs
->next
= mDNSNULL
; return; }
778 LogMsg("ERROR: unlinkSRS - SRS not found in ServiceRegistrations list");
781 mDNSlocal
void LinkActiveQuestion(uDNS_GlobalInfo
*u
, DNSQuestion
*q
)
783 if (uDNS_IsActiveQuery(q
, u
))
784 { LogMsg("LinkActiveQuestion - %##s (%d) already in list!", q
->qname
.c
, q
->qtype
); return; }
786 q
->next
= u
->ActiveQueries
;
787 u
->ActiveQueries
= q
;
790 mDNSlocal
void SwapRData(mDNS
*m
, AuthRecord
*rr
, mDNSBool DeallocOld
)
792 RData
*oldrd
= rr
->resrec
.rdata
;
793 mDNSu16 oldrdlen
= rr
->resrec
.rdlength
;
795 if (!rr
->uDNS_info
.UpdateRData
) { LogMsg("SwapRData invoked with NULL UpdateRData field"); return; }
796 SetNewRData(&rr
->resrec
, rr
->uDNS_info
.UpdateRData
, rr
->uDNS_info
.UpdateRDLen
);
799 rr
->uDNS_info
.UpdateRData
= mDNSNULL
; // Clear the NewRData pointer ...
800 if (rr
->uDNS_info
.UpdateRDCallback
) rr
->uDNS_info
.UpdateRDCallback(m
, rr
, oldrd
); // ... and let the client know
804 rr
->uDNS_info
.UpdateRData
= oldrd
;
805 rr
->uDNS_info
.UpdateRDLen
= oldrdlen
;
809 // set retry timestamp for record with exponential backoff
810 // (for service record sets, use RR_SRV as representative for time checks
811 mDNSlocal
void SetRecordRetry(mDNS
*const m
, AuthRecord
*rr
)
813 rr
->LastAPTime
= mDNSPlatformTimeNow(m
);
814 if (rr
->ThisAPInterval
< INIT_UCAST_POLL_INTERVAL
) { rr
->ThisAPInterval
= INIT_UCAST_POLL_INTERVAL
; return; }
815 if (rr
->ThisAPInterval
*2 <= MAX_UCAST_POLL_INTERVAL
) { rr
->ThisAPInterval
*= 2; return; }
816 if (rr
->ThisAPInterval
!= MAX_UCAST_POLL_INTERVAL
) { rr
->ThisAPInterval
= MAX_UCAST_POLL_INTERVAL
; }
820 // ***************************************************************************
821 #if COMPILER_LIKES_PRAGMA_MARK
822 #pragma mark - Name Server List Management
825 mDNSexport
void mDNS_AddDNSServer(mDNS
*const m
, const mDNSAddr
*addr
, const domainname
*d
)
827 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
828 DNSServer
*s
, **p
= &u
->Servers
;
831 if (!d
) d
= (domainname
*)"";
833 while (*p
) // Check if we already have this {server,domain} pair registered
835 if (mDNSSameAddress(&(*p
)->addr
, addr
) && SameDomainName(&(*p
)->domain
, d
))
836 LogMsg("Note: DNS Server %#a for domain %##s registered more than once", addr
, d
->c
);
840 // allocate, add to list
841 s
= umalloc(sizeof(*s
));
842 if (!s
) { LogMsg("Error: mDNS_AddDNSServer - malloc"); goto end
; }
844 AssignDomainName(&s
->domain
, d
);
852 mDNSexport
void mDNS_DeleteDNSServers(mDNS
*const m
)
857 s
= m
->uDNS_info
.Servers
;
858 m
->uDNS_info
.Servers
= mDNSNULL
;
869 // ***************************************************************************
870 #if COMPILER_LIKES_PRAGMA_MARK
871 #pragma mark - authorization management
874 mDNSlocal uDNS_AuthInfo
*GetAuthInfoForZone(const uDNS_GlobalInfo
*u
, const domainname
*zone
)
879 for (ptr
= u
->AuthInfoList
; ptr
; ptr
= ptr
->next
)
880 if (SameDomainName(&ptr
->zone
, zone
)) return(ptr
);
881 zone
= (const domainname
*)(zone
->c
+ 1 + zone
->c
[0]);
886 mDNSlocal
void DeleteAuthInfoForZone(uDNS_GlobalInfo
*u
, const domainname
*zone
)
888 uDNS_AuthInfo
*ptr
, *prev
= mDNSNULL
;
890 for (ptr
= u
->AuthInfoList
; ptr
; ptr
= ptr
->next
)
892 if (SameDomainName(&ptr
->zone
, zone
))
894 if (prev
) prev
->next
= ptr
->next
;
895 else u
->AuthInfoList
= ptr
->next
;
903 mDNSexport mStatus
mDNS_SetSecretForZone(mDNS
*m
, const domainname
*zone
, const domainname
*key
, const char *sharedSecret
, mDNSu32 ssLen
, mDNSBool base64
)
908 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
909 mStatus status
= mStatus_NoError
;
913 if (GetAuthInfoForZone(u
, zone
)) DeleteAuthInfoForZone(u
, zone
);
916 info
= (uDNS_AuthInfo
*)umalloc(sizeof(uDNS_AuthInfo
) + ssLen
);
917 if (!info
) { LogMsg("ERROR: umalloc"); status
= mStatus_NoMemoryErr
; goto exit
; }
918 ubzero(info
, sizeof(uDNS_AuthInfo
));
919 AssignDomainName(&info
->zone
, zone
);
920 AssignDomainName(&info
->keyname
, key
);
924 keylen
= DNSDigest_Base64ToBin(sharedSecret
, keybuf
, 1024);
927 LogMsg("ERROR: mDNS_UpdateDomainRequiresAuthentication - could not convert shared secret from base64");
929 status
= mStatus_UnknownErr
;
932 DNSDigest_ConstructHMACKey(info
, keybuf
, (mDNSu32
)keylen
);
934 else DNSDigest_ConstructHMACKey(info
, (mDNSu8
*)sharedSecret
, ssLen
);
937 info
->next
= m
->uDNS_info
.AuthInfoList
;
938 m
->uDNS_info
.AuthInfoList
= info
;
944 // ***************************************************************************
945 #if COMPILER_LIKES_PRAGMA_MARK
946 #pragma mark - NAT Traversal
949 mDNSlocal mDNSBool
DomainContainsLabelString(const domainname
*d
, const char *str
)
951 const domainlabel
*l
;
954 if (!MakeDomainLabelFromLiteralString(&buf
, str
)) return mDNSfalse
;
956 for (l
= (const domainlabel
*)d
; l
->c
[0]; l
= (const domainlabel
*)(l
->c
+ l
->c
[0]+1))
957 if (SameDomainLabel(l
->c
, buf
.c
)) return mDNStrue
;
961 // allocate struct, link into global list, initialize
962 mDNSlocal NATTraversalInfo
*AllocNATInfo(mDNS
*const m
, NATOp_t op
, NATResponseHndlr callback
)
964 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
965 NATTraversalInfo
*info
= umalloc(sizeof(NATTraversalInfo
));
966 if (!info
) { LogMsg("ERROR: malloc"); return mDNSNULL
; }
967 ubzero(info
, sizeof(NATTraversalInfo
));
968 info
->next
= u
->NATTraversals
;
969 u
->NATTraversals
= info
;
970 info
->retry
= mDNSPlatformTimeNow(m
) + NATMAP_INIT_RETRY
;
972 info
->state
= NATState_Init
;
973 info
->ReceiveResponse
= callback
;
974 info
->PublicPort
.NotAnInteger
= 0;
975 info
->Router
= u
->Router
;
979 // unlink from list, deallocate
980 mDNSlocal mDNSBool
FreeNATInfo(mDNS
*m
, NATTraversalInfo
*n
)
982 NATTraversalInfo
*ptr
, *prev
= mDNSNULL
;
983 ServiceRecordSet
*s
= m
->uDNS_info
.ServiceRegistrations
;
985 // Verify that object is not referenced by any services
988 if (s
->uDNS_info
.NATinfo
== n
)
990 LogMsg("Error: Freeing NAT info object still referenced by Service Record Set %##s!", s
->RR_SRV
.resrec
.name
->c
);
991 s
->uDNS_info
.NATinfo
= mDNSNULL
;
996 if (n
== m
->uDNS_info
.LLQNatInfo
) m
->uDNS_info
.LLQNatInfo
= mDNSNULL
;
997 ptr
= m
->uDNS_info
.NATTraversals
;
1002 if (prev
) prev
->next
= ptr
->next
;
1003 else m
->uDNS_info
.NATTraversals
= ptr
->next
;
1010 LogMsg("FreeNATInfo: NATTraversalInfo not found in list");
1014 mDNSlocal
void SendNATMsg(NATTraversalInfo
*info
, mDNS
*m
)
1019 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1021 if (info
->state
!= NATState_Request
&& info
->state
!= NATState_Refresh
)
1022 { LogMsg("SendNATMsg: Bad state %d", info
->state
); return; }
1024 if (u
->Router
.ip
.v4
.NotAnInteger
)
1026 // send msg if we have a router
1027 const mDNSu8
*end
= (mDNSu8
*)&info
->request
;
1028 if (info
->op
== NATOp_AddrRequest
) end
+= sizeof(NATAddrRequest
);
1029 else end
+= sizeof(NATPortMapRequest
);
1031 dst
.type
= u
->Router
.type
;
1032 dst
.ip
.v4
= u
->Router
.ip
.v4
;
1033 dstport
= mDNSOpaque16fromIntVal(NATMAP_PORT
);
1034 err
= mDNSPlatformSendUDP(m
, &info
->request
, end
, 0, &dst
, dstport
);
1035 if (!err
) (info
->ntries
++); // don't increment attempt counter if the send failed
1039 if (info
->RetryInterval
< NATMAP_INIT_RETRY
) info
->RetryInterval
= NATMAP_INIT_RETRY
;
1040 else if (info
->RetryInterval
* 2 > NATMAP_MAX_RETRY
) info
->RetryInterval
= NATMAP_MAX_RETRY
;
1041 else info
->RetryInterval
*= 2;
1042 info
->retry
= mDNSPlatformTimeNow(m
) + info
->RetryInterval
;
1045 mDNSlocal
void ReceiveNATAddrResponse(NATTraversalInfo
*n
, mDNS
*m
, mDNSu8
*pkt
, mDNSu16 len
)
1047 mStatus err
= mStatus_NoError
;
1048 AuthRecord
*rr
= mDNSNULL
;
1049 NATAddrReply
*response
= (NATAddrReply
*)pkt
;
1052 if (n
->state
!= NATState_Request
)
1054 LogMsg("ReceiveNATAddrResponse: bad state %d", n
->state
);
1055 err
= mStatus_UnknownErr
;
1059 rr
= n
->reg
.RecordRegistration
;
1062 LogMsg("ReceiveNATAddrResponse: registration cancelled");
1063 err
= mStatus_UnknownErr
;
1067 addr
.type
= mDNSAddrType_IPv4
;
1068 addr
.ip
.v4
= rr
->resrec
.rdata
->u
.ipv4
;
1070 if (!pkt
) // timeout
1072 #ifdef _LEGACY_NAT_TRAVERSAL_
1073 err
= LNT_GetPublicIP(&addr
.ip
.v4
);
1075 else n
->state
= NATState_Legacy
;
1077 debugf("ReceiveNATAddrResponse: timeout");
1078 err
= mStatus_NATTraversal
;
1080 #endif // _LEGACY_NAT_TRAVERSAL_
1084 if (len
< sizeof(*response
))
1086 LogMsg("ReceiveNATAddrResponse: response too short (%d bytes)", len
);
1087 err
= mStatus_NATTraversal
;
1090 if (response
->vers
!= NATMAP_VERS
)
1092 LogMsg("ReceiveNATAddrResponse: received version %d (expect version %d)", pkt
[0], NATMAP_VERS
);
1093 err
= mStatus_NATTraversal
;
1096 if (response
->opcode
!= (NATOp_AddrRequest
| NATMAP_RESPONSE_MASK
))
1098 LogMsg("ReceiveNATAddrResponse: bad response code %d", response
->opcode
);
1099 err
= mStatus_NATTraversal
;
1102 if (response
->err
.NotAnInteger
)
1103 { LogMsg("ReceiveAddrResponse: received error %d", mDNSVal16(response
->err
)); err
= mStatus_NATTraversal
; goto end
; }
1105 addr
.ip
.v4
= response
->PubAddr
;
1106 n
->state
= NATState_Established
;
1109 if (IsPrivateV4Addr(&addr
))
1111 LogMsg("ReceiveNATAddrResponse: Double NAT");
1112 err
= mStatus_DoubleNAT
;
1122 rr
->uDNS_info
.NATinfo
= mDNSNULL
;
1123 rr
->uDNS_info
.state
= regState_Unregistered
; // note that rr is not yet in global list
1124 rr
->RecordCallback(m
, rr
, mStatus_NATTraversal
);
1125 // note - unsafe to touch rr after callback
1129 else LogMsg("Received public IP address %d.%d.%d.%d from NAT.", addr
.ip
.v4
.b
[0], addr
.ip
.v4
.b
[1], addr
.ip
.v4
.b
[2], addr
.ip
.v4
.b
[3]);
1130 rr
->resrec
.rdata
->u
.ipv4
= addr
.ip
.v4
; // replace rdata w/ public address
1131 uDNS_RegisterRecord(m
, rr
);
1135 mDNSlocal
void StartGetPublicAddr(mDNS
*m
, uDNS_HostnameInfo
*hInfo
)
1137 NATAddrRequest
*req
;
1138 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1140 NATTraversalInfo
*info
= AllocNATInfo(m
, NATOp_AddrRequest
, ReceiveNATAddrResponse
);
1141 if (!info
) { uDNS_RegisterRecord(m
, hInfo
->ar
); return; }
1142 hInfo
->ar
->uDNS_info
.NATinfo
= info
;
1143 info
->reg
.RecordRegistration
= hInfo
->ar
;
1144 info
->state
= NATState_Request
;
1147 req
= &info
->request
.AddrReq
;
1148 req
->vers
= NATMAP_VERS
;
1149 req
->opcode
= NATOp_AddrRequest
;
1151 if (!u
->Router
.ip
.v4
.NotAnInteger
)
1153 debugf("No router. Will retry NAT traversal in %ld ticks", NATMAP_INIT_RETRY
);
1157 SendNATMsg(info
, m
);
1161 mDNSlocal
void RefreshNATMapping(NATTraversalInfo
*n
, mDNS
*m
)
1163 n
->state
= NATState_Refresh
;
1164 n
->RetryInterval
= NATMAP_INIT_RETRY
;
1169 mDNSlocal
void LLQNatMapComplete(mDNS
*m
)
1171 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1173 NATTraversalInfo
*n
= u
->LLQNatInfo
;
1175 if (!n
) { LogMsg("Error: LLQNatMapComplete called with NULL LLQNatInfo"); return; }
1176 if (n
->state
!= NATState_Established
&& n
->state
!= NATState_Legacy
&& n
->state
!= NATState_Error
)
1177 { LogMsg("LLQNatMapComplete - bad nat state %d", n
->state
); return; }
1179 u
->CurrentQuery
= u
->ActiveQueries
;
1180 while (u
->CurrentQuery
)
1182 DNSQuestion
*q
= u
->CurrentQuery
;
1183 u
->CurrentQuery
= u
->CurrentQuery
->next
;
1184 llqInfo
= q
->uDNS_info
.llq
;
1185 if (q
->LongLived
&& llqInfo
->state
== LLQ_NatMapWait
)
1187 if (n
->state
== NATState_Error
)
1189 llqInfo
->NATMap
= mDNSfalse
;
1190 llqInfo
->question
->uDNS_info
.responseCallback
= llqResponseHndlr
;
1191 llqInfo
->state
= LLQ_Poll
;
1192 llqInfo
->question
->LastQTime
= mDNSPlatformTimeNow(m
) - (2 * INIT_UCAST_POLL_INTERVAL
); // trigger immediate poll
1193 llqInfo
->question
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
;
1195 else { llqInfo
->state
= LLQ_GetZoneInfo
; startLLQHandshake(m
, llqInfo
, mDNSfalse
); }
1200 mDNSlocal
void ReceivePortMapReply(NATTraversalInfo
*n
, mDNS
*m
, mDNSu8
*pkt
, mDNSu16 len
)
1202 ServiceRecordSet
*srs
;
1206 NATPortMapReply
*reply
= (NATPortMapReply
*)pkt
;
1208 if (n
->state
!= NATState_Request
&& n
->state
!= NATState_Refresh
)
1209 { LogMsg("ReceivePortMapReply: bad state %d", n
->state
); return; }
1211 deletion
= (!n
->request
.PortReq
.lease
.NotAnInteger
);
1212 if (deletion
) { n
->state
= NATState_Deleted
; return; }
1213 // note that we explicitly ignore timeouts here
1214 // we keep the context struct around so that the SendServiceDeregistration code can reference
1215 // it to determine the public port to delete in the SRV record.
1217 srs
= n
->reg
.ServiceRegistration
;
1218 if (!srs
&& n
!= m
->uDNS_info
.LLQNatInfo
)
1220 debugf("ReceivePortMapReply: registration cancelled");
1225 priv
= srs
? srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
: m
->UnicastPort4
;
1227 if (!pkt
) // timeout
1229 #ifdef _LEGACY_NAT_TRAVERSAL_
1233 mDNSBool tcp
= (srs
&& DomainContainsLabelString(srs
->RR_PTR
.resrec
.name
, "_tcp"));
1235 pub
= priv
; // initially request priv == pub
1238 err
= LNT_MapPort(priv
, pub
, tcp
);
1241 n
->PublicPort
= pub
;
1242 n
->state
= NATState_Legacy
;
1245 else if (err
!= mStatus_AlreadyRegistered
|| ++ntries
> LEGACY_NATMAP_MAX_TRIES
)
1247 n
->state
= NATState_Error
;
1252 // the mapping we want is taken - try a random port
1253 mDNSu16 RandPort
= mDNSRandom(DYN_PORT_MAX
- DYN_PORT_MIN
) + DYN_PORT_MIN
;
1254 pub
= mDNSOpaque16fromIntVal(RandPort
);
1259 #endif // _LEGACY_NAT_TRAVERSAL_
1262 if (len
< sizeof(*reply
)) { LogMsg("ReceivePortMapReply: response too short (%d bytes)", len
); goto end
; }
1263 if (reply
->vers
!= NATMAP_VERS
) { LogMsg("ReceivePortMapReply: received version %d (expect version %d)", pkt
[0], NATMAP_VERS
); goto end
; }
1264 if (reply
->opcode
!= (n
->op
| NATMAP_RESPONSE_MASK
)) { LogMsg("ReceivePortMapReply: bad response code %d", pkt
[1]); goto end
; }
1265 if (reply
->err
.NotAnInteger
) { LogMsg("ReceivePortMapReply: received error %d", mDNSVal16(reply
->err
)); goto end
; }
1266 if (priv
.NotAnInteger
!= reply
->priv
.NotAnInteger
)
1267 { LogMsg("ReceivePortMapReply: reply private port does not match requested private port"); goto end
; }
1269 lease
= (mDNSu32
)mDNSVal32(reply
->lease
);
1270 if (lease
> 0x70000000UL
/ mDNSPlatformOneSecond
) lease
= 0x70000000UL
/ mDNSPlatformOneSecond
;
1272 if (n
->state
== NATState_Refresh
&& reply
->pub
.NotAnInteger
!= n
->PublicPort
.NotAnInteger
)
1273 LogMsg("ReceivePortMapReply: NAT refresh changed public port from %d to %d", mDNSVal16(n
->PublicPort
), mDNSVal16(reply
->pub
));
1274 // !!!KRS we need to update the SRV here!
1275 n
->PublicPort
= reply
->pub
;
1277 n
->retry
= mDNSPlatformTimeNow(m
) + ((mDNSs32
)lease
* mDNSPlatformOneSecond
/ 2); // retry half way to expiration
1279 if (n
->state
== NATState_Refresh
) { n
->state
= NATState_Established
; return; }
1280 n
->state
= NATState_Established
;
1283 if (n
->state
!= NATState_Established
&& n
->state
!= NATState_Legacy
)
1285 LogMsg("NAT Port Mapping: timeout");
1286 n
->state
= NATState_Error
;
1287 if (srs
) srs
->uDNS_info
.state
= regState_NATError
;
1288 else LLQNatMapComplete(m
);
1289 return; // note - unsafe to touch srs here
1292 LogMsg("Mapped private port %d to public port %d", mDNSVal16(priv
), mDNSVal16(n
->PublicPort
));
1293 if (!srs
) { LLQNatMapComplete(m
); return; }
1295 if (srs
->uDNS_info
.ns
.ip
.v4
.NotAnInteger
) SendServiceRegistration(m
, srs
); // non-zero server address means we already have necessary zone data to send update
1298 srs
->uDNS_info
.state
= regState_FetchingZoneData
;
1299 startGetZoneData(srs
->RR_SRV
.resrec
.name
, m
, mDNStrue
, mDNSfalse
, serviceRegistrationCallback
, srs
);
1303 mDNSlocal
void FormatPortMaprequest(NATTraversalInfo
*info
, mDNSIPPort port
)
1305 NATPortMapRequest
*req
= &info
->request
.PortReq
;
1307 req
->vers
= NATMAP_VERS
;
1308 req
->opcode
= info
->op
;
1309 req
->unused
.NotAnInteger
= 0;
1312 req
->lease
= mDNSOpaque32fromIntVal(NATMAP_DEFAULT_LEASE
);
1315 mDNSlocal
void SendInitialPMapReq(mDNS
*m
, NATTraversalInfo
*info
)
1317 if (!m
->uDNS_info
.Router
.ip
.v4
.NotAnInteger
)
1319 debugf("No router. Will retry NAT traversal in %ld seconds", NATMAP_INIT_RETRY
);
1320 info
->retry
= mDNSPlatformTimeNow(m
) + NATMAP_INIT_RETRY
;
1321 info
->RetryInterval
= NATMAP_INIT_RETRY
;
1324 SendNATMsg(info
, m
);
1328 mDNSlocal
void StartNATPortMap(mDNS
*m
, ServiceRecordSet
*srs
)
1331 NATTraversalInfo
*info
;
1333 if (DomainContainsLabelString(srs
->RR_PTR
.resrec
.name
, "_tcp")) op
= NATOp_MapTCP
;
1334 else if (DomainContainsLabelString(srs
->RR_PTR
.resrec
.name
, "_udp")) op
= NATOp_MapUDP
;
1335 else { LogMsg("StartNATPortMap: could not determine transport protocol of service %##s", srs
->RR_SRV
.resrec
.name
->c
); goto error
; }
1337 if (srs
->uDNS_info
.NATinfo
) { LogMsg("Error: StartNATPortMap - NAT info already initialized!"); FreeNATInfo(m
, srs
->uDNS_info
.NATinfo
); }
1338 info
= AllocNATInfo(m
, op
, ReceivePortMapReply
);
1339 srs
->uDNS_info
.NATinfo
= info
;
1340 info
->reg
.ServiceRegistration
= srs
;
1341 info
->state
= NATState_Request
;
1343 FormatPortMaprequest(info
, srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
);
1344 SendInitialPMapReq(m
, info
);
1348 startGetZoneData(srs
->RR_SRV
.resrec
.name
, m
, mDNStrue
, mDNSfalse
, serviceRegistrationCallback
, srs
);
1351 mDNSlocal
void DeleteNATPortMapping(mDNS
*m
, NATTraversalInfo
*nat
, ServiceRecordSet
*srs
)
1353 if (nat
->state
== NATState_Established
) // let other edge-case states expire for simplicity
1356 nat
->request
.PortReq
.lease
.NotAnInteger
= 0;
1357 nat
->state
= NATState_Request
;
1360 #ifdef _LEGACY_NAT_TRAVERSAL_
1361 else if (nat
->state
== NATState_Legacy
)
1363 mStatus err
= mStatus_NoError
;
1364 mDNSBool tcp
= srs
? DomainContainsLabelString(srs
->RR_PTR
.resrec
.name
, "_tcp") : mDNSfalse
;
1365 err
= LNT_UnmapPort(nat
->PublicPort
, tcp
);
1366 if (err
) LogMsg("Legacy NAT Traversal - unmap request failed with error %ld", err
);
1369 (void)srs
; // unused
1370 #endif // _LEGACY_NAT_TRAVERSAL_
1373 mDNSlocal
void StartLLQNatMap(mDNS
*m
)
1375 NATTraversalInfo
*info
= AllocNATInfo(m
, NATOp_MapUDP
, ReceivePortMapReply
);
1376 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1378 u
->LLQNatInfo
= info
;
1380 info
->reg
.RecordRegistration
= mDNSNULL
;
1381 info
->reg
.ServiceRegistration
= mDNSNULL
;
1382 info
->state
= NATState_Request
;
1383 FormatPortMaprequest(info
, m
->UnicastPort4
);
1384 SendInitialPMapReq(m
, info
);
1388 // if LLQ NAT context unreferenced, delete the mapping
1389 mDNSlocal
void CheckForUnreferencedLLQMapping(mDNS
*m
)
1391 NATTraversalInfo
*nat
= m
->uDNS_info
.LLQNatInfo
;
1396 for (q
= m
->uDNS_info
.ActiveQueries
; q
; q
= q
->next
)
1397 if (q
->LongLived
&& q
->uDNS_info
.llq
->NATMap
) return;
1399 //to avoid race condition if we need to recreate before this finishes, we do one-shot deregistration
1400 if (nat
->state
== NATState_Established
|| nat
->state
== NATState_Legacy
)
1401 DeleteNATPortMapping(m
, nat
, mDNSNULL
); // for simplicity we allow other states to expire
1402 FreeNATInfo(m
, nat
); // note: this clears the global LLQNatInfo pointer
1405 // ***************************************************************************
1406 #if COMPILER_LIKES_PRAGMA_MARK
1407 #pragma mark - host name and interface management
1410 // if we ever want to refine support for multiple hostnames, we can add logic matching service names to a particular hostname
1411 // for now, we grab the first registered DynDNS name, if any, or a static name we learned via a reverse-map query
1412 mDNSlocal mDNSBool
GetServiceTarget(uDNS_GlobalInfo
*u
, AuthRecord
*srv
, domainname
*dst
)
1414 uDNS_HostnameInfo
*hi
= u
->Hostnames
;
1415 (void)srv
; // unused
1420 if (hi
->ar
->uDNS_info
.state
== regState_Registered
|| hi
->ar
->uDNS_info
.state
== regState_Refresh
)
1421 { AssignDomainName(dst
, hi
->ar
->resrec
.name
); return mDNStrue
; }
1425 if (u
->StaticHostname
.c
[0]) { AssignDomainName(dst
, &u
->StaticHostname
); return mDNStrue
; }
1429 mDNSlocal
void UpdateSRV(mDNS
*m
, ServiceRecordSet
*srs
)
1431 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1432 ExtraResourceRecord
*e
;
1434 // Target change if:
1435 // We have a target and were previously waiting for one, or
1436 // We had a target and no longer do, or
1437 // The target has changed
1439 domainname newtarget
;
1440 domainname
*curtarget
= &srs
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
1441 mDNSBool HaveTarget
= GetServiceTarget(u
, &srs
->RR_SRV
, &newtarget
);
1442 mDNSBool TargetChanged
= (HaveTarget
&& srs
->uDNS_info
.state
== regState_NoTarget
) || (curtarget
->c
[0] && !HaveTarget
) || !SameDomainName(curtarget
, &newtarget
);
1443 mDNSBool HaveZoneData
= srs
->uDNS_info
.ns
.ip
.v4
.NotAnInteger
? mDNStrue
: mDNSfalse
;
1445 // Nat state change if:
1446 // We were behind a NAT, and now we are behind a new NAT, or
1447 // We're not behind a NAT but our port was previously mapped to a different public port
1448 // We were not behind a NAT and now we are
1450 NATTraversalInfo
*nat
= srs
->uDNS_info
.NATinfo
;
1451 mDNSIPPort port
= srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
;
1452 mDNSBool NATChanged
= mDNSfalse
;
1453 mDNSBool NowBehindNAT
= port
.NotAnInteger
&& IsPrivateV4Addr(&u
->PrimaryIP
);
1454 mDNSBool WereBehindNAT
= nat
!= mDNSNULL
;
1455 mDNSBool NATRouterChanged
= nat
&& nat
->Router
.ip
.v4
.NotAnInteger
!= u
->Router
.ip
.v4
.NotAnInteger
;
1456 mDNSBool PortWasMapped
= nat
&& (nat
->state
== NATState_Established
|| nat
->state
== NATState_Legacy
) && nat
->PublicPort
.NotAnInteger
!= port
.NotAnInteger
;
1458 if (WereBehindNAT
&& NowBehindNAT
&& NATRouterChanged
) NATChanged
= mDNStrue
;
1459 else if (!NowBehindNAT
&& PortWasMapped
) NATChanged
= mDNStrue
;
1460 else if (!WereBehindNAT
&& NowBehindNAT
) NATChanged
= mDNStrue
;
1462 if (!TargetChanged
&& !NATChanged
) return;
1464 debugf("UpdateSRV (%##s) HadZoneData=%d, TargetChanged=%d, HaveTarget=%d, NowBehindNAT=%d, WereBehindNAT=%d, NATRouterChanged=%d, PortWasMapped=%d",
1465 srs
->RR_SRV
.resrec
.name
->c
, HaveZoneData
, TargetChanged
, HaveTarget
, NowBehindNAT
, WereBehindNAT
, NATRouterChanged
, PortWasMapped
);
1467 switch(srs
->uDNS_info
.state
)
1469 case regState_FetchingZoneData
:
1470 case regState_Cancelled
:
1471 case regState_DeregPending
:
1472 case regState_DeregDeferred
:
1473 case regState_Unregistered
:
1474 case regState_NATMap
:
1475 case regState_ExtraQueued
:
1476 // In these states, the SRV has either not yet been registered (it will get up-to-date information when it is)
1477 // or is in the process of, or has already been, deregistered
1480 case regState_Pending
:
1481 case regState_Refresh
:
1482 case regState_UpdatePending
:
1483 // let the in-flight operation complete before updating
1484 srs
->uDNS_info
.SRVUpdateDeferred
= mDNStrue
;
1487 case regState_NATError
:
1488 if (!NATChanged
) return;
1489 // if nat changed, register if we have a target (below)
1491 case regState_NoTarget
:
1494 debugf("UpdateSRV: %s service %##s", HaveZoneData
? (NATChanged
&& NowBehindNAT
? "Starting Port Map for" : "Registering") : "Getting Zone Data for", srs
->RR_SRV
.resrec
.name
->c
);
1497 srs
->uDNS_info
.state
= regState_FetchingZoneData
;
1498 startGetZoneData(srs
->RR_SRV
.resrec
.name
, m
, mDNStrue
, mDNSfalse
, serviceRegistrationCallback
, srs
);
1502 if (nat
&& (NATChanged
|| !NowBehindNAT
)) { srs
->uDNS_info
.NATinfo
= mDNSNULL
; FreeNATInfo(m
, nat
); }
1503 if (NATChanged
&& NowBehindNAT
) { srs
->uDNS_info
.state
= regState_NATMap
; StartNATPortMap(m
, srs
); }
1504 else SendServiceRegistration(m
, srs
);
1509 case regState_Registered
:
1510 // target or nat changed. deregister service. upon completion, we'll look for a new target
1511 debugf("UpdateSRV: SRV record changed for service %##s - deregistering (will re-register with new SRV)", srs
->RR_SRV
.resrec
.name
->c
);
1512 for (e
= srs
->Extras
; e
; e
= e
->next
) e
->r
.uDNS_info
.state
= regState_ExtraQueued
; // extra will be re-registed if the service is re-registered
1513 srs
->uDNS_info
.SRVChanged
= mDNStrue
;
1514 SendServiceDeregistration(m
, srs
);
1519 mDNSlocal
void UpdateSRVRecords(mDNS
*m
)
1521 ServiceRecordSet
*srs
;
1523 for (srs
= m
->uDNS_info
.ServiceRegistrations
; srs
; srs
= srs
->next
) UpdateSRV(m
, srs
);
1526 mDNSlocal
void HostnameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
1528 uDNS_HostnameInfo
*hi
= (uDNS_HostnameInfo
*)rr
->RecordContext
;
1529 mDNSu8
*ip
= rr
->resrec
.rdata
->u
.ipv4
.b
;
1531 if (result
== mStatus_MemFree
)
1533 debugf("MemFree: %##s IP %d.%d.%d.%d", rr
->resrec
.name
->c
, ip
[0], ip
[1], ip
[2], ip
[3]);
1541 // don't unlink or free - we can retry when we get a new address/router
1542 LogMsg("HostnameCallback: Error %ld for registration of %##s IP %d.%d.%d.%d", result
, rr
->resrec
.name
->c
, ip
[0], ip
[1], ip
[2], ip
[3]);
1543 if (!hi
) { ufree(rr
); return; }
1544 if (hi
->ar
->uDNS_info
.state
!= regState_Unregistered
) LogMsg("Error: HostnameCallback invoked with error code for record not in regState_Unregistered!");
1545 rr
->RecordContext
= (void *)hi
->StatusContext
;
1546 if (hi
->StatusCallback
)
1547 hi
->StatusCallback(m
, rr
, result
); // client may NOT make API calls here
1548 rr
->RecordContext
= (void *)hi
;
1552 // register any pending services that require a target
1553 UpdateSRVRecords(m
);
1555 // Deliver success to client
1556 if (!hi
) { LogMsg("HostnameCallback invoked with orphaned address record"); return; }
1557 LogMsg("Registered hostname %##s IP %d.%d.%d.%d", rr
->resrec
.name
->c
, ip
[0], ip
[1], ip
[2], ip
[3]);
1558 rr
->RecordContext
= (void *)hi
->StatusContext
;
1559 if (hi
->StatusCallback
)
1560 hi
->StatusCallback(m
, rr
, result
); // client may NOT make API calls here
1561 rr
->RecordContext
= (void *)hi
;
1564 // register record or begin NAT traversal
1565 mDNSlocal
void AdvertiseHostname(mDNS
*m
, uDNS_HostnameInfo
*h
)
1567 if (IsPrivateV4Addr(&m
->uDNS_info
.PrimaryIP
))
1568 StartGetPublicAddr(m
, h
);
1571 mDNSu8
*ip
= m
->uDNS_info
.PrimaryIP
.ip
.v4
.b
;
1572 LogMsg("Advertising %##s IP %d.%d.%d.%d", h
->ar
->resrec
.name
->c
, ip
[0], ip
[1], ip
[2], ip
[3]);
1573 uDNS_RegisterRecord(m
, h
->ar
);
1577 mDNSlocal
void FoundStaticHostname(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
)
1579 const domainname
*pktname
= &answer
->rdata
->u
.name
;
1580 domainname
*storedname
= &m
->uDNS_info
.StaticHostname
;
1581 uDNS_HostnameInfo
*h
= m
->uDNS_info
.Hostnames
;
1585 debugf("FoundStaticHostname: %##s -> %##s (%s)", question
->qname
.c
, answer
->rdata
->u
.name
.c
, AddRecord
? "added" : "removed");
1586 if (AddRecord
&& !SameDomainName(pktname
, storedname
))
1588 AssignDomainName(storedname
, pktname
);
1591 if (h
->ar
&& (h
->ar
->uDNS_info
.state
== regState_FetchingZoneData
|| h
->ar
->uDNS_info
.state
== regState_Pending
|| h
->ar
->uDNS_info
.state
== regState_NATMap
))
1593 // if we're in the process of registering a dynamic hostname, delay SRV update so we don't have to reregister services if the dynamic name succeeds
1594 m
->uDNS_info
.DelaySRVUpdate
= mDNStrue
;
1595 m
->uDNS_info
.NextSRVUpdate
= mDNSPlatformTimeNow(m
) + (5 * mDNSPlatformOneSecond
);
1600 UpdateSRVRecords(m
);
1602 else if (!AddRecord
&& SameDomainName(pktname
, storedname
))
1604 storedname
->c
[0] = 0;
1605 UpdateSRVRecords(m
);
1609 mDNSlocal
void GetStaticHostname(mDNS
*m
)
1611 char buf
[MAX_ESCAPED_DOMAIN_NAME
];
1612 DNSQuestion
*q
= &m
->uDNS_info
.ReverseMap
;
1613 mDNSu8
*ip
= m
->uDNS_info
.PrimaryIP
.ip
.v4
.b
;
1616 if (m
->uDNS_info
.ReverseMapActive
)
1618 uDNS_StopQuery(m
, q
);
1619 m
->uDNS_info
.ReverseMapActive
= mDNSfalse
;
1622 m
->uDNS_info
.StaticHostname
.c
[0] = 0;
1623 if (!m
->uDNS_info
.PrimaryIP
.ip
.v4
.NotAnInteger
) return;
1624 ubzero(q
, sizeof(*q
));
1625 mDNS_snprintf(buf
, MAX_ESCAPED_DOMAIN_NAME
, "%d.%d.%d.%d.in-addr.arpa.", ip
[3], ip
[2], ip
[1], ip
[0]);
1626 if (!MakeDomainNameFromDNSNameString(&q
->qname
, buf
)) { LogMsg("Error: GetStaticHostname - bad name %s", buf
); return; }
1628 q
->InterfaceID
= mDNSInterface_Any
;
1629 q
->Target
= zeroAddr
;
1630 q
->qtype
= kDNSType_PTR
;
1631 q
->qclass
= kDNSClass_IN
;
1632 q
->LongLived
= mDNSfalse
;
1633 q
->ExpectUnique
= mDNSfalse
;
1634 q
->ForceMCast
= mDNSfalse
;
1635 q
->QuestionCallback
= FoundStaticHostname
;
1636 q
->QuestionContext
= mDNSNULL
;
1638 err
= uDNS_StartQuery(m
, q
);
1639 if (err
) LogMsg("Error: GetStaticHostname - StartQuery returned error %d", err
);
1640 else m
->uDNS_info
.ReverseMapActive
= mDNStrue
;
1643 // Deregister hostnames and register new names for each host domain with the current global
1644 // values for the hostlabel and primary IP address
1645 mDNSlocal
void UpdateHostnameRegistrations(mDNS
*m
)
1647 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1649 uDNS_HostnameInfo
*i
;
1651 for (i
= u
->Hostnames
; i
; i
= i
->next
)
1653 // only allocate new record if existing record is actually registered (i.e. it wasn't pending the hostname or IP being set)
1654 if (i
->ar
->uDNS_info
.state
== regState_Unregistered
) new = i
->ar
;
1657 new = umalloc(sizeof(AuthRecord
));
1658 if (!new) { LogMsg("ERROR: UpdateHostnameRegistration - malloc"); return; }
1659 mDNS_SetupResourceRecord(new, mDNSNULL
, 0, kDNSType_A
, kWideAreaTTL
, kDNSRecordTypeKnownUnique
, HostnameCallback
, i
);
1663 AssignDomainName(new->resrec
.name
, i
->ar
->resrec
.name
);
1664 new->resrec
.rdata
->u
.ipv4
= u
->PrimaryIP
.ip
.v4
;
1666 if (i
->ar
->uDNS_info
.state
!= regState_Unregistered
)
1668 // delete old record
1669 i
->ar
->RecordContext
= mDNSNULL
; // clear backpointer to HostnameInfo
1670 uDNS_DeregisterRecord(m
, i
->ar
);
1675 AdvertiseHostname(m
, i
);
1679 mDNSexport
void mDNS_AddDynDNSHostName(mDNS
*m
, const domainname
*fqdn
, mDNSRecordCallback
*StatusCallback
, const void *StatusContext
)
1681 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1682 uDNS_HostnameInfo
*ptr
, *new;
1686 // check if domain already registered
1687 for (ptr
= u
->Hostnames
; ptr
; ptr
= ptr
->next
)
1689 if (SameDomainName(fqdn
, ptr
->ar
->resrec
.name
))
1690 { LogMsg("Host Domain %##s already in list", fqdn
->c
); goto exit
; }
1693 // allocate and format new address record
1694 new = umalloc(sizeof(*new));
1695 if (new) new->ar
= umalloc(sizeof(AuthRecord
));
1696 if (!new || !new->ar
) { LogMsg("ERROR: mDNS_AddDynDNSHostname - malloc"); goto exit
; }
1697 new->StatusCallback
= StatusCallback
;
1698 new->StatusContext
= StatusContext
;
1699 mDNS_SetupResourceRecord(new->ar
, mDNSNULL
, 0, kDNSType_A
, 1, kDNSRecordTypeKnownUnique
, HostnameCallback
, new);
1700 AppendDomainName(new->ar
->resrec
.name
, fqdn
);
1701 new->next
= u
->Hostnames
;
1703 if (u
->PrimaryIP
.ip
.v4
.NotAnInteger
)
1705 // only set RData if we have a valid IP
1706 if (u
->MappedPrimaryIP
.ip
.v4
.NotAnInteger
) new->ar
->resrec
.rdata
->u
.ipv4
= u
->MappedPrimaryIP
.ip
.v4
; //!!!KRS implement code that caches this
1707 else new->ar
->resrec
.rdata
->u
.ipv4
= u
->PrimaryIP
.ip
.v4
;
1708 AdvertiseHostname(m
, new);
1710 else new->ar
->uDNS_info
.state
= regState_Unregistered
;
1715 mDNSexport
void mDNS_RemoveDynDNSHostName(mDNS
*m
, const domainname
*fqdn
)
1717 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1718 uDNS_HostnameInfo
**ptr
= &u
->Hostnames
;
1722 while (*ptr
&& !SameDomainName(fqdn
, (*ptr
)->ar
->resrec
.name
)) ptr
= &(*ptr
)->next
;
1723 if (!*ptr
) LogMsg("mDNS_RemoveDynDNSHostName: no such domainname %##s", fqdn
->c
);
1726 uDNS_HostnameInfo
*hi
= *ptr
;
1727 *ptr
= (*ptr
)->next
; // unlink
1728 hi
->ar
->RecordContext
= mDNSNULL
; // about to free wrapper struct
1729 if (hi
->ar
->uDNS_info
.state
!= regState_Unregistered
) uDNS_DeregisterRecord(m
, hi
->ar
);
1730 else { ufree(hi
->ar
); hi
->ar
= mDNSNULL
; }
1733 UpdateSRVRecords(m
);
1737 mDNSexport
void mDNS_SetPrimaryInterfaceInfo(mDNS
*m
, const mDNSAddr
*addr
, const mDNSAddr
*router
)
1739 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
1740 mDNSBool AddrChanged
, RouterChanged
;
1742 if (addr
&& addr
->type
!=mDNSAddrType_IPv4
) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-V4 address. Discarding."); return; }
1743 if (router
&& router
->type
!=mDNSAddrType_IPv4
) { LogMsg("mDNS_SetPrimaryInterfaceInfo passed non-V4 address. Discarding."); return; }
1746 AddrChanged
= ((addr
? addr
->ip
.v4
.NotAnInteger
: 0) != u
->PrimaryIP
.ip
.v4
.NotAnInteger
);
1747 RouterChanged
= ((router
? router
->ip
.v4
.NotAnInteger
: 0) != u
->Router
.ip
.v4
.NotAnInteger
);
1750 if (addr
&& (AddrChanged
|| RouterChanged
))
1751 LogMsg("mDNS_SetPrimaryInterfaceInfo: address changed from %d.%d.%d.%d to %d.%d.%d.%d:%d",
1752 u
->PrimaryIP
.ip
.v4
.b
[0], u
->PrimaryIP
.ip
.v4
.b
[1], u
->PrimaryIP
.ip
.v4
.b
[2], u
->PrimaryIP
.ip
.v4
.b
[3],
1753 addr
->ip
.v4
.b
[0], addr
->ip
.v4
.b
[1], addr
->ip
.v4
.b
[2], addr
->ip
.v4
.b
[3], mDNSVal16(m
->UnicastPort4
));
1754 #endif // MDNS_DEBUGMSGS
1756 if (addr
) u
->PrimaryIP
= *addr
;
1757 if (router
) u
->Router
= *router
;
1758 else u
->Router
.ip
.v4
.NotAnInteger
= 0; // setting router to zero indicates that nat mappings must be reestablished when router is reset
1760 if ((AddrChanged
|| RouterChanged
) && (addr
&& router
))
1762 UpdateHostnameRegistrations(m
);
1763 UpdateSRVRecords(m
);
1764 GetStaticHostname(m
); // look up reverse map record to find any static hostnames for our IP address
1770 // ***************************************************************************
1771 #if COMPILER_LIKES_PRAGMA_MARK
1772 #pragma mark - Incoming Message Processing
1775 mDNSlocal mDNSBool
kaListContainsAnswer(DNSQuestion
*question
, CacheRecord
*rr
)
1779 for (ptr
= question
->uDNS_info
.knownAnswers
; ptr
; ptr
= ptr
->next
)
1780 if (SameResourceRecord(&ptr
->resrec
, &rr
->resrec
)) return mDNStrue
;
1786 mDNSlocal
void removeKnownAnswer(DNSQuestion
*question
, CacheRecord
*rr
)
1788 CacheRecord
*ptr
, *prev
= mDNSNULL
;
1790 for (ptr
= question
->uDNS_info
.knownAnswers
; ptr
; ptr
= ptr
->next
)
1792 if (SameResourceRecord(&ptr
->resrec
, &rr
->resrec
))
1794 if (prev
) prev
->next
= ptr
->next
;
1795 else question
->uDNS_info
.knownAnswers
= ptr
->next
;
1801 LogMsg("removeKnownAnswer() called for record not in KA list");
1805 mDNSlocal
void addKnownAnswer(DNSQuestion
*question
, const CacheRecord
*rr
)
1807 CacheRecord
*newCR
= mDNSNULL
;
1810 size
= sizeof(CacheRecord
) + rr
->resrec
.rdlength
- InlineCacheRDSize
;
1811 newCR
= (CacheRecord
*)umalloc(size
);
1812 if (!newCR
) { LogMsg("ERROR: addKnownAnswer - malloc"); return; }
1813 umemcpy(newCR
, rr
, size
);
1814 newCR
->resrec
.rdata
= (RData
*)&newCR
->rdatastorage
;
1815 newCR
->resrec
.rdata
->MaxRDLength
= rr
->resrec
.rdlength
;
1816 newCR
->resrec
.name
= &question
->qname
;
1817 newCR
->next
= question
->uDNS_info
.knownAnswers
;
1818 question
->uDNS_info
.knownAnswers
= newCR
;
1821 mDNSlocal
void deriveGoodbyes(mDNS
* const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
)
1825 CacheRecord
*fptr
, *ka
, *cr
, *answers
= mDNSNULL
, *prev
= mDNSNULL
;
1826 LargeCacheRecord
*lcr
;
1828 if (question
!= m
->uDNS_info
.CurrentQuery
) { LogMsg("ERROR: deriveGoodbyes called without CurrentQuery set!"); return; }
1830 ptr
= LocateAnswers(msg
, end
);
1831 if (!ptr
) goto pkt_error
;
1833 if (!msg
->h
.numAnswers
)
1835 // delete the whole KA list
1836 ka
= question
->uDNS_info
.knownAnswers
;
1839 debugf("deriving goodbye for %##s", ka
->resrec
.name
->c
);
1841 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
1842 question
->QuestionCallback(m
, question
, &ka
->resrec
, mDNSfalse
);
1843 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
1844 if (question
!= m
->uDNS_info
.CurrentQuery
)
1846 debugf("deriveGoodbyes - question removed via callback. returning.");
1853 question
->uDNS_info
.knownAnswers
= mDNSNULL
;
1857 // make a list of all the new answers
1858 for (i
= 0; i
< msg
->h
.numAnswers
; i
++)
1860 lcr
= (LargeCacheRecord
*)umalloc(sizeof(LargeCacheRecord
));
1861 if (!lcr
) goto malloc_error
;
1862 ubzero(lcr
, sizeof(LargeCacheRecord
));
1863 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, lcr
);
1864 if (!ptr
) goto pkt_error
;
1866 if (ResourceRecordAnswersQuestion(&cr
->resrec
, question
))
1874 // make sure every known answer is in the answer list
1875 ka
= question
->uDNS_info
.knownAnswers
;
1878 for (cr
= answers
; cr
; cr
= cr
->next
)
1879 { if (SameResourceRecord(&ka
->resrec
, &cr
->resrec
)) break; }
1882 // record is in KA list but not answer list - remove from KA list
1883 if (prev
) prev
->next
= ka
->next
;
1884 else question
->uDNS_info
.knownAnswers
= ka
->next
;
1885 debugf("deriving goodbye for %##s", ka
->resrec
.name
->c
);
1886 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
1887 question
->QuestionCallback(m
, question
, &ka
->resrec
, mDNSfalse
);
1888 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
1889 if (question
!= m
->uDNS_info
.CurrentQuery
)
1891 debugf("deriveGoodbyes - question removed via callback. returning.");
1905 // free temp answers list
1907 while (cr
) { fptr
= cr
; cr
= cr
->next
; ufree(fptr
); }
1912 LogMsg("ERROR: deriveGoodbyes - received malformed response to query for %##s (%d)",
1913 question
->qname
.c
, question
->qtype
);
1917 LogMsg("ERROR: Malloc");
1920 mDNSlocal
void pktResponseHndlr(mDNS
* const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
, mDNSBool llq
)
1924 LargeCacheRecord lcr
;
1925 CacheRecord
*cr
= &lcr
.r
;
1926 mDNSBool goodbye
, inKAList
, followedCName
= mDNSfalse
;
1927 LLQ_Info
*llqInfo
= question
->uDNS_info
.llq
;
1928 domainname origname
;
1931 if (question
!= m
->uDNS_info
.CurrentQuery
)
1932 { LogMsg("ERROR: pktResponseHdnlr called without CurrentQuery ptr set!"); return; }
1934 question
->uDNS_info
.Answered
= mDNStrue
;
1936 ptr
= LocateAnswers(msg
, end
);
1937 if (!ptr
) goto pkt_error
;
1939 for (i
= 0; i
< msg
->h
.numAnswers
; i
++)
1941 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, &lcr
);
1942 if (!ptr
) goto pkt_error
;
1943 if (ResourceRecordAnswersQuestion(&cr
->resrec
, question
))
1945 if (cr
->resrec
.rrtype
== kDNSType_CNAME
)
1947 if (followedCName
) LogMsg("Error: multiple CNAME referals for question %##s", question
->qname
.c
);
1950 debugf("Following cname %##s -> %##s", question
->qname
.c
, cr
->resrec
.rdata
->u
.name
.c
);
1951 AssignDomainName(&origname
, &question
->qname
);
1952 AssignDomainName(&question
->qname
, &cr
->resrec
.rdata
->u
.name
);
1953 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
1954 followedCName
= mDNStrue
;
1955 i
= -1; // restart packet answer matching
1956 ptr
= LocateAnswers(msg
, end
);
1961 goodbye
= llq
? ((mDNSs32
)cr
->resrec
.rroriginalttl
== -1) : mDNSfalse
;
1962 inKAList
= kaListContainsAnswer(question
, cr
);
1964 if ((goodbye
&& !inKAList
) || (!goodbye
&& inKAList
)) continue; // list up to date
1965 if (!inKAList
) addKnownAnswer(question
, cr
);
1966 if (goodbye
) removeKnownAnswer(question
, cr
);
1967 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
1968 question
->QuestionCallback(m
, question
, &cr
->resrec
, !goodbye
);
1969 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
1970 if (question
!= m
->uDNS_info
.CurrentQuery
)
1972 debugf("pktResponseHndlr - CurrentQuery changed by QuestionCallback - returning");
1976 else if (!followedCName
|| !SameDomainName(cr
->resrec
.name
, &origname
))
1977 LogMsg("Question %##s %X %s %##s- unexpected answer %##s %X %s",
1978 question
->qname
.c
, question
->qnamehash
, DNSTypeName(question
->qtype
), origname
.c
,
1979 cr
->resrec
.name
->c
, cr
->resrec
.namehash
, DNSTypeName(cr
->resrec
.rrtype
));
1982 if (!llq
|| llqInfo
->state
== LLQ_Poll
|| llqInfo
->deriveRemovesOnResume
)
1984 deriveGoodbyes(m
, msg
, end
,question
);
1985 if (llq
&& llqInfo
->deriveRemovesOnResume
) llqInfo
->deriveRemovesOnResume
= mDNSfalse
;
1988 // our interval may be set lower to recover from failures - now that we have an answer, fully back off retry
1989 if (question
->ThisQInterval
< MAX_UCAST_POLL_INTERVAL
) question
->ThisQInterval
= MAX_UCAST_POLL_INTERVAL
;
1993 LogMsg("ERROR: pktResponseHndlr - received malformed response to query for %##s (%d)",
1994 question
->qname
.c
, question
->qtype
);
1998 mDNSlocal
void simpleResponseHndlr(mDNS
* const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
, void *context
)
2000 (void)context
; // unused
2001 pktResponseHndlr(m
, msg
, end
, question
, mDNSfalse
);
2004 mDNSlocal
void llqResponseHndlr(mDNS
* const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
, void *context
)
2006 (void)context
; // unused
2007 pktResponseHndlr(m
, msg
, end
, question
, mDNStrue
);
2010 mDNSlocal mStatus
ParseTSIGError(mDNS
*m
, const DNSMessage
*msg
, const mDNSu8
*end
, const domainname
*displayname
)
2012 LargeCacheRecord lcr
;
2014 mStatus err
= mStatus_NoError
;
2017 ptr
= LocateAdditionals(msg
, end
);
2018 if (!ptr
) goto finish
;
2020 for (i
= 0; i
< msg
->h
.numAdditionals
; i
++)
2022 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &lcr
);
2023 if (!ptr
) goto finish
;
2024 if (lcr
.r
.resrec
.rrtype
== kDNSType_TSIG
)
2027 mDNSu8
*rd
= lcr
.r
.resrec
.rdata
->u
.data
;
2028 mDNSu8
*rdend
= rd
+ MaximumRDSize
;
2029 int alglen
= DomainNameLength(&lcr
.r
.resrec
.rdata
->u
.name
);
2031 if (rd
+ alglen
> rdend
) goto finish
;
2032 rd
+= alglen
; // algorithm name
2033 if (rd
+ 6 > rdend
) goto finish
;
2034 rd
+= 6; // 48-bit timestamp
2035 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2036 rd
+= sizeof(mDNSOpaque16
); // fudge
2037 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2038 macsize
= mDNSVal16(*(mDNSOpaque16
*)rd
);
2039 rd
+= sizeof(mDNSOpaque16
); // MAC size
2040 if (rd
+ macsize
> rdend
) goto finish
;
2042 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2043 rd
+= sizeof(mDNSOpaque16
); // orig id
2044 if (rd
+ sizeof(mDNSOpaque16
) > rdend
) goto finish
;
2045 err
= mDNSVal16(*(mDNSOpaque16
*)rd
); // error code
2047 if (err
== TSIG_ErrBadSig
) { LogMsg("%##s: bad signature", displayname
->c
); err
= mStatus_BadSig
; }
2048 else if (err
== TSIG_ErrBadKey
) { LogMsg("%##s: bad key", displayname
->c
); err
= mStatus_BadKey
; }
2049 else if (err
== TSIG_ErrBadTime
) { LogMsg("%##s: bad time", displayname
->c
); err
= mStatus_BadTime
; }
2050 else if (err
) { LogMsg("%##s: unknown tsig error %d", displayname
->c
, err
); err
= mStatus_UnknownErr
; }
2059 mDNSlocal mStatus
checkUpdateResult(domainname
*displayname
, mDNSu8 rcode
, mDNS
*m
, const DNSMessage
*msg
, const mDNSu8
*end
)
2061 (void)msg
; // currently unused, needed for TSIG errors
2062 if (!rcode
) return mStatus_NoError
;
2063 else if (rcode
== kDNSFlag1_RC_YXDomain
)
2065 LogMsg("name in use: %##s", displayname
->c
);
2066 return mStatus_NameConflict
;
2068 else if (rcode
== kDNSFlag1_RC_Refused
)
2070 LogMsg("Update %##s refused", displayname
->c
);
2071 return mStatus_Refused
;
2073 else if (rcode
== kDNSFlag1_RC_NXRRSet
)
2075 LogMsg("Reregister refused (NXRRSET): %##s", displayname
->c
);
2076 return mStatus_NoSuchRecord
;
2078 else if (rcode
== kDNSFlag1_RC_NotAuth
)
2080 // TSIG errors should come with FmtErr as per RFC 2845, but BIND 9 sends them with NotAuth so we look here too
2081 mStatus tsigerr
= ParseTSIGError(m
, msg
, end
, displayname
);
2084 LogMsg("Permission denied (NOAUTH): %##s", displayname
->c
);
2085 return mStatus_UnknownErr
;
2087 else return tsigerr
;
2089 else if (rcode
== kDNSFlag1_RC_FmtErr
)
2091 mStatus tsigerr
= ParseTSIGError(m
, msg
, end
, displayname
);
2094 LogMsg("Format Error: %##s", displayname
->c
);
2095 return mStatus_UnknownErr
;
2097 else return tsigerr
;
2101 LogMsg("Update %##s failed with rcode %d", displayname
->c
, rcode
);
2102 return mStatus_UnknownErr
;
2106 mDNSlocal
void hndlServiceUpdateReply(mDNS
* const m
, ServiceRecordSet
*srs
, mStatus err
)
2108 mDNSBool InvokeCallback
= mDNSfalse
;
2109 uDNS_RegInfo
*info
= &srs
->uDNS_info
;
2110 NATTraversalInfo
*nat
= srs
->uDNS_info
.NATinfo
;
2111 ExtraResourceRecord
**e
= &srs
->Extras
;
2113 switch (info
->state
)
2115 case regState_Pending
:
2116 if (err
== mStatus_NameConflict
&& !info
->TestForSelfConflict
)
2118 info
->TestForSelfConflict
= mDNStrue
;
2119 debugf("checking for self-conflict of service %##s", srs
->RR_SRV
.resrec
.name
->c
);
2120 SendServiceRegistration(m
, srs
);
2123 else if (info
->TestForSelfConflict
)
2125 info
->TestForSelfConflict
= mDNSfalse
;
2126 if (err
== mStatus_NoSuchRecord
) err
= mStatus_NameConflict
; // NoSuchRecord implies that our prereq was not met, so we actually have a name conflict
2127 if (err
) info
->state
= regState_Unregistered
;
2128 else info
->state
= regState_Registered
;
2129 InvokeCallback
= mDNStrue
;
2132 else if (err
== mStatus_UnknownErr
&& info
->lease
)
2134 LogMsg("Re-trying update of service %##s without lease option", srs
->RR_SRV
.resrec
.name
->c
);
2135 info
->lease
= mDNSfalse
;
2136 SendServiceRegistration(m
, srs
);
2141 if (err
) { LogMsg("Error %ld for registration of service %##s", err
, srs
->RR_SRV
.resrec
.name
->c
); info
->state
= regState_Unregistered
; } //!!!KRS make sure all structs will still get cleaned up when client calls DeregisterService with this state
2142 else info
->state
= regState_Registered
;
2143 InvokeCallback
= mDNStrue
;
2146 case regState_Refresh
:
2149 LogMsg("Error %ld for refresh of service %##s", err
, srs
->RR_SRV
.resrec
.name
->c
);
2150 InvokeCallback
= mDNStrue
;
2151 info
->state
= regState_Unregistered
;
2153 else info
->state
= regState_Registered
;
2155 case regState_DeregPending
:
2156 if (err
) LogMsg("Error %ld for deregistration of service %##s", err
, srs
->RR_SRV
.resrec
.name
->c
);
2157 if (info
->SRVChanged
)
2159 info
->state
= regState_NoTarget
; // NoTarget will allow us to pick up new target OR nat traversal state
2162 err
= mStatus_MemFree
;
2163 InvokeCallback
= mDNStrue
;
2166 if (nat
->state
== NATState_Deleted
) { FreeNATInfo(m
, nat
); info
->NATinfo
= mDNSNULL
; } // deletion copmleted
2167 else nat
->reg
.ServiceRegistration
= mDNSNULL
; // allow mapping deletion to continue
2169 info
->state
= regState_Unregistered
;
2171 case regState_DeregDeferred
:
2174 debugf("Error %ld received prior to deferred derigstration of %##s", err
, srs
->RR_SRV
.resrec
.name
->c
);
2175 err
= mStatus_MemFree
;
2176 InvokeCallback
= mDNStrue
;
2177 info
->state
= regState_Unregistered
;
2182 debugf("Performing deferred deregistration of %##s", srs
->RR_SRV
.resrec
.name
->c
);
2183 info
->state
= regState_Registered
;
2184 SendServiceDeregistration(m
, srs
);
2187 case regState_UpdatePending
:
2188 // mDNS clients don't expect asyncronous UpdateRecord errors, so we just log (rare) failures
2189 if (err
) LogMsg("hndlServiceUpdateReply: error updating TXT record for service %##s", srs
->RR_SRV
.resrec
.name
->c
);
2190 info
->state
= regState_Registered
;
2191 SwapRData(m
, &srs
->RR_TXT
, mDNStrue
); // deallocate old rdata
2193 case regState_FetchingZoneData
:
2194 case regState_Registered
:
2195 case regState_Cancelled
:
2196 case regState_Unregistered
:
2197 case regState_NATMap
:
2198 case regState_NoTarget
:
2199 case regState_ExtraQueued
:
2200 case regState_NATError
:
2201 LogMsg("hndlServiceUpdateReply called for service %##s in unexpected state %d with error %ld. Unlinking.",
2202 srs
->RR_SRV
.resrec
.name
->c
, info
->state
, err
);
2203 err
= mStatus_UnknownErr
;
2206 if ((info
->SRVChanged
|| info
->SRVUpdateDeferred
) && (info
->state
== regState_NoTarget
|| info
->state
== regState_Registered
))
2210 info
->ClientCallbackDeferred
= mDNStrue
;
2211 info
->DeferredStatus
= err
;
2213 info
->SRVChanged
= mDNSfalse
;
2220 uDNS_RegInfo
*einfo
= &(*e
)->r
.uDNS_info
;
2221 if (einfo
->state
== regState_ExtraQueued
)
2223 if (info
->state
== regState_Registered
&& !err
)
2225 // extra resource record queued for this service - copy zone info and register
2226 AssignDomainName(&einfo
->zone
, &info
->zone
);
2227 einfo
->ns
= info
->ns
;
2228 einfo
->port
= info
->port
;
2229 einfo
->lease
= info
->lease
;
2230 sendRecordRegistration(m
, &(*e
)->r
);
2233 else if (err
&& einfo
->state
!= regState_Unregistered
)
2235 // unlink extra from list
2236 einfo
->state
= regState_Unregistered
;
2239 else e
= &(*e
)->next
;
2241 else e
= &(*e
)->next
;
2244 if (info
->state
== regState_Unregistered
) unlinkSRS(m
, srs
);
2245 else if (srs
->RR_TXT
.uDNS_info
.UpdateQueued
&& !err
)
2249 // if we were supposed to give a client callback, we'll do it after we update the primary txt record
2250 info
->ClientCallbackDeferred
= mDNStrue
;
2251 info
->DeferredStatus
= err
;
2253 srs
->RR_TXT
.uDNS_info
.UpdateQueued
= mDNSfalse
;
2254 info
->state
= regState_UpdatePending
;
2255 SendServiceRegistration(m
, srs
);
2258 else srs
->RR_SRV
.ThisAPInterval
= INIT_UCAST_POLL_INTERVAL
- 1; // reset retry delay for future refreshes, dereg, etc.
2260 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2261 if (InvokeCallback
) srs
->ServiceCallback(m
, srs
, err
);
2262 else if (info
->ClientCallbackDeferred
)
2264 info
->ClientCallbackDeferred
= mDNSfalse
;
2265 srs
->ServiceCallback(m
, srs
, info
->DeferredStatus
);
2267 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2268 // NOTE: do not touch structures after calling ServiceCallback
2271 mDNSlocal
void hndlRecordUpdateReply(mDNS
*m
, AuthRecord
*rr
, mStatus err
)
2273 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
2275 if (rr
->uDNS_info
.state
== regState_UpdatePending
)
2279 LogMsg("Update record failed for %##s (err %d)", rr
->resrec
.name
->c
, err
);
2280 rr
->uDNS_info
.state
= regState_Unregistered
;
2284 debugf("Update record %##s - success", rr
->resrec
.name
->c
);
2285 rr
->uDNS_info
.state
= regState_Registered
;
2286 SwapRData(m
, rr
, mDNStrue
);
2288 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2289 if (rr
->RecordCallback
) rr
->RecordCallback(m
, rr
, err
);
2290 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2294 if (rr
->uDNS_info
.state
== regState_DeregPending
)
2296 debugf("Received reply for deregister record %##s type %d", rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
2297 if (err
) LogMsg("ERROR: Deregistration of record %##s type %d failed with error %ld",
2298 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, err
);
2299 err
= mStatus_MemFree
;
2300 if (unlinkAR(&m
->uDNS_info
.RecordRegistrations
, rr
))
2301 LogMsg("ERROR: Could not unlink resource record following deregistration");
2302 rr
->uDNS_info
.state
= regState_Unregistered
;
2303 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2304 if (rr
->RecordCallback
) rr
->RecordCallback(m
, rr
, err
);
2305 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2309 if (rr
->uDNS_info
.state
== regState_DeregDeferred
)
2313 LogMsg("Cancelling deferred deregistration record %##s type %d due to registration error %ld",
2314 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, err
);
2315 unlinkAR(&m
->uDNS_info
.RecordRegistrations
, rr
);
2316 rr
->uDNS_info
.state
= regState_Unregistered
;
2319 LogMsg("Calling deferred deregistration of record %##s type %d",
2320 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
2321 rr
->uDNS_info
.state
= regState_Registered
;
2322 uDNS_DeregisterRecord(m
, rr
);
2326 if (rr
->uDNS_info
.state
== regState_Pending
|| rr
->uDNS_info
.state
== regState_Refresh
)
2330 if (rr
->uDNS_info
.lease
&& err
== mStatus_UnknownErr
)
2332 LogMsg("Re-trying update of record %##s without lease option", rr
->resrec
.name
->c
);
2333 rr
->uDNS_info
.lease
= mDNSfalse
;
2334 sendRecordRegistration(m
, rr
);
2338 LogMsg("Registration of record %##s type %d failed with error %ld",
2339 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, err
);
2340 unlinkAR(&u
->RecordRegistrations
, rr
);
2341 rr
->uDNS_info
.state
= regState_Unregistered
;
2342 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2343 if (rr
->RecordCallback
) rr
->RecordCallback(m
, rr
, err
);
2344 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2349 if (rr
->uDNS_info
.UpdateQueued
)
2351 debugf("%##s: sending queued update", rr
->resrec
.name
->c
);
2352 rr
->uDNS_info
.state
= regState_Registered
;
2353 SendRecordUpdate(m
,rr
, &rr
->uDNS_info
);
2356 if (rr
->uDNS_info
.state
== regState_Refresh
)
2357 rr
->uDNS_info
.state
= regState_Registered
;
2360 rr
->uDNS_info
.state
= regState_Registered
;
2361 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
2362 if (rr
->RecordCallback
) rr
->RecordCallback(m
, rr
, err
);
2363 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
2369 LogMsg("Received unexpected response for record %##s type %d, in state %d, with response error %ld",
2370 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
, rr
->uDNS_info
.state
, err
);
2374 mDNSlocal
void SetUpdateExpiration(mDNS
*m
, DNSMessage
*msg
, const mDNSu8
*end
, uDNS_RegInfo
*info
)
2376 LargeCacheRecord lcr
;
2382 ptr
= LocateAdditionals(msg
, end
);
2384 if (info
->lease
&& (ptr
= LocateAdditionals(msg
, end
)))
2386 for (i
= 0; i
< msg
->h
.numAdditionals
; i
++)
2388 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &lcr
);
2390 if (lcr
.r
.resrec
.rrtype
== kDNSType_OPT
)
2392 if (lcr
.r
.resrec
.rdlength
< LEASE_OPT_SIZE
) continue;
2393 if (lcr
.r
.resrec
.rdata
->u
.opt
.opt
!= kDNSOpt_Lease
) continue;
2394 lease
= lcr
.r
.resrec
.rdata
->u
.opt
.OptData
.lease
;
2402 expire
= (mDNSPlatformTimeNow(m
) + (((mDNSs32
)lease
* mDNSPlatformOneSecond
)) * 3/4);
2403 if (info
->state
== regState_UpdatePending
)
2404 // if updating individual record, the service record set may expire sooner
2405 { if (expire
- info
->expire
< 0) info
->expire
= expire
; }
2406 else info
->expire
= expire
;
2408 else info
->lease
= mDNSfalse
;
2411 mDNSexport
void uDNS_ReceiveNATMap(mDNS
*m
, mDNSu8
*pkt
, mDNSu16 len
)
2413 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
2414 NATTraversalInfo
*ptr
, *cur
;
2417 // check length, version, opcode
2418 if (len
< sizeof(NATPortMapReply
) && len
< sizeof(NATAddrReply
)) { LogMsg("NAT Traversal message too short (%d bytes)", len
); return; }
2419 if (pkt
[0] != NATMAP_VERS
) { LogMsg("Received NAT Traversal response with version %d (expect version %d)", pkt
[0], NATMAP_VERS
); return; }
2421 if (!(op
& NATMAP_RESPONSE_MASK
)) { LogMsg("Received NAT Traversal message that is not a response (opcode %d)", op
); return; }
2423 ptr
= u
->NATTraversals
;
2428 if ((cur
->state
== NATState_Request
|| cur
->state
== NATState_Refresh
) &&
2429 (cur
->op
| NATMAP_RESPONSE_MASK
) == op
)
2430 cur
->ReceiveResponse(cur
, m
, pkt
, len
); // callback may delete "cur"
2431 // specific request/reply matching logic handled by callback - we don't know if this was a match, so we don't break here
2435 mDNSexport
void uDNS_ReceiveMsg(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
2436 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*const dstaddr
,
2437 const mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
)
2441 ServiceRecordSet
*sptr
;
2442 mStatus err
= mStatus_NoError
;
2443 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
2445 mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
2446 mDNSu8 UpdateR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
2447 mDNSu8 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
2448 mDNSu8 rcode
= (mDNSu8
)(msg
->h
.flags
.b
[1] & kDNSFlag1_RC
);
2450 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
2459 // !!!KRS we should to a table lookup here to see if it answers an LLQ or a 1-shot
2460 // LLQ Responses over TCP not currently supported
2461 if (srcaddr
&& recvLLQResponse(m
, msg
, end
, srcaddr
, srcport
, InterfaceID
)) return;
2463 for (qptr
= u
->ActiveQueries
; qptr
; qptr
= qptr
->next
)
2465 //!!!KRS we should have a hashtable, hashed on message id
2466 if (qptr
->uDNS_info
.id
.NotAnInteger
== msg
->h
.id
.NotAnInteger
)
2468 if (timenow
- (qptr
->LastQTime
+ RESPONSE_WINDOW
) > 0)
2469 { LogMsg("uDNS_ReceiveMsg - response received after maximum allowed window. Discarding"); return; }
2470 if (msg
->h
.flags
.b
[0] & kDNSFlag0_TC
)
2471 { hndlTruncatedAnswer(qptr
, srcaddr
, m
); return; }
2474 u
->CurrentQuery
= qptr
;
2475 qptr
->uDNS_info
.responseCallback(m
, msg
, end
, qptr
, qptr
->uDNS_info
.context
);
2476 u
->CurrentQuery
= mDNSNULL
;
2477 // Note: responseCallback can invalidate qptr
2483 if (QR_OP
== UpdateR
)
2485 for (sptr
= u
->ServiceRegistrations
; sptr
; sptr
= sptr
->next
)
2487 if (sptr
->uDNS_info
.id
.NotAnInteger
== msg
->h
.id
.NotAnInteger
)
2489 err
= checkUpdateResult(sptr
->RR_SRV
.resrec
.name
, rcode
, m
, msg
, end
);
2490 if (!err
) SetUpdateExpiration(m
, msg
, end
, &sptr
->uDNS_info
);
2491 hndlServiceUpdateReply(m
, sptr
, err
);
2495 for (rptr
= u
->RecordRegistrations
; rptr
; rptr
= rptr
->next
)
2497 if (rptr
->uDNS_info
.id
.NotAnInteger
== msg
->h
.id
.NotAnInteger
)
2499 err
= checkUpdateResult(rptr
->resrec
.name
, rcode
, m
, msg
, end
);
2500 if (!err
) SetUpdateExpiration(m
, msg
, end
, &rptr
->uDNS_info
);
2501 hndlRecordUpdateReply(m
, rptr
, err
);
2506 debugf("Received unexpected response: ID %d matches no active records", mDNSVal16(msg
->h
.id
));
2509 // lookup a DNS Server, matching by name in split-dns configurations. Result stored in addr parameter if successful
2510 mDNSlocal mDNSBool
GetServerForName(uDNS_GlobalInfo
*u
, const domainname
*name
, mDNSAddr
*addr
)
2512 DNSServer
*curmatch
= mDNSNULL
, *p
= u
->Servers
;
2513 int i
, ncount
, scount
, curmatchlen
= -1;
2516 ncount
= name
? CountLabels(name
) : 0;
2519 scount
= CountLabels(&p
->domain
);
2520 if (scount
<= ncount
&& scount
> curmatchlen
)
2522 // only inspect if server's domain is longer than current best match and shorter than the name itself
2523 const domainname
*tail
= name
;
2524 for (i
= 0; i
< ncount
- scount
; i
++)
2525 tail
= (domainname
*)(tail
->c
+ 1 + tail
->c
[0]); // find "tail" (scount labels) of name
2526 if (SameDomainName(tail
, &p
->domain
)) { curmatch
= p
; curmatchlen
= scount
; }
2533 *addr
= curmatch
->addr
;
2536 else return mDNSfalse
;
2539 // ***************************************************************************
2540 #if COMPILER_LIKES_PRAGMA_MARK
2541 #pragma mark - Query Routines
2544 #define sameID(x,y) mDNSPlatformMemSame(x,y,8)
2546 mDNSlocal
void initializeQuery(DNSMessage
*msg
, DNSQuestion
*question
)
2548 mDNSOpaque16 flags
= QueryFlags
;
2550 ubzero(msg
, sizeof(msg
));
2551 flags
.b
[0] |= kDNSFlag0_RD
; // recursion desired
2552 InitializeDNSMessage(&msg
->h
, question
->uDNS_info
.id
, flags
);
2555 mDNSlocal mStatus
constructQueryMsg(DNSMessage
*msg
, mDNSu8
**endPtr
, DNSQuestion
*const question
)
2557 initializeQuery(msg
, question
);
2559 *endPtr
= putQuestion(msg
, msg
->data
, msg
->data
+ AbsoluteMaxDNSMessageData
, &question
->qname
, question
->qtype
, question
->qclass
);
2562 LogMsg("ERROR: Unicast query out of space in packet");
2563 return mStatus_UnknownErr
;
2565 return mStatus_NoError
;
2568 mDNSlocal mDNSu8
*putLLQ(DNSMessage
*const msg
, mDNSu8
*ptr
, DNSQuestion
*question
, LLQOptData
*data
, mDNSBool includeQuestion
)
2571 ResourceRecord
*opt
= &rr
.resrec
;
2574 //!!!KRS when we implement multiple llqs per message, we'll need to memmove anything past the question section
2575 if (includeQuestion
)
2577 ptr
= putQuestion(msg
, ptr
, msg
->data
+ AbsoluteMaxDNSMessageData
, &question
->qname
, question
->qtype
, question
->qclass
);
2578 if (!ptr
) { LogMsg("ERROR: putLLQ - putQuestion"); return mDNSNULL
; }
2580 // locate OptRR if it exists, set pointer to end
2581 // !!!KRS implement me
2584 // format opt rr (fields not specified are zero-valued)
2585 ubzero(&rr
, sizeof(AuthRecord
));
2586 mDNS_SetupResourceRecord(&rr
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
2587 opt
->rdlength
= LLQ_OPT_SIZE
;
2588 opt
->rdestimate
= LLQ_OPT_SIZE
;
2590 optRD
= &rr
.resrec
.rdata
->u
.opt
;
2591 optRD
->opt
= kDNSOpt_LLQ
;
2592 optRD
->optlen
= sizeof(LLQOptData
);
2593 umemcpy(&optRD
->OptData
.llq
, data
, sizeof(LLQOptData
));
2594 ptr
= PutResourceRecordTTLJumbo(msg
, ptr
, &msg
->h
.numAdditionals
, opt
, 0);
2595 if (!ptr
) { LogMsg("ERROR: putLLQ - PutResourceRecordTTLJumbo"); return mDNSNULL
; }
2601 mDNSlocal mDNSBool
getLLQAtIndex(mDNS
*m
, DNSMessage
*msg
, const mDNSu8
*end
, LLQOptData
*llq
, int index
)
2603 LargeCacheRecord lcr
;
2607 ptr
= LocateAdditionals(msg
, end
);
2608 if (!ptr
) return mDNSfalse
;
2610 // find the last additional
2611 for (i
= 0; i
< msg
->h
.numAdditionals
; i
++)
2612 // { ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &lcr); if (!ptr) return mDNSfalse; }
2613 //!!!KRS workaround for LH server bug, which puts OPT as first additional
2614 { ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &lcr
); if (!ptr
) return mDNSfalse
; if (lcr
.r
.resrec
.rrtype
== kDNSType_OPT
) break; }
2615 if (lcr
.r
.resrec
.rrtype
!= kDNSType_OPT
) return mDNSfalse
;
2616 if (lcr
.r
.resrec
.rdlength
< (index
+ 1) * LLQ_OPT_SIZE
) return mDNSfalse
; // rdata too small
2617 umemcpy(llq
, (mDNSu8
*)&lcr
.r
.resrec
.rdata
->u
.opt
.OptData
.llq
+ (index
* sizeof(LLQOptData
)), sizeof(LLQOptData
)); // !!! Should convert to host byte order?
2621 mDNSlocal
void recvRefreshReply(mDNS
*m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*q
)
2626 qInfo
= q
->uDNS_info
.llq
;
2627 if (!getLLQAtIndex(m
, msg
, end
, &pktData
, 0)) { LogMsg("ERROR recvRefreshReply - getLLQAtIndex"); return; }
2628 if (pktData
.llqOp
!= kLLQOp_Refresh
) return;
2629 if (!sameID(pktData
.id
, qInfo
->id
)) { LogMsg("recvRefreshReply - ID mismatch. Discarding"); return; }
2630 if (pktData
.err
!= LLQErr_NoError
) { LogMsg("recvRefreshReply: received error %d from server", pktData
.err
); return; }
2632 qInfo
->expire
= mDNSPlatformTimeNow(m
) + ((mDNSs32
)pktData
.lease
* mDNSPlatformOneSecond
);
2633 qInfo
->retry
= qInfo
->expire
- ((mDNSs32
)pktData
.lease
* mDNSPlatformOneSecond
/2);
2635 qInfo
->origLease
= pktData
.lease
;
2636 qInfo
->state
= LLQ_Established
;
2639 mDNSlocal
void sendLLQRefresh(mDNS
*m
, DNSQuestion
*q
, mDNSu32 lease
)
2644 LLQ_Info
*info
= q
->uDNS_info
.llq
;
2648 timenow
= mDNSPlatformTimeNow(m
);
2649 if ((info
->state
== LLQ_Refresh
&& info
->ntries
>= kLLQ_MAX_TRIES
) ||
2650 info
->expire
- timenow
< 0)
2652 LogMsg("Unable to refresh LLQ %##s - will retry in %d minutes", q
->qname
.c
, kLLQ_DEF_RETRY
/60);
2653 info
->state
= LLQ_Retry
;
2654 info
->retry
= mDNSPlatformTimeNow(m
) + kLLQ_DEF_RETRY
* mDNSPlatformOneSecond
;
2655 info
->deriveRemovesOnResume
= mDNStrue
;
2657 //!!!KRS handle this - periodically try to re-establish
2660 llq
.vers
= kLLQ_Vers
;
2661 llq
.llqOp
= kLLQOp_Refresh
;
2662 llq
.err
= LLQErr_NoError
;
2663 umemcpy(llq
.id
, info
->id
, 8);
2666 initializeQuery(&msg
, q
);
2667 end
= putLLQ(&msg
, msg
.data
, q
, &llq
, mDNStrue
);
2668 if (!end
) { LogMsg("ERROR: sendLLQRefresh - putLLQ"); return; }
2670 err
= mDNSSendDNSMessage(m
, &msg
, end
, mDNSInterface_Any
, &info
->servAddr
, info
->servPort
, -1, mDNSNULL
);
2671 if (err
) LogMsg("ERROR: sendLLQRefresh - mDNSSendDNSMessage returned %ld", err
);
2673 if (info
->state
== LLQ_Established
) info
->ntries
= 1;
2674 else info
->ntries
++;
2675 info
->state
= LLQ_Refresh
;
2676 q
->LastQTime
= timenow
;
2677 info
->retry
= (info
->expire
- q
->LastQTime
) / 2;
2680 mDNSlocal mDNSBool
recvLLQEvent(mDNS
*m
, DNSQuestion
*q
, DNSMessage
*msg
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, mDNSIPPort srcport
, mDNSInterfaceID InterfaceID
)
2683 mDNSu8
*ackEnd
= ack
.data
;
2687 (void)InterfaceID
; // unused
2689 // find Opt RR, verify correct ID
2690 if (!getLLQAtIndex(m
, msg
, end
, &opt
, 0)) { debugf("Pkt does not contain LLQ Opt"); return mDNSfalse
; }
2691 if (opt
.llqOp
!= kLLQOp_Event
) { LogMsg("recvLLQEvent - Bad LLQ Opcode %d", opt
.llqOp
); return mDNSfalse
; }
2692 if (!q
->uDNS_info
.llq
) { LogMsg("Error: recvLLQEvent - question object does not contain LLQ metadata"); return mDNSfalse
; }
2693 if (!sameID(opt
.id
, q
->uDNS_info
.llq
->id
)) { return mDNSfalse
; }
2695 // invoke response handler
2696 m
->uDNS_info
.CurrentQuery
= q
;
2697 q
->uDNS_info
.responseCallback(m
, msg
, end
, q
, q
->uDNS_info
.context
);
2698 if (m
->uDNS_info
.CurrentQuery
!= q
) return mDNStrue
;
2700 // format and send ack
2701 InitializeDNSMessage(&ack
.h
, msg
->h
.id
, ResponseFlags
);
2702 ackEnd
= putQuestion(&ack
, ack
.data
, ack
.data
+ AbsoluteMaxDNSMessageData
, &q
->qname
, q
->qtype
, q
->qclass
);
2703 if (!ackEnd
) { LogMsg("ERROR: recvLLQEvent - putQuestion"); return mDNSfalse
; }
2704 err
= mDNSSendDNSMessage(m
, &ack
, ackEnd
, mDNSInterface_Any
, srcaddr
, srcport
, -1, mDNSNULL
);
2705 if (err
) LogMsg("ERROR: recvLLQEvent - mDNSSendDNSMessage returned %ld", err
);
2711 mDNSlocal
void hndlChallengeResponseAck(mDNS
*m
, DNSMessage
*pktMsg
, const mDNSu8
*end
, LLQOptData
*llq
, DNSQuestion
*q
)
2713 LLQ_Info
*info
= q
->uDNS_info
.llq
;
2715 if (llq
->err
) { LogMsg("hndlChallengeResponseAck - received error %d from server", llq
->err
); goto error
; }
2716 if (!sameID(info
->id
, llq
->id
)) { LogMsg("hndlChallengeResponseAck - ID changed. discarding"); return; } // this can happen rarely (on packet loss + reordering)
2717 info
->expire
= mDNSPlatformTimeNow(m
) + ((mDNSs32
)llq
->lease
* mDNSPlatformOneSecond
);
2718 info
->retry
= info
->expire
- ((mDNSs32
)llq
->lease
* mDNSPlatformOneSecond
/ 2);
2720 info
->origLease
= llq
->lease
;
2721 info
->state
= LLQ_Established
;
2723 q
->uDNS_info
.responseCallback
= llqResponseHndlr
;
2724 llqResponseHndlr(m
, pktMsg
, end
, q
, mDNSNULL
);
2728 info
->state
= LLQ_Error
;
2731 mDNSlocal
void sendChallengeResponse(mDNS
*m
, DNSQuestion
*q
, LLQOptData
*llq
)
2733 LLQ_Info
*info
= q
->uDNS_info
.llq
;
2734 DNSMessage response
;
2735 mDNSu8
*responsePtr
= response
.data
;
2738 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
2740 if (info
->ntries
++ == kLLQ_MAX_TRIES
)
2742 LogMsg("sendChallengeResponse: %d failed attempts for LLQ %##s. Will re-try in %d minutes",
2743 kLLQ_MAX_TRIES
, q
->qname
.c
, kLLQ_DEF_RETRY
/ 60);
2744 info
->state
= LLQ_Retry
;
2745 info
->retry
= timenow
+ (kLLQ_DEF_RETRY
* mDNSPlatformOneSecond
);
2746 // !!!KRS give a callback error in these cases?
2754 llq
->vers
= kLLQ_Vers
;
2755 llq
->llqOp
= kLLQOp_Setup
;
2756 llq
->err
= LLQErr_NoError
;
2757 umemcpy(llq
->id
, info
->id
, 8);
2758 llq
->lease
= info
->origLease
;
2761 q
->LastQTime
= timenow
;
2762 info
->retry
= timenow
+ (kLLQ_INIT_RESEND
* info
->ntries
* mDNSPlatformOneSecond
);
2764 if (constructQueryMsg(&response
, &responsePtr
, q
)) goto error
;
2765 responsePtr
= putLLQ(&response
, responsePtr
, q
, llq
, mDNSfalse
);
2766 if (!responsePtr
) { LogMsg("ERROR: sendChallengeResponse - putLLQ"); goto error
; }
2768 err
= mDNSSendDNSMessage(m
, &response
, responsePtr
, mDNSInterface_Any
, &info
->servAddr
, info
->servPort
, -1, mDNSNULL
);
2769 if (err
) LogMsg("ERROR: sendChallengeResponse - mDNSSendDNSMessage returned %ld", err
);
2770 // on error, we procede as normal and retry after the appropriate interval
2775 info
->state
= LLQ_Error
;
2780 mDNSlocal
void hndlRequestChallenge(mDNS
*m
, DNSMessage
*pktMsg
, const mDNSu8
*end
, LLQOptData
*llq
, DNSQuestion
*q
)
2782 LLQ_Info
*info
= q
->uDNS_info
.llq
;
2783 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
2786 case LLQErr_NoError
: break;
2787 case LLQErr_ServFull
:
2788 LogMsg("hndlRequestChallenge - received ServFull from server for LLQ %##s. Retry in %lu sec", q
->qname
.c
, llq
->lease
);
2789 info
->retry
= timenow
+ ((mDNSs32
)llq
->lease
* mDNSPlatformOneSecond
);
2790 info
->state
= LLQ_Retry
;
2791 simpleResponseHndlr(m
, pktMsg
, end
, q
, mDNSNULL
); // get available answers
2792 info
->deriveRemovesOnResume
= mDNStrue
;
2794 info
->state
= LLQ_Static
;
2795 LogMsg("LLQ %##s: static", q
->qname
.c
);
2796 simpleResponseHndlr(m
, pktMsg
, end
, q
, mDNSNULL
);
2798 case LLQErr_FormErr
:
2799 LogMsg("ERROR: hndlRequestChallenge - received FormErr from server for LLQ %##s", q
->qname
.c
);
2801 case LLQErr_BadVers
:
2802 LogMsg("ERROR: hndlRequestChallenge - received BadVers from server");
2804 case LLQErr_UnknownErr
:
2805 LogMsg("ERROR: hndlRequestChallenge - received UnknownErr from server for LLQ %##s", q
->qname
.c
);
2808 LogMsg("ERROR: hndlRequestChallenge - received invalid error %d for LLQ %##s", llq
->err
, q
->qname
.c
);
2812 if (info
->origLease
!= llq
->lease
)
2813 LogMsg("hndlRequestChallenge: requested lease %lu, granted lease %lu", info
->origLease
, llq
->lease
);
2815 // cache expiration in case we go to sleep before finishing setup
2816 info
->origLease
= llq
->lease
;
2817 info
->expire
= timenow
+ ((mDNSs32
)llq
->lease
* mDNSPlatformOneSecond
);
2820 info
->state
= LLQ_SecondaryRequest
;
2821 umemcpy(info
->id
, llq
->id
, 8);
2822 info
->ntries
= 0; // first attempt to send response
2824 sendChallengeResponse(m
, q
, llq
);
2829 info
->state
= LLQ_Error
;
2833 // response handler for initial and secondary setup responses
2834 mDNSlocal
void recvSetupResponse(mDNS
*m
, DNSMessage
*pktMsg
, const mDNSu8
*end
, DNSQuestion
*q
, void *clientContext
)
2836 DNSQuestion pktQuestion
;
2838 const mDNSu8
*ptr
= pktMsg
->data
;
2839 LLQ_Info
*info
= q
->uDNS_info
.llq
;
2840 mDNSu8 rcode
= (mDNSu8
)(pktMsg
->h
.flags
.b
[1] & kDNSFlag1_RC
);
2842 (void)clientContext
; // unused
2844 if (rcode
&& rcode
!= kDNSFlag1_RC_NXDomain
) goto poll
;
2846 ptr
= getQuestion(pktMsg
, ptr
, end
, 0, &pktQuestion
);
2847 if (!ptr
) { LogMsg("ERROR: recvSetupResponse - getQuestion"); goto poll
; }
2848 if (!SameDomainName(&q
->qname
, &pktQuestion
.qname
))
2849 { LogMsg("ERROR: recvSetupResponse - mismatched question in response for llq setup %##s", q
->qname
.c
); goto poll
; }
2851 if (!getLLQAtIndex(m
, pktMsg
, end
, &llq
, 0)) { debugf("recvSetupResponse - GetLLQAtIndex"); goto poll
; }
2852 if (llq
.llqOp
!= kLLQOp_Setup
) { LogMsg("ERROR: recvSetupResponse - bad op %d", llq
.llqOp
); goto poll
; }
2853 if (llq
.vers
!= kLLQ_Vers
) { LogMsg("ERROR: recvSetupResponse - bad vers %d", llq
.vers
); goto poll
; }
2855 if (info
->state
== LLQ_InitialRequest
) { hndlRequestChallenge(m
, pktMsg
, end
, &llq
, q
); return; }
2856 if (info
->state
== LLQ_SecondaryRequest
) { hndlChallengeResponseAck(m
, pktMsg
, end
, &llq
, q
); return; }
2857 LogMsg("recvSetupResponse - bad state %d", info
->state
);
2860 info
->state
= LLQ_Poll
;
2861 q
->uDNS_info
.responseCallback
= llqResponseHndlr
;
2862 info
->question
->LastQTime
= mDNSPlatformTimeNow(m
) - (2 * INIT_UCAST_POLL_INTERVAL
); // trigger immediate poll
2863 info
->question
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
;
2866 mDNSlocal
void startLLQHandshake(mDNS
*m
, LLQ_Info
*info
, mDNSBool defer
)
2871 DNSQuestion
*q
= info
->question
;
2872 mStatus err
= mStatus_NoError
;
2873 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
2874 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
2876 if (IsPrivateV4Addr(&u
->PrimaryIP
))
2880 info
->state
= LLQ_NatMapWait
;
2884 if (u
->LLQNatInfo
->state
== NATState_Error
) goto poll
;
2885 if (u
->LLQNatInfo
->state
!= NATState_Established
&& u
->LLQNatInfo
->state
!= NATState_Legacy
)
2886 { info
->state
= LLQ_NatMapWait
; info
->NATMap
= mDNStrue
; return; }
2887 info
->NATMap
= mDNStrue
; // this llq references the global llq nat mapping
2890 if (info
->ntries
++ >= kLLQ_MAX_TRIES
)
2892 debugf("startLLQHandshake: %d failed attempts for LLQ %##s. Polling.", kLLQ_MAX_TRIES
, q
->qname
.c
, kLLQ_DEF_RETRY
/ 60);
2897 llqData
.vers
= kLLQ_Vers
;
2898 llqData
.llqOp
= kLLQOp_Setup
;
2899 llqData
.err
= LLQErr_NoError
;
2900 ubzero(llqData
.id
, 8);
2901 llqData
.lease
= kLLQ_DefLease
;
2903 initializeQuery(&msg
, q
);
2904 end
= putLLQ(&msg
, msg
.data
, q
, &llqData
, mDNStrue
);
2907 LogMsg("ERROR: startLLQHandshake - putLLQ");
2908 info
->state
= LLQ_Error
;
2912 if (!defer
) // if we are to defer, we simply set the retry timers so the request goes out in the future
2914 err
= mDNSSendDNSMessage(m
, &msg
, end
, mDNSInterface_Any
, &info
->servAddr
, info
->servPort
, -1, mDNSNULL
);
2915 if (err
) LogMsg("ERROR: startLLQHandshake - mDNSSendDNSMessage returned %ld", err
);
2916 // on error, we procede as normal and retry after the appropriate interval
2919 // update question/info state
2920 info
->state
= LLQ_InitialRequest
;
2921 info
->origLease
= kLLQ_DefLease
;
2922 info
->retry
= timenow
+ (kLLQ_INIT_RESEND
* mDNSPlatformOneSecond
);
2923 q
->LastQTime
= timenow
;
2924 q
->uDNS_info
.responseCallback
= recvSetupResponse
;
2925 q
->uDNS_info
.internal
= mDNStrue
;
2929 info
->question
->uDNS_info
.responseCallback
= llqResponseHndlr
;
2930 info
->state
= LLQ_Poll
;
2931 info
->question
->LastQTime
= mDNSPlatformTimeNow(m
) - (2 * INIT_UCAST_POLL_INTERVAL
); // trigger immediate poll
2932 info
->question
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
;
2935 // wrapper for startLLQHandshake, invoked by async op callback
2936 mDNSlocal
void startLLQHandshakeCallback(mStatus err
, mDNS
*const m
, void *llqInfo
, const AsyncOpResult
*result
)
2938 LLQ_Info
*info
= (LLQ_Info
*)llqInfo
;
2939 const zoneData_t
*zoneInfo
= mDNSNULL
;
2941 // check state first to make sure it is OK to touch question object
2942 if (info
->state
== LLQ_Cancelled
)
2944 // StopQuery was called while we were getting the zone info
2945 debugf("startLLQHandshake - LLQ Cancelled.");
2946 info
->question
= mDNSNULL
; // question may be deallocated
2951 if (!info
->question
)
2952 { LogMsg("ERROR: startLLQHandshakeCallback invoked with NULL question"); goto error
; }
2954 if (info
->state
!= LLQ_GetZoneInfo
)
2955 { LogMsg("ERROR: startLLQHandshake - bad state %d", info
->state
); goto error
; }
2958 { LogMsg("ERROR: startLLQHandshakeCallback invoked with error code %ld", err
); goto poll
; }
2961 { LogMsg("ERROR: startLLQHandshakeCallback invoked with NULL result and no error code"); goto error
; }
2963 zoneInfo
= &result
->zoneData
;
2965 if (!zoneInfo
->llqPort
.NotAnInteger
)
2966 { debugf("LLQ port lookup failed - reverting to polling"); goto poll
; }
2968 // cache necessary zone data
2969 info
->servAddr
.type
= zoneInfo
->primaryAddr
.type
;
2970 info
->servAddr
.ip
.v4
.NotAnInteger
= zoneInfo
->primaryAddr
.ip
.v4
.NotAnInteger
;
2971 info
->servPort
.NotAnInteger
= zoneInfo
->llqPort
.NotAnInteger
;
2974 if (info
->state
== LLQ_SuspendDeferred
) info
->state
= LLQ_Suspended
;
2975 else startLLQHandshake(m
, info
, mDNSfalse
);
2979 info
->question
->uDNS_info
.responseCallback
= llqResponseHndlr
;
2980 info
->state
= LLQ_Poll
;
2981 info
->question
->LastQTime
= mDNSPlatformTimeNow(m
) - (2 * INIT_UCAST_POLL_INTERVAL
); // trigger immediate poll
2982 info
->question
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
;
2986 info
->state
= LLQ_Error
;
2989 mDNSlocal mStatus
startLLQ(mDNS
*m
, DNSQuestion
*question
)
2992 mStatus err
= mStatus_NoError
;
2994 // allocate / init info struct
2995 info
= umalloc(sizeof(LLQ_Info
));
2996 if (!info
) { LogMsg("ERROR: startLLQ - malloc"); return mStatus_NoMemoryErr
; }
2997 ubzero(info
, sizeof(LLQ_Info
));
2998 info
->state
= LLQ_GetZoneInfo
;
3000 // link info/question
3001 info
->question
= question
;
3002 question
->uDNS_info
.llq
= info
;
3004 question
->uDNS_info
.responseCallback
= llqResponseHndlr
;
3006 err
= startGetZoneData(&question
->qname
, m
, mDNSfalse
, mDNStrue
, startLLQHandshakeCallback
, info
);
3009 LogMsg("ERROR: startLLQ - startGetZoneData returned %ld", err
);
3010 info
->question
= mDNSNULL
;
3012 question
->uDNS_info
.llq
= mDNSNULL
;
3016 LinkActiveQuestion(&m
->uDNS_info
, question
);
3020 mDNSlocal mDNSBool
recvLLQResponse(mDNS
*m
, DNSMessage
*msg
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, mDNSIPPort srcport
, const mDNSInterfaceID InterfaceID
)
3022 DNSQuestion pktQ
, *q
;
3023 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
3024 const mDNSu8
*ptr
= msg
->data
;
3027 if (!msg
->h
.numQuestions
) return mDNSfalse
;
3029 ptr
= getQuestion(msg
, ptr
, end
, 0, &pktQ
);
3030 if (!ptr
) return mDNSfalse
;
3031 pktQ
.uDNS_info
.id
= msg
->h
.id
;
3033 q
= u
->ActiveQueries
;
3036 llqInfo
= q
->uDNS_info
.llq
;
3039 q
->qnamehash
== pktQ
.qnamehash
&&
3040 q
->qtype
== pktQ
.qtype
&&
3041 SameDomainName(&q
->qname
, &pktQ
.qname
))
3043 u
->CurrentQuery
= q
;
3044 if (llqInfo
->state
== LLQ_Established
|| (llqInfo
->state
== LLQ_Refresh
&& msg
->h
.numAnswers
))
3045 { if (recvLLQEvent(m
, q
, msg
, end
, srcaddr
, srcport
, InterfaceID
)) return mDNStrue
; }
3046 else if (msg
->h
.id
.NotAnInteger
== q
->uDNS_info
.id
.NotAnInteger
)
3048 if (llqInfo
->state
== LLQ_Refresh
&& msg
->h
.numAdditionals
&& !msg
->h
.numAnswers
)
3049 { recvRefreshReply(m
, msg
, end
, q
); return mDNStrue
; }
3050 if (llqInfo
->state
< LLQ_Static
)
3052 if ((llqInfo
->state
!= LLQ_InitialRequest
&& llqInfo
->state
!= LLQ_SecondaryRequest
) || mDNSSameAddress(srcaddr
, &llqInfo
->servAddr
))
3053 { q
->uDNS_info
.responseCallback(m
, msg
, end
, q
, q
->uDNS_info
.context
); return mDNStrue
; }
3062 mDNSexport mDNSBool
uDNS_IsActiveQuery(DNSQuestion
*const question
, uDNS_GlobalInfo
*u
)
3066 for (q
= u
->ActiveQueries
; q
; q
= q
->next
)
3070 if (!question
->uDNS_info
.id
.NotAnInteger
|| question
->InterfaceID
== mDNSInterface_LocalOnly
|| IsLocalDomain(&question
->qname
))
3071 LogMsg("Warning: Question %##s in Active Unicast Query list with id %d, interfaceID %p",
3072 question
->qname
.c
, question
->uDNS_info
.id
.NotAnInteger
, question
->InterfaceID
);
3079 // stopLLQ happens IN ADDITION to stopQuery
3080 mDNSlocal
void stopLLQ(mDNS
*m
, DNSQuestion
*question
)
3082 LLQ_Info
*info
= question
->uDNS_info
.llq
;
3085 if (!question
->LongLived
) { LogMsg("ERROR: stopLLQ - LongLived flag not set"); return; }
3086 if (!info
) { LogMsg("ERROR: stopLLQ - llq info is NULL"); return; }
3088 switch (info
->state
)
3091 LogMsg("ERROR: stopLLQ - state LLQ_UnInit");
3092 //!!!KRS should we unlink info<->question here?
3094 case LLQ_GetZoneInfo
:
3095 case LLQ_SuspendDeferred
:
3096 info
->question
= mDNSNULL
; // remove ref to question, as it may be freed when we get called back from async op
3097 info
->state
= LLQ_Cancelled
;
3099 case LLQ_Established
:
3101 // refresh w/ lease 0
3102 sendLLQRefresh(m
, question
, 0);
3105 debugf("stopLLQ - silently discarding LLQ in state %d", info
->state
);
3110 if (info
->NATMap
) info
->NATMap
= mDNSfalse
;
3111 CheckForUnreferencedLLQMapping(m
);
3112 info
->question
= mDNSNULL
;
3114 question
->uDNS_info
.llq
= mDNSNULL
;
3115 question
->LongLived
= mDNSfalse
;
3118 mDNSexport mStatus
uDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
3120 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
3121 DNSQuestion
*qptr
, *prev
= mDNSNULL
;
3124 qptr
= u
->ActiveQueries
;
3127 if (qptr
== question
)
3129 if (question
->LongLived
&& question
->uDNS_info
.llq
)
3130 stopLLQ(m
, question
);
3131 if (m
->uDNS_info
.CurrentQuery
== question
)
3132 m
->uDNS_info
.CurrentQuery
= m
->uDNS_info
.CurrentQuery
->next
;
3133 while (question
->uDNS_info
.knownAnswers
)
3135 ka
= question
->uDNS_info
.knownAnswers
;
3136 question
->uDNS_info
.knownAnswers
= question
->uDNS_info
.knownAnswers
->next
;
3139 if (prev
) prev
->next
= question
->next
;
3140 else u
->ActiveQueries
= question
->next
;
3141 return mStatus_NoError
;
3146 LogMsg("uDNS_StopQuery: no such active query (%##s)", question
->qname
.c
);
3147 return mStatus_UnknownErr
;
3150 mDNSlocal mStatus
startQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool internal
)
3152 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
3155 mStatus err
= mStatus_NoError
;
3158 //!!!KRS we should check if the question is already in our acivequestion list
3159 if (!ValidateDomainName(&question
->qname
))
3161 LogMsg("Attempt to start query with invalid qname %##s %##s", question
->qname
.c
, DNSTypeName(question
->qtype
));
3162 return mStatus_Invalid
;
3165 question
->next
= mDNSNULL
;
3166 question
->qnamehash
= DomainNameHashValue(&question
->qname
); // to do quick domain name comparisons
3167 question
->uDNS_info
.id
= newMessageID(u
);
3168 question
->uDNS_info
.Answered
= mDNSfalse
;
3170 // break here if its and LLQ
3171 if (question
->LongLived
) return startLLQ(m
, question
);
3173 // else send the query to our server
3174 err
= constructQueryMsg(&msg
, &endPtr
, question
);
3175 if (err
) return err
;
3177 question
->LastQTime
= mDNSPlatformTimeNow(m
);
3178 question
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
;
3179 // store the question/id in active question list
3180 question
->uDNS_info
.internal
= internal
;
3181 LinkActiveQuestion(u
, question
);
3182 question
->uDNS_info
.knownAnswers
= mDNSNULL
;
3183 if (GetServerForName(u
, &question
->qname
, &server
))
3185 err
= mDNSSendDNSMessage(m
, &msg
, endPtr
, mDNSInterface_Any
, &server
, UnicastDNSPort
, -1, mDNSNULL
);
3186 if (err
) { debugf("ERROR: startQuery - %ld (keeping question in list for retransmission", err
); }
3189 return mStatus_NoError
; // don't return transient errors to caller
3192 mDNSexport mStatus
uDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
3194 ubzero(&question
->uDNS_info
, sizeof(uDNS_QuestionInfo
));
3195 question
->uDNS_info
.responseCallback
= simpleResponseHndlr
;
3196 question
->uDNS_info
.context
= mDNSNULL
;
3197 //LogOperation("uDNS_StartQuery %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3198 return startQuery(m
, question
, 0);
3201 // explicitly set response handler
3202 mDNSlocal mStatus
startInternalQuery(DNSQuestion
*q
, mDNS
*m
, InternalResponseHndlr callback
, void *hndlrContext
)
3204 ubzero(&q
->uDNS_info
, sizeof(uDNS_QuestionInfo
));
3205 q
->QuestionContext
= hndlrContext
;
3206 q
->uDNS_info
.responseCallback
= callback
;
3207 q
->uDNS_info
.context
= hndlrContext
;
3208 return startQuery(m
, q
, 1);
3213 // ***************************************************************************
3214 #if COMPILER_LIKES_PRAGMA_MARK
3215 #pragma mark - Domain -> Name Server Conversion
3221 * Asynchronously find the address of the nameserver for the enclosing zone for a given domain name,
3222 * i.e. the server to which update and LLQ requests will be sent for a given name. Once the address is
3223 * derived, it will be passed to the callback, along with a context pointer. If the zone cannot
3224 * be determined or if an error occurs, an all-zeros address will be passed and a message will be
3225 * written to the syslog.
3227 * If the FindUpdatePort arg is set, the port on which the server accepts dynamic updates is determined
3228 * by querying for the _dns-update._udp.<zone>. SRV record. Likewise, if the FindLLQPort arg is set,
3229 * the port on which the server accepts long lived queries is determined by querying for
3230 * _dns-llq._udp.<zone>. record. If either of these queries fail, or flags are not specified,
3231 * the llqPort and updatePort fields in the result structure are set to zero.
3233 * Steps for deriving the zone name are as follows:
3235 * Query for an SOA record for the required domain. If we don't get an answer (or an SOA in the Authority
3236 * section), we strip the leading label from the name and repeat, until we get an answer.
3238 * The name of the SOA record is our enclosing zone. The mname field in the SOA rdata is the domain
3239 * name of the primary NS.
3241 * We verify that there is an NS record with this zone for a name and the mname for its rdata.
3242 * (!!!KRS this seems redundant, but BIND does this, and it should normally be zero-overhead since
3243 * the NS query will get us address records in the additionals section, which we'd otherwise have to
3244 * explicitly query for.)
3246 * We then query for the address record for this nameserver (if it is not in the addionals section of
3247 * the NS record response.)
3251 // state machine types and structs
3254 // state machine states
3269 // state machine actions
3272 smContinue
, // continue immediately to next state
3273 smBreak
, // break until next packet/timeout
3274 smError
// terminal error - cleanup and abort
3279 domainname origName
; // name we originally try to convert
3280 domainname
*curSOA
; // name we have an outstanding SOA query for
3281 ntaState state
; // determines what we do upon receiving a packet
3283 domainname zone
; // left-hand-side of SOA record
3285 domainname ns
; // mname in SOA rdata, verified in confirmNS state
3286 mDNSv4Addr addr
; // address of nameserver
3287 DNSQuestion question
; // storage for any active question
3288 DNSQuestion extraQuestion
; // additional storage
3289 mDNSBool questionActive
; // if true, StopQuery() can be called on the question field
3290 mDNSBool findUpdatePort
;
3291 mDNSBool findLLQPort
;
3292 mDNSIPPort updatePort
;
3294 AsyncOpCallback
*callback
; // caller specified function to be called upon completion
3299 // function prototypes (for routines that must be used as fn pointers prior to their definitions,
3300 // and allows states to be read top-to-bottom in logical order)
3301 mDNSlocal
void getZoneData(mDNS
*const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
, void *contextPtr
);
3302 mDNSlocal smAction
hndlLookupSOA(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
);
3303 mDNSlocal
void processSOA(ntaContext
*context
, ResourceRecord
*rr
);
3304 mDNSlocal smAction
confirmNS(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
);
3305 mDNSlocal smAction
lookupNSAddr(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
);
3306 mDNSlocal smAction
hndlLookupPorts(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
);
3309 mDNSlocal mStatus
startGetZoneData(domainname
*name
, mDNS
*m
, mDNSBool findUpdatePort
, mDNSBool findLLQPort
,
3310 AsyncOpCallback callback
, void *callbackInfo
)
3312 ntaContext
*context
= (ntaContext
*)umalloc(sizeof(ntaContext
));
3313 if (!context
) { LogMsg("ERROR: startGetZoneData - umalloc failed"); return mStatus_NoMemoryErr
; }
3314 ubzero(context
, sizeof(ntaContext
));
3315 AssignDomainName(&context
->origName
, name
);
3316 context
->state
= init
;
3318 context
->callback
= callback
;
3319 context
->callbackInfo
= callbackInfo
;
3320 context
->findUpdatePort
= findUpdatePort
;
3321 context
->findLLQPort
= findLLQPort
;
3322 getZoneData(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
, context
);
3323 return mStatus_NoError
;
3326 // state machine entry routine
3327 mDNSlocal
void getZoneData(mDNS
*const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
, void *contextPtr
)
3329 AsyncOpResult result
;
3330 ntaContext
*context
= (ntaContext
*)contextPtr
;
3337 // stop any active question
3338 if (context
->questionActive
)
3340 uDNS_StopQuery(context
->m
, &context
->question
);
3341 context
->questionActive
= mDNSfalse
;
3344 if (msg
&& msg
->h
.flags
.b
[2] >> 4 && msg
->h
.flags
.b
[2] >> 4 != kDNSFlag1_RC_NXDomain
)
3346 // rcode non-zero, non-nxdomain
3347 LogMsg("ERROR: getZoneData - received response w/ rcode %d", msg
->h
.flags
.b
[2] >> 4);
3351 switch (context
->state
)
3355 action
= hndlLookupSOA(msg
, end
, context
);
3356 if (action
== smError
) goto error
;
3357 if (action
== smBreak
) return;
3360 action
= confirmNS(msg
, end
, context
);
3361 if (action
== smError
) goto error
;
3362 if (action
== smBreak
) return;
3365 action
= lookupNSAddr(msg
, end
, context
);
3366 if (action
== smError
) goto error
;
3367 if (action
== smBreak
) return;
3369 if (!context
->findUpdatePort
&& !context
->findLLQPort
)
3371 context
->state
= complete
;
3375 action
= hndlLookupPorts(msg
, end
, context
);
3376 if (action
== smError
) goto error
;
3377 if (action
== smBreak
) return;
3378 if (action
== smContinue
) context
->state
= complete
;
3380 case complete
: break;
3383 if (context
->state
!= complete
)
3385 LogMsg("ERROR: getZoneData - exited state machine with state %d", context
->state
);
3389 result
.type
= zoneDataResult
;
3390 result
.zoneData
.primaryAddr
.ip
.v4
.NotAnInteger
= context
->addr
.NotAnInteger
;
3391 result
.zoneData
.primaryAddr
.type
= mDNSAddrType_IPv4
;
3392 AssignDomainName(&result
.zoneData
.zoneName
, &context
->zone
);
3393 result
.zoneData
.zoneClass
= context
->zoneClass
;
3394 result
.zoneData
.llqPort
= context
->findLLQPort
? context
->llqPort
: zeroIPPort
;
3395 result
.zoneData
.updatePort
= context
->findUpdatePort
? context
->updatePort
: zeroIPPort
;
3396 context
->callback(mStatus_NoError
, context
->m
, context
->callbackInfo
, &result
);
3400 if (context
&& context
->callback
)
3401 context
->callback(mStatus_UnknownErr
, context
->m
, context
->callbackInfo
, mDNSNULL
);
3403 if (context
&& context
->questionActive
)
3405 uDNS_StopQuery(context
->m
, &context
->question
);
3406 context
->questionActive
= mDNSfalse
;
3408 if (context
) ufree(context
);
3411 mDNSlocal smAction
hndlLookupSOA(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
)
3414 LargeCacheRecord lcr
;
3415 ResourceRecord
*rr
= &lcr
.r
.resrec
;
3416 DNSQuestion
*query
= &context
->question
;
3421 // if msg contains SOA record in answer or authority sections, update context/state and return
3423 ptr
= LocateAnswers(msg
, end
);
3424 for (i
= 0; i
< msg
->h
.numAnswers
; i
++)
3426 ptr
= GetLargeResourceRecord(context
->m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, &lcr
);
3427 if (!ptr
) { LogMsg("ERROR: hndlLookupSOA, Answers - GetLargeResourceRecord returned NULL"); return smError
; }
3428 if (rr
->rrtype
== kDNSType_SOA
&& SameDomainName(context
->curSOA
, rr
->name
))
3430 processSOA(context
, rr
);
3434 ptr
= LocateAuthorities(msg
, end
);
3435 // SOA not in answers, check in authority
3436 for (i
= 0; i
< msg
->h
.numAuthorities
; i
++)
3438 ptr
= GetLargeResourceRecord(context
->m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, &lcr
); ///!!!KRS using type PacketAns for auth
3439 if (!ptr
) { LogMsg("ERROR: hndlLookupSOA, Authority - GetLargeResourceRecord returned NULL"); return smError
; }
3440 if (rr
->rrtype
== kDNSType_SOA
)
3442 processSOA(context
, rr
);
3448 if (context
->state
!= init
&& !context
->curSOA
->c
[0])
3450 // we've gone down to the root and have not found an SOA
3451 LogMsg("ERROR: hndlLookupSOA - recursed to root label of %##s without finding SOA",
3452 context
->origName
.c
);
3456 ubzero(query
, sizeof(DNSQuestion
));
3457 // chop off leading label unless this is our first try
3458 if (context
->state
== init
) context
->curSOA
= &context
->origName
;
3459 else context
->curSOA
= (domainname
*)(context
->curSOA
->c
+ context
->curSOA
->c
[0]+1);
3461 context
->state
= lookupSOA
;
3462 AssignDomainName(&query
->qname
, context
->curSOA
);
3463 query
->qtype
= kDNSType_SOA
;
3464 query
->qclass
= kDNSClass_IN
;
3465 err
= startInternalQuery(query
, context
->m
, getZoneData
, context
);
3466 context
->questionActive
= mDNStrue
;
3467 if (err
) LogMsg("hndlLookupSOA: startInternalQuery returned error %ld (breaking until next periodic retransmission)", err
);
3469 return smBreak
; // break from state machine until we receive another packet
3472 mDNSlocal
void processSOA(ntaContext
*context
, ResourceRecord
*rr
)
3474 AssignDomainName(&context
->zone
, rr
->name
);
3475 context
->zoneClass
= rr
->rrclass
;
3476 AssignDomainName(&context
->ns
, &rr
->rdata
->u
.soa
.mname
);
3477 context
->state
= foundZone
;
3481 mDNSlocal smAction
confirmNS(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
)
3483 DNSQuestion
*query
= &context
->question
;
3485 LargeCacheRecord lcr
;
3486 const ResourceRecord
*const rr
= &lcr
.r
.resrec
;
3490 if (context
->state
== foundZone
)
3492 // we've just learned the zone. confirm that an NS record exists
3493 AssignDomainName(&query
->qname
, &context
->zone
);
3494 query
->qtype
= kDNSType_NS
;
3495 query
->qclass
= kDNSClass_IN
;
3496 err
= startInternalQuery(query
, context
->m
, getZoneData
, context
);
3497 context
->questionActive
= mDNStrue
;
3498 if (err
) LogMsg("confirmNS: startInternalQuery returned error %ld (breaking until next periodic retransmission", err
);
3499 context
->state
= lookupNS
;
3500 return smBreak
; // break from SM until we receive another packet
3502 else if (context
->state
== lookupNS
)
3504 ptr
= LocateAnswers(msg
, end
);
3505 for (i
= 0; i
< msg
->h
.numAnswers
; i
++)
3507 ptr
= GetLargeResourceRecord(context
->m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, &lcr
);
3508 if (!ptr
) { LogMsg("ERROR: confirmNS, Answers - GetLargeResourceRecord returned NULL"); return smError
; }
3509 if (rr
->rrtype
== kDNSType_NS
&&
3510 SameDomainName(&context
->zone
, rr
->name
) && SameDomainName(&context
->ns
, &rr
->rdata
->u
.name
))
3512 context
->state
= foundNS
;
3513 return smContinue
; // next routine will examine additionals section of A record
3516 LogMsg("ERROR: could not confirm existence of record %##s NS %##s", context
->zone
.c
, context
->ns
.c
);
3519 else { LogMsg("ERROR: confirmNS - bad state %d", context
->state
); return smError
; }
3522 mDNSlocal smAction
queryNSAddr(ntaContext
*context
)
3525 DNSQuestion
*query
= &context
->question
;
3527 AssignDomainName(&query
->qname
, &context
->ns
);
3528 query
->qtype
= kDNSType_A
;
3529 query
->qclass
= kDNSClass_IN
;
3530 err
= startInternalQuery(query
, context
->m
, getZoneData
, context
);
3531 context
->questionActive
= mDNStrue
;
3532 if (err
) LogMsg("confirmNS: startInternalQuery returned error %ld (breaking until next periodic retransmission)", err
);
3533 context
->state
= lookupA
;
3537 mDNSlocal smAction
lookupNSAddr(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
)
3541 LargeCacheRecord lcr
;
3542 ResourceRecord
*rr
= &lcr
.r
.resrec
;
3544 if (context
->state
== foundNS
)
3546 // we just found the NS record - look for the corresponding A record in the Additionals section
3547 if (!msg
->h
.numAdditionals
) return queryNSAddr(context
);
3548 ptr
= LocateAdditionals(msg
, end
);
3551 LogMsg("ERROR: lookupNSAddr - LocateAdditionals returned NULL, expected %d additionals", msg
->h
.numAdditionals
);
3552 return queryNSAddr(context
);
3556 for (i
= 0; i
< msg
->h
.numAdditionals
; i
++)
3558 ptr
= GetLargeResourceRecord(context
->m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, &lcr
);
3561 LogMsg("ERROR: lookupNSAddr, Additionals - GetLargeResourceRecord returned NULL");
3562 return queryNSAddr(context
);
3564 if (rr
->rrtype
== kDNSType_A
&& SameDomainName(&context
->ns
, rr
->name
))
3566 context
->addr
.NotAnInteger
= rr
->rdata
->u
.ipv4
.NotAnInteger
;
3567 context
->state
= foundA
;
3572 // no A record in Additionals - query the server
3573 return queryNSAddr(context
);
3575 else if (context
->state
== lookupA
)
3577 ptr
= LocateAnswers(msg
, end
);
3578 if (!ptr
) { LogMsg("ERROR: lookupNSAddr: LocateAnswers returned NULL"); return smError
; }
3579 for (i
= 0; i
< msg
->h
.numAnswers
; i
++)
3581 ptr
= GetLargeResourceRecord(context
->m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, &lcr
);
3582 if (!ptr
) { LogMsg("ERROR: lookupNSAddr, Answers - GetLargeResourceRecord returned NULL"); break; }
3583 if (rr
->rrtype
== kDNSType_A
&& SameDomainName(&context
->ns
, rr
->name
))
3585 context
->addr
.NotAnInteger
= rr
->rdata
->u
.ipv4
.NotAnInteger
;
3586 context
->state
= foundA
;
3590 LogMsg("ERROR: lookupNSAddr: Address record not found in answer section");
3593 else { LogMsg("ERROR: lookupNSAddr - bad state %d", context
->state
); return smError
; }
3596 mDNSlocal smAction
lookupDNSPort(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
, char *portName
, mDNSIPPort
*port
)
3599 LargeCacheRecord lcr
;
3604 if (context
->state
== lookupPort
) // we've already issued the query
3606 if (!msg
) { LogMsg("ERROR: hndlLookupUpdatePort - NULL message"); return smError
; }
3607 ptr
= LocateAnswers(msg
, end
);
3608 for (i
= 0; i
< msg
->h
.numAnswers
; i
++)
3610 ptr
= GetLargeResourceRecord(context
->m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAns
, &lcr
);
3611 if (!ptr
) { LogMsg("ERROR: hndlLookupUpdatePort - GetLargeResourceRecord returned NULL"); return smError
; }
3612 if (ResourceRecordAnswersQuestion(&lcr
.r
.resrec
, &context
->question
))
3614 port
->NotAnInteger
= lcr
.r
.resrec
.rdata
->u
.srv
.port
.NotAnInteger
;
3615 context
->state
= foundPort
;
3619 debugf("hndlLookupUpdatePort - no answer for type %s", portName
);
3620 port
->NotAnInteger
= 0;
3621 context
->state
= foundPort
;
3625 // query the server for the update port for the zone
3626 context
->state
= lookupPort
;
3627 q
= &context
->question
;
3628 MakeDomainNameFromDNSNameString(&q
->qname
, portName
);
3629 AppendDomainName(&q
->qname
, &context
->zone
);
3630 q
->qtype
= kDNSType_SRV
;
3631 q
->qclass
= kDNSClass_IN
;
3632 err
= startInternalQuery(q
, context
->m
, getZoneData
, context
);
3633 context
->questionActive
= mDNStrue
;
3634 if (err
) LogMsg("hndlLookupSOA: startInternalQuery returned error %ld (breaking until next periodic retransmission)", err
);
3635 return smBreak
; // break from state machine until we receive another packet
3638 mDNSlocal smAction
hndlLookupPorts(DNSMessage
*msg
, const mDNSu8
*end
, ntaContext
*context
)
3642 if (context
->findUpdatePort
&& !context
->updatePort
.NotAnInteger
)
3644 action
= lookupDNSPort(msg
, end
, context
, UPDATE_PORT_NAME
, &context
->updatePort
);
3645 if (action
!= smContinue
) return action
;
3647 if (context
->findLLQPort
&& !context
->llqPort
.NotAnInteger
)
3648 return lookupDNSPort(msg
, end
, context
, LLQ_PORT_NAME
, &context
->llqPort
);
3654 // ***************************************************************************
3655 #if COMPILER_LIKES_PRAGMA_MARK
3656 #pragma mark - Truncation Handling
3661 DNSQuestion
*question
;
3668 // issue queries over a conected socket
3669 mDNSlocal
void conQueryCallback(int sd
, void *context
, mDNSBool ConnectionEstablished
)
3672 char msgbuf
[356]; // 96 (hdr) + 256 (domain) + 4 (class/type)
3675 tcpInfo_t
*info
= (tcpInfo_t
*)context
;
3676 DNSQuestion
*question
= info
->question
;
3682 if (ConnectionEstablished
)
3684 // connection is established - send the message
3685 msg
= (DNSMessage
*)&msgbuf
;
3686 err
= constructQueryMsg(msg
, &end
, question
);
3687 if (err
) { LogMsg("ERROR: conQueryCallback: constructQueryMsg - %ld", err
); goto error
; }
3688 err
= mDNSSendDNSMessage(m
, msg
, end
, mDNSInterface_Any
, &zeroAddr
, zeroIPPort
, sd
, mDNSNULL
);
3689 question
->LastQTime
= mDNSPlatformTimeNow(m
);
3690 if (err
) { LogMsg("ERROR: conQueryCallback: mDNSSendDNSMessage_tcp - %ld", err
); goto error
; }
3698 n
= mDNSPlatformReadTCP(sd
, lenbuf
, 2);
3701 LogMsg("ERROR:conQueryCallback - attempt to read message length failed (read returned %d)", n
);
3704 info
->replylen
= (mDNSu16
)((mDNSu16
)lenbuf
[0] << 8 | lenbuf
[1]);
3706 n
= mDNSPlatformReadTCP(sd
, ((char *)&info
->reply
) + info
->nread
, info
->replylen
- info
->nread
);
3707 if (n
< 0) { LogMsg("ERROR: conQueryCallback - read returned %d", n
); goto error
; }
3709 if (info
->nread
== info
->replylen
)
3711 // Finished reading message; convert the integer parts which are in IETF byte-order (MSB first, LSB second)
3712 DNSMessage
*msg
= &info
->reply
;
3713 mDNSu8
*ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
3714 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
3715 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
3716 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
3717 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
3718 uDNS_ReceiveMsg(m
, msg
, (mDNSu8
*)msg
+ info
->replylen
, mDNSNULL
, zeroIPPort
, mDNSNULL
, zeroIPPort
, question
->InterfaceID
);
3719 mDNSPlatformTCPCloseConnection(sd
);
3728 mDNSPlatformTCPCloseConnection(sd
);
3733 mDNSlocal
void hndlTruncatedAnswer(DNSQuestion
*question
, const mDNSAddr
*src
, mDNS
*m
)
3735 mStatus connectionStatus
;
3736 uDNS_QuestionInfo
*info
= &question
->uDNS_info
;
3740 if (!src
) { LogMsg("hndlTruncatedAnswer: TCP DNS response had TC bit set: ignoring"); return; }
3742 context
= (tcpInfo_t
*)umalloc(sizeof(tcpInfo_t
));
3743 if (!context
) { LogMsg("ERROR: hndlTruncatedAnswer - memallocate failed"); return; }
3744 ubzero(context
, sizeof(tcpInfo_t
));
3745 context
->question
= question
;
3747 info
->id
= newMessageID(&m
->uDNS_info
);
3749 connectionStatus
= mDNSPlatformTCPConnect(src
, UnicastDNSPort
, question
->InterfaceID
, conQueryCallback
, context
, &sd
);
3750 if (connectionStatus
== mStatus_ConnEstablished
) // manually invoke callback if connection completes
3752 conQueryCallback(sd
, context
, mDNStrue
);
3755 if (connectionStatus
== mStatus_ConnPending
) return; // callback will be automatically invoked when connection completes
3756 LogMsg("hndlTruncatedAnswer: connection failed");
3757 uDNS_StopQuery(m
, question
); //!!!KRS can we really call this here?
3761 // ***************************************************************************
3762 #if COMPILER_LIKES_PRAGMA_MARK
3763 #pragma mark - Dynamic Updates
3768 mDNSlocal
void sendRecordRegistration(mDNS
*const m
, AuthRecord
*rr
)
3771 mDNSu8
*ptr
= msg
.data
;
3772 mDNSu8
*end
= (mDNSu8
*)&msg
+ sizeof(DNSMessage
);
3773 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
3775 uDNS_RegInfo
*regInfo
= &rr
->uDNS_info
;
3776 mStatus err
= mStatus_UnknownErr
;
3778 id
= newMessageID(u
);
3779 InitializeDNSMessage(&msg
.h
, id
, UpdateReqFlags
);
3780 rr
->uDNS_info
.id
.NotAnInteger
= id
.NotAnInteger
;
3783 ptr
= putZone(&msg
, ptr
, end
, ®Info
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
3784 if (!ptr
) goto error
;
3786 if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
3788 // KnownUnique: Delete any previous value
3789 ptr
= putDeleteRRSet(&msg
, ptr
, rr
->resrec
.name
, rr
->resrec
.rrtype
);
3790 if (!ptr
) goto error
;
3793 else if (rr
->resrec
.RecordType
!= kDNSRecordTypeShared
)
3795 ptr
= putPrereqNameNotInUse(rr
->resrec
.name
, &msg
, ptr
, end
);
3796 if (!ptr
) goto error
;
3799 ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
);
3800 if (!ptr
) goto error
;
3802 if (rr
->uDNS_info
.lease
)
3803 { ptr
= putUpdateLease(&msg
, ptr
, DEFAULT_UPDATE_LEASE
); if (!ptr
) goto error
; }
3805 err
= mDNSSendDNSMessage(m
, &msg
, ptr
, mDNSInterface_Any
, ®Info
->ns
, regInfo
->port
, -1, GetAuthInfoForZone(u
, ®Info
->zone
));
3806 if (err
) LogMsg("ERROR: sendRecordRegistration - mDNSSendDNSMessage - %ld", err
);
3808 SetRecordRetry(m
, rr
);
3810 if (regInfo
->state
!= regState_Refresh
&& regInfo
->state
!= regState_DeregDeferred
) regInfo
->state
= regState_Pending
;
3814 LogMsg("sendRecordRegistration: Error formatting message");
3815 if (rr
->uDNS_info
.state
!= regState_Unregistered
)
3817 unlinkAR(&u
->RecordRegistrations
, rr
);
3818 rr
->uDNS_info
.state
= regState_Unregistered
;
3820 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
3821 if (rr
->RecordCallback
) rr
->RecordCallback(m
, rr
, err
);
3822 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
3823 // NOTE: not safe to touch any client structures here
3826 mDNSlocal
void RecordRegistrationCallback(mStatus err
, mDNS
*const m
, void *authPtr
, const AsyncOpResult
*result
)
3828 AuthRecord
*newRR
= (AuthRecord
*)authPtr
;
3829 const zoneData_t
*zoneData
= mDNSNULL
;
3830 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
3833 // make sure record is still in list
3834 for (ptr
= u
->RecordRegistrations
; ptr
; ptr
= ptr
->next
)
3835 if (ptr
== newRR
) break;
3836 if (!ptr
) { LogMsg("RecordRegistrationCallback - RR no longer in list. Discarding."); return; }
3838 // check error/result
3839 if (err
) { LogMsg("RecordRegistrationCallback: error %ld", err
); goto error
; }
3840 if (!result
) { LogMsg("ERROR: RecordRegistrationCallback invoked with NULL result and no error"); goto error
; }
3841 else zoneData
= &result
->zoneData
;
3843 if (newRR
->uDNS_info
.state
== regState_Cancelled
)
3845 //!!!KRS we should send a memfree callback here!
3846 debugf("Registration of %##s type %d cancelled prior to update",
3847 newRR
->resrec
.name
->c
, newRR
->resrec
.rrtype
);
3848 newRR
->uDNS_info
.state
= regState_Unregistered
;
3849 unlinkAR(&u
->RecordRegistrations
, newRR
);
3853 if (result
->type
!= zoneDataResult
)
3855 LogMsg("ERROR: buildUpdatePacket passed incorrect result type %d", result
->type
);
3859 if (newRR
->resrec
.rrclass
!= zoneData
->zoneClass
)
3861 LogMsg("ERROR: New resource record's class (%d) does not match zone class (%d)",
3862 newRR
->resrec
.rrclass
, zoneData
->zoneClass
);
3867 AssignDomainName(&newRR
->uDNS_info
.zone
, &zoneData
->zoneName
);
3868 newRR
->uDNS_info
.ns
.type
= mDNSAddrType_IPv4
;
3869 newRR
->uDNS_info
.ns
.ip
.v4
.NotAnInteger
= zoneData
->primaryAddr
.ip
.v4
.NotAnInteger
;
3870 if (zoneData
->updatePort
.NotAnInteger
) newRR
->uDNS_info
.port
= zoneData
->updatePort
;
3873 debugf("Update port not advertised via SRV - guessing port 53, no lease option");
3874 newRR
->uDNS_info
.port
= UnicastDNSPort
;
3875 newRR
->uDNS_info
.lease
= mDNSfalse
;
3878 sendRecordRegistration(m
, newRR
);
3882 if (newRR
->uDNS_info
.state
!= regState_Unregistered
)
3884 unlinkAR(&u
->RecordRegistrations
, newRR
);
3885 newRR
->uDNS_info
.state
= regState_Unregistered
;
3887 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
3888 if (newRR
->RecordCallback
)
3889 newRR
->RecordCallback(m
, newRR
, err
);
3890 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
3891 // NOTE: not safe to touch any client structures here
3894 mDNSlocal
void SendServiceRegistration(mDNS
*m
, ServiceRecordSet
*srs
)
3897 mDNSu8
*ptr
= msg
.data
;
3898 mDNSu8
*end
= (mDNSu8
*)&msg
+ sizeof(DNSMessage
);
3899 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
3901 uDNS_RegInfo
*rInfo
= &srs
->uDNS_info
;
3902 mStatus err
= mStatus_UnknownErr
;
3903 mDNSIPPort privport
;
3904 NATTraversalInfo
*nat
= srs
->uDNS_info
.NATinfo
;
3905 mDNSBool mapped
= mDNSfalse
;
3907 AuthRecord
*srv
= &srs
->RR_SRV
;
3910 if (!rInfo
->ns
.ip
.v4
.NotAnInteger
) { LogMsg("SendServiceRegistration - NS not set!"); return; }
3912 id
= newMessageID(u
);
3913 InitializeDNSMessage(&msg
.h
, id
, UpdateReqFlags
);
3915 // setup resource records
3916 SetNewRData(&srs
->RR_PTR
.resrec
, mDNSNULL
, 0);
3917 SetNewRData(&srs
->RR_TXT
.resrec
, mDNSNULL
, 0);
3919 // replace port w/ NAT mapping if necessary
3920 if (nat
&& nat
->PublicPort
.NotAnInteger
&&
3921 (nat
->state
== NATState_Established
|| nat
->state
== NATState_Refresh
|| nat
->state
== NATState_Legacy
))
3923 privport
= srv
->resrec
.rdata
->u
.srv
.port
;
3924 srv
->resrec
.rdata
->u
.srv
.port
= nat
->PublicPort
;
3928 // construct update packet
3930 ptr
= putZone(&msg
, ptr
, end
, &rInfo
->zone
, mDNSOpaque16fromIntVal(srv
->resrec
.rrclass
));
3931 if (!ptr
) goto error
;
3933 if (srs
->uDNS_info
.TestForSelfConflict
)
3935 // update w/ prereq that SRV already exist to make sure previous registration was ours, and delete any stale TXT records
3936 if (!(ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numPrereqs
, &srs
->RR_SRV
.resrec
, 0))) goto error
;
3937 if (!(ptr
= putDeleteRRSet(&msg
, ptr
, srs
->RR_TXT
.resrec
.name
, srs
->RR_TXT
.resrec
.rrtype
))) goto error
;
3940 else if (srs
->uDNS_info
.state
!= regState_Refresh
&& srs
->uDNS_info
.state
!= regState_UpdatePending
)
3942 // use SRV name for prereq
3943 ptr
= putPrereqNameNotInUse(srv
->resrec
.name
, &msg
, ptr
, end
);
3944 if (!ptr
) goto error
;
3947 //!!!KRS Need to do bounds checking and use TCP if it won't fit!!!
3948 if (!(ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numUpdates
, &srs
->RR_PTR
.resrec
, srs
->RR_PTR
.resrec
.rroriginalttl
))) goto error
;
3950 for (i
= 0; i
< srs
->NumSubTypes
; i
++)
3951 if (!(ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numUpdates
, &srs
->SubTypes
[i
].resrec
, srs
->SubTypes
[i
].resrec
.rroriginalttl
))) goto error
;
3953 if (rInfo
->state
== regState_UpdatePending
)
3955 // we're updating the txt record - delete old, add new
3956 if (!(ptr
= putDeletionRecord(&msg
, ptr
, &srs
->RR_TXT
.resrec
))) goto error
; // delete old rdata
3957 SwapRData(m
, &srs
->RR_TXT
, mDNSfalse
); // add the new rdata
3958 if (!(ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numUpdates
, &srs
->RR_TXT
.resrec
, srs
->RR_TXT
.resrec
.rroriginalttl
))) goto error
;
3959 SwapRData(m
, &srs
->RR_TXT
, mDNSfalse
); // replace old rdata in case we need to retransmit
3962 if (!(ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numUpdates
, &srs
->RR_TXT
.resrec
, srs
->RR_TXT
.resrec
.rroriginalttl
))) goto error
;
3964 if (!GetServiceTarget(u
, srv
, &target
))
3966 debugf("Couldn't get target for service %##s", srv
->resrec
.name
->c
);
3967 rInfo
->state
= regState_NoTarget
;
3971 if (!SameDomainName(&target
, &srv
->resrec
.rdata
->u
.srv
.target
))
3973 AssignDomainName(&srv
->resrec
.rdata
->u
.srv
.target
, &target
);
3974 SetNewRData(&srv
->resrec
, mDNSNULL
, 0);
3977 ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numUpdates
, &srv
->resrec
, srv
->resrec
.rroriginalttl
);
3978 if (!ptr
) goto error
;
3980 if (srs
->uDNS_info
.lease
)
3981 { ptr
= putUpdateLease(&msg
, ptr
, DEFAULT_UPDATE_LEASE
); if (!ptr
) goto error
; }
3983 err
= mDNSSendDNSMessage(m
, &msg
, ptr
, mDNSInterface_Any
, &rInfo
->ns
, rInfo
->port
, -1, GetAuthInfoForZone(u
, &rInfo
->zone
));
3984 if (err
) { LogMsg("ERROR: SendServiceRegistration - mDNSSendDNSMessage - %ld", err
); goto error
; }
3986 if (rInfo
->state
!= regState_Refresh
&& rInfo
->state
!= regState_DeregDeferred
&& srs
->uDNS_info
.state
!= regState_UpdatePending
)
3987 rInfo
->state
= regState_Pending
;
3989 SetRecordRetry(m
, &srs
->RR_SRV
);
3990 rInfo
->id
.NotAnInteger
= id
.NotAnInteger
;
3991 if (mapped
) srv
->resrec
.rdata
->u
.srv
.port
= privport
;
3995 LogMsg("SendServiceRegistration - Error formatting message");
3996 if (mapped
) srv
->resrec
.rdata
->u
.srv
.port
= privport
;
3998 rInfo
->state
= regState_Unregistered
;
3999 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4000 srs
->ServiceCallback(m
, srs
, err
);
4001 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4002 //!!!KRS will mem still be free'd on error?
4003 // NOTE: not safe to touch any client structures here
4006 mDNSlocal
void serviceRegistrationCallback(mStatus err
, mDNS
*const m
, void *srsPtr
, const AsyncOpResult
*result
)
4008 ServiceRecordSet
*srs
= (ServiceRecordSet
*)srsPtr
;
4009 const zoneData_t
*zoneData
= mDNSNULL
;
4011 if (err
) goto error
;
4012 if (!result
) { LogMsg("ERROR: serviceRegistrationCallback invoked with NULL result and no error"); goto error
; }
4013 else zoneData
= &result
->zoneData
;
4015 if (result
->type
!= zoneDataResult
)
4017 LogMsg("ERROR: buildUpdatePacket passed incorrect result type %d", result
->type
);
4021 if (srs
->uDNS_info
.state
== regState_Cancelled
)
4023 // client cancelled registration while fetching zone data
4024 srs
->uDNS_info
.state
= regState_Unregistered
;
4026 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4027 srs
->ServiceCallback(m
, srs
, mStatus_MemFree
);
4028 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4032 if (srs
->RR_SRV
.resrec
.rrclass
!= zoneData
->zoneClass
)
4034 LogMsg("Service %##s - class does not match zone", srs
->RR_SRV
.resrec
.name
->c
);
4039 AssignDomainName(&srs
->uDNS_info
.zone
, &zoneData
->zoneName
);
4040 srs
->uDNS_info
.ns
.type
= mDNSAddrType_IPv4
;
4041 srs
->uDNS_info
.ns
= zoneData
->primaryAddr
;
4042 if (zoneData
->updatePort
.NotAnInteger
) srs
->uDNS_info
.port
= zoneData
->updatePort
;
4045 debugf("Update port not advertised via SRV - guessing port 53, no lease option");
4046 srs
->uDNS_info
.port
= UnicastDNSPort
;
4047 srs
->uDNS_info
.lease
= mDNSfalse
;
4050 if (srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
.NotAnInteger
&& IsPrivateV4Addr(&m
->uDNS_info
.PrimaryIP
))
4051 { srs
->uDNS_info
.state
= regState_NATMap
; StartNATPortMap(m
, srs
); }
4052 else SendServiceRegistration(m
, srs
);
4057 srs
->uDNS_info
.state
= regState_Unregistered
;
4058 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4059 srs
->ServiceCallback(m
, srs
, err
);
4060 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4061 // NOTE: not safe to touch any client structures here
4064 mDNSlocal mStatus
SetupRecordRegistration(mDNS
*m
, AuthRecord
*rr
)
4066 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
4067 AuthRecord
*ptr
= m
->uDNS_info
.RecordRegistrations
;
4069 while (ptr
&& ptr
!= rr
) ptr
= ptr
->next
;
4070 if (ptr
) { LogMsg("Error: SetupRecordRegistration - record %##s already in list!", rr
->resrec
.name
->c
); return mStatus_AlreadyRegistered
; }
4072 if (rr
->uDNS_info
.state
== regState_FetchingZoneData
||
4073 rr
->uDNS_info
.state
== regState_Pending
||
4074 rr
->uDNS_info
.state
== regState_Registered
)
4076 LogMsg("Requested double-registration of physical record %##s type %d",
4077 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
4078 return mStatus_AlreadyRegistered
;
4081 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
4082 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
4084 if (!ValidateDomainName(rr
->resrec
.name
))
4086 LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m
, rr
));
4087 return mStatus_Invalid
;
4090 // Don't do this until *after* we've set rr->resrec.rdlength
4091 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
4093 LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m
, rr
));
4094 return mStatus_Invalid
;
4097 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
4098 rr
->resrec
.rdatahash
= RDataHashValue(rr
->resrec
.rdlength
, &rr
->resrec
.rdata
->u
);
4099 rr
->resrec
.rdnamehash
= target
? DomainNameHashValue(target
) : 0;
4101 rr
->uDNS_info
.state
= regState_FetchingZoneData
;
4102 rr
->next
= m
->uDNS_info
.RecordRegistrations
;
4103 m
->uDNS_info
.RecordRegistrations
= rr
;
4104 rr
->uDNS_info
.lease
= mDNStrue
;
4106 return mStatus_NoError
;
4109 mDNSexport mStatus
uDNS_RegisterRecord(mDNS
*const m
, AuthRecord
*const rr
)
4111 mStatus err
= SetupRecordRegistration(m
, rr
);
4112 if (err
) return err
;
4113 else return startGetZoneData(rr
->resrec
.name
, m
, mDNStrue
, mDNSfalse
, RecordRegistrationCallback
, rr
);
4116 mDNSlocal
void SendRecordDeregistration(mDNS
*m
, AuthRecord
*rr
)
4118 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4120 mDNSu8
*ptr
= msg
.data
;
4121 mDNSu8
*end
= (mDNSu8
*)&msg
+ sizeof(DNSMessage
);
4124 InitializeDNSMessage(&msg
.h
, rr
->uDNS_info
.id
, UpdateReqFlags
);
4126 ptr
= putZone(&msg
, ptr
, end
, &rr
->uDNS_info
.zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
4127 if (!ptr
) goto error
;
4128 if (!(ptr
= putDeletionRecord(&msg
, ptr
, &rr
->resrec
))) goto error
;
4130 err
= mDNSSendDNSMessage(m
, &msg
, ptr
, mDNSInterface_Any
, &rr
->uDNS_info
.ns
, rr
->uDNS_info
.port
, -1, GetAuthInfoForZone(u
, &rr
->uDNS_info
.zone
));
4131 if (err
) LogMsg("ERROR: SendRecordDeregistration - mDNSSendDNSMessage - %ld", err
);
4133 SetRecordRetry(m
, rr
);
4134 rr
->uDNS_info
.state
= regState_DeregPending
;
4138 LogMsg("Error: SendRecordDeregistration - could not contruct deregistration packet");
4139 unlinkAR(&u
->RecordRegistrations
, rr
);
4140 rr
->uDNS_info
.state
= regState_Unregistered
;
4145 mDNSexport mStatus
uDNS_DeregisterRecord(mDNS
*const m
, AuthRecord
*const rr
)
4147 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4148 NATTraversalInfo
*n
= rr
->uDNS_info
.NATinfo
;
4150 switch (rr
->uDNS_info
.state
)
4152 case regState_NATMap
:
4153 // we're in the middle of a NAT traversal operation
4154 if (!n
) LogMsg("uDNS_DeregisterRecord: no NAT info context");
4155 else FreeNATInfo(m
, n
); // cause response to outstanding request to be ignored.
4156 // Note: normally here we're trying to determine our public address,
4157 //in which case there is not state to be torn down. For simplicity,
4158 //we allow other operations to expire.
4159 rr
->uDNS_info
.NATinfo
= mDNSNULL
;
4160 rr
->uDNS_info
.state
= regState_Unregistered
;
4162 case regState_ExtraQueued
:
4163 rr
->uDNS_info
.state
= regState_Unregistered
;
4165 case regState_FetchingZoneData
:
4166 rr
->uDNS_info
.state
= regState_Cancelled
;
4167 return mStatus_NoError
;
4168 case regState_Refresh
:
4169 case regState_Pending
:
4170 case regState_UpdatePending
:
4171 rr
->uDNS_info
.state
= regState_DeregDeferred
;
4172 LogMsg("Deferring deregistration of record %##s until registration completes", rr
->resrec
.name
->c
);
4173 return mStatus_NoError
;
4174 case regState_Registered
:
4175 case regState_DeregPending
:
4177 case regState_DeregDeferred
:
4178 case regState_Cancelled
:
4179 LogMsg("Double deregistration of record %##s type %d",
4180 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
4181 return mStatus_UnknownErr
;
4182 case regState_Unregistered
:
4183 LogMsg("Requested deregistration of unregistered record %##s type %d",
4184 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
4185 return mStatus_UnknownErr
;
4186 case regState_NATError
:
4187 case regState_NoTarget
:
4188 LogMsg("ERROR: uDNS_DeregisterRecord called for record %##s with bad state %s", rr
->resrec
.name
->c
, rr
->uDNS_info
.state
== regState_NoTarget
? "regState_NoTarget" : "regState_NATError");
4189 return mStatus_UnknownErr
;
4192 if (rr
->uDNS_info
.state
== regState_Unregistered
)
4194 // unlink and deliver memfree
4196 unlinkAR(&u
->RecordRegistrations
, rr
);
4197 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4198 if (rr
->RecordCallback
) rr
->RecordCallback(m
, rr
, mStatus_MemFree
);
4199 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4200 return mStatus_NoError
;
4203 if (n
) FreeNATInfo(m
, n
);
4204 rr
->uDNS_info
.NATinfo
= mDNSNULL
;
4206 SendRecordDeregistration(m
, rr
);
4207 return mStatus_NoError
;
4210 mDNSexport mStatus
uDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*srs
)
4214 uDNS_RegInfo
*info
= &srs
->uDNS_info
;
4215 ServiceRecordSet
**p
= &m
->uDNS_info
.ServiceRegistrations
;
4216 while (*p
&& *p
!= srs
) p
=&(*p
)->next
;
4217 if (*p
) { LogMsg("uDNS_RegisterService: %p %##s already in list", srs
, srs
->RR_SRV
.resrec
.name
->c
); return(mStatus_AlreadyRegistered
); }
4218 ubzero(info
, sizeof(*info
));
4220 srs
->next
= mDNSNULL
;
4222 srs
->RR_SRV
.resrec
.rroriginalttl
= kWideAreaTTL
;
4223 srs
->RR_TXT
.resrec
.rroriginalttl
= kWideAreaTTL
;
4224 srs
->RR_PTR
.resrec
.rroriginalttl
= kWideAreaTTL
;
4225 for (i
= 0; i
< srs
->NumSubTypes
;i
++) srs
->SubTypes
[i
].resrec
.rroriginalttl
= kWideAreaTTL
;
4227 info
->lease
= mDNStrue
;
4229 srs
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = 0;
4230 if (!GetServiceTarget(&m
->uDNS_info
, &srs
->RR_SRV
, &target
))
4232 // defer registration until we've got a target
4233 LogMsg("uDNS_RegisterService - no target for %##s", srs
->RR_SRV
.resrec
.name
->c
);
4234 info
->state
= regState_NoTarget
;
4235 return mStatus_NoError
;
4238 info
->state
= regState_FetchingZoneData
;
4239 return startGetZoneData(srs
->RR_SRV
.resrec
.name
, m
, mDNStrue
, mDNSfalse
, serviceRegistrationCallback
, srs
);
4242 mDNSlocal
void SendServiceDeregistration(mDNS
*m
, ServiceRecordSet
*srs
)
4244 uDNS_RegInfo
*info
= &srs
->uDNS_info
;
4245 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4248 mDNSu8
*ptr
= msg
.data
;
4249 mDNSu8
*end
= (mDNSu8
*)&msg
+ sizeof(DNSMessage
);
4250 mStatus err
= mStatus_UnknownErr
;
4253 id
= newMessageID(u
);
4254 InitializeDNSMessage(&msg
.h
, id
, UpdateReqFlags
);
4257 ptr
= putZone(&msg
, ptr
, end
, &info
->zone
, mDNSOpaque16fromIntVal(srs
->RR_SRV
.resrec
.rrclass
));
4258 if (!ptr
) { LogMsg("ERROR: SendServiceDeregistration - putZone"); goto error
; }
4260 if (!(ptr
= putDeleteAllRRSets(&msg
, ptr
, srs
->RR_SRV
.resrec
.name
))) goto error
; // this deletes SRV, TXT, and Extras
4261 if (!(ptr
= putDeletionRecord(&msg
, ptr
, &srs
->RR_PTR
.resrec
))) goto error
;
4262 for (i
= 0; i
< srs
->NumSubTypes
; i
++)
4263 if (!(ptr
= putDeletionRecord(&msg
, ptr
, &srs
->SubTypes
[i
].resrec
))) goto error
;
4266 err
= mDNSSendDNSMessage(m
, &msg
, ptr
, mDNSInterface_Any
, &info
->ns
, info
->port
, -1, GetAuthInfoForZone(u
, &info
->zone
));
4267 if (err
) { LogMsg("ERROR: SendServiceDeregistration - mDNSSendDNSMessage - %ld", err
); goto error
; }
4269 SetRecordRetry(m
, &srs
->RR_SRV
);
4270 info
->id
.NotAnInteger
= id
.NotAnInteger
;
4271 info
->state
= regState_DeregPending
;
4277 info
->state
= regState_Unregistered
;
4280 mDNSexport mStatus
uDNS_DeregisterService(mDNS
*const m
, ServiceRecordSet
*srs
)
4282 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4283 NATTraversalInfo
*nat
= srs
->uDNS_info
.NATinfo
;
4284 AuthRecord
**r
= &u
->RecordRegistrations
;
4285 char *errmsg
= "Unknown State";
4287 // We "silently" unlink any Extras from our RecordRegistration list, as they are implicitly deleted from
4288 // the server when we delete all RRSets for this name
4291 if (SameDomainName(srs
->RR_SRV
.resrec
.name
, (*r
)->resrec
.name
)) *r
= (*r
)->next
;
4292 else r
= &(*r
)->next
;
4295 // don't re-register with a new target following deregistration
4296 srs
->uDNS_info
.SRVChanged
= srs
->uDNS_info
.SRVUpdateDeferred
= mDNSfalse
;
4300 if (nat
->state
== NATState_Established
|| nat
->state
== NATState_Refresh
|| nat
->state
== NATState_Legacy
)
4301 DeleteNATPortMapping(m
, nat
, srs
);
4302 nat
->reg
.ServiceRegistration
= mDNSNULL
;
4303 srs
->uDNS_info
.NATinfo
= mDNSNULL
;
4304 FreeNATInfo(m
, nat
);
4307 switch (srs
->uDNS_info
.state
)
4309 case regState_Unregistered
:
4310 debugf("uDNS_DeregisterService - service %##s not registered", srs
->RR_SRV
.resrec
.name
->c
);
4311 return mStatus_BadReferenceErr
;
4312 case regState_FetchingZoneData
:
4313 // let the async op complete, then terminate
4314 srs
->uDNS_info
.state
= regState_Cancelled
;
4315 return mStatus_NoError
; // deliver memfree upon completion of async op
4316 case regState_Pending
:
4317 case regState_Refresh
:
4318 case regState_UpdatePending
:
4319 // deregister following completion of in-flight operation
4320 srs
->uDNS_info
.state
= regState_DeregDeferred
;
4321 return mStatus_NoError
;
4322 case regState_DeregPending
:
4323 case regState_DeregDeferred
:
4324 case regState_Cancelled
:
4325 debugf("Double deregistration of service %##s", srs
->RR_SRV
.resrec
.name
->c
);
4326 return mStatus_NoError
;
4327 case regState_NATError
: // not registered
4328 case regState_NATMap
: // not registered
4329 case regState_NoTarget
: // not registered
4331 srs
->uDNS_info
.state
= regState_Unregistered
;
4332 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4333 srs
->ServiceCallback(m
, srs
, mStatus_MemFree
);
4334 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4335 return mStatus_NoError
;
4336 case regState_Registered
:
4337 srs
->uDNS_info
.state
= regState_DeregPending
;
4338 SendServiceDeregistration(m
, srs
);
4339 return mStatus_NoError
;
4340 case regState_ExtraQueued
: // only for record registrations
4341 errmsg
= "bad state (regState_ExtraQueued)";
4346 LogMsg("Error, uDNS_DeregisterService: %s", errmsg
);
4347 return mStatus_BadReferenceErr
;
4350 mDNSlocal
void SendRecordUpdate(mDNS
*m
, AuthRecord
*rr
, uDNS_RegInfo
*info
)
4353 mDNSu8
*ptr
= msg
.data
;
4354 mDNSu8
*end
= (mDNSu8
*)&msg
+ sizeof(DNSMessage
);
4355 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4357 mStatus err
= mStatus_UnknownErr
;
4359 if (info
!= &rr
->uDNS_info
) LogMsg("ERROR: SendRecordUpdate - incorrect info struct!");
4360 rr
->uDNS_info
.UpdateQueued
= mDNSfalse
; // if this was queued, clear flag
4361 id
= newMessageID(u
);
4362 InitializeDNSMessage(&msg
.h
, id
, UpdateReqFlags
);
4363 info
->id
.NotAnInteger
= id
.NotAnInteger
;
4366 ptr
= putZone(&msg
, ptr
, end
, &info
->zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
4367 if (!ptr
) goto error
;
4369 // delete the original record
4370 ptr
= putDeletionRecord(&msg
, ptr
, &rr
->resrec
);
4371 if (!ptr
) goto error
;
4373 // change the rdata, add the new record
4374 SwapRData(m
, rr
, mDNSfalse
);
4375 ptr
= PutResourceRecordTTLJumbo(&msg
, ptr
, &msg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
);
4376 SwapRData(m
, rr
, mDNSfalse
); // swap rdata back to original in case we need to retransmit
4377 if (!ptr
) goto error
; // (rdata gets changed permanently on success)
4380 { ptr
= putUpdateLease(&msg
, ptr
, DEFAULT_UPDATE_LEASE
); if (!ptr
) goto error
; }
4382 // don't report send errors - retransmission will occurr if necessary
4383 err
= mDNSSendDNSMessage(m
, &msg
, ptr
, mDNSInterface_Any
, &info
->ns
, info
->port
, -1, GetAuthInfoForZone(u
, &info
->zone
));
4384 if (err
) debugf("ERROR: sendRecordRegistration - mDNSSendDNSMessage - %ld", err
);
4386 //!!! Update this when we implement retransmission for services
4387 SetRecordRetry(m
, rr
);
4389 rr
->uDNS_info
.state
= regState_UpdatePending
;
4390 if (&rr
->uDNS_info
!= info
) info
->state
= regState_UpdatePending
; // set parent SRS
4394 LogMsg("ERROR: SendRecordUpdate. Error formatting update message.");
4395 info
->state
= regState_Registered
;
4398 mDNSexport mStatus
uDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
)
4400 mStatus err
= mStatus_UnknownErr
;
4402 extra
->r
.resrec
.RecordType
= kDNSRecordTypeShared
; // don't want it to conflict with the service name
4403 extra
->r
.RecordCallback
= mDNSNULL
; // don't generate callbacks for extra RRs
4405 if (sr
->uDNS_info
.state
== regState_Registered
|| sr
->uDNS_info
.state
== regState_Refresh
)
4406 err
= uDNS_RegisterRecord(m
, &extra
->r
);
4409 err
= SetupRecordRegistration(m
, &extra
->r
);
4410 extra
->r
.uDNS_info
.state
= regState_ExtraQueued
;
4415 extra
->next
= sr
->Extras
;
4421 mDNSexport mStatus
uDNS_UpdateRecord(mDNS
*m
, AuthRecord
*rr
)
4423 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4424 ServiceRecordSet
*sptr
, *parent
= mDNSNULL
;
4426 uDNS_RegInfo
*info
= mDNSNULL
;
4428 // find the record in registered service list
4429 for (sptr
= u
->ServiceRegistrations
; sptr
; sptr
= sptr
->next
)
4430 if (&sptr
->RR_TXT
== rr
) { info
= &sptr
->uDNS_info
; parent
= sptr
; break; }
4434 // record not part of a service - check individual record registrations
4435 for (rptr
= u
->RecordRegistrations
; rptr
; rptr
= rptr
->next
)
4436 if (rptr
== rr
) { info
= &rr
->uDNS_info
; break; }
4439 if (!info
) goto unreg_error
;
4441 // uDNS-private pointers so that mDNS.c layer doesn't nuke rdata of an in-flight update
4442 rr
->uDNS_info
.UpdateRData
= rr
->NewRData
;
4443 rr
->uDNS_info
.UpdateRDLen
= rr
->newrdlength
;
4444 rr
->uDNS_info
.UpdateRDCallback
= rr
->UpdateCallback
;
4445 rr
->NewRData
= mDNSNULL
;
4449 case regState_DeregPending
:
4450 case regState_DeregDeferred
:
4451 case regState_Cancelled
:
4452 case regState_Unregistered
:
4453 // not actively registered
4456 case regState_FetchingZoneData
:
4457 case regState_NATMap
:
4458 case regState_ExtraQueued
:
4459 // change rdata directly since it hasn't been sent yet
4460 SwapRData(m
, rr
, mDNStrue
);
4461 return mStatus_NoError
;
4463 case regState_Pending
:
4464 case regState_Refresh
:
4465 case regState_UpdatePending
:
4466 // registration in-flight. mark for update after service registration completes
4467 rr
->uDNS_info
.UpdateQueued
= mDNStrue
; // note that we mark the record's Queued flag, not its parent's
4468 return mStatus_NoError
;
4470 case regState_Registered
:
4471 if (parent
) { info
->state
= regState_UpdatePending
; SendServiceRegistration(m
, parent
); }
4472 else SendRecordUpdate(m
, rr
, info
);
4473 return mStatus_NoError
;
4475 case regState_NATError
:
4476 case regState_NoTarget
:
4477 LogMsg("ERROR: uDNS_UpdateRecord called for record %##s with bad state %s", rr
->resrec
.name
->c
, rr
->uDNS_info
.state
== regState_NoTarget
? "regState_NoTarget" : "regState_NATError");
4478 return mStatus_UnknownErr
; // states for service records only
4482 LogMsg("Requested update of record %##s type %d, part of service not currently registered",
4483 rr
->resrec
.name
->c
, rr
->resrec
.rrtype
);
4484 return mStatus_Invalid
;
4488 // ***************************************************************************
4489 #if COMPILER_LIKES_PRAGMA_MARK
4490 #pragma mark - Periodic Execution Routines
4494 mDNSlocal mDNSs32
CheckNATMappings(mDNS
*m
, mDNSs32 timenow
)
4496 NATTraversalInfo
*ptr
, *cur
;
4499 ptr
= m
->uDNS_info
.NATTraversals
;
4500 nextevent
= timenow
+ MIN_UCAST_PERIODIC_EXEC
;
4506 if (cur
->op
!= NATOp_AddrRequest
|| cur
->state
!= NATState_Established
) // no refresh necessary for established Add requests
4508 if (cur
->retry
- timenow
< 0)
4510 if (cur
->state
== NATState_Established
) RefreshNATMapping(cur
, m
);
4511 else if (cur
->state
== NATState_Request
|| cur
->state
== NATState_Refresh
)
4513 if (cur
->ntries
>= NATMAP_MAX_TRIES
) cur
->ReceiveResponse(cur
, m
, mDNSNULL
, 0); // may invalidate "cur"
4514 else SendNATMsg(cur
, m
);
4517 else if (cur
->retry
- nextevent
< 0) nextevent
= cur
->retry
;
4523 mDNSlocal mDNSs32
CheckQueries(mDNS
*m
, mDNSs32 timenow
)
4526 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4529 mDNSs32 nextevent
= timenow
+ MIN_UCAST_PERIODIC_EXEC
;
4533 uDNS_QuestionInfo
*info
;
4535 u
->CurrentQuery
= u
->ActiveQueries
;
4536 while (u
->CurrentQuery
)
4538 q
= u
->CurrentQuery
;
4539 info
= &q
->uDNS_info
;
4542 if (!info
->internal
&& ((!q
->LongLived
&& !info
->Answered
) || (llq
&& llq
->state
< LLQ_Established
)) &&
4543 info
->RestartTime
+ RESTART_GOODBYE_DELAY
- timenow
< 0)
4545 // if we've been spinning on restart setup, and we have known answers, give goodbyes (they may be re-added later)
4546 while (info
->knownAnswers
)
4548 CacheRecord
*cr
= info
->knownAnswers
;
4549 info
->knownAnswers
= info
->knownAnswers
->next
;
4551 m
->mDNS_reentrancy
++; // Increment to allow client to legally make mDNS API calls from the callback
4552 q
->QuestionCallback(m
, q
, &cr
->resrec
, mDNSfalse
);
4553 m
->mDNS_reentrancy
--; // Decrement to block mDNS API calls again
4555 if (q
!= u
->CurrentQuery
) { debugf("CheckQueries - question removed via callback."); break; }
4558 if (q
!= u
->CurrentQuery
) continue;
4560 if (q
->LongLived
&& llq
->state
!= LLQ_Poll
)
4562 if (llq
->state
>= LLQ_InitialRequest
&& llq
->state
<= LLQ_Established
)
4564 if (llq
->retry
- timenow
< 0)
4566 // sanity check to avoid packet flood bugs
4568 LogMsg("ERROR: retry timer not set for LLQ %##s in state %d", q
->qname
.c
, llq
->state
);
4569 else if (llq
->state
== LLQ_Established
|| llq
->state
== LLQ_Refresh
)
4570 sendLLQRefresh(m
, q
, llq
->origLease
);
4571 else if (llq
->state
== LLQ_InitialRequest
)
4572 startLLQHandshake(m
, llq
, mDNSfalse
);
4573 else if (llq
->state
== LLQ_SecondaryRequest
)
4574 sendChallengeResponse(m
, q
, mDNSNULL
);
4575 else if (llq
->state
== LLQ_Retry
)
4576 { llq
->ntries
= 0; startLLQHandshake(m
, llq
, mDNSfalse
); }
4578 else if (llq
->retry
- nextevent
< 0) nextevent
= llq
->retry
;
4583 sendtime
= q
->LastQTime
+ q
->ThisQInterval
;
4584 if (sendtime
- timenow
< 0)
4587 if (GetServerForName(&m
->uDNS_info
, &q
->qname
, &server
))
4589 err
= constructQueryMsg(&msg
, &end
, q
);
4590 if (err
) LogMsg("Error: uDNS_Idle - constructQueryMsg. Skipping question %##s", q
->qname
.c
);
4593 err
= mDNSSendDNSMessage(m
, &msg
, end
, mDNSInterface_Any
, &server
, UnicastDNSPort
, -1, mDNSNULL
);
4594 if (err
) { debugf("ERROR: uDNS_idle - mDNSSendDNSMessage - %ld", err
); } // surpress syslog messages if we have no network
4595 q
->LastQTime
= timenow
;
4596 if (q
->ThisQInterval
< MAX_UCAST_POLL_INTERVAL
) q
->ThisQInterval
= q
->ThisQInterval
* 2;
4600 else if (sendtime
- nextevent
< 0) nextevent
= sendtime
;
4602 u
->CurrentQuery
= u
->CurrentQuery
->next
;
4607 mDNSlocal mDNSs32
CheckRecordRegistrations(mDNS
*m
, mDNSs32 timenow
)
4610 uDNS_RegInfo
*rInfo
;
4611 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4612 mDNSs32 nextevent
= timenow
+ MIN_UCAST_PERIODIC_EXEC
;
4614 //!!!KRS list should be pre-sorted by expiration
4615 for (rr
= u
->RecordRegistrations
; rr
; rr
= rr
->next
)
4617 rInfo
= &rr
->uDNS_info
;
4618 if (rInfo
->state
== regState_Pending
|| rInfo
->state
== regState_DeregPending
|| rInfo
->state
== regState_UpdatePending
|| rInfo
->state
== regState_DeregDeferred
|| rInfo
->state
== regState_Refresh
)
4620 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- timenow
< 0)
4623 char *op
= "(unknown operation)";
4624 if (rInfo
->state
== regState_Pending
) op
= "registration";
4625 else if (rInfo
->state
== regState_DeregPending
) op
= "deregistration";
4626 else if (rInfo
->state
== regState_Refresh
) op
= "refresh";
4627 debugf("Retransmit record %s %##s", op
, rr
->resrec
.name
->c
);
4629 //LogMsg("Retransmit record %##s", rr->resrec.name->c);
4630 if (rInfo
->state
== regState_DeregPending
) SendRecordDeregistration(m
, rr
);
4631 else if (rInfo
->state
== regState_UpdatePending
) SendRecordUpdate(m
, rr
, rInfo
);
4632 else sendRecordRegistration(m
, rr
);
4634 if (rr
->LastAPTime
+ rr
->ThisAPInterval
- nextevent
< 0) nextevent
= rr
->LastAPTime
+ rr
->ThisAPInterval
;
4636 if (rInfo
->lease
&& rInfo
->state
== regState_Registered
)
4638 if (rInfo
->expire
- timenow
< 0)
4640 debugf("refreshing record %##s", rr
->resrec
.name
->c
);
4641 rInfo
->state
= regState_Refresh
;
4642 sendRecordRegistration(m
, rr
);
4644 if (rInfo
->expire
- nextevent
< 0) nextevent
= rInfo
->expire
;
4650 mDNSlocal mDNSs32
CheckServiceRegistrations(mDNS
*m
, mDNSs32 timenow
)
4652 ServiceRecordSet
*s
= m
->uDNS_info
.ServiceRegistrations
;
4653 uDNS_RegInfo
*rInfo
;
4654 mDNSs32 nextevent
= timenow
+ MIN_UCAST_PERIODIC_EXEC
;
4656 // Note: ServiceRegistrations list is in the order they were created; important for in-order event delivery
4659 ServiceRecordSet
*srs
= s
;
4660 // NOTE: Must advance s here -- SendServiceDeregistration may delete the object we're looking at,
4661 // and then if we tried to do srs = srs->next at the end we'd be referencing a dead object
4664 rInfo
= &srs
->uDNS_info
;
4665 if (rInfo
->state
== regState_Pending
|| rInfo
->state
== regState_DeregPending
|| rInfo
->state
== regState_DeregDeferred
|| rInfo
->state
== regState_Refresh
|| rInfo
->state
== regState_UpdatePending
)
4667 if (srs
->RR_SRV
.LastAPTime
+ srs
->RR_SRV
.ThisAPInterval
- timenow
< 0)
4670 char *op
= "unknown";
4671 if (rInfo
->state
== regState_Pending
) op
= "registration";
4672 else if (rInfo
->state
== regState_DeregPending
) op
= "deregistration";
4673 else if (rInfo
->state
== regState_Refresh
) op
= "refresh";
4674 else if (rInfo
->state
== regState_UpdatePending
) op
= "txt record update";
4675 debugf("Retransmit service %s %##s", op
, srs
->RR_SRV
.resrec
.name
->c
);
4677 if (rInfo
->state
== regState_DeregPending
) { SendServiceDeregistration(m
, srs
); continue; }
4678 else SendServiceRegistration (m
, srs
);
4680 if (nextevent
- srs
->RR_SRV
.LastAPTime
+ srs
->RR_SRV
.ThisAPInterval
> 0)
4681 nextevent
= srs
->RR_SRV
.LastAPTime
+ srs
->RR_SRV
.ThisAPInterval
;
4684 if (rInfo
->lease
&& rInfo
->state
== regState_Registered
)
4686 if (rInfo
->expire
- timenow
< 0)
4688 debugf("refreshing service %##s", srs
->RR_SRV
.resrec
.name
->c
);
4689 rInfo
->state
= regState_Refresh
;
4690 SendServiceRegistration(m
, srs
);
4692 if (rInfo
->expire
- nextevent
< 0) nextevent
= rInfo
->expire
;
4698 mDNSexport
void uDNS_Execute(mDNS
*const m
)
4700 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4701 mDNSs32 nexte
, timenow
= mDNSPlatformTimeNow(m
);
4703 u
->nextevent
= timenow
+ MIN_UCAST_PERIODIC_EXEC
;
4705 if (u
->DelaySRVUpdate
&& u
->NextSRVUpdate
- timenow
< 0)
4707 u
->DelaySRVUpdate
= mDNSfalse
;
4708 UpdateSRVRecords(m
);
4711 nexte
= CheckNATMappings(m
, timenow
);
4712 if (nexte
- u
->nextevent
< 0) u
->nextevent
= nexte
;
4714 nexte
= CheckQueries(m
, timenow
);
4715 if (nexte
- u
->nextevent
< 0) u
->nextevent
= nexte
;
4717 nexte
= CheckRecordRegistrations(m
, timenow
);
4718 if (nexte
- u
->nextevent
< 0) u
->nextevent
= nexte
;
4720 nexte
= CheckServiceRegistrations(m
, timenow
);
4721 if (nexte
- u
->nextevent
< 0) u
->nextevent
= nexte
;
4725 // ***************************************************************************
4726 #if COMPILER_LIKES_PRAGMA_MARK
4727 #pragma mark - Startup, Shutdown, and Sleep
4730 // DeregisterActive causes active LLQs to be removed from the server, e.g. before sleep. Pass false
4731 // following a location change, as the server will reject deletions from a source address different
4732 // from the address on which the LLQ was created.
4734 mDNSlocal
void SuspendLLQs(mDNS
*m
, mDNSBool DeregisterActive
)
4738 for (q
= m
->uDNS_info
.ActiveQueries
; q
; q
= q
->next
)
4740 llq
= q
->uDNS_info
.llq
;
4741 if (q
->LongLived
&& llq
)
4743 if (llq
->state
== LLQ_GetZoneInfo
)
4745 debugf("Marking %##s suspend-deferred", q
->qname
.c
);
4746 llq
->state
= LLQ_SuspendDeferred
; // suspend once we're done getting zone info
4748 else if (llq
->state
< LLQ_Suspended
)
4750 if (DeregisterActive
&& (llq
->state
== LLQ_Established
|| llq
->state
== LLQ_Refresh
))
4751 { debugf("Deleting LLQ %##s", q
->qname
.c
); sendLLQRefresh(m
, q
, 0); }
4752 debugf("Marking %##s suspended", q
->qname
.c
);
4753 llq
->state
= LLQ_Suspended
;
4756 else if (llq
->state
== LLQ_Poll
) { debugf("Marking %##s suspended-poll", q
->qname
.c
); llq
->state
= LLQ_SuspendedPoll
; }
4757 if (llq
->NATMap
) llq
->NATMap
= mDNSfalse
; // may not need nat mapping if we restart with new route
4760 CheckForUnreferencedLLQMapping(m
);
4763 mDNSlocal
void RestartQueries(mDNS
*m
)
4765 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4768 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
4770 u
->CurrentQuery
= u
->ActiveQueries
;
4771 while (u
->CurrentQuery
)
4773 q
= u
->CurrentQuery
;
4774 u
->CurrentQuery
= u
->CurrentQuery
->next
;
4775 llqInfo
= q
->uDNS_info
.llq
;
4776 q
->uDNS_info
.RestartTime
= timenow
;
4777 q
->uDNS_info
.Answered
= mDNSfalse
;
4780 if (!llqInfo
) { LogMsg("Error: RestartQueries - %##s long-lived with NULL info", q
->qname
.c
); continue; }
4781 if (llqInfo
->state
== LLQ_Suspended
|| llqInfo
->state
== LLQ_NatMapWait
)
4783 llqInfo
->ntries
= -1;
4784 llqInfo
->deriveRemovesOnResume
= mDNStrue
;
4785 startLLQHandshake(m
, llqInfo
, mDNStrue
); // we set defer to true since several events that may generate restarts often arrive in rapid succession, and this cuts unnecessary packets
4787 else if (llqInfo
->state
== LLQ_SuspendDeferred
)
4788 llqInfo
->state
= LLQ_GetZoneInfo
; // we never finished getting zone data - proceed as usual
4789 else if (llqInfo
->state
== LLQ_SuspendedPoll
)
4791 // if we were polling, we may have had bad zone data due to firewall, etc. - refetch
4792 llqInfo
->ntries
= 0;
4793 llqInfo
->deriveRemovesOnResume
= mDNStrue
;
4794 llqInfo
->state
= LLQ_GetZoneInfo
;
4795 startGetZoneData(&q
->qname
, m
, mDNSfalse
, mDNStrue
, startLLQHandshakeCallback
, llqInfo
);
4798 else { q
->LastQTime
= timenow
; q
->ThisQInterval
= INIT_UCAST_POLL_INTERVAL
; } // trigger poll in 1 second (to reduce packet rate when restarts come in rapid succession)
4802 mDNSexport
void mDNS_UpdateLLQs(mDNS
*m
)
4804 uDNS_GlobalInfo
*u
= &m
->uDNS_info
;
4809 NATTraversalInfo
*nat
= u
->LLQNatInfo
;
4810 u
->LLQNatInfo
= mDNSNULL
;
4811 DeleteNATPortMapping(m
, nat
, mDNSNULL
);
4813 SuspendLLQs(m
, mDNStrue
);
4818 // simplest sleep logic - rather than having sleep states that must be dealt with explicitly in all parts of
4819 // the code, we simply send a deregistration, and put the service in Refresh state, with a timeout far enough
4820 // in the future that we'll sleep (or the sleep will be cancelled) before it is retransmitted. Then to wake,
4821 // we just move up the timers.
4825 mDNSlocal
void SleepRecordRegistrations(mDNS
*m
)
4828 AuthRecord
*rr
= m
->uDNS_info
.RecordRegistrations
;
4829 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
4833 if (rr
->uDNS_info
.state
== regState_Registered
||
4834 rr
->uDNS_info
.state
== regState_Refresh
)
4836 mDNSu8
*ptr
= msg
.data
, *end
= (mDNSu8
*)&msg
+ sizeof(DNSMessage
);
4837 InitializeDNSMessage(&msg
.h
, newMessageID(&m
->uDNS_info
), UpdateReqFlags
);
4839 // construct deletion update
4840 ptr
= putZone(&msg
, ptr
, end
, &rr
->uDNS_info
.zone
, mDNSOpaque16fromIntVal(rr
->resrec
.rrclass
));
4841 if (!ptr
) { LogMsg("Error: SleepRecordRegistrations - could not put zone"); return; }
4842 ptr
= putDeletionRecord(&msg
, ptr
, &rr
->resrec
);
4843 if (!ptr
) { LogMsg("Error: SleepRecordRegistrations - could not put deletion record"); return; }
4845 mDNSSendDNSMessage(m
, &msg
, ptr
, mDNSInterface_Any
, &rr
->uDNS_info
.ns
, rr
->uDNS_info
.port
, -1, GetAuthInfoForZone(&m
->uDNS_info
, &rr
->uDNS_info
.zone
));
4846 rr
->uDNS_info
.state
= regState_Refresh
;
4847 rr
->LastAPTime
= timenow
;
4848 rr
->ThisAPInterval
= 300 * mDNSPlatformOneSecond
;
4854 mDNSlocal
void WakeRecordRegistrations(mDNS
*m
)
4856 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
4857 AuthRecord
*rr
= m
->uDNS_info
.RecordRegistrations
;
4861 if (rr
->uDNS_info
.state
== regState_Refresh
)
4863 // trigger slightly delayed refresh (we usually get this message before kernel is ready to send packets)
4864 rr
->LastAPTime
= timenow
;
4865 rr
->ThisAPInterval
= INIT_UCAST_POLL_INTERVAL
;
4871 mDNSlocal
void SleepServiceRegistrations(mDNS
*m
)
4873 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
4874 ServiceRecordSet
*srs
= m
->uDNS_info
.ServiceRegistrations
;
4877 if (srs
->uDNS_info
.state
== regState_Registered
||
4878 srs
->uDNS_info
.state
== regState_Refresh
)
4880 mDNSOpaque16 origid
= srs
->uDNS_info
.id
;
4881 srs
->uDNS_info
.state
= regState_DeregPending
; // state expected by SendDereg()
4882 SendServiceDeregistration(m
, srs
);
4883 srs
->uDNS_info
.id
= origid
;
4884 srs
->uDNS_info
.state
= regState_Refresh
;
4885 srs
->RR_SRV
.LastAPTime
= timenow
;
4886 srs
->RR_SRV
.ThisAPInterval
= 300 * mDNSPlatformOneSecond
;
4892 mDNSlocal
void WakeServiceRegistrations(mDNS
*m
)
4894 mDNSs32 timenow
= mDNSPlatformTimeNow(m
);
4895 ServiceRecordSet
*srs
= m
->uDNS_info
.ServiceRegistrations
;
4898 if (srs
->uDNS_info
.state
== regState_Refresh
)
4900 // trigger slightly delayed refresh (we usually get this message before kernel is ready to send packets)
4901 srs
->RR_SRV
.LastAPTime
= timenow
;
4902 srs
->RR_SRV
.ThisAPInterval
= INIT_UCAST_POLL_INTERVAL
;
4908 mDNSexport
void uDNS_Init(mDNS
*const m
)
4910 mDNSPlatformMemZero(&m
->uDNS_info
, sizeof(uDNS_GlobalInfo
));
4911 m
->uDNS_info
.nextevent
= m
->timenow_last
+ 0x78000000;
4914 mDNSexport
void uDNS_Sleep(mDNS
*m
)
4916 SuspendLLQs(m
, mDNStrue
);
4917 SleepServiceRegistrations(m
);
4918 SleepRecordRegistrations(m
);
4921 mDNSexport
void uDNS_Wake(mDNS
*m
)
4924 WakeServiceRegistrations(m
);
4925 WakeRecordRegistrations(m
);