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         Service                  *mNext;
411         Heap::String              mInstanceName;
412         Heap::String              mInstanceLabel;
413         Heap::String              mServiceName;
414         Heap::Array<Heap::String> mSubTypes;
415         Host                     *mHost;
416         Heap::Data                mTxtData;
417         uint16_t                  mPriority;
418         uint16_t                  mWeight;
419         uint16_t                  mPort;
420         uint32_t                  mTtl;      // In seconds
421         uint32_t                  mLease;    // In seconds
422         uint32_t                  mKeyLease; // In seconds
423         TimeMilli                 mUpdateTime;
424         bool                      mIsDeleted : 1;
425         bool                      mIsCommitted : 1;
426         bool                      mParsedDeleteAllRrset : 1;
427         bool                      mParsedSrv : 1;
428         bool                      mParsedTxt : 1;
429     };
430 
431     /**
432      * Implements the Host which registers services on the SRP server.
433      *
434      */
435     class Host : public otSrpServerHost,
436                  public InstanceLocator,
437                  public LinkedListEntry<Host>,
438                  private Heap::Allocatable<Host>,
439                  private NonCopyable
440     {
441         friend class Server;
442         friend class LinkedListEntry<Host>;
443         friend class Heap::Allocatable<Host>;
444 
445     public:
446         typedef Crypto::Ecdsa::P256::PublicKey Key; ///< Host key (public ECDSA P256 key).
447 
448         /**
449          * Tells whether the Host object has been deleted.
450          *
451          * The Host object retains event if the host has been deleted by the SRP client,
452          * because the host name may retain.
453          *
454          * @returns  TRUE if the host is deleted, FALSE if the host is not deleted.
455          *
456          */
IsDeleted(void) const457         bool IsDeleted(void) const { return (mLease == 0); }
458 
459         /**
460          * Returns the full name of the host.
461          *
462          * @returns  A pointer to the null-terminated full host name.
463          *
464          */
GetFullName(void) const465         const char *GetFullName(void) const { return mFullName.AsCString(); }
466 
467         /**
468          * Returns addresses of the host.
469          *
470          * @param[out]  aAddressesNum  The number of the addresses.
471          *
472          * @returns  A pointer to the addresses array or `nullptr` if no addresses.
473          *
474          */
GetAddresses(uint8_t & aAddressesNum) const475         const Ip6::Address *GetAddresses(uint8_t &aAddressesNum) const
476         {
477             aAddressesNum = ClampToUint8(mAddresses.GetLength());
478 
479             return mAddresses.AsCArray();
480         }
481 
482         /**
483          * Returns the TTL of the host.
484          *
485          * @returns The TTL of the host.
486          *
487          */
GetTtl(void) const488         uint32_t GetTtl(void) const { return mTtl; }
489 
490         /**
491          * Returns the LEASE time of the host.
492          *
493          * @returns  The LEASE time in seconds.
494          *
495          */
GetLease(void) const496         uint32_t GetLease(void) const { return mLease; }
497 
498         /**
499          * Returns the KEY-LEASE time of the key of the host.
500          *
501          * @returns  The KEY-LEASE time in seconds.
502          *
503          */
GetKeyLease(void) const504         uint32_t GetKeyLease(void) const { return mKeyLease; }
505 
506         /**
507          * Gets the LEASE and KEY-LEASE information of a given host.
508          *
509          * @param[out]  aLeaseInfo  A reference to a LeaseInfo instance. It contains the LEASE time, KEY-LEASE time,
510          *                          remaining LEASE time and the remaining KEY-LEASE time.
511          *
512          */
513         void GetLeaseInfo(LeaseInfo &aLeaseInfo) const;
514 
515         /**
516          * Returns the key associated with this host.
517          *
518          * @returns  The host key.
519          *
520          */
GetKey(void) const521         const Key &GetKey(void) const { return mKey; }
522 
523         /**
524          * Returns the expire time (in milliseconds) of the host.
525          *
526          * @returns  The expire time in milliseconds.
527          *
528          */
529         TimeMilli GetExpireTime(void) const;
530 
531         /**
532          * Returns the expire time (in milliseconds) of the key of the host.
533          *
534          * @returns  The expire time of the key in milliseconds.
535          *
536          */
537         TimeMilli GetKeyExpireTime(void) const;
538 
539         /**
540          * Returns the `Service` linked list associated with the host.
541          *
542          * @returns The `Service` linked list.
543          *
544          */
GetServices(void) const545         const LinkedList<Service> &GetServices(void) const { return mServices; }
546 
547         /*
548          * Returns the next service.
549          *
550          * @param[in] aPrevService   A pointer to the previous service or `nullptr` to start from beginning of the list.
551          *
552          * @returns  A pointer to the next service or `nullptr` if no more services can be found.
553          *
554          */
555         const Service *GetNextService(const Service *aPrevService) const;
556 
557         /**
558          * Tells whether the host matches a given full name.
559          *
560          * @param[in]  aFullName  The full name.
561          *
562          * @returns  A boolean that indicates whether the host matches the given name.
563          *
564          */
565         bool Matches(const char *aFullName) const;
566 
567     private:
568         Host(Instance &aInstance, TimeMilli aUpdateTime);
569         ~Host(void);
570 
571         Error SetFullName(const char *aFullName);
SetTtl(uint32_t aTtl)572         void  SetTtl(uint32_t aTtl) { mTtl = aTtl; }
SetLease(uint32_t aLease)573         void  SetLease(uint32_t aLease) { mLease = aLease; }
SetKeyLease(uint32_t aKeyLease)574         void  SetKeyLease(uint32_t aKeyLease) { mKeyLease = aKeyLease; }
SetUseShortLeaseOption(bool aUse)575         void  SetUseShortLeaseOption(bool aUse) { mUseShortLeaseOption = aUse; }
ShouldUseShortLeaseOption(void) const576         bool  ShouldUseShortLeaseOption(void) const { return mUseShortLeaseOption; }
577         Error ProcessTtl(uint32_t aTtl);
578 
579         Service       *AddNewService(const char *aInstanceName, const char *aInstanceLabel, TimeMilli aUpdateTime);
580         void           AddService(Service &aService);
581         void           RemoveService(Service *aService, RetainName aRetainName, NotifyMode aNotifyServiceHandler);
582         bool           HasService(const char *aInstanceName) const;
583         Service       *FindService(const char *aInstanceName);
584         const Service *FindService(const char *aInstanceName) const;
585         void           FreeAllServices(void);
586         void           ClearResources(void);
587         Error          AddIp6Address(const Ip6::Address &aIp6Address);
588 
589         Host                     *mNext;
590         Heap::String              mFullName;
591         Heap::Array<Ip6::Address> mAddresses;
592         Key                       mKey;
593         uint32_t                  mTtl;      // The TTL in seconds.
594         uint32_t                  mLease;    // The LEASE time in seconds.
595         uint32_t                  mKeyLease; // The KEY-LEASE time in seconds.
596         TimeMilli                 mUpdateTime;
597         LinkedList<Service>       mServices;
598         bool                      mParsedKey : 1;
599         bool                      mUseShortLeaseOption : 1; // Use short lease option (lease only 4 bytes).
600     };
601 
602     /**
603      * Handles TTL configuration.
604      *
605      */
606     class TtlConfig : public otSrpServerTtlConfig
607     {
608         friend class Server;
609 
610     public:
611         /**
612          * Initializes to default TTL configuration.
613          *
614          */
615         TtlConfig(void);
616 
617     private:
IsValid(void) const618         bool     IsValid(void) const { return mMinTtl <= mMaxTtl; }
619         uint32_t GrantTtl(uint32_t aLease, uint32_t aTtl) const;
620     };
621 
622     /**
623      * Handles LEASE and KEY-LEASE configurations.
624      *
625      */
626     class LeaseConfig : public otSrpServerLeaseConfig
627     {
628         friend class Server;
629 
630     public:
631         /**
632          * Initialize to default LEASE and KEY-LEASE configurations.
633          *
634          */
635         LeaseConfig(void);
636 
637     private:
638         bool     IsValid(void) const;
639         uint32_t GrantLease(uint32_t aLease) const;
640         uint32_t GrantKeyLease(uint32_t aKeyLease) const;
641     };
642 
643     /**
644      * Initializes the SRP server object.
645      *
646      * @param[in]  aInstance  A reference to the OpenThread instance.
647      *
648      */
649     explicit Server(Instance &aInstance);
650 
651     /**
652      * Sets the SRP service events handler.
653      *
654      * @param[in]  aServiceHandler         A service events handler.
655      * @param[in]  aServiceHandlerContext  A pointer to arbitrary context information.
656      *
657      * @note  The handler SHOULD call HandleServiceUpdateResult to report the result of its processing.
658      *        Otherwise, a SRP update will be considered failed.
659      *
660      * @sa  HandleServiceUpdateResult
661      *
662      */
SetServiceHandler(otSrpServerServiceUpdateHandler aServiceHandler,void * aServiceHandlerContext)663     void SetServiceHandler(otSrpServerServiceUpdateHandler aServiceHandler, void *aServiceHandlerContext)
664     {
665         mServiceUpdateHandler.Set(aServiceHandler, aServiceHandlerContext);
666     }
667 
668     /**
669      * Returns the domain authorized to the SRP server.
670      *
671      * If the domain if not set by SetDomain, "default.service.arpa." will be returned.
672      * A trailing dot is always appended even if the domain is set without it.
673      *
674      * @returns A pointer to the dot-joined domain string.
675      *
676      */
GetDomain(void) const677     const char *GetDomain(void) const { return mDomain.AsCString(); }
678 
679     /**
680      * Sets the domain on the SRP server.
681      *
682      * A trailing dot will be appended to @p aDomain if it is not already there.
683      * Should only be called before the SRP server is enabled.
684      *
685      * @param[in]  aDomain  The domain to be set. MUST NOT be `nullptr`.
686      *
687      * @retval  kErrorNone          Successfully set the domain to @p aDomain.
688      * @retval  kErrorInvalidState  The SRP server is already enabled and the Domain cannot be changed.
689      * @retval  kErrorInvalidArgs   The argument @p aDomain is not a valid DNS domain name.
690      * @retval  kErrorNoBufs        There is no memory to store content of @p aDomain.
691      *
692      */
693     Error SetDomain(const char *aDomain);
694 
695     /**
696      * Returns the address mode being used by the SRP server.
697      *
698      * @returns The SRP server's address mode.
699      *
700      */
GetAddressMode(void) const701     AddressMode GetAddressMode(void) const { return mAddressMode; }
702 
703     /**
704      * Sets the address mode to be used by the SRP server.
705      *
706      * @param[in] aMode      The address mode to use.
707      *
708      * @retval kErrorNone           Successfully set the address mode.
709      * @retval kErrorInvalidState   The SRP server is enabled and the address mode cannot be changed.
710      *
711      */
712     Error SetAddressMode(AddressMode aMode);
713 
714     /**
715      * Gets the sequence number used with anycast address mode.
716      *
717      * The sequence number is included in "DNS/SRP Service Anycast Address" entry published in the Network Data.
718      *
719      * @returns The anycast sequence number.
720      *
721      */
GetAnycastModeSequenceNumber(void) const722     uint8_t GetAnycastModeSequenceNumber(void) const { return mAnycastSequenceNumber; }
723 
724     /**
725      * Sets the sequence number used with anycast address mode.
726      *
727      * @param[in] aSequenceNumber  The sequence number to use.
728      *
729      * @retval kErrorNone           Successfully set the address mode.
730      * @retval kErrorInvalidState   The SRP server is enabled and the sequence number cannot be changed.
731      *
732      */
733     Error SetAnycastModeSequenceNumber(uint8_t aSequenceNumber);
734 
735     /**
736      * Returns the state of the SRP server.
737      *
738      * @returns  The state of the server.
739      *
740      */
GetState(void) const741     State GetState(void) const { return mState; }
742 
743     /**
744      * Tells the port the SRP server is listening to.
745      *
746      * @returns  The port of the server or 0 if the SRP server is not running.
747      *
748      */
GetPort(void) const749     uint16_t GetPort(void) const { return (mState == kStateRunning) ? mPort : 0; }
750 
751     /**
752      * Enables/disables the SRP server.
753      *
754      * @param[in]  aEnabled  A boolean to enable/disable the SRP server.
755      *
756      */
757     void SetEnabled(bool aEnabled);
758 
759 #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE
760     /**
761      * Enables/disables the auto-enable mode on SRP server.
762      *
763      * When this mode is enabled, the Border Routing Manager controls if/when to enable or disable the SRP server.
764      * SRP sever is auto-enabled if/when Border Routing is started it is done with the initial prefix and route
765      * configurations (when the OMR and on-link prefixes are determined, advertised in emitted Router Advert message on
766      * infrastructure side and published in the Thread Network Data). The SRP server is auto-disabled when BR is
767      * stopped (e.g., if the infrastructure network interface is brought down or if BR gets detached).
768      *
769      * This mode can be disabled by a `SetAutoEnableMode(false)` call or if the SRP server is explicitly enabled or
770      * disabled by a call to `SetEnabled()` method. Disabling auto-enable mode using `SetAutoEnableMode(false` call
771      * will not change the current state of SRP sever (e.g., if it is enabled it stays enabled).
772      *
773      * @param[in] aEnabled    A boolean to enable/disable the auto-enable mode.
774      *
775      */
776     void SetAutoEnableMode(bool aEnabled);
777 
778     /**
779      * Indicates whether the auto-enable mode is enabled or disabled.
780      *
781      * @retval TRUE   The auto-enable mode is enabled.
782      * @retval FALSE  The auto-enable mode is disabled.
783      *
784      */
IsAutoEnableMode(void) const785     bool IsAutoEnableMode(void) const { return mAutoEnable; }
786 #endif
787 
788     /**
789      * Returns the TTL configuration.
790      *
791      * @param[out]  aTtlConfig  A reference to the `TtlConfig` instance.
792      *
793      */
GetTtlConfig(TtlConfig & aTtlConfig) const794     void GetTtlConfig(TtlConfig &aTtlConfig) const { aTtlConfig = mTtlConfig; }
795 
796     /**
797      * Sets the TTL configuration.
798      *
799      * @param[in]  aTtlConfig  A reference to the `TtlConfig` instance.
800      *
801      * @retval  kErrorNone         Successfully set the TTL configuration
802      * @retval  kErrorInvalidArgs  The TTL range is not valid.
803      *
804      */
805     Error SetTtlConfig(const TtlConfig &aTtlConfig);
806 
807     /**
808      * Returns the LEASE and KEY-LEASE configurations.
809      *
810      * @param[out]  aLeaseConfig  A reference to the `LeaseConfig` instance.
811      *
812      */
GetLeaseConfig(LeaseConfig & aLeaseConfig) const813     void GetLeaseConfig(LeaseConfig &aLeaseConfig) const { aLeaseConfig = mLeaseConfig; }
814 
815     /**
816      * Sets the LEASE and KEY-LEASE configurations.
817      *
818      * When a LEASE time is requested from a client, the granted value will be
819      * limited in range [aMinLease, aMaxLease]; and a KEY-LEASE will be granted
820      * in range [aMinKeyLease, aMaxKeyLease].
821      *
822      * @param[in]  aLeaseConfig  A reference to the `LeaseConfig` instance.
823      *
824      * @retval  kErrorNone         Successfully set the LEASE and KEY-LEASE ranges.
825      * @retval  kErrorInvalidArgs  The LEASE or KEY-LEASE range is not valid.
826      *
827      */
828     Error SetLeaseConfig(const LeaseConfig &aLeaseConfig);
829 
830     /**
831      * Returns the `Host` linked list.
832      *
833      * @returns The `Host` linked list.
834      *
835      */
GetHosts(void) const836     const LinkedList<Host> &GetHosts(void) const { return mHosts; }
837 
838     /**
839      * Returns the next registered SRP host.
840      *
841      * @param[in]  aHost  The current SRP host; use `nullptr` to get the first SRP host.
842      *
843      * @returns  A pointer to the next SRP host or `nullptr` if no more SRP hosts can be found.
844      *
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      *
853      */
GetResponseCounters(void) const854     const otSrpServerResponseCounters *GetResponseCounters(void) const { return &mResponseCounters; }
855 
856     /**
857      * Receives the service update result from service handler set by
858      * SetServiceHandler.
859      *
860      * @param[in]  aId     The ID of the service update transaction.
861      * @param[in]  aError  The service update result.
862      *
863      */
864     void HandleServiceUpdateResult(ServiceUpdateId aId, Error aError);
865 
866 private:
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 kAnycastAddressModePort = 53;
881 
882     // Metadata for a received SRP Update message.
883     struct MessageMetadata
884     {
885         // Indicates whether the `Message` is received directly from a
886         // client or from an SRPL partner.
IsDirectRxFromClientot::Srp::Server::MessageMetadata887         bool IsDirectRxFromClient(void) const { return (mMessageInfo != nullptr); }
888 
889         Dns::UpdateHeader       mDnsHeader;
890         Dns::Zone               mDnsZone;
891         uint16_t                mOffset;
892         TimeMilli               mRxTime;
893         TtlConfig               mTtlConfig;
894         LeaseConfig             mLeaseConfig;
895         const Ip6::MessageInfo *mMessageInfo; // Set to `nullptr` when from SRPL.
896     };
897 
898     // This class includes metadata for processing a SRP update (register, deregister)
899     // and sending DNS response to the client.
900     class UpdateMetadata : public InstanceLocator,
901                            public LinkedListEntry<UpdateMetadata>,
902                            public Heap::Allocatable<UpdateMetadata>
903     {
904         friend class LinkedListEntry<UpdateMetadata>;
905         friend class Heap::Allocatable<UpdateMetadata>;
906 
907     public:
GetExpireTime(void) const908         TimeMilli                GetExpireTime(void) const { return mExpireTime; }
GetDnsHeader(void) const909         const Dns::UpdateHeader &GetDnsHeader(void) const { return mDnsHeader; }
GetId(void) const910         ServiceUpdateId          GetId(void) const { return mId; }
GetTtlConfig(void) const911         const TtlConfig         &GetTtlConfig(void) const { return mTtlConfig; }
GetLeaseConfig(void) const912         const LeaseConfig       &GetLeaseConfig(void) const { return mLeaseConfig; }
GetHost(void)913         Host                    &GetHost(void) { return mHost; }
GetMessageInfo(void) const914         const Ip6::MessageInfo  &GetMessageInfo(void) const { return mMessageInfo; }
GetError(void) const915         Error                    GetError(void) const { return mError; }
SetError(Error aError)916         void                     SetError(Error aError) { mError = aError; }
IsDirectRxFromClient(void) const917         bool                     IsDirectRxFromClient(void) const { return mIsDirectRxFromClient; }
Matches(ServiceUpdateId aId) const918         bool                     Matches(ServiceUpdateId aId) const { return mId == aId; }
919 
920     private:
921         UpdateMetadata(Instance &aInstance, Host &aHost, const MessageMetadata &aMessageMetadata);
922 
923         UpdateMetadata   *mNext;
924         TimeMilli         mExpireTime;
925         Dns::UpdateHeader mDnsHeader;
926         ServiceUpdateId   mId;          // The ID of this service update transaction.
927         TtlConfig         mTtlConfig;   // TTL config to use when processing the message.
928         LeaseConfig       mLeaseConfig; // Lease config to use when processing the message.
929         Host             &mHost;        // The `UpdateMetadata` has no ownership of this host.
930         Ip6::MessageInfo  mMessageInfo; // Valid when `mIsDirectRxFromClient` is true.
931         Error             mError;
932         bool              mIsDirectRxFromClient;
933     };
934 
935     void              Enable(void);
936     void              Disable(void);
937     void              Start(void);
938     void              Stop(void);
939     void              SelectPort(void);
940     void              PrepareSocket(void);
941     Ip6::Udp::Socket &GetSocket(void);
942 
943 #if OPENTHREAD_CONFIG_DNSSD_SERVER_ENABLE
944     void  HandleDnssdServerStateChange(void);
945     Error HandleDnssdServerUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
946 #endif
947 
948     void HandleNetDataPublisherEvent(NetworkData::Publisher::Event aEvent);
949 
AllocateId(void)950     ServiceUpdateId AllocateId(void) { return mServiceUpdateId++; }
951 
952     void  InformUpdateHandlerOrCommit(Error aError, Host &aHost, const MessageMetadata &aMetadata);
953     void  CommitSrpUpdate(Error aError, Host &aHost, const MessageMetadata &aMessageMetadata);
954     void  CommitSrpUpdate(UpdateMetadata &aUpdateMetadata);
955     void  CommitSrpUpdate(Error                    aError,
956                           Host                    &aHost,
957                           const Dns::UpdateHeader &aDnsHeader,
958                           const Ip6::MessageInfo  *aMessageInfo,
959                           const TtlConfig         &aTtlConfig,
960                           const LeaseConfig       &aLeaseConfig);
961     Error ProcessMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
962     Error ProcessMessage(Message                &aMessage,
963                          TimeMilli               aRxTime,
964                          const TtlConfig        &aTtlConfig,
965                          const LeaseConfig      &aLeaseConfig,
966                          const Ip6::MessageInfo *aMessageInfo);
967     void  ProcessDnsUpdate(Message &aMessage, MessageMetadata &aMetadata);
968     Error ProcessUpdateSection(Host &aHost, const Message &aMessage, MessageMetadata &aMetadata) const;
969     Error ProcessAdditionalSection(Host *aHost, const Message &aMessage, MessageMetadata &aMetadata) const;
970     Error VerifySignature(const Host::Key  &aKey,
971                           const Message    &aMessage,
972                           Dns::UpdateHeader aDnsHeader,
973                           uint16_t          aSigOffset,
974                           uint16_t          aSigRdataOffset,
975                           uint16_t          aSigRdataLength,
976                           const char       *aSignerName) const;
977     Error ProcessZoneSection(const Message &aMessage, MessageMetadata &aMetadata) const;
978     Error ProcessHostDescriptionInstruction(Host                  &aHost,
979                                             const Message         &aMessage,
980                                             const MessageMetadata &aMetadata) const;
981     Error ProcessServiceDiscoveryInstructions(Host                  &aHost,
982                                               const Message         &aMessage,
983                                               const MessageMetadata &aMetadata) const;
984     Error ProcessServiceDescriptionInstructions(Host &aHost, const Message &aMessage, MessageMetadata &aMetadata) const;
985 
986     static bool IsValidDeleteAllRecord(const Dns::ResourceRecord &aRecord);
987 
988     void        HandleUpdate(Host &aHost, const MessageMetadata &aMetadata);
989     void        RemoveHost(Host *aHost, RetainName aRetainName);
990     bool        HasNameConflictsWith(Host &aHost) const;
991     void        SendResponse(const Dns::UpdateHeader    &aHeader,
992                              Dns::UpdateHeader::Response aResponseCode,
993                              const Ip6::MessageInfo     &aMessageInfo);
994     void        SendResponse(const Dns::UpdateHeader &aHeader,
995                              uint32_t                 aLease,
996                              uint32_t                 aKeyLease,
997                              bool                     mUseShortLeaseOption,
998                              const Ip6::MessageInfo  &aMessageInfo);
999     static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo);
1000     void        HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
1001     void        HandleLeaseTimer(void);
1002     static void HandleOutstandingUpdatesTimer(Timer &aTimer);
1003     void        HandleOutstandingUpdatesTimer(void);
1004     void        ProcessCompletedUpdates(void);
1005 
1006     const UpdateMetadata *FindOutstandingUpdate(const MessageMetadata &aMessageMetadata) const;
1007     static const char    *AddressModeToString(AddressMode aMode);
1008 
1009     void UpdateResponseCounters(Dns::Header::Response aResponseCode);
1010 
1011     using LeaseTimer           = TimerMilliIn<Server, &Server::HandleLeaseTimer>;
1012     using UpdateTimer          = TimerMilliIn<Server, &Server::HandleOutstandingUpdatesTimer>;
1013     using CompletedUpdatesTask = TaskletIn<Server, &Server::ProcessCompletedUpdates>;
1014 
1015     Ip6::Udp::Socket mSocket;
1016 
1017     Callback<otSrpServerServiceUpdateHandler> mServiceUpdateHandler;
1018 
1019     Heap::String mDomain;
1020 
1021     TtlConfig   mTtlConfig;
1022     LeaseConfig mLeaseConfig;
1023 
1024     LinkedList<Host> mHosts;
1025     LeaseTimer       mLeaseTimer;
1026 
1027     UpdateTimer                mOutstandingUpdatesTimer;
1028     LinkedList<UpdateMetadata> mOutstandingUpdates;
1029     LinkedList<UpdateMetadata> mCompletedUpdates;
1030     CompletedUpdatesTask       mCompletedUpdateTask;
1031 
1032     ServiceUpdateId mServiceUpdateId;
1033     uint16_t        mPort;
1034     State           mState;
1035     AddressMode     mAddressMode;
1036     uint8_t         mAnycastSequenceNumber;
1037     bool            mHasRegisteredAnyService : 1;
1038 #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE
1039     bool mAutoEnable : 1;
1040 #endif
1041 
1042     otSrpServerResponseCounters mResponseCounters;
1043 };
1044 
1045 } // namespace Srp
1046 
1047 DefineCoreType(otSrpServerTtlConfig, Srp::Server::TtlConfig);
1048 DefineCoreType(otSrpServerLeaseConfig, Srp::Server::LeaseConfig);
1049 DefineCoreType(otSrpServerHost, Srp::Server::Host);
1050 DefineCoreType(otSrpServerService, Srp::Server::Service);
1051 DefineMapEnum(otSrpServerState, Srp::Server::State);
1052 DefineMapEnum(otSrpServerAddressMode, Srp::Server::AddressMode);
1053 
1054 } // namespace ot
1055 
1056 #endif // OPENTHREAD_CONFIG_SRP_SERVER_ENABLE
1057 #endif // NET_SRP_SERVER_HPP_
1058