1 /* 2 * Copyright (c) 2020, 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 SRP server. 32 */ 33 34 #ifndef NET_SRP_SERVER_HPP_ 35 #define NET_SRP_SERVER_HPP_ 36 37 #include "openthread-core-config.h" 38 39 #if OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 40 41 #if !OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE 42 #error "OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE is required for OPENTHREAD_CONFIG_SRP_SERVER_ENABLE" 43 #endif 44 45 #if !OPENTHREAD_CONFIG_NETDATA_PUBLISHER_ENABLE 46 #error "OPENTHREAD_CONFIG_NETDATA_PUBLISHER_ENABLE is required for OPENTHREAD_CONFIG_SRP_SERVER_ENABLE" 47 #endif 48 49 #if !OPENTHREAD_CONFIG_ECDSA_ENABLE 50 #error "OPENTHREAD_CONFIG_ECDSA_ENABLE is required for OPENTHREAD_CONFIG_SRP_SERVER_ENABLE" 51 #endif 52 53 #include <openthread/ip6.h> 54 #include <openthread/srp_server.h> 55 56 #include "common/array.hpp" 57 #include "common/as_core_type.hpp" 58 #include "common/callback.hpp" 59 #include "common/clearable.hpp" 60 #include "common/heap.hpp" 61 #include "common/heap_allocatable.hpp" 62 #include "common/heap_array.hpp" 63 #include "common/heap_data.hpp" 64 #include "common/heap_string.hpp" 65 #include "common/linked_list.hpp" 66 #include "common/locator.hpp" 67 #include "common/non_copyable.hpp" 68 #include "common/notifier.hpp" 69 #include "common/num_utils.hpp" 70 #include "common/numeric_limits.hpp" 71 #include "common/retain_ptr.hpp" 72 #include "common/timer.hpp" 73 #include "crypto/ecdsa.hpp" 74 #include "net/dns_types.hpp" 75 #include "net/ip6.hpp" 76 #include "net/ip6_address.hpp" 77 #include "net/udp6.hpp" 78 #include "thread/network_data_publisher.hpp" 79 80 struct otSrpServerHost 81 { 82 }; 83 84 struct otSrpServerService 85 { 86 }; 87 88 namespace ot { 89 90 namespace Dns { 91 namespace ServiceDiscovery { 92 class Server; 93 } 94 } // namespace Dns 95 96 #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE 97 namespace BorderRouter { 98 class RoutingManager; 99 } 100 #endif 101 102 namespace Srp { 103 104 /** 105 * Implements the SRP server. 106 * 107 */ 108 class Server : public InstanceLocator, private NonCopyable 109 { 110 friend class NetworkData::Publisher; 111 friend class UpdateMetadata; 112 friend class Service; 113 friend class Host; 114 friend class Dns::ServiceDiscovery::Server; 115 #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE 116 friend class BorderRouter::RoutingManager; 117 #endif 118 119 enum RetainName : bool 120 { 121 kDeleteName = false, 122 kRetainName = true, 123 }; 124 125 enum NotifyMode : bool 126 { 127 kDoNotNotifyServiceHandler = false, 128 kNotifyServiceHandler = true, 129 }; 130 131 public: 132 static constexpr uint16_t kUdpPortMin = OPENTHREAD_CONFIG_SRP_SERVER_UDP_PORT_MIN; ///< The reserved min port. 133 static constexpr uint16_t kUdpPortMax = OPENTHREAD_CONFIG_SRP_SERVER_UDP_PORT_MAX; ///< The reserved max port. 134 135 static_assert(kUdpPortMin <= kUdpPortMax, "invalid port range"); 136 137 /** 138 * The ID of SRP service update transaction. 139 * 140 */ 141 typedef otSrpServerServiceUpdateId ServiceUpdateId; 142 143 /** 144 * The SRP server lease information of a host/service. 145 * 146 */ 147 typedef otSrpServerLeaseInfo LeaseInfo; 148 149 /** 150 * Represents the address mode used by the SRP server. 151 * 152 * Address mode specifies how the address and port number are determined by the SRP server and how this info ins 153 * published in the Thread Network Data. 154 * 155 */ 156 enum AddressMode : uint8_t 157 { 158 kAddressModeUnicast = OT_SRP_SERVER_ADDRESS_MODE_UNICAST, ///< Unicast address mode. 159 kAddressModeAnycast = OT_SRP_SERVER_ADDRESS_MODE_ANYCAST, ///< Anycast address mode. 160 }; 161 162 class Host; 163 164 /** 165 * Represents the state of SRP server. 166 * 167 */ 168 enum State : uint8_t 169 { 170 kStateDisabled = OT_SRP_SERVER_STATE_DISABLED, ///< Server is disabled. 171 kStateRunning = OT_SRP_SERVER_STATE_RUNNING, ///< Server is enabled and running. 172 kStateStopped = OT_SRP_SERVER_STATE_STOPPED, ///< Server is enabled but stopped. 173 }; 174 175 /** 176 * Implements a server-side SRP service. 177 * 178 */ 179 class Service : public otSrpServerService, 180 public LinkedListEntry<Service>, 181 private Heap::Allocatable<Service>, 182 private NonCopyable 183 { 184 friend class Server; 185 friend class LinkedList<Service>; 186 friend class LinkedListEntry<Service>; 187 friend class Heap::Allocatable<Service>; 188 189 public: 190 /** 191 * Tells if the SRP service has been deleted. 192 * 193 * A SRP service can be deleted but retains its name for future uses. 194 * In this case, the service instance is not removed from the SRP server/registry. 195 * It is guaranteed that all services are deleted if the host is deleted. 196 * 197 * @returns TRUE if the service has been deleted, FALSE if not. 198 * 199 */ IsDeleted(void) const200 bool IsDeleted(void) const { return mIsDeleted; } 201 202 /** 203 * Gets the full service instance name of the service. 204 * 205 * @returns A pointer service instance name (as a null-terminated C string). 206 * 207 */ GetInstanceName(void) const208 const char *GetInstanceName(void) const { return mInstanceName.AsCString(); } 209 210 /** 211 * Gets the service instance label of the service. 212 * 213 * @returns A pointer service instance label (as a null-terminated C string). 214 * 215 */ GetInstanceLabel(void) const216 const char *GetInstanceLabel(void) const { return mInstanceLabel.AsCString(); } 217 218 /** 219 * Gets the full service name of the service. 220 * 221 * @returns A pointer service name (as a null-terminated C string). 222 * 223 */ GetServiceName(void) const224 const char *GetServiceName(void) const { return mServiceName.AsCString(); } 225 226 /** 227 * Gets number of sub-types of this service. 228 * 229 * @returns The number of sub-types. 230 * 231 */ GetNumberOfSubTypes(void) const232 uint16_t GetNumberOfSubTypes(void) const { return mSubTypes.GetLength(); } 233 234 /** 235 * Gets the sub-type service name (full name) at a given index. 236 * 237 * The full service name for a sub-type service follows "<sub-label>._sub.<service-labels>.<domain>.". 238 * 239 * @param[in] aIndex The index to get. 240 * 241 * @returns A pointer to sub-type service name at @p aIndex, or `nullptr` if none at this index. 242 * 243 */ 244 const char *GetSubTypeServiceNameAt(uint16_t aIndex) const; 245 246 /** 247 * Indicates whether or not service has a given sub-type. 248 * 249 * @param[in] aSubTypeServiceName The sub-type service name (full name). 250 * 251 * @retval TRUE Service contains the sub-type @p aSubTypeServiceName. 252 * @retval FALSE Service does not contain the sub-type @p aSubTypeServiceName. 253 * 254 */ 255 bool HasSubTypeServiceName(const char *aSubTypeServiceName) const; 256 257 /** 258 * Parses a sub-type service name (full name) and extracts the sub-type label. 259 * 260 * The full service name for a sub-type service follows "<sub-label>._sub.<service-labels>.<domain>.". 261 * 262 * @param[in] aSubTypeServiceName A sub-type service name (full name). 263 * @param[out] aLabel A pointer to a buffer to copy the extracted sub-type label. 264 * @param[in] aLabelSize Maximum size of @p aLabel buffer. 265 * 266 * @retval kErrorNone Name was successfully parsed and @p aLabel was updated. 267 * @retval kErrorNoBufs The sub-type label could not fit in @p aLabel buffer (number of chars from label 268 * that could fit are copied in @p aLabel ensuring it is null-terminated). 269 * @retval kErrorInvalidArgs @p aSubTypeServiceName is not a valid sub-type format. 270 * 271 */ 272 static Error ParseSubTypeServiceName(const char *aSubTypeServiceName, char *aLabel, uint8_t aLabelSize); 273 274 /** 275 * Returns the TTL of the service instance. 276 * 277 * @returns The TTL of the service instance. 278 * 279 */ GetTtl(void) const280 uint32_t GetTtl(void) const { return mTtl; } 281 282 /** 283 * Returns the port of the service instance. 284 * 285 * @returns The port of the service. 286 * 287 */ GetPort(void) const288 uint16_t GetPort(void) const { return mPort; } 289 290 /** 291 * Returns the weight of the service instance. 292 * 293 * @returns The weight of the service. 294 * 295 */ GetWeight(void) const296 uint16_t GetWeight(void) const { return mWeight; } 297 298 /** 299 * Returns the priority of the service instance. 300 * 301 * @returns The priority of the service. 302 * 303 */ GetPriority(void) const304 uint16_t GetPriority(void) const { return mPriority; } 305 306 /** 307 * Returns the TXT record data of the service instance. 308 * 309 * @returns A pointer to the buffer containing the TXT record data. 310 * 311 */ GetTxtData(void) const312 const uint8_t *GetTxtData(void) const { return mTxtData.GetBytes(); } 313 314 /** 315 * Returns the TXT record data length of the service instance. 316 * 317 * @return The TXT record data length (number of bytes in buffer returned from `GetTxtData()`). 318 * 319 */ GetTxtDataLength(void) const320 uint16_t GetTxtDataLength(void) const { return mTxtData.GetLength(); } 321 322 /** 323 * Returns the host which the service instance reside on. 324 * 325 * @returns A reference to the host instance. 326 * 327 */ GetHost(void) const328 const Host &GetHost(void) const { return *mHost; } 329 330 /** 331 * Returns the LEASE time of the service. 332 * 333 * @returns The LEASE time in seconds. 334 * 335 */ GetLease(void) const336 uint32_t GetLease(void) const { return mLease; } 337 338 /** 339 * Returns the KEY-LEASE time of the key of the service. 340 * 341 * @returns The KEY-LEASE time in seconds. 342 * 343 */ GetKeyLease(void) const344 uint32_t GetKeyLease(void) const { return mKeyLease; } 345 346 /** 347 * Returns the expire time (in milliseconds) of the service. 348 * 349 * @returns The service expire time in milliseconds. 350 * 351 */ 352 TimeMilli GetExpireTime(void) const; 353 354 /** 355 * Returns the key expire time (in milliseconds) of the service. 356 * 357 * @returns The service key expire time in milliseconds. 358 * 359 */ 360 TimeMilli GetKeyExpireTime(void) const; 361 362 /** 363 * Gets the LEASE and KEY-LEASE information of a given service. 364 * 365 * @param[out] aLeaseInfo A reference to a LeaseInfo instance. It contains the LEASE time, KEY-LEASE time, 366 * remaining LEASE time and the remaining KEY-LEASE time. 367 * 368 */ 369 void GetLeaseInfo(LeaseInfo &aLeaseInfo) const; 370 371 /** 372 * Indicates whether this service matches a given service instance name. 373 * 374 * @param[in] aInstanceName The service instance name. 375 * 376 * @retval TRUE If the service matches the service instance name. 377 * @retval FALSE If the service does not match the service instance name. 378 * 379 */ 380 bool MatchesInstanceName(const char *aInstanceName) const; 381 382 /** 383 * Tells whether this service matches a given service name. 384 * 385 * @param[in] aServiceName The full service name to match. 386 * 387 * @retval TRUE If the service matches the full service name. 388 * @retval FALSE If the service does not match the full service name. 389 * 390 */ 391 bool MatchesServiceName(const char *aServiceName) const; 392 393 private: 394 enum Action : uint8_t 395 { 396 kAddNew, 397 kUpdateExisting, 398 kKeepUnchanged, 399 kRemoveButRetainName, 400 kFullyRemove, 401 kLeaseExpired, 402 kKeyLeaseExpired, 403 }; 404 405 Error Init(const char *aInstanceName, const char *aInstanceLabel, Host &aHost, TimeMilli aUpdateTime); 406 Error SetTxtDataFromMessage(const Message &aMessage, uint16_t aOffset, uint16_t aLength); 407 bool Matches(const char *aInstanceName) const; 408 void Log(Action aAction) const; 409 410 template <uint16_t kLabelSize> ParseSubTypeServiceName(const char * aSubTypeServiceName,char (& aLabel)[kLabelSize])411 static Error ParseSubTypeServiceName(const char *aSubTypeServiceName, char (&aLabel)[kLabelSize]) 412 { 413 return ParseSubTypeServiceName(aSubTypeServiceName, aLabel, kLabelSize); 414 } 415 416 Service *mNext; 417 Heap::String mInstanceName; 418 Heap::String mInstanceLabel; 419 Heap::String mServiceName; 420 Heap::Array<Heap::String> mSubTypes; 421 Host *mHost; 422 Heap::Data mTxtData; 423 uint16_t mPriority; 424 uint16_t mWeight; 425 uint16_t mPort; 426 uint32_t mTtl; // In seconds 427 uint32_t mLease; // In seconds 428 uint32_t mKeyLease; // In seconds 429 TimeMilli mUpdateTime; 430 bool mIsDeleted : 1; 431 bool mIsCommitted : 1; 432 bool mParsedDeleteAllRrset : 1; 433 bool mParsedSrv : 1; 434 bool mParsedTxt : 1; 435 }; 436 437 /** 438 * Implements the Host which registers services on the SRP server. 439 * 440 */ 441 class Host : public otSrpServerHost, 442 public InstanceLocator, 443 public LinkedListEntry<Host>, 444 private Heap::Allocatable<Host>, 445 private NonCopyable 446 { 447 friend class Server; 448 friend class LinkedListEntry<Host>; 449 friend class Heap::Allocatable<Host>; 450 451 public: 452 typedef Crypto::Ecdsa::P256::PublicKey Key; ///< Host key (public ECDSA P256 key). 453 454 /** 455 * Tells whether the Host object has been deleted. 456 * 457 * The Host object retains event if the host has been deleted by the SRP client, 458 * because the host name may retain. 459 * 460 * @returns TRUE if the host is deleted, FALSE if the host is not deleted. 461 * 462 */ IsDeleted(void) const463 bool IsDeleted(void) const { return (mLease == 0); } 464 465 /** 466 * Returns the full name of the host. 467 * 468 * @returns A pointer to the null-terminated full host name. 469 * 470 */ GetFullName(void) const471 const char *GetFullName(void) const { return mFullName.AsCString(); } 472 473 /** 474 * Returns addresses of the host. 475 * 476 * @param[out] aAddressesNum The number of the addresses. 477 * 478 * @returns A pointer to the addresses array or `nullptr` if no addresses. 479 * 480 */ GetAddresses(uint8_t & aAddressesNum) const481 const Ip6::Address *GetAddresses(uint8_t &aAddressesNum) const 482 { 483 aAddressesNum = ClampToUint8(mAddresses.GetLength()); 484 485 return mAddresses.AsCArray(); 486 } 487 488 /** 489 * Returns the TTL of the host. 490 * 491 * @returns The TTL of the host. 492 * 493 */ GetTtl(void) const494 uint32_t GetTtl(void) const { return mTtl; } 495 496 /** 497 * Returns the LEASE time of the host. 498 * 499 * @returns The LEASE time in seconds. 500 * 501 */ GetLease(void) const502 uint32_t GetLease(void) const { return mLease; } 503 504 /** 505 * Returns the KEY-LEASE time of the key of the host. 506 * 507 * @returns The KEY-LEASE time in seconds. 508 * 509 */ GetKeyLease(void) const510 uint32_t GetKeyLease(void) const { return mKeyLease; } 511 512 /** 513 * Gets the LEASE and KEY-LEASE information of a given host. 514 * 515 * @param[out] aLeaseInfo A reference to a LeaseInfo instance. It contains the LEASE time, KEY-LEASE time, 516 * remaining LEASE time and the remaining KEY-LEASE time. 517 * 518 */ 519 void GetLeaseInfo(LeaseInfo &aLeaseInfo) const; 520 521 /** 522 * Returns the key associated with this host. 523 * 524 * @returns The host key. 525 * 526 */ GetKey(void) const527 const Key &GetKey(void) const { return mKey; } 528 529 /** 530 * Returns the expire time (in milliseconds) of the host. 531 * 532 * @returns The expire time in milliseconds. 533 * 534 */ 535 TimeMilli GetExpireTime(void) const; 536 537 /** 538 * Returns the expire time (in milliseconds) of the key of the host. 539 * 540 * @returns The expire time of the key in milliseconds. 541 * 542 */ 543 TimeMilli GetKeyExpireTime(void) const; 544 545 /** 546 * Returns the `Service` linked list associated with the host. 547 * 548 * @returns The `Service` linked list. 549 * 550 */ GetServices(void) const551 const LinkedList<Service> &GetServices(void) const { return mServices; } 552 553 /* 554 * Returns the next service. 555 * 556 * @param[in] aPrevService A pointer to the previous service or `nullptr` to start from beginning of the list. 557 * 558 * @returns A pointer to the next service or `nullptr` if no more services can be found. 559 * 560 */ 561 const Service *GetNextService(const Service *aPrevService) const; 562 563 /** 564 * Tells whether the host matches a given full name. 565 * 566 * @param[in] aFullName The full name. 567 * 568 * @returns A boolean that indicates whether the host matches the given name. 569 * 570 */ 571 bool Matches(const char *aFullName) const; 572 573 private: 574 Host(Instance &aInstance, TimeMilli aUpdateTime); 575 ~Host(void); 576 577 Error SetFullName(const char *aFullName); SetTtl(uint32_t aTtl)578 void SetTtl(uint32_t aTtl) { mTtl = aTtl; } SetLease(uint32_t aLease)579 void SetLease(uint32_t aLease) { mLease = aLease; } SetKeyLease(uint32_t aKeyLease)580 void SetKeyLease(uint32_t aKeyLease) { mKeyLease = aKeyLease; } SetUseShortLeaseOption(bool aUse)581 void SetUseShortLeaseOption(bool aUse) { mUseShortLeaseOption = aUse; } ShouldUseShortLeaseOption(void) const582 bool ShouldUseShortLeaseOption(void) const { return mUseShortLeaseOption; } 583 Error ProcessTtl(uint32_t aTtl); 584 585 Service *AddNewService(const char *aInstanceName, const char *aInstanceLabel, TimeMilli aUpdateTime); 586 void AddService(Service &aService); 587 void RemoveService(Service *aService, RetainName aRetainName, NotifyMode aNotifyServiceHandler); 588 bool HasService(const char *aInstanceName) const; 589 Service *FindService(const char *aInstanceName); 590 const Service *FindService(const char *aInstanceName) const; 591 void FreeAllServices(void); 592 void ClearResources(void); 593 Error AddIp6Address(const Ip6::Address &aIp6Address); 594 595 Host *mNext; 596 Heap::String mFullName; 597 Heap::Array<Ip6::Address> mAddresses; 598 Key mKey; 599 uint32_t mTtl; // The TTL in seconds. 600 uint32_t mLease; // The LEASE time in seconds. 601 uint32_t mKeyLease; // The KEY-LEASE time in seconds. 602 TimeMilli mUpdateTime; 603 LinkedList<Service> mServices; 604 bool mParsedKey : 1; 605 bool mUseShortLeaseOption : 1; // Use short lease option (lease only 4 bytes). 606 }; 607 608 /** 609 * Handles TTL configuration. 610 * 611 */ 612 class TtlConfig : public otSrpServerTtlConfig 613 { 614 friend class Server; 615 616 public: 617 /** 618 * Initializes to default TTL configuration. 619 * 620 */ 621 TtlConfig(void); 622 623 private: IsValid(void) const624 bool IsValid(void) const { return mMinTtl <= mMaxTtl; } 625 uint32_t GrantTtl(uint32_t aLease, uint32_t aTtl) const; 626 }; 627 628 /** 629 * Handles LEASE and KEY-LEASE configurations. 630 * 631 */ 632 class LeaseConfig : public otSrpServerLeaseConfig 633 { 634 friend class Server; 635 636 public: 637 /** 638 * Initialize to default LEASE and KEY-LEASE configurations. 639 * 640 */ 641 LeaseConfig(void); 642 643 private: 644 bool IsValid(void) const; 645 uint32_t GrantLease(uint32_t aLease) const; 646 uint32_t GrantKeyLease(uint32_t aKeyLease) const; 647 }; 648 649 /** 650 * Initializes the SRP server object. 651 * 652 * @param[in] aInstance A reference to the OpenThread instance. 653 * 654 */ 655 explicit Server(Instance &aInstance); 656 657 /** 658 * Sets the SRP service events handler. 659 * 660 * @param[in] aServiceHandler A service events handler. 661 * @param[in] aServiceHandlerContext A pointer to arbitrary context information. 662 * 663 * @note The handler SHOULD call HandleServiceUpdateResult to report the result of its processing. 664 * Otherwise, a SRP update will be considered failed. 665 * 666 * @sa HandleServiceUpdateResult 667 * 668 */ SetServiceHandler(otSrpServerServiceUpdateHandler aServiceHandler,void * aServiceHandlerContext)669 void SetServiceHandler(otSrpServerServiceUpdateHandler aServiceHandler, void *aServiceHandlerContext) 670 { 671 mServiceUpdateHandler.Set(aServiceHandler, aServiceHandlerContext); 672 } 673 674 /** 675 * Returns the domain authorized to the SRP server. 676 * 677 * If the domain if not set by SetDomain, "default.service.arpa." will be returned. 678 * A trailing dot is always appended even if the domain is set without it. 679 * 680 * @returns A pointer to the dot-joined domain string. 681 * 682 */ GetDomain(void) const683 const char *GetDomain(void) const { return mDomain.AsCString(); } 684 685 /** 686 * Sets the domain on the SRP server. 687 * 688 * A trailing dot will be appended to @p aDomain if it is not already there. 689 * Should only be called before the SRP server is enabled. 690 * 691 * @param[in] aDomain The domain to be set. MUST NOT be `nullptr`. 692 * 693 * @retval kErrorNone Successfully set the domain to @p aDomain. 694 * @retval kErrorInvalidState The SRP server is already enabled and the Domain cannot be changed. 695 * @retval kErrorInvalidArgs The argument @p aDomain is not a valid DNS domain name. 696 * @retval kErrorNoBufs There is no memory to store content of @p aDomain. 697 * 698 */ 699 Error SetDomain(const char *aDomain); 700 701 /** 702 * Returns the address mode being used by the SRP server. 703 * 704 * @returns The SRP server's address mode. 705 * 706 */ GetAddressMode(void) const707 AddressMode GetAddressMode(void) const { return mAddressMode; } 708 709 /** 710 * Sets the address mode to be used by the SRP server. 711 * 712 * @param[in] aMode The address mode to use. 713 * 714 * @retval kErrorNone Successfully set the address mode. 715 * @retval kErrorInvalidState The SRP server is enabled and the address mode cannot be changed. 716 * 717 */ 718 Error SetAddressMode(AddressMode aMode); 719 720 /** 721 * Gets the sequence number used with anycast address mode. 722 * 723 * The sequence number is included in "DNS/SRP Service Anycast Address" entry published in the Network Data. 724 * 725 * @returns The anycast sequence number. 726 * 727 */ GetAnycastModeSequenceNumber(void) const728 uint8_t GetAnycastModeSequenceNumber(void) const { return mAnycastSequenceNumber; } 729 730 /** 731 * Sets the sequence number used with anycast address mode. 732 * 733 * @param[in] aSequenceNumber The sequence number to use. 734 * 735 * @retval kErrorNone Successfully set the address mode. 736 * @retval kErrorInvalidState The SRP server is enabled and the sequence number cannot be changed. 737 * 738 */ 739 Error SetAnycastModeSequenceNumber(uint8_t aSequenceNumber); 740 741 /** 742 * Returns the state of the SRP server. 743 * 744 * @returns The state of the server. 745 * 746 */ GetState(void) const747 State GetState(void) const { return mState; } 748 749 /** 750 * Tells the port the SRP server is listening to. 751 * 752 * @returns The port of the server or 0 if the SRP server is not running. 753 * 754 */ GetPort(void) const755 uint16_t GetPort(void) const { return (mState == kStateRunning) ? mPort : 0; } 756 757 /** 758 * Enables/disables the SRP server. 759 * 760 * @param[in] aEnabled A boolean to enable/disable the SRP server. 761 * 762 */ 763 void SetEnabled(bool aEnabled); 764 765 #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE 766 /** 767 * Enables/disables the auto-enable mode on SRP server. 768 * 769 * When this mode is enabled, the Border Routing Manager controls if/when to enable or disable the SRP server. 770 * SRP sever is auto-enabled if/when Border Routing is started it is done with the initial prefix and route 771 * configurations (when the OMR and on-link prefixes are determined, advertised in emitted Router Advert message on 772 * infrastructure side and published in the Thread Network Data). The SRP server is auto-disabled when BR is 773 * stopped (e.g., if the infrastructure network interface is brought down or if BR gets detached). 774 * 775 * This mode can be disabled by a `SetAutoEnableMode(false)` call or if the SRP server is explicitly enabled or 776 * disabled by a call to `SetEnabled()` method. Disabling auto-enable mode using `SetAutoEnableMode(false` call 777 * will not change the current state of SRP sever (e.g., if it is enabled it stays enabled). 778 * 779 * @param[in] aEnabled A boolean to enable/disable the auto-enable mode. 780 * 781 */ 782 void SetAutoEnableMode(bool aEnabled); 783 784 /** 785 * Indicates whether the auto-enable mode is enabled or disabled. 786 * 787 * @retval TRUE The auto-enable mode is enabled. 788 * @retval FALSE The auto-enable mode is disabled. 789 * 790 */ IsAutoEnableMode(void) const791 bool IsAutoEnableMode(void) const { return mAutoEnable; } 792 #endif 793 794 /** 795 * Returns the TTL configuration. 796 * 797 * @param[out] aTtlConfig A reference to the `TtlConfig` instance. 798 * 799 */ GetTtlConfig(TtlConfig & aTtlConfig) const800 void GetTtlConfig(TtlConfig &aTtlConfig) const { aTtlConfig = mTtlConfig; } 801 802 /** 803 * Sets the TTL configuration. 804 * 805 * @param[in] aTtlConfig A reference to the `TtlConfig` instance. 806 * 807 * @retval kErrorNone Successfully set the TTL configuration 808 * @retval kErrorInvalidArgs The TTL range is not valid. 809 * 810 */ 811 Error SetTtlConfig(const TtlConfig &aTtlConfig); 812 813 /** 814 * Returns the LEASE and KEY-LEASE configurations. 815 * 816 * @param[out] aLeaseConfig A reference to the `LeaseConfig` instance. 817 * 818 */ GetLeaseConfig(LeaseConfig & aLeaseConfig) const819 void GetLeaseConfig(LeaseConfig &aLeaseConfig) const { aLeaseConfig = mLeaseConfig; } 820 821 /** 822 * Sets the LEASE and KEY-LEASE configurations. 823 * 824 * When a LEASE time is requested from a client, the granted value will be 825 * limited in range [aMinLease, aMaxLease]; and a KEY-LEASE will be granted 826 * in range [aMinKeyLease, aMaxKeyLease]. 827 * 828 * @param[in] aLeaseConfig A reference to the `LeaseConfig` instance. 829 * 830 * @retval kErrorNone Successfully set the LEASE and KEY-LEASE ranges. 831 * @retval kErrorInvalidArgs The LEASE or KEY-LEASE range is not valid. 832 * 833 */ 834 Error SetLeaseConfig(const LeaseConfig &aLeaseConfig); 835 836 /** 837 * Returns the `Host` linked list. 838 * 839 * @returns The `Host` linked list. 840 * 841 */ GetHosts(void) const842 const LinkedList<Host> &GetHosts(void) const { return mHosts; } 843 844 /** 845 * Returns the next registered SRP host. 846 * 847 * @param[in] aHost The current SRP host; use `nullptr` to get the first SRP host. 848 * 849 * @returns A pointer to the next SRP host or `nullptr` if no more SRP hosts can be found. 850 * 851 */ 852 const Host *GetNextHost(const Host *aHost); 853 854 /** 855 * Returns the response counters of the SRP server. 856 * 857 * @returns A pointer to the response counters of the SRP server. 858 * 859 */ GetResponseCounters(void) const860 const otSrpServerResponseCounters *GetResponseCounters(void) const { return &mResponseCounters; } 861 862 /** 863 * Receives the service update result from service handler set by 864 * SetServiceHandler. 865 * 866 * @param[in] aId The ID of the service update transaction. 867 * @param[in] aError The service update result. 868 * 869 */ 870 void HandleServiceUpdateResult(ServiceUpdateId aId, Error aError); 871 872 private: 873 static constexpr uint16_t kUdpPayloadSize = Ip6::kMaxDatagramLength - sizeof(Ip6::Udp::Header); 874 875 static constexpr uint32_t kDefaultMinLease = 30; // 30 seconds. 876 static constexpr uint32_t kDefaultMaxLease = 27u * 3600; // 27 hours (in seconds). 877 static constexpr uint32_t kDefaultMinKeyLease = 30; // 30 seconds. 878 static constexpr uint32_t kDefaultMaxKeyLease = 189u * 3600; // 189 hours (in seconds). 879 static constexpr uint32_t kDefaultMinTtl = kDefaultMinLease; 880 static constexpr uint32_t kDefaultMaxTtl = kDefaultMaxLease; 881 static constexpr uint32_t kDefaultEventsHandlerTimeout = OPENTHREAD_CONFIG_SRP_SERVER_SERVICE_UPDATE_TIMEOUT; 882 883 static constexpr AddressMode kDefaultAddressMode = 884 static_cast<AddressMode>(OPENTHREAD_CONFIG_SRP_SERVER_DEFAULT_ADDRESS_MODE); 885 886 static constexpr uint16_t kAnycastAddressModePort = 53; 887 888 // Metadata for a received SRP Update message. 889 struct MessageMetadata 890 { 891 // Indicates whether the `Message` is received directly from a 892 // client or from an SRPL partner. IsDirectRxFromClientot::Srp::Server::MessageMetadata893 bool IsDirectRxFromClient(void) const { return (mMessageInfo != nullptr); } 894 895 Dns::UpdateHeader mDnsHeader; 896 Dns::Zone mDnsZone; 897 uint16_t mOffset; 898 TimeMilli mRxTime; 899 TtlConfig mTtlConfig; 900 LeaseConfig mLeaseConfig; 901 const Ip6::MessageInfo *mMessageInfo; // Set to `nullptr` when from SRPL. 902 }; 903 904 // This class includes metadata for processing a SRP update (register, deregister) 905 // and sending DNS response to the client. 906 class UpdateMetadata : public InstanceLocator, 907 public LinkedListEntry<UpdateMetadata>, 908 public Heap::Allocatable<UpdateMetadata> 909 { 910 friend class LinkedListEntry<UpdateMetadata>; 911 friend class Heap::Allocatable<UpdateMetadata>; 912 913 public: GetExpireTime(void) const914 TimeMilli GetExpireTime(void) const { return mExpireTime; } GetDnsHeader(void) const915 const Dns::UpdateHeader &GetDnsHeader(void) const { return mDnsHeader; } GetId(void) const916 ServiceUpdateId GetId(void) const { return mId; } GetTtlConfig(void) const917 const TtlConfig &GetTtlConfig(void) const { return mTtlConfig; } GetLeaseConfig(void) const918 const LeaseConfig &GetLeaseConfig(void) const { return mLeaseConfig; } GetHost(void)919 Host &GetHost(void) { return mHost; } GetMessageInfo(void) const920 const Ip6::MessageInfo &GetMessageInfo(void) const { return mMessageInfo; } GetError(void) const921 Error GetError(void) const { return mError; } SetError(Error aError)922 void SetError(Error aError) { mError = aError; } IsDirectRxFromClient(void) const923 bool IsDirectRxFromClient(void) const { return mIsDirectRxFromClient; } Matches(ServiceUpdateId aId) const924 bool Matches(ServiceUpdateId aId) const { return mId == aId; } 925 926 private: 927 UpdateMetadata(Instance &aInstance, Host &aHost, const MessageMetadata &aMessageMetadata); 928 929 UpdateMetadata *mNext; 930 TimeMilli mExpireTime; 931 Dns::UpdateHeader mDnsHeader; 932 ServiceUpdateId mId; // The ID of this service update transaction. 933 TtlConfig mTtlConfig; // TTL config to use when processing the message. 934 LeaseConfig mLeaseConfig; // Lease config to use when processing the message. 935 Host &mHost; // The `UpdateMetadata` has no ownership of this host. 936 Ip6::MessageInfo mMessageInfo; // Valid when `mIsDirectRxFromClient` is true. 937 Error mError; 938 bool mIsDirectRxFromClient; 939 }; 940 941 void Enable(void); 942 void Disable(void); 943 void Start(void); 944 void Stop(void); 945 void SelectPort(void); 946 void PrepareSocket(void); 947 Ip6::Udp::Socket &GetSocket(void); 948 949 #if OPENTHREAD_CONFIG_DNSSD_SERVER_ENABLE 950 void HandleDnssdServerStateChange(void); 951 Error HandleDnssdServerUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); 952 #endif 953 954 void HandleNetDataPublisherEvent(NetworkData::Publisher::Event aEvent); 955 AllocateId(void)956 ServiceUpdateId AllocateId(void) { return mServiceUpdateId++; } 957 958 void InformUpdateHandlerOrCommit(Error aError, Host &aHost, const MessageMetadata &aMetadata); 959 void CommitSrpUpdate(Error aError, Host &aHost, const MessageMetadata &aMessageMetadata); 960 void CommitSrpUpdate(UpdateMetadata &aUpdateMetadata); 961 void CommitSrpUpdate(Error aError, 962 Host &aHost, 963 const Dns::UpdateHeader &aDnsHeader, 964 const Ip6::MessageInfo *aMessageInfo, 965 const TtlConfig &aTtlConfig, 966 const LeaseConfig &aLeaseConfig); 967 Error ProcessMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); 968 Error ProcessMessage(Message &aMessage, 969 TimeMilli aRxTime, 970 const TtlConfig &aTtlConfig, 971 const LeaseConfig &aLeaseConfig, 972 const Ip6::MessageInfo *aMessageInfo); 973 void ProcessDnsUpdate(Message &aMessage, MessageMetadata &aMetadata); 974 Error ProcessUpdateSection(Host &aHost, const Message &aMessage, MessageMetadata &aMetadata) const; 975 Error ProcessAdditionalSection(Host *aHost, const Message &aMessage, MessageMetadata &aMetadata) const; 976 Error VerifySignature(const Host::Key &aKey, 977 const Message &aMessage, 978 Dns::UpdateHeader aDnsHeader, 979 uint16_t aSigOffset, 980 uint16_t aSigRdataOffset, 981 uint16_t aSigRdataLength, 982 const char *aSignerName) const; 983 Error ProcessZoneSection(const Message &aMessage, MessageMetadata &aMetadata) const; 984 Error ProcessHostDescriptionInstruction(Host &aHost, 985 const Message &aMessage, 986 const MessageMetadata &aMetadata) const; 987 Error ProcessServiceDiscoveryInstructions(Host &aHost, 988 const Message &aMessage, 989 const MessageMetadata &aMetadata) const; 990 Error ProcessServiceDescriptionInstructions(Host &aHost, const Message &aMessage, MessageMetadata &aMetadata) const; 991 992 static bool IsValidDeleteAllRecord(const Dns::ResourceRecord &aRecord); 993 994 void HandleUpdate(Host &aHost, const MessageMetadata &aMetadata); 995 void RemoveHost(Host *aHost, RetainName aRetainName); 996 bool HasNameConflictsWith(Host &aHost) const; 997 void SendResponse(const Dns::UpdateHeader &aHeader, 998 Dns::UpdateHeader::Response aResponseCode, 999 const Ip6::MessageInfo &aMessageInfo); 1000 void SendResponse(const Dns::UpdateHeader &aHeader, 1001 uint32_t aLease, 1002 uint32_t aKeyLease, 1003 bool mUseShortLeaseOption, 1004 const Ip6::MessageInfo &aMessageInfo); 1005 static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); 1006 void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); 1007 void HandleLeaseTimer(void); 1008 static void HandleOutstandingUpdatesTimer(Timer &aTimer); 1009 void HandleOutstandingUpdatesTimer(void); 1010 void ProcessCompletedUpdates(void); 1011 1012 const UpdateMetadata *FindOutstandingUpdate(const MessageMetadata &aMessageMetadata) const; 1013 static const char *AddressModeToString(AddressMode aMode); 1014 1015 void UpdateResponseCounters(Dns::Header::Response aResponseCode); 1016 1017 using LeaseTimer = TimerMilliIn<Server, &Server::HandleLeaseTimer>; 1018 using UpdateTimer = TimerMilliIn<Server, &Server::HandleOutstandingUpdatesTimer>; 1019 using CompletedUpdatesTask = TaskletIn<Server, &Server::ProcessCompletedUpdates>; 1020 1021 Ip6::Udp::Socket mSocket; 1022 1023 Callback<otSrpServerServiceUpdateHandler> mServiceUpdateHandler; 1024 1025 Heap::String mDomain; 1026 1027 TtlConfig mTtlConfig; 1028 LeaseConfig mLeaseConfig; 1029 1030 LinkedList<Host> mHosts; 1031 LeaseTimer mLeaseTimer; 1032 1033 UpdateTimer mOutstandingUpdatesTimer; 1034 LinkedList<UpdateMetadata> mOutstandingUpdates; 1035 LinkedList<UpdateMetadata> mCompletedUpdates; 1036 CompletedUpdatesTask mCompletedUpdateTask; 1037 1038 ServiceUpdateId mServiceUpdateId; 1039 uint16_t mPort; 1040 State mState; 1041 AddressMode mAddressMode; 1042 uint8_t mAnycastSequenceNumber; 1043 bool mHasRegisteredAnyService : 1; 1044 #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE 1045 bool mAutoEnable : 1; 1046 #endif 1047 1048 otSrpServerResponseCounters mResponseCounters; 1049 }; 1050 1051 } // namespace Srp 1052 1053 DefineCoreType(otSrpServerTtlConfig, Srp::Server::TtlConfig); 1054 DefineCoreType(otSrpServerLeaseConfig, Srp::Server::LeaseConfig); 1055 DefineCoreType(otSrpServerHost, Srp::Server::Host); 1056 DefineCoreType(otSrpServerService, Srp::Server::Service); 1057 DefineMapEnum(otSrpServerState, Srp::Server::State); 1058 DefineMapEnum(otSrpServerAddressMode, Srp::Server::AddressMode); 1059 1060 } // namespace ot 1061 1062 #endif // OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 1063 #endif // NET_SRP_SERVER_HPP_ 1064