Matter SDK Coverage Report
Current view: top level - controller - CHIPDeviceControllerFactory.cpp (source / functions) Coverage Total Hit
Test: SHA:f84fe08d06f240e801b5d923f8a938a9938ca110 Lines: 0.0 % 267 0
Test Date: 2025-02-22 08:08:07 Functions: 0.0 % 14 0

            Line data    Source code
       1              : /*
       2              :  *
       3              :  *    Copyright (c) 2021 Project CHIP Authors
       4              :  *    All rights reserved.
       5              :  *
       6              :  *    Licensed under the Apache License, Version 2.0 (the "License");
       7              :  *    you may not use this file except in compliance with the License.
       8              :  *    You may obtain a copy of the License at
       9              :  *
      10              :  *        http://www.apache.org/licenses/LICENSE-2.0
      11              :  *
      12              :  *    Unless required by applicable law or agreed to in writing, software
      13              :  *    distributed under the License is distributed on an "AS IS" BASIS,
      14              :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      15              :  *    See the License for the specific language governing permissions and
      16              :  *    limitations under the License.
      17              :  */
      18              : 
      19              : /**
      20              :  *    @file
      21              :  *      Implementation of CHIP Device Controller Factory, a utility/manager class
      22              :  *      that vends Controller objects
      23              :  */
      24              : 
      25              : #include <controller/CHIPDeviceControllerFactory.h>
      26              : 
      27              : #include <app/InteractionModelEngine.h>
      28              : #include <app/OperationalSessionSetup.h>
      29              : #include <app/TimerDelegates.h>
      30              : #include <app/reporting/ReportSchedulerImpl.h>
      31              : #include <app/util/DataModelHandler.h>
      32              : #include <lib/core/ErrorStr.h>
      33              : #include <messaging/ReliableMessageProtocolConfig.h>
      34              : 
      35              : #if CONFIG_DEVICE_LAYER
      36              : #include <platform/CHIPDeviceLayer.h>
      37              : #include <platform/ConfigurationManager.h>
      38              : #endif
      39              : 
      40              : #include <app/server/Dnssd.h>
      41              : #include <protocols/secure_channel/CASEServer.h>
      42              : #include <protocols/secure_channel/SimpleSessionResumptionStorage.h>
      43              : 
      44              : using namespace chip::Inet;
      45              : using namespace chip::System;
      46              : using namespace chip::Credentials;
      47              : 
      48              : namespace chip {
      49              : namespace Controller {
      50              : 
      51            0 : CHIP_ERROR DeviceControllerFactory::Init(FactoryInitParams params)
      52              : {
      53              : 
      54              :     // SystemState is only set the first time init is called, after that it is managed
      55              :     // internally. If SystemState is set then init has already completed.
      56            0 :     if (mSystemState != nullptr)
      57              :     {
      58            0 :         ChipLogError(Controller, "Device Controller Factory already initialized...");
      59            0 :         return CHIP_NO_ERROR;
      60              :     }
      61              : 
      62              :     // Save our initialization state that we can't recover later from a
      63              :     // created-but-shut-down system state.
      64            0 :     mListenPort                = params.listenPort;
      65            0 :     mFabricIndependentStorage  = params.fabricIndependentStorage;
      66            0 :     mOperationalKeystore       = params.operationalKeystore;
      67            0 :     mOpCertStore               = params.opCertStore;
      68            0 :     mCertificateValidityPolicy = params.certificateValidityPolicy;
      69            0 :     mSessionResumptionStorage  = params.sessionResumptionStorage;
      70            0 :     mEnableServerInteractions  = params.enableServerInteractions;
      71              : 
      72              :     // Initialize the system state. Note that it is left in a somewhat
      73              :     // special state where it is initialized, but has a ref count of 0.
      74            0 :     CHIP_ERROR err = InitSystemState(params);
      75              : 
      76            0 :     return err;
      77              : }
      78              : 
      79            0 : CHIP_ERROR DeviceControllerFactory::ReinitSystemStateIfNecessary()
      80              : {
      81            0 :     VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE);
      82            0 :     VerifyOrReturnError(mSystemState->IsShutDown(), CHIP_NO_ERROR);
      83              : 
      84            0 :     FactoryInitParams params;
      85            0 :     params.systemLayer        = mSystemState->SystemLayer();
      86            0 :     params.udpEndPointManager = mSystemState->UDPEndPointManager();
      87              : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
      88            0 :     params.tcpEndPointManager = mSystemState->TCPEndPointManager();
      89              : #endif
      90              : #if CONFIG_NETWORK_LAYER_BLE
      91            0 :     params.bleLayer = mSystemState->BleLayer();
      92              : #endif
      93            0 :     params.listenPort                = mListenPort;
      94            0 :     params.fabricIndependentStorage  = mFabricIndependentStorage;
      95            0 :     params.enableServerInteractions  = mEnableServerInteractions;
      96            0 :     params.groupDataProvider         = mSystemState->GetGroupDataProvider();
      97            0 :     params.sessionKeystore           = mSystemState->GetSessionKeystore();
      98            0 :     params.fabricTable               = mSystemState->Fabrics();
      99            0 :     params.operationalKeystore       = mOperationalKeystore;
     100            0 :     params.opCertStore               = mOpCertStore;
     101            0 :     params.certificateValidityPolicy = mCertificateValidityPolicy;
     102            0 :     params.sessionResumptionStorage  = mSessionResumptionStorage;
     103              : 
     104              :     // re-initialization keeps any previously initialized values. The only place where
     105              :     // a provider exists is in the InteractionModelEngine, so just say "keep it as is".
     106            0 :     params.dataModelProvider = app::InteractionModelEngine::GetInstance()->GetDataModelProvider();
     107              : 
     108            0 :     return InitSystemState(params);
     109              : }
     110              : 
     111            0 : CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params)
     112              : {
     113            0 :     if (mSystemState != nullptr)
     114              :     {
     115            0 :         Platform::Delete(mSystemState);
     116            0 :         mSystemState = nullptr;
     117              :     }
     118              : 
     119            0 :     DeviceControllerSystemStateParams stateParams;
     120              : #if CONFIG_DEVICE_LAYER
     121            0 :     ReturnErrorOnFailure(DeviceLayer::PlatformMgr().InitChipStack());
     122              : 
     123            0 :     stateParams.systemLayer        = &DeviceLayer::SystemLayer();
     124            0 :     stateParams.udpEndPointManager = DeviceLayer::UDPEndPointManager();
     125              : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
     126            0 :     stateParams.tcpEndPointManager = DeviceLayer::TCPEndPointManager();
     127              : #endif
     128              : #else
     129              :     stateParams.systemLayer        = params.systemLayer;
     130              :     stateParams.tcpEndPointManager = params.tcpEndPointManager;
     131              :     stateParams.udpEndPointManager = params.udpEndPointManager;
     132              :     ChipLogError(Controller, "Warning: Device Controller Factory should be with a CHIP Device Layer...");
     133              : #endif // CONFIG_DEVICE_LAYER
     134              : 
     135              : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
     136            0 :     auto tcpListenParams = Transport::TcpListenParameters(stateParams.tcpEndPointManager)
     137            0 :                                .SetAddressType(IPAddressType::kIPv6)
     138            0 :                                .SetListenPort(params.listenPort)
     139            0 :                                .SetServerListenEnabled(false); // Initialize as a TCP Client
     140              : #endif
     141              : 
     142            0 :     if (params.dataModelProvider == nullptr)
     143              :     {
     144            0 :         ChipLogError(AppServer, "Device Controller Factory requires a `dataModelProvider` value.");
     145            0 :         ChipLogError(AppServer, "For backwards compatibility, you likely can use `CodegenDataModelProviderInstance(...)`");
     146              :     }
     147              : 
     148            0 :     VerifyOrReturnError(params.dataModelProvider != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     149            0 :     VerifyOrReturnError(stateParams.systemLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     150            0 :     VerifyOrReturnError(stateParams.udpEndPointManager != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     151              : 
     152              :     // OperationalCertificateStore needs to be provided to init the fabric table if fabric table is
     153              :     // not provided wholesale.
     154            0 :     VerifyOrReturnError((params.fabricTable != nullptr) || (params.opCertStore != nullptr), CHIP_ERROR_INVALID_ARGUMENT);
     155            0 :     VerifyOrReturnError(params.sessionKeystore != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     156              : 
     157              : #if CONFIG_NETWORK_LAYER_BLE
     158              : #if CONFIG_DEVICE_LAYER
     159            0 :     stateParams.bleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer();
     160              : #else
     161              :     stateParams.bleLayer = params.bleLayer;
     162              : #endif // CONFIG_DEVICE_LAYER
     163              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     164              :     stateParams.wifipaf_layer = params.wifipaf_layer;
     165              : #endif
     166            0 :     VerifyOrReturnError(stateParams.bleLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     167              : #endif
     168              : 
     169            0 :     stateParams.transportMgr = chip::Platform::New<DeviceTransportMgr>();
     170              : 
     171              :     //
     172              :     // The logic below expects IPv6 to be at index 0 of this tuple. Please do not alter that.
     173              :     //
     174            0 :     ReturnErrorOnFailure(stateParams.transportMgr->Init(Transport::UdpListenParameters(stateParams.udpEndPointManager)
     175              :                                                             .SetAddressType(Inet::IPAddressType::kIPv6)
     176              :                                                             .SetListenPort(params.listenPort)
     177              : #if INET_CONFIG_ENABLE_IPV4
     178              :                                                             ,
     179              :                                                         Transport::UdpListenParameters(stateParams.udpEndPointManager)
     180              :                                                             .SetAddressType(Inet::IPAddressType::kIPv4)
     181              :                                                             .SetListenPort(params.listenPort)
     182              : #endif
     183              : #if CONFIG_NETWORK_LAYER_BLE
     184              :                                                             ,
     185              :                                                         Transport::BleListenParameters(stateParams.bleLayer)
     186              : #endif
     187              : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
     188              :                                                             ,
     189              :                                                         tcpListenParams
     190              : #endif
     191              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     192              :                                                         ,
     193              :                                                         Transport::WiFiPAFListenParameters()
     194              : #endif
     195              :                                                             ));
     196              : 
     197              :     // TODO(#16231): All the new'ed state above/below in this method is never properly released or null-checked!
     198            0 :     stateParams.sessionMgr                = chip::Platform::New<SessionManager>();
     199            0 :     stateParams.certificateValidityPolicy = params.certificateValidityPolicy;
     200            0 :     stateParams.unsolicitedStatusHandler  = Platform::New<Protocols::SecureChannel::UnsolicitedStatusHandler>();
     201            0 :     stateParams.exchangeMgr               = chip::Platform::New<Messaging::ExchangeManager>();
     202            0 :     stateParams.messageCounterManager     = chip::Platform::New<secure_channel::MessageCounterManager>();
     203            0 :     stateParams.groupDataProvider         = params.groupDataProvider;
     204            0 :     stateParams.timerDelegate             = chip::Platform::New<chip::app::DefaultTimerDelegate>();
     205            0 :     stateParams.reportScheduler           = chip::Platform::New<app::reporting::ReportSchedulerImpl>(stateParams.timerDelegate);
     206            0 :     stateParams.sessionKeystore           = params.sessionKeystore;
     207            0 :     stateParams.bdxTransferServer         = chip::Platform::New<bdx::BDXTransferServer>();
     208              : 
     209              :     // if no fabricTable was provided, create one and track it in stateParams for cleanup
     210            0 :     stateParams.fabricTable = params.fabricTable;
     211              : 
     212            0 :     FabricTable * tempFabricTable = nullptr;
     213            0 :     if (stateParams.fabricTable == nullptr)
     214              :     {
     215              :         // TODO(#16231): Previously (and still) the objects new-ed in this entire method seem expected to last forever...
     216            0 :         auto newFabricTable = Platform::MakeUnique<FabricTable>();
     217            0 :         VerifyOrReturnError(newFabricTable, CHIP_ERROR_NO_MEMORY);
     218              : 
     219            0 :         FabricTable::InitParams fabricTableInitParams;
     220            0 :         fabricTableInitParams.storage             = params.fabricIndependentStorage;
     221            0 :         fabricTableInitParams.operationalKeystore = params.operationalKeystore;
     222            0 :         fabricTableInitParams.opCertStore         = params.opCertStore;
     223            0 :         ReturnErrorOnFailure(newFabricTable->Init(fabricTableInitParams));
     224            0 :         stateParams.fabricTable = newFabricTable.release();
     225            0 :         tempFabricTable         = stateParams.fabricTable;
     226            0 :     }
     227              : 
     228              :     SessionResumptionStorage * sessionResumptionStorage;
     229            0 :     if (params.sessionResumptionStorage == nullptr)
     230              :     {
     231            0 :         auto ownedSessionResumptionStorage = chip::Platform::MakeUnique<SimpleSessionResumptionStorage>();
     232            0 :         ReturnErrorOnFailure(ownedSessionResumptionStorage->Init(params.fabricIndependentStorage));
     233            0 :         stateParams.ownedSessionResumptionStorage    = std::move(ownedSessionResumptionStorage);
     234            0 :         stateParams.externalSessionResumptionStorage = nullptr;
     235            0 :         sessionResumptionStorage                     = stateParams.ownedSessionResumptionStorage.get();
     236            0 :     }
     237              :     else
     238              :     {
     239            0 :         stateParams.ownedSessionResumptionStorage    = nullptr;
     240            0 :         stateParams.externalSessionResumptionStorage = params.sessionResumptionStorage;
     241            0 :         sessionResumptionStorage                     = stateParams.externalSessionResumptionStorage;
     242              :     }
     243              : 
     244            0 :     auto delegate = chip::Platform::MakeUnique<ControllerFabricDelegate>();
     245            0 :     ReturnErrorOnFailure(delegate->Init(sessionResumptionStorage, stateParams.groupDataProvider));
     246            0 :     stateParams.fabricTableDelegate = delegate.get();
     247            0 :     ReturnErrorOnFailure(stateParams.fabricTable->AddFabricDelegate(stateParams.fabricTableDelegate));
     248            0 :     delegate.release();
     249              : 
     250            0 :     ReturnErrorOnFailure(stateParams.sessionMgr->Init(stateParams.systemLayer, stateParams.transportMgr,
     251              :                                                       stateParams.messageCounterManager, params.fabricIndependentStorage,
     252              :                                                       stateParams.fabricTable, *stateParams.sessionKeystore));
     253            0 :     ReturnErrorOnFailure(stateParams.exchangeMgr->Init(stateParams.sessionMgr));
     254            0 :     ReturnErrorOnFailure(stateParams.messageCounterManager->Init(stateParams.exchangeMgr));
     255            0 :     ReturnErrorOnFailure(stateParams.unsolicitedStatusHandler->Init(stateParams.exchangeMgr));
     256            0 :     ReturnErrorOnFailure(stateParams.bdxTransferServer->Init(stateParams.systemLayer, stateParams.exchangeMgr));
     257              : 
     258            0 :     chip::app::InteractionModelEngine * interactionModelEngine = chip::app::InteractionModelEngine::GetInstance();
     259              : 
     260              :     // Initialize the data model now that everything cluster implementations might
     261              :     // depend on is initalized.
     262            0 :     interactionModelEngine->SetDataModelProvider(params.dataModelProvider);
     263              : 
     264            0 :     ReturnErrorOnFailure(Dnssd::Resolver::Instance().Init(stateParams.udpEndPointManager));
     265              : 
     266            0 :     if (params.enableServerInteractions)
     267              :     {
     268            0 :         stateParams.caseServer = chip::Platform::New<CASEServer>();
     269              : 
     270              :         // Enable listening for session establishment messages.
     271            0 :         ReturnErrorOnFailure(stateParams.caseServer->ListenForSessionEstablishment(
     272              :             stateParams.exchangeMgr, stateParams.sessionMgr, stateParams.fabricTable, sessionResumptionStorage,
     273              :             stateParams.certificateValidityPolicy, stateParams.groupDataProvider));
     274              : 
     275              :         //
     276              :         // We need to advertise the port that we're listening to for unsolicited messages over UDP. However, we have both a IPv4
     277              :         // and IPv6 endpoint to pick from. Given that the listen port passed in may be set to 0 (which then has the kernel select
     278              :         // a valid port at bind time), that will result in two possible ports being provided back from the resultant endpoint
     279              :         // initializations. Since IPv6 is POR for Matter, let's go ahead and pick that port.
     280              :         //
     281            0 :         app::DnssdServer::Instance().SetSecuredPort(stateParams.transportMgr->GetTransport().GetImplAtIndex<0>().GetBoundPort());
     282              : 
     283              :         //
     284              :         // TODO: This is a hack to workaround the fact that we have a bi-polar stack that has controller and server modalities that
     285              :         // are mutually exclusive in terms of initialization of key stack singletons. Consequently, DnssdServer accesses
     286              :         // Server::GetInstance().GetFabricTable() to access the fabric table, but we don't want to do that when we're initializing
     287              :         // the controller logic since the factory here has its own fabric table.
     288              :         //
     289              :         // Consequently, reach in set the fabric table pointer to point to the right version.
     290              :         //
     291            0 :         app::DnssdServer::Instance().SetFabricTable(stateParams.fabricTable);
     292              : 
     293              : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
     294              :         // Disable the TCP Server based on the TCPListenParameters setting.
     295            0 :         app::DnssdServer::Instance().SetTCPServerEnabled(tcpListenParams.IsServerListenEnabled());
     296              : #endif
     297              :     }
     298              : 
     299            0 :     stateParams.sessionSetupPool = Platform::New<DeviceControllerSystemStateParams::SessionSetupPool>();
     300            0 :     stateParams.caseClientPool   = Platform::New<DeviceControllerSystemStateParams::CASEClientPool>();
     301              : 
     302              :     CASEClientInitParams sessionInitParams = {
     303            0 :         .sessionManager            = stateParams.sessionMgr,
     304              :         .sessionResumptionStorage  = sessionResumptionStorage,
     305            0 :         .certificateValidityPolicy = stateParams.certificateValidityPolicy,
     306            0 :         .exchangeMgr               = stateParams.exchangeMgr,
     307            0 :         .fabricTable               = stateParams.fabricTable,
     308            0 :         .groupDataProvider         = stateParams.groupDataProvider,
     309              :         // Don't provide an MRP local config, so each CASE initiation will use
     310              :         // the then-current value.
     311              :         .mrpLocalConfig = NullOptional,
     312            0 :     };
     313              : 
     314              :     CASESessionManagerConfig sessionManagerConfig = {
     315              :         .sessionInitParams = sessionInitParams,
     316            0 :         .clientPool        = stateParams.caseClientPool,
     317            0 :         .sessionSetupPool  = stateParams.sessionSetupPool,
     318            0 :     };
     319              : 
     320              :     // TODO: Need to be able to create a CASESessionManagerConfig here!
     321            0 :     stateParams.caseSessionManager = Platform::New<CASESessionManager>();
     322            0 :     ReturnErrorOnFailure(stateParams.caseSessionManager->Init(stateParams.systemLayer, sessionManagerConfig));
     323              : 
     324            0 :     ReturnErrorOnFailure(interactionModelEngine->Init(stateParams.exchangeMgr, stateParams.fabricTable, stateParams.reportScheduler,
     325              :                                                       stateParams.caseSessionManager));
     326              : 
     327              :     // store the system state
     328            0 :     mSystemState = chip::Platform::New<DeviceControllerSystemState>(std::move(stateParams));
     329            0 :     mSystemState->SetTempFabricTable(tempFabricTable, params.enableServerInteractions);
     330            0 :     ChipLogDetail(Controller, "System State Initialized...");
     331            0 :     return CHIP_NO_ERROR;
     332            0 : }
     333              : 
     334            0 : void DeviceControllerFactory::PopulateInitParams(ControllerInitParams & controllerParams, const SetupParams & params)
     335              : {
     336            0 :     controllerParams.operationalCredentialsDelegate       = params.operationalCredentialsDelegate;
     337            0 :     controllerParams.operationalKeypair                   = params.operationalKeypair;
     338            0 :     controllerParams.hasExternallyOwnedOperationalKeypair = params.hasExternallyOwnedOperationalKeypair;
     339            0 :     controllerParams.controllerNOC                        = params.controllerNOC;
     340            0 :     controllerParams.controllerICAC                       = params.controllerICAC;
     341            0 :     controllerParams.controllerRCAC                       = params.controllerRCAC;
     342            0 :     controllerParams.permitMultiControllerFabrics         = params.permitMultiControllerFabrics;
     343            0 :     controllerParams.removeFromFabricTableOnShutdown      = params.removeFromFabricTableOnShutdown;
     344            0 :     controllerParams.deleteFromFabricTableOnShutdown      = params.deleteFromFabricTableOnShutdown;
     345              : 
     346            0 :     controllerParams.systemState        = mSystemState;
     347            0 :     controllerParams.controllerVendorId = params.controllerVendorId;
     348              : 
     349            0 :     controllerParams.enableServerInteractions = params.enableServerInteractions;
     350            0 :     if (params.fabricIndex.HasValue())
     351              :     {
     352            0 :         controllerParams.fabricIndex.SetValue(params.fabricIndex.Value());
     353              :     }
     354            0 : }
     355              : 
     356            0 : void DeviceControllerFactory::ControllerInitialized(const DeviceController & controller)
     357              : {
     358            0 :     if (mEnableServerInteractions && controller.GetFabricIndex() != kUndefinedFabricIndex)
     359              :     {
     360              :         // Restart DNS-SD advertising, because initialization of this controller could
     361              :         // have modified whether a particular fabric identity should be
     362              :         // advertised.  Just calling AdvertiseOperational() is not good enough
     363              :         // here, since we might be removing advertising.
     364            0 :         app::DnssdServer::Instance().StartServer();
     365              :     }
     366            0 : }
     367              : 
     368            0 : CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceController & controller)
     369              : {
     370            0 :     VerifyOrReturnError(params.controllerVendorId != VendorId::Unspecified, CHIP_ERROR_INVALID_ARGUMENT);
     371            0 :     ReturnErrorOnFailure(ReinitSystemStateIfNecessary());
     372              : 
     373            0 :     ControllerInitParams controllerParams;
     374            0 :     PopulateInitParams(controllerParams, params);
     375              : 
     376            0 :     CHIP_ERROR err = controller.Init(controllerParams);
     377              : 
     378            0 :     if (err == CHIP_NO_ERROR)
     379              :     {
     380            0 :         ControllerInitialized(controller);
     381              :     }
     382              : 
     383            0 :     return err;
     384              : }
     385              : 
     386            0 : CHIP_ERROR DeviceControllerFactory::SetupCommissioner(SetupParams params, DeviceCommissioner & commissioner)
     387              : {
     388            0 :     VerifyOrReturnError(params.controllerVendorId != VendorId::Unspecified, CHIP_ERROR_INVALID_ARGUMENT);
     389            0 :     ReturnErrorOnFailure(ReinitSystemStateIfNecessary());
     390              : 
     391            0 :     CommissionerInitParams commissionerParams;
     392              : 
     393              :     // PopulateInitParams works against ControllerInitParams base class of CommissionerInitParams only
     394            0 :     PopulateInitParams(commissionerParams, params);
     395              : 
     396              :     // Set commissioner-specific fields not in ControllerInitParams
     397            0 :     commissionerParams.pairingDelegate           = params.pairingDelegate;
     398            0 :     commissionerParams.defaultCommissioner       = params.defaultCommissioner;
     399            0 :     commissionerParams.deviceAttestationVerifier = params.deviceAttestationVerifier;
     400              : 
     401            0 :     CHIP_ERROR err = commissioner.Init(commissionerParams);
     402              : 
     403            0 :     if (err == CHIP_NO_ERROR)
     404              :     {
     405            0 :         ControllerInitialized(commissioner);
     406              :     }
     407              : 
     408            0 :     return err;
     409              : }
     410              : 
     411            0 : CHIP_ERROR DeviceControllerFactory::ServiceEvents()
     412              : {
     413            0 :     VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE);
     414              : 
     415              : #if CONFIG_DEVICE_LAYER
     416            0 :     ReturnErrorOnFailure(DeviceLayer::PlatformMgr().StartEventLoopTask());
     417              : #endif // CONFIG_DEVICE_LAYER
     418              : 
     419            0 :     return CHIP_NO_ERROR;
     420              : }
     421              : 
     422            0 : void DeviceControllerFactory::RetainSystemState()
     423              : {
     424            0 :     (void) mSystemState->Retain();
     425            0 : }
     426              : 
     427            0 : bool DeviceControllerFactory::ReleaseSystemState()
     428              : {
     429            0 :     return mSystemState->Release();
     430              : }
     431              : 
     432            0 : CHIP_ERROR DeviceControllerFactory::EnsureAndRetainSystemState()
     433              : {
     434            0 :     ReturnErrorOnFailure(ReinitSystemStateIfNecessary());
     435            0 :     RetainSystemState();
     436            0 :     return CHIP_NO_ERROR;
     437              : }
     438              : 
     439            0 : DeviceControllerFactory::~DeviceControllerFactory()
     440              : {
     441            0 :     Shutdown();
     442            0 : }
     443              : 
     444            0 : void DeviceControllerFactory::Shutdown()
     445              : {
     446            0 :     if (mSystemState != nullptr)
     447              :     {
     448              :         // ~DeviceControllerSystemState will call Shutdown(),
     449              :         // which in turn ensures that the reference count is 0.
     450            0 :         Platform::Delete(mSystemState);
     451            0 :         mSystemState = nullptr;
     452              :     }
     453            0 :     mFabricIndependentStorage  = nullptr;
     454            0 :     mOperationalKeystore       = nullptr;
     455            0 :     mOpCertStore               = nullptr;
     456            0 :     mCertificateValidityPolicy = nullptr;
     457            0 :     mSessionResumptionStorage  = nullptr;
     458            0 : }
     459              : 
     460            0 : void DeviceControllerSystemState::Shutdown()
     461              : {
     462            0 :     VerifyOrDie(mRefCount == 0);
     463            0 :     if (mHaveShutDown)
     464              :     {
     465              :         // Nothing else to do here.
     466            0 :         return;
     467              :     }
     468            0 :     mHaveShutDown = true;
     469              : 
     470            0 :     ChipLogDetail(Controller, "Shutting down the System State, this will teardown the CHIP Stack");
     471              : 
     472            0 :     if (mTempFabricTable && mEnableServerInteractions)
     473              :     {
     474              :         // The DnssdServer is holding a reference to our temp fabric table,
     475              :         // which we are about to destroy.  Stop it, so that it will stop trying
     476              :         // to use it.
     477            0 :         app::DnssdServer::Instance().StopServer();
     478              :     }
     479              : 
     480            0 :     if (mFabricTableDelegate != nullptr)
     481              :     {
     482            0 :         if (mFabrics != nullptr)
     483              :         {
     484            0 :             mFabrics->RemoveFabricDelegate(mFabricTableDelegate);
     485              :         }
     486              : 
     487            0 :         chip::Platform::Delete(mFabricTableDelegate);
     488            0 :         mFabricTableDelegate = nullptr;
     489              :     }
     490              : 
     491            0 :     if (mBDXTransferServer != nullptr)
     492              :     {
     493            0 :         mBDXTransferServer->Shutdown();
     494            0 :         chip::Platform::Delete(mBDXTransferServer);
     495            0 :         mBDXTransferServer = nullptr;
     496              :     }
     497              : 
     498            0 :     if (mCASEServer != nullptr)
     499              :     {
     500            0 :         mCASEServer->Shutdown();
     501            0 :         chip::Platform::Delete(mCASEServer);
     502            0 :         mCASEServer = nullptr;
     503              :     }
     504              : 
     505            0 :     if (mCASESessionManager != nullptr)
     506              :     {
     507            0 :         mCASESessionManager->Shutdown();
     508            0 :         Platform::Delete(mCASESessionManager);
     509            0 :         mCASESessionManager = nullptr;
     510              :     }
     511              : 
     512              :     // The above took care of CASE handshakes, and shutting down all the
     513              :     // controllers should have taken care of the PASE handshakes.  Clean up any
     514              :     // outstanding secure sessions (shouldn't really be any, since controllers
     515              :     // should have handled that, but just in case).
     516            0 :     if (mSessionMgr != nullptr)
     517              :     {
     518            0 :         mSessionMgr->ExpireAllSecureSessions();
     519              :     }
     520              : 
     521              :     // mCASEClientPool and mSessionSetupPool must be deallocated
     522              :     // after mCASESessionManager, which uses them.
     523              : 
     524            0 :     if (mSessionSetupPool != nullptr)
     525              :     {
     526            0 :         Platform::Delete(mSessionSetupPool);
     527            0 :         mSessionSetupPool = nullptr;
     528              :     }
     529              : 
     530            0 :     if (mCASEClientPool != nullptr)
     531              :     {
     532            0 :         Platform::Delete(mCASEClientPool);
     533            0 :         mCASEClientPool = nullptr;
     534              :     }
     535              : 
     536            0 :     Dnssd::Resolver::Instance().Shutdown();
     537              : 
     538              :     // Shut down the interaction model
     539            0 :     app::InteractionModelEngine::GetInstance()->Shutdown();
     540              : 
     541              :     // Shut down the TransportMgr. This holds Inet::UDPEndPoints so it must be shut down
     542              :     // before PlatformMgr().Shutdown() shuts down Inet.
     543            0 :     if (mTransportMgr != nullptr)
     544              :     {
     545            0 :         mTransportMgr->Close();
     546            0 :         chip::Platform::Delete(mTransportMgr);
     547            0 :         mTransportMgr = nullptr;
     548              :     }
     549              : 
     550            0 :     if (mExchangeMgr != nullptr)
     551              :     {
     552            0 :         mExchangeMgr->Shutdown();
     553              :     }
     554            0 :     if (mSessionMgr != nullptr)
     555              :     {
     556            0 :         mSessionMgr->Shutdown();
     557              :     }
     558              : 
     559            0 :     mSystemLayer        = nullptr;
     560            0 :     mUDPEndPointManager = nullptr;
     561              : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
     562            0 :     mTCPEndPointManager = nullptr;
     563              : #endif
     564              : #if CONFIG_NETWORK_LAYER_BLE
     565            0 :     mBleLayer = nullptr;
     566              : #endif // CONFIG_NETWORK_LAYER_BLE
     567              : 
     568            0 :     if (mMessageCounterManager != nullptr)
     569              :     {
     570            0 :         chip::Platform::Delete(mMessageCounterManager);
     571            0 :         mMessageCounterManager = nullptr;
     572              :     }
     573              : 
     574            0 :     if (mExchangeMgr != nullptr)
     575              :     {
     576            0 :         chip::Platform::Delete(mExchangeMgr);
     577            0 :         mExchangeMgr = nullptr;
     578              :     }
     579              : 
     580            0 :     if (mUnsolicitedStatusHandler != nullptr)
     581              :     {
     582            0 :         Platform::Delete(mUnsolicitedStatusHandler);
     583            0 :         mUnsolicitedStatusHandler = nullptr;
     584              :     }
     585              : 
     586            0 :     if (mSessionMgr != nullptr)
     587              :     {
     588            0 :         chip::Platform::Delete(mSessionMgr);
     589            0 :         mSessionMgr = nullptr;
     590              :     }
     591              : 
     592            0 :     if (mReportScheduler != nullptr)
     593              :     {
     594            0 :         chip::Platform::Delete(mReportScheduler);
     595            0 :         mReportScheduler = nullptr;
     596              :     }
     597              : 
     598            0 :     if (mTimerDelegate != nullptr)
     599              :     {
     600            0 :         chip::Platform::Delete(mTimerDelegate);
     601            0 :         mTimerDelegate = nullptr;
     602              :     }
     603              : 
     604            0 :     if (mTempFabricTable != nullptr)
     605              :     {
     606            0 :         mTempFabricTable->Shutdown();
     607            0 :         chip::Platform::Delete(mTempFabricTable);
     608            0 :         mTempFabricTable = nullptr;
     609              :         // if we created a temp fabric table, then mFabrics points to it.
     610              :         // if we did not create a temp fabric table, then keep the reference
     611              :         // so that SetupController/Commissioner can use it
     612            0 :         mFabrics = nullptr;
     613              :     }
     614              : 
     615              : #if CONFIG_DEVICE_LAYER
     616              :     //
     617              :     // We can safely call PlatformMgr().Shutdown(), which like DeviceController::Shutdown(),
     618              :     // expects to be called with external thread synchronization and will not try to acquire the
     619              :     // stack lock.
     620              :     //
     621              :     // Actually stopping the event queue is a separable call that applications will have to sequence.
     622              :     // Consumers are expected to call PlaformMgr().StopEventLoopTask() before calling
     623              :     // DeviceController::Shutdown() in the CONFIG_DEVICE_LAYER configuration
     624              :     //
     625            0 :     DeviceLayer::PlatformMgr().Shutdown();
     626              : #endif
     627              : }
     628              : 
     629              : } // namespace Controller
     630              : } // namespace chip
        

Generated by: LCOV version 2.0-1