This commit removes all Domain Prefix configuration and management logic
from the OpenThread stack, CLI commands, unit tests, and GRL harness
THCI wrapper.
- Removed public Backbone Router Domain Prefix APIs.
- Removed Domain Prefix flag ('mDp') and 'D' flag parser/formatter
from core network data types, Spinel, and CLI.
- Cleaned up local Backbone Router and Leader logic to exclude Domain
Prefix configuration, tracking, and events.
- Updated RoutingManager prefix advertisement (RIO) to exclude
special handling for Domain Prefix.
- Updated CLI documentation to remove Domain Prefix references.
- Removed domain prefix helper methods from python test certification
scripts.
- Removed auto-addition of default domain prefix and D flag support
from GRL harness OpenThread.py.
This commit updates `Name::LabelIterator::ReadLabel()` to explicitly
check that the read label from the message does not contain any embedded
`kNullChar` (`\0`) characters. It uses `StringLength()` to verify that
the length of the string matches the expected label length. If a null
character is found before the end of the label, `kErrorParse` is
returned to prevent potential string truncation issues or
misinterpretation of the label name.
This broader check replaces a recent fix in `PtrRecord::ReadPtrName()`
from #13183 which only verified that the first label was not empty
or malformed by checking for a single-character label with a null
byte. By enforcing this validation centrally at the `ReadLabel()`
level, we now ensure that labels of any length are properly
protected against embedded null characters across all DNS record
types.
This commit updates the codebase to use the `Icmp6Header` type
directly, replacing the nested `Ip6::Icmp::Header` definition.
This change aligns the ICMPv6 header type definition with the
conventions used for other network protocol headers and simplifies
type references across the network, border router, and utility
modules.
This commit updates the codebase to use the `Icmp4Header` type directly,
replacing the nested `Ip4::Icmp::Header` type. The empty `Ip4::Icmp`
wrapper class is removed to simplify the header definition. This change
aligns the ICMPv4 header structure with the flat naming conventions used
for other IP headers (e.g., `Ip6::Icmp6Header`, `Ip6::UpdHeader`).
`PtrRecord::ReadPtrName()` reads a PTR target's first label with
`Name::ReadLabel()`, which performs no emptiness check. A response whose
first label is a single NUL byte (wire `01 00`) is stored as an empty
C-string and cached by the browse cache as a service instance. When the
cache later builds a known-answer question, it calls
`Name::AppendLabel("")`, which returns `kErrorInvalidArgs`; the
surrounding `SuccessOrAssert()` turns that into an abort. A single
unauthenticated link-local mDNS response thus crashes any node with an
active browser.
Reject an empty first label in `ReadPtrName()` so the record is dropped
on receive and never cached. This matches the `Name::ValidateLabel`
checks already applied on the registration and resolver paths, and makes
the "ReadPtrName() validates that PTR record is well-formed" comment at
the call site accurate.
Add a regression test that delivers a PTR response with a single
NUL-byte instance label and verifies no result is reported and the
browser keeps querying without the malformed entry.
This commit updates the codebase to use `TcpHeader` and `UdpHeader` types
directly, instead of the nested `Tcp::Header` and `Udp::Header` types.
The `TcpHeader` and `UdpHeader` classes are already defined in
`ip6_headers.hpp`. This change reduces dependencies on the `Tcp` and
`Udp` class definitions, which is particularly useful when TCP
is disabled in the build configuration, avoiding the need to include
their respective class headers just for the header definitions.
This commit renames several methods in `Ip6::Address`,
`Ip6::InterfaceIdentifier`, `Ip6::Prefix`, and `Ip4::Address` that
fully initialize the object from `Set...()` to `Init...()`.
This creates a clear semantic distinction in the API:
- `Init...()`: Fully (re-)initializing the object.
- `Set...()`: Modifies a specific property or a sub-component of
the object (e.g., `SetPrefix()`, `SetLocator()`,
`SetSubnetId()`).
Some examples of renames include:
- `SetFromExtAddress()` -> `InitFromExtAddress()`
- `SetToLocator()` -> `InitAsLocator()`
- `SetToLinkLocalAddress()` -> `InitAsLinkLocalAddress()`
- `SetToRoutingLocator()` -> `InitAsRoutingLocator()`
- `SetToAnycastLocator()` -> `InitAsAnycastLocator()`
- `SetToIp4Mapped()` -> `InitAsIp4Mapped()`
All calls to these methods across the codebase have been updated
to reflect the new names.
This commit fixes a frequent unit test flake in ot-test-trickle_timer
under the TestTrickleTimerMinMaxIntervalChange test case.
The test case starts the trickle timer with Imin = 2000 and
Imax = 2000. The random time t (mTimeInInterval) is chosen in
[1000, 2000), so t can range up to 1999.
When t randomly evaluates to 1999, t + 1 becomes 2000. Calling
timer.SetIntervalMax(2000) triggers an early-exit optimization
in TrickleTimer::SetIntervalMax because mIntervalMax is already 2000,
leaving the scheduled timer's fire time unchanged. The test then
crashes on the assertion expecting the fire time to have changed.
This is resolved by setting the new interval max to
Min(t + 1, interval - 1). This ensures that the requested value is
strictly less than 2000 even when t = 1999, successfully triggering
the interval shortening and rescheduling logic tested by this case.
This commit updates the DHCPv6 Prefix Delegation (PD) client to
comply with RFC 9915, which obsoletes the Server Unicast option
(Option 12) and the UseMulticast status code.
Changes:
- Removed `mServerAddress` and `ProcessServerUnicastOption()` from
`Dhcp6PdClient`.
- Modified `Dhcp6PdClient::SendMessage` to always transmit via
multicast to `ff02::1:2`.
- Removed `UseMulticast` status code handling in `HandleReply()`.
- Added `otMessageFree` weak stub in simulation platform's
`infra_if.c` to resolve linking errors on simulation radio-only
targets when DHCPv6 PD client is enabled.
- Updated `test_dhcp6_pd_client.cpp` to expect multicast and
removed the obsolete UseMulticast test case.
This commit extends the `BitSet` class with several new
methods:
- `CountElements()`
- `IsSubsetOf()` and `IsSupersetOf()`
- `Complement()`
- `UnionWith()`, `IntersectWith()`, and `SubtractWith()`
- `SetMask()`, `AppendTo()`, and `ReadFrom()` message.
This commit also introduces a new `BitSetUtils` non-template base class
for the `BitSet<kNumBits>` template class. This change helps optimize
code by moving the common implementation logic for various bit
manipulation operations out of the template, reducing template
instantiation overhead.
Per RFC 9664, the UL option is always included in a success response (RCODE=0).
Comment in test_srp_server is updated also to avoid suggesting the opposite.
This commit introduces a new set of template-based APIs for
non-cryptographic random number generation in the `Random::NonCrypto`
namespace. These new methods provide a cleaner, type-safe, and more
robust interface compared to the previous methods.
Key additions:
- `Generate<UintType>()`: Returns a random value of the given
unsigned integer type (`uint8_t`, `uint16_t`, or `uint32_t`).
- `GenerateUpToExcluding<UintType>(aMax)`: Returns a random value in
the range `[0, aMax)`.
- `GenerateFromMinUpToExcluding<UintType>(aMin, aMax)`: Returns a
random value in the range `[aMin, aMax)`.
- `GenerateInClosedRange<UintType>(aMin, aMax)`: Returns a random
value in the closed range `[aMin, aMax]`.
The introduction of `GenerateInClosedRange` is an improvement as it
safely handles ranges up to the maximum value of the integer type
(e.g., `0xffff`) without the risk of overflow.
All call sites across the OpenThread core stack and tests have been
updated to adopt these new APIs. The public `otRandomNonCrypto`
functions are also updated to leverage the new internal methods.
Doxygen documentation is added for all new template methods,
detailing their behavior, including edge cases where the upper bound
is smaller than or equal to the lower bound.
This commit refactors various unit tests to use `constexpr` for
defining constants instead of anonymous `enum` types.
Using `constexpr` is the modern and preferred approach in C++, as it
provides explicit types for constants and improves code clarity and
type safety.
This commit removes all code, configurations, APIs, and tests related
to the OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE feature.
Specifically, the following changes were made:
- Removed DUA ND Proxying Backbone Router configuration option and the
related OPENTHREAD_CONFIG_NDPROXY_TABLE_ENTRY_NUM definition.
- Removed CLI commands: `bbr mgmt dua` and the proactive backbone
notification fake command `/b/ba`.
- Removed NdProxyTable and bbr_manager DUA ND Proxying implementation.
- Removed public/internal APIs for ND Proxying and proactive backbone
notifications.
- Deleted ndproxy_table source files and unit tests.
- Simplified CMake and GN build files to remove deleted targets.
This commit introduces `Message::ReadAndAdvance()` and its template
flavor to the `Message` class. This helper method reads data from a
`Message` at a given `OffsetRange` and advances the `OffsetRange` by
the number of bytes read upon success.
Sequential parsing of structured data (such as TLVs or protocol
headers) is a common pattern across the OpenThread codebase.
Previously, this required two separate calls: one to `Read()` and
another to `AdvanceOffset()`. The new `ReadAndAdvance()` method
consolidates these into a single, safer operation that ensures the
offset is only advanced if the read operation succeeds.
This commit updates numerous call sites across the core stack
(MLE, BBR, DatasetManager, NetworkDiagnostic, DHCPv6, etc.) to use
the new helper, improving code clarity and reducing boilerplate.
This commit enhances the radio URL parsing logic to detect and fail
when unused parameters are provided in the URL. This prevents typos
or unsupported parameters from being silently ignored.
The following changes were made:
- Updated ot::Url::Url to track parameter usage by appending a
trailing '&' delimiter in Init() and replacing it with '\0'
in GetValue() when a parameter is matched. This marks the
parameter as used and removes any limit on the number of
trackable parameters.
- Added a Validate() method to ot::Url::Url to verify that all
parameters in the query string were accessed.
- Refactored ot::Posix::Radio to share a single RadioUrl instance
with SpinelManager, ensuring all components track usage on the
same URL object.
- Integrated Validate() calls in otSysInit() and platformTrelInit()
to perform validation after all platform components have been
initialized.
- Updated Radio::ProcessMaxPowerTable to use a local copy of the
parameter string to avoid premature modification of the URL buffer.
- Adjusted RadioUrl and unit tests to provide sufficient buffer
space for the additional tracking delimiter.
- Added new unit tests in tests/unit/test_url.cpp to verify the
usage tracking and validation logic.
This commit adds validation to ensure that Key ID Mode 0 (implied KEK)
secured frames are only accepted if a KEK is configured. If KEK is not
configured, the frame is rejected.
Specifically:
- Added `mIsKekSet` boolean member variable to `KeyManager` to track
KEK status.
- Implemented `KeyManager::IsKekSet()` to check if a KEK is
configured.
- Enforced a guard in `Mac::ProcessReceiveSecurity()` under
`kKeyIdMode0` to immediately reject incoming frames with
`kErrorSecurity` when the KEK is not configured.
- Added unit test `TestKeyManagerKek()` in `test_pskc.cpp` to
verify that `IsKekSet()` transitions from `false` to `true` as
expected.
This commit fixes an issue where a tasklet could not be successfully
unposted if it was already scheduled for execution in the current
event loop iteration.
Previously, `Scheduler::ProcessQueuedTasklets()` copied and cleared the
queued tasklets before running them. If a running tasklet called
`Unpost()` on another tasklet that was also in the copied list, the
unpost operation would fail to remove it because it only checked the
main queue.
To address this, the `Scheduler` now explicitly maintains two separate
queues: `mPostedQueue` and `mRuningQueue`. The `Tasklet::Unpost()`
method is updated to remove the target tasklet from both queues,
ensuring it is correctly dequeued even if it is pending in the running
list.
The queue logic is encapsulated into a nested `Queue` class to manage
the circular singly linked-list operations cleanly. Additionally, unit
tests are expanded to cover scenarios where tasklets post or unpost
other tasklets during execution.
This commit simplifies the `MulticastListenersTable` by replacing the
custom heap-based sorting logic with a standard `Array` and integrating
an internal `TimerMilli` (`mTimer`) to handle entry expirations.
Previously, the table maintained a min-heap based on expiration times
(`FixHeap`, `SiftHeapElemDown`, `SiftHeapElemUp`) and required
external calls to `Expire()` every second. The new implementation
uses `mListeners.FindMatching()` and `mListeners.RemoveAllMatching()`,
significantly reducing code complexity and maintenance overhead.
The unit tests in `test_multicast_listeners_table.cpp` are also updated
to reflect the simplified model
This commit introduces `AnswerBuilder` class to track and manage
Network Diagnostic answer messages. This class is used when the
response to a query requires multiple CoAP answer messages. It
automatically manages the inclusion of the Query ID and the Answer
TLVs(providing message indexing and "more-to-follow" flags) in each
allocated answer message, while maintaining all answer messages in a
queue. The `NetworkDiagnostic::Server` is updated to use the
`AnswerBuilder`, simplifying the logic for preparing and sending
answers.
The `AnswerBuilder` class is added in a new header file
`network_diagnostic_types.hpp` to allow for its reuse by other
modules in the future.
Due to a state retention issue in the unit test platform, TCAT tests were passing in ways they should not.
Now with the new settings/flash clearing per #12875 applied, these tests were failing.
This fixes TCAT unit tests to pass again and better express the expected behavior also.
Issue: state was retained between OT instances in the unit test platform, across tests.
This commit adds settings and flash clearing as part of testInitInstance().
This commit introduces `testResetInstance()` in the unit test platform
layer to finalize an existing `ot::Instance` and re-initialize it
using the same underlying memory buffer, simulating a device reset.
This commit also updates `test_routing_manager.cpp` to use this new
function to streamline the test implementation.
OpenThread's NAT64 translator assumed a fixed IPv4 header length of 20
bytes, which caused incorrect parsing and translation of IPv4 packets
containing options (IHL > 5).
Specifically, if an IPv4 packet with options was received:
1. The transport header was read from a fixed 20-byte offset, leading
to corruption of transport layer fields (e.g., UDP ports).
2. Only 20 bytes were removed from the message, leaving the IPv4
options at the beginning of the translated IPv6 payload.
3. Mandatory security checks for source route options were bypassed.
This commit fixes these issues by:
- Updating Ip4::Header to validate IHL and provide the actual header
length.
- Using the actual header length for transport header parsing and
IPv4 header removal in the NAT64 translator.
- Implementing a check to discard packets with LSRR or SSRR options
as required by RFC 7915.
A new Nexus regression test is added to verify the fix.
This commit refactors the `OmrPrefixManager` to decouple it from the main
`RoutingManager` policy evaluation cycle. This allows the OMR prefix to
be managed independently and published faster into the Network Data.
Previously, `OmrPrefixManager` relied on its `Evaluate()` method being
called during the main `RoutingManager::EvaluateRoutingPolicy()` cycle.
This meant it had to wait for other components to be ready — such as
sending Router Solicitations to discover other routers on the Adjacent
Infrastructure Link (AIL)—before taking action.
With this change, `OmrPrefixManager` operates independently. It can
evaluate its state as soon as the Border Router function is enabled and
`Start()` is called.
Additional improvements supporting this independent operation include:
- Replaces the `mIsLocalAddedInNetData` boolean with a `LocalPrefixState`
enum (`kNotAdded`, `kToAdd`, `kAdded`) to manage addition state and
support delayed updates.
- Introduces a random delay (`kMinDelayToAdd` to `kMaxDelayToAdd`)
before adding a self-generated OMR prefix to Network Data. This gives
the network time to settle, allowing other BRs or the `PdPrefixManager`
time to establish a prefix.
- Implements a retry mechanism with jitter for Network Data addition
failures, rather than silently ignoring them.
- Refactors `PdPrefixManager` to batch state changes via an `mEvents`
bitmask and process them through `mEventTask`. Changes are now handled
explicitly by `OmrPrefixManager::HandlePdPrefixManagerEvent()`, further
reducing unnecessary main routing policy evaluations.
This commit removes the `Tlv::ReadTlvValue()` method which is no
longer needed or used. The same functionality is provided through
the `Tlv::Info` class, specifically using its `ParseFrom()` and
`ReadValue()` methods. This approach is safer and provides more
comprehensive information about the parsed TLV.
The unit tests are also updated to replace the usage of the removed
method with the new `Tlv::Info` based approach.
This commit provides the platform-level implementation for the
instance-aware logging API `otPlatLogOutput()`. This API is used when
`OPENTHREAD_CONFIG_LOG_INSTANCE_AWARE_API_ENABLE` is enabled, allowing
the platform to receive the `otInstance` pointer with each log line.
The new API is implemented across:
- The simulation platform logging.
- The POSIX platform using `syslog()`.
- The NCP base to route logs to the NCP host.
- The CLI logging module.
- Unit tests and mock platforms.
The `OPENTHREAD_CONFIG_LOG_INSTANCE_AWARE_API_ENABLE` configuration is
also enabled for Toranj simulations to support multi-instance log
testing.
This commit adds `CloneMessage()`, `CloneMessageWithoutFooter()`,
and `CloneMessageWithout<Footer>()` methods to the `MessageAllocator`
class. These methods simplify creating copies of messages by
automatically applying the correct `kReservedHeader` size. It also
updates existing code in `CoapBase`, `Dns::Client`, `Sntp::Client`,
and `Mle` to utilize these new methods.
Additionally, this commit updates the `Clone()` method in `Message`
to be a template method, accepting a `CloneMode` to specify whether
the cloned message should retain the reserved header or have no
reserved header. The documentation for the clone methods has also
been updated to clarify which message fields are copied during the
cloning process.
Thread spec doesn't define the order of TLVs in the dataset, so that
we can't call `memcmp` to compare two dataset. If we convert the
dataset to otOperationalDataset and then compare each value of
otOperationalDataset, we will met an issue if the new Thread spec
defines new TLVs in the dataset in the future.
This commit add a new dataset API `otDatasetTlvsCompare` to check
whether two dataset contain the exact same set of TLVs (same types and
values).
This commit introduces the `MessageAllocator` template class using the
CRTP pattern to provide a unified implementation of the `NewMessage()`
methods. It standardizes the reserved header sizes for different
message types within `ReservedHeaderSize`. This removes boilerplate
code and redundant `NewMessage()` method implementations across the
`Ip6`, `Icmp`, `Udp`, `Udp::Socket`, and `CoapBase` classes.
This commit updates `tests/unit/test_tcat.cpp` to properly handle the
`Error` return value from `NetworkName::Set()`, resolving compiler
warnings about unhandled return types.
In `TestInitInstanceTcat()`, `IgnoreError()` is used when setting
default test values since `NetworkName::Set()` returns `kErrorNone`
or `kErrorAlready` when the same name is set again.
This commit updates the following `otPlatInfraIf` platform APIs to
include an `otInstance *` as their first parameter:
- `otPlatInfraIfHasAddress()`
- `otPlatInfraIfSendIcmp6Nd()`
- `otPlatInfraIfDiscoverNat64Prefix()`
Other APIs under `otPlatInfraIf` already follow this pattern. Passing
the `otInstance` pointer is the required standard for all platform
and public APIs; however, it was missed during the initial design of
these specific APIs.
While missing this parameter is often not a blocker on platforms using
a single OpenThread instance, it has become a blocker for simulations,
especially when multiple Border Routers are emulated in the same
simulation setup.
This change introduces a compatibility break for existing platform
implementations, however, it is necessary to support new use cases
(simulation of BRs). It also helps ensure consistent API design
across the stack.
This commit improves the robustness of CoAP option parsing by adding
rigorous validation checks to prevent potential overflows and null
pointer dereferences.
Summary of changes:
1. In 'ReadExtendedOptionField()', added an overflow check when
calculating extended lengths for 2-byte extensions. It now returns
'kErrorParse' if the value would exceed the 16-bit range.
2. In 'ReadBlockOptionValues()', added a check to ensure the block
option exists before accessing it. This prevents a crash when
'GetOption()' returns null.
3. In 'ReadBlockOptionValues()', added length validation to ensure the
option value does not exceed the local buffer size (5 bytes) before
copying.
4. Added a new unit test 'test_coap_overflow' to verify these validation
checks and ensure they correctly handle malformed or missing options.
This commit introduces a maximum recursion depth limit for 6LoWPAN
decompression to prevent potential stack exhaustion from maliciously
crafted frames with deep IPv6-in-IPv6 encapsulation.
- Added a private constant kMaxRecursionDepth in the Lowpan
class to define the maximum allowed recursion depth.
- Updated Lowpan::Decompress() to track and validate the current
recursion depth, returning kErrorParse if the limit is exceeded.
- Added a new unit test TestLowpanDecompressRecursion in
tests/unit/test_lowpan.cpp to verify the recursion limit and
ensure it correctly handles both excessive and legitimate
encapsulation levels.
Updates the TCAT class public methods for doing Commissioner
authorization checks and clarifies the code, with minor updates to
PSKc cases handling.
Unit tests are added for checking Commissioner authorization. To do
these checks, a new test class UnitTester is added which has access to
private members of the TcatAgent class. Validation/mock functions are
added in the test code to keep the unit tests readable.
Also reverts the CommCert4 fix that was made in #12151.
For more background information see JIRA BHC-766.
This commit updates the object pool implementation to support dynamically
configured pool sizes without penalizing the memory footprint of
existing static usages.
A new `PoolBase` class is introduced to encapsulate the core linked-list
management logic (`Allocate()` and `Free()`), relying on a shared
`mFreeList`.
The existing `Pool` class is updated to inherit from `PoolBase`. It
retains its statically allocated `mPool` array, ensuring zero code-size
or RAM penalty for current users of fixed-size pools.
A new `ConfigPool` class is added, also inheriting from `PoolBase`.
This class allows a pool to be initialized at run-time with an
externally provided memory buffer (`mEntryArray`) and size
(`mNumEntries`). This enables future use cases where memory allocation
for pools can be provided dynamically by the system integrator.
This commit also includes unit tests for `ConfigPool` to verify its
allocation, deallocation, and initialization behavior.
This commit simplifies multicast address management within `Netif` by
merging the `ExternalMulticastAddress` class directly into the base
`MulticastAddress` class. The `otNetifMulticastAddress` structure is
updated to include `mAddressOrigin` and an opaque `mData` field.
The `mData` field is utilized to track the Multicast Listener
Registration (MLR) state when the `OPENTHREAD_CONFIG_MLR_ENABLE`
feature is enabled.
By consolidating these types, we eliminate the need for separate
internal and external multicast address iteration logic in
`MlrManager`, streamlining MLR subscription checks and updates.
Additionally, this provides a more unified way to track the origin of
multicast addresses natively.
This commit adds `MatchesKey()` method to `Dns::TxtEntry` class to
check if the entry's key matches a given key string using a
case-insensitive string comparison.
The new method properly handles the case where the entry's key is
`nullptr` (which can happen when the key is longer than the
recommended max length). It simplifies the TXT entry parsing logic in
`BorderAgent` and `Trel::PeerDiscoverer`.
The unit tests for `Dns::TxtEntry` are also updated to verify the new
method.
This commit enhances the `Message::Clone()` method to support a custom
configuration. This allows callers to specify a different length and
reserved header size for the cloned message via the new overload
`Clone(uint16_t aLength, uint16_t aReserveHeader)`.
The existing `Clone()` overloads have been updated to utilize this new
configuration mechanism. Additionally, `Coap::Message::Clone()`
methods are updated to align with these changes.
A new unit test `TestCloning()` is added to `test_message.cpp` to
verify the behavior of `Clone()` with various configurations.
This commit implements otPlatDnssdStartSrvResolver and
otPlatDnssdStopSrvResolver to support service discovery on NCP.
This commit contains these changes:
* Add new spinel property for starting / stopping service resolver
* Implement encoding/decoding of the new property
* Add unit test for encoding/decoding
* Implement ncp version of dnssd platform API
otPlatDnssdStartSrvResolver and otPlatDnssdStopSrvResolver
* Add property handler to get resolver result on NCP side
* Add unit test to verify that the resolver callback is correctly
invoked after getting resolver result.
This commit updates `tests/unit/test_seeker.cpp` to use `ot::Array`
instead of C-style arrays with initializer lists for passing expected
selection orders in `CheckSelection()`.
The previous approach of passing initializer lists to a function
expecting a reference to a constant array caused compilation issues
on certain toolchains due to template deduction rules or temporary
object handling. By explicitly populating an `ot::Array` and passing
it, the test code becomes more portable and robust across different
compilers.
This commit introduces the `ScanResult` class, which inherits from
`otActiveScanResult`. This new class provides C++ idiomatic getter
methods that return core OpenThread types (e.g., `ExtAddress`,
`ExtendedPanId`, `NetworkName`) instead of raw C structures.
The logic for parsing a received Beacon frame and populating the
result fields is moved into `ScanResult::PopulateFromBeacon()`.
This centralizes the parsing logic and allows it to be reused
across different modules.
Consequently, `Mac`, `DiscoverScanner`, `Seeker`, and
`PanIdQueryServer` are updated to utilize `ScanResult`. The `Mac`
class is also updated to use the `Callback` template for the active
scan handler, replacing the previous raw function pointer and context.
This commit updates `Seeker` to use `MessageBackedArray` for storing
discovered candidates. This moves candidate storage from statically
allocated RAM in the `Seeker` instance to a `Message` buffer,
reducing the resident memory footprint.
The connection logic is enhanced to prioritize network diversity. The
`Seeker` now attempts to connect to the most favored candidate of
each unique network (Extended PAN ID) first. After exhausting unique
networks, it proceeds to remaining backup candidates. This improves
the likelihood of finding the correct network quickly in multi-network
environments.
The candidate storage policy is updated to limit entries per network
(defined by `kMaxCandidatesPerNetwork`). When storage is full, the
`Seeker` evicts a redundant entry from a well-represented network to
accommodate new network discoveries.
A detailed unit test `test_seeker` is included to validate candidate
tracking and selection order under various scenarios.
This commit adds `MessageBackedArray`, which implements a dynamic
array backed by a `Message` for data storage.
The new array class supports:
- Pushing new elements to the end.
- Reading and writing elements at specific indices.
- Searching in the array to find matching entries.
- Iterating over array elements.
- Clearing the array and freeing the underlying message.
Unit tests are added in `tests/unit/test_msg_backed_array.cpp` to
verify its functionality.
This commit enhances the DHCPv6 PD prefix conflict detection logic
to check against Route Information Options (RIOs) present in received
Router Advertisements, in addition to the existing check against
on-link prefixes (PIOs).
The conflict detection behavior is event-driven to correctly handle
network propagation delays and valid advertisements:
1. On new prefix assignment (`kPdPrefixChanged`): A strict check is
performed. If the prefix matches any existing RIO from another
router, it is flagged as a conflict.
2. On RA table updates (`kRxRaPrefixTableChanged`): The check focuses
on conflict resolution. Crucially, it ignores new RIO matches
appearing after the prefix has been adopted. This is necessary
because once the BR publishes the PD prefix in Thread Network
Data as the OMR prefix, other BRs will naturally start
advertising it as a RIO to announce reachability.
The unit test `TestDhcp6PdConflict` is updated to verify both the
detection of conflict, its resolution, and that the subsequent RIO
advertisements do not cause a conflict after PD prefix is published
as OMR.
This commit updates `RoutingManager` to detect if a delegated DHCPv6
PD prefix conflicts with any on-link prefix advertised on the
infrastructure link.
This protects against potential DHCPv6 server misbehavior and bugs
where the same prefix might be assigned to multiple requesters.
If a conflict is detected, the delegated PD prefix is marked as
conflicted and is no longer used as the OMR prefix. Instead, we
revert to using the locally generated OMR prefix. If the conflict
is resolved, the delegated PD prefix is used again.
A new unit test `TestDhcp6PdConflict()` is added to verify this
behavior.
This change simplifies the `Coap::Message` implementation and removes
the fragile `HelpData` struct which was used to cache header
information within reserved portion of message.
The `Coap::Msg` class is updated to hold the parsed CoAP header
information (type, code, message ID, token). It now inherits from a
new `HeaderInfo` class which contains the parsed fields. This change
helps to simplify many of the call sites which previously had to parse
the header information themselves.
The key changes are:
- The `HelpData` struct is removed from `Coap::Message`.
- `Coap::Msg` is updated to track parsed header info in `HeaderInfo`.
- `otCoapMessageInit()` and `otCoapMessageInitResponse()` now return an
`otError`.
- Methods are renamed to harmonize their names.
- A new unit test `test_coap_message.cpp` is added to verify the
`Coap::Message` implementation.
A default OTNS platform API function otPlatOtnsStatus() is now
provided that writes the status push to the log always (regardless of
configured log level). This is useful as a default handling for apps
built with -DOT_OTNS=ON, avoiding linker errors while not mandating
each platform to implement the API by itself.
Specifically it enables the Posix CLI app ot-cli to be built with OTNS
support, which is required to run Posix nodes in OTNS and receive the
status-push events via stdout logging.
The logging is emitted from the module named "Otns" so that a
simulator or other tool can easily detect the OTNS format status push
events in the log output.
This change renames `Tlv::ParsedInfo` to `Tlv::Info` to make it more
concise and to better reflect its purpose as a metadata holder for a
TLV in a message.
The member variables of `Tlv::Info` are made private and public
accessor methods are introduced to interact with the object's
contenet. This helps ensure that the internal representation of the
parsed TLV information is not modified directly by external modules.
All existing caller are updated to use the new name and the public
helper getter methods.
The Doxygen comments of `Tlv::Info` are also improved for better
clarity. Unit test `test_tlv` is also updated to validate all the
new methods.
When `OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE` is active, this
change mandates that the vendor name string MUST begin with the "RD:"
prefix. This ensures that reference devices are clearly and
consistently identifiable through network diagnostic queries.
The enforcement is applied at two levels:
- A compile-time `static_assert` is added to validate the default
`OPENTHREAD_CONFIG_NET_DIAG_VENDOR_NAME` at build time. This uses a
new `constexpr` helper utility `CheckConstStringPrefix()`.
- A runtime check is added to `otThreadSetVendorName()`, which will
now return `OT_ERROR_INVALID_ARGS` if an invalid name is provided
on a reference device build.
All related test configurations (`scan-build`, `toranj`, `nexus`) and
CLI tests are updated to reflect this new requirement and validate
it.