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