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