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 managing Domain Unicast Address feature defined in Thread 1.2.
32  */
33 
34 #ifndef DUA_MANAGER_HPP_
35 #define DUA_MANAGER_HPP_
36 
37 #include "openthread-core-config.h"
38 
39 #if OPENTHREAD_CONFIG_DUA_ENABLE || (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE)
40 
41 #if OPENTHREAD_CONFIG_DUA_ENABLE && (OPENTHREAD_CONFIG_THREAD_VERSION < OT_THREAD_VERSION_1_2)
42 #error "Thread 1.2 or higher version is required for OPENTHREAD_CONFIG_DUA_ENABLE"
43 #endif
44 
45 #if OPENTHREAD_CONFIG_DUA_ENABLE && !OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE
46 #error "OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE is required for OPENTHREAD_CONFIG_DUA_ENABLE"
47 #endif
48 
49 #include "backbone_router/bbr_leader.hpp"
50 #include "coap/coap_message.hpp"
51 #include "common/locator.hpp"
52 #include "common/non_copyable.hpp"
53 #include "common/notifier.hpp"
54 #include "common/tasklet.hpp"
55 #include "common/time.hpp"
56 #include "common/time_ticker.hpp"
57 #include "common/timer.hpp"
58 #include "net/netif.hpp"
59 #include "thread/thread_tlvs.hpp"
60 #include "thread/tmf.hpp"
61 #include "thread/topology.hpp"
62 
63 namespace ot {
64 
65 /**
66  * @addtogroup core-dua
67  *
68  * @brief
69  *   This module includes definitions for generating, managing, registering Domain Unicast Address.
70  *
71  * @{
72  *
73  * @defgroup core-dua Dua
74  *
75  * @}
76  *
77  */
78 
79 /**
80  * This class implements managing DUA.
81  *
82  */
83 class DuaManager : public InstanceLocator, private NonCopyable
84 {
85     friend class ot::Notifier;
86     friend class ot::TimeTicker;
87     friend class Tmf::Agent;
88 
89 public:
90     /**
91      * This constructor initializes the object.
92      *
93      * @param[in]  aInstance     A reference to the OpenThread instance.
94      *
95      */
96     explicit DuaManager(Instance &aInstance);
97 
98     /**
99      * This method notifies Domain Prefix status.
100      *
101      * @param[in]  aState  The Domain Prefix state or state change.
102      *
103      */
104     void HandleDomainPrefixUpdate(BackboneRouter::Leader::DomainPrefixState aState);
105 
106     /**
107      * This method notifies Primary Backbone Router status.
108      *
109      * @param[in]  aState   The state or state change of Primary Backbone Router.
110      * @param[in]  aConfig  The Primary Backbone Router service.
111      *
112      */
113     void HandleBackboneRouterPrimaryUpdate(BackboneRouter::Leader::State aState, const BackboneRouter::Config &aConfig);
114 
115 #if OPENTHREAD_CONFIG_DUA_ENABLE
116 
117     /**
118      * This method returns a reference to the Domain Unicast Address.
119      *
120      * @returns A reference to the Domain Unicast Address.
121      *
122      */
GetDomainUnicastAddress(void) const123     const Ip6::Address &GetDomainUnicastAddress(void) const { return mDomainUnicastAddress.GetAddress(); }
124 
125     /**
126      * This method sets the Interface Identifier manually specified for the Thread Domain Unicast Address.
127      *
128      * @param[in]  aIid        A reference to the Interface Identifier to set.
129      *
130      * @retval kErrorNone          Successfully set the Interface Identifier.
131      * @retval kErrorInvalidArgs   The specified Interface Identifier is reserved.
132      *
133      */
134     Error SetFixedDuaInterfaceIdentifier(const Ip6::InterfaceIdentifier &aIid);
135 
136     /**
137      * This method clears the Interface Identifier manually specified for the Thread Domain Unicast Address.
138      *
139      */
140     void ClearFixedDuaInterfaceIdentifier(void);
141 
142     /**
143      * This method indicates whether or not there is Interface Identifier manually specified for the Thread
144      * Domain Unicast Address.
145      *
146      * @retval true  If there is Interface Identifier manually specified.
147      * @retval false If there is no Interface Identifier manually specified.
148      *
149      */
IsFixedDuaInterfaceIdentifierSet(void)150     bool IsFixedDuaInterfaceIdentifierSet(void) { return !mFixedDuaInterfaceIdentifier.IsUnspecified(); }
151 
152     /**
153      * This method gets the Interface Identifier for the Thread Domain Unicast Address if manually specified.
154      *
155      * @returns A reference to the Interface Identifier.
156      *
157      */
GetFixedDuaInterfaceIdentifier(void) const158     const Ip6::InterfaceIdentifier &GetFixedDuaInterfaceIdentifier(void) const { return mFixedDuaInterfaceIdentifier; }
159 
160     /*
161      * This method restores duplicate address detection information from non-volatile memory.
162      *
163      */
164     void Restore(void);
165 
166     /**
167      * This method notifies duplicated Domain Unicast Address.
168      *
169      */
170     void NotifyDuplicateDomainUnicastAddress(void);
171 #endif
172 
173 #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE
174     void UpdateChildDomainUnicastAddress(const Child &aChild, Mle::ChildDuaState aState);
175 #endif
176 
177 private:
178     static constexpr uint8_t kNewRouterRegistrationDelay = 3; ///< Delay (in sec) to establish link for a new router.
179     static constexpr uint8_t kNewDuaRegistrationDelay    = 1; ///< Delay (in sec) for newly added DUA.
180 
181 #if OPENTHREAD_CONFIG_DUA_ENABLE
182     Error GenerateDomainUnicastAddressIid(void);
183     Error Store(void);
184 
185     void AddDomainUnicastAddress(void);
186     void RemoveDomainUnicastAddress(void);
187     void UpdateRegistrationDelay(uint8_t aDelay);
188 #endif
189 
190 #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE
191     void SendAddressNotification(Ip6::Address &aAddress, ThreadStatusTlv::DuaStatus aStatus, const Child &aChild);
192 #endif
193 
194     void HandleNotifierEvents(Events aEvents);
195 
196     void HandleTimeTick(void);
197 
198     void UpdateTimeTickerRegistration(void);
199 
200     static void HandleDuaResponse(void                *aContext,
201                                   otMessage           *aMessage,
202                                   const otMessageInfo *aMessageInfo,
203                                   Error                aResult);
204     void        HandleDuaResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult);
205 
206     template <Uri kUri> void HandleTmf(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
207 
208     Error ProcessDuaResponse(Coap::Message &aMessage);
209 
210     void PerformNextRegistration(void);
211     void UpdateReregistrationDelay(void);
212     void UpdateCheckDelay(uint8_t aDelay);
213 
214     using RegistrationTask = TaskletIn<DuaManager, &DuaManager::PerformNextRegistration>;
215 
216     RegistrationTask mRegistrationTask;
217     Ip6::Address     mRegisteringDua;
218     bool             mIsDuaPending : 1;
219 
220 #if OPENTHREAD_CONFIG_DUA_ENABLE
221     enum DuaState : uint8_t
222     {
223         kNotExist,    ///< DUA is not available.
224         kToRegister,  ///< DUA is to be registered.
225         kRegistering, ///< DUA is being registered.
226         kRegistered,  ///< DUA is registered.
227     };
228 
229     DuaState  mDuaState;
230     uint8_t   mDadCounter;
231     TimeMilli mLastRegistrationTime; // The time (in milliseconds) when sent last DUA.req or received DUA.rsp.
232     Ip6::InterfaceIdentifier   mFixedDuaInterfaceIdentifier;
233     Ip6::Netif::UnicastAddress mDomainUnicastAddress;
234 #endif
235 
236     union
237     {
238         struct
239         {
240             uint16_t mReregistrationDelay; // Delay (in seconds) for DUA re-registration.
241             uint8_t  mCheckDelay;          // Delay (in seconds) for checking whether or not registration is required.
242 #if OPENTHREAD_CONFIG_DUA_ENABLE
243             uint8_t mRegistrationDelay; // Delay (in seconds) for DUA registration.
244 #endif
245         } mFields;
246         uint32_t mValue; // Non-zero indicates timer should start.
247     } mDelay;
248 
249 #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE
250     // TODO: (DUA) may re-evaluate the alternative option of distributing the flags into the child table:
251     //       - Child class itself have some padding - may save some RAM
252     //       - Avoid cross reference between a bit-vector and the child entry
253     ChildMask mChildDuaMask;             // Child Mask for child who registers DUA via Child Update Request.
254     ChildMask mChildDuaRegisteredMask;   // Child Mask for child's DUA that was registered by the parent on behalf.
255     uint16_t  mChildIndexDuaRegistering; // Child Index of the DUA being registered.
256 #endif
257 };
258 
259 DeclareTmfHandler(DuaManager, kUriDuaRegistrationNotify);
260 
261 } // namespace ot
262 
263 #endif // OPENTHREAD_CONFIG_DUA_ENABLE || (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE)
264 #endif // DUA_MANAGER_HPP_
265