From efc231234bef005674485d0b39030a5c6add15ab Mon Sep 17 00:00:00 2001 From: yunhanw Date: Wed, 14 Apr 2021 23:32:45 -0700 Subject: [PATCH] Revert "Use exchange for session establishment and provisioning (#5938)" This reverts commit 362c5f25d388035c3326a6d03dceaaa09cbd7100. --- examples/chip-tool/main.cpp | 2 +- examples/shell/shell_common/cmd_ping.cpp | 2 +- src/app/InteractionModelDelegate.h | 1 - src/app/chip_data_model.gni | 1 - .../network-commissioning.cpp | 2 +- src/app/server/BUILD.gn | 2 - src/app/server/Mdns.cpp | 2 +- src/app/server/RendezvousServer.cpp | 9 +- src/app/server/RendezvousServer.h | 7 +- src/app/server/Server.cpp | 8 +- src/app/tests/BUILD.gn | 1 - src/app/tests/TestCommandInteraction.cpp | 19 +- src/app/tests/TestReadInteraction.cpp | 2 +- src/app/tests/TestReportingEngine.cpp | 14 +- .../tests/integration/chip_im_initiator.cpp | 3 +- .../tests/integration/chip_im_responder.cpp | 2 +- src/controller/BUILD.gn | 1 - src/controller/CHIPDevice.cpp | 12 - src/controller/CHIPDevice.h | 2 +- src/controller/CHIPDeviceController.cpp | 4 +- src/controller/CHIPDeviceController.h | 2 +- src/messaging/ApplicationExchangeDispatch.cpp | 74 ------- src/messaging/ApplicationExchangeDispatch.h | 64 ------ src/messaging/BUILD.gn | 4 - src/messaging/ExchangeContext.cpp | 146 +++++++++---- src/messaging/ExchangeContext.h | 19 +- src/messaging/ExchangeDelegate.h | 25 +-- src/messaging/ExchangeMessageDispatch.cpp | 134 ------------ src/messaging/ExchangeMessageDispatch.h | 73 ------- src/messaging/ExchangeMgr.cpp | 20 +- src/messaging/ExchangeMgr.h | 20 +- src/messaging/MessageCounterSync.cpp | 11 +- src/messaging/ReliableMessageContext.h | 1 - src/messaging/ReliableMessageMgr.cpp | 37 ++-- src/messaging/tests/MessagingContext.h | 1 - .../tests/TestMessageCounterSyncMgr.cpp | 6 +- src/messaging/tests/echo/echo_requester.cpp | 2 +- src/messaging/tests/echo/echo_responder.cpp | 2 +- src/protocols/secure_channel/BUILD.gn | 10 - .../SessionEstablishmentExchangeDispatch.cpp | 93 -------- .../SessionEstablishmentExchangeDispatch.h | 77 ------- src/transport/AdminPairingTable.h | 4 +- src/transport/BLE.cpp | 25 +-- src/transport/BLE.h | 13 +- src/transport/BUILD.gn | 9 + .../NetworkProvisioning.cpp | 48 ++-- .../NetworkProvisioning.h | 18 +- .../PASESession.cpp | 129 ++++++----- .../PASESession.h | 82 +++---- src/transport/PairingSession.h | 73 ------- .../RendezvousParameters.h | 2 +- .../RendezvousSession.cpp | 206 +++++++++++++++--- .../RendezvousSession.h | 34 +-- src/transport/SecureSessionMgr.cpp | 92 +++----- src/transport/SecureSessionMgr.h | 13 +- .../StorablePeerConnection.cpp | 2 +- .../StorablePeerConnection.h | 2 +- src/transport/TransportMgrBase.cpp | 6 +- src/transport/TransportMgrBase.h | 3 + src/transport/raw/tests/TestTCP.cpp | 1 + src/transport/raw/tests/TestUDP.cpp | 1 + src/transport/tests/BUILD.gn | 1 + .../tests/TestPASESession.cpp | 80 +++---- src/transport/tests/TestSecureSessionMgr.cpp | 4 +- 64 files changed, 612 insertions(+), 1153 deletions(-) delete mode 100644 src/messaging/ApplicationExchangeDispatch.cpp delete mode 100644 src/messaging/ApplicationExchangeDispatch.h delete mode 100644 src/messaging/ExchangeMessageDispatch.cpp delete mode 100644 src/messaging/ExchangeMessageDispatch.h delete mode 100644 src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.cpp delete mode 100644 src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.h rename src/{protocols/secure_channel => transport}/NetworkProvisioning.cpp (88%) rename src/{protocols/secure_channel => transport}/NetworkProvisioning.h (82%) rename src/{protocols/secure_channel => transport}/PASESession.cpp (85%) rename src/{protocols/secure_channel => transport}/PASESession.h (80%) delete mode 100644 src/transport/PairingSession.h rename src/{protocols/secure_channel => transport}/RendezvousParameters.h (99%) rename src/{protocols/secure_channel => transport}/RendezvousSession.cpp (56%) rename src/{protocols/secure_channel => transport}/RendezvousSession.h (77%) rename src/{app/server => transport}/StorablePeerConnection.cpp (98%) rename src/{app/server => transport}/StorablePeerConnection.h (97%) rename src/{protocols/secure_channel => transport}/tests/TestPASESession.cpp (71%) diff --git a/examples/chip-tool/main.cpp b/examples/chip-tool/main.cpp index 164c8c77260d50..5c463e0a336283 100644 --- a/examples/chip-tool/main.cpp +++ b/examples/chip-tool/main.cpp @@ -24,7 +24,7 @@ #include "commands/payload/Commands.h" #include "commands/reporting/Commands.h" -#include +#include // ================================================================================ // Main Code diff --git a/examples/shell/shell_common/cmd_ping.cpp b/examples/shell/shell_common/cmd_ping.cpp index fe8d54ab7ac4e1..579b33e3dd49a2 100644 --- a/examples/shell/shell_common/cmd_ping.cpp +++ b/examples/shell/shell_common/cmd_ping.cpp @@ -26,8 +26,8 @@ #include #include #include -#include #include +#include #include #include #include diff --git a/src/app/InteractionModelDelegate.h b/src/app/InteractionModelDelegate.h index 6e1276e122e917..c5dd99237a8402 100644 --- a/src/app/InteractionModelDelegate.h +++ b/src/app/InteractionModelDelegate.h @@ -26,7 +26,6 @@ #include #include #include -#include #include namespace chip { diff --git a/src/app/chip_data_model.gni b/src/app/chip_data_model.gni index 0ffe6deb6dd6c1..39cced67d04832 100644 --- a/src/app/chip_data_model.gni +++ b/src/app/chip_data_model.gni @@ -146,7 +146,6 @@ template("chip_data_model") { "${chip_root}/src/app", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", - "${chip_root}/src/protocols/secure_channel", ] if (!defined(public_configs)) { diff --git a/src/app/clusters/network-commissioning/network-commissioning.cpp b/src/app/clusters/network-commissioning/network-commissioning.cpp index bb79ca1b47e8ee..2bde91379be3ca 100644 --- a/src/app/clusters/network-commissioning/network-commissioning.cpp +++ b/src/app/clusters/network-commissioning/network-commissioning.cpp @@ -41,7 +41,7 @@ #include #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include // Include DeviceNetworkProvisioningDelegateImpl for WiFi provisioning. // TODO: Enable wifi network should be done by ConnectivityManager. (Or other platform neutral interfaces) diff --git a/src/app/server/BUILD.gn b/src/app/server/BUILD.gn index 00922ad935afbf..d0c924ea483d1c 100644 --- a/src/app/server/BUILD.gn +++ b/src/app/server/BUILD.gn @@ -39,8 +39,6 @@ static_library("server") { "RendezvousServer.h", "Server.cpp", "Server.h", - "StorablePeerConnection.cpp", - "StorablePeerConnection.h", ] public_configs = [ ":server_config" ] diff --git a/src/app/server/Mdns.cpp b/src/app/server/Mdns.cpp index b84b419503581e..bab11c353c199a 100644 --- a/src/app/server/Mdns.cpp +++ b/src/app/server/Mdns.cpp @@ -24,10 +24,10 @@ #include #include #include -#include #include #include #include +#include #include "Server.h" diff --git a/src/app/server/RendezvousServer.cpp b/src/app/server/RendezvousServer.cpp index 1e4f75ffcece18..12da82748eca12 100644 --- a/src/app/server/RendezvousServer.cpp +++ b/src/app/server/RendezvousServer.cpp @@ -17,11 +17,11 @@ #include -#include #include #include #include #include +#include #if CHIP_ENABLE_OPENTHREAD #include @@ -36,11 +36,10 @@ namespace chip { RendezvousServer::RendezvousServer() : mRendezvousSession(this) {} -CHIP_ERROR RendezvousServer::WaitForPairing(const RendezvousParameters & params, Messaging::ExchangeManager * exchangeManager, - TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr, - Transport::AdminPairingInfo * admin) +CHIP_ERROR RendezvousServer::WaitForPairing(const RendezvousParameters & params, TransportMgrBase * transportMgr, + SecureSessionMgr * sessionMgr, Transport::AdminPairingInfo * admin) { - return mRendezvousSession.Init(params, exchangeManager, transportMgr, sessionMgr, admin); + return mRendezvousSession.Init(params, transportMgr, sessionMgr, admin); } void RendezvousServer::OnRendezvousError(CHIP_ERROR err) diff --git a/src/app/server/RendezvousServer.h b/src/app/server/RendezvousServer.h index 49b38906c04674..8d8209fee14787 100644 --- a/src/app/server/RendezvousServer.h +++ b/src/app/server/RendezvousServer.h @@ -19,9 +19,8 @@ #include #include -#include #include -#include +#include namespace chip { @@ -30,8 +29,8 @@ class RendezvousServer : public RendezvousSessionDelegate public: RendezvousServer(); - CHIP_ERROR WaitForPairing(const RendezvousParameters & params, Messaging::ExchangeManager * exchangeManager, - TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr, Transport::AdminPairingInfo * admin); + CHIP_ERROR WaitForPairing(const RendezvousParameters & params, TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr, + Transport::AdminPairingInfo * admin); CHIP_ERROR Init(AppDelegate * delegate, PersistentStorageDelegate * storage) { diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 310b8de5673d71..62eb0dab9715c2 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -41,6 +40,7 @@ #include #include #include +#include #include "Mdns.h" @@ -296,7 +296,6 @@ class ServerRendezvousAdvertisementDelegate : public RendezvousAdvertisementDele DemoTransportMgr gTransports; SecureSessionMgr gSessions; RendezvousServer gRendezvousServer; -Messaging::ExchangeManager gExchangeMgr; ServerRendezvousAdvertisementDelegate gAdvDelegate; static CHIP_ERROR OpenPairingWindowUsingVerifier(uint16_t discriminator, PASEVerifier & verifier) @@ -319,7 +318,7 @@ static CHIP_ERROR OpenPairingWindowUsingVerifier(uint16_t discriminator, PASEVer VerifyOrReturnError(adminInfo != nullptr, CHIP_ERROR_NO_MEMORY); gNextAvailableAdminId++; - return gRendezvousServer.WaitForPairing(std::move(params), &gExchangeMgr, &gTransports, &gSessions, adminInfo); + return gRendezvousServer.WaitForPairing(std::move(params), &gTransports, &gSessions, adminInfo); } class ServerCallback : public ExchangeDelegate @@ -408,6 +407,7 @@ class ServerCallback : public ExchangeDelegate SecureSessionMgr * mSessionMgr = nullptr; }; +Messaging::ExchangeManager gExchangeMgr; ServerCallback gCallbacks; SecurePairingUsingTestSecret gTestPairing; @@ -457,7 +457,7 @@ CHIP_ERROR OpenDefaultPairingWindow(ResetAdmins resetAdmins, chip::PairingWindow VerifyOrReturnError(adminInfo != nullptr, CHIP_ERROR_NO_MEMORY); gNextAvailableAdminId++; - return gRendezvousServer.WaitForPairing(std::move(params), &gExchangeMgr, &gTransports, &gSessions, adminInfo); + return gRendezvousServer.WaitForPairing(std::move(params), &gTransports, &gSessions, adminInfo); } // The function will initialize datamodel handler and then start the server diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 41294f6dfd1558..8d8e838f197847 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -33,7 +33,6 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/app", "${chip_root}/src/lib/core", - "${chip_root}/src/protocols", "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 2a69977df54207..b92ab7b60bc1d6 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -31,11 +31,11 @@ #include #include #include -#include #include #include #include #include +#include #include #include @@ -68,15 +68,6 @@ class TestCommandInteraction bool aIsEmptyResponse); }; -class TestExchangeDelegate : public Messaging::ExchangeDelegate -{ - void OnMessageReceived(Messaging::ExchangeContext * ec, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - System::PacketBufferHandle payload) override - {} - - void OnResponseTimeout(Messaging::ExchangeContext * ec) override {} -}; - void TestCommandInteraction::GenerateReceivedCommand(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -198,9 +189,7 @@ void TestCommandInteraction::TestCommandHandlerWithSendEmptyCommand(nlTestSuite NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); commandHandler.mpExchangeCtx = gExchangeManager.NewContext({ 0, 0, 0 }, nullptr); - TestExchangeDelegate delegate; - commandHandler.mpExchangeCtx->SetDelegate(&delegate); - err = commandHandler.AddCommand(commandParams); + err = commandHandler.AddCommand(commandParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); err = commandHandler.SendCommandResponse(); NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_NOT_CONNECTED); @@ -232,9 +221,7 @@ void TestCommandInteraction::ValidateCommandHandlerWithSendCommand(nlTestSuite * NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); commandHandler.mpExchangeCtx = gExchangeManager.NewContext({ 0, 0, 0 }, nullptr); - TestExchangeDelegate delegate; - commandHandler.mpExchangeCtx->SetDelegate(&delegate); - + ; AddCommandDataElement(apSuite, apContext, &commandHandler, aNeedStatusCode, aIsEmptyResponse); err = commandHandler.SendCommandResponse(); NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_NOT_CONNECTED); diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index e7df1641914a9a..5e98304d6a8478 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -31,11 +31,11 @@ #include #include #include -#include #include #include #include #include +#include #include #include diff --git a/src/app/tests/TestReportingEngine.cpp b/src/app/tests/TestReportingEngine.cpp index 974bfaae367316..5506fa223f5227 100644 --- a/src/app/tests/TestReportingEngine.cpp +++ b/src/app/tests/TestReportingEngine.cpp @@ -32,11 +32,11 @@ #include #include #include -#include #include #include #include #include +#include #include #include @@ -57,15 +57,6 @@ class TestReportingEngine static void TestBuildAndSendSingleReportData(nlTestSuite * apSuite, void * apContext); }; -class TestExchangeDelegate : public Messaging::ExchangeDelegate -{ - void OnMessageReceived(Messaging::ExchangeContext * ec, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - System::PacketBufferHandle payload) override - {} - - void OnResponseTimeout(Messaging::ExchangeContext * ec) override {} -}; - void TestReportingEngine::TestBuildAndSendSingleReportData(nlTestSuite * apSuite, void * apContext) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -78,9 +69,6 @@ void TestReportingEngine::TestBuildAndSendSingleReportData(nlTestSuite * apSuite err = InteractionModelEngine::GetInstance()->Init(&gExchangeManager, nullptr); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); Messaging::ExchangeContext * exchangeCtx = gExchangeManager.NewContext({ 0, 0, 0 }, nullptr); - TestExchangeDelegate delegate; - exchangeCtx->SetDelegate(&delegate); - writer.Init(std::move(readRequestbuf)); err = readRequestBuilder.Init(&writer); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); diff --git a/src/app/tests/integration/chip_im_initiator.cpp b/src/app/tests/integration/chip_im_initiator.cpp index 4deba524d356ec..7be6deddfefa84 100644 --- a/src/app/tests/integration/chip_im_initiator.cpp +++ b/src/app/tests/integration/chip_im_initiator.cpp @@ -33,9 +33,10 @@ #include #include #include -#include + #include #include +#include #include #include diff --git a/src/app/tests/integration/chip_im_responder.cpp b/src/app/tests/integration/chip_im_responder.cpp index c1a8523ba37ea9..38211a1d4867e2 100644 --- a/src/app/tests/integration/chip_im_responder.cpp +++ b/src/app/tests/integration/chip_im_responder.cpp @@ -33,9 +33,9 @@ #include #include #include -#include #include #include +#include #include #include diff --git a/src/controller/BUILD.gn b/src/controller/BUILD.gn index 6cb30f86880a2c..79558e762ab094 100644 --- a/src/controller/BUILD.gn +++ b/src/controller/BUILD.gn @@ -41,7 +41,6 @@ static_library("controller") { "${chip_root}/src/lib/support", "${chip_root}/src/messaging", "${chip_root}/src/platform", - "${chip_root}/src/protocols", "${chip_root}/src/setup_payload", "${chip_root}/src/transport", ] diff --git a/src/controller/CHIPDevice.cpp b/src/controller/CHIPDevice.cpp index a75ffeb0f61d83..3439874258263f 100644 --- a/src/controller/CHIPDevice.cpp +++ b/src/controller/CHIPDevice.cpp @@ -55,15 +55,6 @@ using namespace chip::Callback; namespace chip { namespace Controller { -// TODO: This is a placeholder delegate for exchange context created in Device::SendMessage() -// Delete this class when Device::SendMessage() is obsoleted. -class DeviceExchangeDelegate : public Messaging::ExchangeDelegate -{ - void OnMessageReceived(Messaging::ExchangeContext * ec, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - System::PacketBufferHandle payload) override - {} - void OnResponseTimeout(Messaging::ExchangeContext * ec) override {} -}; CHIP_ERROR Device::SendMessage(Protocols::Id protocolId, uint8_t msgType, System::PacketBufferHandle buffer) { @@ -95,9 +86,6 @@ CHIP_ERROR Device::SendMessage(Protocols::Id protocolId, uint8_t msgType, System // receive the ack message. This logic need to be deleted after we converting all legacy ZCL messages to IM messages. sendFlags.Set(Messaging::SendMessageFlags::kFromInitiator).Set(Messaging::SendMessageFlags::kNoAutoRequestAck); - DeviceExchangeDelegate delegate; - exchange->SetDelegate(&delegate); - CHIP_ERROR err = exchange->SendMessage(protocolId, msgType, std::move(buffer), sendFlags); buffer = nullptr; diff --git a/src/controller/CHIPDevice.h b/src/controller/CHIPDevice.h index f2ce804ecc8c23..41b44685818841 100644 --- a/src/controller/CHIPDevice.h +++ b/src/controller/CHIPDevice.h @@ -33,10 +33,10 @@ #include #include #include -#include #include #include #include +#include #include #include #include diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index aa5688a261fcd3..44e39f9a3510de 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -705,8 +705,8 @@ CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParam mRendezvousSession = chip::Platform::New(this); VerifyOrExit(mRendezvousSession != nullptr, err = CHIP_ERROR_NO_MEMORY); mRendezvousSession->SetNextKeyId(mNextKeyId); - err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId).SetRemoteNodeId(remoteDeviceId), mExchangeMgr, - mTransportMgr, mSessionMgr, admin); + err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId).SetRemoteNodeId(remoteDeviceId), mTransportMgr, + mSessionMgr, admin); SuccessOrExit(err); device->Init(GetControllerDeviceInitParams(), mListenPort, remoteDeviceId, udpPeerAddress, admin->GetAdminId()); diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index fc794e74fcea75..2032813dc3875c 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -35,10 +35,10 @@ #include #include #include -#include #include #include #include +#include #include #include #include diff --git a/src/messaging/ApplicationExchangeDispatch.cpp b/src/messaging/ApplicationExchangeDispatch.cpp deleted file mode 100644 index 34ef91f7c1e1f9..00000000000000 --- a/src/messaging/ApplicationExchangeDispatch.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file provides implementation of Application Channel class. - */ - -#include -#include - -namespace chip { -namespace Messaging { - -CHIP_ERROR ApplicationExchangeDispatch::SendMessageImpl(SecureSessionHandle session, PayloadHeader & payloadHeader, - System::PacketBufferHandle && message, - EncryptedPacketBufferHandle * retainedMessage) -{ - return mSessionMgr->SendMessage(session, payloadHeader, std::move(message), retainedMessage); -} - -CHIP_ERROR ApplicationExchangeDispatch::ResendMessage(SecureSessionHandle session, EncryptedPacketBufferHandle message, - EncryptedPacketBufferHandle * retainedMessage) const -{ - return mSessionMgr->SendEncryptedMessage(session, std::move(message), retainedMessage); -} - -bool ApplicationExchangeDispatch::MessagePermitted(uint16_t protocol, uint8_t type) -{ - // TODO: Change this check to only include the protocol and message types that are allowed - switch (protocol) - { - case Protocols::SecureChannel::Id.GetProtocolId(): - switch (type) - { - case static_cast(Protocols::SecureChannel::MsgType::PBKDFParamRequest): - case static_cast(Protocols::SecureChannel::MsgType::PBKDFParamResponse): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2p1): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2p2): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2p3): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2pError): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaR1): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaR2): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaR3): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaErr): - return false; - - default: - break; - } - break; - - default: - break; - } - return true; -} - -} // namespace Messaging -} // namespace chip diff --git a/src/messaging/ApplicationExchangeDispatch.h b/src/messaging/ApplicationExchangeDispatch.h deleted file mode 100644 index a195ce25423608..00000000000000 --- a/src/messaging/ApplicationExchangeDispatch.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file defines Application Channel class. The object of this - * class can be used by CHIP data model cluster applications to send - * and receive messages. The messages are encrypted using session keys. - */ - -#pragma once - -#include -#include -#include - -namespace chip { -namespace Messaging { - -class ApplicationExchangeDispatch : public ExchangeMessageDispatch -{ -public: - ApplicationExchangeDispatch() {} - - virtual ~ApplicationExchangeDispatch() {} - - CHIP_ERROR Init(ReliableMessageMgr * reliableMessageMgr, SecureSessionMgr * sessionMgr) - { - ReturnErrorCodeIf(sessionMgr == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - mSessionMgr = sessionMgr; - return ExchangeMessageDispatch::Init(reliableMessageMgr); - } - - CHIP_ERROR ResendMessage(SecureSessionHandle session, EncryptedPacketBufferHandle message, - EncryptedPacketBufferHandle * retainedMessage) const override; - - SecureSessionMgr * GetSessionMgr() const { return mSessionMgr; } - -protected: - CHIP_ERROR SendMessageImpl(SecureSessionHandle session, PayloadHeader & payloadHeader, System::PacketBufferHandle && message, - EncryptedPacketBufferHandle * retainedMessage) override; - - bool MessagePermitted(uint16_t protocol, uint8_t type) override; - -private: - SecureSessionMgr * mSessionMgr = nullptr; -}; - -} // namespace Messaging -} // namespace chip diff --git a/src/messaging/BUILD.gn b/src/messaging/BUILD.gn index f77617f16da1e9..18c4e6c3995f5f 100644 --- a/src/messaging/BUILD.gn +++ b/src/messaging/BUILD.gn @@ -18,8 +18,6 @@ static_library("messaging") { output_name = "libMessagingLayer" sources = [ - "ApplicationExchangeDispatch.cpp", - "ApplicationExchangeDispatch.h", "Channel.cpp", "Channel.h", "ChannelContext.cpp", @@ -30,8 +28,6 @@ static_library("messaging") { "ExchangeContext.cpp", "ExchangeContext.h", "ExchangeDelegate.h", - "ExchangeMessageDispatch.cpp", - "ExchangeMessageDispatch.h", "ExchangeMgr.cpp", "ExchangeMgr.h", "ExchangeMgrDelegate.h", diff --git a/src/messaging/ExchangeContext.cpp b/src/messaging/ExchangeContext.cpp index 61d28c54a5c1e8..216e92e0742092 100644 --- a/src/messaging/ExchangeContext.cpp +++ b/src/messaging/ExchangeContext.cpp @@ -85,9 +85,10 @@ CHIP_ERROR ExchangeContext::SendMessage(Protocols::Id protocolId, uint8_t msgTyp VerifyOrReturnError(mExchangeMgr != nullptr, CHIP_ERROR_INTERNAL); state = mExchangeMgr->GetSessionMgr()->GetPeerConnectionState(mSecureSession); + VerifyOrReturnError(state != nullptr, CHIP_ERROR_NOT_CONNECTED); // If a group message is to be transmitted to a destination node whose message counter is unknown. - if (state != nullptr && ChipKeyId::IsAppGroupKey(state->GetLocalKeyID()) && !state->IsPeerMsgCounterSynced()) + if (ChipKeyId::IsAppGroupKey(state->GetLocalKeyID()) && !state->IsPeerMsgCounterSynced()) { MessageCounterSyncMgr * messageCounterSyncMgr = mExchangeMgr->GetMessageCounterSyncMgr(); VerifyOrReturnError(messageCounterSyncMgr != nullptr, CHIP_ERROR_INTERNAL); @@ -114,20 +115,55 @@ CHIP_ERROR ExchangeContext::SendMessageImpl(Protocols::Id protocolId, uint8_t ms const SendFlags & sendFlags, Transport::PeerConnectionState * state) { CHIP_ERROR err = CHIP_NO_ERROR; + PayloadHeader payloadHeader; // Don't let method get called on a freed object. VerifyOrDie(mExchangeMgr != nullptr && GetReferenceCount() > 0); + if (state == nullptr) + { + state = mExchangeMgr->GetSessionMgr()->GetPeerConnectionState(mSecureSession); + } + + VerifyOrExit(state != nullptr, err = CHIP_ERROR_NOT_CONNECTED); + // we hold the exchange context here in case the entity that // originally generated it tries to close it as a result of // an error arising below. at the end, we have to close it. Retain(); - bool reliableTransmissionRequested = !sendFlags.Has(SendMessageFlags::kNoAutoRequestAck); + // Set the exchange ID for this header. + payloadHeader.SetExchangeID(mExchangeId); + + // Set the protocol ID and message type for this header. + payloadHeader.SetMessageType(protocolId, msgType); + + payloadHeader.SetInitiator(IsInitiator()); + + // If sending via UDP and auto-request ACK feature is enabled, automatically request an acknowledgment, + // UNLESS the NoAutoRequestAck send flag has been specified. + if ((state->GetPeerAddress().GetTransportType() == Transport::Type::kUdp) && mReliableMessageContext.AutoRequestAck() && + !sendFlags.Has(SendMessageFlags::kNoAutoRequestAck)) + { + payloadHeader.SetNeedsAck(true); + } + + // If there is a pending acknowledgment piggyback it on this message. + if (mReliableMessageContext.HasPeerRequestedAck()) + { + payloadHeader.SetAckId(mReliableMessageContext.mPendingPeerAckId); - ChipLogProgress(ExchangeManager, "Trying to send message using dispatch %p", GetMessageDispatch()); + // Set AckPending flag to false since current outgoing message is going to serve as the ack on this exchange. + mReliableMessageContext.SetAckPending(false); - VerifyOrExit(GetMessageDispatch() != nullptr, err = CHIP_ERROR_INCORRECT_STATE); +#if !defined(NDEBUG) + if (!payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::StandaloneAck)) + { + ChipLogProgress(ExchangeManager, "Piggybacking Ack for MsgId:%08" PRIX32 " with msg", + mReliableMessageContext.mPendingPeerAckId); + } +#endif + } // If a response message is expected... if (sendFlags.Has(SendMessageFlags::kExpectResponse)) @@ -145,8 +181,33 @@ CHIP_ERROR ExchangeContext::SendMessageImpl(Protocols::Id protocolId, uint8_t ms } } - err = GetMessageDispatch()->SendMessage(mSecureSession, mExchangeId, IsInitiator(), mReliableMessageContext, - reliableTransmissionRequested, protocolId, msgType, std::move(msgBuf)); + // Send the message. + if (payloadHeader.NeedsAck()) + { + ReliableMessageMgr::RetransTableEntry * entry = nullptr; + + // Add to Table for subsequent sending + err = mExchangeMgr->GetReliableMessageMgr()->AddToRetransTable(&mReliableMessageContext, &entry); + SuccessOrExit(err); + + err = mExchangeMgr->GetSessionMgr()->SendMessage(mSecureSession, payloadHeader, std::move(msgBuf), &entry->retainedBuf); + + if (err != CHIP_NO_ERROR) + { + // Remove from table + ChipLogError(ExchangeManager, "Failed to send message with err %ld", long(err)); + mExchangeMgr->GetReliableMessageMgr()->ClearRetransTable(*entry); + } + else + { + mExchangeMgr->GetReliableMessageMgr()->StartRetransmision(entry); + } + } + else + { + err = mExchangeMgr->GetSessionMgr()->SendMessage(mSecureSession, payloadHeader, std::move(msgBuf)); + SuccessOrExit(err); + } exit: if (err != CHIP_NO_ERROR && IsResponseExpected()) @@ -232,18 +293,8 @@ void ExchangeContext::Reset() *this = ExchangeContext(); } -ExchangeMessageDispatch * ExchangeContext::GetMessageDispatch() -{ - if (mDelegate != nullptr) - { - return mDelegate->GetMessageDispatch(mExchangeMgr->GetReliableMessageMgr(), mExchangeMgr->GetSessionMgr()); - } - - return nullptr; -} - ExchangeContext * ExchangeContext::Alloc(ExchangeManager * em, uint16_t ExchangeId, SecureSessionHandle session, bool Initiator, - ExchangeDelegateBase * delegate) + ExchangeDelegate * delegate) { VerifyOrDie(mExchangeMgr == nullptr && GetReferenceCount() == 0); @@ -347,7 +398,7 @@ void ExchangeContext::HandleResponseTimeout(System::Layer * aSystemLayer, void * // NOTE: we don't set mResponseExpected to false here because the response could still arrive. If the user // wants to never receive the response, they must close the exchange context. - ExchangeDelegateBase * delegate = ec->GetDelegate(); + ExchangeDelegate * delegate = ec->GetDelegate(); // Call the user's timeout handler. if (delegate != nullptr) @@ -355,41 +406,62 @@ void ExchangeContext::HandleResponseTimeout(System::Layer * aSystemLayer, void * } CHIP_ERROR ExchangeContext::HandleMessage(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - const Transport::PeerAddress & peerAddress, PacketBufferHandle msgBuf) + PacketBufferHandle msgBuf) { + CHIP_ERROR err = CHIP_NO_ERROR; + uint32_t messageId = packetHeader.GetMessageId(); + Protocols::Id protocolId = payloadHeader.GetProtocolID(); + uint8_t messageType = payloadHeader.GetMessageType(); + // We hold a reference to the ExchangeContext here to // guard against Close() calls(decrementing the reference // count) by the protocol before the CHIP Exchange // layer has completed its work on the ExchangeContext. Retain(); - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(GetMessageDispatch() != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - - err = GetMessageDispatch()->OnMessageReceived(payloadHeader, packetHeader.GetMessageId(), peerAddress, mReliableMessageContext); - SuccessOrExit(err); - - // The SecureChannel::StandaloneAck message type is only used for CRMP; do not pass such messages to the application layer. - if (payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::StandaloneAck)) + if (payloadHeader.IsAckMsg()) { - ExitNow(err = CHIP_NO_ERROR); + err = mReliableMessageContext.HandleRcvdAck(payloadHeader.GetAckId().Value()); + SuccessOrExit(err); } - // Since we got the response, cancel the response timer. - CancelResponseTimer(); + if (payloadHeader.NeedsAck()) + { + MessageFlags msgFlags; - // If the context was expecting a response to a previously sent message, this message - // is implicitly that response. - SetResponseExpected(false); + // An acknowledgment needs to be sent back to the peer for this message on this exchange, + // Set the flag in message header indicating an ack requested by peer; + msgFlags.Set(MessageFlagValues::kPeerRequestedAck); - if (mDelegate != nullptr) + // Also set the flag in the exchange context indicating an ack requested; + mReliableMessageContext.SetPeerRequestedAck(true); + + err = mReliableMessageContext.HandleNeedsAck(messageId, msgFlags); + SuccessOrExit(err); + } + + // The SecureChannel::StandaloneAck message type is only used for CRMP; do not pass such messages to the application layer. + if (payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::StandaloneAck)) { - mDelegate->OnMessageReceived(this, packetHeader, payloadHeader, std::move(msgBuf)); + ExitNow(err = CHIP_NO_ERROR); } else { - DefaultOnMessageReceived(this, packetHeader, payloadHeader.GetProtocolID(), payloadHeader.GetMessageType(), - std::move(msgBuf)); + // Since we got the response, cancel the response timer. + CancelResponseTimer(); + + // If the context was expecting a response to a previously sent message, this message + // is implicitly that response. + SetResponseExpected(false); + + if (mDelegate != nullptr) + { + mDelegate->OnMessageReceived(this, packetHeader, payloadHeader, std::move(msgBuf)); + } + else + { + DefaultOnMessageReceived(this, packetHeader, protocolId, messageType, std::move(msgBuf)); + } } exit: diff --git a/src/messaging/ExchangeContext.h b/src/messaging/ExchangeContext.h index b67e4738dd50b4..0042c9af2aa4ac 100644 --- a/src/messaging/ExchangeContext.h +++ b/src/messaging/ExchangeContext.h @@ -42,7 +42,6 @@ namespace Messaging { class ExchangeManager; class ExchangeContext; -class ExchangeMessageDispatch; class ExchangeContextDeletor { @@ -130,8 +129,6 @@ class DLL_EXPORT ExchangeContext : public ReferenceCounted -#include -#include #include -#include #include namespace chip { @@ -42,10 +38,10 @@ class ExchangeContext; * is interested in receiving these callbacks, they can specialize this class and handle * each trigger in their implementation of this class. */ -class DLL_EXPORT ExchangeDelegateBase +class DLL_EXPORT ExchangeDelegate { public: - virtual ~ExchangeDelegateBase() {} + virtual ~ExchangeDelegate() {} /** * @brief @@ -76,23 +72,6 @@ class DLL_EXPORT ExchangeDelegateBase * @param[in] ec A pointer to the ExchangeContext object. */ virtual void OnExchangeClosing(ExchangeContext * ec) {} - - virtual ExchangeMessageDispatch * GetMessageDispatch(ReliableMessageMgr * rmMgr, SecureSessionMgr * sessionMgr) = 0; -}; - -class DLL_EXPORT ExchangeDelegate : public ExchangeDelegateBase -{ -public: - virtual ~ExchangeDelegate() {} - - virtual ExchangeMessageDispatch * GetMessageDispatch(ReliableMessageMgr * rmMgr, SecureSessionMgr * sessionMgr) - { - mMessageDispatch.Init(rmMgr, sessionMgr); - return &mMessageDispatch; - } - -private: - ApplicationExchangeDispatch mMessageDispatch; }; } // namespace Messaging diff --git a/src/messaging/ExchangeMessageDispatch.cpp b/src/messaging/ExchangeMessageDispatch.cpp deleted file mode 100644 index 012baeda0dba4b..00000000000000 --- a/src/messaging/ExchangeMessageDispatch.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file provides implementation of ExchangeMessageDispatch class. - */ - -#ifndef __STDC_FORMAT_MACROS -#define __STDC_FORMAT_MACROS -#endif - -#ifndef __STDC_LIMIT_MACROS -#define __STDC_LIMIT_MACROS -#endif - -#include - -#include -#include -#include -#include -#include - -namespace chip { -namespace Messaging { - -CHIP_ERROR ExchangeMessageDispatch::SendMessage(SecureSessionHandle session, uint16_t exchangeId, bool isInitiator, - ReliableMessageContext & reliableMessageContext, bool isReliableTransmission, - Protocols::Id protocol, uint8_t type, System::PacketBufferHandle message) -{ - ReturnErrorCodeIf(!MessagePermitted(protocol.GetProtocolId(), type), CHIP_ERROR_INVALID_ARGUMENT); - - PayloadHeader payloadHeader; - payloadHeader.SetExchangeID(exchangeId).SetMessageType(protocol, type).SetInitiator(isInitiator); - - // If there is a pending acknowledgment piggyback it on this message. - if (reliableMessageContext.HasPeerRequestedAck()) - { - payloadHeader.SetAckId(reliableMessageContext.mPendingPeerAckId); - - // Set AckPending flag to false since current outgoing message is going to serve as the ack on this exchange. - reliableMessageContext.SetAckPending(false); - -#if !defined(NDEBUG) - if (!payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::StandaloneAck)) - { - ChipLogProgress(ExchangeManager, "Piggybacking Ack for MsgId:%08" PRIX32 " with msg", - reliableMessageContext.mPendingPeerAckId); - } -#endif - } - - if (!IsTransportReliable() && reliableMessageContext.AutoRequestAck() && mReliableMessageMgr != nullptr && - isReliableTransmission) - { - payloadHeader.SetNeedsAck(true); - - ReliableMessageMgr::RetransTableEntry * entry = nullptr; - - // Add to Table for subsequent sending - ReturnErrorOnFailure(mReliableMessageMgr->AddToRetransTable(&reliableMessageContext, &entry)); - - CHIP_ERROR err = SendMessageImpl(session, payloadHeader, std::move(message), &entry->retainedBuf); - if (err != CHIP_NO_ERROR) - { - // Remove from table - ChipLogError(ExchangeManager, "Failed to send message with err %s", ::chip::ErrorStr(err)); - mReliableMessageMgr->ClearRetransTable(*entry); - ReturnErrorOnFailure(err); - } - else - { - mReliableMessageMgr->StartRetransmision(entry); - } - } - else - { - // If the channel itself is providing reliability, let's not request CRMP acks - payloadHeader.SetNeedsAck(false); - ReturnErrorOnFailure(SendMessageImpl(session, payloadHeader, std::move(message), nullptr)); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR ExchangeMessageDispatch::OnMessageReceived(const PayloadHeader & payloadHeader, uint32_t messageId, - const Transport::PeerAddress & peerAddress, - ReliableMessageContext & reliableMessageContext) -{ - ReturnErrorCodeIf(!MessagePermitted(payloadHeader.GetProtocolID().GetProtocolId(), payloadHeader.GetMessageType()), - CHIP_ERROR_INVALID_ARGUMENT); - - if (!IsTransportReliable()) - { - if (payloadHeader.IsAckMsg() && payloadHeader.GetAckId().HasValue()) - { - ReturnErrorOnFailure(reliableMessageContext.HandleRcvdAck(payloadHeader.GetAckId().Value())); - } - - if (payloadHeader.NeedsAck()) - { - MessageFlags msgFlags; - - // An acknowledgment needs to be sent back to the peer for this message on this exchange, - // Set the flag in message header indicating an ack requested by peer; - msgFlags.Set(MessageFlagValues::kPeerRequestedAck); - - // Also set the flag in the exchange context indicating an ack requested; - reliableMessageContext.SetPeerRequestedAck(true); - - ReturnErrorOnFailure(reliableMessageContext.HandleNeedsAck(messageId, msgFlags)); - } - } - - return CHIP_NO_ERROR; -} - -} // namespace Messaging -} // namespace chip diff --git a/src/messaging/ExchangeMessageDispatch.h b/src/messaging/ExchangeMessageDispatch.h deleted file mode 100644 index b53253a3a1a319..00000000000000 --- a/src/messaging/ExchangeMessageDispatch.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file defines ExchangeMessageDispatch class. The object of this - * class can be used by CHIP protocols to send and receive messages. - */ - -#pragma once - -#include - -namespace chip { -namespace Messaging { - -class ReliableMessageMgr; -class ReliableMessageContext; - -class ExchangeMessageDispatch -{ -public: - ExchangeMessageDispatch() {} - virtual ~ExchangeMessageDispatch() {} - - CHIP_ERROR Init(ReliableMessageMgr * reliableMessageMgr) - { - mReliableMessageMgr = reliableMessageMgr; - return CHIP_NO_ERROR; - } - - CHIP_ERROR SendMessage(SecureSessionHandle session, uint16_t exchangeId, bool isInitiator, - ReliableMessageContext & reliableMessageContext, bool isReliableTransmission, Protocols::Id protocol, - uint8_t type, System::PacketBufferHandle message); - - virtual CHIP_ERROR ResendMessage(SecureSessionHandle session, EncryptedPacketBufferHandle message, - EncryptedPacketBufferHandle * retainedMessage) const - { - return CHIP_ERROR_NOT_IMPLEMENTED; - } - - virtual CHIP_ERROR OnMessageReceived(const PayloadHeader & payloadHeader, uint32_t messageId, - const Transport::PeerAddress & peerAddress, - ReliableMessageContext & reliableMessageContext); - -protected: - virtual bool MessagePermitted(uint16_t protocol, uint8_t type) = 0; - - virtual CHIP_ERROR SendMessageImpl(SecureSessionHandle session, PayloadHeader & payloadHeader, - System::PacketBufferHandle && message, EncryptedPacketBufferHandle * retainedMessage) = 0; - - virtual bool IsTransportReliable() { return false; } - -private: - ReliableMessageMgr * mReliableMessageMgr = nullptr; -}; - -} // namespace Messaging -} // namespace chip diff --git a/src/messaging/ExchangeMgr.cpp b/src/messaging/ExchangeMgr.cpp index 9dd772f3b25140..420de42f836f6b 100644 --- a/src/messaging/ExchangeMgr.cpp +++ b/src/messaging/ExchangeMgr.cpp @@ -85,6 +85,8 @@ CHIP_ERROR ExchangeManager::Init(SecureSessionMgr * sessionMgr) handler.Reset(); } + mSessionMgr->GetTransportManager()->SetRendezvousSession(this); + sessionMgr->SetDelegate(this); mReliableMessageMgr.Init(sessionMgr->SystemLayer(), sessionMgr); @@ -113,18 +115,18 @@ CHIP_ERROR ExchangeManager::Shutdown() return CHIP_NO_ERROR; } -ExchangeContext * ExchangeManager::NewContext(SecureSessionHandle session, ExchangeDelegateBase * delegate) +ExchangeContext * ExchangeManager::NewContext(SecureSessionHandle session, ExchangeDelegate * delegate) { return AllocContext(mNextExchangeId++, session, true, delegate); } -CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegateBase * delegate) +CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate) { return RegisterUMH(protocolId, kAnyMessageType, delegate); } CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType, - ExchangeDelegateBase * delegate) + ExchangeDelegate * delegate) { return RegisterUMH(protocolId, static_cast(msgType), delegate); } @@ -145,7 +147,7 @@ void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddr } ExchangeContext * ExchangeManager::AllocContext(uint16_t ExchangeId, SecureSessionHandle session, bool Initiator, - ExchangeDelegateBase * delegate) + ExchangeDelegate * delegate) { CHIP_FAULT_INJECT(FaultInjection::kFault_AllocExchangeContext, return nullptr); @@ -161,7 +163,7 @@ ExchangeContext * ExchangeManager::AllocContext(uint16_t ExchangeId, SecureSessi return nullptr; } -CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegateBase * delegate) +CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate) { UnsolicitedMessageHandler * umh = UMHandlerPool; UnsolicitedMessageHandler * selected = nullptr; @@ -210,8 +212,7 @@ CHIP_ERROR ExchangeManager::UnregisterUMH(Protocols::Id protocolId, int16_t msgT } void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - SecureSessionHandle session, const Transport::PeerAddress & source, - System::PacketBufferHandle msgBuf, SecureSessionMgr * msgLayer) + SecureSessionHandle session, System::PacketBufferHandle msgBuf, SecureSessionMgr * msgLayer) { CHIP_ERROR err = CHIP_NO_ERROR; UnsolicitedMessageHandler * umh = nullptr; @@ -231,7 +232,7 @@ void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const } // Matched ExchangeContext; send to message handler. - ec.HandleMessage(packetHeader, payloadHeader, source, std::move(msgBuf)); + ec.HandleMessage(packetHeader, payloadHeader, std::move(msgBuf)); ExitNow(err = CHIP_NO_ERROR); } @@ -283,7 +284,6 @@ void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const { // If rcvd msg is from initiator then this exchange is created as not Initiator. // If rcvd msg is not from initiator then this exchange is created as Initiator. - // TODO: Figure out which channel to use for the received message ec = AllocContext(payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), nullptr); } else @@ -296,7 +296,7 @@ void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const ChipLogProgress(ExchangeManager, "ec pos: %d, id: %d, Delegate: 0x%x", ec - mContextPool.begin(), ec->GetExchangeId(), ec->GetDelegate()); - ec->HandleMessage(packetHeader, payloadHeader, source, std::move(msgBuf)); + ec->HandleMessage(packetHeader, payloadHeader, std::move(msgBuf)); // Close exchange if it was created only to send ack for a duplicate message. if (sendAckAndCloseExchange) diff --git a/src/messaging/ExchangeMgr.h b/src/messaging/ExchangeMgr.h index 827e7453f92051..a9a2bba5b9e3a4 100644 --- a/src/messaging/ExchangeMgr.h +++ b/src/messaging/ExchangeMgr.h @@ -42,7 +42,7 @@ namespace chip { namespace Messaging { class ExchangeContext; -class ExchangeDelegateBase; +class ExchangeDelegate; static constexpr int16_t kAnyMessageType = -1; @@ -98,7 +98,7 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate, public Trans * @return A pointer to the created ExchangeContext object On success. Otherwise NULL if no object * can be allocated or is available. */ - ExchangeContext * NewContext(SecureSessionHandle session, ExchangeDelegateBase * delegate); + ExchangeContext * NewContext(SecureSessionHandle session, ExchangeDelegate * delegate); /** * Register an unsolicited message handler for a given protocol identifier. This handler would be @@ -114,7 +114,7 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate, public Trans * is full and a new one cannot be allocated. * @retval #CHIP_NO_ERROR On success. */ - CHIP_ERROR RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegateBase * delegate); + CHIP_ERROR RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate); /** * Register an unsolicited message handler for a given protocol identifier and message type. @@ -129,13 +129,13 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate, public Trans * is full and a new one cannot be allocated. * @retval #CHIP_NO_ERROR On success. */ - CHIP_ERROR RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType, ExchangeDelegateBase * delegate); + CHIP_ERROR RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType, ExchangeDelegate * delegate); /** * A strongly-message-typed version of RegisterUnsolicitedMessageHandlerForType. */ template ::value>> - CHIP_ERROR RegisterUnsolicitedMessageHandlerForType(MessageType msgType, ExchangeDelegateBase * delegate) + CHIP_ERROR RegisterUnsolicitedMessageHandlerForType(MessageType msgType, ExchangeDelegate * delegate) { static_assert(std::is_same, uint8_t>::value, "Enum is wrong size; cast is not safe"); return RegisterUnsolicitedMessageHandlerForType(Protocols::MessageTypeTraits::ProtocolId(), @@ -229,7 +229,7 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate, public Trans return ProtocolId == aProtocolId && MessageType == aMessageType; } - ExchangeDelegateBase * Delegate; + ExchangeDelegate * Delegate; Protocols::Id ProtocolId; // Message types are normally 8-bit unsigned ints, but we use // kAnyMessageType, which is negative, to represent a wildcard handler, @@ -256,17 +256,15 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate, public Trans BitMapObjectPool mChannelContexts; BitMapObjectPool mChannelHandles; - ExchangeContext * AllocContext(uint16_t ExchangeId, SecureSessionHandle session, bool Initiator, - ExchangeDelegateBase * delegate); + ExchangeContext * AllocContext(uint16_t ExchangeId, SecureSessionHandle session, bool Initiator, ExchangeDelegate * delegate); - CHIP_ERROR RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegateBase * delegate); + CHIP_ERROR RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate); CHIP_ERROR UnregisterUMH(Protocols::Id protocolId, int16_t msgType); void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * msgLayer) override; void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, SecureSessionHandle session, - const Transport::PeerAddress & source, System::PacketBufferHandle msgBuf, - SecureSessionMgr * msgLayer) override; + System::PacketBufferHandle msgBuf, SecureSessionMgr * msgLayer) override; void OnNewConnection(SecureSessionHandle session, SecureSessionMgr * mgr) override; void OnConnectionExpired(SecureSessionHandle session, SecureSessionMgr * mgr) override; diff --git a/src/messaging/MessageCounterSync.cpp b/src/messaging/MessageCounterSync.cpp index 45c22adc952608..cb17b163797286 100644 --- a/src/messaging/MessageCounterSync.cpp +++ b/src/messaging/MessageCounterSync.cpp @@ -38,12 +38,17 @@ namespace Messaging { CHIP_ERROR MessageCounterSyncMgr::Init(Messaging::ExchangeManager * exchangeMgr) { - VerifyOrReturnError(exchangeMgr != nullptr, CHIP_ERROR_INCORRECT_STATE); + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrReturnError(exchangeMgr != nullptr, err = CHIP_ERROR_INCORRECT_STATE); mExchangeMgr = exchangeMgr; // Register to receive unsolicited Secure Channel Request messages from the exchange manager. - // TODO: Register for specific message types, as CASE and PASE share the same protocol ID - return mExchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::SecureChannel::Id, this); + err = mExchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::SecureChannel::Id, this); + + ReturnErrorOnFailure(err); + + return err; } void MessageCounterSyncMgr::Shutdown() diff --git a/src/messaging/ReliableMessageContext.h b/src/messaging/ReliableMessageContext.h index 4ef97446cc63e5..47cb7c1171f09e 100644 --- a/src/messaging/ReliableMessageContext.h +++ b/src/messaging/ReliableMessageContext.h @@ -220,7 +220,6 @@ class ReliableMessageContext private: friend class ReliableMessageMgr; friend class ExchangeContext; - friend class ExchangeMessageDispatch; ReliableMessageMgr * mManager; ExchangeContext * mExchange; diff --git a/src/messaging/ReliableMessageMgr.cpp b/src/messaging/ReliableMessageMgr.cpp index 64a7829c0376c2..6ff1ca5fd177f1 100644 --- a/src/messaging/ReliableMessageMgr.cpp +++ b/src/messaging/ReliableMessageMgr.cpp @@ -26,7 +26,6 @@ #include #include -#include #include #include #include @@ -344,26 +343,30 @@ CHIP_ERROR ReliableMessageMgr::SendFromRetransTable(RetransTableEntry * entry) CHIP_ERROR err = CHIP_NO_ERROR; ReliableMessageContext * rc = entry->rc; - VerifyOrReturnError(rc != nullptr, err); - - const ExchangeMessageDispatch * transport = rc->mExchange->GetMessageDispatch(); - VerifyOrExit(transport != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - - err = transport->ResendMessage(rc->mExchange->GetSecureSession(), std::move(entry->retainedBuf), &entry->retainedBuf); - SuccessOrExit(err); + if (rc) + { + err = mSessionMgr->SendEncryptedMessage(entry->rc->mExchange->GetSecureSession(), std::move(entry->retainedBuf), + &entry->retainedBuf); - // Update the counters - entry->sendCount++; + if (err == CHIP_NO_ERROR) + { + // Update the counters + entry->sendCount++; + } + else + { + // Remove from table + ChipLogError(ExchangeManager, "Crit-err %ld when sending CHIP MsgId:%08" PRIX32 ", send tries: %d", long(err), + entry->retainedBuf.GetMsgId(), entry->sendCount); -exit: - if (err != CHIP_NO_ERROR) + ClearRetransTable(*entry); + } + } + else { - // Remove from table - ChipLogError(ExchangeManager, "Crit-err %ld when sending CHIP MsgId:%08" PRIX32 ", send tries: %d", long(err), - entry->retainedBuf.GetMsgId(), entry->sendCount); - - ClearRetransTable(*entry); + ChipLogError(ExchangeManager, "Table entry invalid"); } + return err; } diff --git a/src/messaging/tests/MessagingContext.h b/src/messaging/tests/MessagingContext.h index dc9db33b714f67..3e1bb59948a420 100644 --- a/src/messaging/tests/MessagingContext.h +++ b/src/messaging/tests/MessagingContext.h @@ -18,7 +18,6 @@ #include #include -#include #include #include #include diff --git a/src/messaging/tests/TestMessageCounterSyncMgr.cpp b/src/messaging/tests/TestMessageCounterSyncMgr.cpp index 27199610917428..0b95713f79a235 100644 --- a/src/messaging/tests/TestMessageCounterSyncMgr.cpp +++ b/src/messaging/tests/TestMessageCounterSyncMgr.cpp @@ -83,8 +83,7 @@ class TestExchangeMgr : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, SecureSessionHandle session, - const Transport::PeerAddress & source, System::PacketBufferHandle msgBuf, - SecureSessionMgr * mgr) override + System::PacketBufferHandle msgBuf, SecureSessionMgr * mgr) override { NL_TEST_ASSERT(mSuite, header.GetSourceNodeId() == Optional::Value(kSourceNodeId)); NL_TEST_ASSERT(mSuite, header.GetDestinationNodeId() == Optional::Value(kDestinationNodeId)); @@ -105,8 +104,7 @@ class TestSessMgrCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, SecureSessionHandle session, - const Transport::PeerAddress & source, System::PacketBufferHandle msgBuf, - SecureSessionMgr * mgr) override + System::PacketBufferHandle msgBuf, SecureSessionMgr * mgr) override {} void OnNewConnection(SecureSessionHandle session, SecureSessionMgr * mgr) override diff --git a/src/messaging/tests/echo/echo_requester.cpp b/src/messaging/tests/echo/echo_requester.cpp index 0129ac06d0e2c8..f8eecbb7d5f895 100644 --- a/src/messaging/tests/echo/echo_requester.cpp +++ b/src/messaging/tests/echo/echo_requester.cpp @@ -32,9 +32,9 @@ #include #include #include -#include #include #include +#include #include #include #include diff --git a/src/messaging/tests/echo/echo_responder.cpp b/src/messaging/tests/echo/echo_responder.cpp index 011dd983882ac8..2de325ce05af6f 100644 --- a/src/messaging/tests/echo/echo_responder.cpp +++ b/src/messaging/tests/echo/echo_responder.cpp @@ -32,9 +32,9 @@ #include #include #include -#include #include #include +#include #include #include #include diff --git a/src/protocols/secure_channel/BUILD.gn b/src/protocols/secure_channel/BUILD.gn index 406e1922d15ef7..4eebcc86fe792a 100644 --- a/src/protocols/secure_channel/BUILD.gn +++ b/src/protocols/secure_channel/BUILD.gn @@ -4,15 +4,6 @@ static_library("secure_channel") { output_name = "libSecureChannel" sources = [ - "NetworkProvisioning.cpp", - "NetworkProvisioning.h", - "PASESession.cpp", - "PASESession.h", - "RendezvousParameters.h", - "RendezvousSession.cpp", - "RendezvousSession.h", - "SessionEstablishmentExchangeDispatch.cpp", - "SessionEstablishmentExchangeDispatch.h", "StatusReport.cpp", "StatusReport.h", ] @@ -22,7 +13,6 @@ static_library("secure_channel") { public_deps = [ "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", - "${chip_root}/src/messaging", "${chip_root}/src/system", ] } diff --git a/src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.cpp b/src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.cpp deleted file mode 100644 index 0b4a4f2d0a2379..00000000000000 --- a/src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file provides implementation of Application Channel class. - */ - -#include -#include -#include - -#include - -namespace chip { - -using namespace Messaging; - -CHIP_ERROR SessionEstablishmentExchangeDispatch::SendMessageImpl(SecureSessionHandle session, PayloadHeader & payloadHeader, - System::PacketBufferHandle && message, - EncryptedPacketBufferHandle * retainedMessage) -{ - ChipLogProgress(Ble, "SessionEstablishmentExchangeDispatch::SendMessageImpl mBLETransport %p, mTransportMgr %p", mBLETransport, - mTransportMgr); - ReturnErrorOnFailure(payloadHeader.EncodeBeforeData(message)); - if (mBLETransport != nullptr && mPeerAddress.GetTransportType() == Transport::Type::kBle) - { - ChipLogProgress(Ble, "Sending message using BLE transport"); - return mBLETransport->SendMessage(PacketHeader(), Transport::PeerAddress::BLE(), std::move(message)); - } - else if (mTransportMgr != nullptr) - { - return mTransportMgr->SendMessage(PacketHeader(), mPeerAddress, std::move(message)); - } - - return CHIP_ERROR_INCORRECT_STATE; -} - -CHIP_ERROR SessionEstablishmentExchangeDispatch::OnMessageReceived(const PayloadHeader & payloadHeader, uint32_t messageId, - const Transport::PeerAddress & peerAddress, - ReliableMessageContext & reliableMessageContext) -{ - ReturnErrorOnFailure(ExchangeMessageDispatch::OnMessageReceived(payloadHeader, messageId, peerAddress, reliableMessageContext)); - mPeerAddress = peerAddress; - - return CHIP_NO_ERROR; -} - -bool SessionEstablishmentExchangeDispatch::MessagePermitted(uint16_t protocol, uint8_t type) -{ - switch (protocol) - { - case Protocols::SecureChannel::Id.GetProtocolId(): - switch (type) - { - case static_cast(Protocols::SecureChannel::MsgType::PBKDFParamRequest): - case static_cast(Protocols::SecureChannel::MsgType::PBKDFParamResponse): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2p1): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2p2): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2p3): - case static_cast(Protocols::SecureChannel::MsgType::PASE_Spake2pError): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaR1): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaR2): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaR3): - case static_cast(Protocols::SecureChannel::MsgType::CASE_SigmaErr): - return true; - - default: - break; - } - break; - - default: - break; - } - return false; -} - -} // namespace chip diff --git a/src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.h b/src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.h deleted file mode 100644 index 2e59d192205536..00000000000000 --- a/src/protocols/secure_channel/SessionEstablishmentExchangeDispatch.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file defines Application Channel class. The object of this - * class can be used by CHIP data model cluster applications to send - * and receive messages. The messages are encrypted using session keys. - */ - -#pragma once - -#include -#include - -namespace chip { -namespace Transport { -class BLE; -} - -class SessionEstablishmentExchangeDispatch : public Messaging::ExchangeMessageDispatch -{ -public: - SessionEstablishmentExchangeDispatch() {} - - virtual ~SessionEstablishmentExchangeDispatch() {} - - CHIP_ERROR Init(Transport::BLE * transport, TransportMgrBase * transportMgr) - { - ReturnErrorCodeIf(transport == nullptr && transportMgr == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - mBLETransport = transport; - mTransportMgr = transportMgr; - return CHIP_NO_ERROR; - } - - CHIP_ERROR OnMessageReceived(const PayloadHeader & payloadHeader, uint32_t messageId, - const Transport::PeerAddress & peerAddress, - Messaging::ReliableMessageContext & reliableMessageContext) override; - - const Transport::PeerAddress & GetPeerAddress() const { return mPeerAddress; } - - void SetPeerAddress(const Transport::PeerAddress & address) { mPeerAddress = address; } - -protected: - CHIP_ERROR SendMessageImpl(SecureSessionHandle session, PayloadHeader & payloadHeader, System::PacketBufferHandle && message, - EncryptedPacketBufferHandle * retainedMessage) override; - - bool MessagePermitted(uint16_t protocol, uint8_t type) override; - - bool IsTransportReliable() override - { - // If we are not using BLE as the transport, the underlying transport is UDP based. - // (return true only if BLE is being used as the transport) - return (mTransportMgr == nullptr); - } - -private: - Transport::BLE * mBLETransport = nullptr; - TransportMgrBase * mTransportMgr = nullptr; - Transport::PeerAddress mPeerAddress; -}; - -} // namespace chip diff --git a/src/transport/AdminPairingTable.h b/src/transport/AdminPairingTable.h index 41ce4be09433f3..dec75ba8d585f7 100644 --- a/src/transport/AdminPairingTable.h +++ b/src/transport/AdminPairingTable.h @@ -76,7 +76,7 @@ class DLL_EXPORT AdminPairingInfo AccessControlList & GetACL() { return mACL; } void SetACL(const AccessControlList & acl) { mACL = acl; } - bool IsInitialized() const { return (mAdmin != kUndefinedAdminId); } + bool IsInitialized() const { return (mNodeId != kUndefinedNodeId && mAdmin != kUndefinedAdminId); } /** * Reset the state to a completely uninitialized status. @@ -100,7 +100,7 @@ class DLL_EXPORT AdminPairingInfo OperationalCredentials mOpCred; AccessControlList mACL; - static constexpr size_t KeySize(); + static constexpr size_t KeySize(); // { return sizeof(kAdminTableKeyPrefix) + 2 * sizeof(AdminId); } static CHIP_ERROR GenerateKey(AdminId id, char * key, size_t len); diff --git a/src/transport/BLE.cpp b/src/transport/BLE.cpp index 4224a3ae0c0cc4..47ca32c728f81a 100644 --- a/src/transport/BLE.cpp +++ b/src/transport/BLE.cpp @@ -36,9 +36,6 @@ using namespace chip::System; namespace chip { namespace Transport { -// The largest supported value for Rendezvous discriminators -const uint16_t kMaxRendezvousDiscriminatorValue = 0xFFF; - BLE::~BLE() { ClearState(); @@ -60,29 +57,28 @@ void BLE::ClearState() } } -CHIP_ERROR BLE::Init(RendezvousSessionDelegate * delegate, TransportMgrDelegate * transport, BleLayer * bleLayer, - uint16_t discriminator, BLE_CONNECTION_OBJECT connObj) +CHIP_ERROR BLE::Init(RendezvousSessionDelegate * delegate, const RendezvousParameters & params) { - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; + BleLayer * bleLayer = params.GetBleLayer(); VerifyOrExit(mState == State::kNotReady, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(bleLayer, err = CHIP_ERROR_INCORRECT_STATE); - mDelegate = delegate; - mTransport = transport; + mDelegate = delegate; mBleLayer = bleLayer; mBleLayer->mAppState = reinterpret_cast(this); mBleLayer->OnChipBleConnectReceived = OnNewConnection; - if (discriminator <= kMaxRendezvousDiscriminatorValue) + if (params.HasDiscriminator()) { - err = mBleLayer->NewBleConnection(reinterpret_cast(this), discriminator, OnBleConnectionComplete, + err = mBleLayer->NewBleConnection(reinterpret_cast(this), params.GetDiscriminator(), OnBleConnectionComplete, OnBleConnectionError); } - else if (connObj != 0) + else if (params.HasConnectionObject()) { - err = InitInternal(connObj); + err = InitInternal(params.GetConnectionObject()); } SuccessOrExit(err); @@ -138,6 +134,7 @@ CHIP_ERROR BLE::SendMessage(const PacketHeader & header, const Transport::PeerAd { CHIP_ERROR err = CHIP_NO_ERROR; + VerifyOrExit(address.GetTransportType() == Type::kBle, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(mState == State::kInitialized, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mBleEndPoint != nullptr, err = CHIP_ERROR_INCORRECT_STATE); @@ -186,13 +183,13 @@ void BLE::OnBleEndPointReceive(BLEEndPoint * endPoint, PacketBufferHandle buffer BLE * ble = reinterpret_cast(endPoint->mAppState); CHIP_ERROR err = CHIP_NO_ERROR; - if (ble->mTransport) + if (ble->mDelegate) { PacketHeader header; err = header.DecodeAndConsume(buffer); SuccessOrExit(err); - ble->mTransport->OnMessageReceived(header, Transport::PeerAddress(Transport::Type::kBle), std::move(buffer)); + ble->mDelegate->OnRendezvousMessageReceived(header, Transport::PeerAddress(Transport::Type::kBle), std::move(buffer)); } exit: if (err != CHIP_NO_ERROR) diff --git a/src/transport/BLE.h b/src/transport/BLE.h index b82352afa13f83..387712862d19e6 100644 --- a/src/transport/BLE.h +++ b/src/transport/BLE.h @@ -32,8 +32,8 @@ #include #include #include +#include #include -#include #include namespace chip { @@ -63,14 +63,10 @@ class DLL_EXPORT BLE : public Base /** * Initialize a BLE transport to a given peripheral or a given device name. * - * @param delegate the delegate that will receive BLE events - * @param transportDelegate the delegate object to receive incoming messages - * @param bleLayer the instance of BleLayer to use - * @param discriminator device advertisement discriminator - * @param connObj BLE connection object + * @param delegate the delegate that will receive BLE events + * @param params BLE configuration parameters for this transport */ - CHIP_ERROR Init(RendezvousSessionDelegate * delegate, TransportMgrDelegate * transportDelegate, Ble::BleLayer * bleLayer, - uint16_t discriminator, BLE_CONNECTION_OBJECT connObj); + CHIP_ERROR Init(RendezvousSessionDelegate * delegate, const RendezvousParameters & params); CHIP_ERROR SendMessage(const PacketHeader & header, const Transport::PeerAddress & address, System::PacketBufferHandle msgBuf) override; @@ -110,7 +106,6 @@ class DLL_EXPORT BLE : public Base State mState = State::kNotReady; ///< State of the BLE transport Ble::BLEEndPoint * mBleEndPoint = nullptr; ///< BLE endpoint used by transport RendezvousSessionDelegate * mDelegate = nullptr; ///< BLE events from transport - TransportMgrDelegate * mTransport = nullptr; }; } // namespace Transport diff --git a/src/transport/BUILD.gn b/src/transport/BUILD.gn index d2c612c16b6cef..58e200e8f15cab 100644 --- a/src/transport/BUILD.gn +++ b/src/transport/BUILD.gn @@ -24,8 +24,15 @@ static_library("transport") { "AdminPairingTable.h", "CASESession.cpp", "CASESession.h", + "NetworkProvisioning.cpp", + "NetworkProvisioning.h", + "PASESession.cpp", + "PASESession.h", "PeerConnectionState.h", "PeerConnections.h", + "RendezvousParameters.h", + "RendezvousSession.cpp", + "RendezvousSession.h", "RendezvousSessionDelegate.h", "SecureMessageCodec.cpp", "SecureMessageCodec.h", @@ -34,6 +41,8 @@ static_library("transport") { "SecureSessionMgr.cpp", "SecureSessionMgr.h", "SessionEstablishmentDelegate.h", + "StorablePeerConnection.cpp", + "StorablePeerConnection.h", "TransportMgr.h", "TransportMgrBase.cpp", "TransportMgrBase.h", diff --git a/src/protocols/secure_channel/NetworkProvisioning.cpp b/src/transport/NetworkProvisioning.cpp similarity index 88% rename from src/protocols/secure_channel/NetworkProvisioning.cpp rename to src/transport/NetworkProvisioning.cpp index 78d7dd15edc481..894b9aa13c6e28 100644 --- a/src/protocols/secure_channel/NetworkProvisioning.cpp +++ b/src/transport/NetworkProvisioning.cpp @@ -19,10 +19,10 @@ #include #include #include -#include #include #include #include +#include #include #if CONFIG_DEVICE_LAYER @@ -38,18 +38,14 @@ namespace chip { constexpr char kAPInterfaceNamePrefix[] = "ap"; constexpr char kLoobackInterfaceNamePrefix[] = "lo"; -void NetworkProvisioning::Init(Messaging::ExchangeManager * exchangeMgr, SecureSessionHandle session, - NetworkProvisioningDelegate * delegate) +void NetworkProvisioning::Init(NetworkProvisioningDelegate * delegate) { - mExchangeMgr = exchangeMgr; - mDelegate = delegate; + mDelegate = delegate; #if CONFIG_DEVICE_LAYER #if defined(CHIP_DEVICE_LAYER_TARGET) DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast(this)); #endif #endif - exchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::NetworkProvisioning::Id, this); - mSession = session; } NetworkProvisioning::~NetworkProvisioning() @@ -61,17 +57,6 @@ NetworkProvisioning::~NetworkProvisioning() #endif } -void NetworkProvisioning::OnMessageReceived(Messaging::ExchangeContext * exchangeContext, const PacketHeader & packetHeader, - const PayloadHeader & payloadHeader, System::PacketBufferHandle payload) -{ - HandleNetworkProvisioningMessage(payloadHeader.GetMessageType(), payload); - - // Currently, the only mechanism to get this callback is via unsolicited message handler. - // That means that we now own the reference to exchange context. Let's free the reference since we no longer - // need it. - exchangeContext->Release(); -} - CHIP_ERROR NetworkProvisioning::HandleNetworkProvisioningMessage(uint8_t msgType, const System::PacketBufferHandle & msgBuf) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -190,16 +175,6 @@ CHIP_ERROR NetworkProvisioning::DecodeString(const uint8_t * input, size_t input return err; } -CHIP_ERROR NetworkProvisioning::SendMessageUsingExchange(uint8_t msgType, System::PacketBufferHandle msgPayload) -{ - Messaging::ExchangeContext * exchangeContext = mExchangeMgr->NewContext(mSession, this); - VerifyOrReturnError(exchangeContext != nullptr, CHIP_ERROR_INTERNAL); - CHIP_ERROR err = exchangeContext->SendMessage(Protocols::NetworkProvisioning::Id, msgType, std::move(msgPayload), - Messaging::SendMessageFlags::kNoAutoRequestAck); - exchangeContext->Release(); - return err; -} - CHIP_ERROR NetworkProvisioning::SendIPAddress(const Inet::IPAddress & addr) { char * addrStr; @@ -209,10 +184,12 @@ CHIP_ERROR NetworkProvisioning::SendIPAddress(const Inet::IPAddress & addr) addrStr = addr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength()); buffer->SetDataLength(static_cast(strlen(addrStr) + 1)); - ChipLogProgress(NetworkProvisioning, "Sending IP Address\n"); + ChipLogProgress(NetworkProvisioning, "Sending IP Address. Delegate %p\n", mDelegate); + VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS); - err = SendMessageUsingExchange(NetworkProvisioning::MsgTypes::kIPAddressAssigned, std::move(buffer)); + err = mDelegate->SendSecureMessage(Protocols::NetworkProvisioning::Id, NetworkProvisioning::MsgTypes::kIPAddressAssigned, + std::move(buffer)); SuccessOrExit(err); exit: @@ -249,13 +226,15 @@ CHIP_ERROR NetworkProvisioning::SendNetworkCredentials(const char * ssid, const { Encoding::LittleEndian::PacketBufferWriter bbuf(MessagePacketBuffer::New(bufferSize), bufferSize); - ChipLogProgress(NetworkProvisioning, "Sending Network Creds\n"); + ChipLogProgress(NetworkProvisioning, "Sending Network Creds. Delegate %p\n", mDelegate); + VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(!bbuf.IsNull(), err = CHIP_ERROR_NO_MEMORY); SuccessOrExit(EncodeString(ssid, bbuf)); SuccessOrExit(EncodeString(passwd, bbuf)); VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_BUFFER_TOO_SMALL); - err = SendMessageUsingExchange(NetworkProvisioning::MsgTypes::kWiFiAssociationRequest, bbuf.Finalize()); + err = mDelegate->SendSecureMessage(Protocols::NetworkProvisioning::Id, + NetworkProvisioning::MsgTypes::kWiFiAssociationRequest, bbuf.Finalize()); SuccessOrExit(err); } @@ -282,6 +261,7 @@ CHIP_ERROR NetworkProvisioning::SendThreadCredentials(const DeviceLayer::Interna Encoding::LittleEndian::PacketBufferWriter bbuf(MessagePacketBuffer::New(credentialSize), credentialSize); ChipLogProgress(NetworkProvisioning, "Sending Thread Credentials"); + VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(!bbuf.IsNull(), err = CHIP_ERROR_NO_MEMORY); bbuf.Put(threadData.ThreadNetworkName, sizeof(threadData.ThreadNetworkName)); @@ -296,8 +276,8 @@ CHIP_ERROR NetworkProvisioning::SendThreadCredentials(const DeviceLayer::Interna bbuf.Put(static_cast(threadData.FieldPresent.ThreadPSKc)); VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_BUFFER_TOO_SMALL); - - err = SendMessageUsingExchange(NetworkProvisioning::MsgTypes::kThreadAssociationRequest, bbuf.Finalize()); + err = mDelegate->SendSecureMessage(Protocols::NetworkProvisioning::Id, NetworkProvisioning::MsgTypes::kThreadAssociationRequest, + bbuf.Finalize()); exit: if (CHIP_NO_ERROR != err) diff --git a/src/protocols/secure_channel/NetworkProvisioning.h b/src/transport/NetworkProvisioning.h similarity index 82% rename from src/protocols/secure_channel/NetworkProvisioning.h rename to src/transport/NetworkProvisioning.h index 3efa8510f8b3ba..2808063b0ac956 100644 --- a/src/protocols/secure_channel/NetworkProvisioning.h +++ b/src/transport/NetworkProvisioning.h @@ -24,14 +24,11 @@ #pragma once #include -#include -#include #include #include #include #include #include -#include #if CONFIG_DEVICE_LAYER #include @@ -73,7 +70,7 @@ class DLL_EXPORT NetworkProvisioningDelegate virtual ~NetworkProvisioningDelegate() {} }; -class DLL_EXPORT NetworkProvisioning : public Messaging::ExchangeDelegate +class DLL_EXPORT NetworkProvisioning { public: enum MsgTypes : uint8_t @@ -83,7 +80,7 @@ class DLL_EXPORT NetworkProvisioning : public Messaging::ExchangeDelegate kThreadAssociationRequest = 2 }; - void Init(Messaging::ExchangeManager * exchangeMgr, SecureSessionHandle session, NetworkProvisioningDelegate * delegate); + void Init(NetworkProvisioningDelegate * delegate); ~NetworkProvisioning(); @@ -101,20 +98,11 @@ class DLL_EXPORT NetworkProvisioning : public Messaging::ExchangeDelegate */ const Inet::IPAddress & GetIPAddress() const { return mDeviceAddress; } - //// ExchangeDelegate Implementation //// - void OnMessageReceived(Messaging::ExchangeContext * exchangeContext, const PacketHeader & packetHeader, - const PayloadHeader & payloadHeader, System::PacketBufferHandle payload) override; - void OnResponseTimeout(Messaging::ExchangeContext * exchangeContext) override {} - private: NetworkProvisioningDelegate * mDelegate = nullptr; - Messaging::ExchangeManager * mExchangeMgr = nullptr; - Inet::IPAddress mDeviceAddress = Inet::IPAddress::Any; - SecureSessionHandle mSession; - /** * @brief * The device can use this function to send its IP address to @@ -140,8 +128,6 @@ class DLL_EXPORT NetworkProvisioning : public Messaging::ExchangeDelegate CHIP_ERROR DecodeThreadAssociationRequest(const System::PacketBufferHandle & msgBuf); - CHIP_ERROR SendMessageUsingExchange(uint8_t msgType, System::PacketBufferHandle msgPayload); - #if CONFIG_DEVICE_LAYER static void ConnectivityHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg); #endif // CONFIG_DEVICE_LAYER diff --git a/src/protocols/secure_channel/PASESession.cpp b/src/transport/PASESession.cpp similarity index 85% rename from src/protocols/secure_channel/PASESession.cpp rename to src/transport/PASESession.cpp index f985d99f303fb9..a821bca87997a3 100644 --- a/src/protocols/secure_channel/PASESession.cpp +++ b/src/transport/PASESession.cpp @@ -27,7 +27,7 @@ * (https://www.ietf.org/id/draft-bar-cfrg-spake2plus-01.html) * */ -#include +#include #include #include @@ -46,7 +46,6 @@ namespace chip { using namespace Crypto; -using namespace Messaging; const char * kSpake2pContext = "CHIP PAKE V1 Commissioning"; const char * kSpake2pI2RSessionInfo = "Commissioning I2R Key"; @@ -55,11 +54,6 @@ const char * kSpake2pR2ISessionInfo = "Commissioning R2I Key"; static constexpr uint32_t kSpake2p_Iteration_Count = 100; static const char * kSpake2pKeyExchangeSalt = "SPAKE2P Key Salt"; -// Wait at most 30 seconds for the response from the peer. -// This timeout value assumes the underlying transport is reliable. -// The session establishment fails if the response is not received with in timeout window. -static constexpr ExchangeContext::Timeout kSpake2p_Response_Timeout = 30000; - PASESession::PASESession() {} PASESession::~PASESession() @@ -92,12 +86,6 @@ void PASESession::Clear() mPairingComplete = false; mComputeVerifier = true; mConnectionState.Reset(); - - if (mExchangeCtxt != nullptr) - { - mExchangeCtxt->Release(); - mExchangeCtxt = nullptr; - } } CHIP_ERROR PASESession::Serialize(PASESessionSerialized & output) @@ -292,16 +280,24 @@ CHIP_ERROR PASESession::WaitForPairing(const PASEVerifier & verifier, uint16_t m return err; } +CHIP_ERROR PASESession::AttachHeaderAndSend(Protocols::SecureChannel::MsgType msgType, System::PacketBufferHandle msgBuf) +{ + PayloadHeader payloadHeader; + + payloadHeader.SetMessageType(msgType); + + ReturnErrorOnFailure(payloadHeader.EncodeBeforeData(msgBuf)); + + return mDelegate->SendSessionEstablishmentMessage(PacketHeader().SetEncryptionKeyID(mConnectionState.GetLocalKeyID()), + mConnectionState.GetPeerAddress(), std::move(msgBuf)); +} + CHIP_ERROR PASESession::Pair(const Transport::PeerAddress peerAddress, uint32_t peerSetUpPINCode, uint16_t myKeyId, - Messaging::ExchangeContext * exchangeCtxt, SessionEstablishmentDelegate * delegate) + SessionEstablishmentDelegate * delegate) { - ReturnErrorCodeIf(exchangeCtxt == nullptr, CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR err = Init(myKeyId, peerSetUpPINCode, delegate); SuccessOrExit(err); - mExchangeCtxt = exchangeCtxt->Retain(); - mExchangeCtxt->SetResponseTimeout(kSpake2p_Response_Timeout); - mConnectionState.SetPeerAddress(peerAddress); err = SendPBKDFParamRequest(); @@ -315,14 +311,26 @@ CHIP_ERROR PASESession::Pair(const Transport::PeerAddress peerAddress, uint32_t return err; } -void PASESession::OnResponseTimeout(ExchangeContext * ec) +CHIP_ERROR PASESession::Pair(const Transport::PeerAddress peerAddress, const PASEVerifier & verifier, uint16_t myKeyId, + SessionEstablishmentDelegate * delegate) { - VerifyOrReturn(ec != nullptr, ChipLogError(Ble, "PASESession::OnResponseTimeout was called by null exchange")); - VerifyOrReturn(mExchangeCtxt == nullptr || mExchangeCtxt == ec, - ChipLogError(Ble, "PASESession::OnResponseTimeout exchange doesn't match")); - ChipLogError(Ble, "PASESession timed out while waiting for a response from the peer. Expected message type was %d", - mNextExpectedMsg); - mDelegate->OnSessionEstablishmentError(CHIP_ERROR_TIMEOUT); + CHIP_ERROR err = Init(myKeyId, 0, delegate); + SuccessOrExit(err); + + mConnectionState.SetPeerAddress(peerAddress); + + memmove(&mPASEVerifier, verifier, sizeof(verifier)); + mComputeVerifier = false; + + err = SendPBKDFParamRequest(); + SuccessOrExit(err); + +exit: + if (err != CHIP_NO_ERROR) + { + Clear(); + } + return err; } CHIP_ERROR PASESession::DeriveSecureSession(const uint8_t * info, size_t info_len, SecureSession & session) @@ -352,8 +360,7 @@ CHIP_ERROR PASESession::SendPBKDFParamRequest() mNextExpectedMsg = Protocols::SecureChannel::MsgType::PBKDFParamResponse; - err = mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::PBKDFParamRequest, std::move(req), - SendFlags(SendMessageFlags::kExpectResponse)); + err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PBKDFParamRequest, std::move(req)); SuccessOrExit(err); ChipLogDetail(Ble, "Sent PBKDF param request"); @@ -367,7 +374,7 @@ CHIP_ERROR PASESession::SendPBKDFParamRequest() return err; } -CHIP_ERROR PASESession::HandlePBKDFParamRequest(const System::PacketBufferHandle & msg) +CHIP_ERROR PASESession::HandlePBKDFParamRequest(const PacketHeader & header, const System::PacketBufferHandle & msg) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -432,14 +439,14 @@ CHIP_ERROR PASESession::SendPBKDFParamResponse() mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2p1; - ReturnErrorOnFailure(mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::PBKDFParamResponse, std::move(resp), - SendFlags(SendMessageFlags::kExpectResponse))); + ReturnErrorOnFailure(AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PBKDFParamResponse, std::move(resp))); + ChipLogDetail(Ble, "Sent PBKDF param response"); return CHIP_NO_ERROR; } -CHIP_ERROR PASESession::HandlePBKDFParamResponse(const System::PacketBufferHandle & msg) +CHIP_ERROR PASESession::HandlePBKDFParamResponse(const PacketHeader & header, const System::PacketBufferHandle & msg) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -507,14 +514,14 @@ CHIP_ERROR PASESession::SendMsg1() mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2p2; // Call delegate to send the Msg1 to peer - ReturnErrorOnFailure(mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::PASE_Spake2p1, bbuf.Finalize(), - SendFlags(SendMessageFlags::kExpectResponse))); + ReturnErrorOnFailure(AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2p1, bbuf.Finalize())); + ChipLogDetail(Ble, "Sent spake2p msg1"); return CHIP_NO_ERROR; } -CHIP_ERROR PASESession::HandleMsg1_and_SendMsg2(const System::PacketBufferHandle & msg) +CHIP_ERROR PASESession::HandleMsg1_and_SendMsg2(const PacketHeader & header, const System::PacketBufferHandle & msg) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -567,8 +574,7 @@ CHIP_ERROR PASESession::HandleMsg1_and_SendMsg2(const System::PacketBufferHandle mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2p3; // Call delegate to send the Msg2 to peer - err = mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::PASE_Spake2p2, bbuf.Finalize(), - SendFlags(SendMessageFlags::kExpectResponse)); + err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2p2, bbuf.Finalize()); SuccessOrExit(err); } @@ -583,7 +589,7 @@ CHIP_ERROR PASESession::HandleMsg1_and_SendMsg2(const System::PacketBufferHandle return err; } -CHIP_ERROR PASESession::HandleMsg2_and_SendMsg3(const System::PacketBufferHandle & msg) +CHIP_ERROR PASESession::HandleMsg2_and_SendMsg3(const PacketHeader & header, const System::PacketBufferHandle & msg) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -627,8 +633,7 @@ CHIP_ERROR PASESession::HandleMsg2_and_SendMsg3(const System::PacketBufferHandle VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_NO_MEMORY); // Call delegate to send the Msg3 to peer - err = mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::PASE_Spake2p3, bbuf.Finalize(), - SendFlags(SendMessageFlags::kNone)); + err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2p3, bbuf.Finalize()); SuccessOrExit(err); } @@ -661,7 +666,7 @@ CHIP_ERROR PASESession::HandleMsg2_and_SendMsg3(const System::PacketBufferHandle return err; } -CHIP_ERROR PASESession::HandleMsg3(const System::PacketBufferHandle & msg) +CHIP_ERROR PASESession::HandleMsg3(const PacketHeader & header, const System::PacketBufferHandle & msg) { CHIP_ERROR err = CHIP_NO_ERROR; const uint8_t * hash = msg->Start(); @@ -716,15 +721,14 @@ void PASESession::SendErrorMsg(Spake2pErrorType errorCode) msg->SetDataLength(msglen); - err = mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::PASE_Spake2pError, std::move(msg), - SendFlags(SendMessageFlags::kNone)); + err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2pError, std::move(msg)); SuccessOrExit(err); exit: Clear(); } -void PASESession::HandleErrorMsg(const System::PacketBufferHandle & msg) +void PASESession::HandleErrorMsg(const PacketHeader & header, const System::PacketBufferHandle & msg) { // Request message processing const uint8_t * buf = msg->Start(); @@ -737,56 +741,45 @@ void PASESession::HandleErrorMsg(const System::PacketBufferHandle & msg) pMsg = reinterpret_cast(msg->Start()); ChipLogError(Ble, "Received error (%d) during pairing process", pMsg->error); - mDelegate->OnSessionEstablishmentError(pMsg->error); - exit: Clear(); } -void PASESession::OnMessageReceived(ExchangeContext * ec, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - System::PacketBufferHandle msg) +CHIP_ERROR PASESession::HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msg) { CHIP_ERROR err = CHIP_NO_ERROR; + PayloadHeader payloadHeader; - VerifyOrExit(ec != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(mExchangeCtxt == nullptr || mExchangeCtxt == ec, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(!msg.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(payloadHeader.HasMessageType(mNextExpectedMsg) || - payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::PASE_Spake2pError), - err = CHIP_ERROR_INVALID_MESSAGE_TYPE); - if (mExchangeCtxt == nullptr) - { - mExchangeCtxt = ec->Retain(); - mExchangeCtxt->SetResponseTimeout(kSpake2p_Response_Timeout); - } + err = payloadHeader.DecodeAndConsume(msg); + SuccessOrExit(err); - mConnectionState.SetPeerAddress(mMessageDispatch.GetPeerAddress()); + VerifyOrExit(payloadHeader.HasMessageType(mNextExpectedMsg), err = CHIP_ERROR_INVALID_MESSAGE_TYPE); + + mConnectionState.SetPeerAddress(peerAddress); switch (static_cast(payloadHeader.GetMessageType())) { case Protocols::SecureChannel::MsgType::PBKDFParamRequest: - err = HandlePBKDFParamRequest(msg); + err = HandlePBKDFParamRequest(packetHeader, msg); break; case Protocols::SecureChannel::MsgType::PBKDFParamResponse: - err = HandlePBKDFParamResponse(msg); + err = HandlePBKDFParamResponse(packetHeader, msg); break; case Protocols::SecureChannel::MsgType::PASE_Spake2p1: - err = HandleMsg1_and_SendMsg2(msg); + err = HandleMsg1_and_SendMsg2(packetHeader, msg); break; case Protocols::SecureChannel::MsgType::PASE_Spake2p2: - err = HandleMsg2_and_SendMsg3(msg); + err = HandleMsg2_and_SendMsg3(packetHeader, msg); break; case Protocols::SecureChannel::MsgType::PASE_Spake2p3: - err = HandleMsg3(msg); - break; - - case Protocols::SecureChannel::MsgType::PASE_Spake2pError: - HandleErrorMsg(msg); + err = HandleMsg3(packetHeader, msg); break; default: @@ -801,6 +794,8 @@ void PASESession::OnMessageReceived(ExchangeContext * ec, const PacketHeader & p { mDelegate->OnSessionEstablishmentError(err); } + + return CHIP_NO_ERROR; } } // namespace chip diff --git a/src/protocols/secure_channel/PASESession.h b/src/transport/PASESession.h similarity index 80% rename from src/protocols/secure_channel/PASESession.h rename to src/transport/PASESession.h index 4715b61e57d46f..1b12bdccb754e5 100644 --- a/src/protocols/secure_channel/PASESession.h +++ b/src/transport/PASESession.h @@ -27,14 +27,9 @@ #pragma once #include -#include -#include -#include #include -#include #include #include -#include #include #include #include @@ -65,7 +60,7 @@ struct PASESessionSerializable typedef uint8_t PASEVerifier[2][kSpake2p_WS_Length]; -class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public PairingSession +class DLL_EXPORT PASESession { public: PASESession(); @@ -111,13 +106,26 @@ class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public Pa * @param peerAddress Address of peer to pair * @param peerSetUpPINCode Setup PIN code of the peer device * @param myKeyId Key ID to be assigned to the secure session on the peer node - * @param exchangeCtxt The exchange context to send and receive messages with the peer * @param delegate Callback object * * @return CHIP_ERROR The result of initialization */ CHIP_ERROR Pair(const Transport::PeerAddress peerAddress, uint32_t peerSetUpPINCode, uint16_t myKeyId, - Messaging::ExchangeContext * exchangeCtxt, SessionEstablishmentDelegate * delegate); + SessionEstablishmentDelegate * delegate); + + /** + * @brief + * Create a pairing request using given PASE verifier. + * + * @param peerAddress Address of peer to pair + * @param verifier PASE verifier to be used for SPAKE2P pairing + * @param myKeyId Key ID to be assigned to the secure session on the peer node + * @param delegate Callback object + * + * @return CHIP_ERROR The result of initialization + */ + CHIP_ERROR Pair(const Transport::PeerAddress peerAddress, const PASEVerifier & verifier, uint16_t myKeyId, + SessionEstablishmentDelegate * delegate); /** * @brief @@ -142,7 +150,19 @@ class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public Pa * initialized once pairing is complete * @return CHIP_ERROR The result of session derivation */ - CHIP_ERROR DeriveSecureSession(const uint8_t * info, size_t info_len, SecureSession & session) override; + CHIP_ERROR DeriveSecureSession(const uint8_t * info, size_t info_len, SecureSession & session); + + /** + * @brief + * Handler for peer's messages, exchanged during pairing handshake. + * + * @param packetHeader Message header for the received message + * @param peerAddress Source of the message + * @param msg Message sent by the peer + * @return CHIP_ERROR The result of message processing + */ + virtual CHIP_ERROR HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msg); /** * @brief @@ -150,7 +170,7 @@ class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public Pa * * @return uint16_t The associated peer key id */ - uint16_t GetPeerKeyId() override { return mConnectionState.GetPeerKeyID(); } + uint16_t GetPeerKeyId() { return mConnectionState.GetPeerKeyID(); } /** * @brief @@ -158,11 +178,7 @@ class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public Pa * * @return uint16_t The assocated local key id */ - uint16_t GetLocalKeyId() override { return mConnectionState.GetLocalKeyID(); } - - const char * GetI2RSessionInfo() const override { return kSpake2pI2RSessionInfo; } - - const char * GetR2ISessionInfo() const override { return kSpake2pR2ISessionInfo; } + uint16_t GetLocalKeyId() { return mConnectionState.GetLocalKeyID(); } Transport::PeerConnectionState & PeerConnection() { return mConnectionState; } @@ -194,18 +210,6 @@ class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public Pa **/ void Clear(); - SessionEstablishmentExchangeDispatch & MessageDispatch() { return mMessageDispatch; } - - //// ExchangeDelegate Implementation //// - void OnMessageReceived(Messaging::ExchangeContext * ec, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - System::PacketBufferHandle payload) override; - void OnResponseTimeout(Messaging::ExchangeContext * ec) override; - Messaging::ExchangeMessageDispatch * GetMessageDispatch(Messaging::ReliableMessageMgr * rmMgr, - SecureSessionMgr * sessionMgr) override - { - return &mMessageDispatch; - } - private: enum Spake2pErrorType : uint8_t { @@ -221,19 +225,21 @@ class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public Pa CHIP_ERROR SetupSpake2p(uint32_t pbkdf2IterCount, const uint8_t * salt, size_t saltLen); CHIP_ERROR SendPBKDFParamRequest(); - CHIP_ERROR HandlePBKDFParamRequest(const System::PacketBufferHandle & msg); + CHIP_ERROR HandlePBKDFParamRequest(const PacketHeader & header, const System::PacketBufferHandle & msg); CHIP_ERROR SendPBKDFParamResponse(); - CHIP_ERROR HandlePBKDFParamResponse(const System::PacketBufferHandle & msg); + CHIP_ERROR HandlePBKDFParamResponse(const PacketHeader & header, const System::PacketBufferHandle & msg); CHIP_ERROR SendMsg1(); - CHIP_ERROR HandleMsg1_and_SendMsg2(const System::PacketBufferHandle & msg); - CHIP_ERROR HandleMsg2_and_SendMsg3(const System::PacketBufferHandle & msg); - CHIP_ERROR HandleMsg3(const System::PacketBufferHandle & msg); + CHIP_ERROR HandleMsg1_and_SendMsg2(const PacketHeader & header, const System::PacketBufferHandle & msg); + CHIP_ERROR HandleMsg2_and_SendMsg3(const PacketHeader & header, const System::PacketBufferHandle & msg); + CHIP_ERROR HandleMsg3(const PacketHeader & header, const System::PacketBufferHandle & msg); void SendErrorMsg(Spake2pErrorType errorCode); - void HandleErrorMsg(const System::PacketBufferHandle & msg); + void HandleErrorMsg(const PacketHeader & header, const System::PacketBufferHandle & msg); + + CHIP_ERROR AttachHeaderAndSend(Protocols::SecureChannel::MsgType msgType, System::PacketBufferHandle msgBuf); SessionEstablishmentDelegate * mDelegate = nullptr; @@ -255,10 +261,6 @@ class DLL_EXPORT PASESession : public Messaging::ExchangeDelegateBase, public Pa uint16_t mSaltLength = 0; uint8_t * mSalt = nullptr; - Messaging::ExchangeContext * mExchangeCtxt = nullptr; - - SessionEstablishmentExchangeDispatch mMessageDispatch; - struct Spake2pErrorMsg { Spake2pErrorType error; @@ -326,6 +328,12 @@ class SecurePairingUsingTestSecret : public PASESession { return CHIP_NO_ERROR; } + + CHIP_ERROR HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msg) override + { + return CHIP_NO_ERROR; + } }; typedef struct PASESessionSerialized diff --git a/src/transport/PairingSession.h b/src/transport/PairingSession.h deleted file mode 100644 index 0497a34a8219ab..00000000000000 --- a/src/transport/PairingSession.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file defines a common interface to access various types of secure - * pairing sessions (e.g. PASE, CASE) - * - */ - -#pragma once - -#include -#include - -namespace chip { - -class DLL_EXPORT PairingSession -{ -public: - PairingSession() {} - virtual ~PairingSession() {} - - /** - * @brief - * Derive a secure session from the paired session. The API will return error - * if called before pairing is established. - * - * @param info Information string used for key derivation - * @param info_len Length of info string - * @param session Referene to the secure session that will be - * initialized once pairing is complete - * @return CHIP_ERROR The result of session derivation - */ - virtual CHIP_ERROR DeriveSecureSession(const uint8_t * info, size_t info_len, SecureSession & session) = 0; - - /** - * @brief - * Return the associated peer key id - * - * @return uint16_t The associated peer key id - */ - virtual uint16_t GetPeerKeyId() = 0; - - /** - * @brief - * Return the associated local key id - * - * @return uint16_t The associated local key id - */ - virtual uint16_t GetLocalKeyId() = 0; - - virtual const char * GetI2RSessionInfo() const = 0; - - virtual const char * GetR2ISessionInfo() const = 0; -}; - -} // namespace chip diff --git a/src/protocols/secure_channel/RendezvousParameters.h b/src/transport/RendezvousParameters.h similarity index 99% rename from src/protocols/secure_channel/RendezvousParameters.h rename to src/transport/RendezvousParameters.h index ce6407dec854d5..753adde140785e 100644 --- a/src/protocols/secure_channel/RendezvousParameters.h +++ b/src/transport/RendezvousParameters.h @@ -17,13 +17,13 @@ #pragma once +#include #include #include #if CONFIG_NETWORK_LAYER_BLE #include #endif // CONFIG_NETWORK_LAYER_BLE -#include #include namespace chip { diff --git a/src/protocols/secure_channel/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp similarity index 56% rename from src/protocols/secure_channel/RendezvousSession.cpp rename to src/transport/RendezvousSession.cpp index 330c0be5676ca6..f2995ef6a4edd6 100644 --- a/src/protocols/secure_channel/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -17,11 +17,20 @@ #include -#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include #include #include +#include #if CONFIG_NETWORK_LAYER_BLE #include @@ -36,13 +45,11 @@ using namespace chip::Transport; namespace chip { -CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, Messaging::ExchangeManager * exchangeManager, - TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr, - Transport::AdminPairingInfo * admin) +CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, TransportMgrBase * transportMgr, + SecureSessionMgr * sessionMgr, Transport::AdminPairingInfo * admin) { mParams = params; mTransportMgr = transportMgr; - VerifyOrReturnError(exchangeManager != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(mDelegate != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(sessionMgr != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(admin != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -53,7 +60,6 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, Messagin mSecureSessionMgr = sessionMgr; mAdmin = admin; - mExchangeManager = exchangeManager; // TODO: BLE Should be a transport, in that case, RendezvousSession and BLE should decouple if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle) @@ -63,10 +69,7 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, Messagin Transport::BLE * transport = chip::Platform::New(); mTransport = transport; - ReturnErrorOnFailure( - transport->Init(this, sessionMgr, mParams.GetBleLayer(), mParams.GetDiscriminator(), mParams.GetConnectionObject())); - ReturnErrorOnFailure(mPairingSession.MessageDispatch().Init(transport, mTransportMgr)); - mPairingSession.MessageDispatch().SetPeerAddress(mParams.GetPeerAddress()); + ReturnErrorOnFailure(transport->Init(this, mParams)); } #else { @@ -76,9 +79,6 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, Messagin if (!mParams.IsController()) { - ReturnErrorOnFailure(mExchangeManager->RegisterUnsolicitedMessageHandlerForType( - Protocols::SecureChannel::MsgType::PBKDFParamRequest, &mPairingSession)); - if (mParams.HasPASEVerifier()) { ReturnErrorOnFailure(WaitForPairing(mParams.GetPASEVerifier())); @@ -89,11 +89,11 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, Messagin } } + mNetworkProvision.Init(this); // TODO: We should assume mTransportMgr not null for IP rendezvous. - if (mTransportMgr != nullptr && params.GetPeerAddress().GetTransportType() != Transport::Type::kBle) + if (mTransportMgr != nullptr) { - ReturnErrorOnFailure(mPairingSession.MessageDispatch().Init(nullptr, mTransportMgr)); - mPairingSession.MessageDispatch().SetPeerAddress(mParams.GetPeerAddress()); + mTransportMgr->SetRendezvousSession(this); } return CHIP_NO_ERROR; @@ -109,9 +109,66 @@ RendezvousSession::~RendezvousSession() mTransport = nullptr; } + if (mTransportMgr != nullptr) + { + mTransportMgr->SetRendezvousSession(nullptr); + } + mDelegate = nullptr; } +CHIP_ERROR RendezvousSession::SendSessionEstablishmentMessage(const PacketHeader & header, + const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msgIn) +{ + if (mCurrentState != State::kSecurePairing) + { + return CHIP_ERROR_INCORRECT_STATE; + } + + // TODO: Admin information and node ID shouold be set during operation credential configuration + // This setting of header properties is a hack to transmit the local node id to our peer + // so that admin configurations are preserved. Generally PASE sesions should not need to send + // node-ids as the peers may not be part of a fabric. + PacketHeader headerWithNodeIds = header; + + if (mParams.HasLocalNodeId()) + { + headerWithNodeIds.SetSourceNodeId(mParams.GetLocalNodeId().Value()); + } + + if (mParams.HasRemoteNodeId()) + { + headerWithNodeIds.SetDestinationNodeId(mParams.GetRemoteNodeId()); + } + + if (peerAddress.GetTransportType() == Transport::Type::kBle) + { + return mTransport->SendMessage(headerWithNodeIds, peerAddress, std::move(msgIn)); + } + else if (mTransportMgr != nullptr) + { + return mTransportMgr->SendMessage(headerWithNodeIds, peerAddress, std::move(msgIn)); + } + else + { + ChipLogError(Ble, "SendSessionEstablishmentMessage dropped since no transport mgr for IP rendezvous"); + return CHIP_ERROR_INVALID_ADDRESS; + } +} + +CHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::Id protocol, uint8_t msgType, System::PacketBufferHandle msgBuf) +{ + VerifyOrReturnError(mPairingSessionHandle != nullptr, CHIP_ERROR_INCORRECT_STATE); + + PayloadHeader payloadHeader; + payloadHeader.SetMessageType(protocol, msgType); + + return mSecureSessionMgr->SendMessage(*mPairingSessionHandle, payloadHeader, std::move(msgBuf)); +} + +void RendezvousSession::OnSessionEstablishmentError(CHIP_ERROR err) {} + void RendezvousSession::OnSessionEstablished() { SecureSessionMgr::PairingDirection direction = SecureSessionMgr::PairingDirection::kInitiator; @@ -142,12 +199,10 @@ void RendezvousSession::OnSessionEstablished() InitPairingSessionHandle(); - mNetworkProvision.Init(mExchangeManager, *mPairingSessionHandle, this); - // TODO: This check of BLE transport should be removed in the future, after we have network provisioning cluster and ble becomes // a transport. - if (mParams.GetPeerAddress().GetTransportType() != Transport::Type::kBle || // For rendezvous initializer - mPairingSession.PeerConnection().GetPeerAddress().GetTransportType() != Transport::Type::kBle) // For rendezvous target + if (mParams.GetPeerAddress().GetTransportType() != Transport::Type::kBle || // For rendezvous initializer + mPeerAddress.GetTransportType() != Transport::Type::kBle) // For rendezvous target { UpdateState(State::kRendezvousComplete); if (!mParams.IsController()) @@ -202,7 +257,6 @@ void RendezvousSession::UpdateState(RendezvousSession::State newState, CHIP_ERRO switch (mCurrentState) { case State::kSecurePairing: - mExchangeManager->UnregisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest); if (CHIP_NO_ERROR == err) { mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingSuccess, err); @@ -277,15 +331,108 @@ void RendezvousSession::UpdateState(RendezvousSession::State newState, CHIP_ERRO }; } +void RendezvousSession::OnRendezvousMessageReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + PacketBufferHandle msgBuf) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + mPeerAddress = peerAddress; + // TODO: RendezvousSession should handle SecurePairing messages only + + switch (mCurrentState) + { + case State::kSecurePairing: + // TODO: when operational certificates are in use, Rendezvous should not rely on destination node id. + // This marks internal key settings to identify the underlying key by the value that the + // remote node has sent. + // Generally such things should be saved as part of a CASE session, where operational credentials + // would be authenticated and matched against a remote node id. + // Also unclear why 'destination node id' is used here - it seems to be better ot use + // the source node id, which would identify the peer (rather than 'self' - rendezvous should + // already know the local node id). + if (packetHeader.GetDestinationNodeId().HasValue()) + { + NodeId destNodeId = packetHeader.GetDestinationNodeId().Value(); + ChipLogProgress(Ble, "Received pairing message for 0x%08" PRIx32 "%08" PRIx32, static_cast(destNodeId >> 32), + static_cast(destNodeId)); + mAdmin->SetNodeId(destNodeId); + } + + err = HandlePairingMessage(packetHeader, peerAddress, std::move(msgBuf)); + break; + + case State::kNetworkProvisioning: + err = HandleSecureMessage(packetHeader, peerAddress, std::move(msgBuf)); + break; + + default: + err = CHIP_ERROR_INCORRECT_STATE; + break; + }; + + if (err != CHIP_NO_ERROR) + { + OnRendezvousError(err); + } +} + void RendezvousSession::OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, System::PacketBufferHandle msgBuf) -{} +{ + // TODO: OnRendezvousMessageReceived can be renamed to OnMessageReceived after BLE becomes a transport. + this->OnRendezvousMessageReceived(header, source, std::move(msgBuf)); +} + +CHIP_ERROR RendezvousSession::HandlePairingMessage(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + PacketBufferHandle msgBuf) +{ + return mPairingSession.HandlePeerMessage(packetHeader, peerAddress, std::move(msgBuf)); +} + +CHIP_ERROR RendezvousSession::HandleSecureMessage(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + PacketBufferHandle msgBuf) +{ + ReturnErrorCodeIf(mPairingSessionHandle == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(msgBuf.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); + + PeerConnectionState * state = mSecureSessionMgr->GetPeerConnectionState(*mPairingSessionHandle); + ReturnErrorCodeIf(state == nullptr, CHIP_ERROR_KEY_NOT_FOUND_FROM_PEER); + + PayloadHeader payloadHeader; + ReturnErrorOnFailure(SecureMessageCodec::Decode(state, payloadHeader, packetHeader, msgBuf)); + + // Use the node IDs from the packet header only after it's successfully decrypted + if (packetHeader.GetDestinationNodeId().HasValue() && !mParams.HasLocalNodeId()) + { + NodeId destNodeId = packetHeader.GetDestinationNodeId().Value(); + ChipLogProgress(Ble, "Received rendezvous message for 0x%08" PRIx32 "%08" PRIx32, static_cast(destNodeId >> 32), + static_cast(destNodeId)); + mAdmin->SetNodeId(destNodeId); + mParams.SetLocalNodeId(destNodeId); + mSecureSessionMgr->SetLocalNodeId(destNodeId); + } + + if (packetHeader.GetSourceNodeId().HasValue() && !mParams.HasRemoteNodeId()) + { + NodeId sourceNodeId = packetHeader.GetSourceNodeId().Value(); + ChipLogProgress(Ble, "Received rendezvous message from 0x%08" PRIx32 "%08" PRIx32, + static_cast(sourceNodeId >> 32), static_cast(sourceNodeId)); + mParams.SetRemoteNodeId(sourceNodeId); + } + + if (payloadHeader.HasProtocol(Protocols::NetworkProvisioning::Id)) + { + ReturnErrorOnFailure(mNetworkProvision.HandleNetworkProvisioningMessage(payloadHeader.GetMessageType(), msgBuf)); + } + + return CHIP_NO_ERROR; +} void RendezvousSession::InitPairingSessionHandle() { ReleasePairingSessionHandle(); - mPairingSessionHandle = chip::Platform::New( - mPairingSession.PeerConnection().GetPeerNodeId(), mPairingSession.PeerConnection().GetPeerKeyID(), mAdmin->GetAdminId()); + mPairingSessionHandle = chip::Platform::New(mPairingSession.PeerConnection().GetPeerNodeId(), + mPairingSession.PeerConnection().GetPeerKeyID(), + mPairingSession.PeerConnection().GetAdminId()); } void RendezvousSession::ReleasePairingSessionHandle() @@ -326,13 +473,14 @@ CHIP_ERROR RendezvousSession::WaitForPairing(const PASEVerifier & verifier) CHIP_ERROR RendezvousSession::Pair(uint32_t setupPINCode) { - Messaging::ExchangeContext * ctxt = mExchangeManager->NewContext(SecureSessionHandle(), &mPairingSession); - ReturnErrorCodeIf(ctxt == nullptr, CHIP_ERROR_INTERNAL); + UpdateState(State::kSecurePairing); + return mPairingSession.Pair(mParams.GetPeerAddress(), setupPINCode, mNextKeyId++, this); +} +CHIP_ERROR RendezvousSession::Pair(const PASEVerifier & verifier) +{ UpdateState(State::kSecurePairing); - CHIP_ERROR err = mPairingSession.Pair(mParams.GetPeerAddress(), setupPINCode, mNextKeyId++, ctxt, this); - ctxt->Release(); - return err; + return mPairingSession.Pair(mParams.GetPeerAddress(), verifier, mNextKeyId++, this); } void RendezvousSession::SendNetworkCredentials(const char * ssid, const char * passwd) diff --git a/src/protocols/secure_channel/RendezvousSession.h b/src/transport/RendezvousSession.h similarity index 77% rename from src/protocols/secure_channel/RendezvousSession.h rename to src/transport/RendezvousSession.h index 5bb19ef465f152..8f88bc5806bef3 100644 --- a/src/protocols/secure_channel/RendezvousSession.h +++ b/src/transport/RendezvousSession.h @@ -23,14 +23,12 @@ #pragma once #include -#include #include -#include -#include -#include -#include #include #include +#include +#include +#include #include #include #include @@ -88,15 +86,14 @@ class RendezvousSession : public SessionEstablishmentDelegate, * @brief * Initialize the underlying transport using the RendezvousParameters passed in the constructor. * - * @param params The RendezvousParameters - * @param exchangeManager The instance of exchange manager to create exchange contexts - * @param transportMgr The transport to use - * @param sessionMgr Pointer to secure session manager - * @param admin Pointer to a device administrator info that will be filled up on successful pairing + * @param params The RendezvousParameters + * @param transportMgr The transport to use + * @param sessionMgr Pointer to secure session manager + * @param admin Pointer to a device administrator info that will be filled up on successful pairing * @ return CHIP_ERROR The result of the initialization */ - CHIP_ERROR Init(const RendezvousParameters & params, Messaging::ExchangeManager * exchangeManager, - TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr, Transport::AdminPairingInfo * admin); + CHIP_ERROR Init(const RendezvousParameters & params, TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr, + Transport::AdminPairingInfo * admin); /** * @brief @@ -110,12 +107,17 @@ class RendezvousSession : public SessionEstablishmentDelegate, Optional GetRemoteNodeId() const { return mParams.GetRemoteNodeId(); } //////////// SessionEstablishmentDelegate Implementation /////////////// + CHIP_ERROR SendSessionEstablishmentMessage(const PacketHeader & header, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msgBuf) override; + void OnSessionEstablishmentError(CHIP_ERROR err) override; void OnSessionEstablished() override; //////////// RendezvousSessionDelegate Implementation /////////////// void OnRendezvousConnectionOpened() override; void OnRendezvousConnectionClosed() override; void OnRendezvousError(CHIP_ERROR err) override; + void OnRendezvousMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle buffer) override; //////////// RendezvousDeviceCredentialsDelegate Implementation /////////////// void SendNetworkCredentials(const char * ssid, const char * passwd) override; @@ -123,6 +125,7 @@ class RendezvousSession : public SessionEstablishmentDelegate, void SendOperationalCredentials() override; //////////// NetworkProvisioningDelegate Implementation /////////////// + CHIP_ERROR SendSecureMessage(Protocols::Id protocol, uint8_t msgType, System::PacketBufferHandle msgBug) override; void OnNetworkProvisioningError(CHIP_ERROR error) override; void OnNetworkProvisioningComplete() override; @@ -145,17 +148,22 @@ class RendezvousSession : public SessionEstablishmentDelegate, void SetNextKeyId(uint16_t id) { mNextKeyId = id; } private: + CHIP_ERROR HandlePairingMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msgBuf); CHIP_ERROR Pair(uint32_t setupPINCode); + CHIP_ERROR Pair(const PASEVerifier & verifier); CHIP_ERROR WaitForPairing(uint32_t setupPINCode); CHIP_ERROR WaitForPairing(const PASEVerifier & verifier); + CHIP_ERROR HandleSecureMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msgBuf); Transport::Base * mTransport = nullptr; ///< Underlying transport RendezvousSessionDelegate * mDelegate = nullptr; ///< Underlying transport events RendezvousParameters mParams; ///< Rendezvous configuration PASESession mPairingSession; NetworkProvisioning mNetworkProvision; - Messaging::ExchangeManager * mExchangeManager = nullptr; + Transport::PeerAddress mPeerAddress; // Current peer address we are doing rendezvous with. TransportMgrBase * mTransportMgr; uint16_t mNextKeyId = 0; SecureSessionMgr * mSecureSessionMgr = nullptr; diff --git a/src/transport/SecureSessionMgr.cpp b/src/transport/SecureSessionMgr.cpp index a98ae82e1e386c..ed2ab66b255e57 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -31,12 +31,14 @@ #include #include -#include #include #include #include #include +#include +#include #include +#include #include #include @@ -248,9 +250,8 @@ CHIP_ERROR SecureSessionMgr::SendMessage(SecureSessionHandle session, PayloadHea return err; } -CHIP_ERROR SecureSessionMgr::NewPairing(const Optional & peerAddr, NodeId peerNodeId, - PairingSession * pairing, PairingDirection direction, Transport::AdminId admin, - Transport::Base * transport) +CHIP_ERROR SecureSessionMgr::NewPairing(const Optional & peerAddr, NodeId peerNodeId, PASESession * pairing, + PairingDirection direction, Transport::AdminId admin, Transport::Base * transport) { uint16_t peerKeyId = pairing->GetPeerKeyId(); uint16_t localKeyId = pairing->GetLocalKeyId(); @@ -291,26 +292,21 @@ CHIP_ERROR SecureSessionMgr::NewPairing(const Optional & { switch (direction) { - case PairingDirection::kInitiator: { - const char * i2rInfo = pairing->GetI2RSessionInfo(); - ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(i2rInfo), strlen(i2rInfo), - state->GetSenderSecureSession())); - - const char * r2iInfo = pairing->GetR2ISessionInfo(); - ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(r2iInfo), strlen(r2iInfo), - state->GetReceiverSecureSession())); - } - break; - case PairingDirection::kResponder: { - const char * i2rInfo = pairing->GetR2ISessionInfo(); - ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(i2rInfo), strlen(i2rInfo), - state->GetSenderSecureSession())); - - const char * r2iInfo = pairing->GetI2RSessionInfo(); - ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(r2iInfo), strlen(r2iInfo), - state->GetReceiverSecureSession())); - } - break; + case PairingDirection::kInitiator: + ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(kSpake2pI2RSessionInfo), + strlen(kSpake2pI2RSessionInfo), state->GetSenderSecureSession())); + + ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(kSpake2pR2ISessionInfo), + strlen(kSpake2pR2ISessionInfo), state->GetReceiverSecureSession())); + + break; + case PairingDirection::kResponder: + ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(kSpake2pR2ISessionInfo), + strlen(kSpake2pR2ISessionInfo), state->GetSenderSecureSession())); + ReturnErrorOnFailure(pairing->DeriveSecureSession(reinterpret_cast(kSpake2pI2RSessionInfo), + strlen(kSpake2pI2RSessionInfo), state->GetReceiverSecureSession())); + + break; default: return CHIP_ERROR_INVALID_ARGUMENT; }; @@ -350,35 +346,12 @@ void SecureSessionMgr::HandleGroupMessageReceived(const PacketHeader & packetHea void SecureSessionMgr::OnMessageReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, System::PacketBufferHandle msg) -{ - if (packetHeader.GetFlags().Has(Header::FlagValues::kSecure)) - { - SecureMessageDispatch(packetHeader, peerAddress, std::move(msg)); - } - else - { - MessageDispatch(packetHeader, peerAddress, std::move(msg)); - } -} - -void SecureSessionMgr::MessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, - System::PacketBufferHandle msg) -{ - if (mCB != nullptr) - { - PayloadHeader payloadHeader; - ReturnOnFailure(payloadHeader.DecodeAndConsume(msg)); - mCB->OnMessageReceived(packetHeader, payloadHeader, SecureSessionHandle(), peerAddress, std::move(msg), this); - } -} - -void SecureSessionMgr::SecureMessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, - System::PacketBufferHandle msg) { CHIP_ERROR err = CHIP_NO_ERROR; PeerConnectionState * state = mPeerConnections.FindPeerConnectionState(packetHeader.GetEncryptionKeyID(), nullptr); + PacketBufferHandle origMsg; PayloadHeader payloadHeader; Transport::AdminPairingInfo * admin = nullptr; @@ -392,10 +365,8 @@ void SecureSessionMgr::SecureMessageDispatch(const PacketHeader & packetHeader, } admin = mAdmins->FindAdmin(state->GetAdminId()); - VerifyOrExit(admin != nullptr, - ChipLogError(Inet, "Secure transport received packet for unknown admin (%p, %d) pairing, discarding", state, - state->GetAdminId())); - if (packetHeader.GetDestinationNodeId().HasValue() && admin->GetNodeId() != kUndefinedNodeId) + VerifyOrExit(admin != nullptr, ChipLogError(Inet, "Secure transport received packet for unknown admin pairing, discarding")); + if (packetHeader.GetDestinationNodeId().HasValue()) { VerifyOrExit( admin->GetNodeId() == packetHeader.GetDestinationNodeId().Value(), @@ -425,20 +396,11 @@ void SecureSessionMgr::SecureMessageDispatch(const PacketHeader & packetHeader, } // Decode the message - VerifyOrExit(CHIP_NO_ERROR == SecureMessageCodec::Decode(state, payloadHeader, packetHeader, msg), - ChipLogError(Inet, "Secure transport received message, but failed to decode it, discarding")); + VerifyOrReturn(CHIP_NO_ERROR == SecureMessageCodec::Decode(state, payloadHeader, packetHeader, msg)); - if (packetHeader.GetSourceNodeId().HasValue()) - { - if (state->GetPeerNodeId() == kUndefinedNodeId) - { - state->SetPeerNodeId(packetHeader.GetSourceNodeId().Value()); - } - } - - if (packetHeader.GetDestinationNodeId().HasValue()) + if (state->GetPeerNodeId() == kUndefinedNodeId && packetHeader.GetSourceNodeId().HasValue()) { - admin->SetNodeId(packetHeader.GetDestinationNodeId().Value()); + state->SetPeerNodeId(packetHeader.GetSourceNodeId().Value()); } // TODO: once mDNS address resolution is available reconsider if this is required @@ -462,7 +424,7 @@ void SecureSessionMgr::SecureMessageDispatch(const PacketHeader & packetHeader, if (mCB != nullptr) { SecureSessionHandle session(state->GetPeerNodeId(), state->GetPeerKeyID(), state->GetAdminId()); - mCB->OnMessageReceived(packetHeader, payloadHeader, session, peerAddress, std::move(msg), this); + mCB->OnMessageReceived(packetHeader, payloadHeader, session, std::move(msg), this); } exit: diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index 8fd23673141ead..53e25f6ae62359 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include #include @@ -149,13 +149,11 @@ class DLL_EXPORT SecureSessionMgrDelegate * @param packetHeader The message header * @param payloadHeader The payload header * @param session The handle to the secure session - * @param source The sender's address * @param msgBuf The received message * @param mgr A pointer to the SecureSessionMgr */ virtual void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - SecureSessionHandle session, const Transport::PeerAddress & source, - System::PacketBufferHandle msgBuf, SecureSessionMgr * mgr) + SecureSessionHandle session, System::PacketBufferHandle msgBuf, SecureSessionMgr * mgr) {} /** @@ -254,7 +252,7 @@ class DLL_EXPORT SecureSessionMgr : public TransportMgrDelegate * establishes the security keys for secure communication with the * peer node. */ - CHIP_ERROR NewPairing(const Optional & peerAddr, NodeId peerNodeId, PairingSession * pairing, + CHIP_ERROR NewPairing(const Optional & peerAddr, NodeId peerNodeId, PASESession * pairing, PairingDirection direction, Transport::AdminId admin, Transport::Base * transport = nullptr); /** @@ -368,11 +366,6 @@ class DLL_EXPORT SecureSessionMgr : public TransportMgrDelegate * Callback for timer expiry check */ static void ExpiryTimerCallback(System::Layer * layer, void * param, System::Error error); - - void SecureMessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, - System::PacketBufferHandle msg); - void MessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, - System::PacketBufferHandle msg); }; namespace MessagePacketBuffer { diff --git a/src/app/server/StorablePeerConnection.cpp b/src/transport/StorablePeerConnection.cpp similarity index 98% rename from src/app/server/StorablePeerConnection.cpp rename to src/transport/StorablePeerConnection.cpp index 8b032c68a59d7f..647b18ef457526 100644 --- a/src/app/server/StorablePeerConnection.cpp +++ b/src/transport/StorablePeerConnection.cpp @@ -15,9 +15,9 @@ * limitations under the License. */ -#include #include #include +#include namespace chip { diff --git a/src/app/server/StorablePeerConnection.h b/src/transport/StorablePeerConnection.h similarity index 97% rename from src/app/server/StorablePeerConnection.h rename to src/transport/StorablePeerConnection.h index 5583c410a98834..9038e677c2acf0 100644 --- a/src/app/server/StorablePeerConnection.h +++ b/src/transport/StorablePeerConnection.h @@ -18,7 +18,7 @@ #pragma once #include -#include +#include namespace chip { diff --git a/src/transport/TransportMgrBase.cpp b/src/transport/TransportMgrBase.cpp index 0265e6369dc34b..08079f69a46b59 100644 --- a/src/transport/TransportMgrBase.cpp +++ b/src/transport/TransportMgrBase.cpp @@ -48,15 +48,17 @@ CHIP_ERROR TransportMgrBase::Init(Transport::Base * transport) void TransportMgrBase::Close() { mSecureSessionMgr = nullptr; + mRendezvous = nullptr; mTransport = nullptr; } void TransportMgrBase::HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBufferHandle msg) { - if (mSecureSessionMgr != nullptr) + TransportMgrDelegate * handler = packetHeader.GetFlags().Has(Header::FlagValues::kSecure) ? mSecureSessionMgr : mRendezvous; + if (handler != nullptr) { - mSecureSessionMgr->OnMessageReceived(packetHeader, peerAddress, std::move(msg)); + handler->OnMessageReceived(packetHeader, peerAddress, std::move(msg)); } else { diff --git a/src/transport/TransportMgrBase.h b/src/transport/TransportMgrBase.h index fcb60080ce881c..91c97a6c7ae1c5 100644 --- a/src/transport/TransportMgrBase.h +++ b/src/transport/TransportMgrBase.h @@ -44,11 +44,14 @@ class TransportMgrBase : public Transport::RawTransportDelegate void SetSecureSessionMgr(TransportMgrDelegate * secureSessionMgr) { mSecureSessionMgr = secureSessionMgr; } + void SetRendezvousSession(TransportMgrDelegate * rendezvousSessionMgr) { mRendezvous = rendezvousSessionMgr; } + void HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBufferHandle msg) override; private: TransportMgrDelegate * mSecureSessionMgr = nullptr; + TransportMgrDelegate * mRendezvous = nullptr; Transport::Base * mTransport = nullptr; }; diff --git a/src/transport/raw/tests/TestTCP.cpp b/src/transport/raw/tests/TestTCP.cpp index cd801b7997c918..e8f91c637bd412 100644 --- a/src/transport/raw/tests/TestTCP.cpp +++ b/src/transport/raw/tests/TestTCP.cpp @@ -111,6 +111,7 @@ class MockTransportMgrDelegate : public chip::TransportMgrDelegate NL_TEST_ASSERT(mSuite, err == CHIP_NO_ERROR); mTransportMgrBase.SetSecureSessionMgr(this); + mTransportMgrBase.SetRendezvousSession(this); mTransportMgrBase.Init(&tcp); mReceiveHandlerCallCount = 0; diff --git a/src/transport/raw/tests/TestUDP.cpp b/src/transport/raw/tests/TestUDP.cpp index aa7a75a170c8d2..f2400a15faac4a 100644 --- a/src/transport/raw/tests/TestUDP.cpp +++ b/src/transport/raw/tests/TestUDP.cpp @@ -124,6 +124,7 @@ void CheckMessageTest(nlTestSuite * inSuite, void * inContext, const IPAddress & MockTransportMgrDelegate gMockTransportMgrDelegate(inSuite); TransportMgrBase gTransportMgrBase; gTransportMgrBase.SetSecureSessionMgr(&gMockTransportMgrDelegate); + gTransportMgrBase.SetRendezvousSession(&gMockTransportMgrDelegate); gTransportMgrBase.Init(&udp); ReceiveHandlerCallCount = 0; diff --git a/src/transport/tests/BUILD.gn b/src/transport/tests/BUILD.gn index e66799aa3b975f..b14384ac163223 100644 --- a/src/transport/tests/BUILD.gn +++ b/src/transport/tests/BUILD.gn @@ -24,6 +24,7 @@ chip_test_suite("tests") { test_sources = [ "TestCASESession.cpp", + "TestPASESession.cpp", "TestPeerConnections.cpp", "TestSecureSession.cpp", "TestSecureSessionMgr.cpp", diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/transport/tests/TestPASESession.cpp similarity index 71% rename from src/protocols/secure_channel/tests/TestPASESession.cpp rename to src/transport/tests/TestPASESession.cpp index b7998829708c53..2c315122408717 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/transport/tests/TestPASESession.cpp @@ -26,50 +26,34 @@ #include #include -#include #include #include #include #include +#include using namespace chip; class TestSecurePairingDelegate : public SessionEstablishmentDelegate { public: - void OnSessionEstablishmentError(CHIP_ERROR error) override { mNumPairingErrors++; } - - void OnSessionEstablished() override { mNumPairingComplete++; } - - uint32_t mNumPairingErrors = 0; - uint32_t mNumPairingComplete = 0; -}; - -class TestSecurePairingExchangeContext : public Messaging::ExchangeContext -{ -public: - CHIP_ERROR SendMessage(Protocols::Id protocolId, uint8_t msgType, System::PacketBufferHandle msgPayload, - const Messaging::SendFlags & sendFlags) override + CHIP_ERROR SendSessionEstablishmentMessage(const PacketHeader & header, const Transport::PeerAddress & peerAddress, + System::PacketBufferHandle msgBuf) override { mNumMessageSend++; - ReturnErrorOnFailure(mMessageSendError); - if (peer != nullptr) - { - PayloadHeader payloadHeader; - payloadHeader.SetMessageType(protocolId, msgType); - peer->OnMessageReceived(peerContext, PacketHeader(), payloadHeader, std::move(msgPayload)); - } - - return CHIP_NO_ERROR; + return (peer != nullptr) ? peer->HandlePeerMessage(header, peerAddress, std::move(msgBuf)) : mMessageSendError; } - void Free() override {} + void OnSessionEstablishmentError(CHIP_ERROR error) override { mNumPairingErrors++; } + + void OnSessionEstablished() override { mNumPairingComplete++; } uint32_t mNumMessageSend = 0; + uint32_t mNumPairingErrors = 0; + uint32_t mNumPairingComplete = 0; CHIP_ERROR mMessageSendError = CHIP_NO_ERROR; - PASESession * peer = nullptr; - Messaging::ExchangeContext * peerContext = nullptr; + PASESession * peer = nullptr; }; void SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext) @@ -88,24 +72,19 @@ void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) { // Test all combinations of invalid parameters TestSecurePairingDelegate delegate; - - TestSecurePairingExchangeContext * context = chip::Platform::New(); PASESession pairing; - NL_TEST_ASSERT(inSuite, - pairing.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, nullptr, nullptr) != CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - pairing.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, context, &delegate) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, pairing.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, nullptr) != CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, pairing.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, &delegate) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, context->mNumMessageSend == 1); + NL_TEST_ASSERT(inSuite, delegate.mNumMessageSend == 1); + + delegate.mMessageSendError = CHIP_ERROR_BAD_REQUEST; PASESession pairing1; - TestSecurePairingExchangeContext * context1 = chip::Platform::New(); - context1->mMessageSendError = CHIP_ERROR_BAD_REQUEST; NL_TEST_ASSERT(inSuite, - pairing1.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, context1, &delegate) == - CHIP_ERROR_BAD_REQUEST); + pairing1.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, &delegate) == CHIP_ERROR_BAD_REQUEST); } void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, PASESession & pairingCommissioner, @@ -113,27 +92,22 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, P { // Test all combinations of invalid parameters TestSecurePairingDelegate delegateAccessory; - TestSecurePairingExchangeContext * contextAccessory = chip::Platform::New(); - TestSecurePairingExchangeContext * contextCommissioner = chip::Platform::New(); PASESession pairingAccessory; - contextAccessory->peerContext = contextCommissioner; - contextCommissioner->peerContext = contextAccessory; - - contextCommissioner->peer = &pairingAccessory; - contextAccessory->peer = &pairingCommissioner; + delegateCommissioner.peer = &pairingAccessory; + delegateAccessory.peer = &pairingCommissioner; NL_TEST_ASSERT(inSuite, pairingAccessory.WaitForPairing(1234, 500, (const uint8_t *) "saltSALT", 8, 0, &delegateAccessory) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - pairingCommissioner.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, contextCommissioner, - &delegateCommissioner) == CHIP_NO_ERROR); + pairingCommissioner.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 0, &delegateCommissioner) == + CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, contextAccessory->mNumMessageSend == 2); + NL_TEST_ASSERT(inSuite, delegateAccessory.mNumMessageSend == 2); NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, contextCommissioner->mNumMessageSend == 3); + NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumMessageSend == 3); NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); } @@ -179,12 +153,10 @@ void SecurePairingSerializeTest(nlTestSuite * inSuite, void * inContext) { SecureSession session1; - CHIP_ERROR err = testPairingSession1->DeriveSecureSession(Uint8::from_const_char("abc"), 3, session1); - - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, + testPairingSession1->DeriveSecureSession(Uint8::from_const_char("abc"), 3, session1) == CHIP_NO_ERROR); - err = session1.Encrypt(plain_text, sizeof(plain_text), encrypted, header, mac); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, session1.Encrypt(plain_text, sizeof(plain_text), encrypted, header, mac) == CHIP_NO_ERROR); } { @@ -248,8 +220,6 @@ static nlTestSuite sSuite = }; // clang-format on -// TODO: TestPASESession is currently disabled due to lacking convenient way of creating exchange context - /** * Main */ diff --git a/src/transport/tests/TestSecureSessionMgr.cpp b/src/transport/tests/TestSecureSessionMgr.cpp index dcaa61e4df98a1..a2a66e90bb148a 100644 --- a/src/transport/tests/TestSecureSessionMgr.cpp +++ b/src/transport/tests/TestSecureSessionMgr.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include @@ -93,8 +92,7 @@ class TestSessMgrCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, SecureSessionHandle session, - const Transport::PeerAddress & source, System::PacketBufferHandle msgBuf, - SecureSessionMgr * mgr) override + System::PacketBufferHandle msgBuf, SecureSessionMgr * mgr) override { NL_TEST_ASSERT(mSuite, header.GetSourceNodeId() == Optional::Value(kSourceNodeId)); NL_TEST_ASSERT(mSuite, header.GetDestinationNodeId() == Optional::Value(kDestinationNodeId));