1 /*
2  *  Copyright (c) 2016, 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 implements Thread's EID-to-RLOC mapping and caching.
32  */
33 
34 #include "address_resolver.hpp"
35 
36 #include "coap/coap_message.hpp"
37 #include "common/as_core_type.hpp"
38 #include "common/code_utils.hpp"
39 #include "common/debug.hpp"
40 #include "common/encoding.hpp"
41 #include "common/instance.hpp"
42 #include "common/locator_getters.hpp"
43 #include "common/log.hpp"
44 #include "common/time.hpp"
45 #include "mac/mac_types.hpp"
46 #include "thread/mesh_forwarder.hpp"
47 #include "thread/mle_router.hpp"
48 #include "thread/thread_netif.hpp"
49 #include "thread/uri_paths.hpp"
50 
51 namespace ot {
52 
53 RegisterLogModule("AddrResolver");
54 
AddressResolver(Instance & aInstance)55 AddressResolver::AddressResolver(Instance &aInstance)
56     : InstanceLocator(aInstance)
57 #if OPENTHREAD_FTD
58     , mCacheEntryPool(aInstance)
59     , mIcmpHandler(&AddressResolver::HandleIcmpReceive, this)
60 #endif
61 {
62 #if OPENTHREAD_FTD
63     IgnoreError(Get<Ip6::Icmp>().RegisterHandler(mIcmpHandler));
64 #endif
65 }
66 
67 #if OPENTHREAD_FTD
68 
Clear(void)69 void AddressResolver::Clear(void)
70 {
71     CacheEntryList *lists[] = {&mCachedList, &mSnoopedList, &mQueryList, &mQueryRetryList};
72 
73     for (CacheEntryList *list : lists)
74     {
75         CacheEntry *entry;
76 
77         while ((entry = list->Pop()) != nullptr)
78         {
79             if (list == &mQueryList)
80             {
81                 Get<MeshForwarder>().HandleResolved(entry->GetTarget(), kErrorDrop);
82             }
83 
84             mCacheEntryPool.Free(*entry);
85         }
86     }
87 }
88 
GetNextCacheEntry(EntryInfo & aInfo,Iterator & aIterator) const89 Error AddressResolver::GetNextCacheEntry(EntryInfo &aInfo, Iterator &aIterator) const
90 {
91     Error                 error = kErrorNone;
92     const CacheEntryList *list  = aIterator.GetList();
93     const CacheEntry     *entry = aIterator.GetEntry();
94 
95     while (entry == nullptr)
96     {
97         if (list == nullptr)
98         {
99             list = &mCachedList;
100         }
101         else if (list == &mCachedList)
102         {
103             list = &mSnoopedList;
104         }
105         else if (list == &mSnoopedList)
106         {
107             list = &mQueryList;
108         }
109         else if (list == &mQueryList)
110         {
111             list = &mQueryRetryList;
112         }
113         else
114         {
115             ExitNow(error = kErrorNotFound);
116         }
117 
118         entry = list->GetHead();
119     }
120 
121     // Update the iterator then populate the `aInfo`.
122 
123     aIterator.SetEntry(entry->GetNext());
124     aIterator.SetList(list);
125 
126     aInfo.Clear();
127     aInfo.mTarget = entry->GetTarget();
128     aInfo.mRloc16 = entry->GetRloc16();
129 
130     if (list == &mCachedList)
131     {
132         aInfo.mState          = MapEnum(EntryInfo::kStateCached);
133         aInfo.mCanEvict       = true;
134         aInfo.mValidLastTrans = entry->IsLastTransactionTimeValid();
135 
136         VerifyOrExit(entry->IsLastTransactionTimeValid());
137 
138         aInfo.mLastTransTime = entry->GetLastTransactionTime();
139         AsCoreType(&aInfo.mMeshLocalEid).SetPrefix(Get<Mle::MleRouter>().GetMeshLocalPrefix());
140         AsCoreType(&aInfo.mMeshLocalEid).SetIid(entry->GetMeshLocalIid());
141 
142         ExitNow();
143     }
144 
145     if (list == &mSnoopedList)
146     {
147         aInfo.mState = MapEnum(EntryInfo::kStateSnooped);
148     }
149     else if (list == &mQueryList)
150     {
151         aInfo.mState = MapEnum(EntryInfo::kStateQuery);
152     }
153     else
154     {
155         aInfo.mState    = MapEnum(EntryInfo::kStateRetryQuery);
156         aInfo.mRampDown = entry->IsInRampDown();
157     }
158 
159     aInfo.mCanEvict   = entry->CanEvict();
160     aInfo.mTimeout    = entry->GetTimeout();
161     aInfo.mRetryDelay = entry->GetRetryDelay();
162 
163 exit:
164     return error;
165 }
166 
RemoveEntriesForRouterId(uint8_t aRouterId)167 void AddressResolver::RemoveEntriesForRouterId(uint8_t aRouterId)
168 {
169     Remove(Mle::Rloc16FromRouterId(aRouterId), /* aMatchRouterId */ true);
170 }
171 
RemoveEntriesForRloc16(uint16_t aRloc16)172 void AddressResolver::RemoveEntriesForRloc16(uint16_t aRloc16) { Remove(aRloc16, /* aMatchRouterId */ false); }
173 
GetEntryAfter(CacheEntry * aPrev,CacheEntryList & aList)174 AddressResolver::CacheEntry *AddressResolver::GetEntryAfter(CacheEntry *aPrev, CacheEntryList &aList)
175 {
176     return (aPrev == nullptr) ? aList.GetHead() : aPrev->GetNext();
177 }
178 
Remove(Mac::ShortAddress aRloc16,bool aMatchRouterId)179 void AddressResolver::Remove(Mac::ShortAddress aRloc16, bool aMatchRouterId)
180 {
181     CacheEntryList *lists[] = {&mCachedList, &mSnoopedList};
182 
183     for (CacheEntryList *list : lists)
184     {
185         CacheEntry *prev = nullptr;
186         CacheEntry *entry;
187 
188         while ((entry = GetEntryAfter(prev, *list)) != nullptr)
189         {
190             if ((aMatchRouterId && Mle::RouterIdMatch(entry->GetRloc16(), aRloc16)) ||
191                 (!aMatchRouterId && (entry->GetRloc16() == aRloc16)))
192             {
193                 RemoveCacheEntry(*entry, *list, prev, aMatchRouterId ? kReasonRemovingRouterId : kReasonRemovingRloc16);
194                 mCacheEntryPool.Free(*entry);
195 
196                 // If the entry is removed from list, we keep the same
197                 // `prev` pointer.
198             }
199             else
200             {
201                 prev = entry;
202             }
203         }
204     }
205 }
206 
FindCacheEntry(const Ip6::Address & aEid,CacheEntryList * & aList,CacheEntry * & aPrevEntry)207 AddressResolver::CacheEntry *AddressResolver::FindCacheEntry(const Ip6::Address &aEid,
208                                                              CacheEntryList    *&aList,
209                                                              CacheEntry        *&aPrevEntry)
210 {
211     CacheEntry     *entry   = nullptr;
212     CacheEntryList *lists[] = {&mCachedList, &mSnoopedList, &mQueryList, &mQueryRetryList};
213 
214     for (CacheEntryList *list : lists)
215     {
216         aList = list;
217         entry = aList->FindMatching(aEid, aPrevEntry);
218         VerifyOrExit(entry == nullptr);
219     }
220 
221 exit:
222     return entry;
223 }
224 
RemoveEntryForAddress(const Ip6::Address & aEid)225 void AddressResolver::RemoveEntryForAddress(const Ip6::Address &aEid) { Remove(aEid, kReasonRemovingEid); }
226 
Remove(const Ip6::Address & aEid,Reason aReason)227 void AddressResolver::Remove(const Ip6::Address &aEid, Reason aReason)
228 {
229     CacheEntry     *entry;
230     CacheEntry     *prev;
231     CacheEntryList *list;
232 
233     entry = FindCacheEntry(aEid, list, prev);
234     VerifyOrExit(entry != nullptr);
235 
236     RemoveCacheEntry(*entry, *list, prev, aReason);
237     mCacheEntryPool.Free(*entry);
238 
239 exit:
240     return;
241 }
242 
ReplaceEntriesForRloc16(uint16_t aOldRloc16,uint16_t aNewRloc16)243 void AddressResolver::ReplaceEntriesForRloc16(uint16_t aOldRloc16, uint16_t aNewRloc16)
244 {
245     CacheEntryList *lists[] = {&mCachedList, &mSnoopedList};
246 
247     for (CacheEntryList *list : lists)
248     {
249         for (CacheEntry &entry : *list)
250         {
251             if (entry.GetRloc16() == aOldRloc16)
252             {
253                 entry.SetRloc16(aNewRloc16);
254             }
255         }
256     }
257 }
258 
NewCacheEntry(bool aSnoopedEntry)259 AddressResolver::CacheEntry *AddressResolver::NewCacheEntry(bool aSnoopedEntry)
260 {
261     CacheEntry     *newEntry  = nullptr;
262     CacheEntry     *prevEntry = nullptr;
263     CacheEntryList *lists[]   = {&mSnoopedList, &mQueryRetryList, &mQueryList, &mCachedList};
264 
265     // The following order is used when trying to allocate a new cache
266     // entry: First the cache pool is checked, followed by the list
267     // of snooped entries, then query-retry list (entries in delay
268     // retry timeout wait due to a prior query failing to get a
269     // response), then the query list (entries actively querying and
270     // waiting for address notification response), and finally the
271     // cached (in-use) list. Within each list the oldest entry is
272     // reclaimed first (the list's tail). We also make sure the entry
273     // can be evicted (e.g., first time query entries can not be
274     // evicted till timeout).
275 
276     newEntry = mCacheEntryPool.Allocate();
277     VerifyOrExit(newEntry == nullptr);
278 
279     for (CacheEntryList *list : lists)
280     {
281         CacheEntry *prev;
282         CacheEntry *entry;
283         uint16_t    numNonEvictable = 0;
284 
285         for (prev = nullptr; (entry = GetEntryAfter(prev, *list)) != nullptr; prev = entry)
286         {
287             if ((list != &mCachedList) && !entry->CanEvict())
288             {
289                 numNonEvictable++;
290                 continue;
291             }
292 
293             newEntry  = entry;
294             prevEntry = prev;
295         }
296 
297         if (newEntry != nullptr)
298         {
299             RemoveCacheEntry(*newEntry, *list, prevEntry, kReasonEvictingForNewEntry);
300             ExitNow();
301         }
302 
303         if (aSnoopedEntry && (list == &mSnoopedList))
304         {
305             // Check if the new entry is being requested for "snoop
306             // optimization" (i.e., inspection of a received message).
307             // When a new snooped entry is added, we do not allow it
308             // to be evicted for a short timeout. This allows some
309             // delay for a response message to use the entry (if entry
310             // is used it will be moved to the cached list). If a
311             // snooped entry is not used after the timeout, we allow
312             // it to be evicted. To ensure snooped entries do not
313             // overwrite other cached entries, we limit the number of
314             // snooped entries that are in timeout mode and cannot be
315             // evicted by `kMaxNonEvictableSnoopedEntries`.
316 
317             VerifyOrExit(numNonEvictable < kMaxNonEvictableSnoopedEntries);
318         }
319     }
320 
321 exit:
322     return newEntry;
323 }
324 
RemoveCacheEntry(CacheEntry & aEntry,CacheEntryList & aList,CacheEntry * aPrevEntry,Reason aReason)325 void AddressResolver::RemoveCacheEntry(CacheEntry     &aEntry,
326                                        CacheEntryList &aList,
327                                        CacheEntry     *aPrevEntry,
328                                        Reason          aReason)
329 {
330     aList.PopAfter(aPrevEntry);
331 
332     if (&aList == &mQueryList)
333     {
334         Get<MeshForwarder>().HandleResolved(aEntry.GetTarget(), kErrorDrop);
335     }
336 
337     LogCacheEntryChange(kEntryRemoved, aReason, aEntry, &aList);
338 }
339 
UpdateCacheEntry(const Ip6::Address & aEid,Mac::ShortAddress aRloc16)340 Error AddressResolver::UpdateCacheEntry(const Ip6::Address &aEid, Mac::ShortAddress aRloc16)
341 {
342     // This method updates an existing cache entry for the EID (if any).
343     // Returns `kErrorNone` if entry is found and successfully updated,
344     // `kErrorNotFound` if no matching entry.
345 
346     Error           error = kErrorNone;
347     CacheEntryList *list;
348     CacheEntry     *entry;
349     CacheEntry     *prev;
350 
351     entry = FindCacheEntry(aEid, list, prev);
352     VerifyOrExit(entry != nullptr, error = kErrorNotFound);
353 
354     if ((list == &mCachedList) || (list == &mSnoopedList))
355     {
356         VerifyOrExit(entry->GetRloc16() != aRloc16);
357         entry->SetRloc16(aRloc16);
358     }
359     else
360     {
361         // Entry is in `mQueryList` or `mQueryRetryList`. Remove it
362         // from its current list, update it, and then add it to the
363         // `mCachedList`.
364 
365         list->PopAfter(prev);
366 
367         entry->SetRloc16(aRloc16);
368         entry->MarkLastTransactionTimeAsInvalid();
369         mCachedList.Push(*entry);
370 
371         Get<MeshForwarder>().HandleResolved(aEid, kErrorNone);
372     }
373 
374     LogCacheEntryChange(kEntryUpdated, kReasonSnoop, *entry);
375 
376 exit:
377     return error;
378 }
379 
UpdateSnoopedCacheEntry(const Ip6::Address & aEid,Mac::ShortAddress aRloc16,Mac::ShortAddress aDest)380 void AddressResolver::UpdateSnoopedCacheEntry(const Ip6::Address &aEid,
381                                               Mac::ShortAddress   aRloc16,
382                                               Mac::ShortAddress   aDest)
383 {
384     uint16_t          numNonEvictable = 0;
385     CacheEntry       *entry;
386     Mac::ShortAddress macAddress;
387 
388     VerifyOrExit(Get<Mle::MleRouter>().IsFullThreadDevice());
389 
390 #if OPENTHREAD_CONFIG_TMF_ALLOW_ADDRESS_RESOLUTION_USING_NET_DATA_SERVICES
391     VerifyOrExit(ResolveUsingNetDataServices(aEid, macAddress) != kErrorNone);
392 #endif
393 
394     VerifyOrExit(UpdateCacheEntry(aEid, aRloc16) != kErrorNone);
395 
396     // Skip if the `aRloc16` (i.e., the source of the snooped message)
397     // is this device or an MTD (minimal) child of the device itself.
398 
399     macAddress = Get<Mac::Mac>().GetShortAddress();
400     VerifyOrExit((aRloc16 != macAddress) && !Get<Mle::MleRouter>().IsMinimalChild(aRloc16));
401 
402     // Ensure that the destination of the snooped message is this device
403     // or a minimal child of this device.
404 
405     VerifyOrExit((aDest == macAddress) || Get<Mle::MleRouter>().IsMinimalChild(aDest));
406 
407     entry = NewCacheEntry(/* aSnoopedEntry */ true);
408     VerifyOrExit(entry != nullptr);
409 
410     for (CacheEntry &snooped : mSnoopedList)
411     {
412         if (!snooped.CanEvict())
413         {
414             numNonEvictable++;
415         }
416     }
417 
418     entry->SetTarget(aEid);
419     entry->SetRloc16(aRloc16);
420 
421     if (numNonEvictable < kMaxNonEvictableSnoopedEntries)
422     {
423         entry->SetCanEvict(false);
424         entry->SetTimeout(kSnoopBlockEvictionTimeout);
425 
426         Get<TimeTicker>().RegisterReceiver(TimeTicker::kAddressResolver);
427     }
428     else
429     {
430         entry->SetCanEvict(true);
431         entry->SetTimeout(0);
432     }
433 
434     mSnoopedList.Push(*entry);
435 
436     LogCacheEntryChange(kEntryAdded, kReasonSnoop, *entry);
437 
438 exit:
439     return;
440 }
441 
RestartAddressQueries(void)442 void AddressResolver::RestartAddressQueries(void)
443 {
444     CacheEntry *tail;
445 
446     // We move all entries from `mQueryRetryList` at the tail of
447     // `mQueryList` and then (re)send Address Query for all entries in
448     // the updated `mQueryList`.
449 
450     tail = mQueryList.GetTail();
451 
452     if (tail == nullptr)
453     {
454         mQueryList.SetHead(mQueryRetryList.GetHead());
455     }
456     else
457     {
458         tail->SetNext(mQueryRetryList.GetHead());
459     }
460 
461     mQueryRetryList.Clear();
462 
463     for (CacheEntry &entry : mQueryList)
464     {
465         IgnoreError(SendAddressQuery(entry.GetTarget()));
466 
467         entry.SetTimeout(kAddressQueryTimeout);
468         entry.SetRetryDelay(kAddressQueryInitialRetryDelay);
469         entry.SetCanEvict(false);
470     }
471 }
472 
LookUp(const Ip6::Address & aEid)473 Mac::ShortAddress AddressResolver::LookUp(const Ip6::Address &aEid)
474 {
475     Mac::ShortAddress rloc16 = Mac::kShortAddrInvalid;
476 
477     IgnoreError(Resolve(aEid, rloc16, /* aAllowAddressQuery */ false));
478     return rloc16;
479 }
480 
Resolve(const Ip6::Address & aEid,Mac::ShortAddress & aRloc16,bool aAllowAddressQuery)481 Error AddressResolver::Resolve(const Ip6::Address &aEid, Mac::ShortAddress &aRloc16, bool aAllowAddressQuery)
482 {
483     Error           error = kErrorNone;
484     CacheEntry     *entry;
485     CacheEntry     *prev = nullptr;
486     CacheEntryList *list;
487 
488 #if OPENTHREAD_CONFIG_TMF_ALLOW_ADDRESS_RESOLUTION_USING_NET_DATA_SERVICES
489     VerifyOrExit(ResolveUsingNetDataServices(aEid, aRloc16) != kErrorNone);
490 #endif
491 
492     entry = FindCacheEntry(aEid, list, prev);
493 
494     if (entry == nullptr)
495     {
496         // If the entry is not present in any of the lists, try to
497         // allocate a new entry and perform address query. We do not
498         // allow first-time address query entries to be evicted till
499         // timeout.
500 
501         VerifyOrExit(aAllowAddressQuery, error = kErrorNotFound);
502 
503         entry = NewCacheEntry(/* aSnoopedEntry */ false);
504         VerifyOrExit(entry != nullptr, error = kErrorNoBufs);
505 
506         entry->SetTarget(aEid);
507         entry->SetRloc16(Mac::kShortAddrInvalid);
508         entry->SetRetryDelay(kAddressQueryInitialRetryDelay);
509         entry->SetCanEvict(false);
510         list = nullptr;
511     }
512 
513     if ((list == &mCachedList) || (list == &mSnoopedList))
514     {
515         // Remove the entry from its current list and push it at the
516         // head of cached list.
517 
518         list->PopAfter(prev);
519 
520         if (list == &mSnoopedList)
521         {
522             entry->MarkLastTransactionTimeAsInvalid();
523         }
524 
525         mCachedList.Push(*entry);
526         aRloc16 = entry->GetRloc16();
527         ExitNow();
528     }
529 
530     // Note that if `aAllowAddressQuery` is `false` then the `entry`
531     // is definitely already in a list, i.e., we cannot not get here
532     // with `aAllowAddressQuery` being `false` and `entry` being a
533     // newly allocated one, due to the `VerifyOrExit` check that
534     // `aAllowAddressQuery` is `true` before allocating a new cache
535     // entry.
536     VerifyOrExit(aAllowAddressQuery, error = kErrorNotFound);
537 
538     if (list == &mQueryList)
539     {
540         ExitNow(error = kErrorAddressQuery);
541     }
542 
543     if (list == &mQueryRetryList)
544     {
545         // Allow an entry in query-retry mode to resend an Address
546         // Query again only if it is in ramp down mode, i.e., the
547         // retry delay timeout is expired.
548 
549         VerifyOrExit(entry->IsInRampDown(), error = kErrorDrop);
550         mQueryRetryList.PopAfter(prev);
551     }
552 
553     entry->SetTimeout(kAddressQueryTimeout);
554 
555     error = SendAddressQuery(aEid);
556     VerifyOrExit(error == kErrorNone, mCacheEntryPool.Free(*entry));
557 
558     if (list == nullptr)
559     {
560         LogCacheEntryChange(kEntryAdded, kReasonQueryRequest, *entry);
561     }
562 
563     mQueryList.Push(*entry);
564     error = kErrorAddressQuery;
565 
566 exit:
567     return error;
568 }
569 
570 #if OPENTHREAD_CONFIG_TMF_ALLOW_ADDRESS_RESOLUTION_USING_NET_DATA_SERVICES
571 
ResolveUsingNetDataServices(const Ip6::Address & aEid,Mac::ShortAddress & aRloc16)572 Error AddressResolver::ResolveUsingNetDataServices(const Ip6::Address &aEid, Mac::ShortAddress &aRloc16)
573 {
574     // Tries to resolve `aEid` Network Data DNS/SRP Unicast address
575     // service entries.  Returns `kErrorNone` and updates `aRloc16`
576     // if successful, otherwise returns `kErrorNotFound`.
577 
578     Error                                     error = kErrorNotFound;
579     NetworkData::Service::Manager::Iterator   iterator;
580     NetworkData::Service::DnsSrpUnicast::Info unicastInfo;
581 
582     VerifyOrExit(Get<Mle::Mle>().GetDeviceMode().GetNetworkDataType() == NetworkData::kFullSet);
583 
584     while (Get<NetworkData::Service::Manager>().GetNextDnsSrpUnicastInfo(iterator, unicastInfo) == kErrorNone)
585     {
586         if (unicastInfo.mOrigin != NetworkData::Service::DnsSrpUnicast::kFromServerData)
587         {
588             continue;
589         }
590 
591         if (aEid == unicastInfo.mSockAddr.GetAddress())
592         {
593             aRloc16 = unicastInfo.mRloc16;
594             error   = kErrorNone;
595             ExitNow();
596         }
597     }
598 
599 exit:
600     return error;
601 }
602 
603 #endif // OPENTHREAD_CONFIG_TMF_ALLOW_ADDRESS_RESOLUTION_USING_NET_DATA_SERVICES
604 
SendAddressQuery(const Ip6::Address & aEid)605 Error AddressResolver::SendAddressQuery(const Ip6::Address &aEid)
606 {
607     Error            error;
608     Coap::Message   *message;
609     Tmf::MessageInfo messageInfo(GetInstance());
610 
611     message = Get<Tmf::Agent>().NewPriorityNonConfirmablePostMessage(kUriAddressQuery);
612     VerifyOrExit(message != nullptr, error = kErrorNoBufs);
613 
614     SuccessOrExit(error = Tlv::Append<ThreadTargetTlv>(*message, aEid));
615 
616     messageInfo.SetSockAddrToRlocPeerAddrToRealmLocalAllRoutersMulticast();
617 
618     SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));
619 
620     LogInfo("Sent %s for %s", UriToString<kUriAddressQuery>(), aEid.ToString().AsCString());
621 
622 exit:
623 
624     Get<TimeTicker>().RegisterReceiver(TimeTicker::kAddressResolver);
625     FreeMessageOnError(message, error);
626 
627 #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE
628     if (Get<BackboneRouter::Local>().IsPrimary() && Get<BackboneRouter::Leader>().IsDomainUnicast(aEid))
629     {
630         uint16_t selfRloc16 = Get<Mle::MleRouter>().GetRloc16();
631 
632         LogInfo("Extending %s to %s for target %s, rloc16=%04x(self)", UriToString<kUriAddressQuery>(),
633                 UriToString<kUriBackboneQuery>(), aEid.ToString().AsCString(), selfRloc16);
634         IgnoreError(Get<BackboneRouter::Manager>().SendBackboneQuery(aEid, selfRloc16));
635     }
636 #endif
637 
638     return error;
639 }
640 
641 template <>
HandleTmf(Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)642 void AddressResolver::HandleTmf<kUriAddressNotify>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
643 {
644     Ip6::Address             target;
645     Ip6::InterfaceIdentifier meshLocalIid;
646     uint16_t                 rloc16;
647     uint32_t                 lastTransactionTime;
648     CacheEntryList          *list;
649     CacheEntry              *entry;
650     CacheEntry              *prev;
651 
652     VerifyOrExit(aMessage.IsConfirmablePostRequest());
653 
654     SuccessOrExit(Tlv::Find<ThreadTargetTlv>(aMessage, target));
655     SuccessOrExit(Tlv::Find<ThreadMeshLocalEidTlv>(aMessage, meshLocalIid));
656     SuccessOrExit(Tlv::Find<ThreadRloc16Tlv>(aMessage, rloc16));
657 
658     switch (Tlv::Find<ThreadLastTransactionTimeTlv>(aMessage, lastTransactionTime))
659     {
660     case kErrorNone:
661         break;
662     case kErrorNotFound:
663         lastTransactionTime = 0;
664         break;
665     default:
666         ExitNow();
667     }
668 
669     LogInfo("Received %s from 0x%04x for %s to 0x%04x", UriToString<kUriAddressNotify>(),
670             aMessageInfo.GetPeerAddr().GetIid().GetLocator(), target.ToString().AsCString(), rloc16);
671 
672     entry = FindCacheEntry(target, list, prev);
673     VerifyOrExit(entry != nullptr);
674 
675     if (list == &mCachedList)
676     {
677         if (entry->IsLastTransactionTimeValid())
678         {
679             // Receiving multiple Address Notification for an EID from
680             // different mesh-local IIDs indicates address is in use
681             // by more than one device. Try to resolve the duplicate
682             // address by sending an Address Error message.
683 
684             VerifyOrExit(entry->GetMeshLocalIid() == meshLocalIid, SendAddressError(target, meshLocalIid, nullptr));
685 
686             VerifyOrExit(lastTransactionTime < entry->GetLastTransactionTime());
687         }
688     }
689 
690     entry->SetRloc16(rloc16);
691     entry->SetMeshLocalIid(meshLocalIid);
692     entry->SetLastTransactionTime(lastTransactionTime);
693 
694     list->PopAfter(prev);
695     mCachedList.Push(*entry);
696 
697     LogCacheEntryChange(kEntryUpdated, kReasonReceivedNotification, *entry);
698 
699     if (Get<Tmf::Agent>().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone)
700     {
701         LogInfo("Sent %s ack", UriToString<kUriAddressNotify>());
702     }
703 
704     Get<MeshForwarder>().HandleResolved(target, kErrorNone);
705 
706 exit:
707     return;
708 }
709 
SendAddressError(const Ip6::Address & aTarget,const Ip6::InterfaceIdentifier & aMeshLocalIid,const Ip6::Address * aDestination)710 void AddressResolver::SendAddressError(const Ip6::Address             &aTarget,
711                                        const Ip6::InterfaceIdentifier &aMeshLocalIid,
712                                        const Ip6::Address             *aDestination)
713 {
714     Error            error;
715     Coap::Message   *message;
716     Tmf::MessageInfo messageInfo(GetInstance());
717 
718     VerifyOrExit((message = Get<Tmf::Agent>().NewMessage()) != nullptr, error = kErrorNoBufs);
719 
720     message->Init(aDestination == nullptr ? Coap::kTypeNonConfirmable : Coap::kTypeConfirmable, Coap::kCodePost);
721     SuccessOrExit(error = message->AppendUriPathOptions(PathForUri(kUriAddressError)));
722     SuccessOrExit(error = message->SetPayloadMarker());
723 
724     SuccessOrExit(error = Tlv::Append<ThreadTargetTlv>(*message, aTarget));
725     SuccessOrExit(error = Tlv::Append<ThreadMeshLocalEidTlv>(*message, aMeshLocalIid));
726 
727     if (aDestination == nullptr)
728     {
729         messageInfo.SetSockAddrToRlocPeerAddrToRealmLocalAllRoutersMulticast();
730     }
731     else
732     {
733         messageInfo.SetSockAddrToRlocPeerAddrTo(*aDestination);
734     }
735 
736     SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));
737 
738     LogInfo("Sent %s for target %s", UriToString<kUriAddressError>(), aTarget.ToString().AsCString());
739 
740 exit:
741 
742     if (error != kErrorNone)
743     {
744         FreeMessage(message);
745         LogInfo("Failed to send %s: %s", UriToString<kUriAddressError>(), ErrorToString(error));
746     }
747 }
748 
749 #endif // OPENTHREAD_FTD
750 
751 template <>
HandleTmf(Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)752 void AddressResolver::HandleTmf<kUriAddressError>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
753 {
754     Error                    error = kErrorNone;
755     Ip6::Address             target;
756     Ip6::InterfaceIdentifier meshLocalIid;
757 #if OPENTHREAD_FTD
758     Mac::ExtAddress extAddr;
759     Ip6::Address    destination;
760 #endif
761 
762     VerifyOrExit(aMessage.IsPostRequest(), error = kErrorDrop);
763 
764     LogInfo("Received %s", UriToString<kUriAddressError>());
765 
766     if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast())
767     {
768         if (Get<Tmf::Agent>().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone)
769         {
770             LogInfo("Sent %s ack", UriToString<kUriAddressError>());
771         }
772     }
773 
774     SuccessOrExit(error = Tlv::Find<ThreadTargetTlv>(aMessage, target));
775     SuccessOrExit(error = Tlv::Find<ThreadMeshLocalEidTlv>(aMessage, meshLocalIid));
776 
777     for (const Ip6::Netif::UnicastAddress &address : Get<ThreadNetif>().GetUnicastAddresses())
778     {
779         if (address.GetAddress() == target && Get<Mle::MleRouter>().GetMeshLocal64().GetIid() != meshLocalIid)
780         {
781             // Target EID matches address and Mesh Local EID differs
782 #if OPENTHREAD_CONFIG_DUA_ENABLE
783             if (Get<BackboneRouter::Leader>().IsDomainUnicast(address.GetAddress()))
784             {
785                 Get<DuaManager>().NotifyDuplicateDomainUnicastAddress();
786             }
787             else
788 #endif
789             {
790                 Get<ThreadNetif>().RemoveUnicastAddress(address);
791             }
792 
793             ExitNow();
794         }
795     }
796 
797 #if OPENTHREAD_FTD
798     meshLocalIid.ConvertToExtAddress(extAddr);
799 
800     for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid))
801     {
802         if (child.IsFullThreadDevice())
803         {
804             continue;
805         }
806 
807         if (child.GetExtAddress() != extAddr)
808         {
809             // Mesh Local EID differs, so check whether Target EID
810             // matches a child address and if so remove it.
811 
812             if (child.RemoveIp6Address(target) == kErrorNone)
813             {
814                 SuccessOrExit(error = Get<Mle::Mle>().GetLocatorAddress(destination, child.GetRloc16()));
815 
816                 SendAddressError(target, meshLocalIid, &destination);
817                 ExitNow();
818             }
819         }
820     }
821 #endif // OPENTHREAD_FTD
822 
823 exit:
824 
825     if (error != kErrorNone)
826     {
827         LogWarn("Error %s when processing %s", ErrorToString(error), UriToString<kUriAddressError>());
828     }
829 }
830 
831 #if OPENTHREAD_FTD
832 
833 template <>
HandleTmf(Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)834 void AddressResolver::HandleTmf<kUriAddressQuery>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
835 {
836     Ip6::Address target;
837     uint32_t     lastTransactionTime;
838 
839     VerifyOrExit(aMessage.IsNonConfirmablePostRequest());
840 
841     SuccessOrExit(Tlv::Find<ThreadTargetTlv>(aMessage, target));
842 
843     LogInfo("Received %s from 0x%04x for target %s", UriToString<kUriAddressQuery>(),
844             aMessageInfo.GetPeerAddr().GetIid().GetLocator(), target.ToString().AsCString());
845 
846     if (Get<ThreadNetif>().HasUnicastAddress(target))
847     {
848         SendAddressQueryResponse(target, Get<Mle::MleRouter>().GetMeshLocal64().GetIid(), nullptr,
849                                  aMessageInfo.GetPeerAddr());
850         ExitNow();
851     }
852 
853     for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid))
854     {
855         if (child.IsFullThreadDevice() || child.GetLinkFailures() >= Mle::kFailedChildTransmissions)
856         {
857             continue;
858         }
859 
860         if (child.HasIp6Address(target))
861         {
862             lastTransactionTime = Time::MsecToSec(TimerMilli::GetNow() - child.GetLastHeard());
863             SendAddressQueryResponse(target, child.GetMeshLocalIid(), &lastTransactionTime, aMessageInfo.GetPeerAddr());
864             ExitNow();
865         }
866     }
867 
868 #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE
869     if (Get<BackboneRouter::Local>().IsPrimary() && Get<BackboneRouter::Leader>().IsDomainUnicast(target))
870     {
871         uint16_t srcRloc16 = aMessageInfo.GetPeerAddr().GetIid().GetLocator();
872 
873         LogInfo("Extending %s to %s for target %s rloc16=%04x", UriToString<kUriAddressQuery>(),
874                 UriToString<kUriBackboneQuery>(), target.ToString().AsCString(), srcRloc16);
875         IgnoreError(Get<BackboneRouter::Manager>().SendBackboneQuery(target, srcRloc16));
876     }
877 #endif
878 
879 exit:
880     return;
881 }
882 
SendAddressQueryResponse(const Ip6::Address & aTarget,const Ip6::InterfaceIdentifier & aMeshLocalIid,const uint32_t * aLastTransactionTime,const Ip6::Address & aDestination)883 void AddressResolver::SendAddressQueryResponse(const Ip6::Address             &aTarget,
884                                                const Ip6::InterfaceIdentifier &aMeshLocalIid,
885                                                const uint32_t                 *aLastTransactionTime,
886                                                const Ip6::Address             &aDestination)
887 {
888     Error            error;
889     Coap::Message   *message;
890     Tmf::MessageInfo messageInfo(GetInstance());
891 
892     message = Get<Tmf::Agent>().NewPriorityConfirmablePostMessage(kUriAddressNotify);
893     VerifyOrExit(message != nullptr, error = kErrorNoBufs);
894 
895     SuccessOrExit(error = Tlv::Append<ThreadTargetTlv>(*message, aTarget));
896     SuccessOrExit(error = Tlv::Append<ThreadMeshLocalEidTlv>(*message, aMeshLocalIid));
897     SuccessOrExit(error = Tlv::Append<ThreadRloc16Tlv>(*message, Get<Mle::MleRouter>().GetRloc16()));
898 
899     if (aLastTransactionTime != nullptr)
900     {
901         SuccessOrExit(error = Tlv::Append<ThreadLastTransactionTimeTlv>(*message, *aLastTransactionTime));
902     }
903 
904     messageInfo.SetSockAddrToRlocPeerAddrTo(aDestination);
905 
906     SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));
907 
908     LogInfo("Sent %s for target %s", UriToString<kUriAddressNotify>(), aTarget.ToString().AsCString());
909 
910 exit:
911     FreeMessageOnError(message, error);
912 }
913 
HandleTimeTick(void)914 void AddressResolver::HandleTimeTick(void)
915 {
916     bool continueRxingTicks = false;
917 
918     for (CacheEntry &entry : mSnoopedList)
919     {
920         if (entry.IsTimeoutZero())
921         {
922             continue;
923         }
924 
925         continueRxingTicks = true;
926         entry.DecrementTimeout();
927 
928         if (entry.IsTimeoutZero())
929         {
930             entry.SetCanEvict(true);
931         }
932     }
933 
934     for (CacheEntry &entry : mQueryRetryList)
935     {
936         if (entry.IsTimeoutZero())
937         {
938             continue;
939         }
940 
941         continueRxingTicks = true;
942         entry.DecrementTimeout();
943 
944         if (entry.IsTimeoutZero())
945         {
946             if (!entry.IsInRampDown())
947             {
948                 entry.SetRampDown(true);
949                 entry.SetTimeout(kAddressQueryMaxRetryDelay);
950 
951                 LogInfo("Starting ramp down of %s retry-delay:%u", entry.GetTarget().ToString().AsCString(),
952                         entry.GetTimeout());
953             }
954             else
955             {
956                 uint16_t retryDelay = entry.GetRetryDelay();
957 
958                 retryDelay >>= 1;
959                 retryDelay = Max(retryDelay, kAddressQueryInitialRetryDelay);
960 
961                 if (retryDelay != entry.GetRetryDelay())
962                 {
963                     entry.SetRetryDelay(retryDelay);
964                     entry.SetTimeout(kAddressQueryMaxRetryDelay);
965 
966                     LogInfo("Ramping down %s retry-delay:%u", entry.GetTarget().ToString().AsCString(), retryDelay);
967                 }
968             }
969         }
970     }
971 
972     {
973         CacheEntry *prev = nullptr;
974         CacheEntry *entry;
975 
976         while ((entry = GetEntryAfter(prev, mQueryList)) != nullptr)
977         {
978             OT_ASSERT(!entry->IsTimeoutZero());
979 
980             continueRxingTicks = true;
981             entry->DecrementTimeout();
982 
983             if (entry->IsTimeoutZero())
984             {
985                 uint16_t retryDelay = entry->GetRetryDelay();
986 
987                 entry->SetTimeout(retryDelay);
988 
989                 retryDelay <<= 1;
990                 retryDelay = Min(retryDelay, kAddressQueryMaxRetryDelay);
991 
992                 entry->SetRetryDelay(retryDelay);
993                 entry->SetCanEvict(true);
994                 entry->SetRampDown(false);
995 
996                 // Move the entry from `mQueryList` to `mQueryRetryList`
997                 mQueryList.PopAfter(prev);
998                 mQueryRetryList.Push(*entry);
999 
1000                 LogInfo("Timed out waiting for %s for %s, retry: %d", UriToString<kUriAddressNotify>(),
1001                         entry->GetTarget().ToString().AsCString(), entry->GetTimeout());
1002 
1003                 Get<MeshForwarder>().HandleResolved(entry->GetTarget(), kErrorDrop);
1004 
1005                 // When the entry is removed from `mQueryList`
1006                 // we keep the `prev` pointer same as before.
1007             }
1008             else
1009             {
1010                 prev = entry;
1011             }
1012         }
1013     }
1014 
1015     if (!continueRxingTicks)
1016     {
1017         Get<TimeTicker>().UnregisterReceiver(TimeTicker::kAddressResolver);
1018     }
1019 }
1020 
HandleIcmpReceive(void * aContext,otMessage * aMessage,const otMessageInfo * aMessageInfo,const otIcmp6Header * aIcmpHeader)1021 void AddressResolver::HandleIcmpReceive(void                *aContext,
1022                                         otMessage           *aMessage,
1023                                         const otMessageInfo *aMessageInfo,
1024                                         const otIcmp6Header *aIcmpHeader)
1025 {
1026     OT_UNUSED_VARIABLE(aMessageInfo);
1027 
1028     static_cast<AddressResolver *>(aContext)->HandleIcmpReceive(AsCoreType(aMessage), AsCoreType(aMessageInfo),
1029                                                                 AsCoreType(aIcmpHeader));
1030 }
1031 
HandleIcmpReceive(Message & aMessage,const Ip6::MessageInfo & aMessageInfo,const Ip6::Icmp::Header & aIcmpHeader)1032 void AddressResolver::HandleIcmpReceive(Message                 &aMessage,
1033                                         const Ip6::MessageInfo  &aMessageInfo,
1034                                         const Ip6::Icmp::Header &aIcmpHeader)
1035 {
1036     OT_UNUSED_VARIABLE(aMessageInfo);
1037 
1038     Ip6::Header ip6Header;
1039 
1040     VerifyOrExit(aIcmpHeader.GetType() == Ip6::Icmp::Header::kTypeDstUnreach);
1041     VerifyOrExit(aIcmpHeader.GetCode() == Ip6::Icmp::Header::kCodeDstUnreachNoRoute);
1042     SuccessOrExit(aMessage.Read(aMessage.GetOffset(), ip6Header));
1043 
1044     Remove(ip6Header.GetDestination(), kReasonReceivedIcmpDstUnreachNoRoute);
1045 
1046 exit:
1047     return;
1048 }
1049 
1050 // LCOV_EXCL_START
1051 
1052 #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_INFO)
1053 
LogCacheEntryChange(EntryChange aChange,Reason aReason,const CacheEntry & aEntry,CacheEntryList * aList)1054 void AddressResolver::LogCacheEntryChange(EntryChange       aChange,
1055                                           Reason            aReason,
1056                                           const CacheEntry &aEntry,
1057                                           CacheEntryList   *aList)
1058 {
1059     static const char *const kChangeStrings[] = {
1060         "added",   // (0) kEntryAdded
1061         "updated", // (1) kEntryUpdated
1062         "removed", // (2) kEntryRemoved
1063     };
1064 
1065     static const char *const kReasonStrings[] = {
1066         "query request",          // (0) kReasonQueryRequest
1067         "snoop",                  // (1) kReasonSnoop
1068         "rx notification",        // (2) kReasonReceivedNotification
1069         "removing router id",     // (3) kReasonRemovingRouterId
1070         "removing rloc16",        // (4) kReasonRemovingRloc16
1071         "rx icmp no route",       // (5) kReasonReceivedIcmpDstUnreachNoRoute
1072         "evicting for new entry", // (6) kReasonEvictingForNewEntry
1073         "removing eid",           // (7) kReasonRemovingEid
1074     };
1075 
1076     static_assert(0 == kEntryAdded, "kEntryAdded value is incorrect");
1077     static_assert(1 == kEntryUpdated, "kEntryUpdated value is incorrect");
1078     static_assert(2 == kEntryRemoved, "kEntryRemoved value is incorrect");
1079 
1080     static_assert(0 == kReasonQueryRequest, "kReasonQueryRequest value is incorrect");
1081     static_assert(1 == kReasonSnoop, "kReasonSnoop value is incorrect");
1082     static_assert(2 == kReasonReceivedNotification, "kReasonReceivedNotification value is incorrect");
1083     static_assert(3 == kReasonRemovingRouterId, "kReasonRemovingRouterId value is incorrect");
1084     static_assert(4 == kReasonRemovingRloc16, "kReasonRemovingRloc16 value is incorrect");
1085     static_assert(5 == kReasonReceivedIcmpDstUnreachNoRoute, "kReasonReceivedIcmpDstUnreachNoRoute value is incorrect");
1086     static_assert(6 == kReasonEvictingForNewEntry, "kReasonEvictingForNewEntry value is incorrect");
1087     static_assert(7 == kReasonRemovingEid, "kReasonRemovingEid value is incorrect");
1088 
1089     LogInfo("Cache entry %s: %s, 0x%04x%s%s - %s", kChangeStrings[aChange], aEntry.GetTarget().ToString().AsCString(),
1090             aEntry.GetRloc16(), (aList == nullptr) ? "" : ", list:", ListToString(aList), kReasonStrings[aReason]);
1091 }
1092 
ListToString(const CacheEntryList * aList) const1093 const char *AddressResolver::ListToString(const CacheEntryList *aList) const
1094 {
1095     const char *str = "";
1096 
1097     VerifyOrExit(aList != &mCachedList, str = "cached");
1098     VerifyOrExit(aList != &mSnoopedList, str = "snooped");
1099     VerifyOrExit(aList != &mQueryList, str = "query");
1100     VerifyOrExit(aList != &mQueryRetryList, str = "query-retry");
1101 
1102 exit:
1103     return str;
1104 }
1105 
1106 #else // #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_INFO)
1107 
LogCacheEntryChange(EntryChange,Reason,const CacheEntry &,CacheEntryList *)1108 void AddressResolver::LogCacheEntryChange(EntryChange, Reason, const CacheEntry &, CacheEntryList *) {}
1109 
1110 #endif // #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_NOTE)
1111 
1112 // LCOV_EXCL_STOP
1113 
1114 //---------------------------------------------------------------------------------------------------------------------
1115 // AddressResolver::CacheEntry
1116 
Init(Instance & aInstance)1117 void AddressResolver::CacheEntry::Init(Instance &aInstance)
1118 {
1119     InstanceLocatorInit::Init(aInstance);
1120     mNextIndex = kNoNextIndex;
1121 }
1122 
GetNext(void)1123 AddressResolver::CacheEntry *AddressResolver::CacheEntry::GetNext(void)
1124 {
1125     return (mNextIndex == kNoNextIndex) ? nullptr : &Get<AddressResolver>().GetCacheEntryPool().GetEntryAt(mNextIndex);
1126 }
1127 
GetNext(void) const1128 const AddressResolver::CacheEntry *AddressResolver::CacheEntry::GetNext(void) const
1129 {
1130     return (mNextIndex == kNoNextIndex) ? nullptr : &Get<AddressResolver>().GetCacheEntryPool().GetEntryAt(mNextIndex);
1131 }
1132 
SetNext(CacheEntry * aEntry)1133 void AddressResolver::CacheEntry::SetNext(CacheEntry *aEntry)
1134 {
1135     VerifyOrExit(aEntry != nullptr, mNextIndex = kNoNextIndex);
1136     mNextIndex = Get<AddressResolver>().GetCacheEntryPool().GetIndexOf(*aEntry);
1137 
1138 exit:
1139     return;
1140 }
1141 
1142 #endif // OPENTHREAD_FTD
1143 
1144 } // namespace ot
1145