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 03d8e4cbe6d86b..821443ea9793eb 100644 --- a/examples/common/chip-app-server/RendezvousServer.cpp +++ b/examples/common/chip-app-server/RendezvousServer.cpp @@ -55,7 +55,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 a651db2b29f249..da18dc1de7086a 100644 --- a/examples/common/chip-app-server/Server.cpp +++ b/examples/common/chip-app-server/Server.cpp @@ -49,7 +49,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]; @@ -76,20 +76,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; } @@ -103,8 +104,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 @@ -127,6 +127,9 @@ void InitServer() gSessions.SetDelegate(&gCallbacks); + 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 ccb1e8ce14416d..2284d83b5140b8 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -141,6 +141,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); @@ -205,14 +218,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); @@ -227,11 +251,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; @@ -274,10 +305,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); VerifyOrExit(mDeviceAddr != IPAddress::Any, 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( @@ -457,6 +505,9 @@ CHIP_ERROR ChipDeviceController::DisconnectDevice() mRendezvousSession = nullptr; } + mTransportMgr->SetSecureSessionMgr(nullptr); + mTransportMgr->SetRendezvousSession(nullptr); + mConState = kConnectionState_NotConnected; return err; } @@ -614,11 +665,11 @@ void ChipDeviceController::ClearRequestState() } } -void ChipDeviceController::OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgrBase * mgr) {} +void ChipDeviceController::OnNewConnection(Transport::PeerConnectionState * state, SecureSessionMgr * mgr) {} void ChipDeviceController::OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, - SecureSessionMgrBase * mgr) + SecureSessionMgr * mgr) { if (header.GetSourceNodeId().HasValue()) { @@ -644,6 +695,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 c0611c36d0a50d..6a0955ea2a4b97 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; //////////// RendezvousSessionDelegate Implementation /////////////// void OnRendezvousError(CHIP_ERROR err) override; @@ -268,7 +275,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 79828d5743de94..85d3751a35f468 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 502b4623e3c31b..5fce9e3fa3fae2 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); @@ -79,14 +88,15 @@ RendezvousSession::~RendezvousSession() mDelegate = nullptr; } -CHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf) +CHIP_ERROR RendezvousSession::SendMessage(PacketHeader & packetHeader, Header::Flags packetFlags, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) { CHIP_ERROR err = CHIP_NO_ERROR; switch (mCurrentState) { case State::kSecurePairing: - err = SendPairingMessage(msgBuf); + err = SendPairingMessage(packetHeader, packetFlags, peerAddress, msgBuf); break; case State::kNetworkProvisioning: @@ -110,20 +120,37 @@ CHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf) return err; } -CHIP_ERROR RendezvousSession::SendPairingMessage(System::PacketBuffer * msgBuf) +CHIP_ERROR RendezvousSession::SendPairingMessage(PacketHeader & packetHeader, Header::Flags packetFlags, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) { - CHIP_ERROR err = CHIP_NO_ERROR; - PacketHeader header; - uint16_t headerSize = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + uint16_t headerSize = packetHeader.EncodeSizeBytes(); + uint16_t actualEncodedHeaderSize = 0; VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); - err = header.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize); + VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY); + + msgBuf->SetStart(msgBuf->Start() - headerSize); + err = packetHeader.Encode(msgBuf->Start(), msgBuf->DataLength(), &actualEncodedHeaderSize, packetFlags); + SuccessOrExit(err); + VerifyOrExit(headerSize == actualEncodedHeaderSize, err = CHIP_ERROR_INTERNAL); + + err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize); SuccessOrExit(err); msgBuf->ConsumeHead(headerSize); - err = mTransport->SendMessage(header, Header::Flags(), Transport::PeerAddress::BLE(), msgBuf); + + // TODO: This check should be removed after BLE becoming a transport + if (peerAddress.GetTransportType() == Transport::Type::kBle) + { + err = mTransport->SendMessage(packetHeader, Header::Flags(), Transport::PeerAddress::BLE(), msgBuf); + } + else + { + err = mTransportMgr->SendMessage(packetHeader, Header::Flags(), peerAddress, msgBuf); + } msgBuf = nullptr; SuccessOrExit(err); @@ -258,6 +285,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) @@ -282,18 +314,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: @@ -310,28 +344,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; @@ -343,10 +365,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(); @@ -410,7 +428,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 84ac11c7ab60ca..7cf4d975faed32 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,19 @@ class RendezvousSession : public SecurePairingSessionDelegate, SecurePairingSession & GetPairingSession() { return mPairingSession; } //////////// SecurePairingSessionDelegate Implementation /////////////// - CHIP_ERROR SendMessage(System::PacketBuffer * msgBuf) override; + /** + * @brief + * Send message to TransportMgr + * + * @param packetHeader The packetHeader + * @param packetFlags The flags that requires packetHeader set + * @param peerAddress The destination of the packet + * @param msgBuf The message buffer, it will always be released regardless the return value + * + * @return The result of SendMessage + */ + CHIP_ERROR SendMessage(PacketHeader & packetHeader, Header::Flags packetFlags, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msgBuf) override; void OnPairingError(CHIP_ERROR err) override; void OnPairingComplete() override; @@ -100,7 +116,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,12 +141,15 @@ class RendezvousSession : public SecurePairingSessionDelegate, const Inet::IPAddress & GetIPAddress() const { return mNetworkProvision.GetIPAddress(); } private: - CHIP_ERROR SendPairingMessage(System::PacketBuffer * msgBug); - CHIP_ERROR HandlePairingMessage(System::PacketBuffer * msgBug); + CHIP_ERROR SendPairingMessage(PacketHeader & packetHeader, Header::Flags packetFlags, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBug); + CHIP_ERROR HandlePairingMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msgBuf); 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 @@ -135,6 +157,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 3868da7a779fc0..4bcc8496bbe09b 100644 --- a/src/transport/SecurePairingSession.cpp +++ b/src/transport/SecurePairingSession.cpp @@ -187,25 +187,17 @@ CHIP_ERROR SecurePairingSession::AttachHeaderAndSend(uint8_t msgType, System::Pa uint16_t headerSize = payloadHeader.EncodeSizeBytes(); uint16_t actualEncodedHeaderSize = 0; - VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY); - - msgBuf->SetStart(msgBuf->Start() - headerSize); - err = payloadHeader.Encode(msgBuf->Start(), msgBuf->DataLength(), &actualEncodedHeaderSize); - SuccessOrExit(err); - VerifyOrExit(headerSize == actualEncodedHeaderSize, err = CHIP_ERROR_INTERNAL); - - headerSize = packetHeader.EncodeSizeBytes(); - 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); - err = - packetHeader.Encode(msgBuf->Start(), msgBuf->DataLength(), &actualEncodedHeaderSize, payloadHeader.GetEncodePacketFlags()); + err = payloadHeader.Encode(msgBuf->Start(), msgBuf->DataLength(), &actualEncodedHeaderSize); SuccessOrExit(err); VerifyOrExit(headerSize == actualEncodedHeaderSize, err = CHIP_ERROR_INTERNAL); - err = mDelegate->SendMessage(msgBuf); + err = mDelegate->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), mPeerAddress, msgBuf); msgBuf = nullptr; SuccessOrExit(err); @@ -215,8 +207,9 @@ CHIP_ERROR SecurePairingSession::AttachHeaderAndSend(uint8_t msgType, System::Pa 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); @@ -227,6 +220,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); @@ -446,7 +441,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; @@ -462,6 +458,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 3e12ce250f5e16..89a07ab04079b6 100644 --- a/src/transport/SecurePairingSession.h +++ b/src/transport/SecurePairingSession.h @@ -30,6 +30,8 @@ #include #include #include +#include +#include namespace chip { @@ -45,10 +47,17 @@ class DLL_EXPORT SecurePairingSessionDelegate * @brief * Called when pairing session generates a new message that should be sent to peer. * + * @param packetHeader the header of the new message + * @param packetHeaderFlags the flags for adding the header + * @param peerAddress the destination of the message * @param msgBuf the new message that should be sent to the peer * @return CHIP_ERROR Error thrown when sending the message */ - virtual CHIP_ERROR SendMessage(System::PacketBuffer * msgBuf) { return CHIP_NO_ERROR; } + virtual CHIP_ERROR SendMessage(PacketHeader & packetHeader, Header::Flags packetHeaderFlags, + const Transport::PeerAddress & peerAddress, System::PacketBuffer * msgBuf) + { + return CHIP_NO_ERROR; + } /** * @brief @@ -101,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 @@ -111,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 @@ -132,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 @@ -218,6 +231,8 @@ class DLL_EXPORT SecurePairingSession uint16_t mLocalKeyId; uint16_t mPeerKeyId; + + Transport::PeerAddress mPeerAddress; }; /* @@ -259,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 f94aefbb0e3754..1a6e06537bbc94 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -28,8 +28,10 @@ #include #include #include +#include #include #include +#include #include @@ -46,14 +48,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); @@ -61,9 +63,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); ScheduleExpiryTimer(); @@ -72,14 +72,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 = nullptr; @@ -118,6 +118,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); @@ -139,7 +140,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); @@ -164,7 +165,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; @@ -199,24 +258,24 @@ 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; @@ -309,19 +368,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 88330d162192e4..0039dcea659f35 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -40,12 +40,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. */ @@ -64,8 +65,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) {} /** @@ -76,7 +76,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 @@ -85,12 +85,12 @@ 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) {} virtual ~SecureSessionMgrDelegate() {} }; -class DLL_EXPORT SecureSessionMgrBase +class DLL_EXPORT SecureSessionMgr { public: /** @@ -103,8 +103,21 @@ class DLL_EXPORT SecureSessionMgrBase */ CHIP_ERROR SendMessage(NodeId peerNodeId, System::PacketBuffer * msgBuf); CHIP_ERROR SendMessage(PayloadHeader & payloadHeader, NodeId peerNodeId, System::PacketBuffer * msgBuf); - SecureSessionMgrBase(); - virtual ~SecureSessionMgrBase(); + + /** + * @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); + SecureSessionMgr(); + virtual ~SecureSessionMgr(); /** * @brief @@ -115,6 +128,12 @@ class DLL_EXPORT SecureSessionMgrBase */ 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 @@ -132,18 +151,17 @@ class DLL_EXPORT SecureSessionMgrBase */ 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. */ @@ -153,13 +171,13 @@ class DLL_EXPORT SecureSessionMgrBase 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(); @@ -167,13 +185,13 @@ class DLL_EXPORT SecureSessionMgrBase /** 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 @@ -181,38 +199,4 @@ class DLL_EXPORT SecureSessionMgrBase static void ExpiryTimerCallback(System::Layer * layer, void * param, System::Error error); }; -/** - * 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 8cf8c16d542ff3..94d13046f0aec0 100644 --- a/src/transport/tests/TestSecurePairingSession.cpp +++ b/src/transport/tests/TestSecurePairingSession.cpp @@ -39,18 +39,13 @@ using namespace chip; class TestSecurePairingDelegate : public SecurePairingSessionDelegate { public: - CHIP_ERROR SendMessage(System::PacketBuffer * msgBuf) override + CHIP_ERROR SendMessage(PacketHeader & hdr, Header::Flags, const Transport::PeerAddress & peerAddress, + System::PacketBuffer * msgBuf) override { mNumMessageSend++; if (peer != nullptr) { - PacketHeader hdr; - uint16_t headerSize = 0; - - hdr.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize); - msgBuf->ConsumeHead(headerSize); - - return peer->HandlePeerMessage(hdr, msgBuf); + return peer->HandlePeerMessage(hdr, peerAddress, msgBuf); } return mMessageSendError; } @@ -91,12 +86,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); @@ -105,8 +102,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, @@ -123,8 +120,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;