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 #include "srp_client.hpp"
30 
31 #if OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE
32 
33 #include "common/as_core_type.hpp"
34 #include "common/code_utils.hpp"
35 #include "common/debug.hpp"
36 #include "common/instance.hpp"
37 #include "common/locator_getters.hpp"
38 #include "common/num_utils.hpp"
39 #include "common/random.hpp"
40 #include "common/settings.hpp"
41 #include "common/string.hpp"
42 
43 /**
44  * @file
45  *   This file implements the SRP client.
46  */
47 
48 namespace ot {
49 namespace Srp {
50 
51 RegisterLogModule("SrpClient");
52 
53 //---------------------------------------------------------------------
54 // Client::HostInfo
55 
Init(void)56 void Client::HostInfo::Init(void)
57 {
58     Clearable<HostInfo>::Clear();
59 
60     // State is directly set on `mState` instead of using `SetState()`
61     // to avoid logging.
62     mState = OT_SRP_CLIENT_ITEM_STATE_REMOVED;
63 }
64 
Clear(void)65 void Client::HostInfo::Clear(void)
66 {
67     Clearable<HostInfo>::Clear();
68     SetState(kRemoved);
69 }
70 
SetState(ItemState aState)71 void Client::HostInfo::SetState(ItemState aState)
72 {
73     if (aState != GetState())
74     {
75         LogInfo("HostInfo %s -> %s", ItemStateToString(GetState()), ItemStateToString(aState));
76         mState = MapEnum(aState);
77     }
78 }
79 
EnableAutoAddress(void)80 void Client::HostInfo::EnableAutoAddress(void)
81 {
82     mAddresses    = nullptr;
83     mNumAddresses = 0;
84     mAutoAddress  = true;
85 
86     LogInfo("HostInfo enabled auto address");
87 }
88 
SetAddresses(const Ip6::Address * aAddresses,uint8_t aNumAddresses)89 void Client::HostInfo::SetAddresses(const Ip6::Address *aAddresses, uint8_t aNumAddresses)
90 {
91     mAddresses    = aAddresses;
92     mNumAddresses = aNumAddresses;
93     mAutoAddress  = false;
94 
95     LogInfo("HostInfo set %d addrs", GetNumAddresses());
96 
97     for (uint8_t index = 0; index < GetNumAddresses(); index++)
98     {
99         LogInfo("%s", GetAddress(index).ToString().AsCString());
100     }
101 }
102 
103 //---------------------------------------------------------------------
104 // Client::Service
105 
Init(void)106 Error Client::Service::Init(void)
107 {
108     Error error = kErrorNone;
109 
110     VerifyOrExit((GetName() != nullptr) && (GetInstanceName() != nullptr), error = kErrorInvalidArgs);
111     VerifyOrExit((GetTxtEntries() != nullptr) || (GetNumTxtEntries() == 0), error = kErrorInvalidArgs);
112 
113     // State is directly set on `mState` instead of using `SetState()`
114     // to avoid logging.
115     mState = OT_SRP_CLIENT_ITEM_STATE_REMOVED;
116 
117     mLease    = Min(mLease, kMaxLease);
118     mKeyLease = Min(mKeyLease, kMaxLease);
119 
120 exit:
121     return error;
122 }
123 
SetState(ItemState aState)124 void Client::Service::SetState(ItemState aState)
125 {
126     VerifyOrExit(GetState() != aState);
127 
128     LogInfo("Service %s -> %s, \"%s\" \"%s\"", ItemStateToString(GetState()), ItemStateToString(aState),
129             GetInstanceName(), GetName());
130 
131     if (aState == kToAdd)
132     {
133         constexpr uint16_t kSubTypeLabelStringSize = 80;
134 
135         String<kSubTypeLabelStringSize> string;
136 
137         // Log more details only when entering `kToAdd` state.
138 
139         if (HasSubType())
140         {
141             const char *label;
142 
143             for (uint16_t index = 0; (label = GetSubTypeLabelAt(index)) != nullptr; index++)
144             {
145                 string.Append("%s\"%s\"", (index != 0) ? ", " : "", label);
146             }
147         }
148 
149         LogInfo("subtypes:[%s] port:%d weight:%d prio:%d txts:%d", string.AsCString(), GetPort(), GetWeight(),
150                 GetPriority(), GetNumTxtEntries());
151     }
152 
153     mState = MapEnum(aState);
154 
155 exit:
156     return;
157 }
158 
Matches(const Service & aOther) const159 bool Client::Service::Matches(const Service &aOther) const
160 {
161     // This method indicates whether or not two service entries match,
162     // i.e., have the same service and instance names. This is intended
163     // for use by `LinkedList::FindMatching()` to search within the
164     // `mServices` list.
165 
166     return (strcmp(GetName(), aOther.GetName()) == 0) && (strcmp(GetInstanceName(), aOther.GetInstanceName()) == 0);
167 }
168 
169 //---------------------------------------------------------------------
170 // Client::AutoStart
171 
172 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
173 
AutoStart(void)174 Client::AutoStart::AutoStart(void)
175 {
176     Clear();
177     mState = kDefaultMode ? kSelectedNone : kDisabled;
178 }
179 
HasSelectedServer(void) const180 bool Client::AutoStart::HasSelectedServer(void) const
181 {
182     bool hasSelected = false;
183 
184     switch (mState)
185     {
186     case kDisabled:
187     case kSelectedNone:
188         break;
189 
190     case kSelectedUnicastPreferred:
191     case kSelectedUnicast:
192     case kSelectedAnycast:
193         hasSelected = true;
194         break;
195     }
196 
197     return hasSelected;
198 }
199 
SetState(State aState)200 void Client::AutoStart::SetState(State aState)
201 {
202     if (mState != aState)
203     {
204         LogInfo("AutoStartState %s -> %s", StateToString(mState), StateToString(aState));
205         mState = aState;
206     }
207 }
208 
InvokeCallback(const Ip6::SockAddr * aServerSockAddr) const209 void Client::AutoStart::InvokeCallback(const Ip6::SockAddr *aServerSockAddr) const
210 {
211     mCallback.InvokeIfSet(aServerSockAddr);
212 }
213 
214 #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_INFO)
StateToString(State aState)215 const char *Client::AutoStart::StateToString(State aState)
216 {
217     static const char *const kStateStrings[] = {
218         "Disabled",    // (0) kDisabled
219         "Idle",        // (1) kSelectedNone
220         "Unicast-prf", // (2) kSelectedUnicastPreferred
221         "Anycast",     // (3) kSelectedAnycast
222         "Unicast",     // (4) kSelectedUnicast
223     };
224 
225     static_assert(0 == kDisabled, "kDisabled value is incorrect");
226     static_assert(1 == kSelectedNone, "kSelectedNone value is incorrect");
227     static_assert(2 == kSelectedUnicastPreferred, "kSelectedUnicastPreferred value is incorrect");
228     static_assert(3 == kSelectedAnycast, "kSelectedAnycast value is incorrect");
229     static_assert(4 == kSelectedUnicast, "kSelectedUnicast value is incorrect");
230 
231     return kStateStrings[aState];
232 }
233 #endif
234 
235 #endif // OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
236 
237 //---------------------------------------------------------------------
238 // Client
239 
240 const char Client::kDefaultDomainName[] = "default.service.arpa";
241 
Client(Instance & aInstance)242 Client::Client(Instance &aInstance)
243     : InstanceLocator(aInstance)
244     , mState(kStateStopped)
245     , mTxFailureRetryCount(0)
246     , mShouldRemoveKeyLease(false)
247     , mAutoHostAddressAddedMeshLocal(false)
248     , mSingleServiceMode(false)
249 #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE
250     , mServiceKeyRecordEnabled(false)
251     , mUseShortLeaseOption(false)
252 #endif
253     , mUpdateMessageId(0)
254     , mRetryWaitInterval(kMinRetryWaitInterval)
255     , mTtl(0)
256     , mLease(0)
257     , mKeyLease(0)
258     , mDefaultLease(kDefaultLease)
259     , mDefaultKeyLease(kDefaultKeyLease)
260     , mSocket(aInstance)
261     , mDomainName(kDefaultDomainName)
262     , mTimer(aInstance)
263 {
264     mHostInfo.Init();
265 
266     // The `Client` implementation uses different constant array of
267     // `ItemState` to define transitions between states in `Pause()`,
268     // `Stop()`, `SendUpdate`, and `ProcessResponse()`, or to convert
269     // an `ItemState` to string. Here, we assert that the enumeration
270     // values are correct.
271 
272     static_assert(kToAdd == 0, "kToAdd value is not correct");
273     static_assert(kAdding == 1, "kAdding value is not correct");
274     static_assert(kToRefresh == 2, "kToRefresh value is not correct");
275     static_assert(kRefreshing == 3, "kRefreshing value is not correct");
276     static_assert(kToRemove == 4, "kToRemove value is not correct");
277     static_assert(kRemoving == 5, "kRemoving value is not correct");
278     static_assert(kRegistered == 6, "kRegistered value is not correct");
279     static_assert(kRemoved == 7, "kRemoved value is not correct");
280 }
281 
Start(const Ip6::SockAddr & aServerSockAddr,Requester aRequester)282 Error Client::Start(const Ip6::SockAddr &aServerSockAddr, Requester aRequester)
283 {
284     Error error;
285 
286     VerifyOrExit(GetState() == kStateStopped,
287                  error = (aServerSockAddr == GetServerAddress()) ? kErrorNone : kErrorBusy);
288 
289     SuccessOrExit(error = mSocket.Open(Client::HandleUdpReceive, this));
290     SuccessOrExit(error = mSocket.Connect(aServerSockAddr));
291 
292     LogInfo("%starting, server %s", (aRequester == kRequesterUser) ? "S" : "Auto-s",
293             aServerSockAddr.ToString().AsCString());
294 
295     Resume();
296 
297 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
298     if (aRequester == kRequesterAuto)
299     {
300 #if OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE && OPENTHREAD_CONFIG_DNS_CLIENT_DEFAULT_SERVER_ADDRESS_AUTO_SET_ENABLE
301         Get<Dns::Client>().UpdateDefaultConfigAddress();
302 #endif
303         mAutoStart.InvokeCallback(&aServerSockAddr);
304     }
305 #endif
306 
307 exit:
308     return error;
309 }
310 
Stop(Requester aRequester,StopMode aMode)311 void Client::Stop(Requester aRequester, StopMode aMode)
312 {
313     // Change the state of host info and services so that they are
314     // added/removed again once the client is started back. In the
315     // case of `kAdding`, we intentionally move to `kToRefresh`
316     // instead of `kToAdd` since the server may receive our add
317     // request and the item may be registered on the server. This
318     // ensures that if we are later asked to remove the item, we do
319     // notify server.
320 
321     static const ItemState kNewStateOnStop[]{
322         /* (0) kToAdd      -> */ kToAdd,
323         /* (1) kAdding     -> */ kToRefresh,
324         /* (2) kToRefresh  -> */ kToRefresh,
325         /* (3) kRefreshing -> */ kToRefresh,
326         /* (4) kToRemove   -> */ kToRemove,
327         /* (5) kRemoving   -> */ kToRemove,
328         /* (6) kRegistered -> */ kToRefresh,
329         /* (7) kRemoved    -> */ kRemoved,
330     };
331 
332     VerifyOrExit(GetState() != kStateStopped);
333 
334     mSingleServiceMode = false;
335 
336     // State changes:
337     //   kAdding     -> kToRefresh
338     //   kRefreshing -> kToRefresh
339     //   kRemoving   -> kToRemove
340     //   kRegistered -> kToRefresh
341 
342     ChangeHostAndServiceStates(kNewStateOnStop, kForAllServices);
343 
344     IgnoreError(mSocket.Close());
345 
346     mShouldRemoveKeyLease = false;
347     mTxFailureRetryCount  = 0;
348 
349     if (aMode == kResetRetryInterval)
350     {
351         ResetRetryWaitInterval();
352     }
353 
354     SetState(kStateStopped);
355 
356 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
357 #if OPENTHREAD_CONFIG_SRP_CLIENT_SWITCH_SERVER_ON_FAILURE
358     mAutoStart.ResetTimeoutFailureCount();
359 #endif
360     if (aRequester == kRequesterAuto)
361     {
362         mAutoStart.InvokeCallback(nullptr);
363     }
364 #endif
365 
366 exit:
367 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
368     if (aRequester == kRequesterUser)
369     {
370         DisableAutoStartMode();
371     }
372 #endif
373 }
374 
Resume(void)375 void Client::Resume(void)
376 {
377     SetState(kStateUpdated);
378     UpdateState();
379 }
380 
Pause(void)381 void Client::Pause(void)
382 {
383     // Change the state of host info and services that are are being
384     // added or removed so that they are added/removed again once the
385     // client is resumed or started back.
386 
387     static const ItemState kNewStateOnPause[]{
388         /* (0) kToAdd      -> */ kToAdd,
389         /* (1) kAdding     -> */ kToRefresh,
390         /* (2) kToRefresh  -> */ kToRefresh,
391         /* (3) kRefreshing -> */ kToRefresh,
392         /* (4) kToRemove   -> */ kToRemove,
393         /* (5) kRemoving   -> */ kToRemove,
394         /* (6) kRegistered -> */ kRegistered,
395         /* (7) kRemoved    -> */ kRemoved,
396     };
397 
398     mSingleServiceMode = false;
399 
400     // State changes:
401     //   kAdding     -> kToRefresh
402     //   kRefreshing -> kToRefresh
403     //   kRemoving   -> kToRemove
404 
405     ChangeHostAndServiceStates(kNewStateOnPause, kForAllServices);
406 
407     SetState(kStatePaused);
408 }
409 
HandleNotifierEvents(Events aEvents)410 void Client::HandleNotifierEvents(Events aEvents)
411 {
412     if (aEvents.Contains(kEventThreadRoleChanged))
413     {
414         HandleRoleChanged();
415     }
416 
417 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
418     if (aEvents.ContainsAny(kEventThreadNetdataChanged | kEventThreadMeshLocalAddrChanged))
419     {
420         ProcessAutoStart();
421     }
422 #endif
423 
424     if (mHostInfo.IsAutoAddressEnabled())
425     {
426         Events::Flags eventFlags = (kEventIp6AddressAdded | kEventIp6AddressRemoved);
427 
428         if (mAutoHostAddressAddedMeshLocal)
429         {
430             eventFlags |= kEventThreadMeshLocalAddrChanged;
431         }
432 
433         if (aEvents.ContainsAny(eventFlags))
434         {
435             IgnoreError(UpdateHostInfoStateOnAddressChange());
436             UpdateState();
437         }
438     }
439 }
440 
HandleRoleChanged(void)441 void Client::HandleRoleChanged(void)
442 {
443     if (Get<Mle::Mle>().IsAttached())
444     {
445         VerifyOrExit(GetState() == kStatePaused);
446         Resume();
447     }
448     else
449     {
450         VerifyOrExit(GetState() != kStateStopped);
451         Pause();
452     }
453 
454 exit:
455     return;
456 }
457 
458 #if OPENTHREAD_CONFIG_SRP_CLIENT_DOMAIN_NAME_API_ENABLE
SetDomainName(const char * aName)459 Error Client::SetDomainName(const char *aName)
460 {
461     Error error = kErrorNone;
462 
463     VerifyOrExit((mHostInfo.GetState() == kToAdd) || (mHostInfo.GetState() == kRemoved), error = kErrorInvalidState);
464 
465     mDomainName = (aName != nullptr) ? aName : kDefaultDomainName;
466     LogInfo("Domain name \"%s\"", mDomainName);
467 
468 exit:
469     return error;
470 }
471 #endif
472 
SetHostName(const char * aName)473 Error Client::SetHostName(const char *aName)
474 {
475     Error error = kErrorNone;
476 
477     VerifyOrExit(aName != nullptr, error = kErrorInvalidArgs);
478 
479     VerifyOrExit((mHostInfo.GetState() == kToAdd) || (mHostInfo.GetState() == kRemoved), error = kErrorInvalidState);
480 
481     LogInfo("Host name \"%s\"", aName);
482     mHostInfo.SetName(aName);
483     mHostInfo.SetState(kToAdd);
484     UpdateState();
485 
486 exit:
487     return error;
488 }
489 
EnableAutoHostAddress(void)490 Error Client::EnableAutoHostAddress(void)
491 {
492     Error error = kErrorNone;
493 
494     VerifyOrExit(!mHostInfo.IsAutoAddressEnabled());
495     SuccessOrExit(error = UpdateHostInfoStateOnAddressChange());
496 
497     mHostInfo.EnableAutoAddress();
498     UpdateState();
499 
500 exit:
501     return error;
502 }
503 
SetHostAddresses(const Ip6::Address * aAddresses,uint8_t aNumAddresses)504 Error Client::SetHostAddresses(const Ip6::Address *aAddresses, uint8_t aNumAddresses)
505 {
506     Error error = kErrorNone;
507 
508     VerifyOrExit((aAddresses != nullptr) && (aNumAddresses > 0), error = kErrorInvalidArgs);
509     SuccessOrExit(error = UpdateHostInfoStateOnAddressChange());
510 
511     mHostInfo.SetAddresses(aAddresses, aNumAddresses);
512     UpdateState();
513 
514 exit:
515     return error;
516 }
517 
UpdateHostInfoStateOnAddressChange(void)518 Error Client::UpdateHostInfoStateOnAddressChange(void)
519 {
520     Error error = kErrorNone;
521 
522     VerifyOrExit((mHostInfo.GetState() != kToRemove) && (mHostInfo.GetState() != kRemoving),
523                  error = kErrorInvalidState);
524 
525     if (mHostInfo.GetState() == kRemoved)
526     {
527         mHostInfo.SetState(kToAdd);
528     }
529     else if (mHostInfo.GetState() != kToAdd)
530     {
531         mHostInfo.SetState(kToRefresh);
532     }
533 
534 exit:
535     return error;
536 }
537 
AddService(Service & aService)538 Error Client::AddService(Service &aService)
539 {
540     Error error;
541 
542     VerifyOrExit(mServices.FindMatching(aService) == nullptr, error = kErrorAlready);
543 
544     SuccessOrExit(error = aService.Init());
545     mServices.Push(aService);
546 
547     aService.SetState(kToAdd);
548     UpdateState();
549 
550 exit:
551     return error;
552 }
553 
RemoveService(Service & aService)554 Error Client::RemoveService(Service &aService)
555 {
556     Error               error = kErrorNone;
557     LinkedList<Service> removedServices;
558 
559     VerifyOrExit(mServices.Contains(aService), error = kErrorNotFound);
560 
561     UpdateServiceStateToRemove(aService);
562     UpdateState();
563 
564 exit:
565     return error;
566 }
567 
UpdateServiceStateToRemove(Service & aService)568 void Client::UpdateServiceStateToRemove(Service &aService)
569 {
570     if (aService.GetState() != kRemoving)
571     {
572         aService.SetState(kToRemove);
573     }
574 }
575 
ClearService(Service & aService)576 Error Client::ClearService(Service &aService)
577 {
578     Error error;
579 
580     SuccessOrExit(error = mServices.Remove(aService));
581     aService.SetNext(nullptr);
582     aService.SetState(kRemoved);
583     UpdateState();
584 
585 exit:
586     return error;
587 }
588 
RemoveHostAndServices(bool aShouldRemoveKeyLease,bool aSendUnregToServer)589 Error Client::RemoveHostAndServices(bool aShouldRemoveKeyLease, bool aSendUnregToServer)
590 {
591     Error error = kErrorNone;
592 
593     LogInfo("Remove host & services");
594 
595     VerifyOrExit(mHostInfo.GetState() != kRemoved, error = kErrorAlready);
596 
597     if ((mHostInfo.GetState() == kToRemove) || (mHostInfo.GetState() == kRemoving))
598     {
599         // Host info remove is already ongoing, if "key lease" remove mode is
600         // the same, there is no need to send a new update message.
601         VerifyOrExit(mShouldRemoveKeyLease != aShouldRemoveKeyLease);
602     }
603 
604     mShouldRemoveKeyLease = aShouldRemoveKeyLease;
605 
606     for (Service &service : mServices)
607     {
608         UpdateServiceStateToRemove(service);
609     }
610 
611     if ((mHostInfo.GetState() == kToAdd) && !aSendUnregToServer)
612     {
613         // Host info is not added yet (not yet registered with
614         // server), so we can remove it and all services immediately.
615         mHostInfo.SetState(kRemoved);
616         HandleUpdateDone();
617         ExitNow();
618     }
619 
620     mHostInfo.SetState(kToRemove);
621     UpdateState();
622 
623 exit:
624     return error;
625 }
626 
ClearHostAndServices(void)627 void Client::ClearHostAndServices(void)
628 {
629     LogInfo("Clear host & services");
630 
631     switch (GetState())
632     {
633     case kStateStopped:
634     case kStatePaused:
635         break;
636 
637     case kStateToUpdate:
638     case kStateUpdating:
639     case kStateUpdated:
640     case kStateToRetry:
641         SetState(kStateUpdated);
642         break;
643     }
644 
645     mTxFailureRetryCount = 0;
646     ResetRetryWaitInterval();
647 
648     mServices.Clear();
649     mHostInfo.Clear();
650 }
651 
SetState(State aState)652 void Client::SetState(State aState)
653 {
654     VerifyOrExit(aState != mState);
655 
656     LogInfo("State %s -> %s", StateToString(mState), StateToString(aState));
657     mState = aState;
658 
659     switch (mState)
660     {
661     case kStateStopped:
662     case kStatePaused:
663     case kStateUpdated:
664         mTimer.Stop();
665         break;
666 
667     case kStateToUpdate:
668         mTimer.Start(Random::NonCrypto::GetUint32InRange(kUpdateTxMinDelay, kUpdateTxMaxDelay));
669         break;
670 
671     case kStateUpdating:
672         mTimer.Start(GetRetryWaitInterval());
673         break;
674 
675     case kStateToRetry:
676         break;
677     }
678 exit:
679     return;
680 }
681 
ChangeHostAndServiceStates(const ItemState * aNewStates,ServiceStateChangeMode aMode)682 void Client::ChangeHostAndServiceStates(const ItemState *aNewStates, ServiceStateChangeMode aMode)
683 {
684 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SAVE_SELECTED_SERVER_ENABLE
685     ItemState oldHostState = mHostInfo.GetState();
686 #endif
687 
688     mHostInfo.SetState(aNewStates[mHostInfo.GetState()]);
689 
690     for (Service &service : mServices)
691     {
692         if ((aMode == kForServicesAppendedInMessage) && !service.IsAppendedInMessage())
693         {
694             continue;
695         }
696 
697         service.SetState(aNewStates[service.GetState()]);
698     }
699 
700 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SAVE_SELECTED_SERVER_ENABLE
701     if ((oldHostState != kRegistered) && (mHostInfo.GetState() == kRegistered))
702     {
703         Settings::SrpClientInfo info;
704 
705         switch (mAutoStart.GetState())
706         {
707         case AutoStart::kDisabled:
708         case AutoStart::kSelectedNone:
709             break;
710 
711         case AutoStart::kSelectedUnicastPreferred:
712         case AutoStart::kSelectedUnicast:
713             info.SetServerAddress(GetServerAddress().GetAddress());
714             info.SetServerPort(GetServerAddress().GetPort());
715             IgnoreError(Get<Settings>().Save(info));
716             break;
717 
718         case AutoStart::kSelectedAnycast:
719             IgnoreError(Get<Settings>().Delete<Settings::SrpClientInfo>());
720             break;
721         }
722     }
723 #endif // OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SAVE_SELECTED_SERVER_ENABLE
724 }
725 
InvokeCallback(Error aError) const726 void Client::InvokeCallback(Error aError) const { InvokeCallback(aError, mHostInfo, nullptr); }
727 
InvokeCallback(Error aError,const HostInfo & aHostInfo,const Service * aRemovedServices) const728 void Client::InvokeCallback(Error aError, const HostInfo &aHostInfo, const Service *aRemovedServices) const
729 {
730     mCallback.InvokeIfSet(aError, &aHostInfo, mServices.GetHead(), aRemovedServices);
731 }
732 
SendUpdate(void)733 void Client::SendUpdate(void)
734 {
735     static const ItemState kNewStateOnMessageTx[]{
736         /* (0) kToAdd      -> */ kAdding,
737         /* (1) kAdding     -> */ kAdding,
738         /* (2) kToRefresh  -> */ kRefreshing,
739         /* (3) kRefreshing -> */ kRefreshing,
740         /* (4) kToRemove   -> */ kRemoving,
741         /* (5) kRemoving   -> */ kRemoving,
742         /* (6) kRegistered -> */ kRegistered,
743         /* (7) kRemoved    -> */ kRemoved,
744     };
745 
746     Error    error   = kErrorNone;
747     Message *message = mSocket.NewMessage();
748     uint32_t length;
749 
750     VerifyOrExit(message != nullptr, error = kErrorNoBufs);
751     SuccessOrExit(error = PrepareUpdateMessage(*message));
752 
753     length = message->GetLength() + sizeof(Ip6::Udp::Header) + sizeof(Ip6::Header);
754 
755     if (length >= Ip6::kMaxDatagramLength)
756     {
757         LogInfo("Msg len %lu is larger than MTU, enabling single service mode", ToUlong(length));
758         mSingleServiceMode = true;
759         IgnoreError(message->SetLength(0));
760         SuccessOrExit(error = PrepareUpdateMessage(*message));
761     }
762 
763     SuccessOrExit(error = mSocket.SendTo(*message, Ip6::MessageInfo()));
764 
765     LogInfo("Send update");
766 
767     // State changes:
768     //   kToAdd     -> kAdding
769     //   kToRefresh -> kRefreshing
770     //   kToRemove  -> kRemoving
771 
772     ChangeHostAndServiceStates(kNewStateOnMessageTx, kForServicesAppendedInMessage);
773 
774     // Remember the update message tx time to use later to determine the
775     // lease renew time.
776     mLeaseRenewTime      = TimerMilli::GetNow();
777     mTxFailureRetryCount = 0;
778 
779     SetState(kStateUpdating);
780 
781     if (!Get<Mle::Mle>().IsRxOnWhenIdle())
782     {
783         // If device is sleepy send fast polls while waiting for
784         // the response from server.
785         Get<DataPollSender>().SendFastPolls(kFastPollsAfterUpdateTx);
786     }
787 
788 exit:
789     if (error != kErrorNone)
790     {
791         // If there is an error in preparation or transmission of the
792         // update message (e.g., no buffer to allocate message), up to
793         // `kMaxTxFailureRetries` times, we wait for a short interval
794         // `kTxFailureRetryInterval` and try again. After this, we
795         // continue to retry using the `mRetryWaitInterval` (which keeps
796         // growing on each failure).
797 
798         LogInfo("Failed to send update: %s", ErrorToString(error));
799 
800         mSingleServiceMode = false;
801         FreeMessage(message);
802 
803         SetState(kStateToRetry);
804 
805         if (mTxFailureRetryCount < kMaxTxFailureRetries)
806         {
807             uint32_t interval;
808 
809             mTxFailureRetryCount++;
810             interval = Random::NonCrypto::AddJitter(kTxFailureRetryInterval, kTxFailureRetryJitter);
811             mTimer.Start(interval);
812 
813             LogInfo("Quick retry %u in %lu msec", mTxFailureRetryCount, ToUlong(interval));
814 
815             // Do not report message preparation errors to user
816             // until `kMaxTxFailureRetries` are exhausted.
817         }
818         else
819         {
820             LogRetryWaitInterval();
821             mTimer.Start(Random::NonCrypto::AddJitter(GetRetryWaitInterval(), kRetryIntervalJitter));
822             GrowRetryWaitInterval();
823             InvokeCallback(error);
824         }
825     }
826 }
827 
PrepareUpdateMessage(Message & aMessage)828 Error Client::PrepareUpdateMessage(Message &aMessage)
829 {
830     constexpr uint16_t kHeaderOffset = 0;
831 
832     Error             error = kErrorNone;
833     Dns::UpdateHeader header;
834     Info              info;
835 
836     info.Clear();
837 
838 #if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
839     info.mKeyRef.SetKeyRef(kSrpEcdsaKeyRef);
840     SuccessOrExit(error = ReadOrGenerateKey(info.mKeyRef));
841 #else
842     SuccessOrExit(error = ReadOrGenerateKey(info.mKeyPair));
843 #endif
844 
845     // Generate random Message ID and ensure it is different from last one
846     do
847     {
848         SuccessOrExit(error = header.SetRandomMessageId());
849     } while (header.GetMessageId() == mUpdateMessageId);
850 
851     mUpdateMessageId = header.GetMessageId();
852 
853     // SRP Update (DNS Update) message must have exactly one record in
854     // Zone section, no records in Prerequisite Section, can have
855     // multiple records in Update Section (tracked as they are added),
856     // and two records in Additional Data Section (OPT and SIG records).
857     // The SIG record itself should not be included in calculation of
858     // SIG(0) signature, so the addition record count is set to one
859     // here. After signature calculation and appending of SIG record,
860     // the additional record count is updated to two and the header is
861     // rewritten in the message.
862 
863     header.SetZoneRecordCount(1);
864     header.SetAdditionalRecordCount(1);
865     SuccessOrExit(error = aMessage.Append(header));
866 
867     // Prepare Zone section
868 
869     info.mDomainNameOffset = aMessage.GetLength();
870     SuccessOrExit(error = Dns::Name::AppendName(mDomainName, aMessage));
871     SuccessOrExit(error = aMessage.Append(Dns::Zone()));
872 
873     // Prepare Update section
874 
875     SuccessOrExit(error = AppendServiceInstructions(aMessage, info));
876     SuccessOrExit(error = AppendHostDescriptionInstruction(aMessage, info));
877 
878     header.SetUpdateRecordCount(info.mRecordCount);
879     aMessage.Write(kHeaderOffset, header);
880 
881     // Prepare Additional Data section
882 
883     SuccessOrExit(error = AppendUpdateLeaseOptRecord(aMessage));
884     SuccessOrExit(error = AppendSignature(aMessage, info));
885 
886     header.SetAdditionalRecordCount(2); // Lease OPT and SIG RRs
887     aMessage.Write(kHeaderOffset, header);
888 
889 exit:
890     return error;
891 }
892 
893 #if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
ReadOrGenerateKey(Crypto::Ecdsa::P256::KeyPairAsRef & aKeyRef)894 Error Client::ReadOrGenerateKey(Crypto::Ecdsa::P256::KeyPairAsRef &aKeyRef)
895 {
896     Error                        error = kErrorNone;
897     Crypto::Ecdsa::P256::KeyPair keyPair;
898 
899     VerifyOrExit(!Crypto::Storage::HasKey(aKeyRef.GetKeyRef()));
900     error = Get<Settings>().Read<Settings::SrpEcdsaKey>(keyPair);
901 
902     if (error == kErrorNone)
903     {
904         Crypto::Ecdsa::P256::PublicKey publicKey;
905 
906         if (keyPair.GetPublicKey(publicKey) == kErrorNone)
907         {
908             SuccessOrExit(error = aKeyRef.ImportKeyPair(keyPair));
909             IgnoreError(Get<Settings>().Delete<Settings::SrpEcdsaKey>());
910             ExitNow();
911         }
912         IgnoreError(Get<Settings>().Delete<Settings::SrpEcdsaKey>());
913     }
914 
915     error = aKeyRef.Generate();
916 
917 exit:
918     return error;
919 }
920 #else
ReadOrGenerateKey(Crypto::Ecdsa::P256::KeyPair & aKeyPair)921 Error Client::ReadOrGenerateKey(Crypto::Ecdsa::P256::KeyPair &aKeyPair)
922 {
923     Error error;
924 
925     error = Get<Settings>().Read<Settings::SrpEcdsaKey>(aKeyPair);
926 
927     if (error == kErrorNone)
928     {
929         Crypto::Ecdsa::P256::PublicKey publicKey;
930 
931         if (aKeyPair.GetPublicKey(publicKey) == kErrorNone)
932         {
933             ExitNow();
934         }
935     }
936 
937     SuccessOrExit(error = aKeyPair.Generate());
938     IgnoreError(Get<Settings>().Save<Settings::SrpEcdsaKey>(aKeyPair));
939 
940 exit:
941     return error;
942 }
943 #endif //  OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
944 
AppendServiceInstructions(Message & aMessage,Info & aInfo)945 Error Client::AppendServiceInstructions(Message &aMessage, Info &aInfo)
946 {
947     Error error = kErrorNone;
948 
949     if ((mHostInfo.GetState() == kToRemove) || (mHostInfo.GetState() == kRemoving))
950     {
951         // When host is being removed, there is no need to include
952         // services in the message (server is expected to remove any
953         // previously registered services by this client). However, we
954         // still mark all services as if they are appended in the message
955         // so to ensure to update their state after sending the message.
956 
957         for (Service &service : mServices)
958         {
959             service.MarkAsAppendedInMessage();
960         }
961 
962         mLease    = 0;
963         mKeyLease = mShouldRemoveKeyLease ? 0 : mDefaultKeyLease;
964         ExitNow();
965     }
966 
967     mLease    = kUnspecifiedInterval;
968     mKeyLease = kUnspecifiedInterval;
969 
970     // We first go through all services which are being updated (in any
971     // of `...ing` states) and determine the lease and key lease intervals
972     // associated with them. By the end of the loop either of `mLease` or
973     // `mKeyLease` may be set or may still remain `kUnspecifiedInterval`.
974 
975     for (Service &service : mServices)
976     {
977         uint32_t lease    = DetermineLeaseInterval(service.GetLease(), mDefaultLease);
978         uint32_t keyLease = Max(DetermineLeaseInterval(service.GetKeyLease(), mDefaultKeyLease), lease);
979 
980         service.ClearAppendedInMessageFlag();
981 
982         switch (service.GetState())
983         {
984         case kAdding:
985         case kRefreshing:
986             OT_ASSERT((mLease == kUnspecifiedInterval) || (mLease == lease));
987             mLease = lease;
988 
989             OT_FALL_THROUGH;
990 
991         case kRemoving:
992             OT_ASSERT((mKeyLease == kUnspecifiedInterval) || (mKeyLease == keyLease));
993             mKeyLease = keyLease;
994             break;
995 
996         case kToAdd:
997         case kToRefresh:
998         case kToRemove:
999         case kRegistered:
1000         case kRemoved:
1001             break;
1002         }
1003     }
1004 
1005     // We go through all services again and append the services that
1006     // match the selected `mLease` and `mKeyLease`. If the lease intervals
1007     // are not yet set, the first appended service will determine them.
1008 
1009     for (Service &service : mServices)
1010     {
1011         // Skip over services that are already registered in this loop.
1012         // They may be added from the loop below once the lease intervals
1013         // are determined.
1014 
1015         if ((service.GetState() != kRegistered) && CanAppendService(service))
1016         {
1017             SuccessOrExit(error = AppendServiceInstruction(service, aMessage, aInfo));
1018 
1019             if (mSingleServiceMode)
1020             {
1021                 // In "single service mode", we allow only one service
1022                 // to be appended in the message.
1023                 break;
1024             }
1025         }
1026     }
1027 
1028     if (!mSingleServiceMode)
1029     {
1030         for (Service &service : mServices)
1031         {
1032             if ((service.GetState() == kRegistered) && CanAppendService(service) && ShouldRenewEarly(service))
1033             {
1034                 // If the lease needs to be renewed or if we are close to the
1035                 // renewal time of a registered service, we refresh the service
1036                 // early and include it in this update. This helps put more
1037                 // services on the same lease refresh schedule.
1038 
1039                 service.SetState(kToRefresh);
1040                 SuccessOrExit(error = AppendServiceInstruction(service, aMessage, aInfo));
1041             }
1042         }
1043     }
1044 
1045     // `mLease` or `mKeylease` may be determined from the set of
1046     // services included in the message. If they are not yet set we
1047     // use the default intervals.
1048 
1049     mLease    = DetermineLeaseInterval(mLease, mDefaultLease);
1050     mKeyLease = DetermineLeaseInterval(mKeyLease, mDefaultKeyLease);
1051 
1052     // When message only contains removal of a previously registered
1053     // service, then `mKeyLease` is set but `mLease` remains unspecified.
1054     // In such a case, we end up using `mDefaultLease` but then we need
1055     // to make sure it is not greater than the selected `mKeyLease`.
1056 
1057     mLease = Min(mLease, mKeyLease);
1058 
1059 exit:
1060     return error;
1061 }
1062 
CanAppendService(const Service & aService)1063 bool Client::CanAppendService(const Service &aService)
1064 {
1065     // Check the lease intervals associated with `aService` to see if
1066     // it can be included in this message. When removing a service,
1067     // only key lease interval should match. In all other cases, both
1068     // lease and key lease should match. The `mLease` and/or `mKeyLease`
1069     // may be updated if they were unspecified.
1070 
1071     bool     canAppend = false;
1072     uint32_t lease     = DetermineLeaseInterval(aService.GetLease(), mDefaultLease);
1073     uint32_t keyLease  = Max(DetermineLeaseInterval(aService.GetKeyLease(), mDefaultKeyLease), lease);
1074 
1075     switch (aService.GetState())
1076     {
1077     case kToAdd:
1078     case kAdding:
1079     case kToRefresh:
1080     case kRefreshing:
1081     case kRegistered:
1082         VerifyOrExit((mLease == kUnspecifiedInterval) || (mLease == lease));
1083         VerifyOrExit((mKeyLease == kUnspecifiedInterval) || (mKeyLease == keyLease));
1084         mLease    = lease;
1085         mKeyLease = keyLease;
1086         canAppend = true;
1087         break;
1088 
1089     case kToRemove:
1090     case kRemoving:
1091         VerifyOrExit((mKeyLease == kUnspecifiedInterval) || (mKeyLease == keyLease));
1092         mKeyLease = keyLease;
1093         canAppend = true;
1094         break;
1095 
1096     case kRemoved:
1097         break;
1098     }
1099 
1100 exit:
1101     return canAppend;
1102 }
1103 
AppendServiceInstruction(Service & aService,Message & aMessage,Info & aInfo)1104 Error Client::AppendServiceInstruction(Service &aService, Message &aMessage, Info &aInfo)
1105 {
1106     Error               error    = kErrorNone;
1107     bool                removing = ((aService.GetState() == kToRemove) || (aService.GetState() == kRemoving));
1108     Dns::ResourceRecord rr;
1109     Dns::SrvRecord      srv;
1110     uint16_t            serviceNameOffset;
1111     uint16_t            instanceNameOffset;
1112     uint16_t            offset;
1113 
1114     aService.MarkAsAppendedInMessage();
1115 
1116     //----------------------------------
1117     // Service Discovery Instruction
1118 
1119     // PTR record
1120 
1121     // "service name labels" + (pointer to) domain name.
1122     serviceNameOffset = aMessage.GetLength();
1123     SuccessOrExit(error = Dns::Name::AppendMultipleLabels(aService.GetName(), aMessage));
1124     SuccessOrExit(error = Dns::Name::AppendPointerLabel(aInfo.mDomainNameOffset, aMessage));
1125 
1126     // On remove, we use "Delete an RR from an RRSet" where class is set
1127     // to NONE and TTL to zero (RFC 2136 - section 2.5.4).
1128 
1129     rr.Init(Dns::ResourceRecord::kTypePtr, removing ? Dns::PtrRecord::kClassNone : Dns::PtrRecord::kClassInternet);
1130     rr.SetTtl(removing ? 0 : DetermineTtl());
1131     offset = aMessage.GetLength();
1132     SuccessOrExit(error = aMessage.Append(rr));
1133 
1134     // "Instance name" + (pointer to) service name.
1135     instanceNameOffset = aMessage.GetLength();
1136     SuccessOrExit(error = Dns::Name::AppendLabel(aService.GetInstanceName(), aMessage));
1137     SuccessOrExit(error = Dns::Name::AppendPointerLabel(serviceNameOffset, aMessage));
1138 
1139     UpdateRecordLengthInMessage(rr, offset, aMessage);
1140     aInfo.mRecordCount++;
1141 
1142     if (aService.HasSubType() && !removing)
1143     {
1144         const char *subTypeLabel;
1145         uint16_t    subServiceNameOffset = 0;
1146 
1147         for (uint16_t index = 0; (subTypeLabel = aService.GetSubTypeLabelAt(index)) != nullptr; ++index)
1148         {
1149             // subtype label + "_sub" label + (pointer to) service name.
1150 
1151             SuccessOrExit(error = Dns::Name::AppendLabel(subTypeLabel, aMessage));
1152 
1153             if (index == 0)
1154             {
1155                 subServiceNameOffset = aMessage.GetLength();
1156                 SuccessOrExit(error = Dns::Name::AppendLabel("_sub", aMessage));
1157                 SuccessOrExit(error = Dns::Name::AppendPointerLabel(serviceNameOffset, aMessage));
1158             }
1159             else
1160             {
1161                 SuccessOrExit(error = Dns::Name::AppendPointerLabel(subServiceNameOffset, aMessage));
1162             }
1163 
1164             // `rr` is already initialized as PTR.
1165             offset = aMessage.GetLength();
1166             SuccessOrExit(error = aMessage.Append(rr));
1167 
1168             SuccessOrExit(error = Dns::Name::AppendPointerLabel(instanceNameOffset, aMessage));
1169             UpdateRecordLengthInMessage(rr, offset, aMessage);
1170             aInfo.mRecordCount++;
1171         }
1172     }
1173 
1174     //----------------------------------
1175     // Service Description Instruction
1176 
1177     // "Delete all RRsets from a name" for Instance Name.
1178 
1179     SuccessOrExit(error = Dns::Name::AppendPointerLabel(instanceNameOffset, aMessage));
1180     SuccessOrExit(error = AppendDeleteAllRrsets(aMessage));
1181     aInfo.mRecordCount++;
1182 
1183     VerifyOrExit(!removing);
1184 
1185     // SRV RR
1186 
1187     SuccessOrExit(error = Dns::Name::AppendPointerLabel(instanceNameOffset, aMessage));
1188     srv.Init();
1189     srv.SetTtl(DetermineTtl());
1190     srv.SetPriority(aService.GetPriority());
1191     srv.SetWeight(aService.GetWeight());
1192     srv.SetPort(aService.GetPort());
1193     offset = aMessage.GetLength();
1194     SuccessOrExit(error = aMessage.Append(srv));
1195     SuccessOrExit(error = AppendHostName(aMessage, aInfo));
1196     UpdateRecordLengthInMessage(srv, offset, aMessage);
1197     aInfo.mRecordCount++;
1198 
1199     // TXT RR
1200 
1201     SuccessOrExit(error = Dns::Name::AppendPointerLabel(instanceNameOffset, aMessage));
1202     rr.Init(Dns::ResourceRecord::kTypeTxt);
1203     offset = aMessage.GetLength();
1204     SuccessOrExit(error = aMessage.Append(rr));
1205     SuccessOrExit(error =
1206                       Dns::TxtEntry::AppendEntries(aService.GetTxtEntries(), aService.GetNumTxtEntries(), aMessage));
1207     UpdateRecordLengthInMessage(rr, offset, aMessage);
1208     aInfo.mRecordCount++;
1209 
1210 #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE
1211     if (mServiceKeyRecordEnabled)
1212     {
1213         // KEY RR is optional in "Service Description Instruction". It
1214         // is added here under `REFERENCE_DEVICE` config and is intended
1215         // for testing only.
1216 
1217         SuccessOrExit(error = Dns::Name::AppendPointerLabel(instanceNameOffset, aMessage));
1218         SuccessOrExit(error = AppendKeyRecord(aMessage, aInfo));
1219     }
1220 #endif
1221 
1222 exit:
1223     return error;
1224 }
1225 
AppendHostDescriptionInstruction(Message & aMessage,Info & aInfo)1226 Error Client::AppendHostDescriptionInstruction(Message &aMessage, Info &aInfo)
1227 {
1228     Error error = kErrorNone;
1229 
1230     //----------------------------------
1231     // Host Description Instruction
1232 
1233     // "Delete all RRsets from a name" for Host Name.
1234 
1235     SuccessOrExit(error = AppendHostName(aMessage, aInfo));
1236     SuccessOrExit(error = AppendDeleteAllRrsets(aMessage));
1237     aInfo.mRecordCount++;
1238 
1239     // AAAA RRs
1240 
1241     if (mHostInfo.IsAutoAddressEnabled())
1242     {
1243         // Append all addresses on Thread netif excluding link-local and
1244         // mesh-local addresses. If no address is appended, we include
1245         // the mesh local address.
1246 
1247         mAutoHostAddressAddedMeshLocal = true;
1248 
1249         for (const Ip6::Netif::UnicastAddress &unicastAddress : Get<ThreadNetif>().GetUnicastAddresses())
1250         {
1251             if (unicastAddress.GetAddress().IsLinkLocal() ||
1252                 Get<Mle::Mle>().IsMeshLocalAddress(unicastAddress.GetAddress()))
1253             {
1254                 continue;
1255             }
1256 
1257             SuccessOrExit(error = AppendAaaaRecord(unicastAddress.GetAddress(), aMessage, aInfo));
1258             mAutoHostAddressAddedMeshLocal = false;
1259         }
1260 
1261         if (mAutoHostAddressAddedMeshLocal)
1262         {
1263             SuccessOrExit(error = AppendAaaaRecord(Get<Mle::Mle>().GetMeshLocal64(), aMessage, aInfo));
1264         }
1265     }
1266     else
1267     {
1268         for (uint8_t index = 0; index < mHostInfo.GetNumAddresses(); index++)
1269         {
1270             SuccessOrExit(error = AppendAaaaRecord(mHostInfo.GetAddress(index), aMessage, aInfo));
1271         }
1272     }
1273 
1274     // KEY RR
1275 
1276     SuccessOrExit(error = AppendHostName(aMessage, aInfo));
1277     SuccessOrExit(error = AppendKeyRecord(aMessage, aInfo));
1278 
1279 exit:
1280     return error;
1281 }
1282 
AppendAaaaRecord(const Ip6::Address & aAddress,Message & aMessage,Info & aInfo) const1283 Error Client::AppendAaaaRecord(const Ip6::Address &aAddress, Message &aMessage, Info &aInfo) const
1284 {
1285     Error               error;
1286     Dns::ResourceRecord rr;
1287 
1288     rr.Init(Dns::ResourceRecord::kTypeAaaa);
1289     rr.SetTtl(DetermineTtl());
1290     rr.SetLength(sizeof(Ip6::Address));
1291 
1292     SuccessOrExit(error = AppendHostName(aMessage, aInfo));
1293     SuccessOrExit(error = aMessage.Append(rr));
1294     SuccessOrExit(error = aMessage.Append(aAddress));
1295     aInfo.mRecordCount++;
1296 
1297 exit:
1298     return error;
1299 }
1300 
AppendKeyRecord(Message & aMessage,Info & aInfo) const1301 Error Client::AppendKeyRecord(Message &aMessage, Info &aInfo) const
1302 {
1303     Error                          error;
1304     Dns::KeyRecord                 key;
1305     Crypto::Ecdsa::P256::PublicKey publicKey;
1306 
1307     key.Init();
1308     key.SetTtl(DetermineTtl());
1309     key.SetFlags(Dns::KeyRecord::kAuthConfidPermitted, Dns::KeyRecord::kOwnerNonZone,
1310                  Dns::KeyRecord::kSignatoryFlagGeneral);
1311     key.SetProtocol(Dns::KeyRecord::kProtocolDnsSec);
1312     key.SetAlgorithm(Dns::KeyRecord::kAlgorithmEcdsaP256Sha256);
1313     key.SetLength(sizeof(Dns::KeyRecord) - sizeof(Dns::ResourceRecord) + sizeof(Crypto::Ecdsa::P256::PublicKey));
1314     SuccessOrExit(error = aMessage.Append(key));
1315 #if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
1316     SuccessOrExit(error = aInfo.mKeyRef.GetPublicKey(publicKey));
1317 #else
1318     SuccessOrExit(error = aInfo.mKeyPair.GetPublicKey(publicKey));
1319 #endif
1320     SuccessOrExit(error = aMessage.Append(publicKey));
1321     aInfo.mRecordCount++;
1322 
1323 exit:
1324     return error;
1325 }
1326 
AppendDeleteAllRrsets(Message & aMessage) const1327 Error Client::AppendDeleteAllRrsets(Message &aMessage) const
1328 {
1329     // "Delete all RRsets from a name" (RFC 2136 - 2.5.3)
1330     // Name should be already appended in the message.
1331 
1332     Dns::ResourceRecord rr;
1333 
1334     rr.Init(Dns::ResourceRecord::kTypeAny, Dns::ResourceRecord::kClassAny);
1335     rr.SetTtl(0);
1336     rr.SetLength(0);
1337 
1338     return aMessage.Append(rr);
1339 }
1340 
AppendHostName(Message & aMessage,Info & aInfo,bool aDoNotCompress) const1341 Error Client::AppendHostName(Message &aMessage, Info &aInfo, bool aDoNotCompress) const
1342 {
1343     Error error;
1344 
1345     if (aDoNotCompress)
1346     {
1347         // Uncompressed (canonical form) of host name is used for SIG(0)
1348         // calculation.
1349         SuccessOrExit(error = Dns::Name::AppendMultipleLabels(mHostInfo.GetName(), aMessage));
1350         error = Dns::Name::AppendName(mDomainName, aMessage);
1351         ExitNow();
1352     }
1353 
1354     // If host name was previously added in the message, add it
1355     // compressed as pointer to the previous one. Otherwise,
1356     // append it and remember the offset.
1357 
1358     if (aInfo.mHostNameOffset != Info::kUnknownOffset)
1359     {
1360         ExitNow(error = Dns::Name::AppendPointerLabel(aInfo.mHostNameOffset, aMessage));
1361     }
1362 
1363     aInfo.mHostNameOffset = aMessage.GetLength();
1364     SuccessOrExit(error = Dns::Name::AppendMultipleLabels(mHostInfo.GetName(), aMessage));
1365     error = Dns::Name::AppendPointerLabel(aInfo.mDomainNameOffset, aMessage);
1366 
1367 exit:
1368     return error;
1369 }
1370 
AppendUpdateLeaseOptRecord(Message & aMessage)1371 Error Client::AppendUpdateLeaseOptRecord(Message &aMessage)
1372 {
1373     Error            error;
1374     Dns::OptRecord   optRecord;
1375     Dns::LeaseOption leaseOption;
1376     uint16_t         optionSize;
1377 
1378     // Append empty (root domain) as OPT RR name.
1379     SuccessOrExit(error = Dns::Name::AppendTerminator(aMessage));
1380 
1381     // `Init()` sets the type and clears (set to zero) the extended
1382     // Response Code, version and all flags.
1383     optRecord.Init();
1384     optRecord.SetUdpPayloadSize(kUdpPayloadSize);
1385     optRecord.SetDnsSecurityFlag();
1386 
1387 #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE
1388     if (mUseShortLeaseOption)
1389     {
1390         LogInfo("Test mode - appending short variant of Lease Option");
1391         mKeyLease = mLease;
1392         leaseOption.InitAsShortVariant(mLease);
1393     }
1394     else
1395 #endif
1396     {
1397         leaseOption.InitAsLongVariant(mLease, mKeyLease);
1398     }
1399 
1400     optionSize = static_cast<uint16_t>(leaseOption.GetSize());
1401 
1402     optRecord.SetLength(optionSize);
1403 
1404     SuccessOrExit(error = aMessage.Append(optRecord));
1405     error = aMessage.AppendBytes(&leaseOption, optionSize);
1406 
1407 exit:
1408     return error;
1409 }
1410 
AppendSignature(Message & aMessage,Info & aInfo)1411 Error Client::AppendSignature(Message &aMessage, Info &aInfo)
1412 {
1413     Error                          error;
1414     Dns::SigRecord                 sig;
1415     Crypto::Sha256                 sha256;
1416     Crypto::Sha256::Hash           hash;
1417     Crypto::Ecdsa::P256::Signature signature;
1418     uint16_t                       offset;
1419     uint16_t                       len;
1420 
1421     // Prepare SIG RR: TTL, type covered, labels count should be set
1422     // to zero. Since we have no clock, inception and expiration time
1423     // are also set to zero. The RDATA length will be set later (not
1424     // yet known due to variably (and possible compression) of signer's
1425     // name.
1426 
1427     sig.Clear();
1428     sig.Init(Dns::ResourceRecord::kClassAny);
1429     sig.SetAlgorithm(Dns::KeyRecord::kAlgorithmEcdsaP256Sha256);
1430 
1431     // Append the SIG RR with full uncompressed form of the host name
1432     // as the signer's name. This is used for SIG(0) calculation only.
1433     // It will be overwritten with host name compressed.
1434 
1435     offset = aMessage.GetLength();
1436     SuccessOrExit(error = aMessage.Append(sig));
1437     SuccessOrExit(error = AppendHostName(aMessage, aInfo, /* aDoNotCompress */ true));
1438 
1439     // Calculate signature (RFC 2931): Calculated over "data" which is
1440     // concatenation of (1) the SIG RR RDATA wire format (including
1441     // the canonical form of the signer's name), entirely omitting the
1442     // signature subfield, (2) DNS query message, including DNS header
1443     // but not UDP/IP header before the header RR counts have been
1444     // adjusted for the inclusion of SIG(0).
1445 
1446     sha256.Start();
1447 
1448     // (1) SIG RR RDATA wire format
1449     len = aMessage.GetLength() - offset - sizeof(Dns::ResourceRecord);
1450     sha256.Update(aMessage, offset + sizeof(Dns::ResourceRecord), len);
1451 
1452     // (2) Message from DNS header before SIG
1453     sha256.Update(aMessage, 0, offset);
1454 
1455     sha256.Finish(hash);
1456 #if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
1457     SuccessOrExit(error = aInfo.mKeyRef.Sign(hash, signature));
1458 #else
1459     SuccessOrExit(error = aInfo.mKeyPair.Sign(hash, signature));
1460 #endif
1461 
1462     // Move back in message and append SIG RR now with compressed host
1463     // name (as signer's name) along with the calculated signature.
1464 
1465     IgnoreError(aMessage.SetLength(offset));
1466 
1467     // SIG(0) uses owner name of root (single zero byte).
1468     SuccessOrExit(error = Dns::Name::AppendTerminator(aMessage));
1469 
1470     offset = aMessage.GetLength();
1471     SuccessOrExit(error = aMessage.Append(sig));
1472     SuccessOrExit(error = AppendHostName(aMessage, aInfo));
1473     SuccessOrExit(error = aMessage.Append(signature));
1474     UpdateRecordLengthInMessage(sig, offset, aMessage);
1475 
1476 exit:
1477     return error;
1478 }
1479 
UpdateRecordLengthInMessage(Dns::ResourceRecord & aRecord,uint16_t aOffset,Message & aMessage) const1480 void Client::UpdateRecordLengthInMessage(Dns::ResourceRecord &aRecord, uint16_t aOffset, Message &aMessage) const
1481 {
1482     // This method is used to calculate an RR DATA length and update
1483     // (rewrite) it in a message. This should be called immediately
1484     // after all the fields in the record are written in the message.
1485     // `aOffset` gives the offset in the message to the start of the
1486     // record.
1487 
1488     aRecord.SetLength(aMessage.GetLength() - aOffset - sizeof(Dns::ResourceRecord));
1489     aMessage.Write(aOffset, aRecord);
1490 }
1491 
HandleUdpReceive(void * aContext,otMessage * aMessage,const otMessageInfo * aMessageInfo)1492 void Client::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
1493 {
1494     OT_UNUSED_VARIABLE(aMessageInfo);
1495 
1496     static_cast<Client *>(aContext)->ProcessResponse(AsCoreType(aMessage));
1497 }
1498 
ProcessResponse(Message & aMessage)1499 void Client::ProcessResponse(Message &aMessage)
1500 {
1501     static const ItemState kNewStateOnUpdateDone[]{
1502         /* (0) kToAdd      -> */ kToAdd,
1503         /* (1) kAdding     -> */ kRegistered,
1504         /* (2) kToRefresh  -> */ kToRefresh,
1505         /* (3) kRefreshing -> */ kRegistered,
1506         /* (4) kToRemove   -> */ kToRemove,
1507         /* (5) kRemoving   -> */ kRemoved,
1508         /* (6) kRegistered -> */ kRegistered,
1509         /* (7) kRemoved    -> */ kRemoved,
1510     };
1511 
1512     Error               error = kErrorNone;
1513     Dns::UpdateHeader   header;
1514     uint16_t            offset = aMessage.GetOffset();
1515     uint16_t            recordCount;
1516     LinkedList<Service> removedServices;
1517 
1518     VerifyOrExit(GetState() == kStateUpdating);
1519 
1520     SuccessOrExit(error = aMessage.Read(offset, header));
1521 
1522     VerifyOrExit(header.GetType() == Dns::Header::kTypeResponse, error = kErrorParse);
1523     VerifyOrExit(header.GetQueryType() == Dns::Header::kQueryTypeUpdate, error = kErrorParse);
1524     VerifyOrExit(header.GetMessageId() == mUpdateMessageId, error = kErrorDrop);
1525 
1526     if (!Get<Mle::Mle>().IsRxOnWhenIdle())
1527     {
1528         Get<DataPollSender>().StopFastPolls();
1529     }
1530 
1531     // Response is for the earlier request message.
1532 
1533     LogInfo("Received response");
1534 
1535 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SWITCH_SERVER_ON_FAILURE
1536     mAutoStart.ResetTimeoutFailureCount();
1537 #endif
1538 
1539     error = Dns::Header::ResponseCodeToError(header.GetResponseCode());
1540 
1541     if (error != kErrorNone)
1542     {
1543         LogInfo("Server rejected %s code:%d", ErrorToString(error), header.GetResponseCode());
1544 
1545         if (mHostInfo.GetState() == kAdding)
1546         {
1547             // Since server rejected the update message, we go back to
1548             // `kToAdd` state to allow user to give a new name using
1549             // `SetHostName()`.
1550             mHostInfo.SetState(kToAdd);
1551         }
1552 
1553         // Wait for the timer to expire to retry. Note that timer is
1554         // already scheduled for the current wait interval when state
1555         // was changed to `kStateUpdating`.
1556 
1557         LogRetryWaitInterval();
1558         GrowRetryWaitInterval();
1559         SetState(kStateToRetry);
1560         InvokeCallback(error);
1561 
1562 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SWITCH_SERVER_ON_FAILURE
1563         if ((error == kErrorDuplicated) || (error == kErrorSecurity))
1564         {
1565             // If the server rejects the update with specific errors
1566             // (indicating duplicate name and/or security error), we
1567             // try to switch the server (we check if another can be
1568             // found in the Network Data).
1569             //
1570             // Note that this is done after invoking the callback and
1571             // notifying the user of the error from server. This works
1572             // correctly even if user makes changes from callback
1573             // (e.g., calls SRP client APIs like `Stop` or disables
1574             // auto-start), since we have a guard check at the top of
1575             // `SelectNextServer()` to verify that client is still
1576             // running and auto-start is enabled and selected the
1577             // server.
1578 
1579             SelectNextServer(/* aDisallowSwitchOnRegisteredHost */ true);
1580         }
1581 #endif
1582         ExitNow(error = kErrorNone);
1583     }
1584 
1585     offset += sizeof(header);
1586 
1587     // Skip over all sections till Additional Data section
1588     // SPEC ENHANCEMENT: Server can echo the request back or not
1589     // include any of RRs. Would be good to explicitly require SRP server
1590     // to not echo back RRs.
1591 
1592     if (header.GetZoneRecordCount() != 0)
1593     {
1594         VerifyOrExit(header.GetZoneRecordCount() == 1, error = kErrorParse);
1595         SuccessOrExit(error = Dns::Name::ParseName(aMessage, offset));
1596         VerifyOrExit(offset + sizeof(Dns::Zone) <= aMessage.GetLength(), error = kErrorParse);
1597         offset += sizeof(Dns::Zone);
1598     }
1599 
1600     // Check for Update Lease OPT RR. This determines the lease
1601     // interval accepted by server. If not present, then use the
1602     // transmitted lease interval from the update request message.
1603 
1604     recordCount =
1605         header.GetPrerequisiteRecordCount() + header.GetUpdateRecordCount() + header.GetAdditionalRecordCount();
1606 
1607     while (recordCount > 0)
1608     {
1609         uint16_t            startOffset = offset;
1610         Dns::ResourceRecord rr;
1611 
1612         SuccessOrExit(error = ReadResourceRecord(aMessage, offset, rr));
1613         recordCount--;
1614 
1615         if (rr.GetType() == Dns::ResourceRecord::kTypeOpt)
1616         {
1617             SuccessOrExit(error = ProcessOptRecord(aMessage, startOffset, static_cast<Dns::OptRecord &>(rr)));
1618         }
1619     }
1620 
1621     // Calculate the lease renew time based on update message tx time
1622     // and the lease time. `kLeaseRenewGuardInterval` is used to
1623     // ensure that we renew the lease before server expires it. In the
1624     // unlikely (but maybe useful for testing) case where the accepted
1625     // lease interval is too short (shorter than the guard time) we
1626     // just use half of the accepted lease interval.
1627 
1628     if (mLease > kLeaseRenewGuardInterval)
1629     {
1630         mLeaseRenewTime += Time::SecToMsec(mLease - kLeaseRenewGuardInterval);
1631     }
1632     else
1633     {
1634         mLeaseRenewTime += Time::SecToMsec(mLease) / 2;
1635     }
1636 
1637     for (Service &service : mServices)
1638     {
1639         if ((service.GetState() == kAdding) || (service.GetState() == kRefreshing))
1640         {
1641             service.SetLeaseRenewTime(mLeaseRenewTime);
1642         }
1643     }
1644 
1645     // State changes:
1646     //   kAdding     -> kRegistered
1647     //   kRefreshing -> kRegistered
1648     //   kRemoving   -> kRemoved
1649 
1650     ChangeHostAndServiceStates(kNewStateOnUpdateDone, kForServicesAppendedInMessage);
1651 
1652     HandleUpdateDone();
1653     UpdateState();
1654 
1655 exit:
1656     if (error != kErrorNone)
1657     {
1658         LogInfo("Failed to process response %s", ErrorToString(error));
1659     }
1660 }
1661 
HandleUpdateDone(void)1662 void Client::HandleUpdateDone(void)
1663 {
1664     HostInfo            hostInfoCopy = mHostInfo;
1665     LinkedList<Service> removedServices;
1666 
1667     if (mHostInfo.GetState() == kRemoved)
1668     {
1669         mHostInfo.Clear();
1670     }
1671 
1672     ResetRetryWaitInterval();
1673     SetState(kStateUpdated);
1674 
1675     GetRemovedServices(removedServices);
1676     InvokeCallback(kErrorNone, hostInfoCopy, removedServices.GetHead());
1677 }
1678 
GetRemovedServices(LinkedList<Service> & aRemovedServices)1679 void Client::GetRemovedServices(LinkedList<Service> &aRemovedServices)
1680 {
1681     mServices.RemoveAllMatching(kRemoved, aRemovedServices);
1682 }
1683 
ReadResourceRecord(const Message & aMessage,uint16_t & aOffset,Dns::ResourceRecord & aRecord)1684 Error Client::ReadResourceRecord(const Message &aMessage, uint16_t &aOffset, Dns::ResourceRecord &aRecord)
1685 {
1686     // Reads and skips over a Resource Record (RR) from message at
1687     // given offset. On success, `aOffset` is updated to point to end
1688     // of RR.
1689 
1690     Error error;
1691 
1692     SuccessOrExit(error = Dns::Name::ParseName(aMessage, aOffset));
1693     SuccessOrExit(error = aMessage.Read(aOffset, aRecord));
1694     VerifyOrExit(aOffset + aRecord.GetSize() <= aMessage.GetLength(), error = kErrorParse);
1695     aOffset += static_cast<uint16_t>(aRecord.GetSize());
1696 
1697 exit:
1698     return error;
1699 }
1700 
ProcessOptRecord(const Message & aMessage,uint16_t aOffset,const Dns::OptRecord & aOptRecord)1701 Error Client::ProcessOptRecord(const Message &aMessage, uint16_t aOffset, const Dns::OptRecord &aOptRecord)
1702 {
1703     // Read and process all options (in an OPT RR) from a message.
1704     // The `aOffset` points to beginning of record in `aMessage`.
1705 
1706     Error            error = kErrorNone;
1707     Dns::LeaseOption leaseOption;
1708 
1709     IgnoreError(Dns::Name::ParseName(aMessage, aOffset));
1710     aOffset += sizeof(Dns::OptRecord);
1711 
1712     switch (error = leaseOption.ReadFrom(aMessage, aOffset, aOptRecord.GetLength()))
1713     {
1714     case kErrorNone:
1715         mLease    = Min(leaseOption.GetLeaseInterval(), kMaxLease);
1716         mKeyLease = Min(leaseOption.GetKeyLeaseInterval(), kMaxLease);
1717         break;
1718 
1719     case kErrorNotFound:
1720         // If server does not include a lease option in its response, it
1721         // indicates that it accepted what we requested.
1722         error = kErrorNone;
1723         break;
1724 
1725     default:
1726         ExitNow();
1727     }
1728 
1729 exit:
1730     return error;
1731 }
1732 
UpdateState(void)1733 void Client::UpdateState(void)
1734 {
1735     TimeMilli now               = TimerMilli::GetNow();
1736     TimeMilli earliestRenewTime = now.GetDistantFuture();
1737     bool      shouldUpdate      = false;
1738 
1739     VerifyOrExit((GetState() != kStateStopped) && (GetState() != kStatePaused));
1740     VerifyOrExit(mHostInfo.GetName() != nullptr);
1741 
1742     // Go through the host info and all the services to check if there
1743     // are any new changes (i.e., anything new to add or remove). This
1744     // is used to determine whether to send an SRP update message or
1745     // not. Also keep track of the earliest renew time among the
1746     // previously registered services. This is used to schedule the
1747     // timer for next refresh.
1748 
1749     switch (mHostInfo.GetState())
1750     {
1751     case kAdding:
1752     case kRefreshing:
1753     case kRemoving:
1754         break;
1755 
1756     case kRegistered:
1757         if (now < mLeaseRenewTime)
1758         {
1759             break;
1760         }
1761 
1762         mHostInfo.SetState(kToRefresh);
1763 
1764         // Fall through
1765 
1766     case kToAdd:
1767     case kToRefresh:
1768         // Make sure we have at least one service and at least one
1769         // host address, otherwise no need to send SRP update message.
1770         // The exception is when removing host info where we allow
1771         // for empty service list.
1772         VerifyOrExit(!mServices.IsEmpty() && (mHostInfo.IsAutoAddressEnabled() || (mHostInfo.GetNumAddresses() > 0)));
1773 
1774         // Fall through
1775 
1776     case kToRemove:
1777         shouldUpdate = true;
1778         break;
1779 
1780     case kRemoved:
1781         ExitNow();
1782     }
1783 
1784     // If host info is being removed, we skip over checking service list
1785     // for new adds (or removes). This handles the situation where while
1786     // remove is ongoing and before we get a response from the server,
1787     // user adds a new service to be registered. We wait for remove to
1788     // finish (receive response from server) before starting with a new
1789     // service adds.
1790 
1791     if (mHostInfo.GetState() != kRemoving)
1792     {
1793         for (Service &service : mServices)
1794         {
1795             switch (service.GetState())
1796             {
1797             case kToAdd:
1798             case kToRefresh:
1799             case kToRemove:
1800                 shouldUpdate = true;
1801                 break;
1802 
1803             case kRegistered:
1804                 if (service.GetLeaseRenewTime() <= now)
1805                 {
1806                     service.SetState(kToRefresh);
1807                     shouldUpdate = true;
1808                 }
1809                 else
1810                 {
1811                     earliestRenewTime = Min(earliestRenewTime, service.GetLeaseRenewTime());
1812                 }
1813 
1814                 break;
1815 
1816             case kAdding:
1817             case kRefreshing:
1818             case kRemoving:
1819             case kRemoved:
1820                 break;
1821             }
1822         }
1823     }
1824 
1825     if (shouldUpdate)
1826     {
1827         SetState(kStateToUpdate);
1828         ExitNow();
1829     }
1830 
1831     if ((GetState() == kStateUpdated) && (earliestRenewTime != now.GetDistantFuture()))
1832     {
1833         mTimer.FireAt(earliestRenewTime);
1834     }
1835 
1836 exit:
1837     return;
1838 }
1839 
GrowRetryWaitInterval(void)1840 void Client::GrowRetryWaitInterval(void)
1841 {
1842     mRetryWaitInterval =
1843         mRetryWaitInterval / kRetryIntervalGrowthFactorDenominator * kRetryIntervalGrowthFactorNumerator;
1844     mRetryWaitInterval = Min(mRetryWaitInterval, kMaxRetryWaitInterval);
1845 }
1846 
DetermineLeaseInterval(uint32_t aInterval,uint32_t aDefaultInterval) const1847 uint32_t Client::DetermineLeaseInterval(uint32_t aInterval, uint32_t aDefaultInterval) const
1848 {
1849     // Determine the lease or key lease interval.
1850     //
1851     // We use `aInterval` if it is non-zero, otherwise, use the
1852     // `aDefaultInterval`. We also ensure that the returned value is
1853     // never greater than `kMaxLease`. The `kMaxLease` is selected
1854     // such the lease intervals in msec can still fit in a `uint32_t`
1855     // `Time` variable (`kMaxLease` is ~ 24.8 days).
1856 
1857     return Min(kMaxLease, (aInterval != kUnspecifiedInterval) ? aInterval : aDefaultInterval);
1858 }
1859 
DetermineTtl(void) const1860 uint32_t Client::DetermineTtl(void) const
1861 {
1862     // Determine the TTL to use based on current `mLease`.
1863     // If `mLease == 0`, it indicates we are removing host
1864     // and so we use `mDefaultLease` instead.
1865 
1866     uint32_t lease = (mLease == 0) ? mDefaultLease : mLease;
1867 
1868     return (mTtl == kUnspecifiedInterval) ? lease : Min(mTtl, lease);
1869 }
1870 
ShouldRenewEarly(const Service & aService) const1871 bool Client::ShouldRenewEarly(const Service &aService) const
1872 {
1873     // Check if we reached the service renew time or close to it. The
1874     // "early renew interval" is used to allow early refresh. It is
1875     // calculated as a factor of the service requested lease interval.
1876     // The  "early lease renew factor" is given as a fraction (numerator
1877     // and denominator). If the denominator is set to zero (i.e., factor
1878     // is set to infinity), then service is always included in all SRP
1879     // update messages.
1880 
1881     bool shouldRenew;
1882 
1883 #if OPENTHREAD_CONFIG_SRP_CLIENT_EARLY_LEASE_RENEW_FACTOR_DENOMINATOR != 0
1884     uint32_t earlyRenewInterval;
1885 
1886     earlyRenewInterval = Time::SecToMsec(DetermineLeaseInterval(aService.GetLease(), mDefaultLease));
1887     earlyRenewInterval = earlyRenewInterval / kEarlyLeaseRenewFactorDenominator * kEarlyLeaseRenewFactorNumerator;
1888 
1889     shouldRenew = (aService.GetLeaseRenewTime() <= TimerMilli::GetNow() + earlyRenewInterval);
1890 #else
1891     OT_UNUSED_VARIABLE(aService);
1892     shouldRenew = true;
1893 #endif
1894 
1895     return shouldRenew;
1896 }
1897 
HandleTimer(void)1898 void Client::HandleTimer(void)
1899 {
1900     switch (GetState())
1901     {
1902     case kStateStopped:
1903     case kStatePaused:
1904         break;
1905 
1906     case kStateToUpdate:
1907     case kStateToRetry:
1908         SendUpdate();
1909         break;
1910 
1911     case kStateUpdating:
1912         mSingleServiceMode = false;
1913         LogRetryWaitInterval();
1914         LogInfo("Timed out, no response");
1915         GrowRetryWaitInterval();
1916         SetState(kStateToUpdate);
1917         InvokeCallback(kErrorResponseTimeout);
1918 
1919 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SWITCH_SERVER_ON_FAILURE
1920 
1921         // After certain number of back-to-back timeout failures, we try
1922         // to switch the server. This is again done after invoking the
1923         // callback. It works correctly due to the guard check at the
1924         // top of `SelectNextServer()`.
1925 
1926         mAutoStart.IncrementTimeoutFailureCount();
1927 
1928         if (mAutoStart.GetTimeoutFailureCount() >= kMaxTimeoutFailuresToSwitchServer)
1929         {
1930             SelectNextServer(kDisallowSwitchOnRegisteredHost);
1931         }
1932 #endif
1933         break;
1934 
1935     case kStateUpdated:
1936         UpdateState();
1937         break;
1938     }
1939 }
1940 
1941 #if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
1942 
EnableAutoStartMode(AutoStartCallback aCallback,void * aContext)1943 void Client::EnableAutoStartMode(AutoStartCallback aCallback, void *aContext)
1944 {
1945     mAutoStart.SetCallback(aCallback, aContext);
1946 
1947     VerifyOrExit(mAutoStart.GetState() == AutoStart::kDisabled);
1948 
1949     mAutoStart.SetState(AutoStart::kSelectedNone);
1950     ProcessAutoStart();
1951 
1952 exit:
1953     return;
1954 }
1955 
ProcessAutoStart(void)1956 void Client::ProcessAutoStart(void)
1957 {
1958     Ip6::SockAddr       serverSockAddr;
1959     DnsSrpAnycast::Info anycastInfo;
1960     DnsSrpUnicast::Info unicastInfo;
1961     bool                shouldRestart = false;
1962 
1963     // If auto start mode is enabled, we check the Network Data entries
1964     // to discover and select the preferred SRP server to register with.
1965     // If we currently have a selected server, we ensure that it is
1966     // still present in the Network Data and is still the preferred one.
1967 
1968     VerifyOrExit(mAutoStart.GetState() != AutoStart::kDisabled);
1969 
1970     // If SRP client is running, we check to make sure that auto-start
1971     // did select the current server, and server was not specified by
1972     // user directly.
1973 
1974     if (IsRunning())
1975     {
1976         VerifyOrExit(mAutoStart.GetState() != AutoStart::kSelectedNone);
1977     }
1978 
1979     // There are three types of entries in Network Data:
1980     //
1981     // 1) Preferred unicast entries with address included in service data.
1982     // 2) Anycast entries (each having a seq number).
1983     // 3) Unicast entries with address info included in server data.
1984 
1985     serverSockAddr.Clear();
1986 
1987     if (SelectUnicastEntry(DnsSrpUnicast::kFromServiceData, unicastInfo) == kErrorNone)
1988     {
1989         mAutoStart.SetState(AutoStart::kSelectedUnicastPreferred);
1990         serverSockAddr = unicastInfo.mSockAddr;
1991     }
1992     else if (Get<NetworkData::Service::Manager>().FindPreferredDnsSrpAnycastInfo(anycastInfo) == kErrorNone)
1993     {
1994         serverSockAddr.SetAddress(anycastInfo.mAnycastAddress);
1995         serverSockAddr.SetPort(kAnycastServerPort);
1996 
1997         // We check if we are selecting an anycast entry for first
1998         // time, or if the seq number has changed. Even if the
1999         // anycast address remains the same as before, on a seq
2000         // number change, the client still needs to restart to
2001         // re-register its info.
2002 
2003         if ((mAutoStart.GetState() != AutoStart::kSelectedAnycast) ||
2004             (mAutoStart.GetAnycastSeqNum() != anycastInfo.mSequenceNumber))
2005         {
2006             shouldRestart = true;
2007             mAutoStart.SetAnycastSeqNum(anycastInfo.mSequenceNumber);
2008         }
2009 
2010         mAutoStart.SetState(AutoStart::kSelectedAnycast);
2011     }
2012     else if (SelectUnicastEntry(DnsSrpUnicast::kFromServerData, unicastInfo) == kErrorNone)
2013     {
2014         mAutoStart.SetState(AutoStart::kSelectedUnicast);
2015         serverSockAddr = unicastInfo.mSockAddr;
2016     }
2017 
2018     if (IsRunning())
2019     {
2020         VerifyOrExit((GetServerAddress() != serverSockAddr) || shouldRestart);
2021         Stop(kRequesterAuto, kResetRetryInterval);
2022     }
2023 
2024     if (!serverSockAddr.GetAddress().IsUnspecified())
2025     {
2026         IgnoreError(Start(serverSockAddr, kRequesterAuto));
2027     }
2028     else
2029     {
2030         mAutoStart.SetState(AutoStart::kSelectedNone);
2031     }
2032 
2033 exit:
2034     return;
2035 }
2036 
SelectUnicastEntry(DnsSrpUnicast::Origin aOrigin,DnsSrpUnicast::Info & aInfo) const2037 Error Client::SelectUnicastEntry(DnsSrpUnicast::Origin aOrigin, DnsSrpUnicast::Info &aInfo) const
2038 {
2039     Error                                   error = kErrorNotFound;
2040     DnsSrpUnicast::Info                     unicastInfo;
2041     NetworkData::Service::Manager::Iterator iterator;
2042 #if OPENTHREAD_CONFIG_SRP_CLIENT_SAVE_SELECTED_SERVER_ENABLE
2043     Settings::SrpClientInfo savedInfo;
2044     bool                    hasSavedServerInfo = false;
2045 
2046     if (!IsRunning())
2047     {
2048         hasSavedServerInfo = (Get<Settings>().Read(savedInfo) == kErrorNone);
2049     }
2050 #endif
2051 
2052     while (Get<NetworkData::Service::Manager>().GetNextDnsSrpUnicastInfo(iterator, unicastInfo) == kErrorNone)
2053     {
2054         if (unicastInfo.mOrigin != aOrigin)
2055         {
2056             continue;
2057         }
2058 
2059         if (mAutoStart.HasSelectedServer() && (GetServerAddress() == unicastInfo.mSockAddr))
2060         {
2061             aInfo = unicastInfo;
2062             error = kErrorNone;
2063             ExitNow();
2064         }
2065 
2066 #if OPENTHREAD_CONFIG_SRP_CLIENT_SAVE_SELECTED_SERVER_ENABLE
2067         if (hasSavedServerInfo && (unicastInfo.mSockAddr.GetAddress() == savedInfo.GetServerAddress()) &&
2068             (unicastInfo.mSockAddr.GetPort() == savedInfo.GetServerPort()))
2069         {
2070             // Stop the search if we see a match for the previously
2071             // saved server info in the network data entries.
2072 
2073             aInfo = unicastInfo;
2074             error = kErrorNone;
2075             ExitNow();
2076         }
2077 #endif
2078 
2079         // Prefer the numerically lowest server address
2080 
2081         if ((error == kErrorNotFound) || (unicastInfo.mSockAddr.GetAddress() < aInfo.mSockAddr.GetAddress()))
2082         {
2083             aInfo = unicastInfo;
2084             error = kErrorNone;
2085         }
2086     }
2087 
2088 exit:
2089     return error;
2090 }
2091 
2092 #if OPENTHREAD_CONFIG_SRP_CLIENT_SWITCH_SERVER_ON_FAILURE
SelectNextServer(bool aDisallowSwitchOnRegisteredHost)2093 void Client::SelectNextServer(bool aDisallowSwitchOnRegisteredHost)
2094 {
2095     // This method tries to find the next unicast server info entry in the
2096     // Network Data after the current one selected. If found, it
2097     // restarts the client with the new server (keeping the retry wait
2098     // interval as before).
2099 
2100     Ip6::SockAddr         serverSockAddr;
2101     bool                  selectNext = false;
2102     DnsSrpUnicast::Origin origin     = DnsSrpUnicast::kFromServiceData;
2103 
2104     serverSockAddr.Clear();
2105 
2106     // Ensure that client is running, auto-start is enabled and
2107     // auto-start selected the server and it is a unicast entry.
2108 
2109     VerifyOrExit(IsRunning());
2110 
2111     switch (mAutoStart.GetState())
2112     {
2113     case AutoStart::kSelectedUnicastPreferred:
2114         origin = DnsSrpUnicast::kFromServiceData;
2115         break;
2116 
2117     case AutoStart::kSelectedUnicast:
2118         origin = DnsSrpUnicast::kFromServerData;
2119         break;
2120 
2121     case AutoStart::kSelectedAnycast:
2122     case AutoStart::kDisabled:
2123     case AutoStart::kSelectedNone:
2124         ExitNow();
2125     }
2126 
2127     if (aDisallowSwitchOnRegisteredHost)
2128     {
2129         // Ensure that host info is not yet registered (indicating that no
2130         // service has yet been registered either).
2131         VerifyOrExit((mHostInfo.GetState() == kAdding) || (mHostInfo.GetState() == kToAdd));
2132     }
2133 
2134     // We go through all entries to find the one matching the currently
2135     // selected one, then set `selectNext` to `true` so to select the
2136     // next one.
2137 
2138     do
2139     {
2140         DnsSrpUnicast::Info                     unicastInfo;
2141         NetworkData::Service::Manager::Iterator iterator;
2142 
2143         while (Get<NetworkData::Service::Manager>().GetNextDnsSrpUnicastInfo(iterator, unicastInfo) == kErrorNone)
2144         {
2145             if (unicastInfo.mOrigin != origin)
2146             {
2147                 continue;
2148             }
2149 
2150             if (selectNext)
2151             {
2152                 serverSockAddr = unicastInfo.mSockAddr;
2153                 ExitNow();
2154             }
2155 
2156             if (GetServerAddress() == unicastInfo.mSockAddr)
2157             {
2158                 selectNext = true;
2159             }
2160         }
2161 
2162         // We loop back to handle the case where the current entry
2163         // is the last one.
2164 
2165     } while (selectNext);
2166 
2167     // If we reach here it indicates we could not find the entry
2168     // associated with currently selected server in the list. This
2169     // situation is rather unlikely but can still happen if Network
2170     // Data happens to be changed and the entry removed but
2171     // the "changed" event from `Notifier` may have not yet been
2172     // processed (note that events are emitted from their own
2173     // tasklet). In such a case we keep `serverSockAddr` as empty.
2174 
2175 exit:
2176     if (!serverSockAddr.GetAddress().IsUnspecified() && (GetServerAddress() != serverSockAddr))
2177     {
2178         // We specifically update `mHostInfo` to `kToAdd` state. This
2179         // ensures that `Stop()` will keep it as kToAdd` and we detect
2180         // that the host info has not been registered yet and allow the
2181         // `SelectNextServer()` to happen again if the timeouts/failures
2182         // continue to happen with the new server.
2183 
2184         mHostInfo.SetState(kToAdd);
2185         Stop(kRequesterAuto, kKeepRetryInterval);
2186         IgnoreError(Start(serverSockAddr, kRequesterAuto));
2187     }
2188 }
2189 #endif // OPENTHREAD_CONFIG_SRP_CLIENT_SWITCH_SERVER_ON_FAILURE
2190 
2191 #endif // OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE
2192 
ItemStateToString(ItemState aState)2193 const char *Client::ItemStateToString(ItemState aState)
2194 {
2195     static const char *const kItemStateStrings[] = {
2196         "ToAdd",      // kToAdd      (0)
2197         "Adding",     // kAdding     (1)
2198         "ToRefresh",  // kToRefresh  (2)
2199         "Refreshing", // kRefreshing (3)
2200         "ToRemove",   // kToRemove   (4)
2201         "Removing",   // kRemoving   (5)
2202         "Registered", // kRegistered (6)
2203         "Removed",    // kRemoved    (7)
2204     };
2205 
2206     return kItemStateStrings[aState];
2207 }
2208 
2209 #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_INFO)
2210 
StateToString(State aState)2211 const char *Client::StateToString(State aState)
2212 {
2213     static const char *const kStateStrings[] = {
2214         "Stopped",  // kStateStopped  (0)
2215         "Paused",   // kStatePaused   (1)
2216         "ToUpdate", // kStateToUpdate (2)
2217         "Updating", // kStateUpdating (3)
2218         "Updated",  // kStateUpdated  (4)
2219         "ToRetry",  // kStateToRetry  (5)
2220     };
2221 
2222     static_assert(kStateStopped == 0, "kStateStopped value is not correct");
2223     static_assert(kStatePaused == 1, "kStatePaused value is not correct");
2224     static_assert(kStateToUpdate == 2, "kStateToUpdate value is not correct");
2225     static_assert(kStateUpdating == 3, "kStateUpdating value is not correct");
2226     static_assert(kStateUpdated == 4, "kStateUpdated value is not correct");
2227     static_assert(kStateToRetry == 5, "kStateToRetry value is not correct");
2228 
2229     return kStateStrings[aState];
2230 }
2231 
LogRetryWaitInterval(void) const2232 void Client::LogRetryWaitInterval(void) const
2233 {
2234     constexpr uint16_t kLogInMsecLimit = 5000; // Max interval (in msec) to log the value in msec unit
2235 
2236     uint32_t interval = GetRetryWaitInterval();
2237 
2238     LogInfo("Retry interval %lu %s", ToUlong((interval < kLogInMsecLimit) ? interval : Time::MsecToSec(interval)),
2239             (interval < kLogInMsecLimit) ? "ms" : "sec");
2240 }
2241 
2242 #endif // #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_INFO)
2243 
2244 } // namespace Srp
2245 } // namespace ot
2246 
2247 #endif // OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE
2248