From 1360066854eba61024868f997f09c1031ee1b2fd Mon Sep 17 00:00:00 2001 From: Zang MingJie Date: Thu, 18 Nov 2021 00:58:13 +0800 Subject: [PATCH] Refactor/Split ExchangeMgrDelegate (#11789) --- src/app/CASESessionManager.cpp | 12 +- src/app/CASESessionManager.h | 9 +- src/app/DeviceProxy.h | 6 - src/app/OperationalDeviceProxy.cpp | 3 +- src/app/OperationalDeviceProxy.h | 4 +- src/channel/Manager.h | 23 +-- src/controller/CHIPDeviceController.cpp | 20 +-- src/controller/CHIPDeviceController.h | 17 +-- src/controller/CommissioneeDeviceProxy.cpp | 2 +- src/controller/CommissioneeDeviceProxy.h | 6 +- src/controller/tests/data_model/TestRead.cpp | 4 +- src/lib/core/CHIPConfig.h | 18 +++ src/messaging/BUILD.gn | 1 - src/messaging/ExchangeMgr.cpp | 32 +--- src/messaging/ExchangeMgr.h | 20 +-- src/messaging/tests/TestExchangeMgr.cpp | 4 +- src/transport/BUILD.gn | 5 + .../SessionDelegate.h} | 34 ++--- src/transport/SessionManager.cpp | 85 ++++++----- src/transport/SessionManager.h | 137 +++++++++--------- src/transport/SessionMessageDelegate.h | 58 ++++++++ src/transport/tests/TestSessionManager.cpp | 26 ++-- 22 files changed, 278 insertions(+), 248 deletions(-) rename src/{messaging/ExchangeMgrDelegate.h => transport/SessionDelegate.h} (55%) create mode 100644 src/transport/SessionMessageDelegate.h diff --git a/src/app/CASESessionManager.cpp b/src/app/CASESessionManager.cpp index ff152e47e6a22a..a4d3d982f3698f 100644 --- a/src/app/CASESessionManager.cpp +++ b/src/app/CASESessionManager.cpp @@ -111,18 +111,12 @@ CHIP_ERROR CASESessionManager::GetPeerAddress(NodeId nodeId, Transport::PeerAddr return CHIP_NO_ERROR; } -void CASESessionManager::OnNewConnection(SessionHandle sessionHandle, Messaging::ExchangeManager * mgr) -{ - // TODO Update the MRP params based on the MRP params extracted from CASE, when this is available. -} - -void CASESessionManager::OnConnectionExpired(SessionHandle sessionHandle, Messaging::ExchangeManager * mgr) +void CASESessionManager::OnSessionReleased(SessionHandle sessionHandle) { OperationalDeviceProxy * session = FindSession(sessionHandle); - VerifyOrReturn(session != nullptr, - ChipLogDetail(Controller, "OnConnectionExpired was called for unknown device, ignoring it.")); + VerifyOrReturn(session != nullptr, ChipLogDetail(Controller, "OnSessionReleased was called for unknown device, ignoring it.")); - session->OnConnectionExpired(sessionHandle); + session->OnSessionReleased(sessionHandle); } OperationalDeviceProxy * CASESessionManager::FindSession(SessionHandle session) diff --git a/src/app/CASESessionManager.h b/src/app/CASESessionManager.h index 56fbdfca449d2a..bf771945348875 100644 --- a/src/app/CASESessionManager.h +++ b/src/app/CASESessionManager.h @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include @@ -43,7 +43,7 @@ struct CASESessionManagerConfig * 4. During session establishment, trigger node ID resolution (if needed), and update the DNS-SD cache (if resolution is * successful) */ -class CASESessionManager : public Messaging::ExchangeMgrDelegate, public Dnssd::ResolverDelegate +class CASESessionManager : public SessionReleaseDelegate, public Dnssd::ResolverDelegate { public: CASESessionManager() = delete; @@ -91,9 +91,8 @@ class CASESessionManager : public Messaging::ExchangeMgrDelegate, public Dnssd:: */ CHIP_ERROR GetPeerAddress(NodeId nodeId, Transport::PeerAddress & addr); - //////////// ExchangeMgrDelegate Implementation /////////////// - void OnNewConnection(SessionHandle session, Messaging::ExchangeManager * mgr) override; - void OnConnectionExpired(SessionHandle session, Messaging::ExchangeManager * mgr) override; + //////////// SessionReleaseDelegate Implementation /////////////// + void OnSessionReleased(SessionHandle session) override; //////////// ResolverDelegate Implementation /////////////// void OnNodeIdResolved(const Dnssd::ResolvedNodeData & nodeData) override; diff --git a/src/app/DeviceProxy.h b/src/app/DeviceProxy.h index c4ce1c2f64d37c..9e4a6d0b90b659 100644 --- a/src/app/DeviceProxy.h +++ b/src/app/DeviceProxy.h @@ -42,12 +42,6 @@ class DLL_EXPORT DeviceProxy virtual ~DeviceProxy() {} DeviceProxy() {} - /** - * Called when a connection is closing. - * The object releases all resources associated with the connection. - */ - virtual void OnConnectionExpired(SessionHandle session) = 0; - /** * Mark any open session with the device as expired. */ diff --git a/src/app/OperationalDeviceProxy.cpp b/src/app/OperationalDeviceProxy.cpp index 140beb734867c8..bf78d8b014c9a2 100644 --- a/src/app/OperationalDeviceProxy.cpp +++ b/src/app/OperationalDeviceProxy.cpp @@ -229,6 +229,7 @@ void OperationalDeviceProxy::OnSessionEstablished() VerifyOrReturn(mState != State::Uninitialized, ChipLogError(Controller, "OnSessionEstablished was called while the device was not initialized")); + // TODO Update the MRP params based on the MRP params extracted from CASE, when this is available. CHIP_ERROR err = mInitParams.sessionManager->NewPairing( Optional::Value(mDeviceAddress), mPeerId.GetNodeId(), &mCASESession, CryptoContext::SessionRole::kInitiator, mInitParams.fabricInfo->GetFabricIndex()); @@ -267,7 +268,7 @@ void OperationalDeviceProxy::Clear() mInitParams = DeviceProxyInitParams(); } -void OperationalDeviceProxy::OnConnectionExpired(SessionHandle session) +void OperationalDeviceProxy::OnSessionReleased(SessionHandle session) { VerifyOrReturn(mSecureSession.HasValue() && mSecureSession.Value() == session, ChipLogDetail(Controller, "Connection expired, but it doesn't match the current session")); diff --git a/src/app/OperationalDeviceProxy.h b/src/app/OperationalDeviceProxy.h index a9cfa2725dcbd5..a98b96d6f515ef 100644 --- a/src/app/OperationalDeviceProxy.h +++ b/src/app/OperationalDeviceProxy.h @@ -69,7 +69,7 @@ class OperationalDeviceProxy; typedef void (*OnDeviceConnected)(void * context, DeviceProxy * device); typedef void (*OnDeviceConnectionFailure)(void * context, NodeId deviceId, CHIP_ERROR error); -class DLL_EXPORT OperationalDeviceProxy : public DeviceProxy, public SessionEstablishmentDelegate +class DLL_EXPORT OperationalDeviceProxy : public DeviceProxy, SessionReleaseDelegate, public SessionEstablishmentDelegate { public: virtual ~OperationalDeviceProxy(); @@ -113,7 +113,7 @@ class DLL_EXPORT OperationalDeviceProxy : public DeviceProxy, public SessionEsta * Called when a connection is closing. * The object releases all resources associated with the connection. */ - void OnConnectionExpired(SessionHandle session) override; + void OnSessionReleased(SessionHandle session) override; void OnNodeIdResolved(const Dnssd::ResolvedNodeData & nodeResolutionData) { diff --git a/src/channel/Manager.h b/src/channel/Manager.h index caf5035a9862d3..588fa099834292 100644 --- a/src/channel/Manager.h +++ b/src/channel/Manager.h @@ -34,10 +34,13 @@ class ChannelContext; * @brief * This class is used to manage Channel Contexts with other CHIP nodes. */ -class DLL_EXPORT ChannelManager : public ExchangeMgrDelegate +class DLL_EXPORT ChannelManager : public SessionCreationDelegate { public: - ChannelManager(ExchangeManager * exchangeManager) : mExchangeManager(exchangeManager) { exchangeManager->SetDelegate(this); } + ChannelManager(ExchangeManager * exchangeManager) : mExchangeManager(exchangeManager) + { + exchangeManager->GetSessionManager()->RegisterCreationDelegate(*this); + } ChannelManager(const ChannelManager &) = delete; ChannelManager operator=(const ChannelManager &) = delete; @@ -58,10 +61,10 @@ class DLL_EXPORT ChannelManager : public ExchangeMgrDelegate }); } - void OnNewConnection(SessionHandle session, ExchangeManager * mgr) override + void OnNewSession(SessionHandle session) override { mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { - if (context->MatchesSession(session, mgr->GetSessionManager())) + if (context->MatchesSession(session, mExchangeManager->GetSessionManager())) { context->OnNewConnection(session); return false; @@ -70,18 +73,6 @@ class DLL_EXPORT ChannelManager : public ExchangeMgrDelegate }); } - void OnConnectionExpired(SessionHandle session, ExchangeManager * mgr) override - { - mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { - if (context->MatchesSession(session, mgr->GetSessionManager())) - { - context->OnConnectionExpired(session); - return false; - } - return true; - }); - } - private: BitMapObjectPool mChannelContexts; BitMapObjectPool mChannelHandles; diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index a4a168a68956ab..3b84465be3e11e 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -131,10 +131,6 @@ CHIP_ERROR DeviceController::Init(ControllerInitParams params) VerifyOrReturnError(params.systemState->TransportMgr() != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - // TODO Exchange Mgr needs to be able to track multiple delegates. Delegate API should be able to query for the right delegate - // to handle events. - params.systemState->ExchangeMgr()->SetDelegate(this); - #if CHIP_DEVICE_CONFIG_ENABLE_DNSSD Dnssd::Resolver::Instance().Init(params.systemState->InetLayer()); Dnssd::Resolver::Instance().SetResolverDelegate(this); @@ -266,10 +262,10 @@ void DeviceController::ReleaseOperationalDevice(NodeId remoteDeviceId) mCASESessionManager->ReleaseSession(remoteDeviceId); } -void DeviceController::OnConnectionExpired(SessionHandle session, Messaging::ExchangeManager * mgr) +void DeviceController::OnSessionReleased(SessionHandle session) { VerifyOrReturn(mState == State::Initialized, ChipLogError(Controller, "OnConnectionExpired was called in incorrect state")); - mCASESessionManager->OnConnectionExpired(session, mgr); + mCASESessionManager->OnSessionReleased(session); } CHIP_ERROR DeviceController::InitializePairedDeviceList() @@ -544,6 +540,9 @@ CHIP_ERROR DeviceCommissioner::Init(CommissionerInitParams params) { ReturnErrorOnFailure(DeviceController::Init(params)); + params.systemState->SessionMgr()->RegisterCreationDelegate(*this); + params.systemState->SessionMgr()->RegisterReleaseDelegate(*this); + uint16_t nextKeyID = 0; uint16_t size = sizeof(nextKeyID); CHIP_ERROR error = mStorageDelegate->SyncGetKeyValue(kNextAvailableKeyID, &nextKeyID, size); @@ -605,24 +604,25 @@ CHIP_ERROR DeviceCommissioner::Shutdown() return CHIP_NO_ERROR; } -void DeviceCommissioner::OnNewConnection(SessionHandle session, Messaging::ExchangeManager * mgr) +void DeviceCommissioner::OnNewSession(SessionHandle session) { VerifyOrReturn(mState == State::Initialized, ChipLogError(Controller, "OnNewConnection was called in incorrect state")); - CommissioneeDeviceProxy * device = FindCommissioneeDevice(mgr->GetSessionManager()->GetSecureSession(session)->GetPeerNodeId()); + CommissioneeDeviceProxy * device = + FindCommissioneeDevice(mSystemState->SessionMgr()->GetSecureSession(session)->GetPeerNodeId()); VerifyOrReturn(device != nullptr, ChipLogDetail(Controller, "OnNewConnection was called for unknown device, ignoring it.")); device->OnNewConnection(session); } -void DeviceCommissioner::OnConnectionExpired(SessionHandle session, Messaging::ExchangeManager * mgr) +void DeviceCommissioner::OnSessionReleased(SessionHandle session) { VerifyOrReturn(mState == State::Initialized, ChipLogError(Controller, "OnConnectionExpired was called in incorrect state")); CommissioneeDeviceProxy * device = FindCommissioneeDevice(session); VerifyOrReturn(device != nullptr, ChipLogDetail(Controller, "OnConnectionExpired was called for unknown device, ignoring it.")); - device->OnConnectionExpired(session); + device->OnSessionReleased(session); } CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(SessionHandle session) diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 8cf10ea0f8dbb8..29215884e7f3dc 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -48,7 +48,6 @@ #include #include #include -#include #include #include #include @@ -187,7 +186,7 @@ typedef void (*OnOpenCommissioningWindow)(void * context, NodeId deviceId, CHIP_ * and device pairing information for individual devices). Alternatively, this class can retrieve the * relevant information when the application tries to communicate with the device */ -class DLL_EXPORT DeviceController : public Messaging::ExchangeMgrDelegate, +class DLL_EXPORT DeviceController : public SessionReleaseDelegate, #if CHIP_DEVICE_CONFIG_ENABLE_DNSSD public AbstractDnssdDiscoveryController, #endif @@ -376,9 +375,8 @@ class DLL_EXPORT DeviceController : public Messaging::ExchangeMgrDelegate, uint16_t mVendorId; - //////////// ExchangeMgrDelegate Implementation /////////////// - void OnNewConnection(SessionHandle session, Messaging::ExchangeManager * mgr) override {} - void OnConnectionExpired(SessionHandle session, Messaging::ExchangeManager * mgr) override; + //////////// SessionReleaseDelegate Implementation /////////////// + void OnSessionReleased(SessionHandle session) override; #if CHIP_DEVICE_CONFIG_ENABLE_DNSSD //////////// ResolverDelegate Implementation /////////////// @@ -412,12 +410,12 @@ class DLL_EXPORT DeviceController : public Messaging::ExchangeMgrDelegate, * will be stored. */ class DLL_EXPORT DeviceCommissioner : public DeviceController, + public SessionCreationDelegate, #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable public Protocols::UserDirectedCommissioning::InstanceNameResolver, public Protocols::UserDirectedCommissioning::UserConfirmationProvider, #endif public SessionEstablishmentDelegate - { public: DeviceCommissioner(); @@ -624,9 +622,10 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, void OnSessionEstablishmentTimeout(); - //////////// ExchangeMgrDelegate Implementation /////////////// - void OnNewConnection(SessionHandle session, Messaging::ExchangeManager * mgr) override; - void OnConnectionExpired(SessionHandle session, Messaging::ExchangeManager * mgr) override; + //////////// SessionCreationDelegate Implementation /////////////// + void OnNewSession(SessionHandle session) override; + //////////// SessionReleaseDelegate Implementation /////////////// + void OnSessionReleased(SessionHandle session) override; static void OnSessionEstablishmentTimeoutCallback(System::Layer * aLayer, void * aAppState); diff --git a/src/controller/CommissioneeDeviceProxy.cpp b/src/controller/CommissioneeDeviceProxy.cpp index 2cf52d31dccc0d..02394d64090137 100644 --- a/src/controller/CommissioneeDeviceProxy.cpp +++ b/src/controller/CommissioneeDeviceProxy.cpp @@ -92,7 +92,7 @@ void CommissioneeDeviceProxy::OnNewConnection(SessionHandle session) mSecureSession.SetValue(session); } -void CommissioneeDeviceProxy::OnConnectionExpired(SessionHandle session) +void CommissioneeDeviceProxy::OnSessionReleased(SessionHandle session) { VerifyOrReturn(mSecureSession.HasValue() && mSecureSession.Value() == session, ChipLogDetail(Controller, "Connection expired, but it doesn't match the current session")); diff --git a/src/controller/CommissioneeDeviceProxy.h b/src/controller/CommissioneeDeviceProxy.h index 64d4ae27b9dcf4..e4a62c0d82cd68 100644 --- a/src/controller/CommissioneeDeviceProxy.h +++ b/src/controller/CommissioneeDeviceProxy.h @@ -79,7 +79,7 @@ struct ControllerDeviceInitParams Controller::DeviceControllerInteractionModelDelegate * imDelegate = nullptr; }; -class CommissioneeDeviceProxy : public DeviceProxy +class CommissioneeDeviceProxy : public DeviceProxy, public SessionReleaseDelegate { public: ~CommissioneeDeviceProxy(); @@ -165,13 +165,13 @@ class CommissioneeDeviceProxy : public DeviceProxy /** * @brief - * Called when a connection is closing. + * Called when the associated session is released * * The receiver should release all resources associated with the connection. * * @param session A handle to the secure session */ - void OnConnectionExpired(SessionHandle session) override; + void OnSessionReleased(SessionHandle session) override; /** * In case there exists an open session to the device, mark it as expired. diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 763d6a787ea309..aec1d89e7560ef 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -235,7 +235,7 @@ void TestReadInteraction::TestReadTimeout(nlTestSuite * apSuite, void * apContex NL_TEST_ASSERT(apSuite, chip::app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients() == 1); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 2); - ctx.GetExchangeManager().OnConnectionExpired(ctx.GetSessionBobToAlice()); + ctx.GetExchangeManager().ExpireExchangesForSession(ctx.GetSessionBobToAlice()); ctx.DrainAndServiceIO(); @@ -251,7 +251,7 @@ void TestReadInteraction::TestReadTimeout(nlTestSuite * apSuite, void * apContex chip::app::InteractionModelEngine::GetInstance()->GetReportingEngine().Run(); ctx.DrainAndServiceIO(); - ctx.GetExchangeManager().OnConnectionExpired(ctx.GetSessionAliceToBob()); + ctx.GetExchangeManager().ExpireExchangesForSession(ctx.GetSessionAliceToBob()); NL_TEST_ASSERT(apSuite, chip::app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); diff --git a/src/lib/core/CHIPConfig.h b/src/lib/core/CHIPConfig.h index fb9a34afea16c7..ba5208013b410c 100644 --- a/src/lib/core/CHIPConfig.h +++ b/src/lib/core/CHIPConfig.h @@ -2673,6 +2673,24 @@ extern const char CHIP_NON_PRODUCTION_MARKER[]; "Please enable at least one of CHIP_CONFIG_EXAMPLE_ACCESS_CONTROL_FAST_COPY_SUPPORT or CHIP_CONFIG_EXAMPLE_ACCESS_CONTROL_FLEXIBLE_COPY_SUPPORT" #endif +/** + * @def CHIP_CONFIG_MAX_SESSION_CREATION_DELEGATES + * + * @brief Defines the max number of SessionCreationDelegates + */ +#ifndef CHIP_CONFIG_MAX_SESSION_CREATION_DELEGATES +#define CHIP_CONFIG_MAX_SESSION_CREATION_DELEGATES 2 +#endif + +/** + * @def CHIP_CONFIG_MAX_SESSION_RELEASE_DELEGATES + * + * @brief Defines the max number of SessionReleaseDelegate + */ +#ifndef CHIP_CONFIG_MAX_SESSION_RELEASE_DELEGATES +#define CHIP_CONFIG_MAX_SESSION_RELEASE_DELEGATES 2 +#endif + /** * @} */ diff --git a/src/messaging/BUILD.gn b/src/messaging/BUILD.gn index 6b3347ea2ff11e..b96b98b823dbeb 100644 --- a/src/messaging/BUILD.gn +++ b/src/messaging/BUILD.gn @@ -42,7 +42,6 @@ static_library("messaging") { "ExchangeMessageDispatch.h", "ExchangeMgr.cpp", "ExchangeMgr.h", - "ExchangeMgrDelegate.h", "Flags.h", "ReliableMessageContext.cpp", "ReliableMessageContext.h", diff --git a/src/messaging/ExchangeMgr.cpp b/src/messaging/ExchangeMgr.cpp index d562331a9703e1..a8f986b5ab50b7 100644 --- a/src/messaging/ExchangeMgr.cpp +++ b/src/messaging/ExchangeMgr.cpp @@ -59,7 +59,7 @@ namespace Messaging { * prior to use. * */ -ExchangeManager::ExchangeManager() : mDelegate(nullptr), mReliableMessageMgr(mContextPool) +ExchangeManager::ExchangeManager() : mReliableMessageMgr(mContextPool) { mState = State::kState_NotInitialized; } @@ -83,7 +83,8 @@ CHIP_ERROR ExchangeManager::Init(SessionManager * sessionManager) handler.Reset(); } - sessionManager->SetDelegate(this); + sessionManager->RegisterReleaseDelegate(*this); + sessionManager->SetMessageDelegate(this); mReliableMessageMgr.Init(sessionManager->SystemLayer(), sessionManager); ReturnErrorOnFailure(mDefaultExchangeDispatch.Init(mSessionManager)); @@ -105,7 +106,8 @@ CHIP_ERROR ExchangeManager::Shutdown() if (mSessionManager != nullptr) { - mSessionManager->SetDelegate(nullptr); + mSessionManager->SetMessageDelegate(nullptr); + mSessionManager->UnregisterReleaseDelegate(*this); mSessionManager = nullptr; } @@ -152,16 +154,6 @@ CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForType(Protocols return UnregisterUMH(protocolId, static_cast(msgType)); } -void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source) -{ -#if CHIP_ERROR_LOGGING - char srcAddressStr[Transport::PeerAddress::kMaxToStringSize]; - source.ToString(srcAddressStr); - - ChipLogError(ExchangeManager, "Error receiving message from %s: %s", srcAddressStr, ErrorStr(error)); -#endif // CHIP_ERROR_LOGGING -} - CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate) { UnsolicitedMessageHandler * selected = nullptr; @@ -326,21 +318,13 @@ void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const } } -void ExchangeManager::OnNewConnection(SessionHandle session) +void ExchangeManager::OnSessionReleased(SessionHandle session) { - if (mDelegate != nullptr) - { - mDelegate->OnNewConnection(session, this); - } + ExpireExchangesForSession(session); } -void ExchangeManager::OnConnectionExpired(SessionHandle session) +void ExchangeManager::ExpireExchangesForSession(SessionHandle session) { - if (mDelegate != nullptr) - { - mDelegate->OnConnectionExpired(session, this); - } - mContextPool.ForEachActiveObject([&](auto * ec) { if (ec->mSession.HasValue() && ec->mSession.Value() == session) { diff --git a/src/messaging/ExchangeMgr.h b/src/messaging/ExchangeMgr.h index c4a93178e12342..7981b150daeeb5 100644 --- a/src/messaging/ExchangeMgr.h +++ b/src/messaging/ExchangeMgr.h @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -50,7 +49,7 @@ static constexpr int16_t kAnyMessageType = -1; * It works on be behalf of higher layers, creating ExchangeContexts and * handling the registration/unregistration of unsolicited message handlers. */ -class DLL_EXPORT ExchangeManager : public SessionManagerDelegate +class DLL_EXPORT ExchangeManager : public SessionMessageDelegate, public SessionReleaseDelegate { friend class ExchangeContext; @@ -184,10 +183,6 @@ class DLL_EXPORT ExchangeManager : public SessionManagerDelegate */ void CloseAllContextsForDelegate(const ExchangeDelegate * delegate); - // TODO Store more than one delegate and add API to query delegates to check if incoming messages are for them. - // Do the same for the UMHs as well - void SetDelegate(ExchangeMgrDelegate * delegate) { mDelegate = delegate; } - SessionManager * GetSessionManager() const { return mSessionManager; } ReliableMessageMgr * GetReliableMessageMgr() { return &mReliableMessageMgr; }; @@ -198,6 +193,10 @@ class DLL_EXPORT ExchangeManager : public SessionManagerDelegate size_t GetNumActiveExchanges() { return mContextPool.Allocated(); } + // TODO: this should be test only, after OnSessionReleased is move to SessionHandle within the exchange context + // Expire all exchanges associated with the given session + void ExpireExchangesForSession(SessionHandle session); + private: enum class State { @@ -230,7 +229,6 @@ class DLL_EXPORT ExchangeManager : public SessionManagerDelegate uint16_t mNextKeyId; State mState; - ExchangeMgrDelegate * mDelegate; SessionManager * mSessionManager; ReliableMessageMgr mReliableMessageMgr; @@ -245,17 +243,11 @@ class DLL_EXPORT ExchangeManager : public SessionManagerDelegate CHIP_ERROR RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate); CHIP_ERROR UnregisterUMH(Protocols::Id protocolId, int16_t msgType); - void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source) override; - void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, SessionHandle session, const Transport::PeerAddress & source, DuplicateMessage isDuplicate, System::PacketBufferHandle && msgBuf) override; - void OnNewConnection(SessionHandle session) override; -#if CHIP_CONFIG_TEST -public: // Allow OnConnectionExpired to be called directly from tests. -#endif // CHIP_CONFIG_TEST - void OnConnectionExpired(SessionHandle session) override; + void OnSessionReleased(SessionHandle session) override; }; } // namespace Messaging diff --git a/src/messaging/tests/TestExchangeMgr.cpp b/src/messaging/tests/TestExchangeMgr.cpp index c7a80b9a7a7466..52ee2995a161d3 100644 --- a/src/messaging/tests/TestExchangeMgr.cpp +++ b/src/messaging/tests/TestExchangeMgr.cpp @@ -124,7 +124,7 @@ void CheckSessionExpirationBasics(nlTestSuite * inSuite, void * inContext) ExchangeContext * ec1 = ctx.NewExchangeToBob(&sendDelegate); // Expire the session this exchange is supposedly on. - ctx.GetExchangeManager().OnConnectionExpired(ec1->GetSessionHandle()); + ctx.GetExchangeManager().ExpireExchangesForSession(ec1->GetSessionHandle()); MockAppDelegate receiveDelegate; CHIP_ERROR err = @@ -154,7 +154,7 @@ void CheckSessionExpirationTimeout(nlTestSuite * inSuite, void * inContext) // Expire the session this exchange is supposedly on. This should close the // exchange. - ctx.GetExchangeManager().OnConnectionExpired(ec1->GetSessionHandle()); + ctx.GetExchangeManager().ExpireExchangesForSession(ec1->GetSessionHandle()); NL_TEST_ASSERT(inSuite, sendDelegate.IsOnResponseTimeoutCalled); } diff --git a/src/transport/BUILD.gn b/src/transport/BUILD.gn index f7fd12ce73e8c0..e85742aff382a4 100644 --- a/src/transport/BUILD.gn +++ b/src/transport/BUILD.gn @@ -26,18 +26,23 @@ static_library("transport") { "FabricTable.h", "MessageCounter.cpp", "MessageCounter.h", + "MessageCounterManagerInterface.h", "PeerMessageCounter.h", "SecureMessageCodec.cpp", "SecureMessageCodec.h", "SecureSession.h", "SecureSessionTable.h", + "SessionDelegate.h", "SessionHandle.cpp", "SessionHandle.h", "SessionManager.cpp", "SessionManager.h", + "SessionMessageCounter.h", + "SessionMessageDelegate.h", "TransportMgr.h", "TransportMgrBase.cpp", "TransportMgrBase.h", + "UnauthenticatedSessionTable.h", ] cflags = [ "-Wconversion" ] diff --git a/src/messaging/ExchangeMgrDelegate.h b/src/transport/SessionDelegate.h similarity index 55% rename from src/messaging/ExchangeMgrDelegate.h rename to src/transport/SessionDelegate.h index 61de9cd1ed94d6..893b063071ba53 100644 --- a/src/messaging/ExchangeMgrDelegate.h +++ b/src/transport/SessionDelegate.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,45 +14,38 @@ * limitations under the License. */ -/** - * @file - * This file defines the classes corresponding to CHIP Exchange Manager Delegate. - * - */ - #pragma once -#include -#include +#include namespace chip { -namespace Messaging { - -class ExchangeManager; -class DLL_EXPORT ExchangeMgrDelegate +class DLL_EXPORT SessionCreationDelegate { public: - virtual ~ExchangeMgrDelegate() {} + virtual ~SessionCreationDelegate() {} /** * @brief - * Called when a new pairing is being established + * Called when a new session is being established * * @param session The handle to the secure session - * @param mgr A pointer to the ExchangeManager */ - virtual void OnNewConnection(SessionHandle session, ExchangeManager * mgr) {} + virtual void OnNewSession(SessionHandle session) = 0; +}; + +class DLL_EXPORT SessionReleaseDelegate +{ +public: + virtual ~SessionReleaseDelegate() {} /** * @brief - * Called when a connection is closing + * Called when a session is releasing * * @param session The handle to the secure session - * @param mgr A pointer to the ExchangeManager */ - virtual void OnConnectionExpired(SessionHandle session, ExchangeManager * mgr) {} + virtual void OnSessionReleased(SessionHandle session) = 0; }; -} // namespace Messaging } // namespace chip diff --git a/src/transport/SessionManager.cpp b/src/transport/SessionManager.cpp index 94585233b723fa..c3c16b0d505cf6 100644 --- a/src/transport/SessionManager.cpp +++ b/src/transport/SessionManager.cpp @@ -288,12 +288,12 @@ CHIP_ERROR SessionManager::NewPairing(const Optional & p ReturnErrorOnFailure(pairing->DeriveSecureSession(session->GetCryptoContext(), direction)); - if (mCB != nullptr) - { - session->GetSessionMessageCounter().GetPeerMessageCounter().SetCounter(pairing->GetPeerCounter()); - mCB->OnNewConnection( - SessionHandle(session->GetPeerNodeId(), session->GetLocalSessionId(), session->GetPeerSessionId(), fabric)); - } + session->GetSessionMessageCounter().GetPeerMessageCounter().SetCounter(pairing->GetPeerCounter()); + SessionHandle sessionHandle(session->GetPeerNodeId(), session->GetLocalSessionId(), session->GetPeerSessionId(), fabric); + mSessionCreationDelegates.ForEachActiveObject([&](std::reference_wrapper * cb) { + cb->get().OnNewSession(sessionHandle); + return true; + }); return CHIP_NO_ERROR; } @@ -348,13 +348,13 @@ void SessionManager::MessageDispatch(const PacketHeader & packetHeader, const Tr } Transport::UnauthenticatedSessionHandle session = optionalSession.Value(); - SessionManagerDelegate::DuplicateMessage isDuplicate = SessionManagerDelegate::DuplicateMessage::No; + SessionMessageDelegate::DuplicateMessage isDuplicate = SessionMessageDelegate::DuplicateMessage::No; // Verify message counter CHIP_ERROR err = session->GetPeerMessageCounter().VerifyOrTrustFirst(packetHeader.GetMessageCounter()); if (err == CHIP_ERROR_DUPLICATE_MESSAGE_RECEIVED) { - isDuplicate = SessionManagerDelegate::DuplicateMessage::Yes; + isDuplicate = SessionMessageDelegate::DuplicateMessage::Yes; err = CHIP_NO_ERROR; } VerifyOrDie(err == CHIP_NO_ERROR); @@ -364,7 +364,7 @@ void SessionManager::MessageDispatch(const PacketHeader & packetHeader, const Tr PayloadHeader payloadHeader; ReturnOnFailure(payloadHeader.DecodeAndConsume(msg)); - if (isDuplicate == SessionManagerDelegate::DuplicateMessage::Yes) + if (isDuplicate == SessionMessageDelegate::DuplicateMessage::Yes) { ChipLogDetail(Inet, "Received a duplicate message with MessageCounter:" ChipLogFormatMessageCounter @@ -389,35 +389,42 @@ void SessionManager::SecureUnicastMessageDispatch(const PacketHeader & packetHea PayloadHeader payloadHeader; - SessionManagerDelegate::DuplicateMessage isDuplicate = SessionManagerDelegate::DuplicateMessage::No; + SessionMessageDelegate::DuplicateMessage isDuplicate = SessionMessageDelegate::DuplicateMessage::No; - VerifyOrExit(!msg.IsNull(), ChipLogError(Inet, "Secure transport received NULL packet, discarding")); + if (msg.IsNull()) + { + ChipLogError(Inet, "Secure transport received NULL packet, discarding"); + return; + } if (session == nullptr) { ChipLogError(Inet, "Data received on an unknown connection (%d). Dropping it!!", packetHeader.GetSessionId()); - ExitNow(err = CHIP_ERROR_KEY_NOT_FOUND_FROM_PEER); + return; } // Decrypt and verify the message before message counter verification or any further processing. - VerifyOrExit(CHIP_NO_ERROR == SecureMessageCodec::Decrypt(session, payloadHeader, packetHeader, msg), - ChipLogError(Inet, "Secure transport received message, but failed to decode/authenticate it, discarding")); + if (SecureMessageCodec::Decrypt(session, payloadHeader, packetHeader, msg) != CHIP_NO_ERROR) + { + ChipLogError(Inet, "Secure transport received message, but failed to decode/authenticate it, discarding"); + return; + } err = session->GetSessionMessageCounter().GetPeerMessageCounter().Verify(packetHeader.GetMessageCounter()); if (err == CHIP_ERROR_DUPLICATE_MESSAGE_RECEIVED) { - isDuplicate = SessionManagerDelegate::DuplicateMessage::Yes; + isDuplicate = SessionMessageDelegate::DuplicateMessage::Yes; err = CHIP_NO_ERROR; } if (err != CHIP_NO_ERROR) { ChipLogError(Inet, "Message counter verify failed, err = %" CHIP_ERROR_FORMAT, err.Format()); + return; } - SuccessOrExit(err); mSecureSessions.MarkSessionActive(session); - if (isDuplicate == SessionManagerDelegate::DuplicateMessage::Yes && !payloadHeader.NeedsAck()) + if (isDuplicate == SessionMessageDelegate::DuplicateMessage::Yes && !payloadHeader.NeedsAck()) { ChipLogDetail(Inet, "Received a duplicate message with MessageCounter:" ChipLogFormatMessageCounter @@ -427,7 +434,7 @@ void SessionManager::SecureUnicastMessageDispatch(const PacketHeader & packetHea { // If it's a duplicate message, but doesn't require an ack, let's drop it right here to save CPU // cycles on further message processing. - ExitNow(err = CHIP_NO_ERROR); + return; } } @@ -447,30 +454,27 @@ void SessionManager::SecureUnicastMessageDispatch(const PacketHeader & packetHea session->GetFabricIndex()); mCB->OnMessageReceived(packetHeader, payloadHeader, sessionHandle, peerAddress, isDuplicate, std::move(msg)); } - -exit: - if (err != CHIP_NO_ERROR && mCB != nullptr) - { - mCB->OnReceiveError(err, peerAddress); - } } void SessionManager::SecureGroupMessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBufferHandle && msg) { - CHIP_ERROR err = CHIP_NO_ERROR; PayloadHeader payloadHeader; - SessionManagerDelegate::DuplicateMessage isDuplicate = SessionManagerDelegate::DuplicateMessage::No; + SessionMessageDelegate::DuplicateMessage isDuplicate = SessionMessageDelegate::DuplicateMessage::No; FabricIndex fabricIndex = 0; // TODO : remove initialization once GroupDataProvider->Decrypt is implemented // Credentials::GroupDataProvider * groups = Credentials::GetGroupDataProvider(); - VerifyOrExit(!msg.IsNull(), ChipLogError(Inet, "Secure transport received NULL packet, discarding")); + if (!msg.IsNull()) + { + ChipLogError(Inet, "Secure transport received NULL packet, discarding"); + return; + } // Check if Message Header is valid first if (!(packetHeader.IsValidMCSPMsg() || packetHeader.IsValidGroupMsg())) { ChipLogError(Inet, "Invalid condition found in packet header"); - ExitNow(err = CHIP_ERROR_INCORRECT_STATE); + return; } // Trial decryption with GroupDataProvider. TODO: Implement the GroupDataProvider Class @@ -487,20 +491,20 @@ void SessionManager::SecureGroupMessageDispatch(const PacketHeader & packetHeade // MCSP processing.. // } - ExitNow(err = CHIP_NO_ERROR); + return; } // Group Messages should never send an Ack if (payloadHeader.NeedsAck()) { ChipLogError(Inet, "Unexpected ACK requested for group message"); - ExitNow(err = CHIP_ERROR_INCORRECT_STATE); + return; } // TODO: Handle Group message counter here spec 4.7.3 // spec 4.5.1.2 for msg counter - if (isDuplicate == SessionManagerDelegate::DuplicateMessage::Yes) + if (isDuplicate == SessionMessageDelegate::DuplicateMessage::Yes) { ChipLogDetail(Inet, "Received a duplicate message with MessageCounter:" ChipLogFormatMessageCounter @@ -508,7 +512,7 @@ void SessionManager::SecureGroupMessageDispatch(const PacketHeader & packetHeade packetHeader.GetMessageCounter(), ChipLogValueExchangeIdFromReceivedHeader(payloadHeader)); // If it's a duplicate message, let's drop it right here to save CPU cycles - ExitNow(err = CHIP_NO_ERROR); + return; } // TODO: Commit Group Message Counter @@ -518,12 +522,6 @@ void SessionManager::SecureGroupMessageDispatch(const PacketHeader & packetHeade SessionHandle session(packetHeader.GetSourceNodeId().Value(), packetHeader.GetDestinationGroupId().Value(), fabricIndex); mCB->OnMessageReceived(packetHeader, payloadHeader, session, peerAddress, isDuplicate, std::move(msg)); } - -exit: - if (err != CHIP_NO_ERROR && mCB != nullptr) - { - mCB->OnReceiveError(err, peerAddress); - } } void SessionManager::HandleConnectionExpired(const Transport::SecureSession & session) @@ -531,11 +529,12 @@ void SessionManager::HandleConnectionExpired(const Transport::SecureSession & se ChipLogDetail(Inet, "Marking old secure session for device 0x" ChipLogFormatX64 " as expired", ChipLogValueX64(session.GetPeerNodeId())); - if (mCB != nullptr) - { - mCB->OnConnectionExpired(SessionHandle(session.GetPeerNodeId(), session.GetLocalSessionId(), session.GetPeerSessionId(), - session.GetFabricIndex())); - } + SessionHandle sessionHandle(session.GetPeerNodeId(), session.GetLocalSessionId(), session.GetPeerSessionId(), + session.GetFabricIndex()); + mSessionReleaseDelegates.ForEachActiveObject([&](std::reference_wrapper * cb) { + cb->get().OnSessionReleased(sessionHandle); + return true; + }); mTransportMgr->Disconnect(session.GetPeerAddress()); } diff --git a/src/transport/SessionManager.h b/src/transport/SessionManager.h index 0248623ce58720..490ac37e6715a6 100644 --- a/src/transport/SessionManager.h +++ b/src/transport/SessionManager.h @@ -35,7 +35,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -113,67 +115,6 @@ class EncryptedPacketBufferHandle final : private System::PacketBufferHandle EncryptedPacketBufferHandle(PacketBufferHandle && aBuffer) : PacketBufferHandle(std::move(aBuffer)) {} }; -/** - * @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 SessionManager - * is interested in receiving these callbacks, they can specialize this class and handle - * each trigger in their implementation of this class. - */ -class DLL_EXPORT SessionManagerDelegate -{ -public: - enum class DuplicateMessage : uint8_t - { - Yes, - No, - }; - - /** - * @brief - * Called when a new message is received. The function must internally release the - * msgBuf after processing it. - * - * @param packetHeader The message header - * @param payloadHeader The payload header - * @param session The handle to the secure session - * @param source The sender's address - * @param isDuplicate The message is a duplicate of previously received message - * @param msgBuf The received message - */ - virtual void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, SessionHandle session, - const Transport::PeerAddress & source, DuplicateMessage isDuplicate, - System::PacketBufferHandle && msgBuf) - {} - - /** - * @brief - * Called when received message processing resulted in error - * - * @param error error code - * @param source network entity that sent the message - */ - virtual void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source) {} - - /** - * @brief - * Called when a new pairing is being established - * - * @param session The handle to the secure session - */ - virtual void OnNewConnection(SessionHandle session) {} - - /** - * @brief - * Called when a new connection is closing - * - * @param session The handle to the secure session - */ - virtual void OnConnectionExpired(SessionHandle session) {} - - virtual ~SessionManagerDelegate() {} -}; - class DLL_EXPORT SessionManager : public TransportMgrDelegate { public: @@ -202,14 +143,59 @@ class DLL_EXPORT SessionManager : public TransportMgrDelegate Transport::SecureSession * GetSecureSession(SessionHandle session); - /** - * @brief - * Set the callback object. - * - * @details - * Release if there was an existing callback object - */ - void SetDelegate(SessionManagerDelegate * cb) { mCB = cb; } + /// @brief Set the delegate for handling incoming messages. There can be only one message delegate (probably the + /// ExchangeManager) + void SetMessageDelegate(SessionMessageDelegate * cb) { mCB = cb; } + + /// @brief Set the delegate for handling session creation. + void RegisterCreationDelegate(SessionCreationDelegate & cb) + { +#ifndef NDEBUG + mSessionCreationDelegates.ForEachActiveObject([&](std::reference_wrapper * i) { + VerifyOrDie(std::addressof(cb) != std::addressof(i->get())); + return true; + }); +#endif + std::reference_wrapper * slot = mSessionCreationDelegates.CreateObject(cb); + VerifyOrDie(slot != nullptr); + } + + void UnregisterCreationDelegate(SessionCreationDelegate & cb) + { + mSessionCreationDelegates.ForEachActiveObject([&](std::reference_wrapper * i) { + if (std::addressof(cb) == std::addressof(i->get())) + { + mSessionCreationDelegates.ReleaseObject(i); + return false; + } + return true; + }); + } + + /// @brief Set the delegate for handling session release. + void RegisterReleaseDelegate(SessionReleaseDelegate & cb) + { +#ifndef NDEBUG + mSessionReleaseDelegates.ForEachActiveObject([&](std::reference_wrapper * i) { + VerifyOrDie(std::addressof(cb) != std::addressof(i->get())); + return true; + }); +#endif + std::reference_wrapper * slot = mSessionReleaseDelegates.CreateObject(cb); + VerifyOrDie(slot != nullptr); + } + + void UnregisterReleaseDelegate(SessionReleaseDelegate & cb) + { + mSessionReleaseDelegates.ForEachActiveObject([&](std::reference_wrapper * i) { + if (std::addressof(cb) == std::addressof(i->get())) + { + mSessionReleaseDelegates.ReleaseObject(i); + return false; + } + return true; + }); + } /** * @brief @@ -292,7 +278,16 @@ class DLL_EXPORT SessionManager : public TransportMgrDelegate Transport::SecureSessionTable mSecureSessions; // < Active connections to other peers State mState; // < Initialization state of the object - SessionManagerDelegate * mCB = nullptr; + SessionMessageDelegate * mCB = nullptr; + BitMapObjectPool, CHIP_CONFIG_MAX_SESSION_CREATION_DELEGATES> + mSessionCreationDelegates; + + // TODO: This is a temporary solution to release sessions, in the near future, SessionReleaseDelegate will be + // directly associated with the every SessionHandle. Then the callback function is called on over the handle + // delegate directly, in order to prevent dangling handles. + BitMapObjectPool, CHIP_CONFIG_MAX_SESSION_RELEASE_DELEGATES> + mSessionReleaseDelegates; + TransportMgrBase * mTransportMgr = nullptr; Transport::MessageCounterManagerInterface * mMessageCounterManager = nullptr; @@ -324,6 +319,8 @@ class DLL_EXPORT SessionManager : public TransportMgrDelegate void MessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress, System::PacketBufferHandle && msg); + void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source); + static bool IsControlMessage(PayloadHeader & payloadHeader) { return payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncReq) || diff --git a/src/transport/SessionMessageDelegate.h b/src/transport/SessionMessageDelegate.h new file mode 100644 index 00000000000000..afdae243971fef --- /dev/null +++ b/src/transport/SessionMessageDelegate.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { + +/** + * @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 SessionManager + * is interested in receiving these callbacks, they can specialize this class and handle + * each trigger in their implementation of this class. + */ +class DLL_EXPORT SessionMessageDelegate +{ +public: + virtual ~SessionMessageDelegate() {} + + enum class DuplicateMessage : uint8_t + { + Yes, + No, + }; + + /** + * @brief + * Called when a new message is received. The function must internally release the + * msgBuf after processing it. + * + * @param packetHeader The message header + * @param payloadHeader The payload header + * @param session The handle to the secure session + * @param source The sender's address + * @param isDuplicate The message is a duplicate of previously received message + * @param msgBuf The received message + */ + virtual void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, SessionHandle session, + const Transport::PeerAddress & source, DuplicateMessage isDuplicate, + System::PacketBufferHandle && msgBuf) = 0; +}; + +} // namespace chip diff --git a/src/transport/tests/TestSessionManager.cpp b/src/transport/tests/TestSessionManager.cpp index 5c7a9d7ebfda23..b3270936132f87 100644 --- a/src/transport/tests/TestSessionManager.cpp +++ b/src/transport/tests/TestSessionManager.cpp @@ -59,7 +59,7 @@ constexpr NodeId kDestinationNodeId = 111222333; const char LARGE_PAYLOAD[kMaxAppMessageLen + 1] = "test message"; -class TestSessMgrCallback : public SessionManagerDelegate +class TestSessMgrCallback : public SessionCreationDelegate, public SessionReleaseDelegate, public SessionMessageDelegate { public: void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, SessionHandle session, @@ -84,7 +84,7 @@ class TestSessMgrCallback : public SessionManagerDelegate ReceiveHandlerCallCount++; } - void OnNewConnection(SessionHandle session) override + void OnNewSession(SessionHandle session) override { // Preset the MessageCounter if (NewConnectionHandlerCallCount == 0) @@ -93,7 +93,8 @@ class TestSessMgrCallback : public SessionManagerDelegate mLocalToRemoteSession.SetValue(session); NewConnectionHandlerCallCount++; } - void OnConnectionExpired(SessionHandle session) override { mOldConnectionDropped = true; } + + void OnSessionReleased(SessionHandle session) override { mOldConnectionDropped = true; } bool mOldConnectionDropped = false; @@ -106,8 +107,6 @@ class TestSessMgrCallback : public SessionManagerDelegate bool LargeMessageSent = false; }; -TestSessMgrCallback callback; - void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); @@ -131,6 +130,7 @@ void CheckMessageTest(nlTestSuite * inSuite, void * inContext) uint16_t payload_len = sizeof(PAYLOAD); + TestSessMgrCallback callback; callback.LargeMessageSent = false; chip::System::PacketBufferHandle buffer = chip::MessagePacketBuffer::NewWithData(PAYLOAD, payload_len); @@ -152,7 +152,8 @@ void CheckMessageTest(nlTestSuite * inSuite, void * inContext) callback.mSuite = inSuite; - sessionManager.SetDelegate(&callback); + sessionManager.RegisterCreationDelegate(callback); + sessionManager.SetMessageDelegate(&callback); Optional peer(Transport::PeerAddress::UDP(addr, CHIP_PORT)); @@ -218,6 +219,7 @@ void SendEncryptedPacketTest(nlTestSuite * inSuite, void * inContext) uint16_t payload_len = sizeof(PAYLOAD); + TestSessMgrCallback callback; callback.LargeMessageSent = false; chip::System::PacketBufferHandle buffer = chip::MessagePacketBuffer::NewWithData(PAYLOAD, payload_len); @@ -239,7 +241,8 @@ void SendEncryptedPacketTest(nlTestSuite * inSuite, void * inContext) callback.mSuite = inSuite; - sessionManager.SetDelegate(&callback); + sessionManager.RegisterCreationDelegate(callback); + sessionManager.SetMessageDelegate(&callback); Optional peer(Transport::PeerAddress::UDP(addr, CHIP_PORT)); @@ -291,6 +294,7 @@ void SendBadEncryptedPacketTest(nlTestSuite * inSuite, void * inContext) uint16_t payload_len = sizeof(PAYLOAD); + TestSessMgrCallback callback; callback.LargeMessageSent = false; chip::System::PacketBufferHandle buffer = chip::MessagePacketBuffer::NewWithData(PAYLOAD, payload_len); @@ -312,7 +316,8 @@ void SendBadEncryptedPacketTest(nlTestSuite * inSuite, void * inContext) callback.mSuite = inSuite; - sessionManager.SetDelegate(&callback); + sessionManager.RegisterCreationDelegate(callback); + sessionManager.SetMessageDelegate(&callback); Optional peer(Transport::PeerAddress::UDP(addr, CHIP_PORT)); @@ -414,9 +419,12 @@ void StaleConnectionDropTest(nlTestSuite * inSuite, void * inContext) err = sessionManager.Init(ctx.GetInetLayer().SystemLayer(), &transportMgr, &gMessageCounterManager); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + TestSessMgrCallback callback; callback.mSuite = inSuite; - sessionManager.SetDelegate(&callback); + sessionManager.RegisterCreationDelegate(callback); + sessionManager.RegisterReleaseDelegate(callback); + sessionManager.SetMessageDelegate(&callback); Optional peer(Transport::PeerAddress::UDP(addr, CHIP_PORT));