This change replaces the `Translator::Result` enum with the standard
`Error` type to report the outcome of a translation attempt. This
simplifies the implementation and aligns it with the rest of the
codebase.
The mapping from the old `Result` to the new `Error` is as follows:
- `kForward` is replaced by `kErrorNone`
- `kDrop` is replaced by `kErrorDrop`
- `kNotTranslated` is replaced by `kErrorAbort`
The `kErrorAbort` return value signals to the caller that no
translation was performed, and it can proceed with normal processing
of the message.
Additionally, the translation methods are renamed for better clarity.
This commit introduces new types `otNetworkDiagData`,
`otNetworkDiagIp6AddrList`, and `otNetworkDiagChildTable` to
represent common data structures within Network Diagnostic TLVs.
These new types replace the previous anonymous structs within the
`otNetworkDiagTlv` union, improving code structure and readability.
The `mNetworkData`, `mIp6AddrList`, `mChildTable`, and
`mChannelPages` fields now use these named types.
This change adds an explicit check for `mState == kStateActive` at the
beginning of the translation functions.
This single check replaces individual validations for a valid IPv4
CIDR and NAT64 prefix. This simplifies the entry logic and fixes a
bug where the `Translator` could continue performing translations
even after it was explicitly disabled via `SetEnabled(false)`.
Additionally, this change fixes a bug in `TranslateToIp6()` where an
IPv4 message would be incorrectly marked as `kForward` when no IPv4
CIDR was configured (`mIp4Cidr.mLength == 0`). The correct behavior
is to drop the packet, so the result is now set to `kDrop`.
This change renames `GetIp6Prefix()` to `GetNat64Prefix()` to more
accurately reflect its purpose and to harmonize its name with the
existing `SetNat64Prefix()` and `ClearNat64Prefix()` methods.
The related getter methods in the header and implementation files are
also reordered for better organization.
This change introduces a new utility function `CountMatchingBits()` to
calculate the number of matching leading bits between two byte
arrays.
This new fn replaces the now-removed `Ip6::Prefix::MatchLength()`.
The previous implementation was specific to the `Ip6::Prefix`
class. The new generic function is placed in `common/bit_utils` and
is used to update `Ip6::Prefix`, `Ip6::Address`, `Ip4::Cidr`, and
`PrefixTlv`.
A new unit test `test_bit_utils` is added with comprehensive tests for
the new function. The existing tests for `CountBitsInMask` are also
moved into this new test file.
This change moves the `kBitsPerByte` constant and the `BitSizeOf()`
and `BytesForBitSize()` macros from `numeric_limits.hpp` to the
more specialized `bit_utils.hpp` header.
This consolidation places common bit-utility definitions into a more
appropriate, dedicated header, improving code organization and
logical grouping. Headers that relied on these definitions are
updated accordingly.
This commit introduces a mechanism within the `RoutingManager` to
track the IPv6 addresses used by the Border Router itself on the
infrastructure interface, particularly when sending Router
Advertisements. This provides visibility for debugging and
monitoring purposes.
A new data structure, `otBorderRoutingIfAddrEntry`, is added to
represent an address and the time elapsed since it was last used as
the source of an RA.
The tracked addresses can be retrieved using the new public API
`otBorderRoutingGetNextIfAddrEntry` or CLI command `br ifaddrs`.
When `OPENTHREAD_CONFIG_NAT64_PORT_TRANSLATION_ENABLE` is enabled,
multiple `Mapping` entries can exist for the same IPv6 and IPv4
addresses, differing only by their protocol ports.
To distinguish between these entries in logs and diagnostics, this
change updates `Mapping::ToString()` to include the source and
translated port numbers in the generated string output.
This commit introduces a new header file, `common/bit_utils.hpp`, to
consolidate bit manipulation utility functions.
These functions were previously located in `common/num_utils.hpp`.
Moving them to a dedicated file improves code organization and
clarity by separating them from general numerical utilities. All
files that used these functions have been updated to include the new
header.
This commit introduces a new Nexus test to validate the functionality
of the NAT64 translator.
The test is divided into two main parts:
- `TestNat64StateChanges`: Verifies the state management of the
translator. It checks that the translator transitions correctly
between `kStateDisabled`, `kStateNotRunning`, and `kStateActive`
when the feature is enabled/disabled or when the IPv4 CIDR and
NAT64 prefix are configured or cleared. This test also confirms
that state change notifications are properly signaled.
- `TestNat64Mapping`: Validates the address mapping and translation
logic. It ensures that address mappings are correctly created for
new IPv6-to-IPv4 traffic, reused for subsequent packets from the
same IPv6 source, and eventually expire and are removed after a
period of inactivity. It also verifies that the mapping table is
cleared when the configured IPv4 CIDR is changed.
This commit moves two global constants, `kBufferSize` and
`kNumBuffers`, into their respective class scopes to improve
encapsulation and avoid potential name conflicts.
The `kBufferSize` constant is moved into the `Buffer` class as
`Buffer::kSize`. As `kBufferSize` is a generic and commonly used
name, this change prevents potential symbol collisions.
Similarly, the `kNumBuffers` constant is moved into the `MessagePool`
class, as it is exclusively used within that class.
All usages of these constants have been updated throughout the
codebase to reflect their new names.
This commit introduces a new common helper class `ExpirationChecker`.
This class is designed to be used as a "matcher" for finding expired
entries in collections like `LinkedList` or `Array`. It encapsulates
a "now" time and provides an `IsExpired()` method to check if a given
time has passed.
This change consolidates duplicated private similar structs that
previously existed in `RoutingManager`, `Mdns`, and
`SrpAdvertisingProxy`, updating all users to the new common
implementation. This simplifies the code by removing redundancy.
This change updates the management of active NAT64 mappings to use an
`OwningList`.
To support this, the `Mapping` struct now inherits from
`InstanceLocatorInit` and includes a new `Free()` method. This method
encapsulates the logic for releasing the associated IPv4 address and
the `Mapping` entry back to their corresponding pools.
This new design simplifies the `Translator` class by removing the
redundant `ReleaseMapping()`, `ReleaseMappings()`, and
`ReleaseExpiredMappings()` methods. All mapping cleanup operations
are now handled by the `OwningList` class (which invokes
`Mapping::Free()` on entries as they are removed).
Adding two extensions:
1. Add an api function to configure a response fallback callback with
`otCoapSetResponseFallback`.
2. Enable fire and forget for NON requests, supporting requests which
do not expect a response.
The mix-in helper classes like `Clearable<T>`, `Equatable<T>`, and
`Unequatable<T>` are intended for CRTP style inheritance, where `T`
is the derived class itself. A mistaken inheritance, such as `class
Foo : public Clearable<Bar>`, can compile successfully but lead to
subtle bugs.
This change enforces the correct CRTP usage at compile time. By making
the constructors of these helper classes `private` and declaring the
derived template class `T` as a `friend`, any incorrect inheritance
will now result in a build failure. This approach correctly detects
such a mistake, even if `Foo` and `Bar` happen to be `friend`s of
each other.
Additionally, `Equatable<T>` is updated to provide both `operator==`
and `operator!=`, removing its dependency on `Unequatable<T>`. This
change allows us to apply the `private` constructor enforcement to
`Equatable<T>` as well.
This commit simplifies the implementation of `SendMessage()` by
changing its parameter from a `Message` reference to an `OwnedPtr`.
The `OwnedPtr` now manages the lifetime of the message, ensuring it is
always freed, whether the translation and send operation succeed or
fail. This change removes the need for a manual tracking flag and an
explicit `Free()` call in the error path, resulting in cleaner and
more robust code.
This change enhances the unit tests for the NAT64 `Translator` to
improve readability. The key improvements include:
- Replaced raw hex dumps of packets with new helper functions that
parse and log IPv4/IPv6 headers in a human-readable format.
- Simplified the counter tests and validation of the
`ProtocolCounters`.
- Reworked the main test case functions, `Verify6To4()` and
`Verify4To6()`, to leverage the new logging and verification
helpers for better output.
The `Cidr` class was incorrectly inheriting from `Clearable<Address>`
instead of `Clearable<Cidr>`. This oversight meant that calling
`Clear()` on a `Cidr` object would not clear its `mLength` member,
only the `mAddress` field. This change corrects the template
parameter for the `Clearable` base class to `Cidr`, ensuring the
entire object is properly zeroed out.
This bug could cause issues in the NAT64 translator. When a user calls
`otNat64ClearIp4Cidr()` to disable translation, the underlying
`mIp4Cidr.Clear()` method would fail to clear the CIDR length. The
`Nat64::Translator` would check `mIp4Cidr.mLength > 0` in its
`UpdateState()` method to determine if a valid CIDR is configured.
Because `mLength` was not cleared, this check would pass incorrectly,
causing NAT64 translation to continue with an invalid,
partially-cleared CIDR instead of stopping as expected.
This change updates multiple modules to consistently use
`Get<Mle::Mle>()` for accessing the MLE component, removing the need
for local `Mle::Mle &mle` references.
This approach aligns with the common `Get<Module>()` access pattern
used across the codebase, improving consistency.
Previously, a NAT64 mapping's lifetime was only extended upon its
initial allocation. This meant that if an existing mapping was found
and reused, its expiration timer would not be refreshed, potentially
leading to its premature removal.
This change moves the `mapping->Touch()` call from `AllocateMapping()` to
`TranslateFromIp6()`. This ensures that a mapping's lifetime is
extended every time it is used for translation, whether it is newly
allocated or an existing one being reused.
This change introduces `ShouldRegisterMulticastAddrsWithParent()` to
consolidate the logic for determining when a child should register
its multicast addresses with its parent, thereby avoiding repeated
code.
The criteria for registration remain the same: a child registers its
multicast addresses if it is a Sleepy End Device (SED), or if it is a
Minimal End Device (MED) and its parent is running Thread 1.2 or a
later version.
The logic for sharing an IPv4 address, intended for scenarios with a
small address pool (CIDR prefix > /28), was incorrectly being applied
even when port translation was disabled.
When `OPENTHREAD_CONFIG_NAT64_PORT_TRANSLATION_ENABLE` is disabled,
each mapping requires a unique IPv4 address. The previous
implementation would incorrectly reuse the same address from the
pool.
This commit makes the address sharing logic conditional on the
`OPENTHREAD_CONFIG_NAT64_PORT_TRANSLATION_ENABLE` configuration. When
disabled, the translator now correctly allocates a unique IPv4
address for each mapping and returns it to the pool upon release.
This commit improves the NAT64 address mapping iterator to ensure the
remaining lifetime for all mapping entries is reported consistently.
The iterator now internally stores a timestamp upon initialization.
This timestamp is then used as a common reference to calculate the
remaining lifetime for each `otNat64AddressMapping` entry, ensuring
consistent values throughout a single iteration.
The public C APIs remain unchanged, while the underlying implementation
and the `otNat64AddressMappingIterator` struct are updated.
This change introduces `RouterUpgradeReasonToString()` to provide
human-readable strings for router upgrade reasons, which is used to
enhance logging in `BecomeRouter()` and `ProcessAddressSolicit()`.
These additions provide clearer insight into why a device is
attempting to become a router, aiding in debugging and network
analysis.
This commit places the `mSrcPortOrId` and `mTranslatedPortOrId`
members of the `Translator::Mapping` struct under the
`OPENTHREAD_CONFIG_NAT64_PORT_TRANSLATION_ENABLE` build-time flag.
This optimization reduces the memory footprint of each `Mapping` entry
and the `mMappingPool` when the NAT64 port translation feature is
disabled.
This change streamlines NAT64 mapping management by removing the
`FindMapping()` and `FindOrAllocateMapping()` helper methods.
Following recent simplifications, such as adding new `Matches()`
flavors, the logic within these `Find` methods became much
simpler. Their functionality is now incorporated directly into
`TranslateToIp6()` and `TranslateFromIp6()`, respectively.
Additionally, the `Mapping::Touch()` method is simplified to no longer
require the current time as an argument. It now retrieves the time
internally.
This commit introduces several cleanups and smaller improvements to
the IPv4 types.
- Optimizes `Cidr::ToString(StringWriter&)` by writing the address
directly to the provided writer, avoiding the allocation of a
temporary `String` object.
- Moves the IPv4 header field offset constants from the public
`ip4_types.hpp` header into the unit test file, as this was their
only place of use. This cleans up the `Ip4::Header` public API.
- Replaces hardcoded values for address and string sizes with the
corresponding `OT_IP4_*` definitions for consistency.
- Corrects the format specifier in `Address::ToString()` from `%d` to
`%u` to properly print unsigned octet values.
This change introduces a new history list to record the DHCPv6 Prefix
Delegation (PD) state and the delegated prefix.
The recorded history can be iterated using the new API
`otHistoryTrackerIterateDhcp6PdHistory()` and viewed from the CLI
using the new `history dhcp6pd` command.
This commit adds a test case to `TestMultiPacket` to validate the
correct eviction of pending truncated queries.
The test scenario sends the same truncated query multiple times,
followed by a query containing a matching known answer. It then
verifies that no response is sent, confirming that the initial
pending queries were successfully evicted from the message queue.
This validates the fix from #11854.
This change updates the `Mapping::Matches` methods to accept
`Ip4::Headers` and `Ip6::Headers` objects instead of separate IP
address and port arguments.
This simplifies the callers `FindOrAllocateMapping` and `FindMapping`
by encapsulating the conditional logic for port translation within
the `Mapping::Matches` methods. This allows for a single, unified
`FindMatching` method on the active mappings list.
This commit changes the `RxMsgEntry` allocation check from `OT_ASSERT`
to `VerifyOrExit`. This ensures that a heap allocation failure for a
multi-packet RX message results in the message being gracefully
dropped, allowing network operation to continue instead of
asserting.
Additionally, `AddNew()` now removes any existing multi-packet message
entries from the same sender before attempting to allocate a new
`RxMsgEntry`. This helps to reclaim resources and prevent stale
entries.
This change also fixes a use-after-release bug by ensuring
that the `aRxMessagePtr` (an `OwnedPtr`) is not accessed after its
ownership is transferred by the `newEntry->Add(aRxMessagePtr)`
call.
This commit simplifies and enhances the NAT64 translator's counter
implementation.
- The `mProtocolCounters` and `mErrorCounters` are explicitly cleared
in the `Translator` constructor, ensuring they are properly
zero-initialized.
- The `ErrorCounters` C++ wrapper class is removed, and the counters
are now updated directly based on `DropReason`.
- The `ProtocolCounters::Count*Packet()` methods are updated to accept
`Ip6::Headers` and `Ip4::Headers` inputs directly, which simplifies
the call sites.
- Private helper methods, `Update6To4()` and `Update4To6()`, are
introduced in `ProtocolCounters` to reduce code duplication when
incrementing packet and byte counts.
This commit introduces two new `static` helper methods,
`GetSourcePortOrIcmp6Id()` and `GetDestinationPortOrIcmp4Id()`, to
the `Translator` class. This eliminates repeated similar code and
improves overall readability.
This commit enhances the `HistoryTracker` to record information about
routers discovered on the Adjacent Infrastructure Link (AIL).
This feature is applicable when the device operates as a Border
Router, providing a mechanism to monitor the history of changes to
the discovered AIL routers for debugging and network analysis.
The history tracker records events when an AIL router is added,
removed, or when its tracked information changes. The recorded
information includes:
- The IPv6 address of the router
- Default router status and its preference
- RA flags: 'M' (Managed Addr), 'O' (Other), 'S' (SNAC Router)
- Operational information:
- Whether the router is a local entity (on same device)
- Reachability status
- Whether it is a peer Border Router on the same Thread mesh
- The favored advertised on-link prefix by this router (if any)
A new public API, `otHistoryTrackerIterateAilRoutersHistory()`, is
added to iterate over the recorded AIL router history. A
corresponding CLI command, `history ailrouters`, is also included to
display this information.
This commit updates the `Translator` class to improve code style,
readability, and consistency with the OpenThread coding conventions.
This is a pure refactoring commit with no intended logic changes. Key
changes include:
- Renamed types and variables for brevity (e.g., `AddressMapping` to
`Mapping`).
- Renamed members within the `Mapping` struct for clarity(e.g., `mIp4`
to `mIp4Address`).
- Standardized local variable names (e.g., `err` to `error`).
- Added `const` to methods that do not modify the class state.
- Improved and reformatted Doxygen and inline comments.
This commit improves the organization of `mle.cpp` by grouping all
`Attacher` method definitions together.
When the `Attacher` class was introduced in #11835, its method
definitions were intentionally kept in their previous order to
minimize the `git diff` for easier review. This resulted in the
`Attacher` methods being interleaved with other `Mle` methods.
This commit acts as a follow-up to rearrange the file and group all
`Attacher` methods into a dedicated section for better readability
and organization.
No logic changes are included in this commit.
This change introduces a `--log-level` option to the `build.sh`
script, allowing the `OPENTHREAD_CONFIG_LOG_LEVEL` to be specified at
build time.
The supported log levels are `NONE`, `CRIT`, `WARN`, `NOTE`, `INFO`,
and `DEBG`. The default level is set to `INFO`.
The CI workflow is updated to test builds with all the supported log
levels.
This commit enhances the `FindContext()` methods and converts the
`Lowpan::Context` struct into a class.
The `FindContext()` methods are updated as follows:
- Renamed to `FindContextForAddress()` and `FindContextForId()` to
more accurately reflect their function.
- The return type is changed from `Error` to `void`. Success is now
indicated by checking the `IsValid()` state of the output `Context`
object (matching how `Lowpan` class uses the `Context`). This
change simplifies the callers and harmonizes the context check
across different modules.
The `Lowpan::Context` struct is converted into a class, encapsulating
its members by making them private and introducing public getters.