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/locator_getters.hpp"
42 #include "common/log.hpp"
43 #include "common/time.hpp"
44 #include "instance/instance.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) && ((list == &mCachedList) || (list == &mSnoopedList)))
495 {
496 list->PopAfter(prev);
497
498 if (Get<RouterTable>().GetNextHop(entry->GetRloc16()) == Mle::kInvalidRloc16)
499 {
500 // If the `entry->GetRloc16()` is unreachable (there is no valid
501 // next hop towards it), we clear the entry so to start a new
502 // address query.
503
504 mCacheEntryPool.Free(*entry);
505 entry = nullptr;
506 }
507 else
508 {
509 // Push the entry at the head of cached list.
510
511 if (list == &mSnoopedList)
512 {
513 entry->MarkLastTransactionTimeAsInvalid();
514 }
515
516 mCachedList.Push(*entry);
517 aRloc16 = entry->GetRloc16();
518 ExitNow();
519 }
520 }
521
522 if (entry == nullptr)
523 {
524 // If the entry is not present in any of the lists, try to
525 // allocate a new entry and perform address query. We do not
526 // allow first-time address query entries to be evicted till
527 // timeout.
528
529 VerifyOrExit(aAllowAddressQuery, error = kErrorNotFound);
530
531 entry = NewCacheEntry(/* aSnoopedEntry */ false);
532 VerifyOrExit(entry != nullptr, error = kErrorNoBufs);
533
534 entry->SetTarget(aEid);
535 entry->SetRloc16(Mac::kShortAddrInvalid);
536 entry->SetRetryDelay(kAddressQueryInitialRetryDelay);
537 entry->SetCanEvict(false);
538 list = nullptr;
539 }
540
541 // Note that if `aAllowAddressQuery` is `false` then the `entry`
542 // is definitely already in a list, i.e., we cannot not get here
543 // with `aAllowAddressQuery` being `false` and `entry` being a
544 // newly allocated one, due to the `VerifyOrExit` check that
545 // `aAllowAddressQuery` is `true` before allocating a new cache
546 // entry.
547 VerifyOrExit(aAllowAddressQuery, error = kErrorNotFound);
548
549 if (list == &mQueryList)
550 {
551 ExitNow(error = kErrorAddressQuery);
552 }
553
554 if (list == &mQueryRetryList)
555 {
556 // Allow an entry in query-retry mode to resend an Address
557 // Query again only if it is in ramp down mode, i.e., the
558 // retry delay timeout is expired.
559
560 VerifyOrExit(entry->IsInRampDown(), error = kErrorDrop);
561 mQueryRetryList.PopAfter(prev);
562 }
563
564 entry->SetTimeout(kAddressQueryTimeout);
565
566 error = SendAddressQuery(aEid);
567 VerifyOrExit(error == kErrorNone, mCacheEntryPool.Free(*entry));
568
569 if (list == nullptr)
570 {
571 LogCacheEntryChange(kEntryAdded, kReasonQueryRequest, *entry);
572 }
573
574 mQueryList.Push(*entry);
575 error = kErrorAddressQuery;
576
577 exit:
578 return error;
579 }
580
581 #if OPENTHREAD_CONFIG_TMF_ALLOW_ADDRESS_RESOLUTION_USING_NET_DATA_SERVICES
582
ResolveUsingNetDataServices(const Ip6::Address & aEid,Mac::ShortAddress & aRloc16)583 Error AddressResolver::ResolveUsingNetDataServices(const Ip6::Address &aEid, Mac::ShortAddress &aRloc16)
584 {
585 // Tries to resolve `aEid` Network Data DNS/SRP Unicast address
586 // service entries. Returns `kErrorNone` and updates `aRloc16`
587 // if successful, otherwise returns `kErrorNotFound`.
588
589 Error error = kErrorNotFound;
590 NetworkData::Service::Manager::Iterator iterator;
591 NetworkData::Service::DnsSrpUnicast::Info unicastInfo;
592
593 VerifyOrExit(Get<Mle::Mle>().GetDeviceMode().GetNetworkDataType() == NetworkData::kFullSet);
594
595 while (Get<NetworkData::Service::Manager>().GetNextDnsSrpUnicastInfo(iterator, unicastInfo) == kErrorNone)
596 {
597 if (unicastInfo.mOrigin != NetworkData::Service::DnsSrpUnicast::kFromServerData)
598 {
599 continue;
600 }
601
602 if (aEid == unicastInfo.mSockAddr.GetAddress())
603 {
604 aRloc16 = unicastInfo.mRloc16;
605 error = kErrorNone;
606 ExitNow();
607 }
608 }
609
610 exit:
611 return error;
612 }
613
614 #endif // OPENTHREAD_CONFIG_TMF_ALLOW_ADDRESS_RESOLUTION_USING_NET_DATA_SERVICES
615
SendAddressQuery(const Ip6::Address & aEid)616 Error AddressResolver::SendAddressQuery(const Ip6::Address &aEid)
617 {
618 Error error;
619 Coap::Message *message;
620 Tmf::MessageInfo messageInfo(GetInstance());
621
622 message = Get<Tmf::Agent>().NewPriorityNonConfirmablePostMessage(kUriAddressQuery);
623 VerifyOrExit(message != nullptr, error = kErrorNoBufs);
624
625 SuccessOrExit(error = Tlv::Append<ThreadTargetTlv>(*message, aEid));
626
627 messageInfo.SetSockAddrToRlocPeerAddrToRealmLocalAllRoutersMulticast();
628
629 SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));
630
631 LogInfo("Sent %s for %s", UriToString<kUriAddressQuery>(), aEid.ToString().AsCString());
632
633 exit:
634
635 Get<TimeTicker>().RegisterReceiver(TimeTicker::kAddressResolver);
636 FreeMessageOnError(message, error);
637
638 #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE
639 if (Get<BackboneRouter::Local>().IsPrimary() && Get<BackboneRouter::Leader>().IsDomainUnicast(aEid))
640 {
641 uint16_t selfRloc16 = Get<Mle::MleRouter>().GetRloc16();
642
643 LogInfo("Extending %s to %s for target %s, rloc16=%04x(self)", UriToString<kUriAddressQuery>(),
644 UriToString<kUriBackboneQuery>(), aEid.ToString().AsCString(), selfRloc16);
645 IgnoreError(Get<BackboneRouter::Manager>().SendBackboneQuery(aEid, selfRloc16));
646 }
647 #endif
648
649 return error;
650 }
651
652 template <>
HandleTmf(Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)653 void AddressResolver::HandleTmf<kUriAddressNotify>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
654 {
655 Ip6::Address target;
656 Ip6::InterfaceIdentifier meshLocalIid;
657 uint16_t rloc16;
658 uint32_t lastTransactionTime;
659 CacheEntryList *list;
660 CacheEntry *entry;
661 CacheEntry *prev;
662
663 VerifyOrExit(aMessage.IsConfirmablePostRequest());
664
665 SuccessOrExit(Tlv::Find<ThreadTargetTlv>(aMessage, target));
666 SuccessOrExit(Tlv::Find<ThreadMeshLocalEidTlv>(aMessage, meshLocalIid));
667 SuccessOrExit(Tlv::Find<ThreadRloc16Tlv>(aMessage, rloc16));
668
669 switch (Tlv::Find<ThreadLastTransactionTimeTlv>(aMessage, lastTransactionTime))
670 {
671 case kErrorNone:
672 break;
673 case kErrorNotFound:
674 lastTransactionTime = 0;
675 break;
676 default:
677 ExitNow();
678 }
679
680 LogInfo("Received %s from 0x%04x for %s to 0x%04x", UriToString<kUriAddressNotify>(),
681 aMessageInfo.GetPeerAddr().GetIid().GetLocator(), target.ToString().AsCString(), rloc16);
682
683 entry = FindCacheEntry(target, list, prev);
684 VerifyOrExit(entry != nullptr);
685
686 if (list == &mCachedList)
687 {
688 if (entry->IsLastTransactionTimeValid())
689 {
690 // Receiving multiple Address Notification for an EID from
691 // different mesh-local IIDs indicates address is in use
692 // by more than one device. Try to resolve the duplicate
693 // address by sending an Address Error message.
694
695 VerifyOrExit(entry->GetMeshLocalIid() == meshLocalIid, SendAddressError(target, meshLocalIid, nullptr));
696
697 VerifyOrExit(lastTransactionTime < entry->GetLastTransactionTime());
698 }
699 }
700
701 entry->SetRloc16(rloc16);
702 entry->SetMeshLocalIid(meshLocalIid);
703 entry->SetLastTransactionTime(lastTransactionTime);
704
705 list->PopAfter(prev);
706 mCachedList.Push(*entry);
707
708 LogCacheEntryChange(kEntryUpdated, kReasonReceivedNotification, *entry);
709
710 if (Get<Tmf::Agent>().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone)
711 {
712 LogInfo("Sent %s ack", UriToString<kUriAddressNotify>());
713 }
714
715 Get<MeshForwarder>().HandleResolved(target, kErrorNone);
716
717 exit:
718 return;
719 }
720
SendAddressError(const Ip6::Address & aTarget,const Ip6::InterfaceIdentifier & aMeshLocalIid,const Ip6::Address * aDestination)721 void AddressResolver::SendAddressError(const Ip6::Address &aTarget,
722 const Ip6::InterfaceIdentifier &aMeshLocalIid,
723 const Ip6::Address *aDestination)
724 {
725 Error error;
726 Coap::Message *message;
727 Tmf::MessageInfo messageInfo(GetInstance());
728
729 VerifyOrExit((message = Get<Tmf::Agent>().NewMessage()) != nullptr, error = kErrorNoBufs);
730
731 message->Init(aDestination == nullptr ? Coap::kTypeNonConfirmable : Coap::kTypeConfirmable, Coap::kCodePost);
732 SuccessOrExit(error = message->AppendUriPathOptions(PathForUri(kUriAddressError)));
733 SuccessOrExit(error = message->SetPayloadMarker());
734
735 SuccessOrExit(error = Tlv::Append<ThreadTargetTlv>(*message, aTarget));
736 SuccessOrExit(error = Tlv::Append<ThreadMeshLocalEidTlv>(*message, aMeshLocalIid));
737
738 if (aDestination == nullptr)
739 {
740 messageInfo.SetSockAddrToRlocPeerAddrToRealmLocalAllRoutersMulticast();
741 }
742 else
743 {
744 messageInfo.SetSockAddrToRlocPeerAddrTo(*aDestination);
745 }
746
747 SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));
748
749 LogInfo("Sent %s for target %s", UriToString<kUriAddressError>(), aTarget.ToString().AsCString());
750
751 exit:
752
753 if (error != kErrorNone)
754 {
755 FreeMessage(message);
756 LogInfo("Failed to send %s: %s", UriToString<kUriAddressError>(), ErrorToString(error));
757 }
758 }
759
760 #endif // OPENTHREAD_FTD
761
762 template <>
HandleTmf(Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)763 void AddressResolver::HandleTmf<kUriAddressError>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
764 {
765 Error error = kErrorNone;
766 Ip6::Address target;
767 Ip6::InterfaceIdentifier meshLocalIid;
768 #if OPENTHREAD_FTD
769 Mac::ExtAddress extAddr;
770 Ip6::Address destination;
771 #endif
772
773 VerifyOrExit(aMessage.IsPostRequest(), error = kErrorDrop);
774
775 LogInfo("Received %s", UriToString<kUriAddressError>());
776
777 if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast())
778 {
779 if (Get<Tmf::Agent>().SendEmptyAck(aMessage, aMessageInfo) == kErrorNone)
780 {
781 LogInfo("Sent %s ack", UriToString<kUriAddressError>());
782 }
783 }
784
785 SuccessOrExit(error = Tlv::Find<ThreadTargetTlv>(aMessage, target));
786 SuccessOrExit(error = Tlv::Find<ThreadMeshLocalEidTlv>(aMessage, meshLocalIid));
787
788 for (Ip6::Netif::UnicastAddress &address : Get<ThreadNetif>().GetUnicastAddresses())
789 {
790 if (address.GetAddress() == target && Get<Mle::MleRouter>().GetMeshLocal64().GetIid() != meshLocalIid)
791 {
792 // Target EID matches address and Mesh Local EID differs
793 #if OPENTHREAD_CONFIG_DUA_ENABLE
794 if (Get<BackboneRouter::Leader>().IsDomainUnicast(address.GetAddress()))
795 {
796 Get<DuaManager>().NotifyDuplicateDomainUnicastAddress();
797 }
798 else
799 #endif
800 {
801 Get<ThreadNetif>().RemoveUnicastAddress(address);
802 }
803
804 ExitNow();
805 }
806 }
807
808 #if OPENTHREAD_FTD
809 meshLocalIid.ConvertToExtAddress(extAddr);
810
811 for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid))
812 {
813 if (child.IsFullThreadDevice())
814 {
815 continue;
816 }
817
818 if (child.GetExtAddress() != extAddr)
819 {
820 // Mesh Local EID differs, so check whether Target EID
821 // matches a child address and if so remove it.
822
823 if (child.RemoveIp6Address(target) == kErrorNone)
824 {
825 SuccessOrExit(error = Get<Mle::Mle>().GetLocatorAddress(destination, child.GetRloc16()));
826
827 SendAddressError(target, meshLocalIid, &destination);
828 ExitNow();
829 }
830 }
831 }
832 #endif // OPENTHREAD_FTD
833
834 exit:
835
836 if (error != kErrorNone)
837 {
838 LogWarn("Error %s when processing %s", ErrorToString(error), UriToString<kUriAddressError>());
839 }
840 }
841
842 #if OPENTHREAD_FTD
843
844 template <>
HandleTmf(Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)845 void AddressResolver::HandleTmf<kUriAddressQuery>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
846 {
847 Ip6::Address target;
848 uint32_t lastTransactionTime;
849
850 VerifyOrExit(aMessage.IsNonConfirmablePostRequest());
851
852 SuccessOrExit(Tlv::Find<ThreadTargetTlv>(aMessage, target));
853
854 LogInfo("Received %s from 0x%04x for target %s", UriToString<kUriAddressQuery>(),
855 aMessageInfo.GetPeerAddr().GetIid().GetLocator(), target.ToString().AsCString());
856
857 if (Get<ThreadNetif>().HasUnicastAddress(target))
858 {
859 SendAddressQueryResponse(target, Get<Mle::MleRouter>().GetMeshLocal64().GetIid(), nullptr,
860 aMessageInfo.GetPeerAddr());
861 ExitNow();
862 }
863
864 for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid))
865 {
866 if (child.IsFullThreadDevice() || child.GetLinkFailures() >= Mle::kFailedChildTransmissions)
867 {
868 continue;
869 }
870
871 if (child.HasIp6Address(target))
872 {
873 lastTransactionTime = Time::MsecToSec(TimerMilli::GetNow() - child.GetLastHeard());
874 SendAddressQueryResponse(target, child.GetMeshLocalIid(), &lastTransactionTime, aMessageInfo.GetPeerAddr());
875 ExitNow();
876 }
877 }
878
879 #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE
880 if (Get<BackboneRouter::Local>().IsPrimary() && Get<BackboneRouter::Leader>().IsDomainUnicast(target))
881 {
882 uint16_t srcRloc16 = aMessageInfo.GetPeerAddr().GetIid().GetLocator();
883
884 LogInfo("Extending %s to %s for target %s rloc16=%04x", UriToString<kUriAddressQuery>(),
885 UriToString<kUriBackboneQuery>(), target.ToString().AsCString(), srcRloc16);
886 IgnoreError(Get<BackboneRouter::Manager>().SendBackboneQuery(target, srcRloc16));
887 }
888 #endif
889
890 exit:
891 return;
892 }
893
SendAddressQueryResponse(const Ip6::Address & aTarget,const Ip6::InterfaceIdentifier & aMeshLocalIid,const uint32_t * aLastTransactionTime,const Ip6::Address & aDestination)894 void AddressResolver::SendAddressQueryResponse(const Ip6::Address &aTarget,
895 const Ip6::InterfaceIdentifier &aMeshLocalIid,
896 const uint32_t *aLastTransactionTime,
897 const Ip6::Address &aDestination)
898 {
899 Error error;
900 Coap::Message *message;
901 Tmf::MessageInfo messageInfo(GetInstance());
902
903 message = Get<Tmf::Agent>().NewPriorityConfirmablePostMessage(kUriAddressNotify);
904 VerifyOrExit(message != nullptr, error = kErrorNoBufs);
905
906 SuccessOrExit(error = Tlv::Append<ThreadTargetTlv>(*message, aTarget));
907 SuccessOrExit(error = Tlv::Append<ThreadMeshLocalEidTlv>(*message, aMeshLocalIid));
908 SuccessOrExit(error = Tlv::Append<ThreadRloc16Tlv>(*message, Get<Mle::MleRouter>().GetRloc16()));
909
910 if (aLastTransactionTime != nullptr)
911 {
912 SuccessOrExit(error = Tlv::Append<ThreadLastTransactionTimeTlv>(*message, *aLastTransactionTime));
913 }
914
915 messageInfo.SetSockAddrToRlocPeerAddrTo(aDestination);
916
917 SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));
918
919 LogInfo("Sent %s for target %s", UriToString<kUriAddressNotify>(), aTarget.ToString().AsCString());
920
921 exit:
922 FreeMessageOnError(message, error);
923 }
924
HandleTimeTick(void)925 void AddressResolver::HandleTimeTick(void)
926 {
927 bool continueRxingTicks = false;
928
929 for (CacheEntry &entry : mSnoopedList)
930 {
931 if (entry.IsTimeoutZero())
932 {
933 continue;
934 }
935
936 continueRxingTicks = true;
937 entry.DecrementTimeout();
938
939 if (entry.IsTimeoutZero())
940 {
941 entry.SetCanEvict(true);
942 }
943 }
944
945 for (CacheEntry &entry : mQueryRetryList)
946 {
947 if (entry.IsTimeoutZero())
948 {
949 continue;
950 }
951
952 continueRxingTicks = true;
953 entry.DecrementTimeout();
954
955 if (entry.IsTimeoutZero())
956 {
957 if (!entry.IsInRampDown())
958 {
959 entry.SetRampDown(true);
960 entry.SetTimeout(kAddressQueryMaxRetryDelay);
961
962 LogInfo("Starting ramp down of %s retry-delay:%u", entry.GetTarget().ToString().AsCString(),
963 entry.GetTimeout());
964 }
965 else
966 {
967 uint16_t retryDelay = entry.GetRetryDelay();
968
969 retryDelay >>= 1;
970 retryDelay = Max(retryDelay, kAddressQueryInitialRetryDelay);
971
972 if (retryDelay != entry.GetRetryDelay())
973 {
974 entry.SetRetryDelay(retryDelay);
975 entry.SetTimeout(kAddressQueryMaxRetryDelay);
976
977 LogInfo("Ramping down %s retry-delay:%u", entry.GetTarget().ToString().AsCString(), retryDelay);
978 }
979 }
980 }
981 }
982
983 {
984 CacheEntry *prev = nullptr;
985 CacheEntry *entry;
986
987 while ((entry = GetEntryAfter(prev, mQueryList)) != nullptr)
988 {
989 OT_ASSERT(!entry->IsTimeoutZero());
990
991 continueRxingTicks = true;
992 entry->DecrementTimeout();
993
994 if (entry->IsTimeoutZero())
995 {
996 uint16_t retryDelay = entry->GetRetryDelay();
997
998 entry->SetTimeout(retryDelay);
999
1000 retryDelay <<= 1;
1001 retryDelay = Min(retryDelay, kAddressQueryMaxRetryDelay);
1002
1003 entry->SetRetryDelay(retryDelay);
1004 entry->SetCanEvict(true);
1005 entry->SetRampDown(false);
1006
1007 // Move the entry from `mQueryList` to `mQueryRetryList`
1008 mQueryList.PopAfter(prev);
1009 mQueryRetryList.Push(*entry);
1010
1011 LogInfo("Timed out waiting for %s for %s, retry: %d", UriToString<kUriAddressNotify>(),
1012 entry->GetTarget().ToString().AsCString(), entry->GetTimeout());
1013
1014 Get<MeshForwarder>().HandleResolved(entry->GetTarget(), kErrorDrop);
1015
1016 // When the entry is removed from `mQueryList`
1017 // we keep the `prev` pointer same as before.
1018 }
1019 else
1020 {
1021 prev = entry;
1022 }
1023 }
1024 }
1025
1026 if (!continueRxingTicks)
1027 {
1028 Get<TimeTicker>().UnregisterReceiver(TimeTicker::kAddressResolver);
1029 }
1030 }
1031
HandleIcmpReceive(void * aContext,otMessage * aMessage,const otMessageInfo * aMessageInfo,const otIcmp6Header * aIcmpHeader)1032 void AddressResolver::HandleIcmpReceive(void *aContext,
1033 otMessage *aMessage,
1034 const otMessageInfo *aMessageInfo,
1035 const otIcmp6Header *aIcmpHeader)
1036 {
1037 OT_UNUSED_VARIABLE(aMessageInfo);
1038
1039 static_cast<AddressResolver *>(aContext)->HandleIcmpReceive(AsCoreType(aMessage), AsCoreType(aMessageInfo),
1040 AsCoreType(aIcmpHeader));
1041 }
1042
HandleIcmpReceive(Message & aMessage,const Ip6::MessageInfo & aMessageInfo,const Ip6::Icmp::Header & aIcmpHeader)1043 void AddressResolver::HandleIcmpReceive(Message &aMessage,
1044 const Ip6::MessageInfo &aMessageInfo,
1045 const Ip6::Icmp::Header &aIcmpHeader)
1046 {
1047 OT_UNUSED_VARIABLE(aMessageInfo);
1048
1049 Ip6::Header ip6Header;
1050
1051 VerifyOrExit(aIcmpHeader.GetType() == Ip6::Icmp::Header::kTypeDstUnreach);
1052 VerifyOrExit(aIcmpHeader.GetCode() == Ip6::Icmp::Header::kCodeDstUnreachNoRoute);
1053 SuccessOrExit(aMessage.Read(aMessage.GetOffset(), ip6Header));
1054
1055 Remove(ip6Header.GetDestination(), kReasonReceivedIcmpDstUnreachNoRoute);
1056
1057 exit:
1058 return;
1059 }
1060
1061 // LCOV_EXCL_START
1062
1063 #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_INFO)
1064
LogCacheEntryChange(EntryChange aChange,Reason aReason,const CacheEntry & aEntry,CacheEntryList * aList)1065 void AddressResolver::LogCacheEntryChange(EntryChange aChange,
1066 Reason aReason,
1067 const CacheEntry &aEntry,
1068 CacheEntryList *aList)
1069 {
1070 static const char *const kChangeStrings[] = {
1071 "added", // (0) kEntryAdded
1072 "updated", // (1) kEntryUpdated
1073 "removed", // (2) kEntryRemoved
1074 };
1075
1076 static const char *const kReasonStrings[] = {
1077 "query request", // (0) kReasonQueryRequest
1078 "snoop", // (1) kReasonSnoop
1079 "rx notification", // (2) kReasonReceivedNotification
1080 "removing router id", // (3) kReasonRemovingRouterId
1081 "removing rloc16", // (4) kReasonRemovingRloc16
1082 "rx icmp no route", // (5) kReasonReceivedIcmpDstUnreachNoRoute
1083 "evicting for new entry", // (6) kReasonEvictingForNewEntry
1084 "removing eid", // (7) kReasonRemovingEid
1085 };
1086
1087 static_assert(0 == kEntryAdded, "kEntryAdded value is incorrect");
1088 static_assert(1 == kEntryUpdated, "kEntryUpdated value is incorrect");
1089 static_assert(2 == kEntryRemoved, "kEntryRemoved value is incorrect");
1090
1091 static_assert(0 == kReasonQueryRequest, "kReasonQueryRequest value is incorrect");
1092 static_assert(1 == kReasonSnoop, "kReasonSnoop value is incorrect");
1093 static_assert(2 == kReasonReceivedNotification, "kReasonReceivedNotification value is incorrect");
1094 static_assert(3 == kReasonRemovingRouterId, "kReasonRemovingRouterId value is incorrect");
1095 static_assert(4 == kReasonRemovingRloc16, "kReasonRemovingRloc16 value is incorrect");
1096 static_assert(5 == kReasonReceivedIcmpDstUnreachNoRoute, "kReasonReceivedIcmpDstUnreachNoRoute value is incorrect");
1097 static_assert(6 == kReasonEvictingForNewEntry, "kReasonEvictingForNewEntry value is incorrect");
1098 static_assert(7 == kReasonRemovingEid, "kReasonRemovingEid value is incorrect");
1099
1100 LogInfo("Cache entry %s: %s, 0x%04x%s%s - %s", kChangeStrings[aChange], aEntry.GetTarget().ToString().AsCString(),
1101 aEntry.GetRloc16(), (aList == nullptr) ? "" : ", list:", ListToString(aList), kReasonStrings[aReason]);
1102 }
1103
ListToString(const CacheEntryList * aList) const1104 const char *AddressResolver::ListToString(const CacheEntryList *aList) const
1105 {
1106 const char *str = "";
1107
1108 VerifyOrExit(aList != &mCachedList, str = "cached");
1109 VerifyOrExit(aList != &mSnoopedList, str = "snooped");
1110 VerifyOrExit(aList != &mQueryList, str = "query");
1111 VerifyOrExit(aList != &mQueryRetryList, str = "query-retry");
1112
1113 exit:
1114 return str;
1115 }
1116
1117 #else // #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_INFO)
1118
LogCacheEntryChange(EntryChange,Reason,const CacheEntry &,CacheEntryList *)1119 void AddressResolver::LogCacheEntryChange(EntryChange, Reason, const CacheEntry &, CacheEntryList *) {}
1120
1121 #endif // #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_NOTE)
1122
1123 // LCOV_EXCL_STOP
1124
1125 //---------------------------------------------------------------------------------------------------------------------
1126 // AddressResolver::CacheEntry
1127
Init(Instance & aInstance)1128 void AddressResolver::CacheEntry::Init(Instance &aInstance)
1129 {
1130 InstanceLocatorInit::Init(aInstance);
1131 mNextIndex = kNoNextIndex;
1132 }
1133
GetNext(void)1134 AddressResolver::CacheEntry *AddressResolver::CacheEntry::GetNext(void)
1135 {
1136 return (mNextIndex == kNoNextIndex) ? nullptr : &Get<AddressResolver>().GetCacheEntryPool().GetEntryAt(mNextIndex);
1137 }
1138
GetNext(void) const1139 const AddressResolver::CacheEntry *AddressResolver::CacheEntry::GetNext(void) const
1140 {
1141 return (mNextIndex == kNoNextIndex) ? nullptr : &Get<AddressResolver>().GetCacheEntryPool().GetEntryAt(mNextIndex);
1142 }
1143
SetNext(CacheEntry * aEntry)1144 void AddressResolver::CacheEntry::SetNext(CacheEntry *aEntry)
1145 {
1146 VerifyOrExit(aEntry != nullptr, mNextIndex = kNoNextIndex);
1147 mNextIndex = Get<AddressResolver>().GetCacheEntryPool().GetIndexOf(*aEntry);
1148
1149 exit:
1150 return;
1151 }
1152
1153 #endif // OPENTHREAD_FTD
1154
1155 } // namespace ot
1156