diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 00000000..7dab184d --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,24 @@ +--- +Checks: > + -*, + bugprone-argument-comment, + bugprone-too-small-loop-variable, + google-explicit-constructor, + google-readability-casting, + misc-include-cleaner, + misc-unused-using-decls, + modernize-loop-convert, + modernize-use-bool-literals, + modernize-use-equals-default, + modernize-use-equals-delete, + modernize-use-nullptr, + readability-avoid-const-params-in-decls, + readability-else-after-return, + readability-inconsistent-declaration-parameter-name, + readability-make-member-function-const, + readability-redundant-control-flow, + readability-redundant-member-init, + readability-simplify-boolean-expr, + readability-static-accessed-through-instance +WarningsAsErrors: '*' +HeaderFilterRegex: '(include|src|tests).*(? +#include #include +#include #include #include diff --git a/include/commissioner/error.hpp b/include/commissioner/error.hpp index f61719f7..5771eed5 100644 --- a/include/commissioner/error.hpp +++ b/include/commissioner/error.hpp @@ -34,9 +34,9 @@ #ifndef OT_COMM_ERROR_HPP_ #define OT_COMM_ERROR_HPP_ -#include #include #include +#include #include @@ -227,18 +227,9 @@ class OT_COMM_MUST_USE_RESULT Error std::string mMessage; }; -inline Error::Error(const Error &aError) - : mCode(aError.mCode) - , mMessage(aError.mMessage) -{ -} +inline Error::Error(const Error &aError) = default; -inline Error &Error::operator=(const Error &aError) -{ - mCode = aError.mCode; - mMessage = aError.mMessage; - return *this; -} +inline Error &Error::operator=(const Error &aError) = default; inline Error::Error(Error &&aError) noexcept : mCode(std::move(aError.mCode)) diff --git a/include/commissioner/network_data.hpp b/include/commissioner/network_data.hpp index 022a13eb..96dc6a9c 100644 --- a/include/commissioner/network_data.hpp +++ b/include/commissioner/network_data.hpp @@ -37,6 +37,7 @@ #include #include +#include #include #include @@ -69,10 +70,10 @@ struct XpanId bool operator==(const XpanId &aOther) const; - bool operator!=(const uint64_t aOther) const; - bool operator<(const XpanId aOther) const; + bool operator!=(const XpanId &aOther) const; + bool operator<(const XpanId &aOther) const; - operator std::string() const; + explicit operator std::string() const; /** * Decodes hexadecimal string. @@ -257,12 +258,14 @@ struct PanId static constexpr uint64_t kEmptyPanId = 0; uint16_t mValue; - PanId(uint16_t aValue); + explicit PanId(uint16_t aValue); + PanId(const PanId &aOther) = default; PanId(); - PanId &operator=(uint16_t aValue); - operator uint16_t() const; - operator std::string() const; + PanId &operator=(const PanId &aValue) = default; + PanId &operator=(uint16_t aValue); + explicit operator uint16_t() const; + explicit operator std::string() const; Error FromHex(const std::string &aInput); }; diff --git a/script/bootstrap.sh b/script/bootstrap.sh index fd94dcba..c0209d05 100755 --- a/script/bootstrap.sh +++ b/script/bootstrap.sh @@ -92,7 +92,7 @@ if [ "$(uname)" = "Linux" ]; then lcov \ jsonlint - sudo apt-get --no-install-recommends install -y clang-format-14 || echo 'WARNING: could not install clang-format-14, which is useful if you plan to contribute C/C++ code to the OpenThread project.' + sudo apt-get --no-install-recommends install -y clang-format-14 clang-tidy-14 || echo 'WARNING: could not install clang-format-14 and clang-tidy-14, which is useful if you plan to contribute C/C++ code to the OpenThread project.' python3 -m pip install yapf==0.29.0 || echo 'WARNING: could not install yapf, which is useful if you plan to contribute python code to the OpenThread project.' ## Install newest CMake @@ -118,8 +118,12 @@ elif [ "$(uname)" = "Darwin" ]; then swig@4 \ lcov && true - brew install llvm@14 && sudo ln -s "$(brew --prefix llvm@14)/bin/clang-format" /usr/local/bin/clang-format-14 \ - || echo 'WARNING: could not install clang-format-14, which is useful if you plan to contribute C/C++ code to the OpenThread project.' + brew install llvm@14 && \ + sudo ln -s "$(brew --prefix llvm@14)/bin/clang-format" /usr/local/bin/clang-format-14 && \ + sudo ln -s "$(brew --prefix llvm@14)/bin/clang-tidy" /usr/local/bin/clang-tidy-14 && \ + sudo ln -s "$(brew --prefix llvm@14)/bin/clang-apply-replacements" /usr/local/bin/clang-apply-replacements-14 && \ + sudo ln -s "$(brew --prefix llvm@14)/bin/run-clang-tidy" /usr/local/bin/run-clang-tidy-14 || \ + echo 'WARNING: could not install clang-format-14, which is useful if you plan to contribute C/C++ code to the OpenThread project.' ## Install latest cmake match_version "$(cmake --version | grep -E -o '[0-9].*')" "${MIN_CMAKE_VERSION}" || { diff --git a/script/clang-tidy b/script/clang-tidy new file mode 100755 index 00000000..c4608092 --- /dev/null +++ b/script/clang-tidy @@ -0,0 +1,86 @@ +#!/bin/bash +# +# Copyright (c) 2020, 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. +# + +CLANG_TIDY_VERSION="LLVM version 14.0" +CLANG_APPLY_REPLACEMENTS_VERSION="clang-apply-replacements version 14.0" + +die() +{ + echo " *** ERROR: $*" + exit 1 +} + +# Search for clang-tidy-14 +if command -v clang-tidy-14 >/dev/null; then + clang_tidy=$(command -v clang-tidy-14) +elif command -v clang-tidy >/dev/null; then + clang_tidy=$(command -v clang-tidy) + case "$($clang_tidy --version)" in + *"$CLANG_TIDY_VERSION"*) ;; + + *) + die "$($clang_tidy --version); $CLANG_TIDY_VERSION required" + ;; + esac +else + die "clang-tidy 14.0 required" +fi + +# Search for clang-apply-replacements-14 +if command -v clang-apply-replacements-14 >/dev/null; then + clang_apply_replacements=$(command -v clang-apply-replacements-14) +elif command -v clang-apply-replacements >/dev/null; then + clang_apply_replacements=$(command -v clang-apply-replacements) + case "$($clang_apply_replacements --version)" in + "$CLANG_APPLY_REPLACEMENTS_VERSION"*) ;; + + *) + die "$($clang_apply_replacements --version); $CLANG_APPLY_REPLACEMENTS_VERSION required" + ;; + esac +else + die "clang-apply-replacements 14.0 required" +fi + +# Search for run-clang-tidy-14.py +if command -v run-clang-tidy-14.py >/dev/null; then + run_clang_tidy=$(command -v run-clang-tidy-14.py) +elif command -v run-clang-tidy-14 >/dev/null; then + run_clang_tidy=$(command -v run-clang-tidy-14) +elif command -v run-clang-tidy.py >/dev/null; then + run_clang_tidy=$(command -v run-clang-tidy.py) +elif command -v run-clang-tidy >/dev/null; then + run_clang_tidy=$(command -v run-clang-tidy) +else + die "run-clang-tidy.py 14.0 required" +fi + +$run_clang_tidy -clang-tidy-binary "$clang_tidy" -clang-apply-replacements-binary "$clang_apply_replacements" "$@" || die + +exit 0 diff --git a/script/make-pretty b/script/make-pretty index c9ffae45..a90f2352 100755 --- a/script/make-pretty +++ b/script/make-pretty @@ -37,6 +37,7 @@ # Format c/c++ only: # # script/make-pretty clang +# script/make-pretty clang-tidy # # Format markdown only: # @@ -49,18 +50,27 @@ # Check only: # # script/make-pretty check clang +# script/make-pretty check clang-tidy # script/make-pretty check markdown # script/make-pretty check python # set -euo pipefail +readonly OT_COMM_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd ) + readonly OT_BUILD_JOBS=$(getconf _NPROCESSORS_ONLN) readonly OT_EXCLUDE_DIRS=(third_party) readonly OT_CLANG_SOURCES=('*.c' '*.cc' '*.cpp' '*.h' '*.hpp') readonly OT_MARKDOWN_SOURCES=('*.md') readonly OT_PYTHON_SOURCES=('*.py') +readonly OT_CLANG_TIDY_FIX_DIRS=("${OT_COMM_DIR}/include" "${OT_COMM_DIR}/src" "${OT_COMM_DIR}/tests") + +OT_CLANG_TIDY_BUILD_OPTS=( + '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON' +) +readonly OT_CLANG_TIDY_BUILD_OPTS do_clang_format() { @@ -82,6 +92,30 @@ do_clang_check() | xargs -n3 -P"${OT_BUILD_JOBS}" script/clang-format-check } +do_clang_tidy_fix() +{ + echo -e '========================================' + echo -e ' format c/c++ (clang-tidy)' + echo -e '========================================' + + (mkdir -p ./build/cmake-tidy \ + && cd ./build/cmake-tidy \ + && cmake "${OT_CLANG_TIDY_BUILD_OPTS[@]}" ../.. \ + && ../../script/clang-tidy -j"$OT_BUILD_JOBS" "${OT_CLANG_TIDY_FIX_DIRS[@]}" -fix) +} + +do_clang_tidy_check() +{ + echo -e '========================================' + echo -e ' check c/c++ (clang-tidy)' + echo -e '========================================' + + (mkdir -p ./build/cmake-tidy \ + && cd ./build/cmake-tidy \ + && cmake "${OT_CLANG_TIDY_BUILD_OPTS[@]}" ../.. \ + && ../../script/clang-tidy -j"$OT_BUILD_JOBS" "${OT_CLANG_TIDY_FIX_DIRS[@]}") +} + do_markdown_format() { echo -e '======================' @@ -126,10 +160,13 @@ do_check() { if [ $# == 0 ]; then do_clang_check + do_clang_tidy_check do_markdown_check do_python_check elif [ "$1" == 'clang' ]; then do_clang_check + elif [ "$1" == 'clang-tidy' ]; then + do_clang_tidy_check elif [ "$1" == 'markdown' ]; then do_markdown_check elif [ "$1" == 'python' ]; then @@ -149,6 +186,8 @@ main() do_python_format elif [ "$1" == 'clang' ]; then do_clang_format + elif [ "$1" == 'clang-tidy' ]; then + do_clang_tidy_fix elif [ "$1" == 'markdown' ]; then do_markdown_format elif [ "$1" == 'python' ]; then diff --git a/src/app/cli/interpreter.cpp b/src/app/cli/interpreter.cpp index 613b2208..e75d66b3 100644 --- a/src/app/cli/interpreter.cpp +++ b/src/app/cli/interpreter.cpp @@ -31,25 +31,49 @@ * The file implements CLI interpreter. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include #include +#include +#include #include #include #include #include +#include +#include #include +#include -#include -#include - +#include "app/border_agent.hpp" #include "app/br_discover.hpp" +#include "app/cli/console.hpp" #include "app/cli/interpreter.hpp" #include "app/cli/job_manager.hpp" +#include "app/commissioner_app.hpp" #include "app/file_util.hpp" #include "app/json.hpp" #include "app/mdns_handler.hpp" #include "app/ps/registry.hpp" +#include "app/ps/registry_entries.hpp" #include "app/sys_logger.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/address.hpp" #include "common/error_macros.hpp" #include "common/utils.hpp" @@ -153,8 +177,8 @@ Interpreter::NetworkSelectionComparator::~NetworkSelectionComparator() if (status == RegistryStatus::kSuccess && mStartWith.mValue != nwk.mXpan.mValue) { - Console::Write(nwk.mXpan == XpanId::kEmptyXpanId ? WARN_NETWORK_SELECTION_DROPPED - : WARN_NETWORK_SELECTION_CHANGED, + Console::Write(nwk.mXpan.mValue == XpanId::kEmptyXpanId ? WARN_NETWORK_SELECTION_DROPPED + : WARN_NETWORK_SELECTION_CHANGED, Console::Color::kYellow); } } @@ -375,7 +399,7 @@ Error Interpreter::UpdateNetworkSelectionInfo(bool onStart /*=false*/) VerifyOrExit(mRegistry->GetCurrentNetwork(nwk) == Registry::Status::kSuccess, error = ERROR_REGISTRY_ERROR(RUNTIME_CUR_NETWORK_FAILED)); - if (onStart && nwk.mXpan != XpanId::kEmptyXpanId) + if (onStart && nwk.mXpan.mValue != XpanId::kEmptyXpanId) { Console::Write(fmt::format(FMT_STRING("Network selection recalled from previous session.\n" "Restored to [{}:'{}']"), @@ -817,7 +841,7 @@ void Interpreter::PrintOrExport(const Value &aValue) void Interpreter::PrintNetworkMessage(uint64_t aNid, std::string aMessage, Console::Color aColor) { - std::string nidHex = XpanId(aNid); + std::string nidHex = std::string(XpanId(aNid)); PrintNetworkMessage(nidHex, aMessage, aColor); } @@ -1202,12 +1226,12 @@ Interpreter::Value Interpreter::ProcessBr(const Expression &aExpr) } else { - for (auto iter = json.begin(); iter != json.end(); ++iter) + for (const auto &jsonObject : json) { BorderAgent ba; try { - BorderAgentFromJson(ba, *iter); + BorderAgentFromJson(ba, jsonObject); } catch (std::exception &e) { ExitNow(value = ERROR_BAD_FORMAT("incorrect border agent JSON format: {}", e.what())); @@ -1440,7 +1464,7 @@ Interpreter::Value Interpreter::ProcessBr(const Expression &aExpr) auto mdnsCancelEventQueue = [](evutil_socket_t aSocket, short aWhat, void *aArg) { (void)aSocket; (void)aWhat; - event_base *ev_base = (event_base *)aArg; + event_base *ev_base = static_cast(aArg); event_base_loopbreak(ev_base); }; // Attach cancel pipe to event loop. When bytes written to the @@ -2047,7 +2071,7 @@ Interpreter::Value Interpreter::ProcessOpDatasetJob(CommissionerAppPtr &aCommiss else { SuccessOrExit(value = aCommissioner->GetPanId(panid)); - value = std::to_string(panid); + value = std::string(panid); } } else if (CaseInsensitiveEqual(aExpr[2], "pskc")) @@ -2112,10 +2136,7 @@ Interpreter::Value Interpreter::ProcessOpDatasetJob(CommissionerAppPtr &aCommiss { if ((dataset.mPresentFlags & ActiveOperationalDataset::kPanIdBit) != 0) { - std::ostringstream panIdStream; - panIdStream << "0x" << std::hex << std::setfill('0') << std::setw(4) << std::uppercase - << dataset.mPanId; - nwkAliases.push_back(panIdStream.str()); + nwkAliases.push_back(fmt::format(FMT_STRING("0x{:04X}"), dataset.mPanId.mValue)); } else if ((dataset.mPresentFlags & ActiveOperationalDataset::kNetworkNameBit) != 0) { diff --git a/src/app/cli/interpreter.hpp b/src/app/cli/interpreter.hpp index 57283fab..2423bae7 100644 --- a/src/app/cli/interpreter.hpp +++ b/src/app/cli/interpreter.hpp @@ -35,11 +35,20 @@ #define OT_COMM_APP_CLI_INTERPRETER_HPP_ #include +#include +#include +#include +#include +#include +#include +#include #include "app/border_agent.hpp" #include "app/cli/console.hpp" #include "app/commissioner_app.hpp" #include "app/ps/registry.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" namespace ot { @@ -179,7 +188,7 @@ class Interpreter * * @see @ref Interpreter::MultiNetCommandContext */ - Error ReParseMultiNetworkSyntax(const Expression &aExpr, Expression &aRretExpr); + Error ReParseMultiNetworkSyntax(const Expression &aExpr, Expression &aRetExpr); /** * Updates on-screen visualization of the current network * selection. diff --git a/src/app/cli/interpreter_test.cpp b/src/app/cli/interpreter_test.cpp index b6dfe00b..f14860d9 100644 --- a/src/app/cli/interpreter_test.cpp +++ b/src/app/cli/interpreter_test.cpp @@ -30,9 +30,28 @@ * @file Interpreter unit tests */ +#include "app/border_agent.hpp" +#include "app/commissioner_app.hpp" +#include "app/ps/persistent_storage.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" +#include "fmt/core.h" #include "gmock/gmock.h" +#include "nlohmann/json.hpp" +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include #define private public @@ -50,7 +69,6 @@ using namespace ot::commissioner::persistent_storage; using testing::_; using testing::DoAll; -using testing::Mock; using testing::Return; using testing::ReturnRef; using testing::StrEq; @@ -83,7 +101,7 @@ class InterpreterTestSuite : public testing::Test // Minimum test setup: create config file const std::string configFile = "./config"; auto error = WriteFile("{\"ThreadSMRoot\": \"./\"}", configFile); - ASSERT_EQ(error.mCode, ErrorCode::kNone); + ASSERT_EQ(error.GetCode(), ErrorCode::kNone); ASSERT_NE(ctx.mDefaultCommissionerObject, nullptr); @@ -93,7 +111,7 @@ class InterpreterTestSuite : public testing::Test Return(Error{}))); auto result = ctx.mInterpreter.Init("./config", ""); - ASSERT_EQ(result.mCode, ErrorCode::kNone); + ASSERT_EQ(result.GetCode(), ErrorCode::kNone); ctx.mRegistry = ctx.mInterpreter.mRegistry.get(); @@ -124,7 +142,7 @@ TEST_F(InterpreterTestSuite, MNSV_ValidSyntaxPass) "", 0, 0x1F | BorderAgent::kDomainNameBit}), RegistryStatus::kSuccess); BorderRouter br; - br.mNetworkId = 0; + br.mNetworkId = NetworkId{0}; ASSERT_EQ(ctx.mRegistry->SetCurrentNetwork(br), RegistryStatus::kSuccess); std::string command; @@ -134,7 +152,7 @@ TEST_F(InterpreterTestSuite, MNSV_ValidSyntaxPass) command = "start --nwk all"; expr = ctx.mInterpreter.ParseExpression(command); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); ctx.mInterpreter.mContext.Cleanup(); ctx.mInterpreter.mJobManager->CleanupJobs(); @@ -143,7 +161,7 @@ TEST_F(InterpreterTestSuite, MNSV_ValidSyntaxPass) command = "start --nwk this"; expr = ctx.mInterpreter.ParseExpression(command); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); ctx.mInterpreter.mContext.Cleanup(); ctx.mInterpreter.mJobManager->CleanupJobs(); @@ -152,7 +170,7 @@ TEST_F(InterpreterTestSuite, MNSV_ValidSyntaxPass) command = "start --nwk other"; expr = ctx.mInterpreter.ParseExpression(command); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); ctx.mInterpreter.mContext.Cleanup(); ctx.mInterpreter.mJobManager->CleanupJobs(); @@ -161,7 +179,7 @@ TEST_F(InterpreterTestSuite, MNSV_ValidSyntaxPass) command = "start --nwk net1 net2"; expr = ctx.mInterpreter.ParseExpression(command); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); ctx.mInterpreter.mContext.Cleanup(); ctx.mInterpreter.mJobManager->CleanupJobs(); @@ -170,7 +188,7 @@ TEST_F(InterpreterTestSuite, MNSV_ValidSyntaxPass) command = "start --dom domain1"; expr = ctx.mInterpreter.ParseExpression(command); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); ctx.mInterpreter.mContext.Cleanup(); ctx.mInterpreter.mJobManager->CleanupJobs(); @@ -186,7 +204,7 @@ TEST_F(InterpreterTestSuite, MNSV_TwoGroupNwkAliasesFail) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk all other"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_FALSE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); } @@ -199,13 +217,13 @@ TEST_F(InterpreterTestSuite, MNSV_ThisResolvesWithCurrentSet) "", 0, 0x1F | BorderAgent::kDomainNameBit}), RegistryStatus::kSuccess); BorderRouter br; - br.mNetworkId = 0; + br.mNetworkId = NetworkId{0}; ASSERT_EQ(ctx.mRegistry->SetCurrentNetwork(br), RegistryStatus::kSuccess); Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk this"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); } @@ -221,7 +239,7 @@ TEST_F(InterpreterTestSuite, MNSV_ThisUnresolvesWithCurrentUnset) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk this"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_FALSE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_EQ(nids.size(), 0); } @@ -245,7 +263,7 @@ TEST_F(InterpreterTestSuite, MNSV_AllOtherSameWithCurrentUnselected) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk all"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{1}), nids.end()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{2}), nids.end()); @@ -255,7 +273,7 @@ TEST_F(InterpreterTestSuite, MNSV_AllOtherSameWithCurrentUnselected) nids.clear(); expr = ctx.mInterpreter.ParseExpression("start --nwk other"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{1}), nids.end()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{2}), nids.end()); @@ -280,13 +298,13 @@ TEST_F(InterpreterTestSuite, MNSV_AllOtherDifferWithCurrentSelected) 0, 0x1F | BorderAgent::kDomainNameBit | BorderAgent::kExtendedPanIdBit}), RegistryStatus::kSuccess); BorderRouter br; - br.mNetworkId = 0; + br.mNetworkId = NetworkId{0}; ASSERT_EQ(ctx.mRegistry->SetCurrentNetwork(br), RegistryStatus::kSuccess); Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk all"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{1}), nids.end()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{2}), nids.end()); @@ -296,7 +314,7 @@ TEST_F(InterpreterTestSuite, MNSV_AllOtherDifferWithCurrentSelected) nids.clear(); expr = ctx.mInterpreter.ParseExpression("start --nwk other"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_EQ(std::find(nids.begin(), nids.end(), XpanId{1}), nids.end()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{2}), nids.end()); @@ -324,7 +342,7 @@ TEST_F(InterpreterTestSuite, MNSV_TwoDomSwitchesFail) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --dom domain1 --dom domain2"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_FALSE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); } @@ -341,7 +359,7 @@ TEST_F(InterpreterTestSuite, MNSV_UnexistingDomainResolveFails) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --dom domain2"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_FALSE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); } @@ -363,7 +381,7 @@ TEST_F(InterpreterTestSuite, MNSV_ExistingDomainResolves) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --dom domain1"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_NE(std::find(nids.begin(), nids.end(), XpanId{1}), nids.end()); EXPECT_EQ(std::find(nids.begin(), nids.end(), XpanId{2}), nids.end()); @@ -375,7 +393,8 @@ TEST_F(InterpreterTestSuite, MNSV_AmbiguousNwkResolutionFails) InitContext(ctx); NetworkId nid; - ASSERT_EQ(ctx.mRegistry->mStorage->Add(Network{EMPTY_ID, EMPTY_ID, "net1", 1, 0, 0xAB, "", 0}, nid), + ASSERT_EQ(ctx.mRegistry->mStorage->Add( + Network{NetworkId{EMPTY_ID}, DomainId{EMPTY_ID}, "net1", XpanId{1}, 0, 0xAB, "", 0}, nid), PersistentStorage::Status::kSuccess); ASSERT_EQ( ctx.mRegistry->Add(BorderAgent{"127.0.0.1", 20001, ByteArray{}, "1.1", BorderAgent::State{0, 0, 0, 0, 0}, @@ -387,14 +406,15 @@ TEST_F(InterpreterTestSuite, MNSV_AmbiguousNwkResolutionFails) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk ab"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_EQ(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).mError.GetCode(), ErrorCode::kNone); EXPECT_EQ(nids.size(), 1); EXPECT_EQ(nids[0], XpanId{1}); ctx.mInterpreter.mContext.Cleanup(); // create ambiguity by adding another network with the same PAN ID - ASSERT_EQ(ctx.mRegistry->mStorage->Add(Network{EMPTY_ID, EMPTY_ID, "net2", 2, 0, 0xAB, "", 0}, nid), + ASSERT_EQ(ctx.mRegistry->mStorage->Add( + Network{NetworkId{EMPTY_ID}, DomainId{EMPTY_ID}, "net2", XpanId{2}, 0, 0xAB, "", 0}, nid), PersistentStorage::Status::kSuccess); ASSERT_EQ( ctx.mRegistry->Add(BorderAgent{"127.0.0.2", 20001, ByteArray{}, "1.1", BorderAgent::State{0, 0, 0, 0, 0}, @@ -404,7 +424,7 @@ TEST_F(InterpreterTestSuite, MNSV_AmbiguousNwkResolutionFails) // the same lookup must fail expr = ctx.mInterpreter.ParseExpression("start --nwk ab"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_EQ(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).mError.GetCode(), ErrorCode::kRegistryError); } @@ -426,7 +446,7 @@ TEST_F(InterpreterTestSuite, MNSV_SameResolutionFromTwoAliasesCollapses) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk 1 net1"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_EQ(nids.size(), 1); } @@ -449,7 +469,7 @@ TEST_F(InterpreterTestSuite, MNSV_GroupAndIndividualNwkAliasesMustFail) Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --nwk 1 all"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_FALSE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); } @@ -468,13 +488,13 @@ TEST_F(InterpreterTestSuite, MNSV_DomThisResolvesWithRespectToSelection) 0, 0x1F | BorderAgent::kDomainNameBit | BorderAgent::kExtendedPanIdBit}), RegistryStatus::kSuccess); BorderRouter br; - br.mNetworkId = 0; + br.mNetworkId = NetworkId{0}; ASSERT_EQ(ctx.mRegistry->SetCurrentNetwork(br), RegistryStatus::kSuccess); Interpreter::Expression expr, ret; XpanIdArray nids; expr = ctx.mInterpreter.ParseExpression("start --dom this"); - EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_EQ(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); EXPECT_TRUE(ctx.mInterpreter.ValidateMultiNetworkSyntax(ret, nids).HasNoError()); EXPECT_EQ(nids.size(), 1); EXPECT_EQ(nids[0], XpanId{1}); @@ -505,7 +525,7 @@ TEST_F(InterpreterTestSuite, MNSV_NoAliasesResolvesToThisNwk) 0, 0x1F | BorderAgent::kDomainNameBit | BorderAgent::kExtendedPanIdBit}), RegistryStatus::kSuccess); BorderRouter br; - br.mNetworkId = 2; + br.mNetworkId = NetworkId{2}; ASSERT_EQ(ctx.mRegistry->SetCurrentNetwork(br), RegistryStatus::kSuccess); XpanId nid; ASSERT_EQ(ctx.mRegistry->GetCurrentNetworkXpan(nid), RegistryStatus::kSuccess); @@ -553,10 +573,10 @@ TEST_F(InterpreterTestSuite, MNSV_EmptyNwkOrDomMustFail) Interpreter::Expression expr, ret; expr = ctx.mInterpreter.ParseExpression("start --nwk"); - EXPECT_NE(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_NE(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); expr = ctx.mInterpreter.ParseExpression("start --dom"); - EXPECT_NE(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).mCode, ErrorCode::kNone); + EXPECT_NE(ctx.mInterpreter.ReParseMultiNetworkSyntax(expr, ret).GetCode(), ErrorCode::kNone); } // Import/Export Syntax Validation test group @@ -642,7 +662,7 @@ TEST_F(InterpreterTestSuite, IESV_SingleImportFileMustPass) }\n\ }"; - EXPECT_EQ(WriteFile(jsonStr, "./json.json").mCode, ErrorCode::kNone); + EXPECT_EQ(WriteFile(jsonStr, "./json.json").GetCode(), ErrorCode::kNone); EXPECT_CALL(*commissionerAppMock, SetActiveDataset(_)).WillOnce(Return(Error{})); expr = ctx.mInterpreter.ParseExpression("opdataset set active --import ./json.json"); @@ -939,7 +959,7 @@ TEST_F(InterpreterTestSuite, PC_StartLegacySyntaxErrorFails) RegistryStatus::kSuccess); BorderRouter br; - br.mNetworkId = 0; + br.mNetworkId = NetworkId{0}; ASSERT_EQ(ctx.mRegistry->SetCurrentNetwork(br), RegistryStatus::kSuccess); EXPECT_CALL(*ctx.mDefaultCommissionerObject, Start(_, _, _)) @@ -1095,7 +1115,7 @@ TEST_F(InterpreterTestSuite, PC_Token) value = ctx.mInterpreter.Eval(expr); EXPECT_TRUE(value.HasNoError()); - EXPECT_EQ(WriteFile("123aef", "./token").mCode, ErrorCode::kNone); + EXPECT_EQ(WriteFile("123aef", "./token").GetCode(), ErrorCode::kNone); EXPECT_CALL(*ctx.mDefaultCommissionerObject, SetToken(_)).WillOnce(Return(Error{})); EXPECT_CALL(*ctx.mDefaultCommissionerObject, GetToken()).WillOnce(ReturnRef(token)); expr = ctx.mInterpreter.ParseExpression("token set ./token"); @@ -1153,7 +1173,7 @@ TEST_F(InterpreterTestSuite, PC_TokenWithCCM) EXPECT_CALL(*pcaMock, SetToken(_)).WillOnce(Return(Error{})); // note: again, we do not expect GetToken() here, same reason - EXPECT_EQ(WriteFile("123aef", "./token").mCode, ErrorCode::kNone); + EXPECT_EQ(WriteFile("123aef", "./token").GetCode(), ErrorCode::kNone); expr = ctx.mInterpreter.ParseExpression("token set ./token"); value = ctx.mInterpreter.Eval(expr); EXPECT_TRUE(value.HasNoError()); @@ -1205,7 +1225,7 @@ TEST_F(InterpreterTestSuite, PC_TokenWithNonCCM) // note: we do not expect GetToken() here as no default config // update to happen with a network selected - EXPECT_EQ(WriteFile("123aef", "./token").mCode, ErrorCode::kNone); + EXPECT_EQ(WriteFile("123aef", "./token").GetCode(), ErrorCode::kNone); expr = ctx.mInterpreter.ParseExpression("token set ./token"); value = ctx.mInterpreter.Eval(expr); EXPECT_TRUE(value.HasNoError()); @@ -1237,7 +1257,7 @@ TEST_F(InterpreterTestSuite, PC_TokenWithNone) // GetToken() to be called on default commissioner instance EXPECT_CALL(*ctx.mDefaultCommissionerObject, GetToken()).WillOnce(ReturnRef(token)); - EXPECT_EQ(WriteFile("123aef", "./token").mCode, ErrorCode::kNone); + EXPECT_EQ(WriteFile("123aef", "./token").GetCode(), ErrorCode::kNone); expr = ctx.mInterpreter.ParseExpression("token set ./token"); value = ctx.mInterpreter.Eval(expr); EXPECT_TRUE(value.HasNoError()); @@ -1803,7 +1823,7 @@ TEST_F(InterpreterTestSuite, PC_OpdatasetGetActive) EXPECT_TRUE(value.HasNoError()); EXPECT_EQ(ctx.mRegistry->mStorage->Get(nwk_id, nwk), PersistentStorage::Status::kSuccess); - EXPECT_EQ(nwk.mPan, 0x0001); + EXPECT_EQ(nwk.mPan.mValue, 0x0001); EXPECT_EQ(system("rm -f ./aods.json"), 0); EXPECT_NE(PathExists("./aods.json").GetCode(), ErrorCode::kNone); @@ -2883,7 +2903,7 @@ TEST_F(InterpreterTestSuite, MNI_MultiEntryImportExplicitNetworkPass) }\n\ }"; const std::string mepdsFileName = "./mepds.json"; - ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).mCode, ErrorCode::kNone); + ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).GetCode(), ErrorCode::kNone); ASSERT_NE(ctx.mRegistry, nullptr); ASSERT_EQ(ctx.mRegistry->Add(BorderAgent{"127.0.0.1", 20001, ByteArray{}, "1.1", BorderAgent::State{0, 0, 0, 0, 0}, @@ -2965,7 +2985,7 @@ TEST_F(InterpreterTestSuite, MNI_MultiEntryImportImplicitNetworkPass) }\n\ }"; const std::string mepdsFileName = "./mepds.json"; - ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).mCode, ErrorCode::kNone); + ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).GetCode(), ErrorCode::kNone); ASSERT_NE(ctx.mRegistry, nullptr); ASSERT_EQ(ctx.mRegistry->Add(BorderAgent{"127.0.0.1", 20001, ByteArray{}, "1.1", BorderAgent::State{0, 0, 0, 0, 0}, @@ -3026,7 +3046,7 @@ TEST_F(InterpreterTestSuite, MNI_SingleEntryImportExplicitNetworkPass) }\n\ }"; const std::string mepdsFileName = "./mepds.json"; - ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).mCode, ErrorCode::kNone); + ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).GetCode(), ErrorCode::kNone); ASSERT_NE(ctx.mRegistry, nullptr); ASSERT_EQ(ctx.mRegistry->Add(BorderAgent{"127.0.0.1", 20001, ByteArray{}, "1.1", BorderAgent::State{0, 0, 0, 0, 0}, @@ -3085,7 +3105,7 @@ TEST_F(InterpreterTestSuite, MNI_SingleEntryImportImplicitNetworkPass) }\n\ }"; const std::string mepdsFileName = "./mepds.json"; - ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).mCode, ErrorCode::kNone); + ASSERT_EQ(WriteFile(multiEntryPendingDataset, mepdsFileName).GetCode(), ErrorCode::kNone); ASSERT_NE(ctx.mRegistry, nullptr); ASSERT_EQ(ctx.mRegistry->Add(BorderAgent{"127.0.0.1", 20001, ByteArray{}, "1.1", BorderAgent::State{0, 0, 0, 0, 0}, diff --git a/src/app/cli/job.hpp b/src/app/cli/job.hpp index 7ff1492f..b23cfb29 100644 --- a/src/app/cli/job.hpp +++ b/src/app/cli/job.hpp @@ -34,10 +34,12 @@ #ifndef OT_COMM_APP_CLI_JOB_HPP_ #define OT_COMM_APP_CLI_JOB_HPP_ +#include +#include #include #include "app/cli/interpreter.hpp" -#include "app/commissioner_app.hpp" +#include "commissioner/network_data.hpp" namespace ot { diff --git a/src/app/cli/job_manager.cpp b/src/app/cli/job_manager.cpp index 345920c8..fcb8f0be 100644 --- a/src/app/cli/job_manager.cpp +++ b/src/app/cli/job_manager.cpp @@ -32,14 +32,25 @@ */ #include "app/cli/job_manager.hpp" +#include +#include +#include +#include "app/border_agent.hpp" +#include "app/cli/console.hpp" #include "app/cli/interpreter.hpp" #include "app/cli/job.hpp" #include "app/cli/security_materials.hpp" +#include "app/commissioner_app.hpp" #include "app/json.hpp" -#include "app/ps/registry.hpp" +#include "app/ps/registry_entries.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/error_macros.hpp" #include "common/logging.hpp" #include "common/utils.hpp" +#include "nlohmann/json.hpp" #define SYNTAX_IMPORT_UNSUPPORTED "import usupported" @@ -92,7 +103,7 @@ void JobManager::CleanupJobs() { for (auto job : mJobPool) { - ASSERT(job == NULL || job->IsStopped()); + ASSERT(job == nullptr || job->IsStopped()); delete job; } mJobPool.clear(); @@ -122,12 +133,16 @@ Error JobManager::CreateJob(CommissionerAppPtr &aCommissioner, const Interpreter Error JobManager::PrepareJobs(const Interpreter::Expression &aExpr, const XpanIdArray &aNids, bool aGroupAlias) { + Error error; + if (utils::ToLower(aExpr[0]) == "start") - return PrepareStartJobs(aExpr, aNids, aGroupAlias); + { + ExitNow(error = PrepareStartJobs(aExpr, aNids, aGroupAlias)); + } else if (utils::ToLower(aExpr[0]) == "stop") - return PrepareStopJobs(aExpr, aNids, aGroupAlias); - - Error error; + { + ExitNow(error = PrepareStopJobs(aExpr, aNids, aGroupAlias)); + } for (const auto &nid : aNids) { @@ -169,6 +184,7 @@ Error JobManager::PrepareJobs(const Interpreter::Expression &aExpr, const XpanId SuccessOrExit(error = CreateJob(entry->second, jobExpr, nid)); } + exit: return error; } @@ -603,7 +619,7 @@ void JobManager::RunJobs() { for (auto job : mJobPool) { - ASSERT(job != NULL); + ASSERT(job != nullptr); job->Run(); } WaitForJobs(); @@ -616,7 +632,7 @@ void JobManager::CancelCommand() for (auto job : mJobPool) { - ASSERT(job != NULL); + ASSERT(job != nullptr); job->Cancel(); } WaitForJobs(); @@ -639,7 +655,7 @@ void JobManager::WaitForJobs() { for (auto job : mJobPool) { - ASSERT(job != NULL); + ASSERT(job != nullptr); job->Wait(); } } @@ -655,7 +671,7 @@ Interpreter::Value JobManager::CollectJobsValue() ASSERT(job->IsStopped()); if (job->GetValue().HasNoError()) { - xpan = job->GetXpanId(); + xpan = XpanId{job->GetXpanId()}; try { std::string valueStr = job->GetValue().ToString(); @@ -672,12 +688,12 @@ Interpreter::Value JobManager::CollectJobsValue() json[xpan.str()] = nlohmann::json::parse(valueStr); } catch (std::exception &e) { - ErrorMsg(xpan.mValue, e.what()); + ErrorMsg(xpan, e.what()); } } else // produce error messages immediately before printing value { - ErrorMsg(job->GetXpanId(), job->GetValue().ToString()); + ErrorMsg(XpanId{job->GetXpanId()}, job->GetValue().ToString()); } } value = json.dump(JSON_INDENT_DEFAULT); @@ -706,7 +722,7 @@ Error JobManager::GetSelectedCommissioner(CommissionerAppPtr &aCommissioner) status = mInterpreter.mRegistry->GetCurrentNetworkXpan(nid); VerifyOrExit(RegistryStatus::kSuccess == status, error = ERROR_REGISTRY_ERROR("getting selected network failed")); - if (nid != XpanId::kEmptyXpanId) + if (nid.mValue != XpanId::kEmptyXpanId) { auto entry = mCommissionerPool.find(nid); if (entry != mCommissionerPool.end()) @@ -744,17 +760,17 @@ bool JobManager::IsClean() void JobManager::ErrorMsg(XpanId aNid, std::string aMessage) { - mInterpreter.PrintNetworkMessage(aNid, aMessage, Console::Color::kRed); + mInterpreter.PrintNetworkMessage(aNid.mValue, aMessage, Console::Color::kRed); } void JobManager::WarningMsg(XpanId aNid, std::string aMessage) { - mInterpreter.PrintNetworkMessage(aNid, aMessage, Console::Color::kMagenta); + mInterpreter.PrintNetworkMessage(aNid.mValue, aMessage, Console::Color::kMagenta); } void JobManager::InfoMsg(XpanId aNid, std::string aMessage) { - mInterpreter.PrintNetworkMessage(aNid, aMessage, Console::Color::kDefault); + mInterpreter.PrintNetworkMessage(aNid.mValue, aMessage, Console::Color::kDefault); } } // namespace commissioner diff --git a/src/app/cli/job_manager.hpp b/src/app/cli/job_manager.hpp index 3b6cc146..dae006b0 100644 --- a/src/app/cli/job_manager.hpp +++ b/src/app/cli/job_manager.hpp @@ -35,6 +35,7 @@ #define OT_COMM_APP_CLI_JOB_MANAGER_HPP_ #include "app/cli/interpreter.hpp" +#include "app/cli/job.hpp" #include "app/commissioner_app.hpp" #include "app/ps/registry_entries.hpp" @@ -47,8 +48,6 @@ using RegistryStatus = ot::commissioner::persistent_storage::Registry::Statu using ot::commissioner::XpanId; using ot::commissioner::persistent_storage::BorderRouter; -class Job; - class JobManager { public: diff --git a/src/app/cli/job_manager_test.cpp b/src/app/cli/job_manager_test.cpp index 18376032..acab6733 100644 --- a/src/app/cli/job_manager_test.cpp +++ b/src/app/cli/job_manager_test.cpp @@ -30,24 +30,40 @@ * @file Job manager unit tests */ -#include "gmock/gmock.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include #define private public +#include "app/border_agent.hpp" #include "app/cli/interpreter.hpp" -#include "app/cli/job.hpp" #include "app/cli/job_manager.hpp" +#include "app/commissioner_app.hpp" #include "app/commissioner_app_mock.hpp" #include "app/file_util.hpp" +#include "app/ps/persistent_storage.hpp" #include "app/ps/persistent_storage_json.hpp" #include "app/ps/registry.hpp" +#include "app/ps/registry_entries.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" using namespace ot::commissioner; using testing::_; using testing::DoAll; using testing::Invoke; -using testing::Mock; using testing::Return; using testing::WithArg; using testing::WithArgs; @@ -63,10 +79,7 @@ class JobManagerTestSuite : public testing::Test struct TestContext { TestContext() - : mPS{} - , mRegistry{} - , mConf{} - , mInterpreter{} + : mConf{} , mJobManager{mInterpreter} , mDefaultCommissioner{new CommissionerAppMock()} { @@ -86,10 +99,7 @@ class JobManagerTestSuite : public testing::Test CommissionerAppStaticExpecter mCommissionerAppStaticExpecter; }; - JobManagerTestSuite() - : Test() - { - } + JobManagerTestSuite() = default; virtual ~JobManagerTestSuite() = default; void SetInitialExpectations(TestContext &aContext) diff --git a/src/app/cli/main.cpp b/src/app/cli/main.cpp index aee82786..218594f0 100644 --- a/src/app/cli/main.cpp +++ b/src/app/cli/main.cpp @@ -31,13 +31,18 @@ * The file is the entrance of the commissioner CLI. */ +#include #include +#include +#include #include #include +#include "app/cli/console.hpp" #include "app/cli/interpreter.hpp" -#include "app/ps/registry.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/error.hpp" #include "common/utils.hpp" using namespace ot::commissioner; @@ -119,7 +124,7 @@ int main(int argc, const char *argv[]) while (parseParams) { - ch = getopt_long(argc, (char *const *)argv, "hvc:r:", gCommissionerCliOptions, nullptr); + ch = getopt_long(argc, const_cast(argv), "hvc:r:", gCommissionerCliOptions, nullptr); switch (ch) { case 'h': diff --git a/src/app/cli/security_materials.cpp b/src/app/cli/security_materials.cpp index 702f5a8b..2dc63a45 100644 --- a/src/app/cli/security_materials.cpp +++ b/src/app/cli/security_materials.cpp @@ -32,11 +32,20 @@ */ #include "app/cli/security_materials.hpp" +#include +#include +#include +#include #include "app/cli/console.hpp" #include "app/file_util.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" #include "common/error_macros.hpp" #include "common/logging.hpp" #include "common/utils.hpp" +#include "fmt/core.h" +#include "fmt/format.h" #define SM_ERROR_MESSAGE_NO_ROOT_AVAILABLE "ThreadSMRoot value is not available" #define SM_ERROR_MESSAGE_PEM_READ_FAILED "Failed to read security data from file {}" @@ -49,8 +58,8 @@ namespace security_material { using SMPair = std::pair; -static Error GetNetworkSMImpl(const std::string aNwkFolder, // a folder to start from - const std::string aAlias, // network id or network name +static Error GetNetworkSMImpl(const std::string &aNwkFolder, // a folder to start from + const std::string &aAlias, // network id or network name bool aNeedCert, bool aNeedPSKc, SecurityMaterials &aSM); @@ -94,7 +103,7 @@ Error Init(const Config &aDefaultConfig) return ERROR_NONE; } -Error GetDomainSM(const std::string aDid, SecurityMaterials &aSM) +Error GetDomainSM(const std::string &aDid, SecurityMaterials &aSM) { Error error; std::string domPath; @@ -151,13 +160,13 @@ Error GetDomainSM(const std::string aDid, SecurityMaterials &aSM) return error; } -Error GetNetworkSM(const std::string aAlias, bool aNeedCert, bool aNeedPSKc, SecurityMaterials &aSM) +Error GetNetworkSM(const std::string &aAlias, bool aNeedCert, bool aNeedPSKc, SecurityMaterials &aSM) { return GetNetworkSMImpl("nwk/", aAlias, aNeedCert, aNeedPSKc, aSM); } -static Error GetNetworkSMImpl(const std::string aNwkFolder, - const std::string aAlias, +static Error GetNetworkSMImpl(const std::string &aNwkFolder, + const std::string &aAlias, bool aNeedCert, bool aNeedPSKc, SecurityMaterials &aSM) @@ -228,19 +237,19 @@ static Error GetNetworkSMImpl(const std::string aNwkFolder, return error; } -bool SecurityMaterials::IsAnyFound(bool aNeedCert, bool aNeedPSKc, bool aNeedToken /*=false*/) +bool SecurityMaterials::IsAnyFound(bool aNeedCert, bool aNeedPSKc, bool aNeedToken /*=false*/) const { return (aNeedCert && (mCertificate.size() != 0 || mPrivateKey.size() != 0 || mTrustAnchor.size() != 0)) || (aNeedToken && mCommissionerToken.size() != 0) || (aNeedPSKc && mPSKc.size() != 0); } -bool SecurityMaterials::IsIncomplete(bool aNeedCert, bool aNeedPSKc, bool aNeedToken /*=false*/) +bool SecurityMaterials::IsIncomplete(bool aNeedCert, bool aNeedPSKc, bool aNeedToken /*=false*/) const { return (aNeedCert && (mCertificate.size() == 0 || mPrivateKey.size() == 0 || mTrustAnchor.size() == 0)) || (aNeedToken && mCommissionerToken.size() == 0) || (aNeedPSKc && mPSKc.size() == 0); } -bool SecurityMaterials::IsEmpty(bool isCCM) +bool SecurityMaterials::IsEmpty(bool isCCM) const { return isCCM ? mCertificate.size() == 0 && mPrivateKey.size() == 0 && mTrustAnchor.size() == 0 && mCommissionerToken.size() == 0 diff --git a/src/app/cli/security_materials.hpp b/src/app/cli/security_materials.hpp index 91088d5a..34aed8aa 100644 --- a/src/app/cli/security_materials.hpp +++ b/src/app/cli/security_materials.hpp @@ -34,7 +34,10 @@ #ifndef OT_COMM_APP_CLI_SECURITY_MATERIALS_HPP_ #define OT_COMM_APP_CLI_SECURITY_MATERIALS_HPP_ +#include + #include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" #include "commissioner/error.hpp" namespace ot { @@ -62,14 +65,14 @@ struct SecurityMaterials // See if any part of credentials is already found depending on the // credentials type - bool IsAnyFound(bool aNeedCert, bool aNeedPSKc, bool aNeedToken = false); + bool IsAnyFound(bool aNeedCert, bool aNeedPSKc, bool aNeedToken = false) const; // See if any part of credentials is missing depending on the // credentials type - bool IsIncomplete(bool aNeedCert, bool aNeedPSKc, bool aNeedToken = false); + bool IsIncomplete(bool aNeedCert, bool aNeedPSKc, bool aNeedToken = false) const; // See if entire set of credentials is empty - bool IsEmpty(bool isCCM); + bool IsEmpty(bool isCCM) const; }; /** @@ -90,7 +93,7 @@ Error Init(const Config &aDefaultConfig); * * @see JobManager::PrepareDtlsConfig() */ -Error GetDomainSM(const std::string aDid, SecurityMaterials &aSM); +Error GetDomainSM(const std::string &aDid, SecurityMaterials &aSM); /** * Finds security materials related to a network. The returned content @@ -103,7 +106,7 @@ Error GetDomainSM(const std::string aDid, SecurityMaterials &aSM); * * @see JobManager::PrepareDtlsConfig() */ -Error GetNetworkSM(const std::string aAlias, bool aNeedCert, bool aNeedPSKc, SecurityMaterials &aSM); +Error GetNetworkSM(const std::string &aAlias, bool aNeedCert, bool aNeedPSKc, SecurityMaterials &aSM); } // namespace security_material diff --git a/src/app/commissioner_app.cpp b/src/app/commissioner_app.cpp index d30df0d6..6eb7cb2b 100644 --- a/src/app/commissioner_app.cpp +++ b/src/app/commissioner_app.cpp @@ -33,10 +33,19 @@ #include "app/commissioner_app.hpp" -#include +#include +#include +#include +#include +#include +#include #include "app/file_util.hpp" #include "app/json.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/address.hpp" #include "common/error_macros.hpp" #include "common/utils.hpp" @@ -527,7 +536,7 @@ Error CommissionerApp::SetExtendedPanId(const ByteArray &aExtendedPanId) VerifyOrExit(IsActive(), error = ERROR_INVALID_STATE("the commissioner is not active")); - activeDataset.mExtendedPanId = utils::Decode(aExtendedPanId); + activeDataset.mExtendedPanId = XpanId{utils::Decode(aExtendedPanId)}; activeDataset.mPresentFlags |= ActiveOperationalDataset::kExtendedPanIdBit; SuccessOrExit(error = mCommissioner->SetActiveDataset(activeDataset)); @@ -1036,7 +1045,7 @@ bool CommissionerApp::JoinerKey::operator<(const JoinerKey &aOther) const return mType < aOther.mType || (mType == aOther.mType && mId < aOther.mId); } -CommissionerDataset CommissionerApp::MakeDefaultCommissionerDataset() +CommissionerDataset CommissionerApp::MakeDefaultCommissionerDataset() const { CommissionerDataset dataset; diff --git a/src/app/commissioner_app.hpp b/src/app/commissioner_app.hpp index 8371fe01..0764698a 100644 --- a/src/app/commissioner_app.hpp +++ b/src/app/commissioner_app.hpp @@ -39,15 +39,18 @@ #define OT_COMM_APP_COMMISSIONER_APP_HPP_ #include -#include -#include +#include +#include #include -#include -#include +#include +#include +#include #include #include +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" #include "common/address.hpp" namespace ot { @@ -269,10 +272,12 @@ class CommissionerApp : public CommissionerHandler const std::string &GetDomainName() const; +protected: + CommissionerApp() = default; + private: friend Error CommissionerAppCreate(std::shared_ptr &aCommApp, const Config &aConfig); - CommissionerApp() = default; Error Init(const Config &aConfig); static Error Create(std::shared_ptr &aCommApp, const Config &aConfig); @@ -285,7 +290,7 @@ class CommissionerApp : public CommissionerHandler bool operator<(const JoinerKey &aOther) const; }; - CommissionerDataset MakeDefaultCommissionerDataset(); + CommissionerDataset MakeDefaultCommissionerDataset() const; static ByteArray &GetSteeringData(CommissionerDataset &aDataset, JoinerType aJoinerType); static uint16_t &GetJoinerUdpPort(CommissionerDataset &aDataset, JoinerType aJoinerType); diff --git a/src/app/commissioner_app_dummy.cpp b/src/app/commissioner_app_dummy.cpp index 54038001..36eb8d3a 100644 --- a/src/app/commissioner_app_dummy.cpp +++ b/src/app/commissioner_app_dummy.cpp @@ -26,7 +26,14 @@ * POSSIBILITY OF SUCH DAMAGE. */ +#include +#include +#include #include "app/commissioner_app.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" +#include "common/address.hpp" #define UNUSED(A) (void)A diff --git a/src/app/commissioner_app_mock.hpp b/src/app/commissioner_app_mock.hpp index 31e46f02..a259887e 100644 --- a/src/app/commissioner_app_mock.hpp +++ b/src/app/commissioner_app_mock.hpp @@ -33,9 +33,19 @@ #ifndef OT_COMM_APP_COMMISSIONER_APP_MOCK_HPP_ #define OT_COMM_APP_COMMISSIONER_APP_MOCK_HPP_ -#include "gmock/gmock.h" +#include +#include +#include +#include + +#include #include "app/commissioner_app.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" +#include "common/address.hpp" using namespace ::ot::commissioner; @@ -44,6 +54,7 @@ class CommissionerAppMock : public ::ot::commissioner::CommissionerApp using Error = ::ot::commissioner::Error; public: + CommissionerAppMock() = default; virtual ~CommissionerAppMock() = default; MOCK_METHOD(std::string, OnJoinerRequest, (const ByteArray &), (override)); MOCK_METHOD(void, OnJoinerConnected, (const ByteArray &, Error), (override)); diff --git a/src/app/file_util.cpp b/src/app/file_util.cpp index 4403f009..178abe4e 100644 --- a/src/app/file_util.cpp +++ b/src/app/file_util.cpp @@ -35,11 +35,16 @@ #include "app/file_util.hpp" #include - -#include +#include +#include +#include +#include +#include #include #include +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" #include "common/error_macros.hpp" #include "common/utils.hpp" @@ -73,7 +78,7 @@ Error WriteFile(const std::string &aData, const std::string &aFilename) fputs(aData.c_str(), f); exit: - if (f != NULL) + if (f != nullptr) { fclose(f); } @@ -107,7 +112,7 @@ Error ReadFile(std::string &aData, const std::string &aFilename) } exit: - if (f != NULL) + if (f != nullptr) { fclose(f); } diff --git a/src/app/file_util_test.cpp b/src/app/file_util_test.cpp index e60a73e8..d1bb05bf 100644 --- a/src/app/file_util_test.cpp +++ b/src/app/file_util_test.cpp @@ -77,7 +77,7 @@ TEST(FileUtil, PathExists) EXPECT_TRUE(RestoreDirPath(dirName).GetCode() == ErrorCode::kNone); EXPECT_TRUE(PathExists(dirName).GetCode() == ErrorCode::kNone); FILE *f = fopen(fileName.c_str(), "w"); - if (f != NULL) + if (f != nullptr) { EXPECT_TRUE(PathExists(fileName).GetCode() == ErrorCode::kNone); fclose(f); @@ -90,7 +90,7 @@ TEST(FileUtil, PathExists) TEST(FileUtil, WriteFile) { - FILE *f = NULL; + FILE *f = nullptr; std::string path = "./test_write"; std::string test = "test"; std::string alt = "alt"; @@ -109,11 +109,11 @@ TEST(FileUtil, WriteFile) EXPECT_EQ(ReadFile(read, path), ErrorCode::kNone); EXPECT_EQ(read, alt); // write to a blocked file - EXPECT_TRUE((f = fopen(path.c_str(), "r")) != NULL); + EXPECT_TRUE((f = fopen(path.c_str(), "r")) != nullptr); EXPECT_EQ(fchmod(fileno(f), 0), 0); EXPECT_EQ(WriteFile(test, path), ErrorCode::kIOBusy); - if (f != NULL) + if (f != nullptr) { fclose(f); } diff --git a/src/app/json.cpp b/src/app/json.cpp index efbe01c0..e1131275 100644 --- a/src/app/json.cpp +++ b/src/app/json.cpp @@ -34,13 +34,23 @@ #include "app/json.hpp" +#include +#include #include -#include -#include +#include +#include +#include +#include + +#include "app/border_agent.hpp" #include "app/commissioner_app.hpp" #include "app/file_logger.hpp" #include "app/file_util.hpp" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/error_macros.hpp" #include "common/utils.hpp" @@ -410,7 +420,7 @@ static void from_json(const Json &aJson, SecurityPolicy &aSecurityPolicy) static void to_json(Json &aJson, const ot::commissioner::PanId &aPanId) { - aJson = (std::string)aPanId; + aJson = std::string(aPanId); } static void from_json(const Json &aJson, ot::commissioner::PanId &aPanId) diff --git a/src/app/mdns_handler.cpp b/src/app/mdns_handler.cpp index 39576935..c5b2affb 100644 --- a/src/app/mdns_handler.cpp +++ b/src/app/mdns_handler.cpp @@ -28,12 +28,21 @@ #include "mdns_handler.hpp" +#include +#include +#include +#include #include +#include #include "border_agent.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/address.hpp" #include "common/error_macros.hpp" #include "common/utils.hpp" +#include "mdns/mdns.h" namespace ot { @@ -49,15 +58,15 @@ static inline ByteArray ToByteArray(const mdns_string_t &aString) return ByteArray{aString.str, aString.str + aString.length}; } -int HandleRecord(const struct sockaddr *from, - mdns_entry_type_t entry, - uint16_t type, - uint16_t rclass, - uint32_t ttl, - const void *data, - size_t size, - size_t offset, - size_t length, +int HandleRecord(const struct sockaddr *aFrom, + mdns_entry_type_t aEntry, + uint16_t aType, + uint16_t aRclass, + uint32_t aTtl, + const void *aData, + size_t aSize, + size_t aOffset, + size_t aLength, void *aBorderAgent) { struct sockaddr_storage fromAddrStorage; @@ -70,10 +79,10 @@ int HandleRecord(const struct sockaddr *from, BorderAgent &borderAgent = borderAgentOrErrorMsg.mBorderAgent; Error &error = borderAgentOrErrorMsg.mError; - (void)rclass; - (void)ttl; + (void)aRclass; + (void)aTtl; - *reinterpret_cast(&fromAddrStorage) = *from; + *reinterpret_cast(&fromAddrStorage) = *aFrom; if (fromAddr.Set(fromAddrStorage) != ErrorCode::kNone) { ExitNow(error = ERROR_BAD_FORMAT("invalid source address of mDNS response")); @@ -81,29 +90,30 @@ int HandleRecord(const struct sockaddr *from, fromAddrStr = fromAddr.ToString(); - entryType = (entry == MDNS_ENTRYTYPE_ANSWER) ? "answer" - : ((entry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional"); - if (type == MDNS_RECORDTYPE_PTR) + entryType = (aEntry == MDNS_ENTRYTYPE_ANSWER) ? "answer" + : ((aEntry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional"); + if (aType == MDNS_RECORDTYPE_PTR) { - mdns_string_t nameStr = mdns_record_parse_ptr(data, size, offset, length, nameBuffer, sizeof(nameBuffer)); + mdns_string_t nameStr = mdns_record_parse_ptr(aData, aSize, aOffset, aLength, nameBuffer, sizeof(nameBuffer)); borderAgent.mServiceName = std::string(nameStr.str, nameStr.length); borderAgent.mPresentFlags = BorderAgent::kServiceNameBit; // TODO(wgtdkp): add debug logging. } - else if (type == MDNS_RECORDTYPE_SRV) + else if (aType == MDNS_RECORDTYPE_SRV) { - mdns_record_srv_t server = mdns_record_parse_srv(data, size, offset, length, nameBuffer, sizeof(nameBuffer)); + mdns_record_srv_t server = + mdns_record_parse_srv(aData, aSize, aOffset, aLength, nameBuffer, sizeof(nameBuffer)); borderAgent.mPort = server.port; borderAgent.mPresentFlags |= BorderAgent::kPortBit; } - else if (type == MDNS_RECORDTYPE_A) + else if (aType == MDNS_RECORDTYPE_A) { struct sockaddr_storage addrStorage; struct sockaddr_in addr; std::string addrStr; - mdns_record_parse_a(data, size, offset, length, &addr); + mdns_record_parse_a(aData, aSize, aOffset, aLength, &addr); *reinterpret_cast(&addrStorage) = addr; if (fromAddr.Set(addrStorage) != ErrorCode::kNone) @@ -120,13 +130,13 @@ int HandleRecord(const struct sockaddr *from, borderAgent.mPresentFlags |= BorderAgent::kAddrBit; } } - else if (type == MDNS_RECORDTYPE_AAAA) + else if (aType == MDNS_RECORDTYPE_AAAA) { struct sockaddr_storage addrStorage; struct sockaddr_in6 addr; std::string addrStr; - mdns_record_parse_aaaa(data, size, offset, length, &addr); + mdns_record_parse_aaaa(aData, aSize, aOffset, aLength, &addr); *reinterpret_cast(&addrStorage) = addr; if (fromAddr.Set(addrStorage) != ErrorCode::kNone) @@ -139,13 +149,13 @@ int HandleRecord(const struct sockaddr *from, borderAgent.mAddr = addrStr; borderAgent.mPresentFlags |= BorderAgent::kAddrBit; } - else if (type == MDNS_RECORDTYPE_TXT) + else if (aType == MDNS_RECORDTYPE_TXT) { mdns_record_txt_t txtBuffer[128]; size_t parsed; - parsed = - mdns_record_parse_txt(data, size, offset, length, txtBuffer, sizeof(txtBuffer) / sizeof(mdns_record_txt_t)); + parsed = mdns_record_parse_txt(aData, aSize, aOffset, aLength, txtBuffer, + sizeof(txtBuffer) / sizeof(mdns_record_txt_t)); for (size_t i = 0; i < parsed; ++i) { @@ -317,7 +327,7 @@ int HandleRecord(const struct sockaddr *from, if (borderAgent.mPresentFlags != 0) { // Actualize Timestamp - borderAgent.mUpdateTimestamp.mTime = time(0); + borderAgent.mUpdateTimestamp.mTime = time(nullptr); borderAgent.mPresentFlags |= BorderAgent::kUpdateTimestampBit; } exit: diff --git a/src/app/mdns_handler.hpp b/src/app/mdns_handler.hpp index e6b231c5..2716fe01 100644 --- a/src/app/mdns_handler.hpp +++ b/src/app/mdns_handler.hpp @@ -35,16 +35,16 @@ namespace ot { namespace commissioner { -int HandleRecord(const struct sockaddr *from, - mdns_entry_type_t entry, - uint16_t type, - uint16_t rclass, - uint32_t ttl, - const void *data, - size_t size, - size_t offset, - size_t length, - void *userData); +int HandleRecord(const struct sockaddr *aFrom, + mdns_entry_type_t aEntry, + uint16_t aType, + uint16_t aRclass, + uint32_t aTtl, + const void *aData, + size_t aSize, + size_t aOffset, + size_t aLength, + void *aBorderAgent); } // namespace commissioner diff --git a/src/app/ps/persistent_storage_json.cpp b/src/app/ps/persistent_storage_json.cpp index ba02e0a7..5f153961 100644 --- a/src/app/ps/persistent_storage_json.cpp +++ b/src/app/ps/persistent_storage_json.cpp @@ -32,8 +32,22 @@ */ #include "persistent_storage_json.hpp" + +#include +#include +#include +#include +#include + +#include "app/border_agent.hpp" #include "app/file_util.hpp" +#include "app/ps/persistent_storage.hpp" +#include "app/ps/registry_entries.hpp" +#include "app/ps/semaphore.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/utils.hpp" +#include "nlohmann/json.hpp" namespace ot { namespace commissioner { @@ -60,7 +74,6 @@ using SemaphoreStatus = ot::os::semaphore::SemaphoreStatus; PersistentStorageJson::PersistentStorageJson(std::string const &aFileName) : mFileName(aFileName) - , mCache() , mStorageLock() { SemaphoreOpen("thrcomm_json_storage", mStorageLock); @@ -353,13 +366,13 @@ PersistentStorage::Status PersistentStorageJson::Lookup(Network const &aValue, s { std::function pred = [](Network const &) { return true; }; - pred = [aValue](Network const &el) { + pred = [&aValue](Network const &el) { bool aRet = (aValue.mCcm < 0 || aValue.mCcm == el.mCcm) && (aValue.mId.mId == EMPTY_ID || (el.mId.mId == aValue.mId.mId)) && (aValue.mDomainId.mId == EMPTY_ID || (el.mDomainId.mId == aValue.mDomainId.mId)) && (aValue.mName.empty() || (aValue.mName == el.mName)) && (aValue.mXpan.mValue == XpanId::kEmptyXpanId || aValue.mXpan == el.mXpan) && - (aValue.mPan.mValue == PanId::kEmptyPanId || (aValue.mPan == el.mPan)) && + (aValue.mPan.mValue == PanId::kEmptyPanId || (aValue.mPan.mValue == el.mPan.mValue)) && (aValue.mMlp.empty() || CaseInsensitiveEqual(aValue.mMlp, el.mMlp)) && (aValue.mChannel == 0 || (aValue.mChannel == el.mChannel)); @@ -458,13 +471,13 @@ PersistentStorage::Status PersistentStorageJson::LookupAny(Network const &aValue { std::function pred = [](Network const &) { return true; }; - pred = [aValue](Network const &el) { + pred = [&aValue](Network const &el) { bool aRet = (aValue.mCcm < 0 || aValue.mCcm == el.mCcm) || (aValue.mId.mId == EMPTY_ID || (el.mId.mId == aValue.mId.mId)) || (aValue.mDomainId.mId == EMPTY_ID || (el.mDomainId.mId == aValue.mDomainId.mId)) || (aValue.mName.empty() || (aValue.mName == el.mName)) || (aValue.mXpan.mValue == XpanId::kEmptyXpanId || aValue.mXpan == el.mXpan) || - (aValue.mPan.mValue == PanId::kEmptyPanId || (aValue.mPan == el.mPan)) || + (aValue.mPan.mValue == PanId::kEmptyPanId || (aValue.mPan.mValue == el.mPan.mValue)) || (aValue.mMlp.empty() || CaseInsensitiveEqual(aValue.mMlp, el.mMlp)) || (aValue.mChannel == 0 || (aValue.mChannel == el.mChannel)); diff --git a/src/app/ps/persistent_storage_json.hpp b/src/app/ps/persistent_storage_json.hpp index 7c3a7f8e..79e72bed 100644 --- a/src/app/ps/persistent_storage_json.hpp +++ b/src/app/ps/persistent_storage_json.hpp @@ -35,7 +35,14 @@ #define _PERSISTENT_STORAGE_JSON_HPP_ #include "persistent_storage.hpp" -#include "semaphore.hpp" +#include +#include +#include +#include +#include +#include "app/ps/registry_entries.hpp" +#include "app/ps/semaphore_posix.hpp" +#include "nlohmann/json.hpp" namespace ot { @@ -59,7 +66,7 @@ class PersistentStorageJson : public PersistentStorage * * @param[in] aFileName file name to be used as storage */ - PersistentStorageJson(std::string const &aFileName); + explicit PersistentStorageJson(std::string const &aFileName); /** * Destructor @@ -113,15 +120,15 @@ class PersistentStorageJson : public PersistentStorage * Gets value by unique id from store * * @param[in] aId value's unique id - * @param[out] aValue value from registry + * @param[out] aRetValue value from registry * @return Status * @see Status * @see registry_entries.hpp */ - Status Get(RegistrarId const &aId, Registrar &aValue) override; - Status Get(DomainId const &aId, Domain &aValue) override; - Status Get(NetworkId const &aId, Network &aValue) override; - Status Get(BorderRouterId const &aId, BorderRouter &aValue) override; + Status Get(RegistrarId const &aId, Registrar &aRetValue) override; + Status Get(DomainId const &aId, Domain &aRetValue) override; + Status Get(NetworkId const &aId, Network &aRetValue) override; + Status Get(BorderRouterId const &aId, BorderRouter &aRetValue) override; /** * Updates value in store diff --git a/src/app/ps/registry.cpp b/src/app/ps/registry.cpp index 917ae467..8368f939 100644 --- a/src/app/ps/registry.cpp +++ b/src/app/ps/registry.cpp @@ -31,8 +31,18 @@ * The file implements JSON-based Thread networks/domains registry. */ -#include "registry.hpp" -#include "persistent_storage_json.hpp" +#include +#include +#include +#include + +#include "app/border_agent.hpp" +#include "app/ps/persistent_storage.hpp" +#include "app/ps/persistent_storage_json.hpp" +#include "app/ps/registry.hpp" +#include "app/ps/registry_entries.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/error_macros.hpp" #include "common/utils.hpp" @@ -136,7 +146,8 @@ Registry::Status Registry::Add(BorderAgent const &aValue) { return Registry::Status::kError; } - else if (status == Registry::Status::kNotFound) + + if (status == Registry::Status::kNotFound) { DomainId domainId{EMPTY_ID}; status = MapStatus(mStorage->Add(dom, domainId)); @@ -166,7 +177,7 @@ Registry::Status Registry::Add(BorderAgent const &aValue) // Decided: update network aName in the network entity if ((aValue.mPresentFlags & BorderAgent::kExtendedPanIdBit) != 0) { - nwk.mXpan = aValue.mExtendedPanId; + nwk.mXpan = XpanId{aValue.mExtendedPanId}; } else { @@ -179,7 +190,8 @@ Registry::Status Registry::Add(BorderAgent const &aValue) { throw status; } - else if (status == Registry::Status::kNotFound) + + if (status == Registry::Status::kNotFound) { NetworkId networkId{EMPTY_ID}; // It is possible we found the network by xpan @@ -189,7 +201,7 @@ Registry::Status Registry::Add(BorderAgent const &aValue) nwk.mName = aValue.mNetworkName; } nwk.mDomainId = dom.mId; - nwk.mXpan = aValue.mExtendedPanId; + nwk.mXpan = XpanId{aValue.mExtendedPanId}; // Provisionally set network's CCM flag considering // advertised Connection Mode. @@ -224,7 +236,7 @@ Registry::Status Registry::Add(BorderAgent const &aValue) } } - BorderRouter br{EMPTY_ID, nwk.mId, aValue}; + BorderRouter br{BorderRouterId{EMPTY_ID}, nwk.mId, aValue}; try { if (br.mNetworkId.mId == EMPTY_ID) @@ -331,7 +343,7 @@ Registry::Status Registry::GetNetworksInDomain(const std::string &aDomainName, N } else { - Domain dom{EMPTY_ID, aDomainName}; + Domain dom{DomainId{EMPTY_ID}, aDomainName}; VerifyOrExit((status = MapStatus(mStorage->Lookup(dom, domains))) == Registry::Status::kSuccess); } VerifyOrExit(domains.size() < 2, status = Registry::Status::kAmbiguity); @@ -523,7 +535,7 @@ Registry::Status Registry::ForgetCurrentNetwork() return SetCurrentNetwork(NetworkId{}); } -Registry::Status Registry::SetCurrentNetwork(const XpanId aXpan) +Registry::Status Registry::SetCurrentNetwork(const XpanId &aXpan) { Network nwk; Registry::Status status; @@ -582,7 +594,7 @@ Registry::Status Registry::LookupOne(const Network &aPred, Network &aRet) return status; } -Registry::Status Registry::GetNetworkByXpan(const XpanId aXpan, Network &aRet) +Registry::Status Registry::GetNetworkByXpan(const XpanId &aXpan, Network &aRet) { Network nwk{}; nwk.mXpan = aXpan; @@ -608,7 +620,7 @@ Registry::Status Registry::GetNetworkByPan(const std::string &aPan, Network &aRe return LookupOne(nwk, aRet); } -Registry::Status Registry::GetDomainNameByXpan(const XpanId aXpan, std::string &aName) +Registry::Status Registry::GetDomainNameByXpan(const XpanId &aXpan, std::string &aName) { Registry::Status status; Network nwk; @@ -621,7 +633,7 @@ Registry::Status Registry::GetDomainNameByXpan(const XpanId aXpan, std::string & return status; } -Registry::Status Registry::DeleteBorderRouterById(const BorderRouterId aRouterId) +Registry::Status Registry::DeleteBorderRouterById(const BorderRouterId &aRouterId) { Registry::Status status; BorderRouter br; @@ -778,9 +790,9 @@ Registry::Status Registry::DeleteBorderRoutersInDomain(const std::string &aDomai return status; } -Registry::Status Registry::Update(const Network &nwk) +Registry::Status Registry::Update(const Network &aNetwork) { - return MapStatus(mStorage->Update(nwk)); + return MapStatus(mStorage->Update(aNetwork)); } } // namespace persistent_storage diff --git a/src/app/ps/registry.hpp b/src/app/ps/registry.hpp index 8f1d4b30..ad24089f 100644 --- a/src/app/ps/registry.hpp +++ b/src/app/ps/registry.hpp @@ -34,11 +34,14 @@ #ifndef _REGISTRY_HPP_ #define _REGISTRY_HPP_ +#include +#include +#include + #include "persistent_storage.hpp" #include "registry_entries.hpp" #include "app/border_agent.hpp" - -#include +#include "commissioner/network_data.hpp" namespace ot { namespace commissioner { @@ -75,7 +78,7 @@ class Registry * * @param[in] aStorage persistent storage to be used */ - Registry(PersistentStorage *aStorage); + explicit Registry(PersistentStorage *aStorage); /** * Registry constructor with default PersistentStorage impl @@ -83,7 +86,7 @@ class Registry * * @param[in] aName PersistentStorageJson file name */ - Registry(std::string const &aName); + explicit Registry(std::string const &aName); /** * Registry destructor @@ -125,7 +128,7 @@ class Registry * It is expected that user becomes aware of the border router raw id from * 'br list' results. */ - Status GetBorderRouter(const BorderRouterId aRawId, BorderRouter &aBr); + Status GetBorderRouter(BorderRouterId aRawId, BorderRouter &aBr); /** * Get border routers belonging to the specified network. @@ -133,7 +136,7 @@ class Registry * @param[in] aXpan network's XPAN ID * @param[out] aRetValue resultant array of @ref BorderRouter records */ - Status GetBorderRoutersInNetwork(const XpanId aXpan, BorderRouterArray &aRetValue); + Status GetBorderRoutersInNetwork(XpanId aXpan, BorderRouterArray &aRetValue); /** * Get networks of the domain @@ -193,7 +196,7 @@ class Registry /** * Set current network. */ - Status SetCurrentNetwork(const XpanId aXpan); + Status SetCurrentNetwork(const XpanId &aXpan); /** * Set current network by border router specified. @@ -229,7 +232,7 @@ class Registry * @li @ref REG_DATA_INVALID is more than one network was found * @li @ref REG_ERROR on other errors */ - Status GetNetworkByXpan(const XpanId aXpan, Network &aRetValue); + Status GetNetworkByXpan(const XpanId &aXpan, Network &aRetValue); /** * Get network with specified name @@ -268,7 +271,7 @@ class Registry * @li @ref REG_AMBUGUITY is more than one network was found * @li @ref REG_ERROR on other errors */ - Status GetDomainNameByXpan(const XpanId aXpan, std::string &aName); + Status GetDomainNameByXpan(const XpanId &aXpan, std::string &aName); /** * Remove border router record. @@ -279,7 +282,7 @@ class Registry * @return * @li @ref REG_SUCCESS if successfully deleted record */ - Status DeleteBorderRouterById(const BorderRouterId aRouterId); + Status DeleteBorderRouterById(const BorderRouterId &aRouterId); /** * Remove border router records corresponding to the network aliases list along with the corresponding networks. diff --git a/src/app/ps/registry_entries.cpp b/src/app/ps/registry_entries.cpp index bc5f5d8c..7aee5bb8 100644 --- a/src/app/ps/registry_entries.cpp +++ b/src/app/ps/registry_entries.cpp @@ -32,8 +32,16 @@ */ #include "registry_entries.hpp" - +#include +#include +#include +#include + +#include "app/border_agent.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" #include "common/utils.hpp" +#include "nlohmann/json.hpp" using nlohmann::json; @@ -147,8 +155,8 @@ void to_json(json &aJson, const Network &aValue) aJson = json{{JSON_ID, aValue.mId}, {JSON_DOM_REF, aValue.mDomainId}, {JSON_NAME, aValue.mName}, - {JSON_PAN, (std::string)aValue.mPan}, - {JSON_XPAN, (std::string)aValue.mXpan}, + {JSON_PAN, std::string(aValue.mPan)}, + {JSON_XPAN, std::string(aValue.mXpan)}, {JSON_CHANNEL, aValue.mChannel}, {JSON_MLP, aValue.mMlp}, {JSON_CCM, aValue.mCcm}}; @@ -233,7 +241,7 @@ void to_json(json &aJson, const BorderRouter &aValue) { // Note that UnixTime::operator std::string() does formatting // here using UnixTime::kFmtString - aJson[JSON_UPDATE_TIMESTAMP] = (std::string)aValue.mAgent.mUpdateTimestamp; + aJson[JSON_UPDATE_TIMESTAMP] = std::string(aValue.mAgent.mUpdateTimestamp); } } @@ -281,7 +289,7 @@ void from_json(const json &aJson, BorderRouter &aValue) { uint64_t value; aJson.at(JSON_ACTIVE_TIMESTAMP).get_to(value); - aValue.mAgent.mActiveTimestamp.Decode(value); + aValue.mAgent.mActiveTimestamp = Timestamp::Decode(value); aValue.mAgent.mPresentFlags |= BorderAgent::kActiveTimestampBit; } if (aJson.contains(JSON_PARTITION_ID)) @@ -434,10 +442,6 @@ BorderRouter::BorderRouter(BorderRouterId const &aId, NetworkId const &aNetworkI { } -BorderRouter::~BorderRouter() -{ -} - } // namespace persistent_storage } // namespace commissioner diff --git a/src/app/ps/registry_entries.hpp b/src/app/ps/registry_entries.hpp index 9c90617c..fe28f270 100644 --- a/src/app/ps/registry_entries.hpp +++ b/src/app/ps/registry_entries.hpp @@ -34,12 +34,14 @@ #ifndef _REGISTRY_ENTRIES_HPP_ #define _REGISTRY_ENTRIES_HPP_ -#include "nlohmann_json.hpp" - +#include #include #include +#include + #include "app/border_agent.hpp" +#include "commissioner/network_data.hpp" namespace ot { @@ -52,7 +54,7 @@ namespace persistent_storage { * * Id value is not set */ -const unsigned int EMPTY_ID = (unsigned int)-1; +const unsigned int EMPTY_ID = static_cast(-1); /** * Registrar entity id @@ -110,7 +112,7 @@ struct Registrar Registrar(RegistrarId const &aId, std::string const &aAddr, - unsigned int const aPort, + unsigned int aPort, std::vector const &aDomains); Registrar(); }; @@ -148,10 +150,10 @@ struct Network DomainId const &aDomainId, std::string const &aName, XpanId const &aXpan, - unsigned int const aChannel, - uint16_t const aPan, + unsigned int aChannel, + uint16_t aPan, std::string const &aMlp, - int const aCcm); + int aCcm); Network(); }; @@ -171,7 +173,7 @@ struct BorderRouter /** * Minimum polymorphic requirements. */ - virtual ~BorderRouter(); + virtual ~BorderRouter() = default; }; typedef std::vector BorderRouterArray; diff --git a/src/app/ps/semaphore.cpp b/src/app/ps/semaphore.cpp index 3fc97261..c50b6d2c 100644 --- a/src/app/ps/semaphore.cpp +++ b/src/app/ps/semaphore.cpp @@ -33,8 +33,11 @@ #include "semaphore.hpp" -#include #include +#include +#include + +#include "app/ps/semaphore_posix.hpp" namespace ot { @@ -46,10 +49,10 @@ namespace semaphore { SemaphoreStatus SemaphoreOpen(std::string const &aName, Semaphore &aSem) { std::string semName = "Global\\" + aName; - aSem.platform = NULL; + aSem.platform = nullptr; - aSem.platform = CreateSemaphoreA(NULL, 1, 1, semName.c_str()); - if (aSem.platform == NULL) + aSem.platform = CreateSemaphoreA(nullptr, 1, 1, semName.c_str()); + if (aSem.platform == nullptr) { return kError; } @@ -60,13 +63,13 @@ SemaphoreStatus SemaphoreOpen(std::string const &aName, Semaphore &aSem) SemaphoreStatus SemaphoreClose(Semaphore &aSem) { CloseHandle(aSem.platform); - aSem.platform = NULL; + aSem.platform = nullptr; return kSuccess; } SemaphoreStatus SemaphorePost(Semaphore &aSem) { - if (ReleaseSemaphore(aSem.platform, 1, NULL) == 0) + if (ReleaseSemaphore(aSem.platform, 1, nullptr) == 0) { return kError; } @@ -87,7 +90,7 @@ SemaphoreStatus SemaphoreWait(Semaphore &aSem) SemaphoreStatus SemaphoreOpen(std::string const &aName, Semaphore &aSem) { std::string semName = "/" + aName; - aSem.mPlatform = NULL; + aSem.mPlatform = nullptr; aSem.mPlatform = sem_open(semName.c_str(), O_CREAT, S_IWUSR | S_IRUSR, 1); if (aSem.mPlatform == SEM_FAILED) @@ -101,7 +104,7 @@ SemaphoreStatus SemaphoreOpen(std::string const &aName, Semaphore &aSem) SemaphoreStatus SemaphoreClose(Semaphore &aSem) { sem_close(aSem.mPlatform); - aSem.mPlatform = NULL; + aSem.mPlatform = nullptr; return kSuccess; } diff --git a/src/common/utils.hpp b/src/common/utils.hpp index 77ea510f..c8450648 100644 --- a/src/common/utils.hpp +++ b/src/common/utils.hpp @@ -34,9 +34,11 @@ #ifndef OT_COMM_COMMON_UTILS_HPP_ #define OT_COMM_COMMON_UTILS_HPP_ +#include +#include +#include #include - -#include +#include #include #include diff --git a/src/library/coap.cpp b/src/library/coap.cpp index d1178559..0fe87d3b 100644 --- a/src/library/coap.cpp +++ b/src/library/coap.cpp @@ -35,13 +35,29 @@ #include +#include +#include +#include +#include #include +#include #include +#include +#include +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" #include "common/error_macros.hpp" #include "common/logging.hpp" +#include "common/time.hpp" #include "common/utils.hpp" +#include "event2/event.h" +#include "fmt/core.h" +#include "fmt/format.h" +#include "library/endpoint.hpp" +#include "library/message.hpp" #include "library/openthread/random.hpp" +#include "library/timer.hpp" namespace ot { @@ -191,22 +207,22 @@ bool Message::IsTokenEqual(const Message &aMessage) const return GetToken() == aMessage.GetToken(); } -Error Message::AppendOption(OptionType aNumber, const OptionValue &aValue) +Error Message::AppendOption(OptionType aType, const OptionValue &aValue) { Error error; - VerifyOrExit(IsValidOption(aNumber, aValue), error = ERROR_INVALID_ARGS("invalid CoAP option {}", aNumber)); + VerifyOrExit(IsValidOption(aType, aValue), error = ERROR_INVALID_ARGS("invalid CoAP option {}", aType)); - if (aNumber == OptionType::kUriPath) + if (aType == OptionType::kUriPath) { std::string uriPath = aValue.GetStringValue(); SuccessOrExit(error = NormalizeUriPath(uriPath)); - mOptions[aNumber] = mOptions[aNumber].GetStringValue() + uriPath; + mOptions[aType] = OptionValue{mOptions[aType].GetStringValue() + uriPath}; } else { // We don't allow multiple options of the same type. - mOptions.emplace(aNumber, aValue); + mOptions.emplace(aType, aValue); } exit: @@ -258,7 +274,7 @@ Error Message::SetUriPath(const std::string &aUriPath) std::string NormalizedUriPath = aUriPath; SuccessOrExit(error = NormalizeUriPath(NormalizedUriPath)); - SuccessOrExit(error = AppendOption(OptionType::kUriPath, NormalizedUriPath)); + SuccessOrExit(error = AppendOption(OptionType::kUriPath, OptionValue{NormalizedUriPath})); exit: return error; @@ -474,7 +490,7 @@ Error Message::Deserialize(OptionType &aOptionNumber, VerifyOrExit(valueLength + extend <= aBuf.size(), error = ERROR_BAD_FORMAT("premature end of a CoAP option")); aOptionNumber = utils::from_underlying(aLastOptionNumber + delta); - aOptionValue = ByteArray{aBuf.begin() + extend, aBuf.begin() + extend + valueLength}; + aOptionValue = OptionValue{ByteArray{aBuf.begin() + extend, aBuf.begin() + extend + valueLength}}; aOffset += length + valueLength; @@ -482,7 +498,7 @@ Error Message::Deserialize(OptionType &aOptionNumber, return error; } -Coap::RequestHolder::RequestHolder(const RequestPtr aRequest, ResponseHandler aHandler) +Coap::RequestHolder::RequestHolder(const RequestPtr &aRequest, ResponseHandler aHandler) : mRequest(aRequest) , mHandler(aHandler) , mRetransmissionCount(0) @@ -672,7 +688,6 @@ void Coap::HandleRequest(const Request &aRequest) { LOG_INFO(LOG_REGION_COAP, "server(={}) handle request failed: {}", static_cast(this), error.ToString()); } - return; } void Coap::HandleResponse(Response &aResponse) @@ -926,7 +941,7 @@ void Coap::ResponsesCache::Eliminate() } } -void Coap::RequestsCache::Put(const RequestPtr aRequest, ResponseHandler aHandler) +void Coap::RequestsCache::Put(const RequestPtr &aRequest, ResponseHandler aHandler) { Put({aRequest, aHandler}); } @@ -1022,7 +1037,7 @@ Error Message::Serialize(ByteArray &aBuf) const SuccessOrExit(error = SplitUriPath(uriPathSegments, value.GetStringValue())); for (const auto &segment : uriPathSegments) { - SuccessOrExit(error = Serialize(number, segment, lastOptionNumber, aBuf)); + SuccessOrExit(error = Serialize(number, OptionValue{segment}, lastOptionNumber, aBuf)); lastOptionNumber = utils::to_underlying(number); } } diff --git a/src/library/coap.hpp b/src/library/coap.hpp index b8f60034..3d3d193e 100644 --- a/src/library/coap.hpp +++ b/src/library/coap.hpp @@ -35,20 +35,24 @@ #define OT_COMM_LIBRARY_COAP_HPP_ #include +#include +#include #include #include #include #include -#include #include +#include #include -#include -#include - +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" #include "common/address.hpp" +#include "common/time.hpp" #include "common/utils.hpp" +#include "event2/event.h" +#include "fmt/core.h" #include "library/endpoint.hpp" #include "library/message.hpp" #include "library/timer.hpp" @@ -311,15 +315,15 @@ class OptionValue { public: OptionValue() = default; - OptionValue(const ByteArray &aOpaque) + explicit OptionValue(const ByteArray &aOpaque) : mValue(aOpaque) { } - OptionValue(const std::string &aString) + explicit OptionValue(const std::string &aString) : mValue(aString.begin(), aString.end()) { } - OptionValue(uint32_t aUint32) + explicit OptionValue(uint32_t aUint32) { // Encoding an unsigned integer without preceding zeros. while (aUint32 != 0) @@ -469,13 +473,13 @@ class Message Error SetAccept(ContentFormat aAcceptFormat) { - return AppendOption(OptionType::kAccept, utils::to_underlying(aAcceptFormat)); + return AppendOption(OptionType::kAccept, OptionValue{utils::to_underlying(aAcceptFormat)}); } Error GetAccept(ContentFormat &aAcceptFormat) const; Error SetContentFormat(ContentFormat aContentFormat) { - return AppendOption(OptionType::kContentFormat, utils::to_underlying(aContentFormat)); + return AppendOption(OptionType::kContentFormat, OptionValue{utils::to_underlying(aContentFormat)}); } Error GetContentFormat(ContentFormat &aContentFormat) const; @@ -649,7 +653,7 @@ class Coap */ struct RequestHolder { - RequestHolder(const RequestPtr aRequest, ResponseHandler aHandler); + RequestHolder(const RequestPtr &aRequest, ResponseHandler aHandler); RequestPtr mRequest; mutable ResponseHandler mHandler; @@ -673,7 +677,7 @@ class Coap } ~RequestsCache() = default; - void Put(const RequestPtr aRequest, ResponseHandler aHandler); + void Put(const RequestPtr &aRequest, ResponseHandler aHandler); void Put(const RequestHolder &aRequestHolder); // Find corresponding request with the response. diff --git a/src/library/coap_secure.hpp b/src/library/coap_secure.hpp index eddaf0df..a53bfbb5 100644 --- a/src/library/coap_secure.hpp +++ b/src/library/coap_secure.hpp @@ -34,9 +34,17 @@ #ifndef OT_COMM_LIBRARY_COAP_SECURE_HPP_ #define OT_COMM_LIBRARY_COAP_SECURE_HPP_ +#include +#include +#include +#include "commissioner/error.hpp" +#include "common/address.hpp" #include "common/error_macros.hpp" +#include "common/utils.hpp" +#include "event2/event.h" #include "library/coap.hpp" #include "library/dtls.hpp" +#include "library/socket.hpp" namespace ot { diff --git a/src/library/coap_test.cpp b/src/library/coap_test.cpp index 2f8c3ecd..26f8ae0b 100644 --- a/src/library/coap_test.cpp +++ b/src/library/coap_test.cpp @@ -31,11 +31,25 @@ * This file defines test cases for CoAP implementation. */ -#include "common/error_macros.hpp" -#include "library/coap.hpp" +#include +#include +#include +#include #include +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "common/address.hpp" +#include "common/error_macros.hpp" +#include "common/utils.hpp" +#include "event2/event.h" +#include "event2/event_struct.h" +#include "event2/util.h" +#include "library/coap.hpp" +#include "library/endpoint.hpp" +#include "library/message.hpp" + namespace ot { namespace commissioner { @@ -291,7 +305,7 @@ class MockEndpoint : public Endpoint event_add(&mSendEvent, nullptr); } - ~MockEndpoint() override {} + ~MockEndpoint() override = default; void SetPeer(MockEndpoint *aPeer) { mPeer = aPeer; } diff --git a/src/library/commissioner_impl.cpp b/src/library/commissioner_impl.cpp index 50b84f11..685e65c5 100644 --- a/src/library/commissioner_impl.cpp +++ b/src/library/commissioner_impl.cpp @@ -32,14 +32,31 @@ */ #include "library/commissioner_impl.hpp" - +#include +#include +#include +#include +#include +#include +#include + +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" +#include "common/address.hpp" +#include "common/error_macros.hpp" #include "common/logging.hpp" +#include "common/time.hpp" +#include "event2/event.h" #include "library/coap.hpp" -#include "library/cose.hpp" #include "library/dtls.hpp" +#include "library/joiner_session.hpp" #include "library/openthread/bloom_filter.hpp" #include "library/openthread/pbkdf2_cmac.hpp" #include "library/openthread/sha256.hpp" +#include "library/timer.hpp" +#include "library/tlv.hpp" #include "library/uri.hpp" #include "common/utils.hpp" @@ -493,7 +510,7 @@ void CommissionerImpl::GetRawActiveDataset(Handler aHandler, uint16_t } } -void CommissionerImpl::SetActiveDataset(ErrorHandler aHandler, const ActiveOperationalDataset &aDataset) +void CommissionerImpl::SetActiveDataset(ErrorHandler aHandler, const ActiveOperationalDataset &aActiveDataset) { Error error; coap::Request request{coap::Type::kConfirmable, coap::Code::kPost}; @@ -502,27 +519,27 @@ void CommissionerImpl::SetActiveDataset(ErrorHandler aHandler, const ActiveOpera aHandler(HandleStateResponse(aResponse, aError)); }; - VerifyOrExit(aDataset.mPresentFlags & ActiveOperationalDataset::kActiveTimestampBit, + VerifyOrExit(aActiveDataset.mPresentFlags & ActiveOperationalDataset::kActiveTimestampBit, error = ERROR_INVALID_ARGS("Active Timestamp is mandatory for an Active Operational Dataset")); // TLVs affect connectivity are not allowed. - VerifyOrExit((aDataset.mPresentFlags & ActiveOperationalDataset::kChannelBit) == 0, + VerifyOrExit((aActiveDataset.mPresentFlags & ActiveOperationalDataset::kChannelBit) == 0, error = ERROR_INVALID_ARGS("Channel cannot be set with Active Operational Dataset, " "try setting with Pending Operational Dataset instead")); - VerifyOrExit((aDataset.mPresentFlags & ActiveOperationalDataset::kPanIdBit) == 0, + VerifyOrExit((aActiveDataset.mPresentFlags & ActiveOperationalDataset::kPanIdBit) == 0, error = ERROR_INVALID_ARGS("PAN ID cannot be set with Active Operational Dataset, " "try setting with Pending Operational Dataset instead")); - VerifyOrExit((aDataset.mPresentFlags & ActiveOperationalDataset::kMeshLocalPrefixBit) == 0, + VerifyOrExit((aActiveDataset.mPresentFlags & ActiveOperationalDataset::kMeshLocalPrefixBit) == 0, error = ERROR_INVALID_ARGS("Mesh-Local Prefix cannot be set with Active Operational Dataset, " "try setting with Pending Operational Dataset instead")); - VerifyOrExit((aDataset.mPresentFlags & ActiveOperationalDataset::kNetworkMasterKeyBit) == 0, + VerifyOrExit((aActiveDataset.mPresentFlags & ActiveOperationalDataset::kNetworkMasterKeyBit) == 0, error = ERROR_INVALID_ARGS("Network Master Key cannot be set with Active Operational Dataset, " "try setting with Pending Operational Dataset instead")); VerifyOrExit(IsActive(), error = ERROR_INVALID_STATE("the commissioner is not active")); SuccessOrExit(error = request.SetUriPath(uri::kMgmtActiveSet)); SuccessOrExit(error = AppendTlv(request, {tlv::Type::kCommissionerSessionId, GetSessionId()})); - SuccessOrExit(error = EncodeActiveOperationalDataset(request, aDataset)); + SuccessOrExit(error = EncodeActiveOperationalDataset(request, aActiveDataset)); #if OT_COMM_CONFIG_CCM_ENABLE if (IsCcmMode()) @@ -596,7 +613,7 @@ void CommissionerImpl::GetPendingDataset(Handler aHan } } -void CommissionerImpl::SetPendingDataset(ErrorHandler aHandler, const PendingOperationalDataset &aDataset) +void CommissionerImpl::SetPendingDataset(ErrorHandler aHandler, const PendingOperationalDataset &aPendingDataset) { Error error; coap::Request request{coap::Type::kConfirmable, coap::Code::kPost}; @@ -605,18 +622,18 @@ void CommissionerImpl::SetPendingDataset(ErrorHandler aHandler, const PendingOpe aHandler(HandleStateResponse(aResponse, aError)); }; - VerifyOrExit(aDataset.mPresentFlags & PendingOperationalDataset::kActiveTimestampBit, + VerifyOrExit(aPendingDataset.mPresentFlags & PendingOperationalDataset::kActiveTimestampBit, error = ERROR_INVALID_ARGS("Active Timestamp is mandatory for a Pending Operational Dataset")); - VerifyOrExit(aDataset.mPresentFlags & PendingOperationalDataset::kPendingTimestampBit, + VerifyOrExit(aPendingDataset.mPresentFlags & PendingOperationalDataset::kPendingTimestampBit, error = ERROR_INVALID_ARGS("Pending Timestamp is mandatory for a Pending Operational Dataset")); - VerifyOrExit(aDataset.mPresentFlags & PendingOperationalDataset::kDelayTimerBit, + VerifyOrExit(aPendingDataset.mPresentFlags & PendingOperationalDataset::kDelayTimerBit, error = ERROR_INVALID_ARGS("Delay Timer is mandatory for a Pending Operational Dataset")); VerifyOrExit(IsActive(), error = ERROR_INVALID_STATE("the commissioner is not active")); SuccessOrExit(error = request.SetUriPath(uri::kMgmtPendingSet)); SuccessOrExit(error = AppendTlv(request, {tlv::Type::kCommissionerSessionId, GetSessionId()})); - SuccessOrExit(error = EncodePendingOperationalDataset(request, aDataset)); + SuccessOrExit(error = EncodePendingOperationalDataset(request, aPendingDataset)); #if OT_COMM_CONFIG_CCM_ENABLE if (IsCcmMode()) @@ -1471,7 +1488,7 @@ Error CommissionerImpl::DecodeActiveOperationalDataset(ActiveOperationalDataset if (auto extendedPanId = tlvSet[tlv::Type::kExtendedPanId]) { - dataset.mExtendedPanId = utils::Decode(extendedPanId->GetValue()); + dataset.mExtendedPanId = XpanId{utils::Decode(extendedPanId->GetValue())}; dataset.mPresentFlags |= ActiveOperationalDataset::kExtendedPanIdBit; } diff --git a/src/library/commissioner_impl.hpp b/src/library/commissioner_impl.hpp index 0491b18b..1b0eb05e 100644 --- a/src/library/commissioner_impl.hpp +++ b/src/library/commissioner_impl.hpp @@ -29,15 +29,23 @@ #ifndef OT_COMM_LIBRARY_COMMISSIONER_IMPL_HPP_ #define OT_COMM_LIBRARY_COMMISSIONER_IMPL_HPP_ -#include -#include +#include +#include +#include +#include +#include +#include #include +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" +#include "common/error_macros.hpp" +#include "common/time.hpp" +#include "event2/event.h" #include "library/coap.hpp" #include "library/coap_secure.hpp" -#include "library/dtls.hpp" -#include "library/event.hpp" #include "library/joiner_session.hpp" #include "library/timer.hpp" #include "library/tlv.hpp" @@ -240,7 +248,7 @@ class CommissionerImpl : public Commissioner static Error MakeChannelMask(ByteArray &aBuf, uint32_t aChannelMask); - void HandleRlyRx(const coap::Request &aRequest); + void HandleRlyRx(const coap::Request &aRlyRx); void HandleJoinerSessionTimer(Timer &aTimer); diff --git a/src/library/cose.cpp b/src/library/cose.cpp index 946df814..9dd5f7a6 100644 --- a/src/library/cose.cpp +++ b/src/library/cose.cpp @@ -38,13 +38,20 @@ #define MBEDTLS_ALLOW_PRIVATE_ACCESS #endif -#include "library/cose.hpp" +#include +#include +#include #include #include +#include +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" #include "common/error_macros.hpp" #include "common/utils.hpp" +#include "library/cbor.hpp" +#include "library/cose.hpp" #include "library/mbedtls_error.hpp" namespace ot { @@ -76,9 +83,9 @@ Error Sign1Message::Init(int aCoseInitFlags) Error Sign1Message::Serialize(ByteArray &aBuf) { size_t length; - length = COSE_Encode((HCOSE)mSign, nullptr, 0, 0) + 1; + length = COSE_Encode(reinterpret_cast(mSign), nullptr, 0, 0) + 1; aBuf.resize(length); - length = COSE_Encode((HCOSE)mSign, aBuf.data(), 0, aBuf.size()); + length = COSE_Encode(reinterpret_cast(mSign), aBuf.data(), 0, aBuf.size()); aBuf.resize(length); return ERROR_NONE; @@ -116,13 +123,13 @@ Error Sign1Message::Validate(const CborMap &aCborPublicKey) return error; } -Error Sign1Message::Validate(const mbedtls_pk_context &aPubKey) +Error Sign1Message::Validate(const mbedtls_pk_context &aPublicKey) { Error error; const struct mbedtls_ecp_keypair *eckey; // Accepts only EC keys - VerifyOrExit(mbedtls_pk_can_do(&aPubKey, MBEDTLS_PK_ECDSA) && (eckey = mbedtls_pk_ec(aPubKey)) != nullptr, + VerifyOrExit(mbedtls_pk_can_do(&aPublicKey, MBEDTLS_PK_ECDSA) && (eckey = mbedtls_pk_ec(aPublicKey)) != nullptr, error = ERROR_INVALID_ARGS("validate COSE SIGN1 message without valid EC public key")); VerifyOrExit(COSE_Sign0_validate_eckey(mSign, eckey, nullptr), diff --git a/src/library/cose.hpp b/src/library/cose.hpp index bb467870..57f80392 100644 --- a/src/library/cose.hpp +++ b/src/library/cose.hpp @@ -48,6 +48,7 @@ #include #include +#include "cn-cbor/cn-cbor.h" #include "library/cbor.hpp" namespace ot { diff --git a/src/library/dtls.cpp b/src/library/dtls.cpp index 53ea69d8..310f529e 100644 --- a/src/library/dtls.cpp +++ b/src/library/dtls.cpp @@ -35,6 +35,27 @@ // Enabling this flag to allow us continue accessing those fields. #ifndef MBEDTLS_ALLOW_PRIVATE_ACCESS #define MBEDTLS_ALLOW_PRIVATE_ACCESS +#include +#include +#include +#include +#include +#include "/usr/local/google/home/wgtdkp/ot-commissioner/third_party/mbedtls/mbedtls-config.h" +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "common/time.hpp" +#include "event2/event.h" +#include "library/message.hpp" +#include "library/socket.hpp" +#include "library/timer.hpp" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" +#include "mbedtls/pk.h" +#include "mbedtls/ssl.h" +#include "mbedtls/ssl_ciphersuites.h" +#include "mbedtls/ssl_cookie.h" +#include "mbedtls/x509_crt.h" #endif #include "library/dtls.hpp" diff --git a/src/library/dtls.hpp b/src/library/dtls.hpp index 22f3d2ec..99ed1c03 100644 --- a/src/library/dtls.hpp +++ b/src/library/dtls.hpp @@ -34,9 +34,13 @@ #ifndef OT_COMM_LIBRARY_DTLS_HPP_ #define OT_COMM_LIBRARY_DTLS_HPP_ +#include +#include #include -#include +#include #include +#include +#include #include #include @@ -49,11 +53,16 @@ #include #include -#include "common/utils.hpp" +#include "commissioner/error.hpp" +#include "common/address.hpp" +#include "common/time.hpp" +#include "event2/event.h" #include "library/endpoint.hpp" -#include "library/event.hpp" +#include "library/message.hpp" #include "library/socket.hpp" #include "library/timer.hpp" +#include "mbedtls/pk.h" +#include "mbedtls/x509_crt.h" namespace ot { diff --git a/src/library/network_data.cpp b/src/library/network_data.cpp index 147f6809..db8c1d2f 100644 --- a/src/library/network_data.cpp +++ b/src/library/network_data.cpp @@ -33,9 +33,18 @@ #include +#include +#include +#include +#include +#include #include +#include #include +#include +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" #include "common/address.hpp" #include "common/error_macros.hpp" #include "common/time.hpp" @@ -126,7 +135,7 @@ XpanId::XpanId() std::string XpanId::str() const { - return *this; + return std::string(*this); } bool XpanId::operator==(const XpanId &aOther) const @@ -134,12 +143,12 @@ bool XpanId::operator==(const XpanId &aOther) const return mValue == aOther.mValue; } -bool XpanId::operator!=(const uint64_t aOther) const +bool XpanId::operator!=(const XpanId &aOther) const { - return !operator==(aOther); + return !(*this == aOther); } -bool XpanId::operator<(const XpanId aOther) const +bool XpanId::operator<(const XpanId &aOther) const { return mValue < aOther.mValue; } diff --git a/src/library/openthread/sha256.cpp b/src/library/openthread/sha256.cpp index 1db57ec5..7a66e4cd 100644 --- a/src/library/openthread/sha256.cpp +++ b/src/library/openthread/sha256.cpp @@ -33,6 +33,10 @@ #include "library/openthread/sha256.hpp" +#include + +#include "mbedtls/sha256.h" + namespace ot { namespace commissioner { diff --git a/src/library/socket.cpp b/src/library/socket.cpp index 4e31a6f8..d19d23d2 100644 --- a/src/library/socket.cpp +++ b/src/library/socket.cpp @@ -28,11 +28,22 @@ #include "library/socket.hpp" +#include +#include +#include #include #include +#include +#include +#include "common/address.hpp" #include "common/logging.hpp" #include "common/utils.hpp" +#include "event2/event.h" +#include "event2/util.h" +#include "library/event.hpp" +#include "library/message.hpp" +#include "mbedtls/net_sockets.h" namespace ot { @@ -40,20 +51,25 @@ namespace commissioner { static uint16_t GetSockPort(const sockaddr_storage &aSockAddr) { + uint16_t port; + if (aSockAddr.ss_family == AF_INET) { auto &addr4 = *reinterpret_cast(&aSockAddr); - return ntohs(addr4.sin_port); + ExitNow(port = ntohs(addr4.sin_port)); } else if (aSockAddr.ss_family == AF_INET6) { auto &addr6 = *reinterpret_cast(&aSockAddr); - return ntohs(addr6.sin6_port); + ExitNow(port = ntohs(addr6.sin6_port)); } else { VerifyOrDie(false); } + +exit: + return port; } Socket::Socket(struct event_base *aEventBase) @@ -111,9 +127,9 @@ UdpSocket::UdpSocket(UdpSocket &&aOther) mbedtls_net_init(&aOther.mNetCtx); } -int UdpSocket::Connect(const std::string &aHost, uint16_t aPort) +int UdpSocket::Connect(const std::string &aPeerAddr, uint16_t aPeerPort) { - auto portStr = std::to_string(aPort); + auto portStr = std::to_string(aPeerPort); // Free the fd if already opened. mbedtls_net_free(&mNetCtx); @@ -123,7 +139,7 @@ int UdpSocket::Connect(const std::string &aHost, uint16_t aPort) } // Connect - int rval = mbedtls_net_connect(&mNetCtx, aHost.c_str(), portStr.c_str(), MBEDTLS_NET_PROTO_UDP); + int rval = mbedtls_net_connect(&mNetCtx, aPeerAddr.c_str(), portStr.c_str(), MBEDTLS_NET_PROTO_UDP); VerifyOrExit(rval == 0); VerifyOrExit((rval = mbedtls_net_set_nonblock(&mNetCtx)) == 0); @@ -144,9 +160,9 @@ int UdpSocket::Connect(const std::string &aHost, uint16_t aPort) return rval; } -int UdpSocket::Bind(const std::string &aBindIp, uint16_t aPort) +int UdpSocket::Bind(const std::string &aLocalAddr, uint16_t aLocalPort) { - auto portStr = std::to_string(aPort); + auto portStr = std::to_string(aLocalPort); // Free the fd if already opened. mbedtls_net_free(&mNetCtx); @@ -156,7 +172,7 @@ int UdpSocket::Bind(const std::string &aBindIp, uint16_t aPort) } // Bind - int rval = mbedtls_net_bind(&mNetCtx, aBindIp.c_str(), portStr.c_str(), MBEDTLS_NET_PROTO_UDP); + int rval = mbedtls_net_bind(&mNetCtx, aLocalAddr.c_str(), portStr.c_str(), MBEDTLS_NET_PROTO_UDP); VerifyOrExit(rval == 0); VerifyOrExit((rval = mbedtls_net_set_nonblock(&mNetCtx)) == 0); diff --git a/src/library/socket.hpp b/src/library/socket.hpp index e692248b..425e40c3 100644 --- a/src/library/socket.hpp +++ b/src/library/socket.hpp @@ -34,16 +34,20 @@ #ifndef OT_COMM_LIBRARY_SOCKET_HPP_ #define OT_COMM_LIBRARY_SOCKET_HPP_ +#include +#include #include #include -#include - #include #include "common/address.hpp" +#include "event2/event.h" +#include "event2/event_struct.h" +#include "event2/util.h" #include "library/event.hpp" #include "library/message.hpp" +#include "mbedtls/net_sockets.h" namespace ot { diff --git a/src/library/token_manager.cpp b/src/library/token_manager.cpp index 2ee7e6da..b84f550d 100644 --- a/src/library/token_manager.cpp +++ b/src/library/token_manager.cpp @@ -31,13 +31,29 @@ * This file implements the Commissioner Token Manager. */ +#include +#include +#include +#include +#include +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "common/error_macros.hpp" +#include "common/utils.hpp" +#include "event2/event.h" +#include "library/cbor.hpp" +#include "library/coap.hpp" +#include "library/dtls.hpp" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" +#include "mbedtls/pk.h" #if OT_COMM_CONFIG_CCM_ENABLE #include "library/token_manager.hpp" #include -#include "common/logging.hpp" #include "library/cose.hpp" #include "library/cwt.hpp" #include "library/mbedtls_error.hpp" @@ -304,7 +320,7 @@ Error TokenManager::MakeTokenRequest(ByteArray &aBuf, uint8_t tokenBuf[kMaxTokenRequestSize]; // Use the commissioner Id as kid(truncated to kMaxCoseKeyIdLength) - const ByteArray kid = {aId.begin(), aId.begin() + std::min(aId.size(), (size_t)kMaxCoseKeyIdLength)}; + const ByteArray kid = {aId.begin(), aId.begin() + std::min(aId.size(), static_cast(kMaxCoseKeyIdLength))}; VerifyOrExit(mbedtls_pk_can_do(&aPublicKey, MBEDTLS_PK_ECDSA), error = ERROR_INVALID_ARGS("the public key is not a ECDSA key")); diff --git a/src/library/token_manager.hpp b/src/library/token_manager.hpp index cae23793..1ba1d06b 100644 --- a/src/library/token_manager.hpp +++ b/src/library/token_manager.hpp @@ -29,6 +29,13 @@ #ifndef OT_COMM_LIBRARY_TOKEN_MANAGER_HPP_ #define OT_COMM_LIBRARY_TOKEN_MANAGER_HPP_ +#include +#include +#include "commissioner/defines.hpp" +#include "event2/event.h" +#include "library/coap.hpp" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" #if OT_COMM_CONFIG_CCM_ENABLE #include @@ -173,7 +180,7 @@ class TokenManager /* * Thread Constants. */ - static const size_t kMaxCoseKeyIdLength = 16; + static constexpr int kMaxCoseKeyIdLength = 16; // Move the resource from src to des, leaving the src invalid. static void MoveMbedtlsKey(mbedtls_pk_context &aDes, mbedtls_pk_context &aSrc); diff --git a/src/library/udp_proxy.cpp b/src/library/udp_proxy.cpp index f8aa20b4..0cb10bff 100644 --- a/src/library/udp_proxy.cpp +++ b/src/library/udp_proxy.cpp @@ -32,9 +32,23 @@ */ #include "library/udp_proxy.hpp" - +#include +#include +#include + +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" +#include "commissioner/error.hpp" +#include "commissioner/network_data.hpp" +#include "common/address.hpp" +#include "common/error_macros.hpp" #include "common/logging.hpp" +#include "common/utils.hpp" +#include "library/coap.hpp" +#include "library/coap_secure.hpp" #include "library/commissioner_impl.hpp" +#include "library/message.hpp" +#include "library/tlv.hpp" #include "library/uri.hpp" namespace ot { @@ -159,7 +173,6 @@ void ProxyClient::HandleUdpRx(const coap::Request &aUdpRx) LOG_WARN(LOG_REGION_COAP, "client(={}) handle UDP_RX.ntf request failed: {}", static_cast(this), error.ToString()); } - return; } void ProxyClient::FetchMeshLocalPrefix(Commissioner::ErrorHandler aHandler) diff --git a/src/library/udp_proxy.hpp b/src/library/udp_proxy.hpp index 8011def7..adcb28ee 100644 --- a/src/library/udp_proxy.hpp +++ b/src/library/udp_proxy.hpp @@ -34,11 +34,16 @@ #ifndef OT_COMM_LIBRARY_UDP_PROXY_HPP_ #define OT_COMM_LIBRARY_UDP_PROXY_HPP_ +#include #include +#include "commissioner/commissioner.hpp" +#include "commissioner/defines.hpp" #include "common/address.hpp" +#include "library/coap.hpp" #include "library/coap_secure.hpp" #include "library/endpoint.hpp" +#include "library/message.hpp" namespace ot { @@ -51,14 +56,14 @@ class CommissionerImpl; class ProxyEndpoint : public Endpoint { public: - ProxyEndpoint(coap::CoapSecure &aBrClient) + explicit ProxyEndpoint(coap::CoapSecure &aBrClient) : mBrClient(aBrClient) , mPeerPort(0) { } ~ProxyEndpoint() override = default; - Error Send(const ByteArray &aBuf, MessageSubType aSubType) override; + Error Send(const ByteArray &aRequest, MessageSubType aSubType) override; Address GetPeerAddr() const override { return mPeerAddr; } uint16_t GetPeerPort() const override { return mPeerPort; } diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt index 28518779..b5577999 100644 --- a/third_party/CMakeLists.txt +++ b/third_party/CMakeLists.txt @@ -42,6 +42,7 @@ endif() add_subdirectory(fmtlib/repo) if (OT_COMM_APP) + set(JSON_BuildTests OFF CACHE BOOL "Disable compiling json tests" FORCE) add_subdirectory(json/repo) endif() diff --git a/third_party/mbedtls/mbedtls-config.h b/third_party/mbedtls/mbedtls-config.h index ad25f581..5c77c1a6 100644 --- a/third_party/mbedtls/mbedtls-config.h +++ b/third_party/mbedtls/mbedtls-config.h @@ -29,8 +29,7 @@ #ifndef OT_COMM_MBEDTLS_CONFIG_H #define OT_COMM_MBEDTLS_CONFIG_H -#include -#include +#include "mbedtls/build_info.h" #define MBEDTLS_DEBUG_C #define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf @@ -109,19 +108,15 @@ #define MBEDTLS_SSL_OUT_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN #define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 -#include "mbedtls/version.h" #if (MBEDTLS_VERSION_NUMBER >= 0x03050000) // This is from build_info.h of 3.X mbedtls to workaround building issues #if defined(MBEDTLS_PSA_CRYPTO_CONFIG) /* PSA_WANT_xxx influences MBEDTLS_xxx */ || \ defined(MBEDTLS_PSA_CRYPTO_C) /* MBEDTLS_xxx influences PSA_WANT_xxx */ - #include "mbedtls/config_psa.h" #endif // Include in the legacy config name adjustment file for mbedtls >= 3.5.0 - #include "mbedtls/config_adjust_legacy_crypto.h" #endif -#include "mbedtls/check_config.h" #endif /* OT_COMM_MBEDTLS_CONFIG_H */ diff --git a/tmpdir/br-list.json b/tmpdir/br-list.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/tmpdir/br-list.json @@ -0,0 +1 @@ +null \ No newline at end of file