1 /* 2 * Copyright (c) 2017, The OpenThread Authors. 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 1. Redistributions of source code must retain the above copyright 8 * notice, this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright 10 * notice, this list of conditions and the following disclaimer in the 11 * documentation and/or other materials provided with the distribution. 12 * 3. Neither the name of the copyright holder nor the 13 * names of its contributors may be used to endorse or promote products 14 * derived from this software without specific prior written permission. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 * POSSIBILITY OF SUCH DAMAGE. 27 */ 28 29 /** 30 * @file 31 * This file includes definitions for generating and processing DNS headers. 32 */ 33 34 #ifndef DNS_HEADER_HPP_ 35 #define DNS_HEADER_HPP_ 36 37 #include "openthread-core-config.h" 38 39 #include <openthread/dns.h> 40 #include <openthread/dns_client.h> 41 42 #include "common/appender.hpp" 43 #include "common/as_core_type.hpp" 44 #include "common/clearable.hpp" 45 #include "common/encoding.hpp" 46 #include "common/equatable.hpp" 47 #include "common/message.hpp" 48 #include "crypto/ecdsa.hpp" 49 #include "net/ip4_types.hpp" 50 #include "net/ip6_address.hpp" 51 52 namespace ot { 53 54 /** 55 * @namespace ot::Dns 56 * @brief 57 * This namespace includes definitions for DNS. 58 * 59 */ 60 namespace Dns { 61 62 using ot::Encoding::BigEndian::HostSwap16; 63 using ot::Encoding::BigEndian::HostSwap32; 64 65 /** 66 * @addtogroup core-dns 67 * 68 * @brief 69 * This module includes definitions for DNS. 70 * 71 * @{ 72 * 73 */ 74 75 /** 76 * This class implements DNS header generation and parsing. 77 * 78 */ 79 OT_TOOL_PACKED_BEGIN 80 class Header : public Clearable<Header> 81 { 82 public: 83 /** 84 * Default constructor for DNS Header. 85 * 86 */ Header(void)87 Header(void) { Clear(); } 88 89 /** 90 * This method returns the Message ID. 91 * 92 * @returns The Message ID value. 93 * 94 */ GetMessageId(void) const95 uint16_t GetMessageId(void) const { return HostSwap16(mMessageId); } 96 97 /** 98 * This method sets the Message ID. 99 * 100 * @param[in] aMessageId The Message ID value. 101 * 102 */ SetMessageId(uint16_t aMessageId)103 void SetMessageId(uint16_t aMessageId) { mMessageId = HostSwap16(aMessageId); } 104 105 /** 106 * This method sets the Message ID to a crypto-secure randomly generated number. 107 * 108 * @retval kErrorNone Successfully generated random Message ID. 109 * @retval kErrorFailed Could not generate random Message ID. 110 * 111 */ 112 Error SetRandomMessageId(void); 113 114 /** 115 * Defines types of DNS message. 116 * 117 */ 118 enum Type : uint8_t 119 { 120 kTypeQuery = 0, 121 kTypeResponse = 1, 122 }; 123 124 /** 125 * This method returns the type of the message. 126 * 127 * @returns The type of the message. 128 * 129 */ GetType(void) const130 Type GetType(void) const { return static_cast<Type>((mFlags[0] & kQrFlagMask) >> kQrFlagOffset); } 131 132 /** 133 * This method sets the type of the message. 134 * 135 * @param[in] aType The type of the message. 136 * 137 */ SetType(Type aType)138 void SetType(Type aType) 139 { 140 mFlags[0] &= ~kQrFlagMask; 141 mFlags[0] |= static_cast<uint8_t>(aType) << kQrFlagOffset; 142 } 143 144 /** 145 * Defines types of query. 146 * 147 */ 148 enum QueryType : uint8_t 149 { 150 kQueryTypeStandard = 0, 151 kQueryTypeInverse = 1, 152 kQueryTypeStatus = 2, 153 kQueryTypeNotify = 4, 154 kQueryTypeUpdate = 5, 155 kQueryTypeDso = 6, 156 }; 157 158 /** 159 * This method returns the type of the query. 160 * 161 * @returns The type of the query. 162 * 163 */ GetQueryType(void) const164 QueryType GetQueryType(void) const { return static_cast<QueryType>((mFlags[0] & kOpCodeMask) >> kOpCodeOffset); } 165 166 /** 167 * This method sets the type of the query. 168 * 169 * @param[in] aType The type of the query. 170 * 171 */ SetQueryType(QueryType aType)172 void SetQueryType(QueryType aType) 173 { 174 mFlags[0] &= ~kOpCodeMask; 175 mFlags[0] |= static_cast<uint8_t>(aType) << kOpCodeOffset; 176 } 177 178 /** 179 * This method specifies in response message if the responding name server is an 180 * authority for the domain name in question section. 181 * 182 * @returns True if Authoritative Answer flag (AA) is set in the header, false otherwise. 183 * 184 */ IsAuthoritativeAnswerFlagSet(void) const185 bool IsAuthoritativeAnswerFlagSet(void) const { return (mFlags[0] & kAaFlagMask) == kAaFlagMask; } 186 187 /** 188 * This method clears the Authoritative Answer flag (AA) in the header. 189 * 190 */ ClearAuthoritativeAnswerFlag(void)191 void ClearAuthoritativeAnswerFlag(void) { mFlags[0] &= ~kAaFlagMask; } 192 193 /** 194 * This method sets the Authoritative Answer flag (AA) in the header. 195 * 196 */ SetAuthoritativeAnswerFlag(void)197 void SetAuthoritativeAnswerFlag(void) { mFlags[0] |= kAaFlagMask; } 198 199 /** 200 * This method specifies if message is truncated. 201 * 202 * @returns True if Truncation flag (TC) is set in the header, false otherwise. 203 * 204 */ IsTruncationFlagSet(void) const205 bool IsTruncationFlagSet(void) const { return (mFlags[0] & kTcFlagMask) == kTcFlagMask; } 206 207 /** 208 * This method clears the Truncation flag (TC) in the header. 209 * 210 */ ClearTruncationFlag(void)211 void ClearTruncationFlag(void) { mFlags[0] &= ~kTcFlagMask; } 212 213 /** 214 * This method sets the Truncation flag (TC) in the header. 215 * 216 */ SetTruncationFlag(void)217 void SetTruncationFlag(void) { mFlags[0] |= kTcFlagMask; } 218 219 /** 220 * This method specifies if resolver wants to direct the name server to pursue 221 * the query recursively. 222 * 223 * @returns True if Recursion Desired flag (RD) is set in the header, false otherwise. 224 * 225 */ IsRecursionDesiredFlagSet(void) const226 bool IsRecursionDesiredFlagSet(void) const { return (mFlags[0] & kRdFlagMask) == kRdFlagMask; } 227 228 /** 229 * This method clears the Recursion Desired flag (RD) in the header. 230 * 231 */ ClearRecursionDesiredFlag(void)232 void ClearRecursionDesiredFlag(void) { mFlags[0] &= ~kRdFlagMask; } 233 234 /** 235 * This method sets the Recursion Desired flag (RD) in the header. 236 * 237 */ SetRecursionDesiredFlag(void)238 void SetRecursionDesiredFlag(void) { mFlags[0] |= kRdFlagMask; } 239 240 /** 241 * This method denotes whether recursive query support is available in the name server. 242 * 243 * @returns True if Recursion Available flag (RA) is set in the header, false otherwise. 244 * 245 */ IsRecursionAvailableFlagSet(void) const246 bool IsRecursionAvailableFlagSet(void) const { return (mFlags[1] & kRaFlagMask) == kRaFlagMask; } 247 248 /** 249 * This method clears the Recursion Available flag (RA) in the header. 250 * 251 */ ClearRecursionAvailableFlag(void)252 void ClearRecursionAvailableFlag(void) { mFlags[1] &= ~kRaFlagMask; } 253 254 /** 255 * This method sets the Recursion Available flag (RA) in the header. 256 * 257 */ SetRecursionAvailableFlag(void)258 void SetRecursionAvailableFlag(void) { mFlags[1] |= kRaFlagMask; } 259 260 /** 261 * Defines response codes. 262 * 263 */ 264 enum Response : uint8_t 265 { 266 kResponseSuccess = 0, ///< Success (no error condition). 267 kResponseFormatError = 1, ///< Server unable to interpret request due to format error. 268 kResponseServerFailure = 2, ///< Server encountered an internal failure. 269 kResponseNameError = 3, ///< Name that ought to exist, does not exists. 270 kResponseNotImplemented = 4, ///< Server does not support the query type (OpCode). 271 kResponseRefused = 5, ///< Server refused to perform operation for policy or security reasons. 272 kResponseNameExists = 6, ///< Some name that ought not to exist, does exist. 273 kResponseRecordExists = 7, ///< Some RRset that ought not to exist, does exist. 274 kResponseRecordNotExists = 8, ///< Some RRset that ought to exist, does not exist. 275 kResponseNotAuth = 9, ///< Service is not authoritative for zone. 276 kResponseNotZone = 10, ///< A name is not in the zone. 277 kDsoTypeNotImplemented = 11, ///< DSO TLV TYPE is not implemented. 278 kResponseBadName = 20, ///< Bad name. 279 kResponseBadAlg = 21, ///< Bad algorithm. 280 kResponseBadTruncation = 22, ///< Bad truncation. 281 }; 282 283 /** 284 * This method returns the response code. 285 * 286 * @returns The response code from the header. 287 * 288 */ GetResponseCode(void) const289 Response GetResponseCode(void) const { return static_cast<Response>((mFlags[1] & kRCodeMask) >> kRCodeOffset); } 290 291 /** 292 * This method sets the response code. 293 * 294 * @param[in] aResponse The type of the response. 295 * 296 */ SetResponseCode(Response aResponse)297 void SetResponseCode(Response aResponse) 298 { 299 mFlags[1] &= ~kRCodeMask; 300 mFlags[1] |= static_cast<uint8_t>(aResponse) << kRCodeOffset; 301 } 302 303 /** 304 * This method converts a Response Code into a related `Error`. 305 * 306 * - kResponseSuccess (0) : Success (no error condition) -> kErrorNone 307 * - kResponseFormatError (1) : Server unable to interpret due to format error -> kErrorParse 308 * - kResponseServerFailure (2) : Server encountered an internal failure -> kErrorFailed 309 * - kResponseNameError (3) : Name that ought to exist, does not exists -> kErrorNotFound 310 * - kResponseNotImplemented (4) : Server does not support the query type (OpCode) -> kErrorNotImplemented 311 * - kResponseRefused (5) : Server refused for policy/security reasons -> kErrorSecurity 312 * - kResponseNameExists (6) : Some name that ought not to exist, does exist -> kErrorDuplicated 313 * - kResponseRecordExists (7) : Some RRset that ought not to exist, does exist -> kErrorDuplicated 314 * - kResponseRecordNotExists (8) : Some RRset that ought to exist, does not exist -> kErrorNotFound 315 * - kResponseNotAuth (9) : Service is not authoritative for zone -> kErrorSecurity 316 * - kResponseNotZone (10) : A name is not in the zone -> kErrorParse 317 * - kDsoTypeNotImplemented (11) : DSO TLV Type is not implemented -> kErrorNotImplemented 318 * - kResponseBadName (20) : Bad name -> kErrorParse 319 * - kResponseBadAlg (21) : Bad algorithm -> kErrorSecurity 320 * - kResponseBadTruncation (22) : Bad truncation -> kErrorParse 321 * - Other error -> kErrorFailed 322 * 323 * @param[in] aResponse The response code to convert. 324 * 325 */ 326 static Error ResponseCodeToError(Response aResponse); 327 328 /** 329 * This method returns the number of entries in question section. 330 * 331 * @returns The number of entries in question section. 332 * 333 */ GetQuestionCount(void) const334 uint16_t GetQuestionCount(void) const { return HostSwap16(mQdCount); } 335 336 /** 337 * This method sets the number of entries in question section. 338 * 339 * @param[in] aCount The number of entries in question section. 340 * 341 */ SetQuestionCount(uint16_t aCount)342 void SetQuestionCount(uint16_t aCount) { mQdCount = HostSwap16(aCount); } 343 344 /** 345 * This method returns the number of entries in answer section. 346 * 347 * @returns The number of entries in answer section. 348 * 349 */ GetAnswerCount(void) const350 uint16_t GetAnswerCount(void) const { return HostSwap16(mAnCount); } 351 352 /** 353 * This method sets the number of entries in answer section. 354 * 355 * @param[in] aCount The number of entries in answer section. 356 * 357 */ SetAnswerCount(uint16_t aCount)358 void SetAnswerCount(uint16_t aCount) { mAnCount = HostSwap16(aCount); } 359 360 /** 361 * This method returns the number of entries in authority records section. 362 * 363 * @returns The number of entries in authority records section. 364 * 365 */ GetAuthorityRecordCount(void) const366 uint16_t GetAuthorityRecordCount(void) const { return HostSwap16(mNsCount); } 367 368 /** 369 * This method sets the number of entries in authority records section. 370 * 371 * @param[in] aCount The number of entries in authority records section. 372 * 373 */ SetAuthorityRecordCount(uint16_t aCount)374 void SetAuthorityRecordCount(uint16_t aCount) { mNsCount = HostSwap16(aCount); } 375 376 /** 377 * This method returns the number of entries in additional records section. 378 * 379 * @returns The number of entries in additional records section. 380 * 381 */ GetAdditionalRecordCount(void) const382 uint16_t GetAdditionalRecordCount(void) const { return HostSwap16(mArCount); } 383 384 /** 385 * This method sets the number of entries in additional records section. 386 * 387 * @param[in] aCount The number of entries in additional records section. 388 * 389 */ SetAdditionalRecordCount(uint16_t aCount)390 void SetAdditionalRecordCount(uint16_t aCount) { mArCount = HostSwap16(aCount); } 391 392 private: 393 // Protocol Constants (RFC 1035). 394 static constexpr uint8_t kQrFlagOffset = 7; // QR Flag offset. 395 static constexpr uint8_t kQrFlagMask = 0x01 << kQrFlagOffset; // QR Flag mask. 396 static constexpr uint8_t kOpCodeOffset = 3; // OpCode field offset. 397 static constexpr uint8_t kOpCodeMask = 0x0f << kOpCodeOffset; // OpCode field mask. 398 static constexpr uint8_t kAaFlagOffset = 2; // AA Flag offset. 399 static constexpr uint8_t kAaFlagMask = 0x01 << kAaFlagOffset; // AA Flag mask. 400 static constexpr uint8_t kTcFlagOffset = 1; // TC Flag offset. 401 static constexpr uint8_t kTcFlagMask = 0x01 << kTcFlagOffset; // TC Flag mask. 402 static constexpr uint8_t kRdFlagOffset = 0; // RD Flag offset. 403 static constexpr uint8_t kRdFlagMask = 0x01 << kRdFlagOffset; // RD Flag mask. 404 static constexpr uint8_t kRaFlagOffset = 7; // RA Flag offset. 405 static constexpr uint8_t kRaFlagMask = 0x01 << kRaFlagOffset; // RA Flag mask. 406 static constexpr uint8_t kRCodeOffset = 0; // RCODE field offset. 407 static constexpr uint8_t kRCodeMask = 0x0f << kRCodeOffset; // RCODE field mask. 408 409 uint16_t mMessageId; // Message identifier for requester to match up replies to outstanding queries. 410 uint8_t mFlags[2]; // DNS header flags. 411 uint16_t mQdCount; // Number of entries in the question section. 412 uint16_t mAnCount; // Number of entries in the answer section. 413 uint16_t mNsCount; // Number of entries in the authority records section. 414 uint16_t mArCount; // Number of entries in the additional records section. 415 416 } OT_TOOL_PACKED_END; 417 418 /** 419 * This class implements DNS Update message header generation and parsing. 420 * 421 * The DNS header specifies record counts for its four sections: Question, Answer, Authority, and Additional. A DNS 422 * Update header uses the same fields, and the same section formats, but the naming and use of these sections differs: 423 * DNS Update header uses Zone, Prerequisite, Update, Additional Data sections. 424 * 425 */ 426 OT_TOOL_PACKED_BEGIN 427 class UpdateHeader : public Header 428 { 429 public: 430 /** 431 * Default constructor for DNS Update message header. 432 * 433 */ UpdateHeader(void)434 UpdateHeader(void) { SetQueryType(kQueryTypeUpdate); } 435 436 /** 437 * This method returns the number of records in Zone section. 438 * 439 * @returns The number of records in Zone section. 440 * 441 */ GetZoneRecordCount(void) const442 uint16_t GetZoneRecordCount(void) const { return GetQuestionCount(); } 443 444 /** 445 * This method sets the number of records in Zone section. 446 * 447 * @param[in] aCount The number of records in Zone section. 448 * 449 */ SetZoneRecordCount(uint16_t aCount)450 void SetZoneRecordCount(uint16_t aCount) { SetQuestionCount(aCount); } 451 452 /** 453 * This method returns the number of records in Prerequisite section. 454 * 455 * @returns The number of records in Prerequisite section. 456 * 457 */ GetPrerequisiteRecordCount(void) const458 uint16_t GetPrerequisiteRecordCount(void) const { return GetAnswerCount(); } 459 460 /** 461 * This method sets the number of records in Prerequisite section. 462 * 463 * @param[in] aCount The number of records in Prerequisite section. 464 * 465 */ SetPrerequisiteRecordCount(uint16_t aCount)466 void SetPrerequisiteRecordCount(uint16_t aCount) { SetAnswerCount(aCount); } 467 468 /** 469 * This method returns the number of records in Update section. 470 * 471 * @returns The number of records in Update section. 472 * 473 */ GetUpdateRecordCount(void) const474 uint16_t GetUpdateRecordCount(void) const { return GetAuthorityRecordCount(); } 475 476 /** 477 * This method sets the number of records in Update section. 478 * 479 * @param[in] aCount The number of records in Update section. 480 * 481 */ SetUpdateRecordCount(uint16_t aCount)482 void SetUpdateRecordCount(uint16_t aCount) { SetAuthorityRecordCount(aCount); } 483 484 } OT_TOOL_PACKED_END; 485 486 /** 487 * This class represents a DNS name and implements helper methods for encoding/decoding of DNS Names. 488 * 489 */ 490 class Name : public Clearable<Name> 491 { 492 public: 493 /** 494 * Max size (number of chars) in a name string array (includes null char at the end of string). 495 * 496 */ 497 static constexpr uint8_t kMaxNameSize = OT_DNS_MAX_NAME_SIZE; 498 499 /** 500 * Maximum length in a name string (does not include null char at the end of string). 501 * 502 */ 503 static constexpr uint8_t kMaxNameLength = kMaxNameSize - 1; 504 505 /** 506 * Max size (number of chars) in a label string array (includes null char at the end of the string). 507 * 508 */ 509 static constexpr uint8_t kMaxLabelSize = OT_DNS_MAX_LABEL_SIZE; 510 511 /** 512 * Maximum length in a label string (does not include null char at the end of string). 513 * 514 */ 515 static constexpr uint8_t kMaxLabelLength = kMaxLabelSize - 1; 516 517 static constexpr char kLabelSeperatorChar = '.'; 518 519 /** 520 * This enumeration represents the name type. 521 * 522 */ 523 enum Type : uint8_t 524 { 525 kTypeEmpty, ///< The name is empty (not specified). 526 kTypeCString, ///< The name is given as a C string (dot '.' separated sequence of labels). 527 kTypeMessage, ///< The name is specified from a message at a given offset (encoded in the message). 528 }; 529 530 /** 531 * This constructor initializes the `Name` object as empty (not specified). 532 * 533 */ Name(void)534 Name(void) 535 : Name(nullptr, nullptr, 0) 536 { 537 } 538 539 /** 540 * This constructor initializes the `Name` object with a given string. 541 * 542 * @param[in] aString A C string specifying the name (dot '.' separated sequence of labels'). 543 * 544 */ Name(const char * aString)545 explicit Name(const char *aString) 546 : Name(aString, nullptr, 0) 547 { 548 } 549 550 /** 551 * This constructor initializes the `Name` object from a message at a given offset. 552 * 553 * @param[in] aMessage The message containing the encoded name. `aMessage.GetOffset()` MUST point to the start of 554 * the DNS header in the message (used to parse compressed name). 555 * @param[in] aOffset The offset in @p aMessage pointing to the start of the name. 556 * 557 */ Name(const Message & aMessage,uint16_t aOffset)558 Name(const Message &aMessage, uint16_t aOffset) 559 : Name(nullptr, &aMessage, aOffset) 560 { 561 } 562 563 /** 564 * This method indicates whether the name is empty (not specified). 565 * 566 * @returns TRUE if the name is empty, FALSE otherwise. 567 * 568 */ IsEmpty(void) const569 bool IsEmpty(void) const { return (mString == nullptr) && (mMessage == nullptr); } 570 571 /** 572 * This method indicates whether the name is specified from a C string. 573 * 574 * @returns TRUE if the name is specified from a string, FALSE otherwise. 575 * 576 */ IsFromCString(void) const577 bool IsFromCString(void) const { return mString != nullptr; } 578 579 /** 580 * This method indicates whether the name is specified from a message. 581 * 582 * @returns TRUE if the name is specified from a message, FALSE otherwise. 583 * 584 */ IsFromMessage(void) const585 bool IsFromMessage(void) const { return mMessage != nullptr; } 586 587 /** 588 * This method gets the type of `Name` object indicating whether it is empty, specified by a C string or from a 589 * message 590 * 591 * @returns The name type. 592 * 593 */ GetFromType(void) const594 Type GetFromType(void) const 595 { 596 return IsFromCString() ? kTypeCString : (IsFromMessage() ? kTypeMessage : kTypeEmpty); 597 } 598 599 /** 600 * This method sets the name from a given C string. 601 * 602 * @param[in] aString A C string specifying the name (dot '.' separated sequence of labels). 603 * 604 */ Set(const char * aString)605 void Set(const char *aString) 606 { 607 mString = aString; 608 mMessage = nullptr; 609 } 610 611 /** 612 * This method sets the name from a message at a given offset. 613 * 614 * @param[in] aMessage The message containing the encoded name. `aMessage.GetOffset()` MUST point to the start of 615 * the DNS header in the message (used to parse compressed name). 616 * @param[in] aOffset The offset in @p aMessage pointing to the start of the name. 617 * 618 */ SetFromMessage(const Message & aMessage,uint16_t aOffset)619 void SetFromMessage(const Message &aMessage, uint16_t aOffset) 620 { 621 mString = nullptr; 622 mMessage = &aMessage; 623 mOffset = aOffset; 624 } 625 626 /** 627 * This method gets the name as a C string. 628 * 629 * This method MUST be used only when the type is `kTypeString`. Otherwise its behavior is undefined. 630 * 631 * @returns A pointer to the C string. 632 * 633 */ GetAsCString(void) const634 const char *GetAsCString(void) const { return mString; } 635 636 /** 637 * This method gets the name message and offset. 638 * 639 * This method MUST be used only when the type is `kTypeMessage`. Otherwise its behavior is undefined. 640 * 641 * @param[out] aOffset A reference to a variable to output the offset of the start of the name in the message. 642 * 643 * @returns A reference to the message containing the name. 644 * 645 */ GetAsMessage(uint16_t & aOffset) const646 const Message &GetAsMessage(uint16_t &aOffset) const 647 { 648 aOffset = mOffset; 649 return *mMessage; 650 } 651 652 /** 653 * This method encodes and appends the name to a message. 654 * 655 * If the name is empty (not specified), then root "." is appended to @p aMessage. If the name is from a C string 656 * then the string is checked and appended (similar to static `AppendName(const char *aName, Message &)` method). 657 * If the the name is from a message, then it is read from the message and appended to @p aMessage. Note that in 658 * this case independent of whether the name is compressed or not in its original message, the name is appended 659 * as full (uncompressed) in @p aMessage. 660 * 661 * @param[in] aMessage The message to append to. 662 * 663 * @retval kErrorNone Successfully encoded and appended the name to @p aMessage. 664 * @retval kErrorInvalidArgs Name is not valid. 665 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 666 * 667 */ 668 Error AppendTo(Message &aMessage) const; 669 670 /** 671 * This static method encodes and appends a single name label to a message. 672 * 673 * The @p aLabel is assumed to contain a single name label as a C string (null-terminated). Unlike 674 * `AppendMultipleLabels()` which parses the label string and treats it as sequence of multiple (dot-separated) 675 * labels, this method always appends @p aLabel as a single whole label. This allows the label string to even 676 * contain dot '.' character, which, for example, is useful for "Service Instance Names" where <Instance> portion 677 * is a user-friendly name and can contain dot characters. 678 * 679 * @param[in] aLabel The label string to append. MUST NOT be `nullptr`. 680 * @param[in] aMessage The message to append to. 681 * 682 * @retval kErrorNone Successfully encoded and appended the name label to @p aMessage. 683 * @retval kErrorInvalidArgs @p aLabel is not valid (e.g., label length is not within valid range). 684 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 685 * 686 */ 687 static Error AppendLabel(const char *aLabel, Message &aMessage); 688 689 /** 690 * This static method encodes and appends a single name label of specified length to a message. 691 * 692 * The @p aLabel is assumed to contain a single name label of given @p aLength. @p aLabel must not contain 693 * '\0' characters within the length @p aLength. Unlike `AppendMultipleLabels()` which parses the label string 694 * and treats it as sequence of multiple (dot-separated) labels, this method always appends @p aLabel as a single 695 * whole label. This allows the label string to even contain dot '.' character, which, for example, is useful for 696 * "Service Instance Names" where <Instance> portion is a user-friendly name and can contain dot characters. 697 * 698 * @param[in] aLabel The label string to append. MUST NOT be `nullptr`. 699 * @param[in] aLength The length of the label to append. 700 * @param[in] aMessage The message to append to. 701 * 702 * @retval kErrorNone Successfully encoded and appended the name label to @p aMessage. 703 * @retval kErrorInvalidArgs @p aLabel is not valid (e.g., label length is not within valid range). 704 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 705 * 706 */ 707 static Error AppendLabel(const char *aLabel, uint8_t aLength, Message &aMessage); 708 709 /** 710 * This static method encodes and appends a sequence of name labels to a given message. 711 * 712 * The @p aLabels must follow "<label1>.<label2>.<label3>", i.e., a sequence of labels separated by dot '.' char. 713 * E.g., "_http._tcp", "_http._tcp." (same as previous one), "host-1.test". 714 * 715 * This method validates that the @p aLabels is a valid name format, i.e., no empty label, and labels are 716 * `kMaxLabelLength` (63) characters or less. 717 * 718 * @note This method NEVER adds a label terminator (empty label) to the message, even in the case where @p aLabels 719 * ends with a dot character, e.g., "host-1.test." is treated same as "host-1.test". 720 * 721 * @param[in] aLabels A name label string. Can be `nullptr` (then treated as ""). 722 * @param[in] aMessage The message to which to append the encoded name. 723 * 724 * @retval kErrorNone Successfully encoded and appended the name label(s) to @p aMessage. 725 * @retval kErrorInvalidArgs Name label @p aLabels is not valid. 726 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 727 * 728 */ 729 static Error AppendMultipleLabels(const char *aLabels, Message &aMessage); 730 731 /** 732 * This static method encodes and appends a sequence of name labels within the specified length to a given message. 733 * This method stops appending labels if @p aLength characters are read or '\0' is found before @p aLength 734 * characters. 735 * 736 * This method is useful for appending a number of labels of the name instead of appending all labels. 737 * 738 * The @p aLabels must follow "<label1>.<label2>.<label3>", i.e., a sequence of labels separated by dot '.' char. 739 * E.g., "_http._tcp", "_http._tcp." (same as previous one), "host-1.test". 740 * 741 * This method validates that the @p aLabels is a valid name format, i.e., no empty label, and labels are 742 * `kMaxLabelLength` (63) characters or less. 743 * 744 * @note This method NEVER adds a label terminator (empty label) to the message, even in the case where @p aLabels 745 * ends with a dot character, e.g., "host-1.test." is treated same as "host-1.test". 746 * 747 * @param[in] aLabels A name label string. Can be `nullptr` (then treated as ""). 748 * @param[in] aLength The max length of the name labels to encode. 749 * @param[in] aMessage The message to which to append the encoded name. 750 * 751 * @retval kErrorNone Successfully encoded and appended the name label(s) to @p aMessage. 752 * @retval kErrorInvalidArgs Name label @p aLabels is not valid. 753 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 754 * 755 */ 756 static Error AppendMultipleLabels(const char *aLabels, uint8_t aLength, Message &aMessage); 757 758 /** 759 * This static method appends a name label terminator to a message. 760 * 761 * An encoded name is terminated by an empty label (a zero byte). 762 * 763 * @param[in] aMessage The message to append to. 764 * 765 * @retval kErrorNone Successfully encoded and appended the terminator label to @p aMessage. 766 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 767 * 768 */ 769 static Error AppendTerminator(Message &aMessage); 770 771 /** 772 * This static method appends a pointer type name label to a message. 773 * 774 * Pointer label is used for name compression. It allows an entire name or a list of labels at the end of an 775 * encoded name to be replaced with a pointer to a prior occurrence of the same name within the message. 776 * 777 * @param[in] aOffset The offset from the start of DNS header to use for pointer value. 778 * @param[in] aMessage The message to append to. 779 * 780 * @retval kErrorNone Successfully encoded and appended the pointer label to @p aMessage. 781 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 782 * 783 */ 784 static Error AppendPointerLabel(uint16_t aOffset, Message &aMessage); 785 786 /** 787 * This static method encodes and appends a full name to a message. 788 * 789 * The @p aName must follow "<label1>.<label2>.<label3>", i.e., a sequence of labels separated by dot '.' char. 790 * E.g., "example.com", "example.com." (same as previous one), "local.", "default.service.arpa", "." or "" (root). 791 * 792 * This method validates that the @p aName is a valid name format, i.e. no empty labels, and labels are 793 * `kMaxLabelLength` (63) characters or less, and the name is `kMaxLength` (255) characters or less. 794 * 795 * @param[in] aName A name string. Can be `nullptr` (then treated as "." or root). 796 * @param[in] aMessage The message to append to. 797 * 798 * @retval kErrorNone Successfully encoded and appended the name to @p aMessage. 799 * @retval kErrorInvalidArgs Name @p aName is not valid. 800 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 801 * 802 */ 803 static Error AppendName(const char *aName, Message &aMessage); 804 805 /** 806 * This static method parses and skips over a full name in a message. 807 * 808 * @param[in] aMessage The message to parse the name from. `aMessage.GetOffset()` MUST point to 809 * the start of DNS header (this is used to handle compressed names). 810 * @param[in,out] aOffset On input the offset in @p aMessage pointing to the start of the name field. 811 * On exit (when parsed successfully), @p aOffset is updated to point to the byte 812 * after the end of name field. 813 * 814 * @retval kErrorNone Successfully parsed and skipped over name, @p Offset is updated. 815 * @retval kErrorParse Name could not be parsed (invalid format). 816 * 817 */ 818 static Error ParseName(const Message &aMessage, uint16_t &aOffset); 819 820 /** 821 * This static method reads a name label from a message. 822 * 823 * This method can be used to read labels one by one in a name. After a successful label read, @p aOffset is 824 * updated to point to the start of the next label. When we reach the end of the name, kErrorNotFound is 825 * returned. This method handles compressed names which use pointer labels. So as the labels in a name are read, 826 * the @p aOffset may jump back in the message and at the end the @p aOffset does not necessarily point to the end 827 * of the original name field. 828 * 829 * Unlike `ReadName()` which requires and verifies that the read label to contain no dot '.' character, this method 830 * allows the read label to include any character. 831 * 832 * @param[in] aMessage The message to read the label from. `aMessage.GetOffset()` MUST point to 833 * the start of DNS header (this is used to handle compressed names). 834 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the label to read. 835 * On exit, when successfully read, @p aOffset is updated to point to the start of 836 * the next label. 837 * @param[out] aLabelBuffer A pointer to a char array to output the read label as a null-terminated C string. 838 * @param[in,out] aLabelLength On input, the maximum number chars in @p aLabelBuffer array. 839 * On output, when label is successfully read, @p aLabelLength is updated to return 840 * the label's length (number of chars in the label string, excluding the null char). 841 * 842 * @retval kErrorNone Successfully read the label and updated @p aLabelBuffer, @p aLabelLength, and @p aOffset. 843 * @retval kErrorNotFound Reached the end of name and no more label to read. 844 * @retval kErrorParse Name could not be parsed (invalid format). 845 * @retval kErrorNoBufs Label could not fit in @p aLabelLength chars. 846 * 847 */ 848 static Error ReadLabel(const Message &aMessage, uint16_t &aOffset, char *aLabelBuffer, uint8_t &aLabelLength); 849 850 /** 851 * This static method reads a full name from a message. 852 * 853 * On successful read, the read name follows "<label1>.<label2>.<label3>.", i.e., a sequence of labels separated by 854 * dot '.' character. The read name will ALWAYS end with a dot. 855 * 856 * This method verifies that the read labels in message do not contain any dot character, otherwise it returns 857 * `kErrorParse`). 858 * 859 * @param[in] aMessage The message to read the name from. `aMessage.GetOffset()` MUST point to 860 * the start of DNS header (this is used to handle compressed names). 861 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the name field. 862 * On exit (when parsed successfully), @p aOffset is updated to point to the byte 863 * after the end of name field. 864 * @param[out] aNameBuffer A pointer to a char array to output the read name as a null-terminated C string. 865 * @param[in,out] aNameBufferSize The maximum number of chars in @p aNameBuffer array. 866 * 867 * @retval kErrorNone Successfully read the name, @p aNameBuffer and @p Offset are updated. 868 * @retval kErrorParse Name could not be parsed (invalid format). 869 * @retval kErrorNoBufs Name could not fit in @p aNameBufferSize chars. 870 * 871 */ 872 static Error ReadName(const Message &aMessage, uint16_t &aOffset, char *aNameBuffer, uint16_t aNameBufferSize); 873 874 /** 875 * This static method compares a single name label from a message with a given label string. 876 * 877 * This method can be used to compare labels one by one. It checks whether the label read from @p aMessage matches 878 * @p aLabel string (case-insensitive comparison). 879 * 880 * Unlike `CompareName()` which requires the labels in the the name string to contain no dot '.' character, this 881 * method allows @p aLabel to include any character. 882 * 883 * @param[in] aMessage The message to read the label from to compare. `aMessage.GetOffset()` MUST point 884 * to the start of DNS header (this is used to handle compressed names). 885 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the label to read. 886 * On exit and only when label is successfully read and does match @p aLabel, 887 * @p aOffset is updated to point to the start of the next label. 888 * @param[in] aLabel A pointer to a null terminated string containing the label to compare with. 889 * 890 * @retval kErrorNone The label from @p aMessage matches @p aLabel. @p aOffset is updated. 891 * @retval kErrorNotFound The label from @p aMessage does not match @p aLabel (note that @p aOffset is not 892 * updated in this case). 893 * @retval kErrorParse Name could not be parsed (invalid format). 894 * 895 */ 896 static Error CompareLabel(const Message &aMessage, uint16_t &aOffset, const char *aLabel); 897 898 /** 899 * This static method parses and compares a full name from a message with a given name. 900 * 901 * This method checks whether the encoded name in a message matches a given name string (using case-insensitive 902 * comparison). It checks the name in the message in place and handles compressed names. If the name read from the 903 * message does not match @p aName, it returns `kErrorNotFound`. `kErrorNone` indicates that the name matches 904 * @p aName. 905 * 906 * The @p aName must follow "<label1>.<label2>.<label3>", i.e., a sequence of labels separated by dot '.' char. 907 * E.g., "example.com", "example.com." (same as previous one), "local.", "default.service.arpa", "." or "" (root). 908 * 909 * @param[in] aMessage The message to read the name from and compare with @p aName. 910 * `aMessage.GetOffset()` MUST point to the start of DNS header (this is used to 911 * handle compressed names). 912 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the name field. 913 * On exit (when parsed successfully independent of whether the read name matches 914 * @p aName or not), @p aOffset is updated to point to the byte after the end of 915 * the name field. 916 * @param[in] aName A pointer to a null terminated string containing the name to compare with. 917 * 918 * @retval kErrorNone The name from @p aMessage matches @p aName. @p aOffset is updated. 919 * @retval kErrorNotFound The name from @p aMessage does not match @p aName. @p aOffset is updated. 920 * @retval kErrorParse Name could not be parsed (invalid format). 921 * @retval kErrorInvalidArgs The @p aName is not a valid name (e.g. back to back "." chars) 922 * 923 */ 924 static Error CompareName(const Message &aMessage, uint16_t &aOffset, const char *aName); 925 926 /** 927 * This static method parses and compares a full name from a message with a name from another message. 928 * 929 * This method checks whether the encoded name in @p aMessage matches the name from @p aMessage2 (using 930 * case-insensitive comparison). It compares the names in both messages in place and handles compressed names. Note 931 * that this method works correctly even when the same message instance is used for both @p aMessage and 932 * @p aMessage2 (e.g., at different offsets). 933 * 934 * Only the name in @p aMessage is fully parsed and checked for parse errors. This method assumes that the name in 935 * @p aMessage2 was previously parsed and validated before calling this method (if there is a parse error in 936 * @p aMessage2, it is treated as a name mismatch with @p aMessage). 937 * 938 * If the name in @p aMessage can be parsed fully (independent of whether the name matches or not with the name 939 * from @p aMessage2), the @p aOffset is updated (note that @p aOffset2 for @p aMessage2 is not changed). 940 * 941 * @param[in] aMessage The message to read the name from and compare. `aMessage.GetOffset()` MUST point 942 * to the start of DNS header (this is used to handle compressed names). 943 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the name field. 944 * On exit (when parsed successfully independent of whether the read name matches 945 * or not), @p aOffset is updated to point to the byte after the end of the name 946 * field. 947 * @param[in] aMessage2 The second message to read the name from and compare with name from @p aMessage. 948 * `aMessage2.GetOffset()` MUST point to the start of DNS header. 949 * @param[in] aOffset2 The offset in @p aMessage2 pointing to the start of the name field. 950 * 951 * @retval kErrorNone The name from @p aMessage matches the name from @p aMessage2. @p aOffset is updated. 952 * @retval kErrorNotFound The name from @p aMessage does not match the name from @p aMessage2. @p aOffset is 953 * updated. 954 * @retval kErrorParse Name in @p aMessage could not be parsed (invalid format). 955 * 956 */ 957 static Error CompareName(const Message &aMessage, uint16_t &aOffset, const Message &aMessage2, uint16_t aOffset2); 958 959 /** 960 * This static method parses and compares a full name from a message with a given name (using case-insensitive 961 * comparison). 962 * 963 * If @p aName is empty (not specified), then any name in @p aMessage is considered a match to it. 964 * 965 * @param[in] aMessage The message to read the name from and compare. `aMessage.GetOffset()` MUST point 966 * to the start of DNS header (this is used to handle compressed names). 967 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the name field. 968 * On exit (when parsed successfully independent of whether the read name matches 969 * or not), @p aOffset is updated to point to the byte after the end of the name 970 * field. 971 * @param[in] aName A reference to a name to compare with. 972 * 973 * @retval kErrorNone The name from @p aMessage matches @p aName. @p aOffset is updated. 974 * @retval kErrorNotFound The name from @p aMessage does not match @p aName. @p aOffset is updated. 975 * @retval kErrorParse Name in @p aMessage could not be parsed (invalid format). 976 * 977 */ 978 static Error CompareName(const Message &aMessage, uint16_t &aOffset, const Name &aName); 979 980 /** 981 * This static method tests if a DNS name is a sub-domain of a given domain. 982 * 983 * Both @p aName and @p aDomain can end without dot ('.'). 984 * 985 * @param[in] aName The dot-separated name. 986 * @param[in] aDomain The dot-separated domain. 987 * 988 * @returns TRUE if the name is a sub-domain of @p aDomain, FALSE if is not. 989 * 990 */ 991 static bool IsSubDomainOf(const char *aName, const char *aDomain); 992 993 private: 994 // The first 2 bits of the encoded label specifies label type. 995 // 996 // - Value 00 indicates normal text label (lower 6-bits indicates the label length). 997 // - Value 11 indicates pointer label type (lower 14-bits indicates the pointer offset). 998 // - Values 01,10 are reserved (RFC 6891 recommends to not use) 999 1000 static constexpr uint8_t kLabelTypeMask = 0xc0; // 0b1100_0000 (first two bits) 1001 static constexpr uint8_t kTextLabelType = 0x00; // Text label type (00) 1002 static constexpr uint8_t kPointerLabelType = 0xc0; // Pointer label type - compressed name (11) 1003 1004 static constexpr uint8_t kMaxEncodedLength = 255; ///< Max length of an encoded name. 1005 1006 static constexpr uint16_t kPointerLabelTypeUint16 = 0xc000; // Pointer label type mask (first 2 bits). 1007 static constexpr uint16_t kPointerLabelOffsetMask = 0x3fff; // Mask for offset in a pointer label (lower 14 bits). 1008 1009 static constexpr bool kIsSingleLabel = true; // Used in `LabelIterator::CompareLable()`. 1010 1011 struct LabelIterator 1012 { 1013 static constexpr uint16_t kUnsetNameEndOffset = 0; // Special value indicating `mNameEndOffset` is not yet set. 1014 LabelIteratorot::Dns::Name::LabelIterator1015 LabelIterator(const Message &aMessage, uint16_t aLabelOffset) 1016 : mMessage(aMessage) 1017 , mNextLabelOffset(aLabelOffset) 1018 , mNameEndOffset(kUnsetNameEndOffset) 1019 { 1020 } 1021 IsEndOffsetSetot::Dns::Name::LabelIterator1022 bool IsEndOffsetSet(void) const { return (mNameEndOffset != kUnsetNameEndOffset); } 1023 Error GetNextLabel(void); 1024 Error ReadLabel(char *aLabelBuffer, uint8_t &aLabelLength, bool aAllowDotCharInLabel) const; 1025 bool CompareLabel(const char *&aName, bool aIsSingleLabel) const; 1026 bool CompareLabel(const LabelIterator &aOtherIterator) const; 1027 Error AppendLabel(Message &aMessage) const; 1028 1029 static bool CaseInsensitiveMatch(uint8_t aFirst, uint8_t aSecond); 1030 1031 const Message &mMessage; // Message to read labels from. 1032 uint16_t mLabelStartOffset; // Offset in `mMessage` to the first char of current label text. 1033 uint8_t mLabelLength; // Length of current label (number of chars). 1034 uint16_t mNextLabelOffset; // Offset in `mMessage` to the start of the next label. 1035 uint16_t mNameEndOffset; // Offset in `mMessage` to the byte after the end of domain name field. 1036 }; 1037 Name(const char * aString,const Message * aMessage,uint16_t aOffset)1038 Name(const char *aString, const Message *aMessage, uint16_t aOffset) 1039 : mString(aString) 1040 , mMessage(aMessage) 1041 , mOffset(aOffset) 1042 { 1043 } 1044 1045 const char * mString; // String containing the name or `nullptr` if name is not from string. 1046 const Message *mMessage; // Message containing the encoded name, or `nullptr` if `Name` is not from message. 1047 uint16_t mOffset; // Offset in `mMessage` to the start of name (used when name is from `mMessage`). 1048 }; 1049 1050 /** 1051 * This type represents a TXT record entry representing a key/value pair (RFC 6763 - section 6.3). 1052 * 1053 */ 1054 class TxtEntry : public otDnsTxtEntry 1055 { 1056 friend class TxtRecord; 1057 1058 public: 1059 /** 1060 * Minimum length of key string (RFC 6763 - section 6.4). 1061 * 1062 */ 1063 static constexpr uint8_t kMinKeyLength = OT_DNS_TXT_KEY_MIN_LENGTH; 1064 1065 /** 1066 * Recommended max length of key string (RFC 6763 - section 6.4). 1067 * 1068 */ 1069 static constexpr uint8_t kMaxKeyLength = OT_DNS_TXT_KEY_MAX_LENGTH; 1070 1071 /** 1072 * This class represents an iterator for TXT record entries (key/value pairs). 1073 * 1074 */ 1075 class Iterator : public otDnsTxtEntryIterator 1076 { 1077 friend class TxtEntry; 1078 1079 public: 1080 /** 1081 * This method initializes a TXT record iterator. 1082 * 1083 * The buffer pointer @p aTxtData and its content MUST persist and remain unchanged while the iterator object 1084 * is being used. 1085 * 1086 * @param[in] aTxtData A pointer to buffer containing the encoded TXT data. 1087 * @param[in] aTxtDataLength The length (number of bytes) of @p aTxtData. 1088 * 1089 */ 1090 void Init(const uint8_t *aTxtData, uint16_t aTxtDataLength); 1091 1092 /** 1093 * This method parses the TXT data from the `Iterator` and gets the next TXT record entry (key/value pair). 1094 * 1095 * The `Iterator` instance MUST be initialized using `Init()` before calling this method and the TXT data 1096 * buffer used to initialize the iterator MUST persist and remain unchanged. 1097 * 1098 * If the parsed key string length is smaller than or equal to `kMaxKeyLength` (recommended max key length) 1099 * the key string is returned in `mKey` in @p aEntry. But if the key is longer, then `mKey` is set to NULL and 1100 * the entire encoded TXT entry is returned in `mValue` and `mValueLength`. 1101 * 1102 * @param[out] aEntry A reference to a `TxtEntry` to output the parsed/read entry. 1103 * 1104 * @retval kErrorNone The next entry was parsed successfully. @p aEntry is updated. 1105 * @retval kErrorNotFound No more entries in TXT data. 1106 * @retval kErrorParse The TXT data from `Iterator` is not well-formed. 1107 * 1108 */ 1109 Error GetNextEntry(TxtEntry &aEntry); 1110 1111 private: 1112 static constexpr uint8_t kIndexTxtLength = 0; 1113 static constexpr uint8_t kIndexTxtPosition = 1; 1114 GetTxtData(void) const1115 const char *GetTxtData(void) const { return reinterpret_cast<const char *>(mPtr); } SetTxtData(const uint8_t * aTxtData)1116 void SetTxtData(const uint8_t *aTxtData) { mPtr = aTxtData; } GetTxtDataLength(void) const1117 uint16_t GetTxtDataLength(void) const { return mData[kIndexTxtLength]; } SetTxtDataLength(uint16_t aLength)1118 void SetTxtDataLength(uint16_t aLength) { mData[kIndexTxtLength] = aLength; } GetTxtDataPosition(void) const1119 uint16_t GetTxtDataPosition(void) const { return mData[kIndexTxtPosition]; } SetTxtDataPosition(uint16_t aValue)1120 void SetTxtDataPosition(uint16_t aValue) { mData[kIndexTxtPosition] = aValue; } IncreaseTxtDataPosition(uint16_t aIncrement)1121 void IncreaseTxtDataPosition(uint16_t aIncrement) { mData[kIndexTxtPosition] += aIncrement; } GetKeyBuffer(void)1122 char * GetKeyBuffer(void) { return mChar; } GetTxtDataEnd(void) const1123 const char *GetTxtDataEnd(void) const { return GetTxtData() + GetTxtDataLength(); } 1124 }; 1125 1126 /** 1127 * This is the default constructor for a `TxtEntry` object. 1128 * 1129 */ 1130 TxtEntry(void) = default; 1131 1132 /** 1133 * This constructor initializes a `TxtEntry` object. 1134 * 1135 * @param[in] aKey A pointer to the key string. 1136 * @param[in] aValue A pointer to a buffer containing the value. 1137 * @param[in] aValueLength Number of bytes in @p aValue buffer. 1138 * 1139 */ TxtEntry(const char * aKey,const uint8_t * aValue,uint8_t aValueLength)1140 TxtEntry(const char *aKey, const uint8_t *aValue, uint8_t aValueLength) { Init(aKey, aValue, aValueLength); } 1141 1142 /** 1143 * This method initializes a `TxtEntry` object. 1144 * 1145 * @param[in] aKey A pointer to the key string. 1146 * @param[in] aValue A pointer to a buffer containing the value. 1147 * @param[in] aValueLength Number of bytes in @p aValue buffer. 1148 * 1149 */ Init(const char * aKey,const uint8_t * aValue,uint8_t aValueLength)1150 void Init(const char *aKey, const uint8_t *aValue, uint8_t aValueLength) 1151 { 1152 mKey = aKey; 1153 mValue = aValue; 1154 mValueLength = aValueLength; 1155 } 1156 1157 /** 1158 * This method encodes and appends the `TxtEntry` to a message. 1159 * 1160 * @param[in] aMessage The message to append to. 1161 * 1162 * @retval kErrorNone Entry was appended successfully to @p aMessage. 1163 * @retval kErrorInvalidArgs The `TxTEntry` info is not valid. 1164 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 1165 * 1166 */ 1167 Error AppendTo(Message &aMessage) const; 1168 1169 /** 1170 * This static method appends an array of `TxtEntry` items to a message. 1171 * 1172 * @param[in] aEntries A pointer to array of `TxtEntry` items. 1173 * @param[in] aNumEntries The number of entries in @p aEntries array. 1174 * @param[in] aMessage The message to append to. 1175 * 1176 * @retval kErrorNone Entries appended successfully to @p aMessage. 1177 * @retval kErrorInvalidArgs The `TxTEntry` info is not valid. 1178 * @retval kErrorNoBufs Insufficient available buffers to grow the message. 1179 * 1180 */ 1181 static Error AppendEntries(const TxtEntry *aEntries, uint8_t aNumEntries, Message &aMessage); 1182 1183 /** 1184 * This static method appends an array of `TxtEntry` items to a `MutableData` buffer. 1185 * 1186 * @param[in] aEntries A pointer to array of `TxtEntry` items. 1187 * @param[in] aNumEntries The number of entries in @p aEntries array. 1188 * @param[in] aData The `MutableData` to append in. 1189 * 1190 * @retval kErrorNone Entries appended successfully . 1191 * @retval kErrorInvalidArgs The `TxTEntry` info is not valid. 1192 * @retval kErrorNoBufs Insufficient available buffers. 1193 * 1194 */ 1195 static Error AppendEntries(const TxtEntry *aEntries, uint8_t aNumEntries, MutableData<kWithUint16Length> &aData); 1196 1197 private: 1198 Error AppendTo(Appender &aAppender) const; 1199 static Error AppendEntries(const TxtEntry *aEntries, uint8_t aNumEntries, Appender &aAppender); 1200 1201 static constexpr uint8_t kMaxKeyValueEncodedSize = 255; 1202 static constexpr char kKeyValueSeparator = '='; 1203 }; 1204 1205 /** 1206 * This class implements Resource Record (RR) body format. 1207 * 1208 */ 1209 OT_TOOL_PACKED_BEGIN 1210 class ResourceRecord 1211 { 1212 friend class OptRecord; 1213 1214 public: 1215 // Resource Record Types. 1216 static constexpr uint16_t kTypeZero = 0; ///< Zero as special indicator for the SIG RR (SIG(0) from RFC 2931). 1217 static constexpr uint16_t kTypeA = 1; ///< Address record (IPv4). 1218 static constexpr uint16_t kTypeSoa = 6; ///< Start of (zone of) authority. 1219 static constexpr uint16_t kTypeCname = 5; ///< CNAME record. 1220 static constexpr uint16_t kTypePtr = 12; ///< PTR record. 1221 static constexpr uint16_t kTypeTxt = 16; ///< TXT record. 1222 static constexpr uint16_t kTypeSig = 24; ///< SIG record. 1223 static constexpr uint16_t kTypeKey = 25; ///< KEY record. 1224 static constexpr uint16_t kTypeAaaa = 28; ///< IPv6 address record. 1225 static constexpr uint16_t kTypeSrv = 33; ///< SRV locator record. 1226 static constexpr uint16_t kTypeOpt = 41; ///< Option record. 1227 static constexpr uint16_t kTypeAny = 255; ///< ANY record. 1228 1229 // Resource Record Class Codes. 1230 static constexpr uint16_t kClassInternet = 1; ///< Class code Internet (IN). 1231 static constexpr uint16_t kClassNone = 254; ///< Class code None (NONE) - RFC 2136. 1232 static constexpr uint16_t kClassAny = 255; ///< Class code Any (ANY). 1233 1234 /** 1235 * This method initializes the resource record by setting its type and class. 1236 * 1237 * This method only sets the type and class fields. Other fields (TTL and length) remain unchanged/uninitialized. 1238 * 1239 * @param[in] aType The type of the resource record. 1240 * @param[in] aClass The class of the resource record (default is `kClassInternet`). 1241 * 1242 */ Init(uint16_t aType,uint16_t aClass=kClassInternet)1243 void Init(uint16_t aType, uint16_t aClass = kClassInternet) 1244 { 1245 SetType(aType); 1246 SetClass(aClass); 1247 } 1248 1249 /** 1250 * This method indicates whether the resources records matches a given type and class code. 1251 * 1252 * @param[in] aType The resource record type to compare with. 1253 * @param[in] aClass The resource record class code to compare with (default is `kClassInternet`). 1254 * 1255 * @returns TRUE if the resources records matches @p aType and @p aClass, FALSE otherwise. 1256 * 1257 */ Matches(uint16_t aType,uint16_t aClass=kClassInternet)1258 bool Matches(uint16_t aType, uint16_t aClass = kClassInternet) 1259 { 1260 return (mType == HostSwap16(aType)) && (mClass == HostSwap16(aClass)); 1261 } 1262 1263 /** 1264 * This method returns the type of the resource record. 1265 * 1266 * @returns The type of the resource record. 1267 * 1268 */ GetType(void) const1269 uint16_t GetType(void) const { return HostSwap16(mType); } 1270 1271 /** 1272 * This method sets the type of the resource record. 1273 * 1274 * @param[in] aType The type of the resource record. 1275 * 1276 */ SetType(uint16_t aType)1277 void SetType(uint16_t aType) { mType = HostSwap16(aType); } 1278 1279 /** 1280 * This method returns the class of the resource record. 1281 * 1282 * @returns The class of the resource record. 1283 * 1284 */ GetClass(void) const1285 uint16_t GetClass(void) const { return HostSwap16(mClass); } 1286 1287 /** 1288 * This method sets the class of the resource record. 1289 * 1290 * @param[in] aClass The class of the resource record. 1291 * 1292 */ SetClass(uint16_t aClass)1293 void SetClass(uint16_t aClass) { mClass = HostSwap16(aClass); } 1294 1295 /** 1296 * This method returns the time to live field of the resource record. 1297 * 1298 * @returns The time to live field of the resource record. 1299 * 1300 */ GetTtl(void) const1301 uint32_t GetTtl(void) const { return HostSwap32(mTtl); } 1302 1303 /** 1304 * This method sets the time to live field of the resource record. 1305 * 1306 * @param[in] aTtl The time to live field of the resource record. 1307 * 1308 */ SetTtl(uint32_t aTtl)1309 void SetTtl(uint32_t aTtl) { mTtl = HostSwap32(aTtl); } 1310 1311 /** 1312 * This method returns the length of the resource record data. 1313 * 1314 * @returns The length of the resource record data. 1315 * 1316 */ GetLength(void) const1317 uint16_t GetLength(void) const { return HostSwap16(mLength); } 1318 1319 /** 1320 * This method sets the length of the resource record data. 1321 * 1322 * @param[in] aLength The length of the resource record data. 1323 * 1324 */ SetLength(uint16_t aLength)1325 void SetLength(uint16_t aLength) { mLength = HostSwap16(aLength); } 1326 1327 /** 1328 * This method returns the size of (number of bytes) in resource record and its data RDATA section (excluding the 1329 * name field). 1330 * 1331 * @returns Size (number of bytes) of resource record and its data section (excluding the name field) 1332 * 1333 */ GetSize(void) const1334 uint32_t GetSize(void) const { return sizeof(ResourceRecord) + GetLength(); } 1335 1336 /** 1337 * This static method parses and skips over a given number of resource records in a message from a given offset. 1338 * 1339 * @param[in] aMessage The message from which to parse/read the resource records. `aMessage.GetOffset()` 1340 * MUST point to the start of DNS header. 1341 * @param[in,out] aOffset On input the offset in @p aMessage pointing to the start of the first record. 1342 * On exit (when parsed successfully), @p aOffset is updated to point to the byte after 1343 * the last parsed record. 1344 * @param[in] aNumRecords Number of resource records to parse. 1345 * 1346 * @retval kErrorNone Parsed records successfully. @p aOffset is updated. 1347 * @retval kErrorParse Could not parse the records from @p aMessage (e.g., ran out of bytes in @p aMessage). 1348 * 1349 */ 1350 static Error ParseRecords(const Message &aMessage, uint16_t &aOffset, uint16_t aNumRecords); 1351 1352 /** 1353 * This static method searches in a given message to find the first resource record matching a given record name. 1354 * 1355 * @param[in] aMessage The message in which to search for a matching resource record. 1356 * `aMessage.GetOffset()` MUST point to the start of DNS header. 1357 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the first record. 1358 * On exit, if a matching record is found, @p aOffset is updated to point to the byte 1359 * after the record name. 1360 * If a matching record could not be found, @p aOffset is updated to point to the byte 1361 * after the last record that was checked. 1362 * @param[in,out] aNumRecords On input, the maximum number of records to check (starting from @p aOffset). 1363 * On exit and if a matching record is found, @p aNumRecords is updated to give the 1364 * number of remaining records after @p aOffset (excluding the matching record). 1365 * @param[in] aName The record name to match against. 1366 * 1367 * @retval kErrorNone A matching record was found. @p aOffset, @p aNumRecords are updated. 1368 * @retval kErrorNotFound A matching record could not be found. @p aOffset and @p aNumRecords are updated. 1369 * @retval kErrorParse Could not parse records from @p aMessage (e.g., ran out of bytes in @p aMessage). 1370 * 1371 */ 1372 static Error FindRecord(const Message &aMessage, uint16_t &aOffset, uint16_t &aNumRecords, const Name &aName); 1373 1374 /** 1375 * This template static method searches in a message to find the i-th occurrence of resource records of specific 1376 * type with a given record name and if found, reads the record from the message. 1377 * 1378 * This method searches in @p aMessage starting from @p aOffset up to maximum of @p aNumRecords, for the 1379 * `(aIndex+1)`th occurrence of a resource record of `RecordType` with record name @p aName. 1380 * 1381 * On success (i.e., when a matching record is found and read from the message), @p aOffset is updated to point 1382 * to after the last byte read from the message and copied into @p aRecord. This allows the caller to read any 1383 * remaining fields in the record data. 1384 * 1385 * @tparam RecordType The resource record type (i.e., a sub-class of `ResourceRecord`). 1386 * 1387 * @param[in] aMessage The message to search within for matching resource records. 1388 * `aMessage.GetOffset()` MUST point to the start of DNS header. 1389 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the start of the first record. 1390 * On exit and only if a matching record is found, @p aOffset is updated to point to 1391 * the last read byte in the record (allowing caller to read any remaining fields in 1392 * the record data from the message). 1393 * @param[in] aNumRecords The maximum number of records to check (starting from @p aOffset). 1394 * @param[in] aIndex The matching record index to find. @p aIndex value of zero returns the first 1395 * matching record. 1396 * @param[in] aName The record name to match against. 1397 * @param[in] aRecord A reference to a record object to read a matching record into. 1398 * If a matching record is found, `sizeof(RecordType)` bytes from @p aMessage are 1399 * read and copied into @p aRecord. 1400 * 1401 * @retval kErrorNone A matching record was found. @p aOffset is updated. 1402 * @retval kErrorNotFound A matching record could not be found. 1403 * @retval kErrorParse Could not parse records from @p aMessage (e.g., ran out of bytes in @p aMessage). 1404 * 1405 */ 1406 template <class RecordType> FindRecord(const Message & aMessage,uint16_t & aOffset,uint16_t aNumRecords,uint16_t aIndex,const Name & aName,RecordType & aRecord)1407 static Error FindRecord(const Message &aMessage, 1408 uint16_t & aOffset, 1409 uint16_t aNumRecords, 1410 uint16_t aIndex, 1411 const Name & aName, 1412 RecordType & aRecord) 1413 { 1414 return FindRecord(aMessage, aOffset, aNumRecords, aIndex, aName, RecordType::kType, aRecord, 1415 sizeof(RecordType)); 1416 } 1417 1418 /** 1419 * This template static method tries to read a resource record of a given type from a message. If the record type 1420 * does not matches the type, it skips over the record. 1421 * 1422 * This method requires the record name to be already parsed/read from the message. On input, @p aOffset should 1423 * point to the start of the `ResourceRecord` fields (type, class, TTL, data length) in @p aMessage. 1424 * 1425 * This method verifies that the record is well-formed in the message. It then reads the record type and compares 1426 * it with `RecordType::kType` and ensures that the record size is at least `sizeof(RecordType)`. If it all matches, 1427 * the record is read into @p aRecord. 1428 * 1429 * On success (i.e., when a matching record is read from the message), the @p aOffset is updated to point to after 1430 * the last byte read from the message and copied into @p aRecord and not necessarily the end of the record. 1431 * Depending on the `RecordType` format, there may still be more data bytes left in the record to be read. For 1432 * example, when reading a SRV record using `SrvRecord` type, @p aOffset would point to after the last field in 1433 * `SrvRecord` which is the start of "target host domain name" field. 1434 * 1435 * @tparam RecordType The resource record type (i.e., a sub-class of `ResourceRecord`). 1436 * 1437 * @param[in] aMessage The message from which to read the record. 1438 * @param[in,out] aOffset On input, the offset in @p aMessage pointing to the byte after the record name. 1439 * On exit, if a matching record is read, @p aOffset is updated to point to the last 1440 * read byte in the record. 1441 * If a matching record could not be read, @p aOffset is updated to point to the byte 1442 * after the entire record (skipping over the record). 1443 * @param[out] aRecord A reference to a record to read a matching record into. 1444 * If a matching record is found, `sizeof(RecordType)` bytes from @p aMessage are 1445 * read and copied into @p aRecord. 1446 * 1447 * @retval kErrorNone A matching record was read successfully. @p aOffset, and @p aRecord are updated. 1448 * @retval kErrorNotFound A matching record could not be found. @p aOffset is updated. 1449 * @retval kErrorParse Could not parse records from @p aMessage (e.g., ran out of bytes in @p aMessage). 1450 * 1451 */ ReadRecord(const Message & aMessage,uint16_t & aOffset,RecordType & aRecord)1452 template <class RecordType> static Error ReadRecord(const Message &aMessage, uint16_t &aOffset, RecordType &aRecord) 1453 { 1454 return ReadRecord(aMessage, aOffset, RecordType::kType, aRecord, sizeof(RecordType)); 1455 } 1456 1457 protected: 1458 Error ReadName(const Message &aMessage, 1459 uint16_t & aOffset, 1460 uint16_t aStartOffset, 1461 char * aNameBuffer, 1462 uint16_t aNameBufferSize, 1463 bool aSkipRecord) const; 1464 Error SkipRecord(const Message &aMessage, uint16_t &aOffset) const; 1465 1466 private: 1467 static constexpr uint16_t kType = kTypeAny; // This is intended for used by `ReadRecord<RecordType>()` only. 1468 1469 static Error FindRecord(const Message & aMessage, 1470 uint16_t & aOffset, 1471 uint16_t aNumRecords, 1472 uint16_t aIndex, 1473 const Name & aName, 1474 uint16_t aType, 1475 ResourceRecord &aRecord, 1476 uint16_t aMinRecordSize); 1477 1478 static Error ReadRecord(const Message & aMessage, 1479 uint16_t & aOffset, 1480 uint16_t aType, 1481 ResourceRecord &aRecord, 1482 uint16_t aMinRecordSize); 1483 1484 Error CheckRecord(const Message &aMessage, uint16_t aOffset) const; 1485 Error ReadFrom(const Message &aMessage, uint16_t aOffset); 1486 1487 uint16_t mType; // The type of the data in RDATA section. 1488 uint16_t mClass; // The class of the data in RDATA section. 1489 uint32_t mTtl; // Specifies the maximum time that the resource record may be cached. 1490 uint16_t mLength; // The length of RDATA section in bytes. 1491 1492 } OT_TOOL_PACKED_END; 1493 1494 /** 1495 * This class implements Resource Record body format of A type. 1496 * 1497 */ 1498 OT_TOOL_PACKED_BEGIN 1499 class ARecord : public ResourceRecord 1500 { 1501 public: 1502 static constexpr uint16_t kType = kTypeA; ///< The A record type. 1503 1504 /** 1505 * This method initializes the A Resource Record by setting its type, class, and length. 1506 * 1507 * Other record fields (TTL, address) remain unchanged/uninitialized. 1508 * 1509 */ Init(void)1510 void Init(void) 1511 { 1512 ResourceRecord::Init(kTypeA); 1513 SetLength(sizeof(Ip4::Address)); 1514 } 1515 1516 /** 1517 * This method sets the IPv4 address of the resource record. 1518 * 1519 * @param[in] aAddress The IPv4 address of the resource record. 1520 * 1521 */ SetAddress(const Ip4::Address & aAddress)1522 void SetAddress(const Ip4::Address &aAddress) { mAddress = aAddress; } 1523 1524 /** 1525 * This method returns the reference to IPv4 address of the resource record. 1526 * 1527 * @returns The reference to IPv4 address of the resource record. 1528 * 1529 */ GetAddress(void) const1530 const Ip4::Address &GetAddress(void) const { return mAddress; } 1531 1532 private: 1533 Ip4::Address mAddress; // IPv4 Address of A Resource Record. 1534 } OT_TOOL_PACKED_END; 1535 1536 /** 1537 * This class implements Resource Record body format of CNAME type. 1538 * 1539 */ 1540 OT_TOOL_PACKED_BEGIN 1541 class CnameRecord : public ResourceRecord 1542 { 1543 public: 1544 static constexpr uint16_t kType = kTypeCname; ///< The CNAME record type. 1545 1546 /** 1547 * This method initializes the CNAME Resource Record by setting its type and class. 1548 * 1549 * Other record fields (TTL, length) remain unchanged/uninitialized. 1550 * 1551 * @param[in] aClass The class of the resource record (default is `kClassInternet`). 1552 * 1553 */ Init(uint16_t aClass=kClassInternet)1554 void Init(uint16_t aClass = kClassInternet) { ResourceRecord::Init(kTypeCname, aClass); } 1555 1556 /** 1557 * This method parses and reads the CNAME alias name from a message. 1558 * 1559 * This method also verifies that the CNAME record is well-formed (e.g., the record data length `GetLength()` 1560 * matches the CNAME encoded name). 1561 * 1562 * @param[in] aMessage The message to read from. `aMessage.GetOffset()` MUST point to the start of 1563 * DNS header. 1564 * @param[in,out] aOffset On input, the offset in @p aMessage to start of CNAME name field. 1565 * On exit when successfully read, @p aOffset is updated to point to the byte 1566 * after the entire PTR record (skipping over the record). 1567 * @param[out] aNameBuffer A pointer to a char array to output the read name as a null-terminated C string 1568 * (MUST NOT be `nullptr`). 1569 * @param[in] aNameBufferSize The size of @p aNameBuffer. 1570 * 1571 * @retval kErrorNone The CNAME name was read successfully. @p aOffset and @p aNameBuffer are updated. 1572 * @retval kErrorParse The CNAME record in @p aMessage could not be parsed (invalid format). 1573 * @retval kErrorNoBufs Name could not fit in @p aNameBufferSize chars. 1574 * 1575 */ ReadCanonicalName(const Message & aMessage,uint16_t & aOffset,char * aNameBuffer,uint16_t aNameBufferSize) const1576 Error ReadCanonicalName(const Message &aMessage, 1577 uint16_t & aOffset, 1578 char * aNameBuffer, 1579 uint16_t aNameBufferSize) const 1580 { 1581 return ResourceRecord::ReadName(aMessage, aOffset, /* aStartOffset */ aOffset - sizeof(CnameRecord), 1582 aNameBuffer, aNameBufferSize, /* aSkipRecord */ true); 1583 } 1584 1585 } OT_TOOL_PACKED_END; 1586 1587 /** 1588 * This class implements Resource Record body format of PTR type. 1589 * 1590 */ 1591 OT_TOOL_PACKED_BEGIN 1592 class PtrRecord : public ResourceRecord 1593 { 1594 public: 1595 static constexpr uint16_t kType = kTypePtr; ///< The PTR record type. 1596 1597 /** 1598 * This method initializes the PTR Resource Record by setting its type and class. 1599 * 1600 * Other record fields (TTL, length) remain unchanged/uninitialized. 1601 * 1602 * @param[in] aClass The class of the resource record (default is `kClassInternet`). 1603 * 1604 */ Init(uint16_t aClass=kClassInternet)1605 void Init(uint16_t aClass = kClassInternet) { ResourceRecord::Init(kTypePtr, aClass); } 1606 1607 /** 1608 * This method parses and reads the PTR name from a message. 1609 * 1610 * This method also verifies that the PTR record is well-formed (e.g., the record data length `GetLength()` matches 1611 * the PTR encoded name). 1612 * 1613 * @param[in] aMessage The message to read from. `aMessage.GetOffset()` MUST point to the start of 1614 * DNS header. 1615 * @param[in,out] aOffset On input, the offset in @p aMessage to start of PTR name field. 1616 * On exit when successfully read, @p aOffset is updated to point to the byte 1617 * after the entire PTR record (skipping over the record). 1618 * @param[out] aNameBuffer A pointer to a char array to output the read name as a null-terminated C string 1619 * (MUST NOT be `nullptr`). 1620 * @param[in] aNameBufferSize The size of @p aNameBuffer. 1621 * 1622 * @retval kErrorNone The PTR name was read successfully. @p aOffset and @p aNameBuffer are updated. 1623 * @retval kErrorParse The PTR record in @p aMessage could not be parsed (invalid format). 1624 * @retval kErrorNoBufs Name could not fit in @p aNameBufferSize chars. 1625 * 1626 */ ReadPtrName(const Message & aMessage,uint16_t & aOffset,char * aNameBuffer,uint16_t aNameBufferSize) const1627 Error ReadPtrName(const Message &aMessage, uint16_t &aOffset, char *aNameBuffer, uint16_t aNameBufferSize) const 1628 { 1629 return ResourceRecord::ReadName(aMessage, aOffset, /* aStartOffset */ aOffset - sizeof(PtrRecord), aNameBuffer, 1630 aNameBufferSize, 1631 /* aSkipRecord */ true); 1632 } 1633 1634 /** 1635 * This method parses and reads the PTR name from a message. 1636 * 1637 * This method also verifies that the PTR record is well-formed (e.g., the record data length `GetLength()` matches 1638 * the PTR encoded name). 1639 * 1640 * Unlike the previous method which reads the entire PTR name into a single char buffer, this method reads the 1641 * first label separately and into a different buffer @p aLabelBuffer and the rest of the name into @p aNameBuffer. 1642 * The @p aNameBuffer can be set to `nullptr` if the caller is only interested in the first label. This method is 1643 * intended for "Service Instance Name" where first label (`<Instance>` portion) can be a user-friendly string and 1644 * can contain dot character. 1645 * 1646 * @param[in] aMessage The message to read from. `aMessage.GetOffset()` MUST point to the start of 1647 * DNS header. 1648 * @param[in,out] aOffset On input, the offset in @p aMessage to the start of PTR name field. 1649 * On exit, when successfully read, @p aOffset is updated to point to the byte 1650 * after the entire PTR record (skipping over the record). 1651 * @param[out] aLabelBuffer A pointer to a char array to output the first label as a null-terminated C 1652 * string (MUST NOT be `nullptr`). 1653 * @param[in] aLabelBufferSize The size of @p aLabelBuffer. 1654 * @param[out] aNameBuffer A pointer to a char array to output the rest of name (after first label). Can 1655 * be `nullptr` if caller is only interested in the first label. 1656 * @param[in] aNameBufferSize The size of @p aNameBuffer. 1657 * 1658 * @retval kErrorNone The PTR name was read successfully. @p aOffset, @aLabelBuffer and @aNameBuffer are updated. 1659 * @retval kErrorParse The PTR record in @p aMessage could not be parsed (invalid format). 1660 * @retval kErrorNoBufs Either label or name could not fit in the related char buffers. 1661 * 1662 */ 1663 Error ReadPtrName(const Message &aMessage, 1664 uint16_t & aOffset, 1665 char * aLabelBuffer, 1666 uint8_t aLabelBufferSize, 1667 char * aNameBuffer, 1668 uint16_t aNameBufferSize) const; 1669 1670 } OT_TOOL_PACKED_END; 1671 1672 /** 1673 * This class implements Resource Record body format of TXT type. 1674 * 1675 */ 1676 OT_TOOL_PACKED_BEGIN 1677 class TxtRecord : public ResourceRecord 1678 { 1679 public: 1680 static constexpr uint16_t kType = kTypeTxt; ///< The TXT record type. 1681 1682 /** 1683 * This method initializes the TXT Resource Record by setting its type and class. 1684 * 1685 * Other record fields (TTL, length) remain unchanged/uninitialized. 1686 * 1687 * @param[in] aClass The class of the resource record (default is `kClassInternet`). 1688 * 1689 */ Init(uint16_t aClass=kClassInternet)1690 void Init(uint16_t aClass = kClassInternet) { ResourceRecord::Init(kTypeTxt, aClass); } 1691 1692 /** 1693 * This method parses and reads the TXT record data from a message. 1694 * 1695 * This method also checks if the TXT data is well-formed by calling `VerifyTxtData()`. 1696 * 1697 * @param[in] aMessage The message to read from. 1698 * @param[in,out] aOffset On input, the offset in @p aMessage to start of TXT record data. 1699 * On exit when successfully read, @p aOffset is updated to point to the byte 1700 * after the entire TXT record (skipping over the record). 1701 * @param[out] aTxtBuffer A pointer to a byte array to output the read TXT data. 1702 * @param[in,out] aTxtBufferSize On input, the size of @p aTxtBuffer (max bytes that can be read). 1703 * On exit, @p aTxtBufferSize gives number of bytes written to @p aTxtBuffer. 1704 * 1705 * @retval kErrorNone The TXT data was read successfully. @p aOffset, @p aTxtBuffer and @p aTxtBufferSize 1706 * are updated. 1707 * @retval kErrorParse The TXT record in @p aMessage could not be parsed (invalid format). 1708 * @retval kErrorNoBufs TXT data could not fit in @p aTxtBufferSize bytes. 1709 * 1710 */ 1711 Error ReadTxtData(const Message &aMessage, uint16_t &aOffset, uint8_t *aTxtBuffer, uint16_t &aTxtBufferSize) const; 1712 1713 /** 1714 * This static method tests if a buffer contains valid encoded TXT data. 1715 * 1716 * @param[in] aTxtData The TXT data buffer. 1717 * @param[in] aTxtLength The length of the TXT data buffer. 1718 * @param[in] aAllowEmpty True if zero-length TXT data is allowed. 1719 * 1720 * @returns TRUE if @p aTxtData contains valid encoded TXT data, FALSE if not. 1721 * 1722 */ 1723 static bool VerifyTxtData(const uint8_t *aTxtData, uint16_t aTxtLength, bool aAllowEmpty); 1724 1725 } OT_TOOL_PACKED_END; 1726 1727 /** 1728 * This class implements Resource Record body format of AAAA type. 1729 * 1730 */ 1731 OT_TOOL_PACKED_BEGIN 1732 class AaaaRecord : public ResourceRecord 1733 { 1734 public: 1735 static constexpr uint16_t kType = kTypeAaaa; ///< The AAAA record type. 1736 1737 /** 1738 * This method initializes the AAAA Resource Record by setting its type, class, and length. 1739 * 1740 * Other record fields (TTL, address) remain unchanged/uninitialized. 1741 * 1742 */ Init(void)1743 void Init(void) 1744 { 1745 ResourceRecord::Init(kTypeAaaa); 1746 SetLength(sizeof(Ip6::Address)); 1747 } 1748 1749 /** 1750 * This method tells whether this is a valid AAAA record. 1751 * 1752 * @returns A boolean indicates whether this is a valid AAAA record. 1753 * 1754 */ 1755 bool IsValid(void) const; 1756 1757 /** 1758 * This method sets the IPv6 address of the resource record. 1759 * 1760 * @param[in] aAddress The IPv6 address of the resource record. 1761 * 1762 */ SetAddress(const Ip6::Address & aAddress)1763 void SetAddress(const Ip6::Address &aAddress) { mAddress = aAddress; } 1764 1765 /** 1766 * This method returns the reference to IPv6 address of the resource record. 1767 * 1768 * @returns The reference to IPv6 address of the resource record. 1769 * 1770 */ GetAddress(void) const1771 const Ip6::Address &GetAddress(void) const { return mAddress; } 1772 1773 private: 1774 Ip6::Address mAddress; // IPv6 Address of AAAA Resource Record. 1775 } OT_TOOL_PACKED_END; 1776 1777 /** 1778 * This class implements Resource Record body format of SRV type (RFC 2782). 1779 * 1780 */ 1781 OT_TOOL_PACKED_BEGIN 1782 class SrvRecord : public ResourceRecord 1783 { 1784 public: 1785 static constexpr uint16_t kType = kTypeSrv; ///< The SRV record type. 1786 1787 /** 1788 * This method initializes the SRV Resource Record by settings its type and class. 1789 * 1790 * Other record fields (TTL, length, propriety, weight, port, ...) remain unchanged/uninitialized. 1791 * 1792 * @param[in] aClass The class of the resource record (default is `kClassInternet`). 1793 * 1794 */ Init(uint16_t aClass=kClassInternet)1795 void Init(uint16_t aClass = kClassInternet) { ResourceRecord::Init(kTypeSrv, aClass); } 1796 1797 /** 1798 * This method returns the SRV record's priority value. 1799 * 1800 * @returns The priority value. 1801 * 1802 */ GetPriority(void) const1803 uint16_t GetPriority(void) const { return HostSwap16(mPriority); } 1804 1805 /** 1806 * This method sets the SRV record's priority value. 1807 * 1808 * @param[in] aPriority The priority value. 1809 * 1810 */ SetPriority(uint16_t aPriority)1811 void SetPriority(uint16_t aPriority) { mPriority = HostSwap16(aPriority); } 1812 1813 /** 1814 * This method returns the SRV record's weight value. 1815 * 1816 * @returns The weight value. 1817 * 1818 */ GetWeight(void) const1819 uint16_t GetWeight(void) const { return HostSwap16(mWeight); } 1820 1821 /** 1822 * This method sets the SRV record's weight value. 1823 * 1824 * @param[in] aWeight The weight value. 1825 * 1826 */ SetWeight(uint16_t aWeight)1827 void SetWeight(uint16_t aWeight) { mWeight = HostSwap16(aWeight); } 1828 1829 /** 1830 * This method returns the SRV record's port number on the target host for this service. 1831 * 1832 * @returns The port number. 1833 * 1834 */ GetPort(void) const1835 uint16_t GetPort(void) const { return HostSwap16(mPort); } 1836 1837 /** 1838 * This method sets the SRV record's port number on the target host for this service. 1839 * 1840 * @param[in] aPort The port number. 1841 * 1842 */ SetPort(uint16_t aPort)1843 void SetPort(uint16_t aPort) { mPort = HostSwap16(aPort); } 1844 1845 /** 1846 * This method parses and reads the SRV target host name from a message. 1847 * 1848 * This method also verifies that the SRV record is well-formed (e.g., the record data length `GetLength()` matches 1849 * the SRV encoded name). 1850 * 1851 * @param[in] aMessage The message to read from. `aMessage.GetOffset()` MUST point to the start of 1852 * DNS header. 1853 * @param[in,out] aOffset On input, the offset in @p aMessage to start of target host name field. 1854 * On exit when successfully read, @p aOffset is updated to point to the byte 1855 * after the entire SRV record (skipping over the record). 1856 * @param[out] aNameBuffer A pointer to a char array to output the read name as a null-terminated C string 1857 * (MUST NOT be `nullptr`). 1858 * @param[in] aNameBufferSize The size of @p aNameBuffer. 1859 * 1860 * @retval kErrorNone The host name was read successfully. @p aOffset and @p aNameBuffer are updated. 1861 * @retval kErrorParse The SRV record in @p aMessage could not be parsed (invalid format). 1862 * @retval kErrorNoBufs Name could not fit in @p aNameBufferSize chars. 1863 * 1864 */ ReadTargetHostName(const Message & aMessage,uint16_t & aOffset,char * aNameBuffer,uint16_t aNameBufferSize) const1865 Error ReadTargetHostName(const Message &aMessage, 1866 uint16_t & aOffset, 1867 char * aNameBuffer, 1868 uint16_t aNameBufferSize) const 1869 { 1870 return ResourceRecord::ReadName(aMessage, aOffset, /* aStartOffset */ aOffset - sizeof(SrvRecord), aNameBuffer, 1871 aNameBufferSize, 1872 /* aSkipRecord */ true); 1873 } 1874 1875 private: 1876 uint16_t mPriority; 1877 uint16_t mWeight; 1878 uint16_t mPort; 1879 // Followed by the target host domain name. 1880 1881 } OT_TOOL_PACKED_END; 1882 1883 /** 1884 * This class implements Resource Record body format of KEY type (RFC 2535). 1885 * 1886 */ 1887 OT_TOOL_PACKED_BEGIN 1888 class KeyRecord : public ResourceRecord 1889 { 1890 public: 1891 static constexpr uint16_t kType = kTypeKey; ///< The KEY record type. 1892 1893 // Protocol field values (RFC 2535 - section 3.1.3). 1894 static constexpr uint8_t kProtocolTls = 1; ///< TLS protocol code. 1895 static constexpr uint8_t kProtocolDnsSec = 3; ///< DNS security protocol code. 1896 1897 // Algorithm field values (RFC 8624 - section 3.1). 1898 static constexpr uint8_t kAlgorithmEcdsaP256Sha256 = 13; ///< ECDSA-P256-SHA256 algorithm. 1899 static constexpr uint8_t kAlgorithmEcdsaP384Sha384 = 14; ///< ECDSA-P384-SHA384 algorithm. 1900 static constexpr uint8_t kAlgorithmEd25519 = 15; ///< ED25519 algorithm. 1901 static constexpr uint8_t kAlgorithmEd448 = 16; ///< ED448 algorithm. 1902 1903 /** 1904 * This enumeration type represents the use (or key type) flags (RFC 2535 - section 3.1.2). 1905 * 1906 */ 1907 enum UseFlags : uint8_t 1908 { 1909 kAuthConfidPermitted = 0x00, ///< Use of the key for authentication and/or confidentiality is permitted. 1910 kAuthPermitted = 0x40, ///< Use of the key is only permitted for authentication. 1911 kConfidPermitted = 0x80, ///< Use of the key is only permitted for confidentiality. 1912 kNoKey = 0xc0, ///< No key value (e.g., can indicate zone is not secure). 1913 }; 1914 1915 /** 1916 * This enumeration type represents key owner (or name type) flags (RFC 2535 - section 3.1.2). 1917 * 1918 */ 1919 enum OwnerFlags : uint8_t 1920 { 1921 kOwnerUser = 0x00, ///< Key is associated with a "user" or "account" at end entity. 1922 kOwnerZone = 0x01, ///< Key is a zone key (used for data origin authentication). 1923 kOwnerNonZone = 0x02, ///< Key is associated with a non-zone "entity". 1924 kOwnerReserved = 0x03, ///< Reserved for future use. 1925 }; 1926 1927 // Constants for flag bits for the "signatory" flags (RFC 2137). 1928 // 1929 // The flags defined are for non-zone (`kOwnerNoneZone`) keys (RFC 2137 - section 3.1.3). 1930 1931 /** 1932 * Key is authorized to attach, detach, and move zones. 1933 * 1934 */ 1935 static constexpr uint8_t kSignatoryFlagZone = 1 << 3; 1936 1937 /** 1938 * Key is authorized to add and delete RRs even if RRs auth with other key. 1939 * 1940 */ 1941 static constexpr uint8_t kSignatoryFlagStrong = 1 << 2; 1942 1943 /** 1944 * Key is authorized to add and update RRs for only a single owner name. 1945 * 1946 */ 1947 static constexpr uint8_t kSignatoryFlagUnique = 1 << 1; 1948 1949 /** 1950 * If the other flags are zero, this is used to indicate it is an update key. 1951 * 1952 */ 1953 static constexpr uint8_t kSignatoryFlagGeneral = 1 << 0; 1954 1955 /** 1956 * This method initializes the KEY Resource Record by setting its type and class. 1957 * 1958 * Other record fields (TTL, length, flags, protocol, algorithm) remain unchanged/uninitialized. 1959 * 1960 * @param[in] aClass The class of the resource record (default is `kClassInternet`). 1961 * 1962 */ Init(uint16_t aClass=kClassInternet)1963 void Init(uint16_t aClass = kClassInternet) { ResourceRecord::Init(kTypeKey, aClass); } 1964 1965 /** 1966 * This method tells whether the KEY record is valid. 1967 * 1968 * @returns TRUE if this is a valid KEY record, FALSE if an invalid KEY record. 1969 * 1970 */ 1971 bool IsValid(void) const; 1972 1973 /** 1974 * This method gets the key use (or key type) flags. 1975 * 1976 * @returns The key use flags. 1977 * 1978 */ GetUseFlags(void) const1979 UseFlags GetUseFlags(void) const { return static_cast<UseFlags>(mFlags[0] & kUseFlagsMask); } 1980 1981 /** 1982 * This method gets the owner (or name type) flags. 1983 * 1984 * @returns The key owner flags. 1985 * 1986 */ GetOwnerFlags(void) const1987 OwnerFlags GetOwnerFlags(void) const { return static_cast<OwnerFlags>(mFlags[0] & kOwnerFlagsMask); } 1988 1989 /** 1990 * This method gets the signatory flags. 1991 * 1992 * @returns The signatory flags. 1993 * 1994 */ GetSignatoryFlags(void) const1995 uint8_t GetSignatoryFlags(void) const { return (mFlags[1] & kSignatoryFlagsMask); } 1996 1997 /** 1998 * This method sets the flags field. 1999 * 2000 * @param[in] aUseFlags The `UseFlags` value. 2001 * @param[in] aOwnerFlags The `OwnerFlags` value. 2002 * @param[in] aSignatoryFlags The signatory flags. 2003 * 2004 */ SetFlags(UseFlags aUseFlags,OwnerFlags aOwnerFlags,uint8_t aSignatoryFlags)2005 void SetFlags(UseFlags aUseFlags, OwnerFlags aOwnerFlags, uint8_t aSignatoryFlags) 2006 { 2007 mFlags[0] = (static_cast<uint8_t>(aUseFlags) | static_cast<uint8_t>(aOwnerFlags)); 2008 mFlags[1] = (aSignatoryFlags & kSignatoryFlagsMask); 2009 } 2010 2011 /** 2012 * This method returns the KEY record's protocol value. 2013 * 2014 * @returns The protocol value. 2015 * 2016 */ GetProtocol(void) const2017 uint8_t GetProtocol(void) const { return mProtocol; } 2018 2019 /** 2020 * This method sets the KEY record's protocol value. 2021 * 2022 * @param[in] aProtocol The protocol value. 2023 * 2024 */ SetProtocol(uint8_t aProtocol)2025 void SetProtocol(uint8_t aProtocol) { mProtocol = aProtocol; } 2026 2027 /** 2028 * This method returns the KEY record's algorithm value. 2029 * 2030 * @returns The algorithm value. 2031 * 2032 */ GetAlgorithm(void) const2033 uint8_t GetAlgorithm(void) const { return mAlgorithm; } 2034 2035 /** 2036 * This method sets the KEY record's algorithm value. 2037 * 2038 * @param[in] aAlgorithm The algorithm value. 2039 * 2040 */ SetAlgorithm(uint8_t aAlgorithm)2041 void SetAlgorithm(uint8_t aAlgorithm) { mAlgorithm = aAlgorithm; } 2042 2043 private: 2044 static constexpr uint8_t kUseFlagsMask = 0xc0; // top two bits in the first flag byte. 2045 static constexpr uint8_t kOwnerFlagsMask = 0x03; // lowest two bits in the first flag byte. 2046 static constexpr uint8_t kSignatoryFlagsMask = 0x0f; // lower 4 bits in the second flag byte. 2047 2048 // Flags format: 2049 // 2050 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 2051 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ 2052 // | Use | Z | XT| Z | Z | Owner | Z | Z | Z | Z | SIG | 2053 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ 2054 // \ / \ / 2055 // ---------- mFlags[0] --------- -------- mFlags[1] ---------- 2056 2057 uint8_t mFlags[2]; 2058 uint8_t mProtocol; 2059 uint8_t mAlgorithm; 2060 // Followed by the public key 2061 2062 } OT_TOOL_PACKED_END; 2063 2064 #if OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 2065 OT_TOOL_PACKED_BEGIN 2066 class Ecdsa256KeyRecord : public KeyRecord, public Clearable<Ecdsa256KeyRecord>, public Equatable<Ecdsa256KeyRecord> 2067 { 2068 public: 2069 /** 2070 * This method initializes the KEY Resource Record to ECDSA with curve P-256. 2071 * 2072 * Other record fields (TTL, length, flags, protocol) remain unchanged/uninitialized. 2073 * 2074 */ 2075 void Init(void); 2076 2077 /** 2078 * This method tells whether this is a valid ECDSA DNSKEY with curve P-256. 2079 * 2080 * @returns A boolean that indicates whether this is a valid ECDSA DNSKEY RR with curve P-256. 2081 * 2082 */ 2083 bool IsValid(void) const; 2084 2085 /** 2086 * This method returns the ECDSA P-256 public kek. 2087 * 2088 * @returns A reference to the public key. 2089 * 2090 */ GetKey(void) const2091 const Crypto::Ecdsa::P256::PublicKey &GetKey(void) const { return mKey; } 2092 2093 private: 2094 Crypto::Ecdsa::P256::PublicKey mKey; 2095 } OT_TOOL_PACKED_END; 2096 #endif // OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 2097 2098 /** 2099 * This class implements Resource Record body format of SIG type (RFC 2535 - section-4.1). 2100 * 2101 * 2102 */ 2103 OT_TOOL_PACKED_BEGIN 2104 class SigRecord : public ResourceRecord, public Clearable<SigRecord> 2105 { 2106 public: 2107 static constexpr uint16_t kType = kTypeSig; ///< The SIG record type. 2108 2109 /** 2110 * This method initializes the SIG Resource Record by setting its type and class. 2111 * 2112 * Other record fields (TTL, length, ...) remain unchanged/uninitialized. 2113 * 2114 * SIG(0) requires SIG RR to set class field as ANY or `kClassAny` (RFC 2931 - section 3). 2115 * 2116 * @param[in] aClass The class of the resource record. 2117 * 2118 */ Init(uint16_t aClass)2119 void Init(uint16_t aClass) { ResourceRecord::Init(kTypeSig, aClass); } 2120 2121 /** 2122 * This method tells whether the SIG record is valid. 2123 * 2124 * @returns TRUE if this is a valid SIG record, FALSE if not a valid SIG record. 2125 * 2126 */ 2127 bool IsValid(void) const; 2128 2129 /** 2130 * This method returns the SIG record's type-covered value. 2131 * 2132 * @returns The type-covered value. 2133 * 2134 */ GetTypeCovered(void) const2135 uint16_t GetTypeCovered(void) const { return HostSwap16(mTypeCovered); } 2136 2137 /** 2138 * This method sets the SIG record's type-covered value. 2139 * 2140 * @param[in] aTypeCovered The type-covered value. 2141 * 2142 */ SetTypeCovered(uint8_t aTypeCovered)2143 void SetTypeCovered(uint8_t aTypeCovered) { mTypeCovered = HostSwap16(aTypeCovered); } 2144 2145 /** 2146 * This method returns the SIG record's algorithm value. 2147 * 2148 * @returns The algorithm value. 2149 * 2150 */ GetAlgorithm(void) const2151 uint8_t GetAlgorithm(void) const { return mAlgorithm; } 2152 2153 /** 2154 * This method sets the SIG record's algorithm value. 2155 * 2156 * @param[in] aAlgorithm The algorithm value. 2157 * 2158 */ SetAlgorithm(uint8_t aAlgorithm)2159 void SetAlgorithm(uint8_t aAlgorithm) { mAlgorithm = aAlgorithm; } 2160 2161 /** 2162 * This method returns the SIG record's labels-count (number of labels, not counting null label, in the original 2163 * name of the owner). 2164 * 2165 * @returns The labels-count value. 2166 * 2167 */ GetLabels(void) const2168 uint8_t GetLabels(void) const { return mLabels; } 2169 2170 /** 2171 * This method sets the SIG record's labels-count (number of labels, not counting null label, in the original 2172 * name of the owner). 2173 * 2174 * @param[in] aLabels The labels-count value. 2175 * 2176 */ SetLabels(uint8_t aLabels)2177 void SetLabels(uint8_t aLabels) { mLabels = aLabels; } 2178 2179 /** 2180 * This method returns the SIG record's original TTL value. 2181 * 2182 * @returns The original TTL value. 2183 * 2184 */ GetOriginalTtl(void) const2185 uint32_t GetOriginalTtl(void) const { return HostSwap32(mOriginalTtl); } 2186 2187 /** 2188 * This method sets the SIG record's original TTL value. 2189 * 2190 * @param[in] aOriginalTtl The original TTL value. 2191 * 2192 */ SetOriginalTtl(uint32_t aOriginalTtl)2193 void SetOriginalTtl(uint32_t aOriginalTtl) { mOriginalTtl = HostSwap32(aOriginalTtl); } 2194 2195 /** 2196 * This method returns the SIG record's expiration time value. 2197 * 2198 * @returns The expiration time value (seconds since Jan 1, 1970). 2199 * 2200 */ GetExpiration(void) const2201 uint32_t GetExpiration(void) const { return HostSwap32(mExpiration); } 2202 2203 /** 2204 * This method sets the SIG record's expiration time value. 2205 * 2206 * @param[in] aExpiration The expiration time value (seconds since Jan 1, 1970). 2207 * 2208 */ SetExpiration(uint32_t aExpiration)2209 void SetExpiration(uint32_t aExpiration) { mExpiration = HostSwap32(aExpiration); } 2210 2211 /** 2212 * This method returns the SIG record's inception time value. 2213 * 2214 * @returns The inception time value (seconds since Jan 1, 1970). 2215 * 2216 */ GetInception(void) const2217 uint32_t GetInception(void) const { return HostSwap32(mInception); } 2218 2219 /** 2220 * This method sets the SIG record's inception time value. 2221 * 2222 * @param[in] aInception The inception time value (seconds since Jan 1, 1970). 2223 * 2224 */ SetInception(uint32_t aInception)2225 void SetInception(uint32_t aInception) { mInception = HostSwap32(aInception); } 2226 2227 /** 2228 * This method returns the SIG record's key tag value. 2229 * 2230 * @returns The key tag value. 2231 * 2232 */ GetKeyTag(void) const2233 uint16_t GetKeyTag(void) const { return HostSwap16(mKeyTag); } 2234 2235 /** 2236 * This method sets the SIG record's key tag value. 2237 * 2238 * @param[in] aKeyTag The key tag value. 2239 * 2240 */ SetKeyTag(uint16_t aKeyTag)2241 void SetKeyTag(uint16_t aKeyTag) { mKeyTag = HostSwap16(aKeyTag); } 2242 2243 /** 2244 * This method returns a pointer to the start of the record data fields. 2245 * 2246 * @returns A pointer to the start of the record data fields. 2247 * 2248 */ GetRecordData(void) const2249 const uint8_t *GetRecordData(void) const { return reinterpret_cast<const uint8_t *>(&mTypeCovered); } 2250 2251 /** 2252 * This method parses and reads the SIG signer name from a message. 2253 * 2254 * @param[in] aMessage The message to read from. `aMessage.GetOffset()` MUST point to the start of DNS 2255 * header. 2256 * @param[in,out] aOffset On input, the offset in @p aMessage to start of signer name field. 2257 * On exit when successfully read, @p aOffset is updated to point to the byte 2258 * after the name field (i.e., start of signature field). 2259 * @param[out] aNameBuffer A pointer to a char array to output the read name as a null-terminated C string 2260 * (MUST NOT be `nullptr`). 2261 * @param[in] aNameBufferSize The size of @p aNameBuffer. 2262 * 2263 * @retval kErrorNone The name was read successfully. @p aOffset and @p aNameBuffer are updated. 2264 * @retval kErrorParse The SIG record in @p aMessage could not be parsed (invalid format). 2265 * @retval kErrorNoBufs Name could not fit in @p aNameBufferSize chars. 2266 * 2267 */ ReadSignerName(const Message & aMessage,uint16_t & aOffset,char * aNameBuffer,uint16_t aNameBufferSize) const2268 Error ReadSignerName(const Message &aMessage, uint16_t &aOffset, char *aNameBuffer, uint16_t aNameBufferSize) const 2269 { 2270 return ResourceRecord::ReadName(aMessage, aOffset, /* aStartOffset */ aOffset - sizeof(SigRecord), aNameBuffer, 2271 aNameBufferSize, 2272 /* aSkipRecord */ false); 2273 } 2274 2275 private: 2276 uint16_t mTypeCovered; // type of the other RRs covered by this SIG. set to zero for SIG(0). 2277 uint8_t mAlgorithm; // Algorithm number (see `KeyRecord` enumeration). 2278 uint8_t mLabels; // Number of labels (not counting null label) in the original name of the owner of RR. 2279 uint32_t mOriginalTtl; // Original time-to-live (should set to zero for SIG(0)). 2280 uint32_t mExpiration; // Signature expiration time (seconds since Jan 1, 1970). 2281 uint32_t mInception; // Signature inception time (seconds since Jan 1, 1970). 2282 uint16_t mKeyTag; // Key tag. 2283 // Followed by signer name fields and signature fields 2284 } OT_TOOL_PACKED_END; 2285 2286 /** 2287 * This class implements DNS OPT Pseudo Resource Record header for EDNS(0) (RFC 6891 - Section 6.1). 2288 * 2289 */ 2290 OT_TOOL_PACKED_BEGIN 2291 class OptRecord : public ResourceRecord 2292 { 2293 public: 2294 static constexpr uint16_t kType = kTypeOpt; ///< The OPT record type. 2295 2296 /** 2297 * This method initializes the OPT Resource Record by setting its type and clearing extended Response Code, version 2298 * and all flags. 2299 * 2300 * Other record fields (UDP payload size, length) remain unchanged/uninitialized. 2301 * 2302 */ Init(void)2303 void Init(void) 2304 { 2305 SetType(kTypeOpt); 2306 SetTtl(0); 2307 } 2308 2309 /** 2310 * This method gets the requester's UDP payload size (the number of bytes of the largest UDP payload that can be 2311 * delivered in the requester's network). 2312 * 2313 * The field is encoded in the CLASS field. 2314 * 2315 * @returns The UDP payload size. 2316 * 2317 */ GetUdpPayloadSize(void) const2318 uint16_t GetUdpPayloadSize(void) const { return GetClass(); } 2319 2320 /** 2321 * This method gets the requester's UDP payload size (the number of bytes of the largest UDP payload that can be 2322 * delivered in the requester's network). 2323 * 2324 * @param[in] aPayloadSize The UDP payload size. 2325 * 2326 */ SetUdpPayloadSize(uint16_t aPayloadSize)2327 void SetUdpPayloadSize(uint16_t aPayloadSize) { SetClass(aPayloadSize); } 2328 2329 /** 2330 * This method gets the upper 8-bit of the extended 12-bit Response Code. 2331 * 2332 * Value of 0 indicates that an unextended Response code is in use. 2333 * 2334 * @return The upper 8-bit of the extended 12-bit Response Code. 2335 * 2336 */ GetExtendedResponseCode(void) const2337 uint8_t GetExtendedResponseCode(void) const { return GetTtlByteAt(kExtRCodeByteIndex); } 2338 2339 /** 2340 * This method sets the upper 8-bit of the extended 12-bit Response Code. 2341 * 2342 * Value of 0 indicates that an unextended Response code is in use. 2343 * 2344 * @param[in] aExtendedResponse The upper 8-bit of the extended 12-bit Response Code. 2345 * 2346 */ SetExtnededResponseCode(uint8_t aExtendedResponse)2347 void SetExtnededResponseCode(uint8_t aExtendedResponse) { GetTtlByteAt(kExtRCodeByteIndex) = aExtendedResponse; } 2348 2349 /** 2350 * This method gets the Version field. 2351 * 2352 * @returns The version. 2353 * 2354 */ GetVersion(void) const2355 uint8_t GetVersion(void) const { return GetTtlByteAt(kVersionByteIndex); } 2356 2357 /** 2358 * This method set the Version field. 2359 * 2360 * @param[in] aVersion The version. 2361 * 2362 */ SetVersion(uint8_t aVersion)2363 void SetVersion(uint8_t aVersion) { GetTtlByteAt(kVersionByteIndex) = aVersion; } 2364 2365 /** 2366 * This method indicates whether the DNSSEC OK flag is set or not. 2367 * 2368 * @returns True if DNSSEC OK flag is set in the header, false otherwise. 2369 * 2370 */ IsDnsSecurityFlagSet(void) const2371 bool IsDnsSecurityFlagSet(void) const { return (GetTtlByteAt(kFlagByteIndex) & kDnsSecFlag) != 0; } 2372 2373 /** 2374 * This method clears the DNSSEC OK bit flag. 2375 * 2376 */ ClearDnsSecurityFlag(void)2377 void ClearDnsSecurityFlag(void) { GetTtlByteAt(kFlagByteIndex) &= ~kDnsSecFlag; } 2378 2379 /** 2380 * This method sets the DNSSEC OK bit flag. 2381 * 2382 */ SetDnsSecurityFlag(void)2383 void SetDnsSecurityFlag(void) { GetTtlByteAt(kFlagByteIndex) |= kDnsSecFlag; } 2384 2385 private: 2386 // The OPT RR re-purposes the existing CLASS and TTL fields in the 2387 // RR. The CLASS field (`uint16_t`) is used for requester UDP 2388 // payload size. The TTL field is used for extended Response Code, 2389 // version and flags as follows: 2390 // 2391 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 2392 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ 2393 // | EXTENDED-RCODE | VERSION | 2394 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ 2395 // | DO| Z | Z | 2396 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ 2397 // 2398 // The variable data part of OPT RR can contain zero of more `Option`. 2399 2400 static constexpr uint8_t kExtRCodeByteIndex = 0; // Byte index of Extended RCODE within the TTL field. 2401 static constexpr uint8_t kVersionByteIndex = 1; // Byte index of Version within the TTL field. 2402 static constexpr uint8_t kFlagByteIndex = 2; // Byte index of flag byte within the TTL field. 2403 static constexpr uint8_t kDnsSecFlag = 1 << 7; // DNSSec OK bit flag. 2404 GetTtlByteAt(uint8_t aIndex) const2405 uint8_t GetTtlByteAt(uint8_t aIndex) const { return reinterpret_cast<const uint8_t *>(&mTtl)[aIndex]; } GetTtlByteAt(uint8_t aIndex)2406 uint8_t &GetTtlByteAt(uint8_t aIndex) { return reinterpret_cast<uint8_t *>(&mTtl)[aIndex]; } 2407 2408 } OT_TOOL_PACKED_END; 2409 2410 /** 2411 * This class implements the body of an Option in OPT Pseudo Resource Record (RFC 6981 - Section 6.1). 2412 * 2413 */ 2414 OT_TOOL_PACKED_BEGIN 2415 class Option 2416 { 2417 public: 2418 static constexpr uint16_t kUpdateLease = 2; ///< Update lease option code. 2419 2420 /** 2421 * This method returns the option code value. 2422 * 2423 * @returns The option code value. 2424 * 2425 */ GetOptionCode(void) const2426 uint16_t GetOptionCode(void) const { return HostSwap16(mOptionCode); } 2427 2428 /** 2429 * This method sets the option code value. 2430 * 2431 * @param[in] aOptionCode The option code value. 2432 * 2433 */ SetOptionCode(uint16_t aOptionCode)2434 void SetOptionCode(uint16_t aOptionCode) { mOptionCode = HostSwap16(aOptionCode); } 2435 2436 /** 2437 * This method returns the option length value. 2438 * 2439 * @returns The option length (size of option data in bytes). 2440 * 2441 */ GetOptionLength(void) const2442 uint16_t GetOptionLength(void) const { return HostSwap16(mOptionLength); } 2443 2444 /** 2445 * This method sets the option length value. 2446 * 2447 * @param[in] aOptionLength The option length (size of option data in bytes). 2448 * 2449 */ SetOptionLength(uint16_t aOptionLength)2450 void SetOptionLength(uint16_t aOptionLength) { mOptionLength = HostSwap16(aOptionLength); } 2451 2452 /** 2453 * This method returns the size of (number of bytes) in the Option and its data. 2454 * 2455 * @returns Size (number of bytes) of the Option its data section. 2456 * 2457 */ GetSize(void) const2458 uint32_t GetSize(void) const { return sizeof(Option) + GetOptionLength(); } 2459 2460 private: 2461 uint16_t mOptionCode; 2462 uint16_t mOptionLength; 2463 // Followed by Option data (varies per option code). 2464 2465 } OT_TOOL_PACKED_END; 2466 2467 /** 2468 * This class implements an Update Lease Option body. 2469 * 2470 * This implementation is intended for use in Dynamic DNS Update Lease Requests and Responses as specified in 2471 * https://tools.ietf.org/html/draft-sekar-dns-ul-02. 2472 * 2473 */ 2474 OT_TOOL_PACKED_BEGIN 2475 class LeaseOption : public Option 2476 { 2477 public: 2478 static constexpr uint16_t kOptionLength = sizeof(uint32_t) + sizeof(uint32_t); ///< lease and key lease values 2479 2480 /** 2481 * This method initialize the Update Lease Option by setting the Option Code and Option Length. 2482 * 2483 * The lease and key lease intervals remain unchanged/uninitialized. 2484 * 2485 */ Init(void)2486 void Init(void) 2487 { 2488 SetOptionCode(kUpdateLease); 2489 SetOptionLength(kOptionLength); 2490 } 2491 2492 /** 2493 * This method tells whether this is a valid Lease Option. 2494 * 2495 * @returns TRUE if this is a valid Lease Option, FALSE if not a valid Lease Option. 2496 * 2497 */ 2498 bool IsValid(void) const; 2499 2500 /** 2501 * This method returns the Update Lease OPT record's lease interval value. 2502 * 2503 * @returns The lease interval value (in seconds). 2504 * 2505 */ GetLeaseInterval(void) const2506 uint32_t GetLeaseInterval(void) const { return HostSwap32(mLeaseInterval); } 2507 2508 /** 2509 * This method sets the Update Lease OPT record's lease interval value. 2510 * 2511 * @param[in] aLeaseInterval The lease interval value. 2512 * 2513 */ SetLeaseInterval(uint32_t aLeaseInterval)2514 void SetLeaseInterval(uint32_t aLeaseInterval) { mLeaseInterval = HostSwap32(aLeaseInterval); } 2515 2516 /** 2517 * This method returns the Update Lease OPT record's key lease interval value. 2518 * 2519 * @returns The key lease interval value (in seconds). 2520 * 2521 */ GetKeyLeaseInterval(void) const2522 uint32_t GetKeyLeaseInterval(void) const { return HostSwap32(mKeyLeaseInterval); } 2523 2524 /** 2525 * This method sets the Update Lease OPT record's key lease interval value. 2526 * 2527 * @param[in] aKeyLeaseInterval The key lease interval value (in seconds). 2528 * 2529 */ SetKeyLeaseInterval(uint32_t aKeyLeaseInterval)2530 void SetKeyLeaseInterval(uint32_t aKeyLeaseInterval) { mKeyLeaseInterval = HostSwap32(aKeyLeaseInterval); } 2531 2532 private: 2533 uint32_t mLeaseInterval; 2534 uint32_t mKeyLeaseInterval; 2535 } OT_TOOL_PACKED_END; 2536 2537 /** 2538 * This class implements Question format. 2539 * 2540 */ 2541 OT_TOOL_PACKED_BEGIN 2542 class Question 2543 { 2544 public: 2545 /** 2546 * Default constructor for Question 2547 * 2548 */ 2549 Question(void) = default; 2550 2551 /** 2552 * Constructor for Question. 2553 * 2554 */ Question(uint16_t aType,uint16_t aClass=ResourceRecord::kClassInternet)2555 explicit Question(uint16_t aType, uint16_t aClass = ResourceRecord::kClassInternet) 2556 { 2557 SetType(aType); 2558 SetClass(aClass); 2559 } 2560 2561 /** 2562 * This method returns the type of the question. 2563 * 2564 * @returns The type of the question. 2565 * 2566 */ GetType(void) const2567 uint16_t GetType(void) const { return HostSwap16(mType); } 2568 2569 /** 2570 * This method sets the type of the question. 2571 * 2572 * @param[in] aType The type of the question. 2573 * 2574 */ SetType(uint16_t aType)2575 void SetType(uint16_t aType) { mType = HostSwap16(aType); } 2576 2577 /** 2578 * This method returns the class of the question. 2579 * 2580 * @returns The class of the question. 2581 * 2582 */ GetClass(void) const2583 uint16_t GetClass(void) const { return HostSwap16(mClass); } 2584 2585 /** 2586 * This method sets the class of the question. 2587 * 2588 * @param[in] aClass The class of the question. 2589 * 2590 */ SetClass(uint16_t aClass)2591 void SetClass(uint16_t aClass) { mClass = HostSwap16(aClass); } 2592 2593 private: 2594 uint16_t mType; // The type of the data in question section. 2595 uint16_t mClass; // The class of the data in question section. 2596 } OT_TOOL_PACKED_END; 2597 2598 /** 2599 * This class implements Zone section body for DNS Update (RFC 2136 - section 2.3). 2600 * 2601 */ 2602 OT_TOOL_PACKED_BEGIN 2603 class Zone : public Question 2604 { 2605 public: 2606 /** 2607 * Constructor for Zone. 2608 * 2609 * @param[in] aClass The class of the zone (default is `kClassInternet`). 2610 * 2611 */ Zone(uint16_t aClass=ResourceRecord::kClassInternet)2612 explicit Zone(uint16_t aClass = ResourceRecord::kClassInternet) 2613 : Question(ResourceRecord::kTypeSoa, aClass) 2614 { 2615 } 2616 } OT_TOOL_PACKED_END; 2617 2618 /** 2619 * @} 2620 * 2621 */ 2622 2623 } // namespace Dns 2624 2625 DefineCoreType(otDnsTxtEntry, Dns::TxtEntry); 2626 DefineCoreType(otDnsTxtEntryIterator, Dns::TxtEntry::Iterator); 2627 2628 } // namespace ot 2629 2630 #endif // DNS_HEADER_HPP_ 2631