From 4cf3481d68efa7cb037d5473dcd8acef2fe3e62d Mon Sep 17 00:00:00 2001 From: Song Guo Date: Thu, 5 Nov 2020 15:40:41 +0800 Subject: [PATCH 01/17] [rendezvous] Add initial support for IP rendezvous --- .../esp32/main/EchoServer.cpp | 26 ++-- .../chip-app-server/DataModelHandler.cpp | 2 +- .../chip-app-server/RendezvousServer.cpp | 3 +- examples/common/chip-app-server/Server.cpp | 15 ++- .../include/DataModelHandler.h | 3 +- .../include/RendezvousServer.h | 4 +- .../common/chip-app-server/include/Server.h | 4 +- .../chip-app-server/include/SessionManager.h | 2 +- .../esp32/main/ResponseServer.cpp | 27 ++-- src/app/util/chip-message-send.cpp | 4 +- src/controller/CHIPDeviceController.cpp | 72 +++++++++-- src/controller/CHIPDeviceController.h | 14 ++- .../ChipDeviceController-ScriptBinding.cpp | 27 ++++ src/controller/python/chip-device-ctrl.py | 11 +- src/controller/python/chip/ChipDeviceCtrl.py | 107 +++++++++++----- src/messaging/ExchangeMgr.cpp | 6 +- src/messaging/ExchangeMgr.h | 12 +- src/messaging/tests/TestExchangeMgr.cpp | 28 +++-- src/transport/BLE.cpp | 17 ++- src/transport/BLE.h | 8 ++ src/transport/BUILD.gn | 2 + src/transport/RendezvousParameters.h | 11 +- src/transport/RendezvousSession.cpp | 56 ++++----- src/transport/RendezvousSession.h | 21 +++- src/transport/RendezvousSessionDelegate.h | 8 +- src/transport/SecurePairingSession.cpp | 21 ++-- src/transport/SecurePairingSession.h | 24 +++- src/transport/SecureSessionMgr.cpp | 102 +++++++++++++--- src/transport/SecureSessionMgr.h | 86 ++++++------- src/transport/TransportMgr.cpp | 57 +++++++++ src/transport/TransportMgr.h | 115 ++++++++++++++++++ src/transport/raw/MessageHeader.h | 5 +- .../tests/TestSecurePairingSession.cpp | 21 ++-- src/transport/tests/TestSecureSessionMgr.cpp | 19 ++- 34 files changed, 698 insertions(+), 242 deletions(-) create mode 100644 src/transport/TransportMgr.cpp create mode 100644 src/transport/TransportMgr.h diff --git a/examples/all-clusters-app/esp32/main/EchoServer.cpp b/examples/all-clusters-app/esp32/main/EchoServer.cpp index 24c61422054fab..a22f7626e9a602 100644 --- a/examples/all-clusters-app/esp32/main/EchoServer.cpp +++ b/examples/all-clusters-app/esp32/main/EchoServer.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include @@ -122,7 +123,7 @@ class EchoServerCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, - System::PacketBuffer * buffer, SecureSessionMgrBase * mgr) override + System::PacketBuffer * buffer, SecureSessionMgr * mgr) override { CHIP_ERROR err; const size_t data_len = buffer->DataLength(); @@ -179,13 +180,13 @@ class EchoServerCallback : public SecureSessionMgrDelegate } } - void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgrBase * mgr) override + void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * mgr) override { ESP_LOGE(TAG, "ERROR: %s\n Got UDP error", ErrorStr(error)); statusLED1.BlinkOnError(); } - void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) override + void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) override { ESP_LOGI(TAG, "Received a new connection."); } @@ -218,15 +219,16 @@ class EchoServerCallback : public SecureSessionMgrDelegate EchoServerCallback gCallbacks; -SecureSessionMgr - sessions; +TransportMgr + gTransports; +SecureSessionMgr sessions; } // namespace namespace chip { -SecureSessionMgrBase & SessionManager() +SecureSessionMgr & SessionManager() { return sessions; } @@ -242,9 +244,11 @@ void PairingComplete(SecurePairingSession * pairing) void startServer() { CHIP_ERROR err = CHIP_NO_ERROR; - err = sessions.Init(kLocalNodeId, &DeviceLayer::SystemLayer, - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(NULL), - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv4)); + err = sessions.Init(kLocalNodeId, &DeviceLayer::SystemLayer); + SuccessOrExit(err); + err = gTransports.Init(&sessions, nullptr, + UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(nullptr), + UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv4)); SuccessOrExit(err); sessions.SetDelegate(&gCallbacks); diff --git a/examples/common/chip-app-server/DataModelHandler.cpp b/examples/common/chip-app-server/DataModelHandler.cpp index 5b7445568d1d6b..31e493cf5e64ac 100644 --- a/examples/common/chip-app-server/DataModelHandler.cpp +++ b/examples/common/chip-app-server/DataModelHandler.cpp @@ -41,7 +41,7 @@ extern "C" { * @param [in] buffer The buffer holding the message. This function guarantees * that it will free the buffer before returning. */ -void HandleDataModelMessage(const PacketHeader & header, System::PacketBuffer * buffer, SecureSessionMgrBase * mgr) +void HandleDataModelMessage(const PacketHeader & header, System::PacketBuffer * buffer, SecureSessionMgr * mgr) { EmberApsFrame frame; bool ok = extractApsFrame(buffer->Start(), buffer->DataLength(), &frame) > 0; diff --git a/examples/common/chip-app-server/RendezvousServer.cpp b/examples/common/chip-app-server/RendezvousServer.cpp index a1179087156051..8208dc90879ee0 100644 --- a/examples/common/chip-app-server/RendezvousServer.cpp +++ b/examples/common/chip-app-server/RendezvousServer.cpp @@ -56,7 +56,8 @@ void RendezvousServer::OnRendezvousConnectionClosed() ChipLogProgress(AppServer, "OnRendezvousConnectionClosed"); } -void RendezvousServer::OnRendezvousMessageReceived(PacketBuffer * buffer) +void RendezvousServer::OnRendezvousMessageReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + PacketBuffer * buffer) { chip::System::PacketBuffer::Free(buffer); } diff --git a/examples/common/chip-app-server/Server.cpp b/examples/common/chip-app-server/Server.cpp index 5f02f51ffdf770..942dd303ae411a 100644 --- a/examples/common/chip-app-server/Server.cpp +++ b/examples/common/chip-app-server/Server.cpp @@ -50,7 +50,7 @@ class ServerCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, - System::PacketBuffer * buffer, SecureSessionMgrBase * mgr) override + System::PacketBuffer * buffer, SecureSessionMgr * mgr) override { const size_t data_len = buffer->DataLength(); char src_addr[PeerAddress::kMaxToStringSize]; @@ -77,20 +77,21 @@ class ServerCallback : public SecureSessionMgrDelegate } } - void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) override + void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) override { ChipLogProgress(AppServer, "Received a new connection."); } }; -DemoSessionManager gSessions; +DemoTransportMgr gTransports; +SecureSessionMgr gSessions; ServerCallback gCallbacks; SecurePairingUsingTestSecret gTestPairing; RendezvousServer gRendezvousServer; } // namespace -SecureSessionMgrBase & chip::SessionManager() +SecureSessionMgr & chip::SessionManager() { return gSessions; } @@ -104,8 +105,7 @@ void InitServer() InitDataModelHandler(); - err = gSessions.Init(EXAMPLE_SERVER_NODEID, &DeviceLayer::SystemLayer, - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); + err = gSessions.Init(EXAMPLE_SERVER_NODEID, &DeviceLayer::SystemLayer); SuccessOrExit(err); // This flag is used to bypass BLE in the cirque test @@ -129,6 +129,9 @@ void InitServer() gSessions.SetDelegate(&gCallbacks); chip::Mdns::DiscoveryManager::GetInstance().StartPublishDevice(chip::Inet::kIPAddressType_IPv6); + gTransports.Init(&gSessions, gRendezvousServer.GetRendezvousSession(), + UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); + exit: if (err != CHIP_NO_ERROR) { diff --git a/examples/common/chip-app-server/include/DataModelHandler.h b/examples/common/chip-app-server/include/DataModelHandler.h index 61493a72d84ca3..d05c557fe13112 100644 --- a/examples/common/chip-app-server/include/DataModelHandler.h +++ b/examples/common/chip-app-server/include/DataModelHandler.h @@ -34,7 +34,6 @@ extern "C" { * @param [in] buffer The buffer holding the message. This function guarantees * that it will free the buffer before returning. */ -void HandleDataModelMessage(const chip::PacketHeader & header, chip::System::PacketBuffer * buffer, - chip::SecureSessionMgrBase * mgr); +void HandleDataModelMessage(const chip::PacketHeader & header, chip::System::PacketBuffer * buffer, chip::SecureSessionMgr * mgr); void InitDataModelHandler(); } diff --git a/examples/common/chip-app-server/include/RendezvousServer.h b/examples/common/chip-app-server/include/RendezvousServer.h index 3b44690d39bfa6..5bf4738be7f335 100644 --- a/examples/common/chip-app-server/include/RendezvousServer.h +++ b/examples/common/chip-app-server/include/RendezvousServer.h @@ -34,8 +34,10 @@ class RendezvousServer : public RendezvousSessionDelegate void OnRendezvousConnectionOpened() override; void OnRendezvousConnectionClosed() override; void OnRendezvousError(CHIP_ERROR err) override; - void OnRendezvousMessageReceived(System::PacketBuffer * buffer) override; + void OnRendezvousMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * buffer) override; void OnRendezvousStatusUpdate(Status status, CHIP_ERROR err) override; + RendezvousSession * GetRendezvousSession() { return &mRendezvousSession; }; private: RendezvousSession mRendezvousSession; diff --git a/examples/common/chip-app-server/include/Server.h b/examples/common/chip-app-server/include/Server.h index b4be5aba1f53ac..6bd260b9f23b8e 100644 --- a/examples/common/chip-app-server/include/Server.h +++ b/examples/common/chip-app-server/include/Server.h @@ -17,10 +17,10 @@ #pragma once -#include +#include #include -using DemoSessionManager = chip::SecureSessionMgr; +using DemoTransportMgr = chip::TransportMgr; /** * Initialize DataModelHandler and start CHIP datamodel server, the server diff --git a/examples/common/chip-app-server/include/SessionManager.h b/examples/common/chip-app-server/include/SessionManager.h index ebfc2d8c78f9f5..17d78a987de5ab 100644 --- a/examples/common/chip-app-server/include/SessionManager.h +++ b/examples/common/chip-app-server/include/SessionManager.h @@ -20,5 +20,5 @@ #include namespace chip { -SecureSessionMgrBase & SessionManager(); +SecureSessionMgr & SessionManager(); } // namespace chip diff --git a/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp b/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp index f2c5c9d92ce642..713bbfa9e92907 100644 --- a/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp +++ b/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include @@ -61,7 +62,7 @@ class ResponseServerCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, - System::PacketBuffer * buffer, SecureSessionMgrBase * mgr) override + System::PacketBuffer * buffer, SecureSessionMgr * mgr) override { CHIP_ERROR err; const size_t data_len = buffer->DataLength(); @@ -90,12 +91,12 @@ class ResponseServerCallback : public SecureSessionMgrDelegate } } - void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgrBase * mgr) override + void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * mgr) override { ESP_LOGE(TAG, "ERROR: %s\n Got UDP error", ErrorStr(error)); } - void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) override + void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) override { ESP_LOGI(TAG, "Received a new connection."); } @@ -127,16 +128,16 @@ class ResponseServerCallback : public SecureSessionMgrDelegate }; ResponseServerCallback gCallbacks; - -SecureSessionMgr - sessions; +TransportMgr + gTransports; +SecureSessionMgr sessions; } // namespace namespace chip { -SecureSessionMgrBase & SessionManager() +SecureSessionMgr & SessionManager() { return sessions; } @@ -152,9 +153,11 @@ void PairingComplete(SecurePairingSession * pairing) void startServer() { CHIP_ERROR err = CHIP_NO_ERROR; - err = sessions.Init(kLocalNodeId, &DeviceLayer::SystemLayer, - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(nullptr), - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv4)); + err = sessions.Init(kLocalNodeId, &DeviceLayer::SystemLayer); + SuccessOrExit(err); + err = gTransports.Init(&sessions, nullptr, + UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(nullptr), + UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv4)); SuccessOrExit(err); sessions.SetDelegate(&gCallbacks); diff --git a/src/app/util/chip-message-send.cpp b/src/app/util/chip-message-send.cpp index 69ec6ead85670a..dbc06e1bdee716 100644 --- a/src/app/util/chip-message-send.cpp +++ b/src/app/util/chip-message-send.cpp @@ -25,7 +25,7 @@ #include #include // PacketBuffer and the like #include -#include // For SecureSessionMgrBase +#include // For SecureSessionMgr using namespace chip; @@ -35,7 +35,7 @@ using namespace chip; // // https://github.com/project-chip/connectedhomeip/issues/2566 tracks that API. namespace chip { -extern SecureSessionMgrBase & SessionManager(); +extern SecureSessionMgr & SessionManager(); } extern "C" { diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index ab1471b3d1f651..ee52a009078c20 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -142,6 +142,19 @@ CHIP_ERROR ChipDeviceController::Init(NodeId localNodeId, System::Layer * system mPairingDelegate = pairingDelegate; mStorageDelegate = storageDelegate; + mTransportMgr = chip::Platform::New(); // Listen to both IPv4 and IPv6 +#if INET_CONFIG_ENABLE_IPV4 + err = mTransportMgr->Init( + mSessionManager, mRendezvousSession, + Transport::UdpListenParameters(mInetLayer).SetAddressType(kIPAddressType_IPv6).SetListenPort(mListenPort), + Transport::UdpListenParameters(mInetLayer).SetAddressType(kIPAddressType_IPv4).SetListenPort(mListenPort)); +#else + err = mTransportMgr->Init( + mSessionManager, mRendezvousSession, + Transport::UdpListenParameters(mInetLayer).SetAddressType(kIPAddressType_IPv6).SetListenPort(mListenPort)); +#endif + SuccessOrExit(err); + if (mStorageDelegate != nullptr) { mStorageDelegate->SetDelegate(this); @@ -206,14 +219,25 @@ CHIP_ERROR ChipDeviceController::ConnectDevice(NodeId remoteDeviceId, Rendezvous VerifyOrExit(mConState == kConnectionState_NotConnected, err = CHIP_ERROR_INCORRECT_STATE); #if CONFIG_DEVICE_LAYER && CONFIG_NETWORK_LAYER_BLE - if (!params.HasBleLayer()) + // To support IP rendezvous, add BLE PeerAddress for default + if (!params.HasPeerAddress()) { - params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()); + params.SetPeerAddress(Transport::PeerAddress(Transport::Type::kBle)); + if (!params.HasBleLayer()) + { + params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()); + } } #endif // CONFIG_DEVICE_LAYER && CONFIG_NETWORK_LAYER_BLE mRendezvousSession = chip::Platform::New(this); - err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId)); + // For UDP, set the discriminator for Controller flag + if (params.GetPeerAddress().GetTransportType() == Transport::Type::kUdp) + { + params.SetDiscriminator(0xfff); + } + err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId)); + mTransportMgr->SetRendezvousSession(mRendezvousSession); SuccessOrExit(err); mRemoteDeviceId = Optional::Value(remoteDeviceId); @@ -228,11 +252,18 @@ CHIP_ERROR ChipDeviceController::ConnectDevice(NodeId remoteDeviceId, Rendezvous mOnComplete.Response = onMessageReceived; mOnError = onError; + if (params.GetPeerAddress().GetTransportType() == Transport::Type::kUdp) + { + // Since we are using UDP, no need to wait for connecting + mRendezvousSession->OnRendezvousConnectionOpened(); + } + exit: if (err != CHIP_NO_ERROR && mRendezvousSession != nullptr) { chip::Platform::Delete(mRendezvousSession); mRendezvousSession = nullptr; + mTransportMgr->SetRendezvousSession(nullptr); } return err; @@ -275,10 +306,27 @@ CHIP_ERROR ChipDeviceController::ConnectDeviceWithoutSecurePairing(NodeId remote CHIP_ERROR ChipDeviceController::SetUdpListenPort(uint16_t listenPort) { + CHIP_ERROR err = CHIP_NO_ERROR; + if (mState != kState_Initialized || mConState != kConnectionState_NotConnected) return CHIP_ERROR_INCORRECT_STATE; mListenPort = listenPort; - return CHIP_NO_ERROR; + + chip::Platform::Delete(mTransportMgr); + mTransportMgr = chip::Platform::New(); + +#if INET_CONFIG_ENABLE_IPV4 + err = mTransportMgr->Init( + mSessionManager, mRendezvousSession, + Transport::UdpListenParameters(mInetLayer).SetAddressType(kIPAddressType_IPv6).SetListenPort(mListenPort), + Transport::UdpListenParameters(mInetLayer).SetAddressType(kIPAddressType_IPv4).SetListenPort(mListenPort)); +#else + err = mTransportMgr->Init( + mSessionManager, mRendezvousSession, + Transport::UdpListenParameters(mInetLayer).SetAddressType(kIPAddressType_IPv6).SetListenPort(mListenPort)); +#endif + + return err; } CHIP_ERROR ChipDeviceController::EstablishSecureSession() @@ -287,13 +335,13 @@ CHIP_ERROR ChipDeviceController::EstablishSecureSession() VerifyOrExit(mSecurePairingSession != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - mSessionManager = chip::Platform::New>(); + mSessionManager = chip::Platform::New(); - err = mSessionManager->Init( - mLocalDeviceId, mSystemLayer, - Transport::UdpListenParameters(mInetLayer).SetAddressType(mDeviceAddr.Type()).SetListenPort(mListenPort)); + err = mSessionManager->Init(mLocalDeviceId, mSystemLayer); SuccessOrExit(err); + mTransportMgr->SetSecureSessionMgr(mSessionManager); + mSessionManager->SetDelegate(this); err = mSessionManager->NewPairing( @@ -460,6 +508,9 @@ CHIP_ERROR ChipDeviceController::DisconnectDevice() mRendezvousSession = nullptr; } + mTransportMgr->SetSecureSessionMgr(nullptr); + mTransportMgr->SetRendezvousSession(nullptr); + mConState = kConnectionState_NotConnected; return err; } @@ -617,7 +668,7 @@ void ChipDeviceController::ClearRequestState() } } -void ChipDeviceController::OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) {} +void ChipDeviceController::OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) {} void ChipDeviceController::OnAddressResolved(CHIP_ERROR error, NodeId nodeId, SecureSessionMgrBase * mgr) { @@ -629,7 +680,7 @@ void ChipDeviceController::OnAddressResolved(CHIP_ERROR error, NodeId nodeId, Se void ChipDeviceController::OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, - SecureSessionMgrBase * mgr) + SecureSessionMgr * mgr) { if (header.GetSourceNodeId().HasValue()) { @@ -655,6 +706,7 @@ void ChipDeviceController::OnRendezvousError(CHIP_ERROR err) { chip::Platform::Delete(mRendezvousSession); mRendezvousSession = nullptr; + mTransportMgr->SetRendezvousSession(nullptr); } if (mPairingDelegate != nullptr) diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index a115288e37752c..3341136170abd9 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -35,6 +35,7 @@ #include #include #include +#include #include namespace chip { @@ -51,6 +52,12 @@ typedef void (*ErrorHandler)(ChipDeviceController * deviceController, void * app const Inet::IPPacketInfo * pktInfo); typedef void (*MessageReceiveHandler)(ChipDeviceController * deviceController, void * appReqState, System::PacketBuffer * payload); +#if INET_CONFIG_ENABLE_IPV4 +using TransportMgrType = TransportMgr; +#else +using TransportMgrType = TransportMgr; +#endif + class DLL_EXPORT DevicePairingDelegate { public: @@ -237,9 +244,9 @@ class DLL_EXPORT ChipDeviceController : public SecureSessionMgrDelegate, CHIP_ERROR ServiceEventSignal(); void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, - System::PacketBuffer * msgBuf, SecureSessionMgrBase * mgr) override; + System::PacketBuffer * msgBuf, SecureSessionMgr * mgr) override; - void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) override; + void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) override; void OnAddressResolved(CHIP_ERROR error, NodeId nodeId, SecureSessionMgrBase * mgr) override; @@ -270,7 +277,8 @@ class DLL_EXPORT ChipDeviceController : public SecureSessionMgrDelegate, System::Layer * mSystemLayer; Inet::InetLayer * mInetLayer; - SecureSessionMgr * mSessionManager; + TransportMgrType * mTransportMgr; + SecureSessionMgr * mSessionManager; RendezvousSession * mRendezvousSession; ConnectionState mConState; diff --git a/src/controller/python/ChipDeviceController-ScriptBinding.cpp b/src/controller/python/ChipDeviceController-ScriptBinding.cpp index 18f6c0268510ae..e6b80d1617ce91 100644 --- a/src/controller/python/ChipDeviceController-ScriptBinding.cpp +++ b/src/controller/python/ChipDeviceController-ScriptBinding.cpp @@ -46,12 +46,16 @@ #include "ChipDeviceController-ScriptDevicePairingDelegate.h" #include +#include #include #include #include #include +#include +using namespace chip; using namespace chip::Ble; +using namespace chip::Inet; using namespace chip::DeviceController; extern "C" { @@ -170,6 +174,9 @@ CHIP_ERROR nl_Chip_DeviceController_DeleteDeviceController(chip::DeviceControlle CHIP_ERROR nl_Chip_DeviceController_Connect(chip::DeviceController::ChipDeviceController * devCtrl, BLE_CONNECTION_OBJECT connObj, uint32_t setupPinCode, OnConnectFunct onConnect, OnMessageFunct onMessage, OnErrorFunct onError); +CHIP_ERROR nl_Chip_DeviceController_ConnectIP(chip::DeviceController::ChipDeviceController * devCtrl, const char * peerIP, + uint32_t setupPINCode, OnConnectFunct onConnect, OnMessageFunct onMessage, + OnErrorFunct onError); // Network Provisioning CHIP_ERROR @@ -549,6 +556,26 @@ CHIP_ERROR nl_Chip_DeviceController_Connect(chip::DeviceController::ChipDeviceCo return err; } +CHIP_ERROR nl_Chip_DeviceController_ConnectIP(chip::DeviceController::ChipDeviceController * devCtrl, const char * peerIP, + uint32_t setupPINCode, OnConnectFunct onConnect, OnMessageFunct onMessage, + OnErrorFunct onError) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + IPAddress addr; + + chip::RendezvousParameters params = chip::RendezvousParameters().SetSetupPINCode(setupPINCode); + + VerifyOrExit(IPAddress::FromString(peerIP, addr), err = CHIP_ERROR_INVALID_ADDRESS); + + params.SetPeerAddress(Transport::PeerAddress(addr, Transport::Type::kUdp)); + + err = devCtrl->ConnectDevice(kRemoteDeviceId, params, (void *) devCtrl, onConnect, onMessage, onError); + SuccessOrExit(err); + +exit: + return err; +} + CHIP_ERROR nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate(chip::DeviceController::ScriptDevicePairingDelegate ** pairingDelegate) { diff --git a/src/controller/python/chip-device-ctrl.py b/src/controller/python/chip-device-ctrl.py index 6b07db4c43c10d..29b3b7cd27fe81 100755 --- a/src/controller/python/chip-device-ctrl.py +++ b/src/controller/python/chip-device-ctrl.py @@ -365,7 +365,7 @@ def do_btpconnect(self, line): def do_connect(self, line): """ - connect (via BLE) + connect [-ip [ipaddress]]|[-ble] connect command is used for establishing a rendezvous session to the device. currently, only connect using setupPinCode is supported. @@ -380,10 +380,13 @@ def do_connect(self, line): print("Usage:") self.do_help("connect SetupPinCode") return - if len(args) > 1: - print("Unexpected argument: " + args[1]) + if args[0] == "-ip" and len(args) <= 3: + self.devCtrl.ConnectIP(args[1], int(args[2])) + elif args[0] == "-ble" and len(args) <= 2: + self.devCtrl.Connect(FAKE_CONN_OBJ_VALUE, int(args[1])) + else: + print("Unexpected argument(s): " + args) return - self.devCtrl.Connect(FAKE_CONN_OBJ_VALUE, int(args[0])) except ChipStack.ChipStackException as ex: print(str(ex)) return diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index 7d1f6f882d923a..47c392c28e133d 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -38,7 +38,8 @@ _CompleteFunct = CFUNCTYPE(None, c_void_p, c_void_p) -_ErrorFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_ulong, POINTER(DeviceStatusStruct)) +_ErrorFunct = CFUNCTYPE(None, c_void_p, c_void_p, + c_ulong, POINTER(DeviceStatusStruct)) _GetBleEventFunct = CFUNCTYPE(c_void_p) _WriteBleCharacteristicFunct = CFUNCTYPE( c_bool, c_void_p, c_void_p, c_void_p, c_void_p, c_uint16 @@ -55,11 +56,14 @@ # typedef void (*OnMessageFunct)(Chip::DeviceController::ChipDeviceController * dc, void * appReqState, PacketBuffer * buffer); _OnConnectFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p) -_OnRendezvousErrorFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_uint32, c_void_p) +_OnRendezvousErrorFunct = CFUNCTYPE( + None, c_void_p, c_void_p, c_uint32, c_void_p) _OnMessageFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p) # This is a fix for WEAV-429. Jay Logue recommends revisiting this at a later # date to allow for truely multiple instances so this is temporary. + + def _singleton(cls): instance = [None] @@ -78,6 +82,7 @@ class DCState(enum.IntEnum): RENDEZVOUS_ONGOING = 3 RENDEZVOUS_CONNECTED = 4 + @_singleton class ChipDeviceController(object): def __init__(self, startNetworkThread=True): @@ -91,16 +96,19 @@ def __init__(self, startNetworkThread=True): self._InitLib() devCtrl = c_void_p(None) - res = self._dmLib.nl_Chip_DeviceController_NewDeviceController(pointer(devCtrl)) + res = self._dmLib.nl_Chip_DeviceController_NewDeviceController( + pointer(devCtrl)) if res != 0: raise self._ChipStack.ErrorToException(res) - + pairingDelegate = c_void_p(None) - res = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate(pointer(pairingDelegate)) + res = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate( + pointer(pairingDelegate)) if res != 0: raise self._ChipStack.ErrorToException(res) - - res = self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate(devCtrl, pairingDelegate) + + res = self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate( + devCtrl, pairingDelegate) if res != 0: raise self._ChipStack.ErrorToException(res) @@ -108,9 +116,11 @@ def __init__(self, startNetworkThread=True): self.pairingDelegate = pairingDelegate self._ChipStack.devCtrl = devCtrl - self.blockingCB = None # set by other modules(BLE) that require service by thread while thread blocks. + # set by other modules(BLE) that require service by thread while thread blocks. + self.blockingCB = None self.cbHandleBleEvent = ( - None # set by other modules (BLE) that provide event callback to Chip. + # set by other modules (BLE) that provide event callback to Chip. + None ) self.cbHandleBleWriteChar = None self.cbHandleBleSubscribeChar = None @@ -118,9 +128,9 @@ def __init__(self, startNetworkThread=True): def DeviceCtrlHandleMessage(appReqState, buffer): pass - + self.cbHandleMessage = _OnMessageFunct(DeviceCtrlHandleMessage) - + def HandleRendezvousError(appState, reqState, err, devStatusPtr): if self.state == DCState.RENDEZVOUS_ONGOING: print("Failed to connect to device: {}".format(err)) @@ -128,8 +138,9 @@ def HandleRendezvousError(appState, reqState, err, devStatusPtr): self._ChipStack.completeEvent.set() elif self.state == DCState.RENDEZVOUS_CONNECTED: print("Disconnected from device") - - self.cbHandleRendezvousError = _OnRendezvousErrorFunct(HandleRendezvousError) + + self.cbHandleRendezvousError = _OnRendezvousErrorFunct( + HandleRendezvousError) if startNetworkThread: self.StartNetworkThread() @@ -137,7 +148,8 @@ def HandleRendezvousError(appState, reqState, err, devStatusPtr): def __del__(self): if self.devCtrl != None: - self._dmLib.nl_Chip_DeviceController_DeleteDeviceManager(self.devCtrl) + self._dmLib.nl_Chip_DeviceController_DeleteDeviceManager( + self.devCtrl) self.devCtrl = None def DriveBleIO(self): @@ -149,11 +161,13 @@ def DriveBleIO(self): def SetBleEventCB(self, bleEventCB): if self.devCtrl != None: self.cbHandleBleEvent = _GetBleEventFunct(bleEventCB) - self._dmLib.nl_Chip_DeviceController_SetBleEventCB(self.cbHandleBleEvent) + self._dmLib.nl_Chip_DeviceController_SetBleEventCB( + self.cbHandleBleEvent) def SetBleWriteCharCB(self, bleWriteCharCB): if self.devCtrl != None: - self.cbHandleBleWriteChar = _WriteBleCharacteristicFunct(bleWriteCharCB) + self.cbHandleBleWriteChar = _WriteBleCharacteristicFunct( + bleWriteCharCB) self._dmLib.nl_Chip_DeviceController_SetBleWriteCharacteristic( self.cbHandleBleWriteChar ) @@ -170,7 +184,8 @@ def SetBleSubscribeCharCB(self, bleSubscribeCharCB): def SetBleCloseCB(self, bleCloseCB): if self.devCtrl != None: self.cbHandleBleClose = _CloseBleFunct(bleCloseCB) - self._dmLib.nl_Chip_DeviceController_SetBleClose(self.cbHandleBleClose) + self._dmLib.nl_Chip_DeviceController_SetBleClose( + self.cbHandleBleClose) def StartNetworkThread(self): if self.networkThread != None: @@ -183,14 +198,16 @@ def RunNetworkThread(): self._ChipStack.networkLock.release() time.sleep(0.005) - self.networkThread = Thread(target=RunNetworkThread, name="ChipNetworkThread") + self.networkThread = Thread( + target=RunNetworkThread, name="ChipNetworkThread") self.networkThread.daemon = True self.networkThreadRunable = True self.networkThread.start() def IsConnected(self): return self._ChipStack.Call( - lambda: self._dmLib.nl_Chip_DeviceController_IsConnected(self.devCtrl) + lambda: self._dmLib.nl_Chip_DeviceController_IsConnected( + self.devCtrl) ) def ConnectBle(self, bleConnection): @@ -202,19 +219,35 @@ def ConnectBle(self, bleConnection): self._ChipStack.cbHandleError, ) ) - + def Connect(self, connObj, setupPinCode): def HandleComplete(dc, connState, appState): print("Rendezvoud Complete") self.state = DCState.RENDEZVOUS_CONNECTED self._ChipStack.callbackRes = True self._ChipStack.completeEvent.set() - + + onConnectFunct = _OnConnectFunct(HandleComplete) + + self.state = DCState.RENDEZVOUS_ONGOING + return self._ChipStack.CallAsync( + lambda: self._dmLib.nl_Chip_DeviceController_Connect( + self.devCtrl, connObj, setupPinCode, onConnectFunct, self.cbHandleMessage, self.cbHandleRendezvousError) + ) + + def ConnectIP(self, ip, setupPinCode): + def HandleComplete(dc, connState, appState): + print("Rendezvoud Complete") + self.state = DCState.RENDEZVOUS_CONNECTED + self._ChipStack.callbackRes = True + self._ChipStack.completeEvent.set() + onConnectFunct = _OnConnectFunct(HandleComplete) self.state = DCState.RENDEZVOUS_ONGOING return self._ChipStack.CallAsync( - lambda: self._dmLib.nl_Chip_DeviceController_Connect(self.devCtrl, connObj, setupPinCode, onConnectFunct, self.cbHandleMessage, self.cbHandleRendezvousError) + lambda: self._dmLib.nl_Chip_DeviceController_ConnectIP( + self.devCtrl, ip.encode("utf-8"), setupPinCode, onConnectFunct, self.cbHandleMessage, self.cbHandleRendezvousError) ) def Close(self): @@ -237,9 +270,10 @@ def GetLogFilter(self): def SetBlockingCB(self, blockingCB): self._ChipStack.blockingCB = blockingCB - + def SetWifiCredential(self, ssid, password): - ret = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential(self.pairingDelegate, ssid.encode("utf-8"), password.encode("utf-8")) + ret = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential( + self.pairingDelegate, ssid.encode("utf-8"), password.encode("utf-8")) if ret != 0: raise self._ChipStack.ErrorToException(res) @@ -288,10 +322,12 @@ def _InitLib(self): c_uint32 ) - self._dmLib.nl_Chip_DeviceController_SetBleClose.argtypes = [_CloseBleFunct] + self._dmLib.nl_Chip_DeviceController_SetBleClose.argtypes = [ + _CloseBleFunct] self._dmLib.nl_Chip_DeviceController_SetBleClose.restype = c_uint32 - self._dmLib.nl_Chip_DeviceController_IsConnected.argtypes = [c_void_p] + self._dmLib.nl_Chip_DeviceController_IsConnected.argtypes = [ + c_void_p] self._dmLib.nl_Chip_DeviceController_IsConnected.restype = c_bool self._dmLib.nl_Chip_DeviceController_ValidateBTP.argtypes = [ @@ -305,17 +341,26 @@ def _InitLib(self): self._dmLib.nl_Chip_DeviceController_GetLogFilter.argtypes = [] self._dmLib.nl_Chip_DeviceController_GetLogFilter.restype = c_uint8 - self._dmLib.nl_Chip_DeviceController_SetLogFilter.argtypes = [c_uint8] + self._dmLib.nl_Chip_DeviceController_SetLogFilter.argtypes = [ + c_uint8] self._dmLib.nl_Chip_DeviceController_SetLogFilter.restype = None - self._dmLib.nl_Chip_DeviceController_Connect.argtypes = [c_void_p, c_void_p, c_uint32, _OnConnectFunct, _OnMessageFunct, _OnRendezvousErrorFunct] + self._dmLib.nl_Chip_DeviceController_Connect.argtypes = [ + c_void_p, c_void_p, c_uint32, _OnConnectFunct, _OnMessageFunct, _OnRendezvousErrorFunct] self._dmLib.nl_Chip_DeviceController_Connect.restype = c_uint32 - self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate.argtypes = [POINTER(c_void_p)] + self._dmLib.nl_Chip_DeviceController_ConnectIP.argtypes = [ + c_void_p, c_char_p, c_uint32, _OnConnectFunct, _OnMessageFunct, _OnRendezvousErrorFunct] + self._dmLib.nl_Chip_DeviceController_ConnectIP.restype = c_uint32 + + self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate.argtypes = [ + POINTER(c_void_p)] self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate.restype = c_uint32 - self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential.argtypes = [c_void_p, c_char_p, c_char_p] + self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential.argtypes = [ + c_void_p, c_char_p, c_char_p] self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential.restype = c_uint32 - self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate.argtypes = [c_void_p, c_void_p] + self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate.argtypes = [ + c_void_p, c_void_p] self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate.restype = c_uint32 diff --git a/src/messaging/ExchangeMgr.cpp b/src/messaging/ExchangeMgr.cpp index 74f2f62519348c..6a6d16d133ffc9 100644 --- a/src/messaging/ExchangeMgr.cpp +++ b/src/messaging/ExchangeMgr.cpp @@ -62,7 +62,7 @@ ExchangeManager::ExchangeManager() mState = State::kState_NotInitialized; } -CHIP_ERROR ExchangeManager::Init(SecureSessionMgrBase * sessionMgr) +CHIP_ERROR ExchangeManager::Init(SecureSessionMgr * sessionMgr) { if (mState != State::kState_NotInitialized) return CHIP_ERROR_INCORRECT_STATE; @@ -140,7 +140,7 @@ CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandler(uint32_t protoco return UnregisterUMH(protocolId, static_cast(msgType)); } -void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgrBase * msgLayer) +void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * msgLayer) { ChipLogError(ExchangeManager, "Accept FAILED, err = %s", ErrorStr(error)); } @@ -299,7 +299,7 @@ CHIP_ERROR ExchangeManager::UnregisterUMH(uint32_t protocolId, int16_t msgType) void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, - SecureSessionMgrBase * msgLayer) + SecureSessionMgr * msgLayer) { DispatchMessage(packetHeader, payloadHeader, msgBuf); } diff --git a/src/messaging/ExchangeMgr.h b/src/messaging/ExchangeMgr.h index 214302b3f2ff7b..bab9a8f6fcd021 100644 --- a/src/messaging/ExchangeMgr.h +++ b/src/messaging/ExchangeMgr.h @@ -53,14 +53,14 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate * construction until a call to Shutdown is made to terminate the * instance. * - * @param[in] sessionMgr A pointer to the SecureSessionMgrBase object. + * @param[in] sessionMgr A pointer to the SecureSessionMgr object. * * @retval #CHIP_ERROR_INCORRECT_STATE If the state is not equal to * kState_NotInitialized. * @retval #CHIP_NO_ERROR On success. * */ - CHIP_ERROR Init(SecureSessionMgrBase * sessionMgr); + CHIP_ERROR Init(SecureSessionMgr * sessionMgr); /** * Shutdown the ExchangeManager. This terminates this instance @@ -163,7 +163,7 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate void IncrementContextsInUse(); void DecrementContextsInUse(); - SecureSessionMgrBase * GetSessionMgr() const { return mSessionMgr; } + SecureSessionMgr * GetSessionMgr() const { return mSessionMgr; } size_t GetContextsInUse() const { return mContextsInUse; } @@ -184,7 +184,7 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate uint16_t mNextExchangeId; State mState; - SecureSessionMgrBase * mSessionMgr; + SecureSessionMgr * mSessionMgr; ExchangeContext ContextPool[CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS]; size_t mContextsInUse; @@ -199,11 +199,11 @@ class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate CHIP_ERROR RegisterUMH(uint32_t protocolId, int16_t msgType, ExchangeContext::MessageReceiveFunct handler, void * appState); CHIP_ERROR UnregisterUMH(uint32_t protocolId, int16_t msgType); - void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgrBase * msgLayer) override; + void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * msgLayer) override; void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, - SecureSessionMgrBase * msgLayer) override; + SecureSessionMgr * msgLayer) override; }; } // namespace chip diff --git a/src/messaging/tests/TestExchangeMgr.cpp b/src/messaging/tests/TestExchangeMgr.cpp index eb522816dd7706..31829182638aa4 100644 --- a/src/messaging/tests/TestExchangeMgr.cpp +++ b/src/messaging/tests/TestExchangeMgr.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -77,12 +78,15 @@ void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - SecureSessionMgr conn; + TransportMgr tm; + SecureSessionMgr conn; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), "LOOPBACK"); + err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + tm.Init(&conn, nullptr, "LOOPBACK"); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; @@ -94,12 +98,14 @@ void CheckNewContextTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - SecureSessionMgr conn; + TransportMgr tm; + SecureSessionMgr conn; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), "LOOPBACK"); + err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + tm.Init(&conn, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; @@ -123,12 +129,15 @@ void CheckFindContextTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - SecureSessionMgr conn; + TransportMgr tm; + SecureSessionMgr conn; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), "LOOPBACK"); + err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = tm.Init(&conn, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; @@ -149,12 +158,15 @@ void CheckUmhRegistrationTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - SecureSessionMgr conn; + TransportMgr tm; + SecureSessionMgr conn; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), "LOOPBACK"); + err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = tm.Init(&conn, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; diff --git a/src/transport/BLE.cpp b/src/transport/BLE.cpp index 9b638c04b6a453..e297e3d6ab3ec5 100644 --- a/src/transport/BLE.cpp +++ b/src/transport/BLE.cpp @@ -192,11 +192,24 @@ void BLE::OnBleConnectionError(void * appState, BLE_ERROR err) void BLE::OnBleEndPointReceive(BLEEndPoint * endPoint, PacketBuffer * buffer) { - BLE * ble = reinterpret_cast(endPoint->mAppState); + BLE * ble = reinterpret_cast(endPoint->mAppState); + CHIP_ERROR err = CHIP_NO_ERROR; if (ble->mDelegate) { - ble->mDelegate->OnRendezvousMessageReceived(buffer); + uint16_t headerSize = 0; + + PacketHeader header; + err = header.Decode(buffer->Start(), buffer->DataLength(), &headerSize); + SuccessOrExit(err); + + buffer->ConsumeHead(headerSize); + ble->mDelegate->OnRendezvousMessageReceived(header, Transport::PeerAddress(Transport::Type::kBle), buffer); + } +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(Inet, "Failed to receive BLE message: %s", ErrorStr(err)); } } diff --git a/src/transport/BLE.h b/src/transport/BLE.h index 7b156adcf5c240..1b601bb5370b4b 100644 --- a/src/transport/BLE.h +++ b/src/transport/BLE.h @@ -39,6 +39,14 @@ namespace chip { namespace Transport { +class DLL_EXPORT BLEConnectionDelegate +{ +public: + virtual void OnBleEndPointReceive(Ble::BLEEndPoint * endPoint, System::PacketBuffer * buffer); + virtual void OnBleEndPointConnectionComplete(Ble::BLEEndPoint * endPoint, BLE_ERROR err); + virtual void OnBleEndPointConnectionClosed(Ble::BLEEndPoint * endPoint, BLE_ERROR err); +}; + /** Implements a transport using BLE. * * TODO: BLE transport currently does NOT receive messages as defined diff --git a/src/transport/BUILD.gn b/src/transport/BUILD.gn index f6e05ba87c764c..2439d50afe987e 100644 --- a/src/transport/BUILD.gn +++ b/src/transport/BUILD.gn @@ -33,6 +33,8 @@ static_library("transport") { "SecureSession.h", "SecureSessionMgr.cpp", "SecureSessionMgr.h", + "TransportMgr.cpp", + "TransportMgr.h", ] if (chip_config_network_layer_ble) { diff --git a/src/transport/RendezvousParameters.h b/src/transport/RendezvousParameters.h index d6174b875601e4..284c149b603e54 100644 --- a/src/transport/RendezvousParameters.h +++ b/src/transport/RendezvousParameters.h @@ -18,7 +18,7 @@ #pragma once #include - +#include #if CONFIG_NETWORK_LAYER_BLE #include #endif // CONFIG_NETWORK_LAYER_BLE @@ -45,6 +45,14 @@ class RendezvousParameters return *this; } + bool HasPeerAddress() const { return mPeerAddress.IsInitialized(); } + Transport::PeerAddress GetPeerAddress() const { return mPeerAddress; } + RendezvousParameters & SetPeerAddress(const Transport::PeerAddress & peerAddress) + { + mPeerAddress = peerAddress; + return *this; + } + bool HasDiscriminator() const { return mDiscriminator <= kMaxRendezvousDiscriminatorValue; } uint16_t GetDiscriminator() const { return mDiscriminator; } RendezvousParameters & SetDiscriminator(uint16_t discriminator) @@ -83,6 +91,7 @@ class RendezvousParameters private: Optional mLocalNodeId; ///< the local node id + Transport::PeerAddress mPeerAddress; ///< the peer node address uint32_t mSetupPINCode = 0; ///< the target peripheral setup PIN Code uint16_t mDiscriminator = UINT16_MAX; ///< the target peripheral discriminator diff --git a/src/transport/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp index 838d4d0c5603a9..4d4c147122fae6 100644 --- a/src/transport/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -23,6 +23,9 @@ #include #include #include +#include +#include +#include #if CONFIG_NETWORK_LAYER_BLE #include @@ -34,6 +37,7 @@ static const char * kSpake2pKeyExchangeSalt = "SPAKE2P Key Exchange Salt" using namespace chip::Inet; using namespace chip::System; +using namespace chip::Transport; namespace chip { @@ -46,13 +50,18 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params) VerifyOrExit(mParams.HasLocalNodeId(), err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT); - err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; + // TODO: BLE Should be a transport, in that case, RendezvousSession and BLE should decouple + if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle) #if CONFIG_NETWORK_LAYER_BLE { Transport::BLE * transport = chip::Platform::New(); err = transport->Init(this, mParams); mTransport = transport; } +#else + { + err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; + } #endif // CONFIG_NETWORK_LAYER_BLE SuccessOrExit(err); @@ -80,7 +89,7 @@ RendezvousSession::~RendezvousSession() } CHIP_ERROR RendezvousSession::SendPairingMessage(const PacketHeader & header, Header::Flags payloadFlags, - System::PacketBuffer * msgBuf) + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) { if (mCurrentState != State::kSecurePairing) { @@ -88,7 +97,7 @@ CHIP_ERROR RendezvousSession::SendPairingMessage(const PacketHeader & header, He return CHIP_ERROR_INCORRECT_STATE; } - return mTransport->SendMessage(header, payloadFlags, Transport::PeerAddress::BLE(), msgBuf); + return mTransport->SendMessage(header, payloadFlags, peerAddress, msgBuf); } CHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgBuf) @@ -216,6 +225,11 @@ void RendezvousSession::OnRendezvousError(CHIP_ERROR err) UpdateState(State::kInit); } +void RendezvousSession::SetTransportMgr(TransportMgrBase * transport) +{ + mTransportMgr = transport; +} + void RendezvousSession::UpdateState(RendezvousSession::State newState) { switch (mCurrentState) @@ -240,18 +254,20 @@ void RendezvousSession::UpdateState(RendezvousSession::State newState) } } -void RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf) +void RendezvousSession::OnRendezvousMessageReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + PacketBuffer * msgBuf) { CHIP_ERROR err = CHIP_NO_ERROR; + // TODO: RendezvousSession should handle SecurePairing messages only switch (mCurrentState) { case State::kSecurePairing: - err = HandlePairingMessage(msgBuf); + err = HandlePairingMessage(packetHeader, peerAddress, msgBuf); break; case State::kNetworkProvisioning: - err = HandleSecureMessage(msgBuf); + err = HandleSecureMessage(packetHeader, peerAddress, msgBuf); break; default: @@ -268,28 +284,16 @@ void RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf) } } -CHIP_ERROR RendezvousSession::HandlePairingMessage(PacketBuffer * msgBuf) +CHIP_ERROR RendezvousSession::HandlePairingMessage(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + PacketBuffer * msgBuf) { - CHIP_ERROR err = CHIP_NO_ERROR; - PacketHeader packetHeader; - uint16_t headerSize = 0; - - err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize); - SuccessOrExit(err); - - msgBuf->ConsumeHead(headerSize); - - err = mPairingSession.HandlePeerMessage(packetHeader, msgBuf); - SuccessOrExit(err); - -exit: - return err; + return mPairingSession.HandlePeerMessage(packetHeader, peerAddress, msgBuf); } -CHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf) +CHIP_ERROR RendezvousSession::HandleSecureMessage(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + PacketBuffer * msgBuf) { CHIP_ERROR err = CHIP_NO_ERROR; - PacketHeader packetHeader; PayloadHeader payloadHeader; MessageAuthenticationCode mac; uint16_t headerSize = 0; @@ -301,10 +305,6 @@ CHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf) uint16_t payloadlen = 0; System::PacketBuffer * origMsg = nullptr; - err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize); - SuccessOrExit(err); - msgBuf->ConsumeHead(headerSize); - headerSize = payloadHeader.EncodeSizeBytes(); data = msgBuf->Start(); len = msgBuf->TotalLength(); @@ -368,7 +368,7 @@ CHIP_ERROR RendezvousSession::WaitForPairing(Optional nodeId, uint32_t s CHIP_ERROR RendezvousSession::Pair(Optional nodeId, uint32_t setupPINCode) { UpdateState(State::kSecurePairing); - return mPairingSession.Pair(setupPINCode, kSpake2p_Iteration_Count, + return mPairingSession.Pair(mParams.GetPeerAddress(), setupPINCode, kSpake2p_Iteration_Count, reinterpret_cast(kSpake2pKeyExchangeSalt), strlen(kSpake2pKeyExchangeSalt), nodeId, mNextKeyId++, this); } diff --git a/src/transport/RendezvousSession.h b/src/transport/RendezvousSession.h index 3a0b71870cb570..fc3942011de91d 100644 --- a/src/transport/RendezvousSession.h +++ b/src/transport/RendezvousSession.h @@ -29,13 +29,17 @@ #include #include #include - +#include +#include namespace chip { namespace DeviceLayer { class CHIPDeviceEvent; } +class SecureSessionMgr; +class TransportMgrBase; + /** * RendezvousSession establishes and maintains the first connection between * a commissioner and a device. This connection is used in order to @@ -92,7 +96,8 @@ class RendezvousSession : public SecurePairingSessionDelegate, SecurePairingSession & GetPairingSession() { return mPairingSession; } //////////// SecurePairingSessionDelegate Implementation /////////////// - CHIP_ERROR SendPairingMessage(const PacketHeader & header, Header::Flags payloadFlags, System::PacketBuffer * msgBuf) override; + CHIP_ERROR SendPairingMessage(const PacketHeader & header, Header::Flags payloadFlags, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) override; void OnPairingError(CHIP_ERROR err) override; void OnPairingComplete() override; @@ -100,7 +105,10 @@ class RendezvousSession : public SecurePairingSessionDelegate, void OnRendezvousConnectionOpened() override; void OnRendezvousConnectionClosed() override; void OnRendezvousError(CHIP_ERROR err) override; - void OnRendezvousMessageReceived(System::/* */ PacketBuffer * buffer) override; + void OnRendezvousMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::/* */ PacketBuffer * buffer) override; + + void SetTransportMgr(TransportMgrBase * transport) override; //////////// RendezvousDeviceCredentialsDelegate Implementation /////////////// void SendNetworkCredentials(const char * ssid, const char * passwd) override; @@ -122,11 +130,13 @@ class RendezvousSession : public SecurePairingSessionDelegate, const Inet::IPAddress & GetIPAddress() const { return mNetworkProvision.GetIPAddress(); } private: - CHIP_ERROR HandlePairingMessage(System::PacketBuffer * msgBug); + CHIP_ERROR HandlePairingMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msgBug); CHIP_ERROR Pair(Optional nodeId, uint32_t setupPINCode); CHIP_ERROR WaitForPairing(Optional nodeId, uint32_t setupPINCode); - CHIP_ERROR HandleSecureMessage(System::PacketBuffer * msgBuf); + CHIP_ERROR HandleSecureMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msgBuf); Transport::Base * mTransport = nullptr; ///< Underlying transport RendezvousSessionDelegate * mDelegate = nullptr; ///< Underlying transport events RendezvousParameters mParams; ///< Rendezvous configuration @@ -134,6 +144,7 @@ class RendezvousSession : public SecurePairingSessionDelegate, SecurePairingSession mPairingSession; NetworkProvisioning mNetworkProvision; SecureSession mSecureSession; + TransportMgrBase * mTransportMgr; uint32_t mSecureMessageIndex = 0; uint16_t mNextKeyId = 0; diff --git a/src/transport/RendezvousSessionDelegate.h b/src/transport/RendezvousSessionDelegate.h index 90139bf2e6b9c2..b66fca64fec57f 100644 --- a/src/transport/RendezvousSessionDelegate.h +++ b/src/transport/RendezvousSessionDelegate.h @@ -19,8 +19,11 @@ #include #include +#include +#include namespace chip { +class TransportMgrBase; class RendezvousSessionDelegate { @@ -39,7 +42,10 @@ class RendezvousSessionDelegate virtual void OnRendezvousConnectionClosed() {} virtual void OnRendezvousError(CHIP_ERROR err) {} virtual void OnRendezvousComplete() {} - virtual void OnRendezvousMessageReceived(System::PacketBuffer * buffer){}; + virtual void OnRendezvousMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * buffer){}; + + virtual void SetTransportMgr(TransportMgrBase * transport) {} virtual void OnRendezvousStatusUpdate(Status status, CHIP_ERROR err) {} }; diff --git a/src/transport/SecurePairingSession.cpp b/src/transport/SecurePairingSession.cpp index 61335c1fb3a8f0..e10aecf76b76e2 100644 --- a/src/transport/SecurePairingSession.cpp +++ b/src/transport/SecurePairingSession.cpp @@ -183,6 +183,9 @@ CHIP_ERROR SecurePairingSession::AttachHeaderAndSend(uint8_t msgType, System::Pa uint16_t headerSize = payloadHeader.EncodeSizeBytes(); uint16_t actualEncodedHeaderSize = 0; + VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); + VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY); msgBuf->SetStart(msgBuf->Start() - headerSize); @@ -190,19 +193,14 @@ CHIP_ERROR SecurePairingSession::AttachHeaderAndSend(uint8_t msgType, System::Pa SuccessOrExit(err); VerifyOrExit(headerSize == actualEncodedHeaderSize, err = CHIP_ERROR_INTERNAL); - err = mDelegate->SendPairingMessage(PacketHeader().SetSourceNodeId(mLocalNodeId).SetEncryptionKeyID(mLocalKeyId), - payloadHeader.GetEncodePacketFlags(), msgBuf); - msgBuf = nullptr; - SuccessOrExit(err); - -exit: if (msgBuf) System::PacketBuffer::Free(msgBuf); return err; } -CHIP_ERROR SecurePairingSession::Pair(uint32_t peerSetUpPINCode, uint32_t pbkdf2IterCount, const uint8_t * salt, size_t saltLen, - Optional myNodeId, uint16_t myKeyId, SecurePairingSessionDelegate * delegate) +CHIP_ERROR SecurePairingSession::Pair(const Transport::PeerAddress peerAddress, uint32_t peerSetUpPINCode, uint32_t pbkdf2IterCount, + const uint8_t * salt, size_t saltLen, Optional myNodeId, uint16_t myKeyId, + SecurePairingSessionDelegate * delegate) { uint8_t X[kMAX_Point_Length]; size_t X_len = sizeof(X); @@ -213,6 +211,8 @@ CHIP_ERROR SecurePairingSession::Pair(uint32_t peerSetUpPINCode, uint32_t pbkdf2 CHIP_ERROR err = Init(peerSetUpPINCode, pbkdf2IterCount, salt, saltLen, myNodeId, myKeyId, delegate); SuccessOrExit(err); + mPeerAddress = peerAddress; + err = mSpake2p.BeginProver(reinterpret_cast(""), 0, reinterpret_cast(""), 0, &mWS[0][0], kSpake2p_WS_Length, &mWS[1][0], kSpake2p_WS_Length); SuccessOrExit(err); @@ -432,7 +432,8 @@ CHIP_ERROR SecurePairingSession::HandleCompute_cA(const PacketHeader & header, S return err; } -CHIP_ERROR SecurePairingSession::HandlePeerMessage(const PacketHeader & packetHeader, System::PacketBuffer * msg) +CHIP_ERROR SecurePairingSession::HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msg) { CHIP_ERROR err = CHIP_NO_ERROR; uint16_t headerSize = 0; @@ -448,6 +449,8 @@ CHIP_ERROR SecurePairingSession::HandlePeerMessage(const PacketHeader & packetHe VerifyOrExit(payloadHeader.GetProtocolID() == Protocols::kProtocol_SecurityChannel, err = CHIP_ERROR_INVALID_MESSAGE_TYPE); VerifyOrExit(payloadHeader.GetMessageType() == (uint8_t) mNextExpectedMsg, err = CHIP_ERROR_INVALID_MESSAGE_TYPE); + mPeerAddress = peerAddress; + switch (static_cast(payloadHeader.GetMessageType())) { case Spake2pMsgType::kSpake2pCompute_pA: diff --git a/src/transport/SecurePairingSession.h b/src/transport/SecurePairingSession.h index dfe3857c5d6863..d73abda72ad67c 100644 --- a/src/transport/SecurePairingSession.h +++ b/src/transport/SecurePairingSession.h @@ -30,6 +30,8 @@ #include #include #include +#include +#include namespace chip { @@ -47,10 +49,12 @@ class DLL_EXPORT SecurePairingSessionDelegate * * @param header the message header for the sent message * @param payloadFlags payload encoding flags + * @param peerAddress the destination of the message * @param msgBuf the raw data for the message being sent * @return CHIP_ERROR Error thrown when sending the message */ - virtual CHIP_ERROR SendPairingMessage(const PacketHeader & header, Header::Flags payloadFlags, System::PacketBuffer * msgBuf) + virtual CHIP_ERROR SendPairingMessage(const PacketHeader & header, Header::Flags payloadFlags, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) { return CHIP_ERROR_NOT_IMPLEMENTED; } @@ -106,6 +110,7 @@ class DLL_EXPORT SecurePairingSession * @brief * Create a pairing request using peer's setup PIN code. * + * @param peerAddress Address of peer to pair * @param peerSetUpPINCode Setup PIN code of the peer device * @param pbkdf2IterCount Iteration count for PBKDF2 function * @param salt Salt to be used for SPAKE2P opertation @@ -116,8 +121,9 @@ class DLL_EXPORT SecurePairingSession * * @return CHIP_ERROR The result of initialization */ - CHIP_ERROR Pair(uint32_t peerSetUpPINCode, uint32_t pbkdf2IterCount, const uint8_t * salt, size_t saltLen, - Optional myNodeId, uint16_t myKeyId, SecurePairingSessionDelegate * delegate); + CHIP_ERROR Pair(const Transport::PeerAddress peerAddress, uint32_t peerSetUpPINCode, uint32_t pbkdf2IterCount, + const uint8_t * salt, size_t saltLen, Optional myNodeId, uint16_t myKeyId, + SecurePairingSessionDelegate * delegate); /** * @brief @@ -137,10 +143,12 @@ class DLL_EXPORT SecurePairingSession * 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, System::PacketBuffer * msg); + virtual CHIP_ERROR HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msg); /** * @brief @@ -223,6 +231,8 @@ class DLL_EXPORT SecurePairingSession uint16_t mLocalKeyId; uint16_t mPeerKeyId; + + Transport::PeerAddress mPeerAddress; }; /* @@ -264,7 +274,11 @@ class SecurePairingUsingTestSecret : public SecurePairingSession 0, reinterpret_cast(secret), secretLen); } - CHIP_ERROR HandlePeerMessage(const PacketHeader & packetHeader, System::PacketBuffer * msg) override { return CHIP_NO_ERROR; } + CHIP_ERROR HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msg) override + { + return CHIP_NO_ERROR; + } }; typedef struct SecurePairingSessionSerializable diff --git a/src/transport/SecureSessionMgr.cpp b/src/transport/SecureSessionMgr.cpp index 4e41dc49620e26..9873f6a4da4956 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -33,7 +33,12 @@ #include #include #include +#include #include +#include +#include + +#include namespace chip { @@ -48,14 +53,14 @@ using Transport::PeerConnectionState; // TODO: this should be checked within the transport message sending instead of the session management layer. static const size_t kMax_SecureSDU_Length = 1024; -SecureSessionMgrBase::SecureSessionMgrBase() : mState(State::kNotReady) {} +SecureSessionMgr::SecureSessionMgr() : mState(State::kNotReady) {} -SecureSessionMgrBase::~SecureSessionMgrBase() +SecureSessionMgr::~SecureSessionMgr() { CancelExpiryTimer(); } -CHIP_ERROR SecureSessionMgrBase::InitInternal(NodeId localNodeId, System::Layer * systemLayer, Transport::Base * transport) +CHIP_ERROR SecureSessionMgr::Init(NodeId localNodeId, System::Layer * systemLayer) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mState == State::kNotReady, err = CHIP_ERROR_INCORRECT_STATE); @@ -63,9 +68,7 @@ CHIP_ERROR SecureSessionMgrBase::InitInternal(NodeId localNodeId, System::Layer mState = State::kInitialized; mLocalNodeId = localNodeId; mSystemLayer = systemLayer; - mTransport = transport; - mTransport->SetMessageReceiveHandler(HandleDataReceived, this); mPeerConnections.SetConnectionExpiredHandler(HandleConnectionExpired, this); Mdns::DiscoveryManager::GetInstance().Init(); @@ -77,14 +80,14 @@ CHIP_ERROR SecureSessionMgrBase::InitInternal(NodeId localNodeId, System::Layer return err; } -CHIP_ERROR SecureSessionMgrBase::SendMessage(NodeId peerNodeId, System::PacketBuffer * msgBuf) +CHIP_ERROR SecureSessionMgr::SendMessage(NodeId peerNodeId, System::PacketBuffer * msgBuf) { PayloadHeader payloadHeader; return SendMessage(payloadHeader, peerNodeId, msgBuf); } -CHIP_ERROR SecureSessionMgrBase::SendMessage(PayloadHeader & payloadHeader, NodeId peerNodeId, System::PacketBuffer * msgBuf) +CHIP_ERROR SecureSessionMgr::SendMessage(PayloadHeader & payloadHeader, NodeId peerNodeId, System::PacketBuffer * msgBuf) { CHIP_ERROR err = CHIP_NO_ERROR; PeerConnectionState * state = mPeerConnections.FindPeerConnectionState(peerNodeId, nullptr); @@ -123,6 +126,7 @@ CHIP_ERROR SecureSessionMgrBase::SendMessage(PayloadHeader & payloadHeader, Node .SetMessageId(state->GetSendMessageIndex()) // .SetEncryptionKeyID(state->GetLocalKeyID()) // .SetPayloadLength(static_cast(payloadLength)); + packetHeader.GetFlags().Set(Header::FlagValues::kSecure); VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY); @@ -144,7 +148,7 @@ CHIP_ERROR SecureSessionMgrBase::SendMessage(PayloadHeader & payloadHeader, Node ChipLogDetail(Inet, "Secure transport transmitting msg %u after encryption", state->GetSendMessageIndex()); - err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), state->GetPeerAddress(), msgBuf); + err = mTransportMgr->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), state->GetPeerAddress(), msgBuf); msgBuf = nullptr; } SuccessOrExit(err); @@ -169,7 +173,65 @@ CHIP_ERROR SecureSessionMgrBase::SendMessage(PayloadHeader & payloadHeader, Node return err; } -CHIP_ERROR SecureSessionMgrBase::NewPairing(const Optional & peerAddr, SecurePairingSession * pairing) +CHIP_ERROR SecureSessionMgr::SendUnsecureMessage(PacketHeader & packetBuffer, PayloadHeader & payloadHeader, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + VerifyOrExit(mState == State::kInitialized, err = CHIP_ERROR_INCORRECT_STATE); + + VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); + VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); + + { + uint8_t * data = nullptr; + PacketHeader packetHeader; + MessageAuthenticationCode mac; + + const uint16_t headerSize = payloadHeader.EncodeSizeBytes(); + uint16_t actualEncodedHeaderSize; + uint16_t totalLen = 0; + uint32_t payloadLength; // Make sure it's big enough to add two 16-bit + // ints without overflowing. + static_assert(std::is_sameTotalLength()), uint16_t>::value, + "Addition to generate payloadLength might overflow"); + payloadLength = static_cast(headerSize + msgBuf->TotalLength()); + VerifyOrExit(CanCastTo(payloadLength), err = CHIP_ERROR_NO_MEMORY); + + packetHeader + .SetSourceNodeId(mLocalNodeId) // + .SetPayloadLength(static_cast(payloadLength)); + packetHeader.GetFlags().Clear(Header::FlagValues::kSecure); + + VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY); + + msgBuf->SetStart(msgBuf->Start() - headerSize); + data = msgBuf->Start(); + totalLen = msgBuf->TotalLength(); + + err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize); + SuccessOrExit(err); + + ChipLogDetail(Inet, "Transmitting unsecured msg"); + + err = mTransportMgr->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), peerAddress, msgBuf); + msgBuf = nullptr; + } + SuccessOrExit(err); + +exit: + if (msgBuf != nullptr) + { + const char * errStr = ErrorStr(err); + ChipLogError(Inet, "Secure transport could not find a valid PeerConnection: %s", errStr); + PacketBuffer::Free(msgBuf); + msgBuf = nullptr; + } + + return err; +} + +CHIP_ERROR SecureSessionMgr::NewPairing(const Optional & peerAddr, SecurePairingSession * pairing) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -215,7 +277,7 @@ CHIP_ERROR SecureSessionMgrBase::NewPairing(const OptionalStartTimer(CHIP_PEER_CONNECTION_TIMEOUT_CHECK_FREQUENCY_MS, SecureSessionMgrBase::ExpiryTimerCallback, this); + mSystemLayer->StartTimer(CHIP_PEER_CONNECTION_TIMEOUT_CHECK_FREQUENCY_MS, SecureSessionMgr::ExpiryTimerCallback, this); VerifyOrDie(err == CHIP_NO_ERROR); } -void SecureSessionMgrBase::CancelExpiryTimer() +void SecureSessionMgr::CancelExpiryTimer() { if (mSystemLayer != nullptr) { - mSystemLayer->CancelTimer(SecureSessionMgrBase::ExpiryTimerCallback, this); + mSystemLayer->CancelTimer(SecureSessionMgr::ExpiryTimerCallback, this); } } -void SecureSessionMgrBase::HandleDataReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, - System::PacketBuffer * msg, SecureSessionMgrBase * connection) +void SecureSessionMgr::HandleSecureMessageReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + System::PacketBuffer * msg, SecureSessionMgr * connection) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -359,19 +421,19 @@ void SecureSessionMgrBase::HandleDataReceived(const PacketHeader & packetHeader, } } -void SecureSessionMgrBase::HandleConnectionExpired(const Transport::PeerConnectionState & state, SecureSessionMgrBase * mgr) +void SecureSessionMgr::HandleConnectionExpired(const Transport::PeerConnectionState & state, SecureSessionMgr * mgr) { char addr[Transport::PeerAddress::kMaxToStringSize]; state.GetPeerAddress().ToString(addr, sizeof(addr)); ChipLogDetail(Inet, "Connection from '%s' expired", addr); - mgr->mTransport->Disconnect(state.GetPeerAddress()); + mgr->mTransportMgr->Disconnect(state.GetPeerAddress()); } -void SecureSessionMgrBase::ExpiryTimerCallback(System::Layer * layer, void * param, System::Error error) +void SecureSessionMgr::ExpiryTimerCallback(System::Layer * layer, void * param, System::Error error) { - SecureSessionMgrBase * mgr = reinterpret_cast(param); + SecureSessionMgr * mgr = reinterpret_cast(param); #if CHIP_CONFIG_SESSION_REKEYING // TODO(#2279): session expiration is currently disabled until rekeying is supported // the #ifdef should be removed after that. diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index ac66baf2e4c06c..254f4b3485c8b3 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -41,12 +41,13 @@ namespace chip { -class SecureSessionMgrBase; +class SecureSessionMgr; +class TransportMgrBase; /** * @brief * This class provides a skeleton for the callback functions. The functions will be - * called by SecureSssionMgrBase object on specific events. If the user of SecureSessionMgrBase + * called by SecureSssionMgrBase object on specific events. If the user of SecureSessionMgr * is interested in receiving these callbacks, they can specialize this class and handle * each trigger in their implementation of this class. */ @@ -65,8 +66,7 @@ class DLL_EXPORT SecureSessionMgrDelegate * @param mgr A pointer to the SecureSessionMgr */ virtual void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, - Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, - SecureSessionMgrBase * mgr) + Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, SecureSessionMgr * mgr) {} /** @@ -77,7 +77,7 @@ class DLL_EXPORT SecureSessionMgrDelegate * @param source network entity that sent the message * @param mgr A pointer to the SecureSessionMgr */ - virtual void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgrBase * mgr) {} + virtual void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * mgr) {} /** * @brief @@ -86,7 +86,7 @@ class DLL_EXPORT SecureSessionMgrDelegate * @param state connection state * @param mgr A pointer to the SecureSessionMgr */ - virtual void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) {} + virtual void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) {} /** * @brief @@ -101,7 +101,7 @@ class DLL_EXPORT SecureSessionMgrDelegate virtual ~SecureSessionMgrDelegate() {} }; -class DLL_EXPORT SecureSessionMgrBase : public Mdns::ResolveDelegate +class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate { public: /** @@ -114,8 +114,21 @@ class DLL_EXPORT SecureSessionMgrBase : public Mdns::ResolveDelegate */ CHIP_ERROR SendMessage(NodeId peerNodeId, System::PacketBuffer * msgBuf); CHIP_ERROR SendMessage(PayloadHeader & payloadHeader, NodeId peerNodeId, System::PacketBuffer * msgBuf); - SecureSessionMgrBase(); - ~SecureSessionMgrBase() override; + SecureSessionMgr(); + ~SecureSessionMgr() override; + + /** + * @brief + * Send a unsecured message to peerAddress + * @details + * This function will fill packet header. and send it to + * transport layer on behalf of the caller. + * All unsecure messages are stateless for SecureSessionMgr. + * This method calls chip::System::PacketBuffer::Free + * on behalf of the caller regardless of the return status. + */ + CHIP_ERROR SendUnsecureMessage(PacketHeader & packetHeader, PayloadHeader & payloadHeader, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf); /** * @brief @@ -126,6 +139,12 @@ class DLL_EXPORT SecureSessionMgrBase : public Mdns::ResolveDelegate */ void SetDelegate(SecureSessionMgrDelegate * cb) { mCB = cb; } + /** + * @brief + * Set the handler for unsecured messages. + */ + void SetTransportMgr(TransportMgrBase * cb) { mTransportMgr = cb; } + /** * @brief * Establish a new pairing with a peer node @@ -143,18 +162,17 @@ class DLL_EXPORT SecureSessionMgrBase : public Mdns::ResolveDelegate */ System::Layer * SystemLayer() { return mSystemLayer; } -protected: /** * @brief * Initialize a Secure Session Manager * * @param localNodeId Node id for the current node * @param systemLayer System, layer to use - * @param transport Underlying Transport to use */ - CHIP_ERROR InitInternal(NodeId localNodeId, System::Layer * systemLayer, Transport::Base * transport); + CHIP_ERROR Init(NodeId localNodeId, System::Layer * systemLayer); private: + friend class TransportMgrBase; /** * The State of a secure transport object. */ @@ -164,13 +182,13 @@ class DLL_EXPORT SecureSessionMgrBase : public Mdns::ResolveDelegate kInitialized, /**< State when the object is ready connect to other peers. */ }; - Transport::Base * mTransport = nullptr; System::Layer * mSystemLayer = nullptr; NodeId mLocalNodeId; // < Id of the current node Transport::PeerConnections mPeerConnections; // < Active connections to other peers State mState; // < Initialization state of the object - SecureSessionMgrDelegate * mCB = nullptr; + SecureSessionMgrDelegate * mCB = nullptr; + TransportMgrBase * mTransportMgr = nullptr; /** Schedules a new oneshot timer for checking connection expiry. */ void ScheduleExpiryTimer(); @@ -178,13 +196,13 @@ class DLL_EXPORT SecureSessionMgrBase : public Mdns::ResolveDelegate /** Cancels any active timers for connection expiry checks. */ void CancelExpiryTimer(); - static void HandleDataReceived(const PacketHeader & header, const Transport::PeerAddress & source, - System::PacketBuffer * msgBuf, SecureSessionMgrBase * transport); + static void HandleSecureMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, + System::PacketBuffer * msgBuf, SecureSessionMgr * transport); /** * Called when a specific connection expires. */ - static void HandleConnectionExpired(const Transport::PeerConnectionState & state, SecureSessionMgrBase * mgr); + static void HandleConnectionExpired(const Transport::PeerConnectionState & state, SecureSessionMgr * mgr); /** * Callback for timer expiry check @@ -194,38 +212,4 @@ class DLL_EXPORT SecureSessionMgrBase : public Mdns::ResolveDelegate void HandleNodeIdResolve(CHIP_ERROR error, NodeId nodeId, const Mdns::MdnsService & service) override; }; -/** - * A secure session manager that includes required underlying transports. - */ -template -class SecureSessionMgr : public SecureSessionMgrBase -{ -public: - /** - * @brief - * Initialize a Secure Session Manager - * - * @param localNodeId Node id for the current node - * @param systemLayer System, layer to use - * @param transportInitArgs Arguments to initialize the underlying transport - */ - template - CHIP_ERROR Init(NodeId localNodeId, System::Layer * systemLayer, Args &&... transportInitArgs) - { - CHIP_ERROR err = CHIP_NO_ERROR; - - err = mTransport.Init(std::forward(transportInitArgs)...); - SuccessOrExit(err); - - err = InitInternal(localNodeId, systemLayer, &mTransport); - SuccessOrExit(err); - - exit: - return err; - } - -private: - Transport::Tuple mTransport; -}; - } // namespace chip diff --git a/src/transport/TransportMgr.cpp b/src/transport/TransportMgr.cpp new file mode 100644 index 00000000000000..69274ae68bd105 --- /dev/null +++ b/src/transport/TransportMgr.cpp @@ -0,0 +1,57 @@ +/* + * + * Copyright (c) 2020 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 + */ + +/** + * @file + * This file implements a stateless TransportMgr, it will took a raw message + * buffer from transports, and then extract the message header without decode it. + * For secure messages, it will pass it to the SecureSessionMgr, and for unsecure + * messages (rendezvous messages), it will pass it to RendezvousSession. + * When sending messages, it will encode the packet header, and pass it to the + * transports. + * The whole process is fully stateless. + */ + +#include + +#include +#include +#include +#include +#include + +namespace chip { + +void TransportMgrBase::HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msg, TransportMgrBase * dispatcher) +{ + if (packetHeader.GetFlags().Has(Header::FlagValues::kSecure)) + { + if (dispatcher->mSecureSessionMgr != nullptr) + { + SecureSessionMgr::HandleSecureMessageReceived(packetHeader, peerAddress, msg, dispatcher->mSecureSessionMgr); + } + } + else + { + if (dispatcher->mRendezvous != nullptr) + { + dispatcher->mRendezvous->OnRendezvousMessageReceived(packetHeader, peerAddress, msg); + // Unsecure message received, pass it to Rendezvous Session Mgr directly. + } + } +} +} // namespace chip diff --git a/src/transport/TransportMgr.h b/src/transport/TransportMgr.h new file mode 100644 index 00000000000000..2bd99462e816c4 --- /dev/null +++ b/src/transport/TransportMgr.h @@ -0,0 +1,115 @@ +/* + * + * Copyright (c) 2020 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 + */ + +/** + * @file + * This file implements a stateless TransportMgr, it will took a raw message + * buffer from transports, and then extract the message header without decode it. + * For secure messages, it will pass it to the SecureSessionMgr, and for unsecure + * messages (rendezvous messages), it will pass it to RendezvousSession. + * When sending messages, it will encode the packet header, and pass it to the + * transports. + * The whole process is fully stateless. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace chip { + +class TransportMgrBase +{ +public: + CHIP_ERROR SendMessage(const PacketHeader & header, Header::Flags payloadFlags, const Transport::PeerAddress & address, + System::PacketBuffer * msgBuf) + { + return mTransport->SendMessage(header, payloadFlags, address, msgBuf); + } + + void Disconnect(const Transport::PeerAddress & address) { mTransport->Disconnect(address); } + + void SetSecureSessionMgr(SecureSessionMgr * secureSessionMgr) + { + mSecureSessionMgr = secureSessionMgr; + if (secureSessionMgr != nullptr) + { + mSecureSessionMgr->SetTransportMgr(this); + } + } + + void SetRendezvousSession(RendezvousSession * rendezvous) + { + mRendezvous = rendezvous; + if (mRendezvous != nullptr) + { + mRendezvous->SetTransportMgr(this); + } + } + +protected: + void InitInternal(SecureSessionMgr * secureMgr, RendezvousSession * rendezvous, Transport::Base * transport) + { + mSecureSessionMgr = secureMgr; + mRendezvous = rendezvous; + mTransport = transport; + if (mSecureSessionMgr != nullptr) + { + mSecureSessionMgr->SetTransportMgr(this); + } + if (mRendezvous != nullptr) + { + mRendezvous->SetTransportMgr(this); + } + mTransport->SetMessageReceiveHandler(HandleMessageReceived, this); + ChipLogDetail(Inet, "TransportMgr initialized"); + } + +private: + static void HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msg, TransportMgrBase * dispatcher); + + SecureSessionMgr * mSecureSessionMgr = nullptr; + RendezvousSession * mRendezvous = nullptr; + Transport::Base * mTransport = nullptr; +}; + +template +class TransportMgr : public TransportMgrBase +{ +public: + template + CHIP_ERROR Init(SecureSessionMgr * secureMgr, RendezvousSession * rendezvous, Args &&... transportInitArgs) + { + CHIP_ERROR err = CHIP_NO_ERROR; + + err = mTransport.Init(std::forward(transportInitArgs)...); + SuccessOrExit(err); + InitInternal(secureMgr, rendezvous, &mTransport); + exit: + return err; + } + +private: + Transport::Tuple mTransport; +}; + +} // namespace chip diff --git a/src/transport/raw/MessageHeader.h b/src/transport/raw/MessageHeader.h index 13d1987317d65c..6dcb8535013e24 100644 --- a/src/transport/raw/MessageHeader.h +++ b/src/transport/raw/MessageHeader.h @@ -74,6 +74,9 @@ enum class FlagValues : uint16_t /// Header flag specifying that it is a control message for secure session. kSecureSessionControlMessage = 0x0800, + /// Header flag specifying that it is a encrypted message. + kSecure = 0x0001, + }; using Flags = BitFlags; @@ -83,7 +86,7 @@ using ExFlags = BitFlags; // | 4 bit | 4 bit | 4 bit | 4 bit | // +---------+-------+---------+----------| // | version | Flags | encType | reserved | -static constexpr uint16_t kFlagsMask = 0x0F00; +static constexpr uint16_t kFlagsMask = 0x0F01; } // namespace Header diff --git a/src/transport/tests/TestSecurePairingSession.cpp b/src/transport/tests/TestSecurePairingSession.cpp index d50df175f8e164..f123cdf1d4bd4b 100644 --- a/src/transport/tests/TestSecurePairingSession.cpp +++ b/src/transport/tests/TestSecurePairingSession.cpp @@ -39,7 +39,8 @@ using namespace chip; class TestSecurePairingDelegate : public SecurePairingSessionDelegate { public: - CHIP_ERROR SendPairingMessage(const PacketHeader & header, Header::Flags payloadFlags, System::PacketBuffer * msgBuf) override + CHIP_ERROR SendPairingMessage(const PacketHeader & header, Header::Flags payloadFlags, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) override { mNumMessageSend++; return (peer != nullptr) ? peer->HandlePeerMessage(header, msgBuf) : mMessageSendError; @@ -81,12 +82,14 @@ void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) SecurePairingSession pairing; NL_TEST_ASSERT(inSuite, - pairing.Pair(1234, 500, nullptr, 0, Optional::Value(1), 0, &delegate) == CHIP_ERROR_INVALID_ARGUMENT); + pairing.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 500, nullptr, 0, Optional::Value(1), 0, + &delegate) == CHIP_ERROR_INVALID_ARGUMENT); NL_TEST_ASSERT(inSuite, - pairing.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional::Value(1), 0, nullptr) == - CHIP_ERROR_INVALID_ARGUMENT); + pairing.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 500, (const uint8_t *) "salt", 4, + Optional::Value(1), 0, nullptr) == CHIP_ERROR_INVALID_ARGUMENT); NL_TEST_ASSERT(inSuite, - pairing.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional::Value(1), 0, &delegate) == CHIP_NO_ERROR); + pairing.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 500, (const uint8_t *) "salt", 4, + Optional::Value(1), 0, &delegate) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, delegate.mNumMessageSend == 1); @@ -95,8 +98,8 @@ void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) SecurePairingSession pairing1; NL_TEST_ASSERT(inSuite, - pairing1.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional::Value(1), 0, &delegate) == - CHIP_ERROR_BAD_REQUEST); + pairing1.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 500, (const uint8_t *) "salt", 4, + Optional::Value(1), 0, &delegate) == CHIP_ERROR_BAD_REQUEST); } void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, SecurePairingSession & pairingCommissioner, @@ -113,8 +116,8 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S pairingAccessory.WaitForPairing(1234, 500, (const uint8_t *) "salt", 4, Optional::Value(1), 0, &delegateAccessory) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - pairingCommissioner.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional::Value(2), 0, - &delegateCommissioner) == CHIP_NO_ERROR); + pairingCommissioner.Pair(Transport::PeerAddress(Transport::Type::kBle), 1234, 500, (const uint8_t *) "salt", 4, + Optional::Value(2), 0, &delegateCommissioner) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, delegateAccessory.mNumMessageSend == 1); NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); diff --git a/src/transport/tests/TestSecureSessionMgr.cpp b/src/transport/tests/TestSecureSessionMgr.cpp index dace12d5186ae2..fc135e4cf6edba 100644 --- a/src/transport/tests/TestSecureSessionMgr.cpp +++ b/src/transport/tests/TestSecureSessionMgr.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -67,7 +68,7 @@ class TestSessMgrCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, PeerConnectionState * state, - System::PacketBuffer * msgBuf, SecureSessionMgrBase * mgr) override + System::PacketBuffer * msgBuf, SecureSessionMgr * mgr) override { NL_TEST_ASSERT(mSuite, header.GetSourceNodeId() == Optional::Value(kSourceNodeId)); NL_TEST_ASSERT(mSuite, header.GetDestinationNodeId() == Optional::Value(kDestinationNodeId)); @@ -81,7 +82,7 @@ class TestSessMgrCallback : public SecureSessionMgrDelegate ReceiveHandlerCallCount++; } - void OnNewConnection(PeerConnectionState * state, SecureSessionMgrBase * mgr) override { NewConnectionHandlerCallCount++; } + void OnNewConnection(PeerConnectionState * state, SecureSessionMgr * mgr) override { NewConnectionHandlerCallCount++; } nlTestSuite * mSuite = nullptr; int ReceiveHandlerCallCount = 0; @@ -94,12 +95,15 @@ void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - SecureSessionMgr conn; + TransportMgr tm; + SecureSessionMgr conn; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), "LOOPBACK"); + err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = tm.Init(&conn, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } @@ -121,9 +125,12 @@ void CheckMessageTest(nlTestSuite * inSuite, void * inContext) IPAddress::FromString("127.0.0.1", addr); CHIP_ERROR err = CHIP_NO_ERROR; - SecureSessionMgr conn; + TransportMgr tm; + SecureSessionMgr conn; - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), "LOOPBACK"); + err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = tm.Init(&conn, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); callback.mSuite = inSuite; From 0af05d0805bfbd0f3c3272ff68fe2acb0a7759c8 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 11 Nov 2020 14:32:01 +0800 Subject: [PATCH 02/17] Revert python device ctrl change --- .../ChipDeviceController-ScriptBinding.cpp | 27 ----- src/controller/python/chip-device-ctrl.py | 11 +- src/controller/python/chip/ChipDeviceCtrl.py | 107 +++++------------- 3 files changed, 35 insertions(+), 110 deletions(-) diff --git a/src/controller/python/ChipDeviceController-ScriptBinding.cpp b/src/controller/python/ChipDeviceController-ScriptBinding.cpp index e6b80d1617ce91..18f6c0268510ae 100644 --- a/src/controller/python/ChipDeviceController-ScriptBinding.cpp +++ b/src/controller/python/ChipDeviceController-ScriptBinding.cpp @@ -46,16 +46,12 @@ #include "ChipDeviceController-ScriptDevicePairingDelegate.h" #include -#include #include #include #include #include -#include -using namespace chip; using namespace chip::Ble; -using namespace chip::Inet; using namespace chip::DeviceController; extern "C" { @@ -174,9 +170,6 @@ CHIP_ERROR nl_Chip_DeviceController_DeleteDeviceController(chip::DeviceControlle CHIP_ERROR nl_Chip_DeviceController_Connect(chip::DeviceController::ChipDeviceController * devCtrl, BLE_CONNECTION_OBJECT connObj, uint32_t setupPinCode, OnConnectFunct onConnect, OnMessageFunct onMessage, OnErrorFunct onError); -CHIP_ERROR nl_Chip_DeviceController_ConnectIP(chip::DeviceController::ChipDeviceController * devCtrl, const char * peerIP, - uint32_t setupPINCode, OnConnectFunct onConnect, OnMessageFunct onMessage, - OnErrorFunct onError); // Network Provisioning CHIP_ERROR @@ -556,26 +549,6 @@ CHIP_ERROR nl_Chip_DeviceController_Connect(chip::DeviceController::ChipDeviceCo return err; } -CHIP_ERROR nl_Chip_DeviceController_ConnectIP(chip::DeviceController::ChipDeviceController * devCtrl, const char * peerIP, - uint32_t setupPINCode, OnConnectFunct onConnect, OnMessageFunct onMessage, - OnErrorFunct onError) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - IPAddress addr; - - chip::RendezvousParameters params = chip::RendezvousParameters().SetSetupPINCode(setupPINCode); - - VerifyOrExit(IPAddress::FromString(peerIP, addr), err = CHIP_ERROR_INVALID_ADDRESS); - - params.SetPeerAddress(Transport::PeerAddress(addr, Transport::Type::kUdp)); - - err = devCtrl->ConnectDevice(kRemoteDeviceId, params, (void *) devCtrl, onConnect, onMessage, onError); - SuccessOrExit(err); - -exit: - return err; -} - CHIP_ERROR nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate(chip::DeviceController::ScriptDevicePairingDelegate ** pairingDelegate) { diff --git a/src/controller/python/chip-device-ctrl.py b/src/controller/python/chip-device-ctrl.py index 29b3b7cd27fe81..6b07db4c43c10d 100755 --- a/src/controller/python/chip-device-ctrl.py +++ b/src/controller/python/chip-device-ctrl.py @@ -365,7 +365,7 @@ def do_btpconnect(self, line): def do_connect(self, line): """ - connect [-ip [ipaddress]]|[-ble] + connect (via BLE) connect command is used for establishing a rendezvous session to the device. currently, only connect using setupPinCode is supported. @@ -380,13 +380,10 @@ def do_connect(self, line): print("Usage:") self.do_help("connect SetupPinCode") return - if args[0] == "-ip" and len(args) <= 3: - self.devCtrl.ConnectIP(args[1], int(args[2])) - elif args[0] == "-ble" and len(args) <= 2: - self.devCtrl.Connect(FAKE_CONN_OBJ_VALUE, int(args[1])) - else: - print("Unexpected argument(s): " + args) + if len(args) > 1: + print("Unexpected argument: " + args[1]) return + self.devCtrl.Connect(FAKE_CONN_OBJ_VALUE, int(args[0])) except ChipStack.ChipStackException as ex: print(str(ex)) return diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index 47c392c28e133d..7d1f6f882d923a 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -38,8 +38,7 @@ _CompleteFunct = CFUNCTYPE(None, c_void_p, c_void_p) -_ErrorFunct = CFUNCTYPE(None, c_void_p, c_void_p, - c_ulong, POINTER(DeviceStatusStruct)) +_ErrorFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_ulong, POINTER(DeviceStatusStruct)) _GetBleEventFunct = CFUNCTYPE(c_void_p) _WriteBleCharacteristicFunct = CFUNCTYPE( c_bool, c_void_p, c_void_p, c_void_p, c_void_p, c_uint16 @@ -56,14 +55,11 @@ # typedef void (*OnMessageFunct)(Chip::DeviceController::ChipDeviceController * dc, void * appReqState, PacketBuffer * buffer); _OnConnectFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p) -_OnRendezvousErrorFunct = CFUNCTYPE( - None, c_void_p, c_void_p, c_uint32, c_void_p) +_OnRendezvousErrorFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_uint32, c_void_p) _OnMessageFunct = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p) # This is a fix for WEAV-429. Jay Logue recommends revisiting this at a later # date to allow for truely multiple instances so this is temporary. - - def _singleton(cls): instance = [None] @@ -82,7 +78,6 @@ class DCState(enum.IntEnum): RENDEZVOUS_ONGOING = 3 RENDEZVOUS_CONNECTED = 4 - @_singleton class ChipDeviceController(object): def __init__(self, startNetworkThread=True): @@ -96,19 +91,16 @@ def __init__(self, startNetworkThread=True): self._InitLib() devCtrl = c_void_p(None) - res = self._dmLib.nl_Chip_DeviceController_NewDeviceController( - pointer(devCtrl)) + res = self._dmLib.nl_Chip_DeviceController_NewDeviceController(pointer(devCtrl)) if res != 0: raise self._ChipStack.ErrorToException(res) - + pairingDelegate = c_void_p(None) - res = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate( - pointer(pairingDelegate)) + res = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate(pointer(pairingDelegate)) if res != 0: raise self._ChipStack.ErrorToException(res) - - res = self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate( - devCtrl, pairingDelegate) + + res = self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate(devCtrl, pairingDelegate) if res != 0: raise self._ChipStack.ErrorToException(res) @@ -116,11 +108,9 @@ def __init__(self, startNetworkThread=True): self.pairingDelegate = pairingDelegate self._ChipStack.devCtrl = devCtrl - # set by other modules(BLE) that require service by thread while thread blocks. - self.blockingCB = None + self.blockingCB = None # set by other modules(BLE) that require service by thread while thread blocks. self.cbHandleBleEvent = ( - # set by other modules (BLE) that provide event callback to Chip. - None + None # set by other modules (BLE) that provide event callback to Chip. ) self.cbHandleBleWriteChar = None self.cbHandleBleSubscribeChar = None @@ -128,9 +118,9 @@ def __init__(self, startNetworkThread=True): def DeviceCtrlHandleMessage(appReqState, buffer): pass - + self.cbHandleMessage = _OnMessageFunct(DeviceCtrlHandleMessage) - + def HandleRendezvousError(appState, reqState, err, devStatusPtr): if self.state == DCState.RENDEZVOUS_ONGOING: print("Failed to connect to device: {}".format(err)) @@ -138,9 +128,8 @@ def HandleRendezvousError(appState, reqState, err, devStatusPtr): self._ChipStack.completeEvent.set() elif self.state == DCState.RENDEZVOUS_CONNECTED: print("Disconnected from device") - - self.cbHandleRendezvousError = _OnRendezvousErrorFunct( - HandleRendezvousError) + + self.cbHandleRendezvousError = _OnRendezvousErrorFunct(HandleRendezvousError) if startNetworkThread: self.StartNetworkThread() @@ -148,8 +137,7 @@ def HandleRendezvousError(appState, reqState, err, devStatusPtr): def __del__(self): if self.devCtrl != None: - self._dmLib.nl_Chip_DeviceController_DeleteDeviceManager( - self.devCtrl) + self._dmLib.nl_Chip_DeviceController_DeleteDeviceManager(self.devCtrl) self.devCtrl = None def DriveBleIO(self): @@ -161,13 +149,11 @@ def DriveBleIO(self): def SetBleEventCB(self, bleEventCB): if self.devCtrl != None: self.cbHandleBleEvent = _GetBleEventFunct(bleEventCB) - self._dmLib.nl_Chip_DeviceController_SetBleEventCB( - self.cbHandleBleEvent) + self._dmLib.nl_Chip_DeviceController_SetBleEventCB(self.cbHandleBleEvent) def SetBleWriteCharCB(self, bleWriteCharCB): if self.devCtrl != None: - self.cbHandleBleWriteChar = _WriteBleCharacteristicFunct( - bleWriteCharCB) + self.cbHandleBleWriteChar = _WriteBleCharacteristicFunct(bleWriteCharCB) self._dmLib.nl_Chip_DeviceController_SetBleWriteCharacteristic( self.cbHandleBleWriteChar ) @@ -184,8 +170,7 @@ def SetBleSubscribeCharCB(self, bleSubscribeCharCB): def SetBleCloseCB(self, bleCloseCB): if self.devCtrl != None: self.cbHandleBleClose = _CloseBleFunct(bleCloseCB) - self._dmLib.nl_Chip_DeviceController_SetBleClose( - self.cbHandleBleClose) + self._dmLib.nl_Chip_DeviceController_SetBleClose(self.cbHandleBleClose) def StartNetworkThread(self): if self.networkThread != None: @@ -198,16 +183,14 @@ def RunNetworkThread(): self._ChipStack.networkLock.release() time.sleep(0.005) - self.networkThread = Thread( - target=RunNetworkThread, name="ChipNetworkThread") + self.networkThread = Thread(target=RunNetworkThread, name="ChipNetworkThread") self.networkThread.daemon = True self.networkThreadRunable = True self.networkThread.start() def IsConnected(self): return self._ChipStack.Call( - lambda: self._dmLib.nl_Chip_DeviceController_IsConnected( - self.devCtrl) + lambda: self._dmLib.nl_Chip_DeviceController_IsConnected(self.devCtrl) ) def ConnectBle(self, bleConnection): @@ -219,35 +202,19 @@ def ConnectBle(self, bleConnection): self._ChipStack.cbHandleError, ) ) - + def Connect(self, connObj, setupPinCode): def HandleComplete(dc, connState, appState): print("Rendezvoud Complete") self.state = DCState.RENDEZVOUS_CONNECTED self._ChipStack.callbackRes = True self._ChipStack.completeEvent.set() - - onConnectFunct = _OnConnectFunct(HandleComplete) - - self.state = DCState.RENDEZVOUS_ONGOING - return self._ChipStack.CallAsync( - lambda: self._dmLib.nl_Chip_DeviceController_Connect( - self.devCtrl, connObj, setupPinCode, onConnectFunct, self.cbHandleMessage, self.cbHandleRendezvousError) - ) - - def ConnectIP(self, ip, setupPinCode): - def HandleComplete(dc, connState, appState): - print("Rendezvoud Complete") - self.state = DCState.RENDEZVOUS_CONNECTED - self._ChipStack.callbackRes = True - self._ChipStack.completeEvent.set() - + onConnectFunct = _OnConnectFunct(HandleComplete) self.state = DCState.RENDEZVOUS_ONGOING return self._ChipStack.CallAsync( - lambda: self._dmLib.nl_Chip_DeviceController_ConnectIP( - self.devCtrl, ip.encode("utf-8"), setupPinCode, onConnectFunct, self.cbHandleMessage, self.cbHandleRendezvousError) + lambda: self._dmLib.nl_Chip_DeviceController_Connect(self.devCtrl, connObj, setupPinCode, onConnectFunct, self.cbHandleMessage, self.cbHandleRendezvousError) ) def Close(self): @@ -270,10 +237,9 @@ def GetLogFilter(self): def SetBlockingCB(self, blockingCB): self._ChipStack.blockingCB = blockingCB - + def SetWifiCredential(self, ssid, password): - ret = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential( - self.pairingDelegate, ssid.encode("utf-8"), password.encode("utf-8")) + ret = self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential(self.pairingDelegate, ssid.encode("utf-8"), password.encode("utf-8")) if ret != 0: raise self._ChipStack.ErrorToException(res) @@ -322,12 +288,10 @@ def _InitLib(self): c_uint32 ) - self._dmLib.nl_Chip_DeviceController_SetBleClose.argtypes = [ - _CloseBleFunct] + self._dmLib.nl_Chip_DeviceController_SetBleClose.argtypes = [_CloseBleFunct] self._dmLib.nl_Chip_DeviceController_SetBleClose.restype = c_uint32 - self._dmLib.nl_Chip_DeviceController_IsConnected.argtypes = [ - c_void_p] + self._dmLib.nl_Chip_DeviceController_IsConnected.argtypes = [c_void_p] self._dmLib.nl_Chip_DeviceController_IsConnected.restype = c_bool self._dmLib.nl_Chip_DeviceController_ValidateBTP.argtypes = [ @@ -341,26 +305,17 @@ def _InitLib(self): self._dmLib.nl_Chip_DeviceController_GetLogFilter.argtypes = [] self._dmLib.nl_Chip_DeviceController_GetLogFilter.restype = c_uint8 - self._dmLib.nl_Chip_DeviceController_SetLogFilter.argtypes = [ - c_uint8] + self._dmLib.nl_Chip_DeviceController_SetLogFilter.argtypes = [c_uint8] self._dmLib.nl_Chip_DeviceController_SetLogFilter.restype = None - self._dmLib.nl_Chip_DeviceController_Connect.argtypes = [ - c_void_p, c_void_p, c_uint32, _OnConnectFunct, _OnMessageFunct, _OnRendezvousErrorFunct] + self._dmLib.nl_Chip_DeviceController_Connect.argtypes = [c_void_p, c_void_p, c_uint32, _OnConnectFunct, _OnMessageFunct, _OnRendezvousErrorFunct] self._dmLib.nl_Chip_DeviceController_Connect.restype = c_uint32 - self._dmLib.nl_Chip_DeviceController_ConnectIP.argtypes = [ - c_void_p, c_char_p, c_uint32, _OnConnectFunct, _OnMessageFunct, _OnRendezvousErrorFunct] - self._dmLib.nl_Chip_DeviceController_ConnectIP.restype = c_uint32 - - self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate.argtypes = [ - POINTER(c_void_p)] + self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate.argtypes = [POINTER(c_void_p)] self._dmLib.nl_Chip_ScriptDevicePairingDelegate_NewPairingDelegate.restype = c_uint32 - self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential.argtypes = [ - c_void_p, c_char_p, c_char_p] + self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential.argtypes = [c_void_p, c_char_p, c_char_p] self._dmLib.nl_Chip_ScriptDevicePairingDelegate_SetWifiCredential.restype = c_uint32 - self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate.argtypes = [ - c_void_p, c_void_p] + self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate.argtypes = [c_void_p, c_void_p] self._dmLib.nl_Chip_DeviceController_SetDevicePairingDelegate.restype = c_uint32 From ca625dfc550e20fac5cf7249a8f5dbbb26dc33a0 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 11 Nov 2020 16:16:53 +0800 Subject: [PATCH 03/17] Change after merge --- src/controller/CHIPDevice.cpp | 4 +- src/controller/CHIPDevice.h | 18 ++++-- src/controller/CHIPDeviceController.cpp | 21 ++++--- src/controller/CHIPDeviceController.h | 8 ++- src/transport/SecurePairingSession.cpp | 6 ++ src/transport/SecurePairingSession.h | 6 +- src/transport/SecureSessionMgr.cpp | 58 ------------------- src/transport/SecureSessionMgr.h | 15 +---- .../tests/TestSecurePairingSession.cpp | 2 +- 9 files changed, 44 insertions(+), 94 deletions(-) diff --git a/src/controller/CHIPDevice.cpp b/src/controller/CHIPDevice.cpp index 68048e7d97c1ba..ecdbe525bdfb9c 100644 --- a/src/controller/CHIPDevice.cpp +++ b/src/controller/CHIPDevice.cpp @@ -165,7 +165,7 @@ CHIP_ERROR Device::Deserialize(const SerializedDevice & input) } void Device::OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, - Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, SecureSessionMgrBase * mgr) + Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, SecureSessionMgr * mgr) { if (mState == ConnectionState::SecureConnected && mStatusDelegate != nullptr) { @@ -186,7 +186,7 @@ CHIP_ERROR Device::LoadSecureSessionParameters() err = pairingSession.FromSerializable(mPairing); SuccessOrExit(err); - err = mSessionManager->ResetTransport(Transport::UdpListenParameters(mInetLayer).SetAddressType(mDeviceAddr.Type())); + err = mTransportMgr->ResetTransport(Transport::UdpListenParameters(mInetLayer).SetAddressType(mDeviceAddr.Type())); SuccessOrExit(err); err = mSessionManager->NewPairing( diff --git a/src/controller/CHIPDevice.h b/src/controller/CHIPDevice.h index 69d7491717c08a..5f9c2d57c07344 100644 --- a/src/controller/CHIPDevice.h +++ b/src/controller/CHIPDevice.h @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -41,6 +42,8 @@ class DeviceController; class DeviceStatusDelegate; struct SerializedDevice; +using DeviceTransportMgr = TransportMgr; + class DLL_EXPORT Device { public: @@ -96,8 +99,9 @@ class DLL_EXPORT Device * @param[in] sessionMgr Secure session manager object pointer * @param[in] inetLayer InetLayer object pointer */ - void Init(SecureSessionMgr * sessionMgr, Inet::InetLayer * inetLayer) + void Init(DeviceTransportMgr * transportMgr, SecureSessionMgr * sessionMgr, Inet::InetLayer * inetLayer) { + mTransportMgr = transportMgr; mSessionManager = sessionMgr; mInetLayer = inetLayer; } @@ -119,10 +123,10 @@ class DLL_EXPORT Device * @param[in] devicePort Port on which device is listening (typically CHIP_PORT) * @param[in] interfaceId Local Interface ID that should be used to talk to the device */ - void Init(SecureSessionMgr * sessionMgr, Inet::InetLayer * inetLayer, NodeId deviceId, uint16_t devicePort, - Inet::InterfaceId interfaceId) + void Init(DeviceTransportMgr * transportMgr, SecureSessionMgr * sessionMgr, Inet::InetLayer * inetLayer, NodeId deviceId, + uint16_t devicePort, Inet::InterfaceId interfaceId) { - Init(sessionMgr, inetLayer); + Init(transportMgr, sessionMgr, inetLayer); mDeviceId = deviceId; mDevicePort = devicePort; mInterface = interfaceId; @@ -156,7 +160,7 @@ class DLL_EXPORT Device * @param[in] mgr Pointer to secure session manager which received the message */ void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, - System::PacketBuffer * msgBuf, SecureSessionMgrBase * mgr); + System::PacketBuffer * msgBuf, SecureSessionMgr * mgr); /** * @brief @@ -202,7 +206,9 @@ class DLL_EXPORT Device DeviceStatusDelegate * mStatusDelegate; - SecureSessionMgr * mSessionManager; + SecureSessionMgr * mSessionManager; + + DeviceTransportMgr * mTransportMgr; /** * @brief diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 7ce20bddb661e3..e406a4074758f8 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -123,12 +123,15 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, PersistentStorageDelegat mStorageDelegate->SetDelegate(this); } - mSessionManager = chip::Platform::New>(); + mTransportMgr = chip::Platform::New(); + mSessionManager = chip::Platform::New(); - err = mSessionManager->Init(localDeviceId, mSystemLayer, - Transport::UdpListenParameters(mInetLayer).SetAddressType(Inet::kIPAddressType_IPv6)); + err = mSessionManager->Init(localDeviceId, mSystemLayer); SuccessOrExit(err); + err = mTransportMgr->Init(mSessionManager, nullptr, + Transport::UdpListenParameters(mInetLayer).SetAddressType(Inet::kIPAddressType_IPv6)); + mSessionManager->SetDelegate(this); mState = State::Initialized; @@ -202,7 +205,7 @@ CHIP_ERROR DeviceController::GetDevice(NodeId deviceId, const SerializedDevice & err = device->Deserialize(deviceInfo); VerifyOrExit(err == CHIP_NO_ERROR, ReleaseDevice(device)); - device->Init(mSessionManager, mInetLayer); + device->Init(mTransportMgr, mSessionManager, mInetLayer); } *out_device = device; @@ -264,7 +267,7 @@ CHIP_ERROR DeviceController::GetDevice(NodeId deviceId, Device ** out_device) err = device->Deserialize(deviceInfo); VerifyOrExit(err == CHIP_NO_ERROR, ReleaseDevice(device)); - device->Init(mSessionManager, mInetLayer); + device->Init(mTransportMgr, mSessionManager, mInetLayer); } } @@ -309,11 +312,11 @@ CHIP_ERROR DeviceController::ServiceEventSignal() return err; } -void DeviceController::OnNewConnection(Transport::PeerConnectionState * peerConnection, SecureSessionMgrBase * mgr) {} +void DeviceController::OnNewConnection(Transport::PeerConnectionState * peerConnection, SecureSessionMgr * mgr) {} void DeviceController::OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, - SecureSessionMgrBase * mgr) + SecureSessionMgr * mgr) { CHIP_ERROR err = CHIP_NO_ERROR; uint16_t index = 0; @@ -470,7 +473,7 @@ CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParam err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId)); SuccessOrExit(err); - device->Init(mSessionManager, mInetLayer, remoteDeviceId, remotePort, interfaceId); + device->Init(mTransportMgr, mSessionManager, mInetLayer, remoteDeviceId, remotePort, interfaceId); exit: if (err != CHIP_NO_ERROR) @@ -513,7 +516,7 @@ CHIP_ERROR DeviceCommissioner::PairTestDeviceWithoutSecurity(NodeId remoteDevice testSecurePairingSecret->ToSerializable(device->GetPairing()); - device->Init(mSessionManager, mInetLayer, remoteDeviceId, remotePort, interfaceId); + device->Init(mTransportMgr, mSessionManager, mInetLayer, remoteDeviceId, remotePort, interfaceId); device->SetAddress(deviceAddr); diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 1e7ec69befa671..2494cda10fb3d1 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -37,6 +37,7 @@ #include #include #include +#include #include namespace chip { @@ -182,7 +183,8 @@ class DLL_EXPORT DeviceController : public SecureSessionMgrDelegate, public Pers bool mPairedDevicesInitialized; NodeId mLocalDeviceId; - SecureSessionMgr * mSessionManager; + DeviceTransportMgr * mTransportMgr; + SecureSessionMgr * mSessionManager; PersistentStorageDelegate * mStorageDelegate; Inet::InetLayer * mInetLayer; @@ -194,9 +196,9 @@ class DLL_EXPORT DeviceController : public SecureSessionMgrDelegate, public Pers private: //////////// SecureSessionMgrDelegate Implementation /////////////// void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, - System::PacketBuffer * msgBuf, SecureSessionMgrBase * mgr) override; + System::PacketBuffer * msgBuf, SecureSessionMgr * mgr) override; - void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) override; + void OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) override; //////////// PersistentStorageResultDelegate Implementation /////////////// void OnValue(const char * key, const char * value) override; diff --git a/src/transport/SecurePairingSession.cpp b/src/transport/SecurePairingSession.cpp index 89cd5daefd2b16..2984094fe32a98 100644 --- a/src/transport/SecurePairingSession.cpp +++ b/src/transport/SecurePairingSession.cpp @@ -211,6 +211,12 @@ CHIP_ERROR SecurePairingSession::AttachHeaderAndSend(uint8_t msgType, System::Pa SuccessOrExit(err); VerifyOrExit(headerSize == actualEncodedHeaderSize, err = CHIP_ERROR_INTERNAL); + err = mDelegate->SendPairingMessage(PacketHeader().SetSourceNodeId(mLocalNodeId).SetEncryptionKeyID(mLocalKeyId), + payloadHeader.GetEncodePacketFlags(), mPeerAddress, msgBuf); + msgBuf = nullptr; + SuccessOrExit(err); + +exit: if (msgBuf) System::PacketBuffer::Free(msgBuf); return err; diff --git a/src/transport/SecurePairingSession.h b/src/transport/SecurePairingSession.h index 55dbcf1f675f43..af7201d44f79b9 100644 --- a/src/transport/SecurePairingSession.h +++ b/src/transport/SecurePairingSession.h @@ -302,7 +302,11 @@ class SecurePairingUsingTestSecret : public SecurePairingSession return CHIP_NO_ERROR; } - CHIP_ERROR HandlePeerMessage(const PacketHeader & packetHeader, System::PacketBuffer * msg) override { return CHIP_NO_ERROR; } + CHIP_ERROR HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msg) override + { + return CHIP_NO_ERROR; + } }; typedef struct SecurePairingSessionSerialized diff --git a/src/transport/SecureSessionMgr.cpp b/src/transport/SecureSessionMgr.cpp index fd64cb74db5386..8be9ad84ce3baf 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -177,64 +177,6 @@ CHIP_ERROR SecureSessionMgr::SendMessage(PayloadHeader & payloadHeader, NodeId p return err; } -CHIP_ERROR SecureSessionMgr::SendUnsecureMessage(PacketHeader & packetBuffer, PayloadHeader & payloadHeader, - const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mState == State::kInitialized, err = CHIP_ERROR_INCORRECT_STATE); - - VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); - VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); - - { - uint8_t * data = nullptr; - PacketHeader packetHeader; - MessageAuthenticationCode mac; - - const uint16_t headerSize = payloadHeader.EncodeSizeBytes(); - uint16_t actualEncodedHeaderSize; - uint16_t totalLen = 0; - uint32_t payloadLength; // Make sure it's big enough to add two 16-bit - // ints without overflowing. - static_assert(std::is_sameTotalLength()), uint16_t>::value, - "Addition to generate payloadLength might overflow"); - payloadLength = static_cast(headerSize + msgBuf->TotalLength()); - VerifyOrExit(CanCastTo(payloadLength), err = CHIP_ERROR_NO_MEMORY); - - packetHeader - .SetSourceNodeId(mLocalNodeId) // - .SetPayloadLength(static_cast(payloadLength)); - packetHeader.GetFlags().Clear(Header::FlagValues::kSecure); - - VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY); - - msgBuf->SetStart(msgBuf->Start() - headerSize); - data = msgBuf->Start(); - totalLen = msgBuf->TotalLength(); - - err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize); - SuccessOrExit(err); - - ChipLogDetail(Inet, "Transmitting unsecured msg"); - - err = mTransportMgr->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), peerAddress, msgBuf); - msgBuf = nullptr; - } - SuccessOrExit(err); - -exit: - if (msgBuf != nullptr) - { - const char * errStr = ErrorStr(err); - ChipLogError(Inet, "Secure transport could not find a valid PeerConnection: %s", errStr); - PacketBuffer::Free(msgBuf); - msgBuf = nullptr; - } - - return err; -} - CHIP_ERROR SecureSessionMgr::NewPairing(const Optional & peerAddr, SecurePairingSession * pairing) { CHIP_ERROR err = CHIP_NO_ERROR; diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index 254f4b3485c8b3..32d5aa9d66f6ad 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -96,7 +96,7 @@ class DLL_EXPORT SecureSessionMgrDelegate * @param nodeId The node ID resolved, 0 on error * @param mgr A pointer to the SecureSessionMgr */ - virtual void OnAddressResolved(CHIP_ERROR error, NodeId nodeId, SecureSessionMgrBase * mgr) {} + virtual void OnAddressResolved(CHIP_ERROR error, NodeId nodeId, SecureSessionMgr * mgr) {} virtual ~SecureSessionMgrDelegate() {} }; @@ -117,19 +117,6 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate SecureSessionMgr(); ~SecureSessionMgr() override; - /** - * @brief - * Send a unsecured message to peerAddress - * @details - * This function will fill packet header. and send it to - * transport layer on behalf of the caller. - * All unsecure messages are stateless for SecureSessionMgr. - * This method calls chip::System::PacketBuffer::Free - * on behalf of the caller regardless of the return status. - */ - CHIP_ERROR SendUnsecureMessage(PacketHeader & packetHeader, PayloadHeader & payloadHeader, - const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf); - /** * @brief * Set the callback object. diff --git a/src/transport/tests/TestSecurePairingSession.cpp b/src/transport/tests/TestSecurePairingSession.cpp index f123cdf1d4bd4b..dd8a78ef383d23 100644 --- a/src/transport/tests/TestSecurePairingSession.cpp +++ b/src/transport/tests/TestSecurePairingSession.cpp @@ -43,7 +43,7 @@ class TestSecurePairingDelegate : public SecurePairingSessionDelegate const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) override { mNumMessageSend++; - return (peer != nullptr) ? peer->HandlePeerMessage(header, msgBuf) : mMessageSendError; + return (peer != nullptr) ? peer->HandlePeerMessage(header, peerAddress, msgBuf) : mMessageSendError; } void OnPairingError(CHIP_ERROR error) override { mNumPairingErrors++; } From f9a8e727073dd69f16f2bfa3d56972dea74dec98 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 11 Nov 2020 16:26:21 +0800 Subject: [PATCH 04/17] Fix --- src/controller/CHIPDevice.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/controller/CHIPDevice.h b/src/controller/CHIPDevice.h index 5f9c2d57c07344..b41975a0288778 100644 --- a/src/controller/CHIPDevice.h +++ b/src/controller/CHIPDevice.h @@ -96,6 +96,7 @@ class DLL_EXPORT Device * that of this device object. If these objects are freed, while the device object is * still using them, it can lead to unknown behavior and crashes. * + * @param[in] transportMgr Transport manager object pointer * @param[in] sessionMgr Secure session manager object pointer * @param[in] inetLayer InetLayer object pointer */ @@ -117,6 +118,7 @@ class DLL_EXPORT Device * uninitialzed/unpaired device objects. The object is initialized only when the device * is actually paired. * + * @param[in] transportMgr Transport manager object pointer * @param[in] sessionMgr Secure session manager object pointer * @param[in] inetLayer InetLayer object pointer * @param[in] deviceId Node ID of the device From e096d81d93d671b71c7184c96598838d84e87de3 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 11 Nov 2020 17:46:13 +0800 Subject: [PATCH 05/17] Fix --- examples/common/chip-app-server/Server.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/common/chip-app-server/Server.cpp b/examples/common/chip-app-server/Server.cpp index 942dd303ae411a..d3b9011b4fce26 100644 --- a/examples/common/chip-app-server/Server.cpp +++ b/examples/common/chip-app-server/Server.cpp @@ -123,15 +123,15 @@ void InitServer() } #endif + // Init transport before operations with secure session mgr. + gTransports.Init(&gSessions, gRendezvousServer.GetRendezvousSession(), + UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); + err = gSessions.NewPairing(peer, &gTestPairing); SuccessOrExit(err); gSessions.SetDelegate(&gCallbacks); chip::Mdns::DiscoveryManager::GetInstance().StartPublishDevice(chip::Inet::kIPAddressType_IPv6); - - gTransports.Init(&gSessions, gRendezvousServer.GetRendezvousSession(), - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); - exit: if (err != CHIP_NO_ERROR) { From 8ab65dc71591848f42297f5e2ec4ee2e953f7661 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Thu, 12 Nov 2020 10:37:31 +0800 Subject: [PATCH 06/17] Make code clearer --- src/transport/TransportMgr.h | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/src/transport/TransportMgr.h b/src/transport/TransportMgr.h index cb5ed78bf3336e..f8b32fcadc9bfe 100644 --- a/src/transport/TransportMgr.h +++ b/src/transport/TransportMgr.h @@ -50,7 +50,7 @@ class TransportMgrBase void SetSecureSessionMgr(SecureSessionMgr * secureSessionMgr) { mSecureSessionMgr = secureSessionMgr; - if (secureSessionMgr != nullptr) + if (mSecureSessionMgr != nullptr) { mSecureSessionMgr->SetTransportMgr(this); } @@ -68,18 +68,10 @@ class TransportMgrBase protected: void InitInternal(SecureSessionMgr * secureMgr, RendezvousSession * rendezvous, Transport::Base * transport) { - mSecureSessionMgr = secureMgr; - mRendezvous = rendezvous; mTransport = transport; - if (mSecureSessionMgr != nullptr) - { - mSecureSessionMgr->SetTransportMgr(this); - } - if (mRendezvous != nullptr) - { - mRendezvous->SetTransportMgr(this); - } mTransport->SetMessageReceiveHandler(HandleMessageReceived, this); + SetSecureSessionMgr(secureMgr); + SetRendezvousSession(rendezvous); ChipLogDetail(Inet, "TransportMgr initialized"); } From 48217dfe69a773bec6f38459e186ac2de4fb964f Mon Sep 17 00:00:00 2001 From: Song Guo Date: Thu, 12 Nov 2020 10:39:43 +0800 Subject: [PATCH 07/17] Rename variables in tests --- src/transport/tests/TestSecureSessionMgr.cpp | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/transport/tests/TestSecureSessionMgr.cpp b/src/transport/tests/TestSecureSessionMgr.cpp index fc135e4cf6edba..4da542e28b902c 100644 --- a/src/transport/tests/TestSecureSessionMgr.cpp +++ b/src/transport/tests/TestSecureSessionMgr.cpp @@ -95,15 +95,15 @@ void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - TransportMgr tm; - SecureSessionMgr conn; + TransportMgr transportMgr; + SecureSessionMgr secureSessionMgr; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = tm.Init(&conn, nullptr, "LOOPBACK"); + err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } @@ -125,32 +125,32 @@ void CheckMessageTest(nlTestSuite * inSuite, void * inContext) IPAddress::FromString("127.0.0.1", addr); CHIP_ERROR err = CHIP_NO_ERROR; - TransportMgr tm; - SecureSessionMgr conn; + TransportMgr transportMgr; + SecureSessionMgr secureSessionMgr; - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = tm.Init(&conn, nullptr, "LOOPBACK"); + err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); callback.mSuite = inSuite; - conn.SetDelegate(&callback); + secureSessionMgr.SetDelegate(&callback); SecurePairingUsingTestSecret pairing1(Optional::Value(kSourceNodeId), 1, 2); Optional peer(Transport::PeerAddress::UDP(addr, CHIP_PORT)); - err = conn.NewPairing(peer, &pairing1); + err = secureSessionMgr.NewPairing(peer, &pairing1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); SecurePairingUsingTestSecret pairing2(Optional::Value(kDestinationNodeId), 2, 1); - err = conn.NewPairing(peer, &pairing2); + err = secureSessionMgr.NewPairing(peer, &pairing2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Should be able to send a message to itself by just calling send. callback.ReceiveHandlerCallCount = 0; - err = conn.SendMessage(kDestinationNodeId, buffer); + err = secureSessionMgr.SendMessage(kDestinationNodeId, buffer); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ctx.DriveIOUntil(1000 /* ms */, []() { return callback.ReceiveHandlerCallCount != 0; }); From b62d8065592a6bb173e4c417e8002d831b0e1c85 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Thu, 12 Nov 2020 02:37:50 +0000 Subject: [PATCH 08/17] Restyled by clang-format --- src/transport/TransportMgr.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transport/TransportMgr.h b/src/transport/TransportMgr.h index f8b32fcadc9bfe..f6567329bfd2ce 100644 --- a/src/transport/TransportMgr.h +++ b/src/transport/TransportMgr.h @@ -68,7 +68,7 @@ class TransportMgrBase protected: void InitInternal(SecureSessionMgr * secureMgr, RendezvousSession * rendezvous, Transport::Base * transport) { - mTransport = transport; + mTransport = transport; mTransport->SetMessageReceiveHandler(HandleMessageReceived, this); SetSecureSessionMgr(secureMgr); SetRendezvousSession(rendezvous); From a79e5da62ebc9c8ddc83c48c84c1c961bc434651 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Tue, 17 Nov 2020 10:32:41 +0800 Subject: [PATCH 09/17] Add TransportMgrDelegate --- src/transport/RendezvousSession.cpp | 7 ++++ src/transport/RendezvousSession.h | 11 ++++-- src/transport/RendezvousSessionDelegate.h | 3 -- src/transport/SecureSessionMgr.cpp | 18 +++++----- src/transport/SecureSessionMgr.h | 29 +++++++++------ src/transport/TransportMgr.cpp | 4 +-- src/transport/TransportMgr.h | 44 ++++++++++++++++------- 7 files changed, 77 insertions(+), 39 deletions(-) diff --git a/src/transport/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp index 7fe5755a79c94e..b99b6a60af5d0b 100644 --- a/src/transport/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -298,6 +298,13 @@ void RendezvousSession::OnRendezvousMessageReceived(const PacketHeader & packetH } } +void RendezvousSession::OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, + System::PacketBuffer * msgBuf) +{ + // TODO: OnRendezvousMessageReceived can be renamed to OnMessageReceived after BLE becomes a transport. + this->OnRendezvousMessageReceived(header, source, msgBuf); +} + CHIP_ERROR RendezvousSession::HandlePairingMessage(const PacketHeader & packetHeader, const PeerAddress & peerAddress, PacketBuffer * msgBuf) { diff --git a/src/transport/RendezvousSession.h b/src/transport/RendezvousSession.h index 424a6cf3a6704c..0a794e17fd7ce3 100644 --- a/src/transport/RendezvousSession.h +++ b/src/transport/RendezvousSession.h @@ -29,6 +29,7 @@ #include #include #include +#include #include #include namespace chip { @@ -65,7 +66,8 @@ class TransportMgrBase; class RendezvousSession : public SecurePairingSessionDelegate, public RendezvousSessionDelegate, public RendezvousDeviceCredentialsDelegate, - public NetworkProvisioningDelegate + public NetworkProvisioningDelegate, + public TransportMgrDelegate { public: enum State : uint8_t @@ -108,8 +110,6 @@ class RendezvousSession : public SecurePairingSessionDelegate, void OnRendezvousMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::/* */ PacketBuffer * buffer) override; - void SetTransportMgr(TransportMgrBase * transport) override; - //////////// RendezvousDeviceCredentialsDelegate Implementation /////////////// void SendNetworkCredentials(const char * ssid, const char * passwd) override; void SendThreadCredentials(const DeviceLayer::Internal::DeviceNetworkInfo & threadData) override; @@ -120,6 +120,11 @@ class RendezvousSession : public SecurePairingSessionDelegate, void OnNetworkProvisioningError(CHIP_ERROR error) override; void OnNetworkProvisioningComplete() override; + //////////// TransportMgrDelegate Implementation /////////////// + void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, + System::PacketBuffer * msgBuf) override; + void SetTransportMgr(TransportMgrBase * transport) override; + /** * @brief * Get the IP address assigned to the device during network provisioning diff --git a/src/transport/RendezvousSessionDelegate.h b/src/transport/RendezvousSessionDelegate.h index b66fca64fec57f..1c9371ee170270 100644 --- a/src/transport/RendezvousSessionDelegate.h +++ b/src/transport/RendezvousSessionDelegate.h @@ -44,9 +44,6 @@ class RendezvousSessionDelegate virtual void OnRendezvousComplete() {} virtual void OnRendezvousMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBuffer * buffer){}; - - virtual void SetTransportMgr(TransportMgrBase * transport) {} - virtual void OnRendezvousStatusUpdate(Status status, CHIP_ERROR err) {} }; diff --git a/src/transport/SecureSessionMgr.cpp b/src/transport/SecureSessionMgr.cpp index 8be9ad84ce3baf..99994eaa30ebd5 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -273,14 +273,14 @@ void SecureSessionMgr::CancelExpiryTimer() } } -void SecureSessionMgr::HandleSecureMessageReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, - System::PacketBuffer * msg, SecureSessionMgr * connection) +void SecureSessionMgr::OnMessageReceived(const PacketHeader & packetHeader, const PeerAddress & peerAddress, + System::PacketBuffer * msg) { CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBuffer * origMsg = nullptr; - PeerConnectionState * state = connection->mPeerConnections.FindPeerConnectionState(packetHeader.GetSourceNodeId(), - packetHeader.GetEncryptionKeyID(), nullptr); + PeerConnectionState * state = + mPeerConnections.FindPeerConnectionState(packetHeader.GetSourceNodeId(), packetHeader.GetEncryptionKeyID(), nullptr); VerifyOrExit(msg != nullptr, ChipLogError(Inet, "Secure transport received NULL packet, discarding")); @@ -295,7 +295,7 @@ void SecureSessionMgr::HandleSecureMessageReceived(const PacketHeader & packetHe state->SetPeerAddress(peerAddress); } - connection->mPeerConnections.MarkConnectionActive(state); + mPeerConnections.MarkConnectionActive(state); // TODO this is where messages should be decoded { @@ -343,9 +343,9 @@ void SecureSessionMgr::HandleSecureMessageReceived(const PacketHeader & packetHe state->SetPeerNodeId(packetHeader.GetSourceNodeId().Value()); } - if (connection->mCB != nullptr) + if (mCB != nullptr) { - connection->mCB->OnMessageReceived(packetHeader, payloadHeader, state, msg, connection); + mCB->OnMessageReceived(packetHeader, payloadHeader, state, msg, this); msg = nullptr; } } @@ -361,9 +361,9 @@ void SecureSessionMgr::HandleSecureMessageReceived(const PacketHeader & packetHe PacketBuffer::Free(msg); } - if (err != CHIP_NO_ERROR && connection->mCB != nullptr) + if (err != CHIP_NO_ERROR && mCB != nullptr) { - connection->mCB->OnReceiveError(err, peerAddress, connection); + mCB->OnReceiveError(err, peerAddress, this); } } diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index 32d5aa9d66f6ad..ff7b649af1481d 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -36,6 +36,7 @@ #include #include #include +#include #include #include @@ -101,7 +102,7 @@ class DLL_EXPORT SecureSessionMgrDelegate virtual ~SecureSessionMgrDelegate() {} }; -class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate +class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate, public TransportMgrDelegate { public: /** @@ -126,12 +127,6 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate */ void SetDelegate(SecureSessionMgrDelegate * cb) { mCB = cb; } - /** - * @brief - * Set the handler for unsecured messages. - */ - void SetTransportMgr(TransportMgrBase * cb) { mTransportMgr = cb; } - /** * @brief * Establish a new pairing with a peer node @@ -158,6 +153,23 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate */ CHIP_ERROR Init(NodeId localNodeId, System::Layer * systemLayer); +protected: + /** + * @brief + * Handle received secure message. Implements TransportMgrDelegate + * + * @param header the received message header + * @param source the source address of the package + * @param msgBuf the buffer of (encrypted) payload + */ + void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, + System::PacketBuffer * msgBuf) override; + /** + * @brief + * Set the transport manager for secure session manager. + */ + void SetTransportMgr(TransportMgrBase * cb) override { mTransportMgr = cb; } + private: friend class TransportMgrBase; /** @@ -183,9 +195,6 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate /** Cancels any active timers for connection expiry checks. */ void CancelExpiryTimer(); - static void HandleSecureMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, - System::PacketBuffer * msgBuf, SecureSessionMgr * transport); - /** * Called when a specific connection expires. */ diff --git a/src/transport/TransportMgr.cpp b/src/transport/TransportMgr.cpp index 69274ae68bd105..e4da5b6ecd2907 100644 --- a/src/transport/TransportMgr.cpp +++ b/src/transport/TransportMgr.cpp @@ -42,14 +42,14 @@ void TransportMgrBase::HandleMessageReceived(const PacketHeader & packetHeader, { if (dispatcher->mSecureSessionMgr != nullptr) { - SecureSessionMgr::HandleSecureMessageReceived(packetHeader, peerAddress, msg, dispatcher->mSecureSessionMgr); + dispatcher->mSecureSessionMgr->OnMessageReceived(packetHeader, peerAddress, msg); } } else { if (dispatcher->mRendezvous != nullptr) { - dispatcher->mRendezvous->OnRendezvousMessageReceived(packetHeader, peerAddress, msg); + dispatcher->mRendezvous->OnMessageReceived(packetHeader, peerAddress, msg); // Unsecure message received, pass it to Rendezvous Session Mgr directly. } } diff --git a/src/transport/TransportMgr.h b/src/transport/TransportMgr.h index f6567329bfd2ce..7dda42af0c5653 100644 --- a/src/transport/TransportMgr.h +++ b/src/transport/TransportMgr.h @@ -27,15 +27,34 @@ #pragma once +#include #include -#include -#include #include #include #include +#include namespace chip { +class TransportMgrBase; + +class TransportMgrDelegate +{ +public: + virtual ~TransportMgrDelegate() = default; + /** + * @brief + * Handle received secure message. + * + * @param header the received message header + * @param source the source address of the package + * @param msgBuf the buffer of (encrypted) payload + */ + virtual void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, + System::PacketBuffer * msgBuf) = 0; + virtual void SetTransportMgr(TransportMgrBase * transport) = 0; +}; + class TransportMgrBase { public: @@ -47,7 +66,7 @@ class TransportMgrBase void Disconnect(const Transport::PeerAddress & address) { mTransport->Disconnect(address); } - void SetSecureSessionMgr(SecureSessionMgr * secureSessionMgr) + void SetSecureSessionMgr(TransportMgrDelegate * secureSessionMgr) { mSecureSessionMgr = secureSessionMgr; if (mSecureSessionMgr != nullptr) @@ -56,9 +75,9 @@ class TransportMgrBase } } - void SetRendezvousSession(RendezvousSession * rendezvous) + void SetRendezvousSession(TransportMgrDelegate * rendezvousSessionMgr) { - mRendezvous = rendezvous; + mRendezvous = rendezvousSessionMgr; if (mRendezvous != nullptr) { mRendezvous->SetTransportMgr(this); @@ -66,12 +85,13 @@ class TransportMgrBase } protected: - void InitInternal(SecureSessionMgr * secureMgr, RendezvousSession * rendezvous, Transport::Base * transport) + void InitInternal(TransportMgrDelegate * secureSessionMgr, TransportMgrDelegate * rendezvousSessionMgr, + Transport::Base * transport) { mTransport = transport; mTransport->SetMessageReceiveHandler(HandleMessageReceived, this); - SetSecureSessionMgr(secureMgr); - SetRendezvousSession(rendezvous); + SetSecureSessionMgr(secureSessionMgr); + SetRendezvousSession(rendezvousSessionMgr); ChipLogDetail(Inet, "TransportMgr initialized"); } @@ -79,9 +99,9 @@ class TransportMgrBase static void HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBuffer * msg, TransportMgrBase * dispatcher); - SecureSessionMgr * mSecureSessionMgr = nullptr; - RendezvousSession * mRendezvous = nullptr; - Transport::Base * mTransport = nullptr; + TransportMgrDelegate * mSecureSessionMgr = nullptr; + TransportMgrDelegate * mRendezvous = nullptr; + Transport::Base * mTransport = nullptr; }; template @@ -89,7 +109,7 @@ class TransportMgr : public TransportMgrBase { public: template - CHIP_ERROR Init(SecureSessionMgr * secureMgr, RendezvousSession * rendezvous, Args &&... transportInitArgs) + CHIP_ERROR Init(TransportMgrDelegate * secureMgr, TransportMgrDelegate * rendezvous, Args &&... transportInitArgs) { CHIP_ERROR err = CHIP_NO_ERROR; From 2cc7ff45ec3834cfba87b626e81000081c2691d5 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Tue, 17 Nov 2020 12:15:59 +0800 Subject: [PATCH 10/17] remove BLEConnectionDelegate which shouldn't in this pr --- src/transport/BLE.h | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/transport/BLE.h b/src/transport/BLE.h index e778c7a3460bb7..7b156adcf5c240 100644 --- a/src/transport/BLE.h +++ b/src/transport/BLE.h @@ -39,15 +39,6 @@ namespace chip { namespace Transport { -class DLL_EXPORT BLEConnectionDelegate -{ -public: - virtual ~BLEConnectionDelegate() = default; - virtual void OnBleEndPointReceive(Ble::BLEEndPoint * endPoint, System::PacketBuffer * buffer); - virtual void OnBleEndPointConnectionComplete(Ble::BLEEndPoint * endPoint, BLE_ERROR err); - virtual void OnBleEndPointConnectionClosed(Ble::BLEEndPoint * endPoint, BLE_ERROR err); -}; - /** Implements a transport using BLE. * * TODO: BLE transport currently does NOT receive messages as defined From 1ab9edf04084a5ad4f16949beb3e60d23d1e0ff1 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Tue, 17 Nov 2020 12:19:16 +0800 Subject: [PATCH 11/17] Fix nrf build --- src/include/platform/CHIPDeviceLayer.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/include/platform/CHIPDeviceLayer.h b/src/include/platform/CHIPDeviceLayer.h index 434998bb924af0..bbab2d48a701b1 100644 --- a/src/include/platform/CHIPDeviceLayer.h +++ b/src/include/platform/CHIPDeviceLayer.h @@ -29,6 +29,7 @@ #include #include #include +#include #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER #include #endif // CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER From 1733c5220b71c264baf36b0e0dae3e836a67eb56 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 18 Nov 2020 10:01:26 +0800 Subject: [PATCH 12/17] Address comments --- src/messaging/tests/TestExchangeMgr.cpp | 40 +++++++++++------------ src/transport/RendezvousSession.h | 3 +- src/transport/RendezvousSessionDelegate.h | 1 - src/transport/SecureSessionMgr.h | 2 -- src/transport/TransportMgr.cpp | 18 +++++----- src/transport/raw/MessageHeader.h | 9 +++-- 6 files changed, 35 insertions(+), 38 deletions(-) diff --git a/src/messaging/tests/TestExchangeMgr.cpp b/src/messaging/tests/TestExchangeMgr.cpp index 31829182638aa4..7d47ec8fb867a8 100644 --- a/src/messaging/tests/TestExchangeMgr.cpp +++ b/src/messaging/tests/TestExchangeMgr.cpp @@ -78,19 +78,19 @@ void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - TransportMgr tm; - SecureSessionMgr conn; + TransportMgr transportMgr; + SecureSessionMgr secureSessionMgr; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); - tm.Init(&conn, nullptr, "LOOPBACK"); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; - err = exchangeMgr.Init(&conn); + err = exchangeMgr.Init(&secureSessionMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } @@ -98,18 +98,18 @@ void CheckNewContextTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - TransportMgr tm; - SecureSessionMgr conn; + TransportMgr transportMgr; + SecureSessionMgr secureSessionMgr; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); - tm.Init(&conn, nullptr, "LOOPBACK"); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; - err = exchangeMgr.Init(&conn); + err = exchangeMgr.Init(&secureSessionMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeContext * ec1 = exchangeMgr.NewContext(kSourceNodeId, (void *) 0x1234); @@ -129,19 +129,19 @@ void CheckFindContextTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - TransportMgr tm; - SecureSessionMgr conn; + TransportMgr transportMgr; + SecureSessionMgr secureSessionMgr; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = tm.Init(&conn, nullptr, "LOOPBACK"); + err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; - err = exchangeMgr.Init(&conn); + err = exchangeMgr.Init(&secureSessionMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeContext * ec = exchangeMgr.NewContext(kDestinationNodeId, nullptr); @@ -158,19 +158,19 @@ void CheckUmhRegistrationTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - TransportMgr tm; - SecureSessionMgr conn; + TransportMgr transportMgr; + SecureSessionMgr secureSessionMgr; CHIP_ERROR err; ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = tm.Init(&conn, nullptr, "LOOPBACK"); + err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; - err = exchangeMgr.Init(&conn); + err = exchangeMgr.Init(&secureSessionMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = exchangeMgr.RegisterUnsolicitedMessageHandler(0x0001, HanldeAllUnsolicitedMessage, nullptr); diff --git a/src/transport/RendezvousSession.h b/src/transport/RendezvousSession.h index c335df9cbb8eb0..dc2fa3a7819ea2 100644 --- a/src/transport/RendezvousSession.h +++ b/src/transport/RendezvousSession.h @@ -39,7 +39,6 @@ class CHIPDeviceEvent; } class SecureSessionMgr; -class TransportMgrBase; /** * RendezvousSession establishes and maintains the first connection between @@ -111,7 +110,7 @@ class RendezvousSession : public SecurePairingSessionDelegate, void OnRendezvousConnectionClosed() override; void OnRendezvousError(CHIP_ERROR err) override; void OnRendezvousMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, - System::/* */ PacketBuffer * buffer) override; + System::PacketBuffer * buffer) override; //////////// RendezvousDeviceCredentialsDelegate Implementation /////////////// void SendNetworkCredentials(const char * ssid, const char * passwd) override; diff --git a/src/transport/RendezvousSessionDelegate.h b/src/transport/RendezvousSessionDelegate.h index 57025278d582f1..3cd6366341c933 100644 --- a/src/transport/RendezvousSessionDelegate.h +++ b/src/transport/RendezvousSessionDelegate.h @@ -23,7 +23,6 @@ #include namespace chip { -class TransportMgrBase; class RendezvousSessionDelegate { diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index 726c890915b03c..9e9f8799aaf192 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -43,7 +43,6 @@ namespace chip { class SecureSessionMgr; -class TransportMgrBase; /** * @brief @@ -171,7 +170,6 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate, public Transpo void SetTransportMgr(TransportMgrBase * cb) override { mTransportMgr = cb; } private: - friend class TransportMgrBase; /** * The State of a secure transport object. */ diff --git a/src/transport/TransportMgr.cpp b/src/transport/TransportMgr.cpp index e4da5b6ecd2907..b4a6262c757fd5 100644 --- a/src/transport/TransportMgr.cpp +++ b/src/transport/TransportMgr.cpp @@ -38,20 +38,18 @@ namespace chip { void TransportMgrBase::HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBuffer * msg, TransportMgrBase * dispatcher) { - if (packetHeader.GetFlags().Has(Header::FlagValues::kSecure)) + TransportMgrDelegate * handler = + packetHeader.GetFlags().Has(Header::FlagValues::kSecure) ? dispatcher->mSecureSessionMgr : dispatcher->mRendezvous; + if (handler != nullptr) { - if (dispatcher->mSecureSessionMgr != nullptr) - { - dispatcher->mSecureSessionMgr->OnMessageReceived(packetHeader, peerAddress, msg); - } + handler->OnMessageReceived(packetHeader, peerAddress, msg); } else { - if (dispatcher->mRendezvous != nullptr) - { - dispatcher->mRendezvous->OnMessageReceived(packetHeader, peerAddress, msg); - // Unsecure message received, pass it to Rendezvous Session Mgr directly. - } + char addrBuffer[Transport::PeerAddress::kMaxToStringSize]; + peerAddress.ToString(addrBuffer, sizeof(addrBuffer)); + ChipLogError(Inet, "%s message from %s is dropped since no corresponding handler is set in TransportMgr.", + packetHeader.GetFlags().Has(Header::FlagValues::kSecure) ? "Encrypted" : "Unencrypted", addrBuffer); } } } // namespace chip diff --git a/src/transport/raw/MessageHeader.h b/src/transport/raw/MessageHeader.h index 6dcb8535013e24..f32d52fd4ac186 100644 --- a/src/transport/raw/MessageHeader.h +++ b/src/transport/raw/MessageHeader.h @@ -83,9 +83,12 @@ using Flags = BitFlags; using ExFlags = BitFlags; // Header is a 16-bit value of the form -// | 4 bit | 4 bit | 4 bit | 4 bit | -// +---------+-------+---------+----------| -// | version | Flags | encType | reserved | +// | 4 bit | 4 bit |8 bit Security Flags| +// +---------+-------+--------------------| +// | version | Flags | P | C |Reserved| E | +// | | +---Encrypted +// | +----------------Control message (TODO: Implement this) +// +--------------------Privacy enhancements (TODO: Implement this) static constexpr uint16_t kFlagsMask = 0x0F01; } // namespace Header From ef68193591ccd7b14c28ec92f6a950e08567957d Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 18 Nov 2020 10:33:06 +0800 Subject: [PATCH 13/17] update delegate code style --- .../esp32/main/EchoServer.cpp | 7 ++--- .../chip-app-server/RendezvousServer.cpp | 4 +-- examples/common/chip-app-server/Server.cpp | 12 ++++---- .../include/RendezvousServer.h | 2 +- .../esp32/main/ResponseServer.cpp | 7 ++--- src/controller/CHIPDeviceController.cpp | 8 ++--- src/messaging/tests/TestExchangeMgr.cpp | 19 ++++++------ src/transport/RendezvousSession.cpp | 12 ++++---- src/transport/RendezvousSession.h | 3 +- src/transport/SecureSessionMgr.cpp | 12 +++++--- src/transport/SecureSessionMgr.h | 7 +---- src/transport/TransportMgr.h | 29 ++++--------------- src/transport/tests/TestSecureSessionMgr.cpp | 8 ++--- 13 files changed, 54 insertions(+), 76 deletions(-) diff --git a/examples/all-clusters-app/esp32/main/EchoServer.cpp b/examples/all-clusters-app/esp32/main/EchoServer.cpp index bed1976bfcd85c..801b97914956bd 100644 --- a/examples/all-clusters-app/esp32/main/EchoServer.cpp +++ b/examples/all-clusters-app/esp32/main/EchoServer.cpp @@ -238,12 +238,11 @@ SecureSessionMgr & SessionManager() void startServer(NodeId localNodeId) { CHIP_ERROR err = CHIP_NO_ERROR; - err = sessions.Init(localNodeId, &DeviceLayer::SystemLayer); - SuccessOrExit(err); - err = gTransports.Init(&sessions, nullptr, - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(nullptr), + err = gTransports.Init(UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(nullptr), UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv4)); SuccessOrExit(err); + err = sessions.Init(localNodeId, &DeviceLayer::SystemLayer, &gTransports); + SuccessOrExit(err); sessions.SetDelegate(&gCallbacks); diff --git a/examples/common/chip-app-server/RendezvousServer.cpp b/examples/common/chip-app-server/RendezvousServer.cpp index 434da30a56d76a..5d8d8c6d7dfd39 100644 --- a/examples/common/chip-app-server/RendezvousServer.cpp +++ b/examples/common/chip-app-server/RendezvousServer.cpp @@ -36,9 +36,9 @@ namespace chip { RendezvousServer::RendezvousServer() : mRendezvousSession(this) {} -CHIP_ERROR RendezvousServer::Init(const RendezvousParameters & params) +CHIP_ERROR RendezvousServer::Init(const RendezvousParameters & params, TransportMgrBase * transportMgr) { - return mRendezvousSession.Init(params); + return mRendezvousSession.Init(params, transportMgr); } void RendezvousServer::OnRendezvousError(CHIP_ERROR err) diff --git a/examples/common/chip-app-server/Server.cpp b/examples/common/chip-app-server/Server.cpp index 257c65b6deb30c..121f1544892b63 100644 --- a/examples/common/chip-app-server/Server.cpp +++ b/examples/common/chip-app-server/Server.cpp @@ -101,7 +101,11 @@ void InitServer() InitDataModelHandler(); - err = gSessions.Init(chip::kTestDeviceNodeId, &DeviceLayer::SystemLayer); + // Init transport before operations with secure session mgr. + err = gTransports.Init(UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); + SuccessOrExit(err); + + err = gSessions.Init(chip::kTestDeviceNodeId, &DeviceLayer::SystemLayer, &gTransports); SuccessOrExit(err); // This flag is used to bypass BLE in the cirque test @@ -115,14 +119,10 @@ void InitServer() params.SetSetupPINCode(pinCode) .SetLocalNodeId(chip::kTestDeviceNodeId) .SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()); - SuccessOrExit(err = gRendezvousServer.Init(params)); + SuccessOrExit(err = gRendezvousServer.Init(params, &gTransports)); } #endif - // Init transport before operations with secure session mgr. - gTransports.Init(&gSessions, gRendezvousServer.GetRendezvousSession(), - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); - err = gSessions.NewPairing(peer, chip::kTestControllerNodeId, &gTestPairing); SuccessOrExit(err); diff --git a/examples/common/chip-app-server/include/RendezvousServer.h b/examples/common/chip-app-server/include/RendezvousServer.h index 589c96fd219230..5af5e9b92d5f6d 100644 --- a/examples/common/chip-app-server/include/RendezvousServer.h +++ b/examples/common/chip-app-server/include/RendezvousServer.h @@ -27,7 +27,7 @@ class RendezvousServer : public RendezvousSessionDelegate public: RendezvousServer(); - CHIP_ERROR Init(const RendezvousParameters & params); + CHIP_ERROR Init(const RendezvousParameters & params, TransportMgrBase * transportMgr); //////////////// RendezvousSessionDelegate Implementation /////////////////// diff --git a/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp b/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp index 23cdc82c874bc4..bb114ba5ef8b5b 100644 --- a/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp +++ b/examples/temperature-measurement-app/esp32/main/ResponseServer.cpp @@ -147,12 +147,11 @@ SecureSessionMgr & SessionManager() void startServer(NodeId localNodeId) { CHIP_ERROR err = CHIP_NO_ERROR; - err = sessions.Init(localNodeId, &DeviceLayer::SystemLayer); - SuccessOrExit(err); - err = gTransports.Init(&sessions, nullptr, - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(nullptr), + err = gTransports.Init(UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetInterfaceId(nullptr), UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv4)); SuccessOrExit(err); + err = sessions.Init(localNodeId, &DeviceLayer::SystemLayer, &gTransports); + SuccessOrExit(err); sessions.SetDelegate(&gCallbacks); diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 50cc96fba7bc5c..b1662475604792 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -126,11 +126,11 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, PersistentStorageDelegat mTransportMgr = chip::Platform::New(); mSessionManager = chip::Platform::New(); - err = mSessionManager->Init(localDeviceId, mSystemLayer); + err = mTransportMgr->Init(Transport::UdpListenParameters(mInetLayer).SetAddressType(Inet::kIPAddressType_IPv6)); SuccessOrExit(err); - err = mTransportMgr->Init(mSessionManager, nullptr, - Transport::UdpListenParameters(mInetLayer).SetAddressType(Inet::kIPAddressType_IPv6)); + err = mSessionManager->Init(localDeviceId, mSystemLayer, mTransportMgr); + SuccessOrExit(err); mSessionManager->SetDelegate(this); @@ -470,7 +470,7 @@ CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParam mRendezvousSession = chip::Platform::New(this); VerifyOrExit(mRendezvousSession != nullptr, err = CHIP_ERROR_NO_MEMORY); - err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId).SetRemoteNodeId(remoteDeviceId)); + err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId).SetRemoteNodeId(remoteDeviceId), mTransportMgr); SuccessOrExit(err); device->Init(mTransportMgr, mSessionManager, mInetLayer, remoteDeviceId, remotePort, interfaceId); diff --git a/src/messaging/tests/TestExchangeMgr.cpp b/src/messaging/tests/TestExchangeMgr.cpp index 7d47ec8fb867a8..404a1fc0a1280a 100644 --- a/src/messaging/tests/TestExchangeMgr.cpp +++ b/src/messaging/tests/TestExchangeMgr.cpp @@ -84,9 +84,9 @@ void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext) ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); - transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); - + err = transportMgr.Init("LOOPBACK"); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), &transportMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; @@ -104,8 +104,9 @@ void CheckNewContextTest(nlTestSuite * inSuite, void * inContext) ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); - transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); + err = transportMgr.Init("LOOPBACK"); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), &transportMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; @@ -135,9 +136,9 @@ void CheckFindContextTest(nlTestSuite * inSuite, void * inContext) ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = transportMgr.Init("LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), &transportMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; @@ -164,9 +165,9 @@ void CheckUmhRegistrationTest(nlTestSuite * inSuite, void * inContext) ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = transportMgr.Init("LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), &transportMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; diff --git a/src/transport/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp index 07dbf60582e622..7f187b6ff96561 100644 --- a/src/transport/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -43,13 +43,15 @@ using namespace chip::Transport; namespace chip { -CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params) +CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, TransportMgrBase * transportMgr) { CHIP_ERROR err = CHIP_NO_ERROR; - mParams = params; + mParams = params; + mTransportMgr = transportMgr; VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrExit(mTransportMgr != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); // TODO: BLE Should be a transport, in that case, RendezvousSession and BLE should decouple if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle) @@ -73,6 +75,7 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params) } mNetworkProvision.Init(this); + mTransportMgr->SetRendezvousSession(this); exit: return err; @@ -230,11 +233,6 @@ void RendezvousSession::OnRendezvousError(CHIP_ERROR err) UpdateState(State::kInit, err); } -void RendezvousSession::SetTransportMgr(TransportMgrBase * transport) -{ - mTransportMgr = transport; -} - void RendezvousSession::UpdateState(RendezvousSession::State newState, CHIP_ERROR err) { if (mDelegate != nullptr) diff --git a/src/transport/RendezvousSession.h b/src/transport/RendezvousSession.h index dc2fa3a7819ea2..1f40b7633f1bef 100644 --- a/src/transport/RendezvousSession.h +++ b/src/transport/RendezvousSession.h @@ -86,7 +86,7 @@ class RendezvousSession : public SecurePairingSessionDelegate, * * @ return CHIP_ERROR The result of the initialization */ - CHIP_ERROR Init(const RendezvousParameters & params); + CHIP_ERROR Init(const RendezvousParameters & params, TransportMgrBase * transportMgr); /** * @brief @@ -125,7 +125,6 @@ class RendezvousSession : public SecurePairingSessionDelegate, //////////// TransportMgrDelegate Implementation /////////////// void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, System::PacketBuffer * msgBuf) override; - void SetTransportMgr(TransportMgrBase * transport) override; /** * @brief diff --git a/src/transport/SecureSessionMgr.cpp b/src/transport/SecureSessionMgr.cpp index 059d341b15ac48..66745eeb55267d 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -62,14 +62,16 @@ SecureSessionMgr::~SecureSessionMgr() CancelExpiryTimer(); } -CHIP_ERROR SecureSessionMgr::Init(NodeId localNodeId, System::Layer * systemLayer) +CHIP_ERROR SecureSessionMgr::Init(NodeId localNodeId, System::Layer * systemLayer, TransportMgrBase * transportMgr) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mState == State::kNotReady, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(transportMgr != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); - mState = State::kInitialized; - mLocalNodeId = localNodeId; - mSystemLayer = systemLayer; + mState = State::kInitialized; + mLocalNodeId = localNodeId; + mSystemLayer = systemLayer; + mTransportMgr = transportMgr; ChipLogProgress(Inet, "local node id is %llu\n", mLocalNodeId); @@ -80,6 +82,8 @@ CHIP_ERROR SecureSessionMgr::Init(NodeId localNodeId, System::Layer * systemLaye ScheduleExpiryTimer(); + mTransportMgr->SetSecureSessionMgr(this); + exit: return err; } diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index 9e9f8799aaf192..a12b07ead4a5a2 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -150,7 +150,7 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate, public Transpo * @param localNodeId Node id for the current node * @param systemLayer System, layer to use */ - CHIP_ERROR Init(NodeId localNodeId, System::Layer * systemLayer); + CHIP_ERROR Init(NodeId localNodeId, System::Layer * systemLayer, TransportMgrBase * transportMgr); protected: /** @@ -163,11 +163,6 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate, public Transpo */ void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, System::PacketBuffer * msgBuf) override; - /** - * @brief - * Set the transport manager for secure session manager. - */ - void SetTransportMgr(TransportMgrBase * cb) override { mTransportMgr = cb; } private: /** diff --git a/src/transport/TransportMgr.h b/src/transport/TransportMgr.h index 7dda42af0c5653..89a2c54acab404 100644 --- a/src/transport/TransportMgr.h +++ b/src/transport/TransportMgr.h @@ -52,7 +52,7 @@ class TransportMgrDelegate */ virtual void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, System::PacketBuffer * msgBuf) = 0; - virtual void SetTransportMgr(TransportMgrBase * transport) = 0; + // virtual void SetTransportMgr(TransportMgrBase * transport) = 0; }; class TransportMgrBase @@ -66,32 +66,15 @@ class TransportMgrBase void Disconnect(const Transport::PeerAddress & address) { mTransport->Disconnect(address); } - void SetSecureSessionMgr(TransportMgrDelegate * secureSessionMgr) - { - mSecureSessionMgr = secureSessionMgr; - if (mSecureSessionMgr != nullptr) - { - mSecureSessionMgr->SetTransportMgr(this); - } - } + void SetSecureSessionMgr(TransportMgrDelegate * secureSessionMgr) { mSecureSessionMgr = secureSessionMgr; } - void SetRendezvousSession(TransportMgrDelegate * rendezvousSessionMgr) - { - mRendezvous = rendezvousSessionMgr; - if (mRendezvous != nullptr) - { - mRendezvous->SetTransportMgr(this); - } - } + void SetRendezvousSession(TransportMgrDelegate * rendezvousSessionMgr) { mRendezvous = rendezvousSessionMgr; } protected: - void InitInternal(TransportMgrDelegate * secureSessionMgr, TransportMgrDelegate * rendezvousSessionMgr, - Transport::Base * transport) + void InitInternal(Transport::Base * transport) { mTransport = transport; mTransport->SetMessageReceiveHandler(HandleMessageReceived, this); - SetSecureSessionMgr(secureSessionMgr); - SetRendezvousSession(rendezvousSessionMgr); ChipLogDetail(Inet, "TransportMgr initialized"); } @@ -109,13 +92,13 @@ class TransportMgr : public TransportMgrBase { public: template - CHIP_ERROR Init(TransportMgrDelegate * secureMgr, TransportMgrDelegate * rendezvous, Args &&... transportInitArgs) + CHIP_ERROR Init(Args &&... transportInitArgs) { CHIP_ERROR err = CHIP_NO_ERROR; err = mTransport.Init(std::forward(transportInitArgs)...); SuccessOrExit(err); - InitInternal(secureMgr, rendezvous, &mTransport); + InitInternal(&mTransport); exit: return err; } diff --git a/src/transport/tests/TestSecureSessionMgr.cpp b/src/transport/tests/TestSecureSessionMgr.cpp index 06520073ec2615..fcfd880511b053 100644 --- a/src/transport/tests/TestSecureSessionMgr.cpp +++ b/src/transport/tests/TestSecureSessionMgr.cpp @@ -101,9 +101,9 @@ void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext) ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = transportMgr.Init("LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), &transportMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } @@ -128,9 +128,9 @@ void CheckMessageTest(nlTestSuite * inSuite, void * inContext) TransportMgr transportMgr; SecureSessionMgr secureSessionMgr; - err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer()); + err = transportMgr.Init("LOOPBACK"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = transportMgr.Init(&secureSessionMgr, nullptr, "LOOPBACK"); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), &transportMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); callback.mSuite = inSuite; From 4d0c4373fcf2a88f920b20076089925be66dd6c5 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 18 Nov 2020 10:36:32 +0800 Subject: [PATCH 14/17] Fix --- src/transport/RendezvousSession.h | 2 ++ src/transport/SecureSessionMgr.h | 1 + src/transport/TransportMgr.h | 1 - 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/transport/RendezvousSession.h b/src/transport/RendezvousSession.h index 1f40b7633f1bef..9f79908e95e427 100644 --- a/src/transport/RendezvousSession.h +++ b/src/transport/RendezvousSession.h @@ -84,6 +84,8 @@ class RendezvousSession : public SecurePairingSessionDelegate, * @brief * Initialize the underlying transport using the RendezvousParameters passed in the constructor. * + * @param params The RendezvousParameters + * @param transportMgr The transport to use * @ return CHIP_ERROR The result of the initialization */ CHIP_ERROR Init(const RendezvousParameters & params, TransportMgrBase * transportMgr); diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index a12b07ead4a5a2..be30bb93b4e58e 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -149,6 +149,7 @@ class DLL_EXPORT SecureSessionMgr : public Mdns::ResolveDelegate, public Transpo * * @param localNodeId Node id for the current node * @param systemLayer System, layer to use + * @param transportMgr Transport to use */ CHIP_ERROR Init(NodeId localNodeId, System::Layer * systemLayer, TransportMgrBase * transportMgr); diff --git a/src/transport/TransportMgr.h b/src/transport/TransportMgr.h index 89a2c54acab404..a972ea690e893b 100644 --- a/src/transport/TransportMgr.h +++ b/src/transport/TransportMgr.h @@ -52,7 +52,6 @@ class TransportMgrDelegate */ virtual void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, System::PacketBuffer * msgBuf) = 0; - // virtual void SetTransportMgr(TransportMgrBase * transport) = 0; }; class TransportMgrBase From 6270ac4ee0208b2b814241f40187e65713506802 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 18 Nov 2020 10:47:04 +0800 Subject: [PATCH 15/17] Fix tests after merge --- src/messaging/tests/TestExchangeMgr.cpp | 26 ++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/messaging/tests/TestExchangeMgr.cpp b/src/messaging/tests/TestExchangeMgr.cpp index cb6db0bab580aa..379b56c4e7a29a 100644 --- a/src/messaging/tests/TestExchangeMgr.cpp +++ b/src/messaging/tests/TestExchangeMgr.cpp @@ -210,25 +210,29 @@ void CheckExchangeMessages(nlTestSuite * inSuite, void * inContext) TestContext & ctx = *reinterpret_cast(inContext); CHIP_ERROR err; - SecureSessionMgr conn; + TransportMgr transportMgr; + SecureSessionMgr secureSessionMgr; IPAddress addr; IPAddress::FromString("127.0.0.1", addr); - SecurePairingUsingTestSecret pairing1(Optional::Value(kSourceNodeId), 1, 2); - Optional peer1(Transport::PeerAddress::UDP(addr, 1)); - err = conn.NewPairing(peer1, kSourceNodeId, &pairing1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - SecurePairingUsingTestSecret pairing2(Optional::Value(kDestinationNodeId), 2, 1); - Optional peer2(Transport::PeerAddress::UDP(addr, 2)); - err = conn.NewPairing(peer2, kDestinationNodeId, &pairing2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ctx.GetInetLayer().SystemLayer()->Init(nullptr); - err = conn.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), "LOOPBACK"); + err = transportMgr.Init("LOOPBACK"); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = secureSessionMgr.Init(kSourceNodeId, ctx.GetInetLayer().SystemLayer(), &transportMgr); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ExchangeManager exchangeMgr; - err = exchangeMgr.Init(&conn); + err = exchangeMgr.Init(&secureSessionMgr); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + + SecurePairingUsingTestSecret pairing1(Optional::Value(kSourceNodeId), 1, 2); + Optional peer1(Transport::PeerAddress::UDP(addr, 1)); + err = secureSessionMgr.NewPairing(peer1, kSourceNodeId, &pairing1); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + SecurePairingUsingTestSecret pairing2(Optional::Value(kDestinationNodeId), 2, 1); + Optional peer2(Transport::PeerAddress::UDP(addr, 2)); + err = secureSessionMgr.NewPairing(peer2, kDestinationNodeId, &pairing2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // create solicited exchange From 2b2fcbe0b1d826e8b29405828b7006ecd395a051 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 18 Nov 2020 11:03:50 +0800 Subject: [PATCH 16/17] Fix ESP32 Build --- .../esp32/main/RendezvousDeviceDelegate.cpp | 2 +- .../esp32/main/RendezvousDeviceDelegate.cpp | 2 +- src/transport/RendezvousSession.cpp | 22 ++++++++++++++++--- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/examples/all-clusters-app/esp32/main/RendezvousDeviceDelegate.cpp b/examples/all-clusters-app/esp32/main/RendezvousDeviceDelegate.cpp index c735fbea4dc6ef..de539548964c2d 100644 --- a/examples/all-clusters-app/esp32/main/RendezvousDeviceDelegate.cpp +++ b/examples/all-clusters-app/esp32/main/RendezvousDeviceDelegate.cpp @@ -46,7 +46,7 @@ RendezvousDeviceDelegate::RendezvousDeviceDelegate() params.SetSetupPINCode(setupPINCode).SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()); mRendezvousSession = chip::Platform::New(this); - err = mRendezvousSession->Init(params); + err = mRendezvousSession->Init(params, nullptr); exit: if (err != CHIP_NO_ERROR) diff --git a/examples/temperature-measurement-app/esp32/main/RendezvousDeviceDelegate.cpp b/examples/temperature-measurement-app/esp32/main/RendezvousDeviceDelegate.cpp index 66fb309773b97c..f95b23c6f480ee 100644 --- a/examples/temperature-measurement-app/esp32/main/RendezvousDeviceDelegate.cpp +++ b/examples/temperature-measurement-app/esp32/main/RendezvousDeviceDelegate.cpp @@ -44,7 +44,7 @@ RendezvousDeviceDelegate::RendezvousDeviceDelegate() params.SetSetupPINCode(setupPINCode).SetLocalNodeId(kLocalNodeId).SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()); mRendezvousSession = new RendezvousSession(this); - err = mRendezvousSession->Init(params); + err = mRendezvousSession->Init(params, nullptr); exit: if (err != CHIP_NO_ERROR) diff --git a/src/transport/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp index 7f187b6ff96561..df89cd7c66752d 100644 --- a/src/transport/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -51,7 +51,6 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, Transpor mTransportMgr = transportMgr; VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(mTransportMgr != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); // TODO: BLE Should be a transport, in that case, RendezvousSession and BLE should decouple if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle) @@ -75,7 +74,11 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params, Transpor } mNetworkProvision.Init(this); - mTransportMgr->SetRendezvousSession(this); + // TODO: We should assmue mTransportMgr not null for IP rendezvous. + if (mTransportMgr != nullptr) + { + mTransportMgr->SetRendezvousSession(this); + } exit: return err; @@ -102,7 +105,20 @@ CHIP_ERROR RendezvousSession::SendPairingMessage(const PacketHeader & header, He return CHIP_ERROR_INCORRECT_STATE; } - return mTransport->SendMessage(header, payloadFlags, peerAddress, msgBuf.Release()); + if (peerAddress.GetTransportType() == Transport::Type::kBle) + { + + return mTransport->SendMessage(header, payloadFlags, peerAddress, msgBuf.Release()); + } + else if (mTransportMgr != nullptr) + { + return mTransportMgr->SendMessage(header, payloadFlags, peerAddress, msgBuf.Release()); + } + else + { + ChipLogError(Ble, "SendPairingMessage dropped since no transport mgr for IP rendezvous"); + return CHIP_ERROR_INVALID_ADDRESS; + } } CHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgIn) From 38448cd2c9c55353f3ee5cab82c2e3395abe5ea9 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Wed, 18 Nov 2020 22:56:15 +0800 Subject: [PATCH 17/17] InitInternal -> Init --- src/transport/TransportMgr.cpp | 12 ++++++++++++ src/transport/TransportMgr.h | 12 +++--------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/transport/TransportMgr.cpp b/src/transport/TransportMgr.cpp index b4a6262c757fd5..6425866ce79444 100644 --- a/src/transport/TransportMgr.cpp +++ b/src/transport/TransportMgr.cpp @@ -35,6 +35,18 @@ namespace chip { +CHIP_ERROR TransportMgrBase::Init(Transport::Base * transport) +{ + if (mTransport != nullptr) + { + return CHIP_ERROR_INCORRECT_STATE; + } + mTransport = transport; + mTransport->SetMessageReceiveHandler(HandleMessageReceived, this); + ChipLogDetail(Inet, "TransportMgr initialized"); + return CHIP_NO_ERROR; +} + void TransportMgrBase::HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBuffer * msg, TransportMgrBase * dispatcher) { diff --git a/src/transport/TransportMgr.h b/src/transport/TransportMgr.h index a972ea690e893b..af0e3c75ec56e2 100644 --- a/src/transport/TransportMgr.h +++ b/src/transport/TransportMgr.h @@ -57,6 +57,8 @@ class TransportMgrDelegate class TransportMgrBase { public: + CHIP_ERROR Init(Transport::Base * transport); + CHIP_ERROR SendMessage(const PacketHeader & header, Header::Flags payloadFlags, const Transport::PeerAddress & address, System::PacketBuffer * msgBuf) { @@ -69,14 +71,6 @@ class TransportMgrBase void SetRendezvousSession(TransportMgrDelegate * rendezvousSessionMgr) { mRendezvous = rendezvousSessionMgr; } -protected: - void InitInternal(Transport::Base * transport) - { - mTransport = transport; - mTransport->SetMessageReceiveHandler(HandleMessageReceived, this); - ChipLogDetail(Inet, "TransportMgr initialized"); - } - private: static void HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBuffer * msg, TransportMgrBase * dispatcher); @@ -97,7 +91,7 @@ class TransportMgr : public TransportMgrBase err = mTransport.Init(std::forward(transportInitArgs)...); SuccessOrExit(err); - InitInternal(&mTransport); + err = TransportMgrBase::Init(&mTransport); exit: return err; }