From 5f9fe671e92b57af4754a7a005a335bf1b0b7592 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Mon, 22 Jun 2026 10:28:27 -0700 Subject: [PATCH] [mesh-diag] support requesting extra TLVs during topology discovery (#13257) This commit enhances the Mesh Diag topology discovery process (`otMeshDiagDiscoverTopology()`) by allowing users to request an array of extra Network Diagnostic TLVs from each discovered router. Key changes: - Extended `otMeshDiagDiscoverConfig` to include an `mExtraTlvTypes` array and `mExtraTlvTypesLength`. - Added the `otMeshDiagTlvIterator` opaque type and `otMeshDiagGetNextTlvInfo()` API to iterate over the parsed extra TLVs retrieved from each router. - Exposed the new `TlvIterator` via `otMeshDiagRouterInfo` in the `otMeshDiagDiscoverCallback`. - Updated `MeshDiag::DiscoverTopology()` to dynamically include the extra TLVs in the CoAP diagnostic request, along with robust validation ensuring standard TLVs are not requested twice. - Introduced `test_mesh_diag.cpp` under Nexus to validate base discovery, IPv6 and Child Table discovery, extra TLV retrieval, and API argument validation. --- include/openthread/instance.h | 2 +- include/openthread/mesh_diag.h | 81 ++++++++- src/cli/cli_mesh_diag.cpp | 1 + src/core/api/mesh_diag_api.cpp | 5 + src/core/utils/mesh_diag.cpp | 133 ++++++++++++-- src/core/utils/mesh_diag.hpp | 43 +++++ tests/nexus/CMakeLists.txt | 1 + tests/nexus/test_mesh_diag.cpp | 323 +++++++++++++++++++++++++++++++++ 8 files changed, 572 insertions(+), 17 deletions(-) create mode 100644 tests/nexus/test_mesh_diag.cpp diff --git a/include/openthread/instance.h b/include/openthread/instance.h index d9765b288..dc33b436a 100644 --- a/include/openthread/instance.h +++ b/include/openthread/instance.h @@ -52,7 +52,7 @@ extern "C" { * * @note This number versions both OpenThread platform and user APIs. */ -#define OPENTHREAD_API_VERSION (605) +#define OPENTHREAD_API_VERSION (606) /** * @addtogroup api-instance diff --git a/include/openthread/mesh_diag.h b/include/openthread/mesh_diag.h index 66473f5a7..2655b8b16 100644 --- a/include/openthread/mesh_diag.h +++ b/include/openthread/mesh_diag.h @@ -41,6 +41,7 @@ #include #include #include +#include #include #include @@ -62,11 +63,15 @@ extern "C" { /** * Represents the set of configurations used when discovering mesh topology indicating which items to * discover. + * + * The `mExtraTlvTypes` pointer can be NULL if `mExtraTlvTypesLength` is zero. */ typedef struct otMeshDiagDiscoverConfig { - bool mDiscoverIp6Addresses : 1; ///< Whether or not to discover IPv6 addresses of every router. - bool mDiscoverChildTable : 1; ///< Whether or not to discover children of every router. + bool mDiscoverIp6Addresses : 1; ///< Whether or not to discover IPv6 addresses of every router. + bool mDiscoverChildTable : 1; ///< Whether or not to discover children of every router. + const uint8_t *mExtraTlvTypes; ///< An array of extra Net Diag TLV types to request from every router. + uint8_t mExtraTlvTypesLength; ///< The length of the `mExtraTlvTypes` array. Can be zero. } otMeshDiagDiscoverConfig; /** @@ -83,6 +88,18 @@ typedef struct otMeshDiagIp6AddrIterator otMeshDiagIp6AddrIterator; */ typedef struct otMeshDiagChildIterator otMeshDiagChildIterator; +/** + * An opaque iterator to iterate over the list of extra Network Diagnostic TLVs returned by a router. + * + * Pointers to instances of this type are provided in `otMeshDiagRouterInfo`. + */ +typedef struct otMeshDiagTlvIterator otMeshDiagTlvIterator; + +/** + * Represents information about a parsed Network Diagnostic TLV. + */ +typedef otNetworkDiagTlv otMeshDiagTlvInfo; + /** * Specifies that Thread Version is unknown. * @@ -136,6 +153,16 @@ typedef struct otMeshDiagRouterInfo * if the router did not provide the list. */ otMeshDiagChildIterator *mChildIterator; + + /** + * A pointer to an iterator to go through the list of extra Network Diagnostic TLVs returned by the router. + * + * The pointer is valid only while `otMeshDiagRouterInfo` is valid. It can be used in `otMeshDiagGetNextTlvInfo` + * to iterate through the extra TLVs returned by the router. + * + * The pointer may be NULL if there are no extra TLVs (in `otMeshDiagDiscoverConfig`). + */ + otMeshDiagTlvIterator *mTlvIterator; } otMeshDiagRouterInfo; /** @@ -168,6 +195,39 @@ typedef void (*otMeshDiagDiscoverCallback)(otError aError, otMeshDiagRouterInfo /** * Starts network topology discovery. * + * This function initiates a query to discover routers in the Thread network. + * + * The @p aConfig configuration controls what optional topology information is discovered: + * - If `mDiscoverIp6Addresses` is set to true, the list of IPv6 addresses for each router is discovered. + * - If `mDiscoverChildTable` is set to true, the list of children for each router is discovered. + * + * The @p aConfig parameter can be used to request additional standard Network Diagnostic TLVs to be retrieved from + * each discovered router during topology discovery. These extra TLVs can then be accessed via the `mTlvIterator` in + * the callback's router info. + * + * The following restrictions and recommendations apply to the use of `mExtraTlvTypes`: + * - It MUST NOT contain any of the TLV types that are already requested by the discovery process itself. + * These are: + * - `OT_NETWORK_DIAGNOSTIC_TLV_SHORT_ADDRESS` + * - `OT_NETWORK_DIAGNOSTIC_TLV_EXT_ADDRESS` + * - `OT_NETWORK_DIAGNOSTIC_TLV_ROUTE` + * - `OT_NETWORK_DIAGNOSTIC_TLV_VERSION` + * - `OT_NETWORK_DIAGNOSTIC_TLV_IP6_ADDR_LIST` + * - `OT_NETWORK_DIAGNOSTIC_TLV_CHILD_TABLE` + * If any of these types are included in @p aConfig.mExtraTlvTypes, `OT_ERROR_INVALID_ARGS` is returned. + * - The total number of requested TLV types is limited to 32. This limit applies to all TLV types combined, including + * those automatically added by the discovery process and any additional TLVs specified by the caller in + * `mExtraTlvTypes`. If the total count exceeds this limit, `OT_ERROR_NO_BUFS` is returned. + * - It is highly recommended to keep the number of additional TLVs small. Requesting many or large TLVs increases the + * size of the Network Diagnostics responses, which can cause message fragmentation, higher network traffic, or + * response packet drops. + * - Additional TLVs should be restricted to small metadata elements useful during topology discovery (for example, + * `OT_NETWORK_DIAGNOSTIC_TLV_VENDOR_NAME`, `OT_NETWORK_DIAGNOSTIC_TLV_VENDOR_MODEL`, etc). + * For retrieving larger information (like counters, etc.), separate individual queries should be sent to specific + * nodes instead of using this method. + * - The @p aConfig struct and the memory pointed to by its @p mExtraTlvTypes array do not need to persist beyond + * the call to this function. + * * @param[in] aInstance The OpenThread instance. * @param[in] aConfig The configuration to use for discovery (e.g., which items to discover). * @param[in] aCallback The callback to report the discovered routers. @@ -176,7 +236,8 @@ typedef void (*otMeshDiagDiscoverCallback)(otError aError, otMeshDiagRouterInfo * @retval OT_ERROR_NONE The network topology discovery started successfully. * @retval OT_ERROR_BUSY A previous discovery request is still ongoing. * @retval OT_ERROR_INVALID_STATE Device is not attached. - * @retval OT_ERROR_NO_BUFS Could not allocate buffer to send discovery messages. + * @retval OT_ERROR_NO_BUFS Could not allocate buffer to send discovery messages or too many extra TLVs. + * @retval OT_ERROR_INVALID_ARGS Invalid @p aConfig (e.g., includes restricted extra TLVs as listed above). */ otError otMeshDiagDiscoverTopology(otInstance *aInstance, const otMeshDiagDiscoverConfig *aConfig, @@ -220,6 +281,20 @@ otError otMeshDiagGetNextIp6Address(otMeshDiagIp6AddrIterator *aIterator, otIp6A */ otError otMeshDiagGetNextChildInfo(otMeshDiagChildIterator *aIterator, otMeshDiagChildInfo *aChildInfo); +/** + * Iterates through the discovered extra Network Diagnostic TLVs of a router. + * + * This function MUST be used from the callback `otMeshDiagDiscoverCallback()` and use the `mTlvIterator` from the + * `aRouterInfo` struct that is provided as input to the callback. + * + * @param[in,out] aIterator The TLV iterator to use. + * @param[out] aTlvInfo A pointer to return the extra TLV info (if any). + * + * @retval OT_ERROR_NONE Successfully retrieved the next extra TLV. @p aTlvInfo and @p aIterator are updated. + * @retval OT_ERROR_NOT_FOUND No more extra TLVs. Reached the end of the list. + */ +otError otMeshDiagGetNextTlvInfo(otMeshDiagTlvIterator *aIterator, otMeshDiagTlvInfo *aTlvInfo); + /** * Represents information about a child entry from `otMeshDiagQueryChildTable()`. * diff --git a/src/cli/cli_mesh_diag.cpp b/src/cli/cli_mesh_diag.cpp index 8127abb7d..f555bc14b 100644 --- a/src/cli/cli_mesh_diag.cpp +++ b/src/cli/cli_mesh_diag.cpp @@ -125,6 +125,7 @@ template <> otError MeshDiag::Process(Arg aArgs[]) otError error = OT_ERROR_NONE; otMeshDiagDiscoverConfig config; + ClearAllBytes(config); config.mDiscoverIp6Addresses = false; config.mDiscoverChildTable = false; diff --git a/src/core/api/mesh_diag_api.cpp b/src/core/api/mesh_diag_api.cpp index 5e1d4f7b6..18905effe 100644 --- a/src/core/api/mesh_diag_api.cpp +++ b/src/core/api/mesh_diag_api.cpp @@ -60,6 +60,11 @@ otError otMeshDiagGetNextChildInfo(otMeshDiagChildIterator *aIterator, otMeshDia return AsCoreType(aIterator).GetNextChildInfo(AsCoreType(aChildInfo)); } +otError otMeshDiagGetNextTlvInfo(otMeshDiagTlvIterator *aIterator, otMeshDiagTlvInfo *aTlvInfo) +{ + return AsCoreType(aIterator).GetNextTlvInfo(*aTlvInfo); +} + otError otMeshDiagQueryChildTable(otInstance *aInstance, uint16_t aRloc16, otMeshDiagQueryChildTableCallback aCallback, diff --git a/src/core/utils/mesh_diag.cpp b/src/core/utils/mesh_diag.cpp index 60fc48a8c..d5c248809 100644 --- a/src/core/utils/mesh_diag.cpp +++ b/src/core/utils/mesh_diag.cpp @@ -47,6 +47,12 @@ RegisterLogModule("MeshDiag"); //--------------------------------------------------------------------------------------------------------------------- // MeshDiag +const uint8_t MeshDiag::kDiscoverTopologyTlvs[] = { + Address16Tlv::kType, ExtMacAddressTlv::kType, RouteTlv::kType, VersionTlv::kType, + Ip6AddressListTlv::kType, // Only if `mDiscoverIp6Addresses` in `DiscoverConfig`. + ChildTableTlv::kType, // Only if `mDiscoverChildTable` in `DiscoverConfig`. +}; + MeshDiag::MeshDiag(Instance &aInstance) : InstanceLocator(aInstance) , mState(kStateIdle) @@ -64,30 +70,38 @@ void MeshDiag::SetResponseTimeout(uint32_t aTimeout) Error MeshDiag::DiscoverTopology(const DiscoverConfig &aConfig, DiscoverCallback aCallback, void *aContext) { - static constexpr uint8_t kMaxTlvsToRequest = 6; - Error error = kErrorNone; - uint8_t tlvs[kMaxTlvsToRequest]; - uint8_t tlvsLength = 0; + TlvList tlvList; + + if (aConfig.mExtraTlvTypesLength != 0) + { + // Verify that `mExtraTlvTypes` does not contain any of the required topology TLV types. + VerifyOrExit(aConfig.mExtraTlvTypes != nullptr, error = kErrorInvalidArgs); + + for (uint8_t i = 0; i < aConfig.mExtraTlvTypesLength; i++) + { + VerifyOrExit(!DoesArrayContain(kDiscoverTopologyTlvs, aConfig.mExtraTlvTypes[i]), + error = kErrorInvalidArgs); + } + } VerifyOrExit(Get().IsAttached(), error = kErrorInvalidState); VerifyOrExit(mState == kStateIdle, error = kErrorBusy); - tlvs[tlvsLength++] = Address16Tlv::kType; - tlvs[tlvsLength++] = ExtMacAddressTlv::kType; - tlvs[tlvsLength++] = RouteTlv::kType; - tlvs[tlvsLength++] = VersionTlv::kType; + SuccessOrExit(error = tlvList.AddAll(kDiscoverTopologyTlvs, GetArrayLength(kDiscoverTopologyTlvs))); - if (aConfig.mDiscoverIp6Addresses) + if (!aConfig.mDiscoverIp6Addresses) { - tlvs[tlvsLength++] = Ip6AddressListTlv::kType; + tlvList.Remove(Ip6AddressListTlv::kType); } - if (aConfig.mDiscoverChildTable) + if (!aConfig.mDiscoverChildTable) { - tlvs[tlvsLength++] = ChildTableTlv::kType; + tlvList.Remove(ChildTableTlv::kType); } + SuccessOrExit(error = tlvList.AddAll(aConfig.mExtraTlvTypes, aConfig.mExtraTlvTypesLength)); + Get().GetRouterIdMask(mDiscover.mExpectedRouterIds); for (uint8_t routerId = 0; routerId <= Mle::kMaxRouterId; routerId++) @@ -102,7 +116,8 @@ Error MeshDiag::DiscoverTopology(const DiscoverConfig &aConfig, DiscoverCallback Get().ComposeRloc(Mle::Rloc16FromRouterId(routerId), destination); SuccessOrExit(error = Get().SendCommand(kUriDiagnosticGetRequest, Message::kPriorityLow, destination, - tlvs, tlvsLength, HandleDiagGetResponse, this)); + tlvList.GetArrayBuffer(), tlvList.GetLength(), + HandleDiagGetResponse, this)); } mDiscover.mCallback.Set(aCallback, aContext); @@ -119,6 +134,7 @@ void MeshDiag::HandleDiagGetResponse(Coap::Msg *aMsg, Error aResult) RouterInfo routerInfo; Ip6AddrIterator ip6AddrIterator; ChildIterator childIterator; + TlvIterator tlvIterator; SuccessOrExit(aResult); VerifyOrExit(aMsg != nullptr); @@ -136,6 +152,9 @@ void MeshDiag::HandleDiagGetResponse(Coap::Msg *aMsg, Error aResult) routerInfo.mChildIterator = &childIterator; } + tlvIterator.InitFrom(aMsg->mMessage); + routerInfo.mTlvIterator = &tlvIterator; + mDiscover.mExpectedRouterIds.Remove(routerInfo.mRouterId); if (mDiscover.mExpectedRouterIds.DetermineAllocatedCount() == 0) @@ -614,6 +633,94 @@ void MeshDiag::RouterNeighborEntry::SetFrom(const RouterNeighborTlvValue &aTlvVa mMessageErrorRate = aTlvValue.GetMessageErrorRate(); } +//--------------------------------------------------------------------------------------------------------------------- +// MeshDiag::TlvIterator + +void MeshDiag::TlvIterator::InitFrom(const Message &aMessage) +{ + mMessage = &aMessage; + mIter = aMessage.GetOffset(); +} + +Error MeshDiag::TlvIterator::GetNextTlvInfo(DiagTlvInfo &aTlvInfo) +{ + Error error; + uint16_t offset = mIter; + Tlv::Info tlvInfo; + + VerifyOrExit(mMessage != nullptr, error = kErrorNotFound); + + while (offset < mMessage->GetLength()) + { + SuccessOrExit(error = tlvInfo.ParseFrom(*mMessage, offset)); + offset += tlvInfo.GetSize(); + + if (DoesArrayContain(kDiscoverTopologyTlvs, tlvInfo.GetType())) + { + continue; + } + + error = NetDiag::Client::ParseDiagTlv(*mMessage, tlvInfo, aTlvInfo); + + switch (error) + { + case kErrorNotCapable: + // Skip over any unrecognized TLV. + break; + + case kErrorNone: + mIter = offset; + OT_FALL_THROUGH; + + default: + ExitNow(); + } + } + + error = kErrorNotFound; + +exit: + return error; +} + +//--------------------------------------------------------------------------------------------------------------------- +// MeshDiag::TlvList + +Error MeshDiag::TlvList::Add(uint8_t aTlvType) +{ + Error error = kErrorNone; + + VerifyOrExit(!Contains(aTlvType)); + error = PushBack(aTlvType); + +exit: + return error; +} + +Error MeshDiag::TlvList::AddAll(const uint8_t *aTlvTypes, uint8_t aLength) +{ + Error error = kErrorNone; + + for (uint8_t i = 0; i < aLength; i++) + { + SuccessOrExit(error = Add(aTlvTypes[i])); + } + +exit: + return error; +} + +void MeshDiag::TlvList::Remove(uint8_t aTlvType) +{ + uint8_t *entry = Find(aTlvType); + + VerifyOrExit(entry != nullptr); + Array::Remove(*entry); + +exit: + return; +} + } // namespace Utils } // namespace ot diff --git a/src/core/utils/mesh_diag.hpp b/src/core/utils/mesh_diag.hpp index e2508f3c9..2f0d29e17 100644 --- a/src/core/utils/mesh_diag.hpp +++ b/src/core/utils/mesh_diag.hpp @@ -61,6 +61,10 @@ struct otMeshDiagChildIterator { }; +struct otMeshDiagTlvIterator +{ +}; + namespace ot { namespace Utils { @@ -75,6 +79,7 @@ public: static constexpr uint16_t kVersionUnknown = OT_MESH_DIAG_VERSION_UNKNOWN; ///< Unknown version. typedef otMeshDiagDiscoverConfig DiscoverConfig; ///< Discovery configuration. + typedef otMeshDiagTlvInfo DiagTlvInfo; ///< Diagnostic TLV Info. typedef otMeshDiagDiscoverCallback DiscoverCallback; ///< Discovery callback. typedef otMeshDiagQueryChildTableCallback QueryChildTableCallback; ///< Query Child Table callback. typedef otMeshDiagChildIp6AddrsCallback ChildIp6AddrsCallback; ///< Child IPv6 addresses callback. @@ -149,6 +154,31 @@ public: uint16_t mParentRloc16; }; + /** + * Represents an iterator to iterate over extra/custom Network Diagnostic TLVs returned by a router. + */ + class TlvIterator : public otMeshDiagTlvIterator + { + friend class MeshDiag; + + public: + /** + * Iterates to the next extra Network Diagnostic TLV. + * + * @param[out] aTlvInfo A reference to a `DiagTlvInfo` to return the next extra TLV info. + * + * @retval kErrorNone Successfully retrieved the next extra TLV. + * @retval kErrorNotFound No more extra TLVs. + */ + Error GetNextTlvInfo(DiagTlvInfo &aTlvInfo); + + private: + void InitFrom(const Message &aMessage); + + const Message *mMessage; + NetDiag::Client::Iterator mIter; + }; + /** * Initializes the `MeshDiag` instance. * @@ -247,6 +277,7 @@ private: static constexpr uint32_t kResponseTimeout = OPENTHREAD_CONFIG_MESH_DIAG_RESPONSE_TIMEOUT; static constexpr uint32_t kMinResponseTimeout = 50; static constexpr uint32_t kMaxResponseTimeout = 10 * Time::kOneMinuteInMsec; + static constexpr uint16_t kMaxTlvTypes = 32; enum State : uint8_t { @@ -297,6 +328,15 @@ private: void SetFrom(const NetDiag::RouterNeighborTlvValue &aTlvValue); }; + class TlvList : public Array + { + public: + TlvList(void) = default; + Error Add(uint8_t aTlvType); + Error AddAll(const uint8_t *aTlvTypes, uint8_t aLength); + void Remove(uint8_t aTlvType); + }; + Error SendQuery(uint16_t aRloc16, const uint8_t *aTlvs, uint8_t aTlvsLength); void Finalize(Error aError); void HandleTimer(void); @@ -310,6 +350,8 @@ private: using TimeoutTimer = TimerMilliIn; + static const uint8_t kDiscoverTopologyTlvs[]; + State mState; uint16_t mExpectedQueryId; uint16_t mExpectedAnswerIndex; @@ -331,6 +373,7 @@ DefineCoreType(otMeshDiagIp6AddrIterator, Utils::MeshDiag::Ip6AddrIterator); DefineCoreType(otMeshDiagRouterInfo, Utils::MeshDiag::RouterInfo); DefineCoreType(otMeshDiagChildInfo, Utils::MeshDiag::ChildInfo); DefineCoreType(otMeshDiagChildIterator, Utils::MeshDiag::ChildIterator); +DefineCoreType(otMeshDiagTlvIterator, Utils::MeshDiag::TlvIterator); } // namespace ot diff --git a/tests/nexus/CMakeLists.txt b/tests/nexus/CMakeLists.txt index a13563e40..174c793fb 100644 --- a/tests/nexus/CMakeLists.txt +++ b/tests/nexus/CMakeLists.txt @@ -424,6 +424,7 @@ ot_nexus_test(key_rotation_guard_time "core;nexus") ot_nexus_test(leader_reboot_multiple_link_request "core;nexus") ot_nexus_test(log_override "core;nexus") ot_nexus_test(mac_scan "core;nexus") +ot_nexus_test(mesh_diag "core;nexus") ot_nexus_test(mle_router_role_allowed "core;nexus") ot_nexus_test(mle_blocking_downgrade "core;nexus") ot_nexus_test(mle_msg_key_seq_jump "core;nexus") diff --git a/tests/nexus/test_mesh_diag.cpp b/tests/nexus/test_mesh_diag.cpp new file mode 100644 index 000000000..ccb07855b --- /dev/null +++ b/tests/nexus/test_mesh_diag.cpp @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2026, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "platform/nexus_core.hpp" +#include "platform/nexus_node.hpp" + +namespace ot { +namespace Nexus { + +using MeshDiag = ot::Utils::MeshDiag; + +static constexpr uint16_t kMaxEntries = 8; + +struct DiscoveredRouter +{ + bool mValid; + uint16_t mRloc16; + bool mIsThisDevice; + bool mIsLeader; + uint16_t mVersion; + Array mIp6Addrs; + Array mChildren; + Array mExtraTlvTypes; +}; + +static Error sLastCallbackError; +static Array sDiscoveredRouters; + +static void ResetTest(void) +{ + sLastCallbackError = kErrorNone; + sDiscoveredRouters.Clear(); +} + +static void HandleDiscoverCallback(otError aError, otMeshDiagRouterInfo *aRouterInfo, void *aContext) +{ + DiscoveredRouter *router; + + VerifyOrQuit(aContext == nullptr); + + sLastCallbackError = aError; + + VerifyOrExit(aRouterInfo != nullptr); + + router = sDiscoveredRouters.PushBack(); + + VerifyOrQuit(router != nullptr, "sDiscoveredRouters is full"); + + router->mValid = true; + router->mRloc16 = aRouterInfo->mRloc16; + router->mIsThisDevice = aRouterInfo->mIsThisDevice; + router->mIsLeader = aRouterInfo->mIsLeader; + router->mVersion = aRouterInfo->mVersion; + router->mIp6Addrs.Clear(); + router->mChildren.Clear(); + router->mExtraTlvTypes.Clear(); + + if (aRouterInfo->mIp6AddrIterator != nullptr) + { + MeshDiag::Ip6AddrIterator &ip6Iterator = AsCoreType(aRouterInfo->mIp6AddrIterator); + Ip6::Address ip6Addr; + + while (ip6Iterator.GetNextAddress(ip6Addr) == kErrorNone) + { + SuccessOrQuit(router->mIp6Addrs.PushBack(ip6Addr)); + } + } + + if (aRouterInfo->mChildIterator != nullptr) + { + MeshDiag::ChildIterator &childIterator = AsCoreType(aRouterInfo->mChildIterator); + MeshDiag::ChildInfo childInfo; + + while (childIterator.GetNextChildInfo(childInfo) == kErrorNone) + { + SuccessOrQuit(router->mChildren.PushBack(childInfo)); + } + } + + if (aRouterInfo->mTlvIterator != nullptr) + { + MeshDiag::TlvIterator &tlvIterator = AsCoreType(aRouterInfo->mTlvIterator); + MeshDiag::DiagTlvInfo tlvInfo; + + while (tlvIterator.GetNextTlvInfo(tlvInfo) == kErrorNone) + { + SuccessOrQuit(router->mExtraTlvTypes.PushBack(tlvInfo.mType)); + } + } + +exit: + return; +} + +void TestMeshDiag(void) +{ + Core nexus; + + Node &leader = nexus.CreateNode(); + Node &router1 = nexus.CreateNode(); + Node &child1 = nexus.CreateNode(); + Node &child2 = nexus.CreateNode(); + + MeshDiag::DiscoverConfig config; + Array extraTlvTypes; + Array forbiddenTlvTypes; + bool foundLeader; + bool foundRouter1; + + nexus.AdvanceTime(0); + + SuccessOrQuit(Instance::SetGlobalLogLevel(kLogLevelNote)); + + AllowLinkBetween(leader, router1); + AllowLinkBetween(router1, child1); + AllowLinkBetween(router1, child2); + + leader.Form(); + nexus.AdvanceTime(15 * Time::kOneSecondInMsec); + VerifyOrQuit(leader.Get().IsLeader()); + + router1.Join(leader); + nexus.AdvanceTime(5 * Time::kOneMinuteInMsec); + VerifyOrQuit(router1.Get().IsRouter()); + + child1.Join(router1, Node::kAsFed); + nexus.AdvanceTime(5 * Time::kOneSecondInMsec); + child2.Join(router1, Node::kAsFed); + nexus.AdvanceTime(5 * Time::kOneSecondInMsec); + + VerifyOrQuit(child1.Get().IsChild()); + VerifyOrQuit(child2.Get().IsChild()); + + Log("---------------------------------------------------------------------------------------"); + Log("Test Scenario 1: Base Discovery (both config flags false, no extra TLVs)"); + + ResetTest(); + + ClearAllBytes(config); + + SuccessOrQuit(leader.Get().DiscoverTopology(config, HandleDiscoverCallback, nullptr)); + + nexus.AdvanceTime(3 * Time::kOneSecondInMsec); + + SuccessOrQuit(sLastCallbackError); + VerifyOrQuit(sDiscoveredRouters.GetLength() == 2); + + foundLeader = false; + foundRouter1 = false; + + for (DiscoveredRouter &router : sDiscoveredRouters) + { + VerifyOrQuit(router.mValid); + + if (router.mRloc16 == leader.Get().GetRloc16()) + { + foundLeader = true; + VerifyOrQuit(router.mIsLeader); + VerifyOrQuit(router.mIsThisDevice); + } + else if (router.mRloc16 == router1.Get().GetRloc16()) + { + foundRouter1 = true; + VerifyOrQuit(!router.mIsLeader); + VerifyOrQuit(!router.mIsThisDevice); + } + else + { + VerifyOrQuit(false, "Discovered unexpected router RLOC16"); + } + + VerifyOrQuit(router.mIp6Addrs.IsEmpty()); + VerifyOrQuit(router.mChildren.IsEmpty()); + VerifyOrQuit(router.mExtraTlvTypes.IsEmpty()); + } + + VerifyOrQuit(foundLeader); + VerifyOrQuit(foundRouter1); + + Log("---------------------------------------------------------------------------------------"); + Log("Test Scenario 2: Discover IPv6 and Child Tables (both config flags true)"); + + ResetTest(); + + ClearAllBytes(config); + config.mDiscoverIp6Addresses = true; + config.mDiscoverChildTable = true; + + SuccessOrQuit(leader.Get().DiscoverTopology(config, HandleDiscoverCallback, nullptr)); + + nexus.AdvanceTime(2 * Time::kOneSecondInMsec); + + SuccessOrQuit(sLastCallbackError); + VerifyOrQuit(sDiscoveredRouters.GetLength() == 2); + + foundLeader = false; + foundRouter1 = false; + + for (DiscoveredRouter &router : sDiscoveredRouters) + { + VerifyOrQuit(router.mValid); + if (router.mRloc16 == leader.Get().GetRloc16()) + { + foundLeader = true; + VerifyOrQuit(router.mIsLeader); + VerifyOrQuit(router.mIsThisDevice); + + // Leader has no children in this topology (both children joined Router 1) + VerifyOrQuit(router.mChildren.IsEmpty()); + } + else if (router.mRloc16 == router1.Get().GetRloc16()) + { + foundRouter1 = true; + VerifyOrQuit(!router.mIsLeader); + VerifyOrQuit(!router.mIsThisDevice); + + // Router 1 should have 2 children (Child 1 and Child 2) + VerifyOrQuit(router.mChildren.GetLength() == 2); + VerifyOrQuit(router.mChildren[0].mRloc16 == child1.Get().GetRloc16() || + router.mChildren[0].mRloc16 == child2.Get().GetRloc16()); + VerifyOrQuit(router.mChildren[1].mRloc16 == child1.Get().GetRloc16() || + router.mChildren[1].mRloc16 == child2.Get().GetRloc16()); + } + else + { + VerifyOrQuit(false, "Discovered unexpected router RLOC16"); + } + + // Both routers should have returned IPv6 addresses + VerifyOrQuit(!router.mIp6Addrs.IsEmpty()); + } + + VerifyOrQuit(foundLeader); + VerifyOrQuit(foundRouter1); + + Log("---------------------------------------------------------------------------------------"); + Log("Test Scenario 3: Discover Extra Custom TLVs"); + + ResetTest(); + + extraTlvTypes.Clear(); + SuccessOrQuit(extraTlvTypes.PushBack(NetDiag::Tlv::kVendorName)); + SuccessOrQuit(extraTlvTypes.PushBack(NetDiag::Tlv::kVendorModel)); + SuccessOrQuit(extraTlvTypes.PushBack(NetDiag::Tlv::kVendorSwVersion)); + + ClearAllBytes(config); + config.mDiscoverIp6Addresses = false; + config.mDiscoverChildTable = false; + config.mExtraTlvTypes = extraTlvTypes.GetArrayBuffer(); + config.mExtraTlvTypesLength = extraTlvTypes.GetLength(); + + SuccessOrQuit(leader.Get().DiscoverTopology(config, HandleDiscoverCallback, nullptr)); + + nexus.AdvanceTime(2 * Time::kOneSecondInMsec); + + SuccessOrQuit(sLastCallbackError); + VerifyOrQuit(sDiscoveredRouters.GetLength() == 2); + + for (DiscoveredRouter &router : sDiscoveredRouters) + { + VerifyOrQuit(router.mValid); + VerifyOrQuit(router.mIp6Addrs.IsEmpty()); + VerifyOrQuit(router.mChildren.IsEmpty()); + + // Expect extra TLVs to match the length of requested extra TLVs + VerifyOrQuit(router.mExtraTlvTypes.GetLength() == extraTlvTypes.GetLength()); + + for (uint8_t tlvType : extraTlvTypes) + { + VerifyOrQuit(router.mExtraTlvTypes.Contains(tlvType)); + } + } + + Log("---------------------------------------------------------------------------------------"); + Log("Test Scenario 4: Error/Validation checks for extra TLV types"); + + forbiddenTlvTypes.Clear(); + SuccessOrQuit(forbiddenTlvTypes.PushBack(NetDiag::Tlv::kAddress16)); + + ClearAllBytes(config); + config.mDiscoverIp6Addresses = false; + config.mDiscoverChildTable = false; + config.mExtraTlvTypes = forbiddenTlvTypes.GetArrayBuffer(); + config.mExtraTlvTypesLength = forbiddenTlvTypes.GetLength(); + + VerifyOrQuit(leader.Get().DiscoverTopology(config, HandleDiscoverCallback, nullptr) == + kErrorInvalidArgs); +} + +} // namespace Nexus +} // namespace ot + +int main(void) +{ + ot::Nexus::TestMeshDiag(); + printf("All tests passed\n"); + return 0; +}