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