From 2507719b2e460338d5864a30d6a2d2ee2bb0cf7e Mon Sep 17 00:00:00 2001 From: kangping Date: Sun, 29 Mar 2020 16:20:46 +0800 Subject: [PATCH 1/5] [mdns] move mDNS discovery out of the library --- include/commissioner/commissioner.hpp | 17 - src/app/CMakeLists.txt | 2 + src/app/border_agent.cpp | 361 ++++++++++++++ .../commissioner => src/app}/border_agent.hpp | 30 +- src/app/cli/interpreter.cpp | 31 +- src/app/cli/interpreter.hpp | 5 +- src/app/commissioner_app.cpp | 22 - src/app/commissioner_app.hpp | 11 - src/library/CMakeLists.txt | 2 - src/library/commissioner_impl.cpp | 6 - src/library/commissioner_impl.hpp | 6 - src/library/commissioner_safe.cpp | 20 - src/library/commissioner_safe.hpp | 3 - src/library/multicast_dns.cpp | 461 ------------------ src/library/multicast_dns.hpp | 102 ---- tests/unit/test_commissioner_impl.cpp | 2 - 16 files changed, 416 insertions(+), 665 deletions(-) create mode 100644 src/app/border_agent.cpp rename {include/commissioner => src/app}/border_agent.hpp (83%) delete mode 100644 src/library/multicast_dns.cpp delete mode 100644 src/library/multicast_dns.hpp diff --git a/include/commissioner/commissioner.hpp b/include/commissioner/commissioner.hpp index a3fa0396c..cfbf0d0fa 100644 --- a/include/commissioner/commissioner.hpp +++ b/include/commissioner/commissioner.hpp @@ -42,7 +42,6 @@ #include #include -#include "border_agent.hpp" #include "defines.hpp" #include "error.hpp" #include "network_data.hpp" @@ -327,22 +326,6 @@ class Commissioner */ virtual void Stop() = 0; - /** - * @brief Asynchronously discover Thread Network at link-local. - * - * @param[in, out] aHandler A handler of the response and errors; Guaranteed to be called. - */ - virtual void Discover(Handler> aHandler) = 0; - - /** - * @brief Synchronously discover Thread Network at link-local. - * - * @param[out] aBorderAgentList A list of discovered border agent. - * - * @return Error::kNone, succeed; otherwise, failed; - */ - virtual Error Discover(std::list &aBorderAgentList) = 0; - /** * @brief Asynchronously connect to a Thread network. * diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index 1f288da2e..283daa15e 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -32,6 +32,8 @@ target_sources(commissioner-app PRIVATE commissioner_app.cpp commissioner_app.hpp + border_agent.cpp + border_agent.hpp file_logger.cpp file_logger.hpp file_util.cpp diff --git a/src/app/border_agent.cpp b/src/app/border_agent.cpp new file mode 100644 index 000000000..0c5f41a55 --- /dev/null +++ b/src/app/border_agent.cpp @@ -0,0 +1,361 @@ +/* + * Copyright (c) 2019, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "border_agent.hpp" + +#include +#include + +#include +#include + +#include +#include + +namespace ot { + +namespace commissioner { + +struct BorderAgentOrErrorMsg +{ + BorderAgent mBorderAgent; + std::string mErrorMsg; +}; + +static 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 * user_data); + +Error DiscoverBorderAgent(BorderAgentHandler aBorderAgentHandler, size_t aTimeout) +{ + static constexpr size_t kDefaultBufferSize = 1024 * 16; + static constexpr mdns_record_type_t kMdnsQueryType = MDNS_RECORDTYPE_PTR; + static const char * kServiceName = "_meshcop._udp.local"; + + Error error = Error::kNone; + uint8_t buf[kDefaultBufferSize]; + + auto begin = std::chrono::system_clock::now(); + + int socket = mdns_socket_open_ipv4(); + VerifyOrExit(socket >= 0, error = Error::kTransportFailed); + + if (mdns_query_send(socket, kMdnsQueryType, kServiceName, strlen(kServiceName), buf, sizeof(buf)) != 0) + { + ExitNow(error = Error::kTransportFailed); + } + + while (begin + std::chrono::milliseconds(aTimeout) >= std::chrono::system_clock::now()) + { + BorderAgentOrErrorMsg curBorderAgentOrErrorMsg; + + mdns_query_recv(socket, buf, sizeof(buf), HandleRecord, &curBorderAgentOrErrorMsg, 1); + + if (!curBorderAgentOrErrorMsg.mErrorMsg.empty()) + { + aBorderAgentHandler(nullptr, &curBorderAgentOrErrorMsg.mErrorMsg); + } + else if (curBorderAgentOrErrorMsg.mBorderAgent.mPresentFlags != 0) + { + aBorderAgentHandler(&curBorderAgentOrErrorMsg.mBorderAgent, nullptr); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + +exit: + if (socket >= 0) + { + mdns_socket_close(socket); + } + + return error; +} + +static inline std::string ToString(const mdns_string_t &aString) +{ + return std::string(aString.str, aString.length); +} + +/** + * This is the callback per mDNS record. + * + * It may be called multiple times for a single mDNS response. + * + */ +static 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 * border_agent) +{ + Error error = Error::kNone; + struct sockaddr_storage fromAddrStorage; + Address fromAddr; + std::string fromAddrStr; + std::string entryType; + char nameBuffer[256]; + + BorderAgentOrErrorMsg &borderAgentOrErrorMsg = *reinterpret_cast(border_agent); + BorderAgent &borderAgent = borderAgentOrErrorMsg.mBorderAgent; + std::string &errorMsg = borderAgentOrErrorMsg.mErrorMsg; + + (void)rclass; + (void)ttl; + + *reinterpret_cast(&fromAddrStorage) = *from; + if (fromAddr.Set(fromAddrStorage) != Error::kNone || + fromAddr.ToString(fromAddrStr) != Error::kNone) + { + ExitNow(errorMsg = "invalid source address of mDNS response"); + } + + entryType = (entry == MDNS_ENTRYTYPE_ANSWER) ? "answer" + : ((entry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional"); + if (type == MDNS_RECORDTYPE_PTR) + { + mdns_string_t nameStr = mdns_record_parse_ptr(data, size, offset, length, nameBuffer, sizeof(nameBuffer)); + (void)nameStr; + // TODO(wgtdkp): add debug logging. + } + else if (type == MDNS_RECORDTYPE_SRV) + { + mdns_record_srv_t server = mdns_record_parse_srv(data, size, offset, length, nameBuffer, sizeof(nameBuffer)); + + borderAgent.mPort = server.port; + borderAgent.mPresentFlags |= BorderAgent::kPortBit; + } + else if (type == MDNS_RECORDTYPE_A) + { + struct sockaddr_storage addrStorage; + struct sockaddr_in addr; + std::string addrStr; + + mdns_record_parse_a(data, size, offset, length, &addr); + + *reinterpret_cast(&addrStorage) = addr; + if (fromAddr.Set(addrStorage) != Error::kNone || + fromAddr.ToString(addrStr) != Error::kNone) + { + ExitNow(errorMsg = "invalid IPv4 address in A record"); + } + + // We prefer AAAA (IPv6) address than A (IPv4) address. + if (!(borderAgent.mPresentFlags & BorderAgent::kAddrBit)) + { + borderAgent.mAddr = addrStr; + borderAgent.mPresentFlags |= BorderAgent::kAddrBit; + } + } + else if (type == MDNS_RECORDTYPE_AAAA) + { + struct sockaddr_storage addrStorage; + struct sockaddr_in6 addr; + std::string addrStr; + + mdns_record_parse_aaaa(data, size, offset, length, &addr); + + *reinterpret_cast(&addrStorage) = addr; + if (fromAddr.Set(addrStorage) != Error::kNone || + fromAddr.ToString(addrStr) != Error::kNone) + { + ExitNow(errorMsg = "invalid IPv6 address in AAAA record"); + } + + borderAgent.mAddr = addrStr; + borderAgent.mPresentFlags |= BorderAgent::kAddrBit; + } + else if (type == 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)); + + for (size_t i = 0; i < parsed; ++i) + { + auto key = ToString(txtBuffer[i].key); + auto value = ToString(txtBuffer[i].value); + + if (key == "rv") + { + VerifyOrExit(value == "1", errorMsg = fmt::format("value of TXT Key 'rv' is {} but not 1", value)); + } + else if (key == "tv") + { + borderAgent.mThreadVersion = value; + borderAgent.mPresentFlags |= BorderAgent::kThreadVersionBit; + } + else if (key == "sb") + { + ByteArray bitmap; + if (utils::Hex(bitmap, value) != Error::kNone || bitmap.size() != 4) + { + ExitNow(errorMsg = fmt::format("value of TXT Key 'sb' is invalid: value={:X}", value)); + } + + borderAgent.mState.mConnectionMode = (bitmap[0] >> 5); + borderAgent.mState.mThreadIfStatus = (bitmap[0] << 3) >> 6; + borderAgent.mState.mAvailability = (bitmap[0] << 5) >> 6; + borderAgent.mState.mBbrIsActive = (bitmap[0] << 7) >> 7; + borderAgent.mState.mBbrIsPrimary = (bitmap[1] >> 7); + borderAgent.mPresentFlags |= BorderAgent::kStateBit; + } + else if (key == "nn") + { + borderAgent.mNetworkName = value; + borderAgent.mPresentFlags |= BorderAgent::kNetworkNameBit; + } + else if (key == "xp") + { + ByteArray extendPanId; + if (utils::Hex(extendPanId, value) != Error::kNone || extendPanId.size() != 8) + { + ExitNow(errorMsg = fmt::format("value of TXT Key 'xp' is invalid: value={:X}", value)); + } + else + { + borderAgent.mExtendedPanId = utils::Decode(extendPanId); + borderAgent.mPresentFlags |= BorderAgent::kExtendedPanIdBit; + } + } + else if (key == "vn") + { + borderAgent.mVendorName = value; + borderAgent.mPresentFlags |= BorderAgent::kVendorNameBit; + } + else if (key == "mn") + { + borderAgent.mModelName = value; + borderAgent.mPresentFlags |= BorderAgent::kModelNameBit; + } + else if (key == "at") + { + ByteArray activeTimestamp; + if (utils::Hex(activeTimestamp, value) != Error::kNone || activeTimestamp.size() != 8) + { + ExitNow(errorMsg = fmt::format("value of TXT Key 'at' is invalid: value={:X}", value)); + } + else + { + borderAgent.mActiveTimestamp = Timestamp::Decode(utils::Decode(activeTimestamp)); + borderAgent.mPresentFlags |= BorderAgent::kActiveTimestampBit; + } + } + else if (key == "pt") + { + ByteArray partitionId; + if (utils::Hex(partitionId, value) != Error::kNone || partitionId.size() != 4) + { + ExitNow(errorMsg = fmt::format("value of TXT Key 'pt' is invalid: value={:X}", value)); + } + else + { + borderAgent.mPartitionId = utils::Decode(partitionId); + borderAgent.mPresentFlags |= BorderAgent::kPartitionIdBit; + } + } + else if (key == "vd") + { + borderAgent.mVendorData = value; + borderAgent.mPresentFlags |= BorderAgent::kVendorDataBit; + } + else if (key == "vo") + { + ByteArray oui; + if (utils::Hex(oui, value) != Error::kNone || oui.size() != 3) + { + ExitNow(errorMsg = fmt::format("value of TXT Key 'vo' is invalid: value={:X}", value)); + } + else + { + borderAgent.mVendorOui = oui; + borderAgent.mPresentFlags |= BorderAgent::kVendorOuiBit; + } + } + else if (key == "dn") + { + borderAgent.mDomainName = value; + borderAgent.mPresentFlags |= BorderAgent::kDomainNameBit; + } + else if (key == "sq") + { + ByteArray bbrSeqNum; + if (utils::Hex(bbrSeqNum, value) != Error::kNone || bbrSeqNum.size() != 1) + { + ExitNow(errorMsg = fmt::format("[mDNS] value of TXT Key 'vo' is invalid: {:X}", value)); + } + else + { + borderAgent.mBbrSeqNumber = utils::Decode(bbrSeqNum); + borderAgent.mPresentFlags |= BorderAgent::kBbrSeqNumberBit; + } + } + else if (key == "bb") + { + ByteArray bbrPort; + if (utils::Hex(bbrPort, value) != Error::kNone || bbrPort.size() != 2) + { + ExitNow(errorMsg = fmt::format("[mDNS] value of TXT Key 'vo' is invalid: {:X}", value)); + } + else + { + borderAgent.mBbrPort = utils::Decode(bbrPort); + borderAgent.mPresentFlags |= BorderAgent::kBbrPortBit; + } + } + else + { + // TODO(wgtdkp): add debug logging. + } + } + } + else + { + // TODO(wgtdkp): add debug logging. + } + +exit: + return error == Error::kNone ? 0 : -1; +} + +} // namespace commissioner + +} // namespace ot diff --git a/include/commissioner/border_agent.hpp b/src/app/border_agent.hpp similarity index 83% rename from include/commissioner/border_agent.hpp rename to src/app/border_agent.hpp index 0a577bd61..ec6ce9d05 100644 --- a/include/commissioner/border_agent.hpp +++ b/src/app/border_agent.hpp @@ -28,16 +28,20 @@ /** * @file - * The file includes definition of Thread Border Agent. + * The file defines Border Agent structure and discovery + * by mDNS in local network. */ #ifndef OT_COMM_BORDER_AGENT_HPP_ #define OT_COMM_BORDER_AGENT_HPP_ +#include +#include #include -#include "defines.hpp" -#include "network_data.hpp" +#include +#include +#include namespace ot { @@ -45,6 +49,7 @@ namespace commissioner { /** * The definition of Border Agent discovered by Commissioner. + * */ struct BorderAgent { @@ -153,6 +158,25 @@ struct BorderAgent static constexpr uint16_t kBbrPortBit = 1 << 14; }; +/** + * This function is the callback of a discovered Border Agent. + * + * @param[in] aBorderAgent The discovered Border Agent. nullable. + * @param[in] aErrorMessage The detailed message of a malformed Border Agent response. nullable. + * + */ +using BorderAgentHandler = std::function; + +/** + * Discovery Border Agent in local network with mDNS. + * + * @param[in] aBorderAgentHandler The handler of found Border Agent. + * called once for each Border Agent. + * @param[in] aTimeout The time waiting for mDNS responses. + * + */ +Error DiscoverBorderAgent(BorderAgentHandler aBorderAgentHandler, size_t aTimeout); + } // namespace commissioner } // namespace ot diff --git a/src/app/cli/interpreter.cpp b/src/app/cli/interpreter.cpp index eb83de6ef..451976a0d 100644 --- a/src/app/cli/interpreter.cpp +++ b/src/app/cli/interpreter.cpp @@ -92,8 +92,7 @@ const std::map &Interpreter::mUsageMap = *new std::map {"network", "network save \n" "network pull"}, {"sessionid", "sessionid"}, - {"borderagent", "borderagent discover\n" - "borderagent list\n" + {"borderagent", "borderagent discover []\n" "borderagent get locator\n" "borderagent get meshlocaladdr"}, {"joiner", "joiner enable (meshcop|ae|nmkp) [] []\n" @@ -439,15 +438,16 @@ Interpreter::Value Interpreter::ProcessBorderAgent(const Expression &aExpr) if (CaseInsensitiveEqual(aExpr[1], "discover")) { - SuccessOrExit(error = mCommissioner->Discover()); - } - else if (CaseInsensitiveEqual(aExpr[1], "list")) - { - error = Error::kNone; - for (const auto &ba : mCommissioner->GetBorderAgentList()) + uint64_t timeout = 4000; + + if (aExpr.size() >= 3) { - msg += ToString(ba); + SuccessOrExit(ParseInteger(timeout, aExpr[2]), msg = aExpr[2]); } + + SuccessOrExit(error = DiscoverBorderAgent(BorderAgentHandler, static_cast(timeout))); + + ExitNow(error = Error::kNone); } else if (CaseInsensitiveEqual(aExpr[1], "get")) { @@ -1086,6 +1086,19 @@ Interpreter::Value Interpreter::ProcessHelp(const Expression &aExpr) return {error, msg}; } +void Interpreter::BorderAgentHandler(const BorderAgent *aBorderAgent, const std::string *aErrorMessage) +{ + if (aErrorMessage != nullptr) + { + Console::Write(*aErrorMessage, Console::Color::kRed); + } + else + { + ASSERT(aBorderAgent != nullptr); + Console::Write(ToString(*aBorderAgent), Console::Color::kGreen); + } +} + const std::string Interpreter::Usage(Expression aExpr) { ASSERT(aExpr.size() >= 1); diff --git a/src/app/cli/interpreter.hpp b/src/app/cli/interpreter.hpp index 18d88866b..166640b97 100644 --- a/src/app/cli/interpreter.hpp +++ b/src/app/cli/interpreter.hpp @@ -36,7 +36,8 @@ #include -#include "commissioner_app.hpp" +#include +#include #include "console.hpp" @@ -101,6 +102,8 @@ class Interpreter Value ProcessExit(const Expression &aExpr); Value ProcessHelp(const Expression &aExpr); + static void BorderAgentHandler(const BorderAgent *aBorderAgent, const std::string *aErrorMessage); + static const std::string Usage(Expression aExpr); static Error GetJoinerType(JoinerType &aType, const std::string &aStr); static Error ParseChannelMask(ChannelMask &aChannelMask, const Expression &aExpr, size_t aIndex); diff --git a/src/app/commissioner_app.cpp b/src/app/commissioner_app.cpp index 60a0acb2c..d86e9bb7e 100644 --- a/src/app/commissioner_app.cpp +++ b/src/app/commissioner_app.cpp @@ -108,28 +108,6 @@ Error CommissionerApp::Init(const Config &aConfig) return error; } -Error CommissionerApp::Discover() -{ - return mCommissioner->Discover(mBorderAgents); -} - -const std::list &CommissionerApp::GetBorderAgentList() const -{ - return mBorderAgents; -} - -const BorderAgent *CommissionerApp::GetBorderAgent(const std::string &aNetworkName) -{ - for (auto &ba : mBorderAgents) - { - if (aNetworkName.empty() || aNetworkName == ba.mNetworkName) - { - return &ba; - } - } - return nullptr; -} - Error CommissionerApp::Start(std::string & aExistingCommissionerId, const std::string &aBorderAgentAddr, uint16_t aBorderAgentPort) diff --git a/src/app/commissioner_app.hpp b/src/app/commissioner_app.hpp index 43868b0c6..3e61f4bc1 100644 --- a/src/app/commissioner_app.hpp +++ b/src/app/commissioner_app.hpp @@ -70,16 +70,6 @@ class CommissionerApp static std::shared_ptr Create(const Config &aConfig); ~CommissionerApp() = default; - // Discover Border Agent on link-local network. - Error Discover(); - - // Return all Border Agent ranked by the order they are discovered. - const std::list &GetBorderAgentList() const; - - // Return the discovered Border Agent matching the given Thread network name. - // Set @p aNetworkName to empty to match any network name. - const BorderAgent *GetBorderAgent(const std::string &aNetworkName); - Error Start(std::string &aExistingCommissionerId, const std::string &aBorderAgentAddr, uint16_t aBorderAgentPort); void Stop(); @@ -265,7 +255,6 @@ class CommissionerApp PendingOperationalDataset mPendingDataset; CommissionerDataset mCommDataset; BbrDataset mBbrDataset; - std::list mBorderAgents; }; } // namespace commissioner diff --git a/src/library/CMakeLists.txt b/src/library/CMakeLists.txt index 6a468cd97..742324bb6 100644 --- a/src/library/CMakeLists.txt +++ b/src/library/CMakeLists.txt @@ -51,8 +51,6 @@ target_sources(commissioner event.hpp logging.cpp logging.hpp - multicast_dns.cpp - multicast_dns.hpp network_data.cpp openthread/bloom_filter.cpp openthread/bloom_filter.hpp diff --git a/src/library/commissioner_impl.cpp b/src/library/commissioner_impl.cpp index 5ba3b2c92..d34679090 100644 --- a/src/library/commissioner_impl.cpp +++ b/src/library/commissioner_impl.cpp @@ -142,7 +142,6 @@ CommissionerImpl::CommissionerImpl(struct event_base *aEventBase) : mState(State::kDisabled) , mSessionId(0) , mEventBase(aEventBase) - , mBaQuerier(mEventBase) , mKeepAliveTimer(mEventBase, [this](Timer &aTimer) { SendKeepAlive(aTimer); }) , mBrClient(mEventBase) , mCommissioningSessionTimer(mEventBase, [this](Timer &aTimer) { HandleCommissioningSessionTimer(aTimer); }) @@ -329,11 +328,6 @@ void CommissionerImpl::Resign(ErrorHandler aHandler) aHandler(Error::kNone); } -void CommissionerImpl::Discover(Handler> aHandler) -{ - mBaQuerier.SendQuery(aHandler); -} - void CommissionerImpl::Connect(ErrorHandler aHandler, const std::string &aAddr, uint16_t aPort) { auto onConnected = [aHandler](const DtlsSession &, Error aError) { aHandler(aError); }; diff --git a/src/library/commissioner_impl.hpp b/src/library/commissioner_impl.hpp index c863a4d33..ada33a650 100644 --- a/src/library/commissioner_impl.hpp +++ b/src/library/commissioner_impl.hpp @@ -39,7 +39,6 @@ #include "commissioning_session.hpp" #include "dtls.hpp" #include "event.hpp" -#include "multicast_dns.hpp" #include "timer.hpp" #include "token_manager.hpp" #include "udp_proxy.hpp" @@ -100,9 +99,6 @@ class CommissionerImpl : public Commissioner // Stop the commissioner. void Stop() override; - void Discover(Handler> aHandler) override; - Error Discover(std::list &) override { return Error::kNotImplemented; } - void Connect(ErrorHandler aHandler, const std::string &aAddr, uint16_t aPort) override; Error Connect(const std::string &, uint16_t) override { return Error::kNotImplemented; } @@ -274,8 +270,6 @@ class CommissionerImpl : public Commissioner Config mConfig; - BorderAgentQuerier mBaQuerier; - Timer mKeepAliveTimer; coap::CoapSecure mBrClient; diff --git a/src/library/commissioner_safe.cpp b/src/library/commissioner_safe.cpp index 165a5950e..3673e9556 100644 --- a/src/library/commissioner_safe.cpp +++ b/src/library/commissioner_safe.cpp @@ -118,26 +118,6 @@ void CommissionerSafe::Stop() return; } -void CommissionerSafe::Discover(Handler> aHandler) -{ - PushAsyncRequest([=]() { mImpl.Discover(aHandler); }); -} - -Error CommissionerSafe::Discover(std::list &aBorderAgentList) -{ - std::promise pro; - auto wait = [&pro, &aBorderAgentList](const std::list *borderAgentList, Error error) { - if (borderAgentList != nullptr) - { - aBorderAgentList = *borderAgentList; - } - pro.set_value(error); - }; - - Discover(wait); - return pro.get_future().get(); -} - void CommissionerSafe::Connect(ErrorHandler aHandler, const std::string &aAddr, uint16_t aPort) { PushAsyncRequest([=]() { mImpl.Connect(aHandler, aAddr, aPort); }); diff --git a/src/library/commissioner_safe.hpp b/src/library/commissioner_safe.hpp index f35af6396..21a9f25ba 100644 --- a/src/library/commissioner_safe.hpp +++ b/src/library/commissioner_safe.hpp @@ -96,9 +96,6 @@ class CommissionerSafe : public Commissioner // Stop the commissioner running in background. void Stop() override; - void Discover(Handler> aHandler) override; - Error Discover(std::list &aBorderAgentList) override; - void Connect(ErrorHandler aHandler, const std::string &aAddr, uint16_t aPort) override; Error Connect(const std::string &aAddr, uint16_t aPort) override; diff --git a/src/library/multicast_dns.cpp b/src/library/multicast_dns.cpp deleted file mode 100644 index 69b839c61..000000000 --- a/src/library/multicast_dns.cpp +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Copyright (c) 2019, The OpenThread Authors. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holder nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include "multicast_dns.hpp" - -#include - -#include -#include - -#include "logging.hpp" -#include "timer.hpp" - -namespace ot { - -namespace commissioner { - -BorderAgentQuerier::BorderAgentQuerier(struct event_base *aEventBase) - : mEventBase(aEventBase) - , mSocket(-1) - , mResponseHandler(nullptr) -{ -} - -BorderAgentQuerier::~BorderAgentQuerier() -{ - if (mSocket >= 0) - { - event_del(&mResponseEvent); - mdns_socket_close(mSocket); - } -} - -Error BorderAgentQuerier::Setup() -{ - Error error = Error::kFailed; - - struct timeval tv; - evutil_timerclear(&tv); - tv.tv_sec = kQueryTimeout; - - int socket = mdns_socket_open_ipv4(); - - VerifyOrExit(mSocket < 0, error = Error::kAlready); - - VerifyOrExit(socket >= 0, error = Error::kFailed); - - if (event_assign(&mResponseEvent, mEventBase, socket, EV_PERSIST | EV_READ, ReceiveResponse, this) != 0) - { - ExitNow(error = Error::kFailed); - } - VerifyOrExit(event_add(&mResponseEvent, &tv) == 0, error = Error::kFailed); - - error = Error::kNone; - mSocket = socket; - -exit: - if (error != Error::kNone) - { - if (socket >= 0) - { - mdns_socket_close(socket); - } - } - return error; -} - -void BorderAgentQuerier::SendQuery(ResponseHandler aHandler) -{ - static const mdns_record_type_t kMdnsQueryType = MDNS_RECORDTYPE_PTR; - static const char * kServiceName = "_meshcop._udp.local"; - - Error error = Error::kNone; - uint8_t buf[kDefaultBufferSize]; - - VerifyOrExit(mSocket < 0, error = Error::kBusy); - SuccessOrExit(error = Setup()); - - if (mdns_query_send(mSocket, kMdnsQueryType, kServiceName, strlen(kServiceName), buf, sizeof(buf)) != 0) - { - ExitNow(error = Error::kFailed); - } - - mResponseHandler = aHandler; - -exit: - if (error != Error::kNone) - { - aHandler(nullptr, error); - } -} - -void BorderAgentQuerier::ReceiveResponse(evutil_socket_t aSocket, short aFlags, void *aContext) -{ - auto querier = reinterpret_cast(aContext); - querier->ReceiveResponse(aSocket, aFlags); -} - -void BorderAgentQuerier::ReceiveResponse(evutil_socket_t aSocket, short aFlags) -{ - if (aFlags & EV_TIMEOUT) - { - LOG_INFO("found {} Border Agents", mBorderAgents.size()); - - if (mResponseHandler != nullptr) - { - mResponseHandler(&mBorderAgents, Error::kNone); - mResponseHandler = nullptr; - } - - // The BorderAgentQuerier caches the discovered Border Agents, but doesn't store. - mBorderAgents.clear(); - - if (mSocket >= 0) - { - event_del(&mResponseEvent); - mdns_socket_close(mSocket); - mSocket = -1; - } - } - else - { - uint8_t buf[kDefaultBufferSize]; - - mCurBorderAgent.mPresentFlags = 0; - mdns_query_recv(aSocket, buf, sizeof(buf), HandleRecord, this, 1); - if (ValidateBorderAgent(mCurBorderAgent)) - { - mBorderAgents.push_back(mCurBorderAgent); - } - } -} - -static inline std::string ToString(const mdns_string_t &aString) -{ - return std::string(aString.str, aString.length); -} - -int BorderAgentQuerier::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 * user_data) -{ - return reinterpret_cast(user_data)->HandleRecord(from, entry, type, rclass, ttl, data, size, - offset, length); -} - -int BorderAgentQuerier::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) -{ - Error error = Error::kNone; - struct sockaddr_storage fromAddrStorage; - Address fromAddr; - std::string fromAddrStr; - std::string entryType; - char nameBuffer[256]; - - *reinterpret_cast(&fromAddrStorage) = *from; - SuccessOrExit(error = fromAddr.Set(fromAddrStorage)); - SuccessOrExit(error = fromAddr.ToString(fromAddrStr)); - - entryType = (entry == MDNS_ENTRYTYPE_ANSWER) ? "answer" - : ((entry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional"); - if (type == MDNS_RECORDTYPE_PTR) - { - mdns_string_t nameStr = mdns_record_parse_ptr(data, size, offset, length, nameBuffer, sizeof(nameBuffer)); - LOG_INFO("[mDNS] received from {}: {} PTR={}, type={}, rclass={}, ttl={}, length={}", fromAddrStr, entryType, - ToString(nameStr), type, rclass, ttl, length); - } - else if (type == MDNS_RECORDTYPE_SRV) - { - mdns_record_srv_t server = mdns_record_parse_srv(data, size, offset, length, nameBuffer, sizeof(nameBuffer)); - LOG_INFO("[mDNS] received from {}: {} SRV={}, priority={}, weight={}, port={}", fromAddrStr, entryType, - ToString(server.name), server.priority, server.weight, server.port); - - mCurBorderAgent.mPort = server.port; - mCurBorderAgent.mPresentFlags |= BorderAgent::kPortBit; - } - else if (type == MDNS_RECORDTYPE_A) - { - struct sockaddr_storage addrStorage; - struct sockaddr_in addr; - std::string addrStr; - - mdns_record_parse_a(data, size, offset, length, &addr); - - *reinterpret_cast(&addrStorage) = addr; - SuccessOrExit(error = fromAddr.Set(addrStorage)); - SuccessOrExit(error = fromAddr.ToString(addrStr)); - - LOG_INFO("[mDNS] received from {}: {} A={}", fromAddrStr, entryType, addrStr); - - // We prefer AAAA (IPv6) address than A (IPv4) address. - if (!(mCurBorderAgent.mPresentFlags & BorderAgent::kAddrBit)) - { - mCurBorderAgent.mAddr = addrStr; - mCurBorderAgent.mPresentFlags |= BorderAgent::kAddrBit; - } - } - else if (type == MDNS_RECORDTYPE_AAAA) - { - struct sockaddr_storage addrStorage; - struct sockaddr_in6 addr; - std::string addrStr; - - mdns_record_parse_aaaa(data, size, offset, length, &addr); - - *reinterpret_cast(&addrStorage) = addr; - SuccessOrExit(error = fromAddr.Set(addrStorage)); - SuccessOrExit(error = fromAddr.ToString(addrStr)); - - LOG_INFO("[mDNS] received from {}: {} AAAA={}", fromAddrStr, entryType, addrStr); - - mCurBorderAgent.mAddr = addrStr; - mCurBorderAgent.mPresentFlags |= BorderAgent::kAddrBit; - } - else if (type == MDNS_RECORDTYPE_TXT) - { - mdns_record_txt_t txtBuffer[128]; - size_t parsed = - mdns_record_parse_txt(data, size, offset, length, txtBuffer, sizeof(txtBuffer) / sizeof(mdns_record_txt_t)); - for (size_t i = 0; i < parsed; ++i) - { - auto key = ToString(txtBuffer[i].key); - auto value = ToString(txtBuffer[i].value); - - LOG_INFO("[mDNS] received from {}: {} TXT.{}={}", fromAddrStr, entryType, key, value); - - if (key == "rv") - { - if (value != "1") - { - LOG_ERROR("[mDNS] value of TXT Key 'rv' is not '1'"); - ExitNow(error = Error::kBadFormat); - } - } - else if (key == "tv") - { - mCurBorderAgent.mThreadVersion = value; - mCurBorderAgent.mPresentFlags |= BorderAgent::kThreadVersionBit; - } - else if (key == "sb") - { - ByteArray bitmap; - if (utils::Hex(bitmap, value) != Error::kNone || bitmap.size() != 4) - { - LOG_ERROR("[mDNS] value of TXT Key 'sb' is invalid: {}", value); - ExitNow(error = Error::kBadFormat); - } - - mCurBorderAgent.mState.mConnectionMode = (bitmap[0] >> 5); - mCurBorderAgent.mState.mThreadIfStatus = (bitmap[0] << 3) >> 6; - mCurBorderAgent.mState.mAvailability = (bitmap[0] << 5) >> 6; - mCurBorderAgent.mState.mBbrIsActive = (bitmap[0] << 7) >> 7; - mCurBorderAgent.mState.mBbrIsPrimary = (bitmap[1] >> 7); - mCurBorderAgent.mPresentFlags |= BorderAgent::kStateBit; - } - else if (key == "nn") - { - mCurBorderAgent.mNetworkName = value; - mCurBorderAgent.mPresentFlags |= BorderAgent::kNetworkNameBit; - } - else if (key == "xp") - { - ByteArray extendPanId; - if (utils::Hex(extendPanId, value) != Error::kNone || extendPanId.size() != 8) - { - LOG_WARN("[mDNS] value of TXT Key 'xp' is invalid: {}", value); - } - else - { - mCurBorderAgent.mExtendedPanId = utils::Decode(extendPanId); - mCurBorderAgent.mPresentFlags |= BorderAgent::kExtendedPanIdBit; - } - } - else if (key == "vn") - { - mCurBorderAgent.mVendorName = value; - mCurBorderAgent.mPresentFlags |= BorderAgent::kVendorNameBit; - } - else if (key == "mn") - { - mCurBorderAgent.mModelName = value; - mCurBorderAgent.mPresentFlags |= BorderAgent::kModelNameBit; - } - else if (key == "at") - { - ByteArray activeTimestamp; - if (utils::Hex(activeTimestamp, value) != Error::kNone || activeTimestamp.size() != 8) - { - LOG_WARN("[mDNS] value of TXT Key 'at' is invalid: {}", value); - } - else - { - mCurBorderAgent.mActiveTimestamp = Timestamp::Decode(utils::Decode(activeTimestamp)); - mCurBorderAgent.mPresentFlags |= BorderAgent::kActiveTimestampBit; - } - } - else if (key == "pt") - { - ByteArray partitionId; - if (utils::Hex(partitionId, value) != Error::kNone || partitionId.size() != 4) - { - LOG_WARN("[mDNS] value of TXT Key 'pt' is invalid: {}", value); - } - else - { - mCurBorderAgent.mPartitionId = utils::Decode(partitionId); - mCurBorderAgent.mPresentFlags |= BorderAgent::kPartitionIdBit; - } - } - else if (key == "vd") - { - mCurBorderAgent.mVendorData = value; - mCurBorderAgent.mPresentFlags |= BorderAgent::kVendorDataBit; - } - else if (key == "vo") - { - ByteArray oui; - if (utils::Hex(oui, value) != Error::kNone || oui.size() != 3) - { - LOG_WARN("[mDNS] value of TXT Key 'vo' is invalid: {}", value); - } - else - { - mCurBorderAgent.mVendorOui = oui; - mCurBorderAgent.mPresentFlags |= BorderAgent::kVendorOuiBit; - } - } - else if (key == "dn") - { - mCurBorderAgent.mDomainName = value; - mCurBorderAgent.mPresentFlags |= BorderAgent::kDomainNameBit; - } - else if (key == "sq") - { - ByteArray bbrSeqNum; - if (utils::Hex(bbrSeqNum, value) != Error::kNone || bbrSeqNum.size() != 1) - { - LOG_WARN("[mDNS] value of TXT Key 'vo' is invalid: {}", value); - } - else - { - mCurBorderAgent.mBbrSeqNumber = utils::Decode(bbrSeqNum); - mCurBorderAgent.mPresentFlags |= BorderAgent::kBbrSeqNumberBit; - } - } - else if (key == "bb") - { - ByteArray bbrPort; - if (utils::Hex(bbrPort, value) != Error::kNone || bbrPort.size() != 2) - { - LOG_WARN("[mDNS] value of TXT Key 'vo' is invalid: {}", value); - } - else - { - mCurBorderAgent.mBbrPort = utils::Decode(bbrPort); - mCurBorderAgent.mPresentFlags |= BorderAgent::kBbrPortBit; - } - } - else - { - LOG_WARN("[mDNS] unknown TXT key: {}", key); - } - } - } - else - { - LOG_INFO("[mDNS] received from {}: {} type={}, rclass={}, ttl={}, length={}", fromAddrStr, entryType, type, - rclass, ttl, length); - } - -exit: - return error == Error::kNone ? 0 : -1; -} - -bool BorderAgentQuerier::ValidateBorderAgent(const BorderAgent &aBorderAgent) -{ - bool ret = true; - if (!(aBorderAgent.mPresentFlags & BorderAgent::kAddrBit)) - { - LOG_ERROR("'addr' of a border agent is mandatory"); - ret = false; - } - if (!(aBorderAgent.mPresentFlags & BorderAgent::kPortBit)) - { - LOG_ERROR("'port' of a border agent is mandatory"); - ret = false; - } - if (!(aBorderAgent.mPresentFlags & BorderAgent::kThreadVersionBit)) - { - LOG_ERROR("'thread version' of a border agent is mandatory"); - ret = false; - } - if (!(aBorderAgent.mPresentFlags & BorderAgent::kStateBit)) - { - LOG_ERROR("'state bitmap' of a border agent is mandatory"); - ret = false; - } - if (!(aBorderAgent.mPresentFlags & BorderAgent::kNetworkNameBit) && - (aBorderAgent.mPresentFlags & BorderAgent::kStateBit) && aBorderAgent.mState.mConnectionMode != 0) - { - LOG_ERROR("'network name' of a border agent is mandatory when connection mode is not '0'"); - ret = false; - } - if (!(aBorderAgent.mPresentFlags & BorderAgent::kExtendedPanIdBit) && - (aBorderAgent.mPresentFlags & BorderAgent::kStateBit) && aBorderAgent.mState.mConnectionMode != 0) - { - LOG_ERROR("'extended PAN ID' of a border agent is mandatory when connection mode is not '0'"); - ret = false; - } - if (!(aBorderAgent.mPresentFlags & BorderAgent::kVendorOuiBit) && - (aBorderAgent.mPresentFlags & BorderAgent::kVendorDataBit)) - { - LOG_ERROR("'vendor OUI' of a border agent is mandatory when 'vendor data' is present"); - ret = false; - } - return ret; -} - -} // namespace commissioner - -} // namespace ot diff --git a/src/library/multicast_dns.hpp b/src/library/multicast_dns.hpp deleted file mode 100644 index 3e7680c6e..000000000 --- a/src/library/multicast_dns.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2019, 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. - */ - -/** - * @file - * The file defines the mDNS querier which discovers Thread Border Agent in - * link-local network. - */ - -#ifndef OT_COMM_LIBRARY_MULTICAST_DNS_HPP_ -#define OT_COMM_LIBRARY_MULTICAST_DNS_HPP_ - -#include - -#include - -#include - -#include "event.hpp" -#include "time.hpp" - -namespace ot { - -namespace commissioner { - -class BorderAgentQuerier -{ -public: - using ResponseHandler = Commissioner::Handler>; - - BorderAgentQuerier(struct event_base *aEventBase); - ~BorderAgentQuerier(); - - void SendQuery(ResponseHandler aHandler); - -private: - static const size_t kDefaultBufferSize = 1024 * 16; // In bytes. - static const size_t kQueryTimeout = 4; // In seconds. - - static void ReceiveResponse(evutil_socket_t aSocket, short aFlags, void *aContext); - void ReceiveResponse(evutil_socket_t aSocket, short aFlags); - - static 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 * user_data); - 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); - bool ValidateBorderAgent(const BorderAgent &aBorderAgent); - Error Setup(); - - struct event_base * mEventBase; - struct event mResponseEvent; - int mSocket; - ResponseHandler mResponseHandler; - std::list mBorderAgents; - BorderAgent mCurBorderAgent; -}; - -} // namespace commissioner - -} // namespace ot - -#endif // OT_COMM_LIBRARY_MULTICAST_DNS_HPP_ diff --git a/tests/unit/test_commissioner_impl.cpp b/tests/unit/test_commissioner_impl.cpp index df2c31775..065761934 100644 --- a/tests/unit/test_commissioner_impl.cpp +++ b/tests/unit/test_commissioner_impl.cpp @@ -55,8 +55,6 @@ TEST_CASE("commissioner-impl-not-implemented-APIs", "[comm-impl]") CommissionerImpl commImpl(eventBase); REQUIRE(commImpl.Init(config) == Error::kNone); - std::list baList; - REQUIRE(commImpl.Discover(baList) == Error::kNotImplemented); REQUIRE(commImpl.Connect("::1", 5684) == Error::kNotImplemented); std::string existingCommissionerId; From c410ec6784cb8ad6bcb92e3f8910d45cdd6df172 Mon Sep 17 00:00:00 2001 From: kangping Date: Sun, 29 Mar 2020 17:47:44 +0800 Subject: [PATCH 2/5] [test] fix integration tests --- tests/integration/test_discover.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/test_discover.sh b/tests/integration/test_discover.sh index 88dd307fc..6e037fa8a 100755 --- a/tests/integration/test_discover.sh +++ b/tests/integration/test_discover.sh @@ -39,6 +39,6 @@ test_discover() { send_command_to_commissioner "borderagent discover" ## TODO(wgtdkp): verify the output - send_command_to_commissioner "borderagent list" + stop_commissioner } From 2b1f5c95a96a14fbad43d1a1c6e324a3da88a262 Mon Sep 17 00:00:00 2001 From: kangping Date: Sun, 29 Mar 2020 17:51:21 +0800 Subject: [PATCH 3/5] [test] update comments --- tests/integration/test_discover.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/test_discover.sh b/tests/integration/test_discover.sh index 6e037fa8a..684f5bbed 100755 --- a/tests/integration/test_discover.sh +++ b/tests/integration/test_discover.sh @@ -36,9 +36,9 @@ test_discover() { form_network "${PSKC}" start_commissioner "${NON_CCM_CONFIG}" - send_command_to_commissioner "borderagent discover" ## TODO(wgtdkp): verify the output + send_command_to_commissioner "borderagent discover" stop_commissioner } From ba282932a94c3bdb1b254ff5a87dcc8cb21b8e52 Mon Sep 17 00:00:00 2001 From: kangping Date: Mon, 30 Mar 2020 09:36:15 +0800 Subject: [PATCH 4/5] make pretty --- src/app/border_agent.cpp | 42 +++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/src/app/border_agent.cpp b/src/app/border_agent.cpp index 0c5f41a55..ac66d00a1 100644 --- a/src/app/border_agent.cpp +++ b/src/app/border_agent.cpp @@ -60,9 +60,9 @@ static int HandleRecord(const struct sockaddr *from, Error DiscoverBorderAgent(BorderAgentHandler aBorderAgentHandler, size_t aTimeout) { - static constexpr size_t kDefaultBufferSize = 1024 * 16; - static constexpr mdns_record_type_t kMdnsQueryType = MDNS_RECORDTYPE_PTR; - static const char * kServiceName = "_meshcop._udp.local"; + static constexpr size_t kDefaultBufferSize = 1024 * 16; + static constexpr mdns_record_type_t kMdnsQueryType = MDNS_RECORDTYPE_PTR; + static const char * kServiceName = "_meshcop._udp.local"; Error error = Error::kNone; uint8_t buf[kDefaultBufferSize]; @@ -116,15 +116,15 @@ static inline std::string ToString(const mdns_string_t &aString) * */ static 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 * border_agent) + 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 * border_agent) { Error error = Error::kNone; struct sockaddr_storage fromAddrStorage; @@ -133,16 +133,15 @@ static int HandleRecord(const struct sockaddr *from, std::string entryType; char nameBuffer[256]; - BorderAgentOrErrorMsg &borderAgentOrErrorMsg = *reinterpret_cast(border_agent); - BorderAgent &borderAgent = borderAgentOrErrorMsg.mBorderAgent; - std::string &errorMsg = borderAgentOrErrorMsg.mErrorMsg; + BorderAgentOrErrorMsg &borderAgentOrErrorMsg = *reinterpret_cast(border_agent); + BorderAgent & borderAgent = borderAgentOrErrorMsg.mBorderAgent; + std::string & errorMsg = borderAgentOrErrorMsg.mErrorMsg; (void)rclass; (void)ttl; *reinterpret_cast(&fromAddrStorage) = *from; - if (fromAddr.Set(fromAddrStorage) != Error::kNone || - fromAddr.ToString(fromAddrStr) != Error::kNone) + if (fromAddr.Set(fromAddrStorage) != Error::kNone || fromAddr.ToString(fromAddrStr) != Error::kNone) { ExitNow(errorMsg = "invalid source address of mDNS response"); } @@ -171,8 +170,7 @@ static int HandleRecord(const struct sockaddr *from, mdns_record_parse_a(data, size, offset, length, &addr); *reinterpret_cast(&addrStorage) = addr; - if (fromAddr.Set(addrStorage) != Error::kNone || - fromAddr.ToString(addrStr) != Error::kNone) + if (fromAddr.Set(addrStorage) != Error::kNone || fromAddr.ToString(addrStr) != Error::kNone) { ExitNow(errorMsg = "invalid IPv4 address in A record"); } @@ -193,8 +191,7 @@ static int HandleRecord(const struct sockaddr *from, mdns_record_parse_aaaa(data, size, offset, length, &addr); *reinterpret_cast(&addrStorage) = addr; - if (fromAddr.Set(addrStorage) != Error::kNone || - fromAddr.ToString(addrStr) != Error::kNone) + if (fromAddr.Set(addrStorage) != Error::kNone || fromAddr.ToString(addrStr) != Error::kNone) { ExitNow(errorMsg = "invalid IPv6 address in AAAA record"); } @@ -207,7 +204,8 @@ static int HandleRecord(const struct sockaddr *from, 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(data, size, offset, length, txtBuffer, sizeof(txtBuffer) / sizeof(mdns_record_txt_t)); for (size_t i = 0; i < parsed; ++i) { From 2f0bf3e4d02a6d71446e671e3031b2a0a449bbef Mon Sep 17 00:00:00 2001 From: kangping Date: Sat, 18 Apr 2020 17:28:38 +0800 Subject: [PATCH 5/5] rebase to master --- src/app/CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index 283daa15e..98ca6e4b1 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -47,6 +47,8 @@ target_link_libraries(commissioner-app commissioner commissioner-common PRIVATE + fmt::fmt + mdns nlohmann_json::nlohmann_json )