LCOV - code coverage report
Current view: top level - app/server - Server.h (source / functions) Hit Total Coverage
Test: lcov_final.info Lines: 18 84 21.4 %
Date: 2024-02-15 08:20:41 Functions: 12 26 46.2 %

          Line data    Source code
       1             : /*
       2             :  *
       3             :  *    Copyright (c) 2020 Project CHIP Authors
       4             :  *
       5             :  *    Licensed under the Apache License, Version 2.0 (the "License");
       6             :  *    you may not use this file except in compliance with the License.
       7             :  *    You may obtain a copy of the License at
       8             :  *
       9             :  *        http://www.apache.org/licenses/LICENSE-2.0
      10             :  *
      11             :  *    Unless required by applicable law or agreed to in writing, software
      12             :  *    distributed under the License is distributed on an "AS IS" BASIS,
      13             :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      14             :  *    See the License for the specific language governing permissions and
      15             :  *    limitations under the License.
      16             :  */
      17             : 
      18             : #pragma once
      19             : 
      20             : #include <app/AppConfig.h>
      21             : #include <app/icd/server/ICDServerConfig.h>
      22             : 
      23             : #include <access/AccessControl.h>
      24             : #include <access/examples/ExampleAccessControlDelegate.h>
      25             : #include <app/CASEClientPool.h>
      26             : #include <app/CASESessionManager.h>
      27             : #include <app/DefaultAttributePersistenceProvider.h>
      28             : #include <app/FailSafeContext.h>
      29             : #include <app/OperationalSessionSetupPool.h>
      30             : #include <app/SimpleSubscriptionResumptionStorage.h>
      31             : #include <app/TestEventTriggerDelegate.h>
      32             : #include <app/server/AclStorage.h>
      33             : #include <app/server/AppDelegate.h>
      34             : #include <app/server/CommissioningWindowManager.h>
      35             : #include <app/server/DefaultAclStorage.h>
      36             : #include <credentials/CertificateValidityPolicy.h>
      37             : #include <credentials/FabricTable.h>
      38             : #include <credentials/GroupDataProvider.h>
      39             : #include <credentials/GroupDataProviderImpl.h>
      40             : #include <credentials/OperationalCertificateStore.h>
      41             : #include <credentials/PersistentStorageOpCertStore.h>
      42             : #include <crypto/DefaultSessionKeystore.h>
      43             : #include <crypto/OperationalKeystore.h>
      44             : #include <crypto/PersistentStorageOperationalKeystore.h>
      45             : #include <inet/InetConfig.h>
      46             : #include <lib/core/CHIPConfig.h>
      47             : #include <lib/support/SafeInt.h>
      48             : #include <messaging/ExchangeMgr.h>
      49             : #include <platform/DeviceInstanceInfoProvider.h>
      50             : #include <platform/KeyValueStoreManager.h>
      51             : #include <platform/KvsPersistentStorageDelegate.h>
      52             : #include <protocols/secure_channel/CASEServer.h>
      53             : #include <protocols/secure_channel/MessageCounterManager.h>
      54             : #include <protocols/secure_channel/PASESession.h>
      55             : #include <protocols/secure_channel/RendezvousParameters.h>
      56             : #include <protocols/secure_channel/UnsolicitedStatusHandler.h>
      57             : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
      58             : #include <protocols/secure_channel/SimpleSessionResumptionStorage.h>
      59             : #endif
      60             : #include <protocols/user_directed_commissioning/UserDirectedCommissioning.h>
      61             : #include <system/SystemClock.h>
      62             : #include <transport/SessionManager.h>
      63             : #include <transport/TransportMgr.h>
      64             : #include <transport/TransportMgrBase.h>
      65             : #if CONFIG_NETWORK_LAYER_BLE
      66             : #include <transport/raw/BLE.h>
      67             : #endif
      68             : #include <app/TimerDelegates.h>
      69             : #include <app/reporting/ReportSchedulerImpl.h>
      70             : #include <transport/raw/UDP.h>
      71             : 
      72             : #if CHIP_CONFIG_ENABLE_ICD_SERVER
      73             : #include <app/icd/server/ICDManager.h> // nogncheck
      74             : #endif
      75             : 
      76             : namespace chip {
      77             : 
      78             : inline constexpr size_t kMaxBlePendingPackets = 1;
      79             : 
      80             : //
      81             : // NOTE: Please do not alter the order of template specialization here as the logic
      82             : //       in the Server impl depends on this.
      83             : //
      84             : using ServerTransportMgr = chip::TransportMgr<chip::Transport::UDP
      85             : #if INET_CONFIG_ENABLE_IPV4
      86             :                                               ,
      87             :                                               chip::Transport::UDP
      88             : #endif
      89             : #if CONFIG_NETWORK_LAYER_BLE
      90             :                                               ,
      91             :                                               chip::Transport::BLE<kMaxBlePendingPackets>
      92             : #endif
      93             :                                               >;
      94             : 
      95             : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
      96             : using UdcTransportMgr = TransportMgr<Transport::UDP /* IPv6 */
      97             : #if INET_CONFIG_ENABLE_IPV4
      98             :                                      ,
      99             :                                      Transport::UDP /* IPv4 */
     100             : #endif
     101             :                                      >;
     102             : #endif
     103             : 
     104             : struct ServerInitParams
     105             : {
     106             :     ServerInitParams() = default;
     107             : 
     108             :     // Not copyable
     109             :     ServerInitParams(const ServerInitParams &)             = delete;
     110             :     ServerInitParams & operator=(const ServerInitParams &) = delete;
     111             : 
     112             :     // Application delegate to handle some commissioning lifecycle events
     113             :     AppDelegate * appDelegate = nullptr;
     114             :     // Port to use for Matter commissioning/operational traffic
     115             :     uint16_t operationalServicePort = CHIP_PORT;
     116             :     // Port to use for UDC if supported
     117             :     uint16_t userDirectedCommissioningPort = CHIP_UDC_PORT;
     118             :     // Interface on which to run daemon
     119             :     Inet::InterfaceId interfaceId = Inet::InterfaceId::Null();
     120             : 
     121             :     // Persistent storage delegate: MUST be injected. Used to maintain storage by much common code.
     122             :     // Must be initialized before being provided.
     123             :     PersistentStorageDelegate * persistentStorageDelegate = nullptr;
     124             :     // Session resumption storage: Optional. Support session resumption when provided.
     125             :     // Must be initialized before being provided.
     126             :     SessionResumptionStorage * sessionResumptionStorage = nullptr;
     127             :     // Session resumption storage: Optional. Support session resumption when provided.
     128             :     // Must be initialized before being provided.
     129             :     app::SubscriptionResumptionStorage * subscriptionResumptionStorage = nullptr;
     130             :     // Certificate validity policy: Optional. If none is injected, CHIPCert
     131             :     // enforces a default policy.
     132             :     Credentials::CertificateValidityPolicy * certificateValidityPolicy = nullptr;
     133             :     // Group data provider: MUST be injected. Used to maintain critical keys such as the Identity
     134             :     // Protection Key (IPK) for CASE. Must be initialized before being provided.
     135             :     Credentials::GroupDataProvider * groupDataProvider = nullptr;
     136             :     // Session keystore: MUST be injected. Used to derive and manage lifecycle of symmetric keys.
     137             :     Crypto::SessionKeystore * sessionKeystore = nullptr;
     138             :     // Access control delegate: MUST be injected. Used to look up access control rules. Must be
     139             :     // initialized before being provided.
     140             :     Access::AccessControl::Delegate * accessDelegate = nullptr;
     141             :     // ACL storage: MUST be injected. Used to store ACL entries in persistent storage. Must NOT
     142             :     // be initialized before being provided.
     143             :     app::AclStorage * aclStorage = nullptr;
     144             :     // Network native params can be injected depending on the
     145             :     // selected Endpoint implementation
     146             :     void * endpointNativeParams = nullptr;
     147             :     // Optional. Support test event triggers when provided. Must be initialized before being
     148             :     // provided.
     149             :     TestEventTriggerDelegate * testEventTriggerDelegate = nullptr;
     150             :     // Operational keystore with access to the operational keys: MUST be injected.
     151             :     Crypto::OperationalKeystore * operationalKeystore = nullptr;
     152             :     // Operational certificate store with access to the operational certs in persisted storage:
     153             :     // must not be null at timne of Server::Init().
     154             :     Credentials::OperationalCertificateStore * opCertStore = nullptr;
     155             :     // Required, if not provided, the Server::Init() WILL fail.
     156             :     app::reporting::ReportScheduler * reportScheduler = nullptr;
     157             : };
     158             : 
     159             : /**
     160             :  * Transitional version of ServerInitParams to assist SDK integrators in
     161             :  * transitioning to injecting product/platform-owned resources. This version
     162             :  * of `ServerInitParams` statically owns and initializes (via the
     163             :  * `InitializeStaticResourcesBeforeServerInit()` method) the persistent storage
     164             :  * delegate, the group data provider, and the access control delegate. This is to reduce
     165             :  * the amount of copied boilerplate in all the example initializations (e.g. AppTask.cpp,
     166             :  * main.cpp).
     167             :  *
     168             :  * This version SHOULD BE USED ONLY FOR THE IN-TREE EXAMPLES.
     169             :  *
     170             :  * ACTION ITEMS FOR TRANSITION from a example in-tree to a product:
     171             :  *
     172             :  * While this could be used indefinitely, it does not exemplify orderly management of
     173             :  * application-injected resources. It is recommended for actual products to instead:
     174             :  *   - Use the basic ServerInitParams in the application
     175             :  *   - Have the application own an instance of the resources being injected in its own
     176             :  *     state (e.g. an implementation of PersistentStorageDelegate and GroupDataProvider
     177             :  *     interfaces).
     178             :  *   - Initialize the injected resources prior to calling Server::Init()
     179             :  *   - De-initialize the injected resources after calling Server::Shutdown()
     180             :  *
     181             :  * WARNING: DO NOT replicate the pattern shown here of having a subclass of ServerInitParams
     182             :  *          own the resources outside of examples. This was done to reduce the amount of change
     183             :  *          to existing examples while still supporting non-example versions of the
     184             :  *          resources to be injected.
     185             :  */
     186             : struct CommonCaseDeviceServerInitParams : public ServerInitParams
     187             : {
     188             :     CommonCaseDeviceServerInitParams() = default;
     189             : 
     190             :     // Not copyable
     191             :     CommonCaseDeviceServerInitParams(const CommonCaseDeviceServerInitParams &)             = delete;
     192             :     CommonCaseDeviceServerInitParams & operator=(const CommonCaseDeviceServerInitParams &) = delete;
     193             : 
     194             :     /**
     195             :      * Call this before Server::Init() to initialize the internally-owned resources.
     196             :      * Server::Init() will fail if this is not done, since several params required to
     197             :      * be non-null will be null without calling this method. ** See the transition method
     198             :      * in the outer comment of this class **.
     199             :      *
     200             :      * @return CHIP_NO_ERROR on success or a CHIP_ERROR value from APIs called to initialize
     201             :      *         resources on failure.
     202             :      */
     203             :     CHIP_ERROR InitializeStaticResourcesBeforeServerInit()
     204             :     {
     205             :         // KVS-based persistent storage delegate injection
     206             :         if (persistentStorageDelegate == nullptr)
     207             :         {
     208             :             chip::DeviceLayer::PersistedStorage::KeyValueStoreManager & kvsManager =
     209             :                 DeviceLayer::PersistedStorage::KeyValueStoreMgr();
     210             :             ReturnErrorOnFailure(sKvsPersistenStorageDelegate.Init(&kvsManager));
     211             :             this->persistentStorageDelegate = &sKvsPersistenStorageDelegate;
     212             :         }
     213             : 
     214             :         // PersistentStorageDelegate "software-based" operational key access injection
     215             :         if (this->operationalKeystore == nullptr)
     216             :         {
     217             :             // WARNING: PersistentStorageOperationalKeystore::Finish() is never called. It's fine for
     218             :             //          for examples and for now.
     219             :             ReturnErrorOnFailure(sPersistentStorageOperationalKeystore.Init(this->persistentStorageDelegate));
     220             :             this->operationalKeystore = &sPersistentStorageOperationalKeystore;
     221             :         }
     222             : 
     223             :         // OpCertStore can be injected but default to persistent storage default
     224             :         // for simplicity of the examples.
     225             :         if (this->opCertStore == nullptr)
     226             :         {
     227             :             // WARNING: PersistentStorageOpCertStore::Finish() is never called. It's fine for
     228             :             //          for examples and for now, since all storage is immediate for that impl.
     229             :             ReturnErrorOnFailure(sPersistentStorageOpCertStore.Init(this->persistentStorageDelegate));
     230             :             this->opCertStore = &sPersistentStorageOpCertStore;
     231             :         }
     232             : 
     233             :         // Injection of report scheduler WILL lead to two schedulers being allocated. As recommended above, this should only be used
     234             :         // for IN-TREE examples. If a default scheduler is desired, the basic ServerInitParams should be used by the application and
     235             :         // CommonCaseDeviceServerInitParams should not be allocated.
     236             :         if (this->reportScheduler == nullptr)
     237             :         {
     238             :             reportScheduler = &sReportScheduler;
     239             :         }
     240             : 
     241             :         // Session Keystore injection
     242             :         this->sessionKeystore = &sSessionKeystore;
     243             : 
     244             :         // Group Data provider injection
     245             :         sGroupDataProvider.SetStorageDelegate(this->persistentStorageDelegate);
     246             :         sGroupDataProvider.SetSessionKeystore(this->sessionKeystore);
     247             :         ReturnErrorOnFailure(sGroupDataProvider.Init());
     248             :         this->groupDataProvider = &sGroupDataProvider;
     249             : 
     250             : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
     251             :         ReturnErrorOnFailure(sSessionResumptionStorage.Init(this->persistentStorageDelegate));
     252             :         this->sessionResumptionStorage = &sSessionResumptionStorage;
     253             : #else
     254             :         this->sessionResumptionStorage = nullptr;
     255             : #endif
     256             : 
     257             :         // Inject access control delegate
     258             :         this->accessDelegate = Access::Examples::GetAccessControlDelegate();
     259             : 
     260             :         // Inject ACL storage. (Don't initialize it.)
     261             :         this->aclStorage = &sAclStorage;
     262             : 
     263             : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
     264             :         ChipLogProgress(AppServer, "Initializing subscription resumption storage...");
     265             :         ReturnErrorOnFailure(sSubscriptionResumptionStorage.Init(this->persistentStorageDelegate));
     266             :         this->subscriptionResumptionStorage = &sSubscriptionResumptionStorage;
     267             : #else
     268             :         ChipLogProgress(AppServer, "Subscription persistence not supported");
     269             : #endif
     270             : 
     271             :         return CHIP_NO_ERROR;
     272             :     }
     273             : 
     274             : private:
     275             :     static KvsPersistentStorageDelegate sKvsPersistenStorageDelegate;
     276             :     static PersistentStorageOperationalKeystore sPersistentStorageOperationalKeystore;
     277             :     static Credentials::PersistentStorageOpCertStore sPersistentStorageOpCertStore;
     278             :     static Credentials::GroupDataProviderImpl sGroupDataProvider;
     279             :     static chip::app::DefaultTimerDelegate sTimerDelegate;
     280             :     static app::reporting::ReportSchedulerImpl sReportScheduler;
     281             : 
     282             : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
     283             :     static SimpleSessionResumptionStorage sSessionResumptionStorage;
     284             : #endif
     285             : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
     286             :     static app::SimpleSubscriptionResumptionStorage sSubscriptionResumptionStorage;
     287             : #endif
     288             :     static app::DefaultAclStorage sAclStorage;
     289             :     static Crypto::DefaultSessionKeystore sSessionKeystore;
     290             : };
     291             : 
     292             : /**
     293             :  * The `Server` singleton class is an aggregate for all the resources needed to run a
     294             :  * Node that is both Commissionable and mainly used as an end-node with server clusters.
     295             :  * In other words, it aggregates the state needed for the type of Node used for most
     296             :  * products that are not mainly controller/administrator role.
     297             :  *
     298             :  * This sington class expects `ServerInitParams` initialization parameters but does not
     299             :  * own the resources injected from `ServerInitParams`. Any object pointers/references
     300             :  * passed in ServerInitParams must be pre-initialized externally, and shutdown/finalized
     301             :  * after `Server::Shutdown()` is called.
     302             :  *
     303             :  * TODO: Separate lifecycle ownership for some more capabilities that should not belong to
     304             :  *       common logic, such as `GenerateShutDownEvent`.
     305             :  *
     306             :  * TODO: Replace all uses of GetInstance() to "reach in" to this state from all cluster
     307             :  *       server common logic that deal with global node state with either a common NodeState
     308             :  *       compatible with OperationalDeviceProxy/DeviceProxy, or with injection at common
     309             :  *       SDK logic init.
     310             :  */
     311             : class Server
     312             : {
     313             : public:
     314             :     CHIP_ERROR Init(const ServerInitParams & initParams);
     315             : 
     316             : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
     317             :     CHIP_ERROR
     318             :     SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner,
     319             :                                          Protocols::UserDirectedCommissioning::IdentificationDeclaration & id);
     320             : 
     321             :     Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient * GetUserDirectedCommissioningClient()
     322             :     {
     323             :         return gUDCClient;
     324             :     }
     325             : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
     326             : 
     327             :     /**
     328             :      * @brief Call this function to rejoin existing groups found in the GroupDataProvider
     329             :      */
     330             :     void RejoinExistingMulticastGroups();
     331             : 
     332           4 :     FabricTable & GetFabricTable() { return mFabrics; }
     333             : 
     334             :     CASESessionManager * GetCASESessionManager() { return &mCASESessionManager; }
     335             : 
     336          14 :     Messaging::ExchangeManager & GetExchangeManager() { return mExchangeMgr; }
     337             : 
     338           7 :     SessionManager & GetSecureSessionManager() { return mSessions; }
     339             : 
     340           0 :     SessionResumptionStorage * GetSessionResumptionStorage() { return mSessionResumptionStorage; }
     341             : 
     342           0 :     app::SubscriptionResumptionStorage * GetSubscriptionResumptionStorage() { return mSubscriptionResumptionStorage; }
     343             : 
     344           0 :     TransportMgrBase & GetTransportManager() { return mTransports; }
     345             : 
     346           0 :     Credentials::GroupDataProvider * GetGroupDataProvider() { return mGroupsProvider; }
     347             : 
     348             :     Crypto::SessionKeystore * GetSessionKeystore() const { return mSessionKeystore; }
     349             : 
     350             : #if CONFIG_NETWORK_LAYER_BLE
     351           7 :     Ble::BleLayer * GetBleLayerObject() { return mBleLayer; }
     352             : #endif
     353             : 
     354           0 :     CommissioningWindowManager & GetCommissioningWindowManager() { return mCommissioningWindowManager; }
     355             : 
     356           0 :     PersistentStorageDelegate & GetPersistentStorage() { return *mDeviceStorage; }
     357             : 
     358           6 :     app::FailSafeContext & GetFailSafeContext() { return mFailSafeContext; }
     359             : 
     360             :     TestEventTriggerDelegate * GetTestEventTriggerDelegate() { return mTestEventTriggerDelegate; }
     361             : 
     362             :     Crypto::OperationalKeystore * GetOperationalKeystore() { return mOperationalKeystore; }
     363             : 
     364             :     Credentials::OperationalCertificateStore * GetOpCertStore() { return mOpCertStore; }
     365             : 
     366             :     app::DefaultAttributePersistenceProvider & GetDefaultAttributePersister() { return mAttributePersister; }
     367             : 
     368             :     app::reporting::ReportScheduler * GetReportScheduler() { return mReportScheduler; }
     369             : 
     370             : #if CHIP_CONFIG_ENABLE_ICD_SERVER
     371             :     app::ICDManager & GetICDManager() { return mICDManager; }
     372             : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
     373             : 
     374             :     /**
     375             :      * This function causes the ShutDown event to be generated async on the
     376             :      * Matter event loop.  Should be called before stopping the event loop.
     377             :      */
     378             :     void GenerateShutDownEvent();
     379             : 
     380             :     void Shutdown();
     381             : 
     382             :     void ScheduleFactoryReset();
     383             : 
     384             :     System::Clock::Microseconds64 TimeSinceInit() const
     385             :     {
     386             :         return System::SystemClock().GetMonotonicMicroseconds64() - mInitTimestamp;
     387             :     }
     388             : 
     389           0 :     static Server & GetInstance() { return sServer; }
     390             : 
     391             : private:
     392           1 :     Server() {}
     393             : 
     394             :     static Server sServer;
     395             : 
     396             :     void InitFailSafe();
     397             :     void OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event);
     398             :     void CheckServerReadyEvent();
     399             : 
     400             :     static void OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t);
     401             : 
     402             : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
     403             :     /**
     404             :      * @brief Called at Server::Init time to resume persisted subscriptions if the feature flag is enabled
     405             :      */
     406             :     void ResumeSubscriptions();
     407             : #endif
     408             : 
     409             :     class GroupDataProviderListener final : public Credentials::GroupDataProvider::GroupListener
     410             :     {
     411             :     public:
     412           1 :         GroupDataProviderListener() {}
     413             : 
     414           1 :         CHIP_ERROR Init(Server * server)
     415             :         {
     416           1 :             VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     417             : 
     418           1 :             mServer = server;
     419           1 :             return CHIP_NO_ERROR;
     420             :         };
     421             : 
     422           0 :         void OnGroupAdded(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & new_group) override
     423             :         {
     424           0 :             const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
     425           0 :             if (fabric == nullptr)
     426             :             {
     427           0 :                 ChipLogError(AppServer, "Group added to nonexistent fabric?");
     428           0 :                 return;
     429             :             }
     430             : 
     431           0 :             if (mServer->GetTransportManager().MulticastGroupJoinLeave(
     432           0 :                     Transport::PeerAddress::Multicast(fabric->GetFabricId(), new_group.group_id), true) != CHIP_NO_ERROR)
     433             :             {
     434           0 :                 ChipLogError(AppServer, "Unable to listen to group");
     435             :             }
     436             :         };
     437             : 
     438           0 :         void OnGroupRemoved(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & old_group) override
     439             :         {
     440           0 :             const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
     441           0 :             if (fabric == nullptr)
     442             :             {
     443           0 :                 ChipLogError(AppServer, "Group removed from nonexistent fabric?");
     444           0 :                 return;
     445             :             }
     446             : 
     447           0 :             mServer->GetTransportManager().MulticastGroupJoinLeave(
     448           0 :                 Transport::PeerAddress::Multicast(fabric->GetFabricId(), old_group.group_id), false);
     449             :         };
     450             : 
     451             :     private:
     452             :         Server * mServer;
     453             :     };
     454             : 
     455             :     class ServerFabricDelegate final : public chip::FabricTable::Delegate
     456             :     {
     457             :     public:
     458           1 :         ServerFabricDelegate() {}
     459             : 
     460           1 :         CHIP_ERROR Init(Server * server)
     461             :         {
     462           1 :             VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     463             : 
     464           1 :             mServer = server;
     465           1 :             return CHIP_NO_ERROR;
     466             :         }
     467             : 
     468           0 :         void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override
     469             :         {
     470             :             (void) fabricTable;
     471           0 :             ClearCASEResumptionStateOnFabricChange(fabricIndex);
     472           0 :             ClearSubscriptionResumptionStateOnFabricChange(fabricIndex);
     473             : 
     474           0 :             Credentials::GroupDataProvider * groupDataProvider = mServer->GetGroupDataProvider();
     475           0 :             if (groupDataProvider != nullptr)
     476             :             {
     477           0 :                 CHIP_ERROR err = groupDataProvider->RemoveFabric(fabricIndex);
     478           0 :                 if (err != CHIP_NO_ERROR)
     479             :                 {
     480           0 :                     ChipLogError(AppServer,
     481             :                                  "Warning, failed to delete GroupDataProvider state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
     482             :                                  static_cast<unsigned>(fabricIndex), err.Format());
     483             :                 }
     484             :             }
     485             : 
     486             :             // Remove access control entries in reverse order (it could be any order, but reverse order
     487             :             // will cause less churn in persistent storage).
     488           0 :             CHIP_ERROR aclErr = Access::GetAccessControl().DeleteAllEntriesForFabric(fabricIndex);
     489           0 :             if (aclErr != CHIP_NO_ERROR)
     490             :             {
     491           0 :                 ChipLogError(AppServer, "Warning, failed to delete access control state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
     492             :                              static_cast<unsigned>(fabricIndex), aclErr.Format());
     493             :             }
     494             : 
     495             :             //  Remove ACL extension entry for the given fabricIndex.
     496           0 :             auto & storage = mServer->GetPersistentStorage();
     497           0 :             aclErr = storage.SyncDeleteKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(fabricIndex).KeyName());
     498             : 
     499           0 :             if (aclErr != CHIP_NO_ERROR && aclErr != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND)
     500             :             {
     501           0 :                 ChipLogError(AppServer, "Warning, failed to delete ACL extension entry for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
     502             :                              static_cast<unsigned>(fabricIndex), aclErr.Format());
     503             :             }
     504             : 
     505           0 :             mServer->GetCommissioningWindowManager().OnFabricRemoved(fabricIndex);
     506           0 :         }
     507             : 
     508           0 :         void OnFabricUpdated(const FabricTable & fabricTable, chip::FabricIndex fabricIndex) override
     509             :         {
     510             :             (void) fabricTable;
     511           0 :             ClearCASEResumptionStateOnFabricChange(fabricIndex);
     512           0 :         }
     513             : 
     514             :     private:
     515           0 :         void ClearCASEResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
     516             :         {
     517           0 :             auto * sessionResumptionStorage = mServer->GetSessionResumptionStorage();
     518           0 :             VerifyOrReturn(sessionResumptionStorage != nullptr);
     519           0 :             CHIP_ERROR err = sessionResumptionStorage->DeleteAll(fabricIndex);
     520           0 :             if (err != CHIP_NO_ERROR)
     521             :             {
     522           0 :                 ChipLogError(AppServer,
     523             :                              "Warning, failed to delete session resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
     524             :                              static_cast<unsigned>(fabricIndex), err.Format());
     525             :             }
     526             :         }
     527             : 
     528           0 :         void ClearSubscriptionResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
     529             :         {
     530           0 :             auto * subscriptionResumptionStorage = mServer->GetSubscriptionResumptionStorage();
     531           0 :             VerifyOrReturn(subscriptionResumptionStorage != nullptr);
     532           0 :             CHIP_ERROR err = subscriptionResumptionStorage->DeleteAll(fabricIndex);
     533           0 :             if (err != CHIP_NO_ERROR)
     534             :             {
     535           0 :                 ChipLogError(AppServer,
     536             :                              "Warning, failed to delete subscription resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
     537             :                              static_cast<unsigned>(fabricIndex), err.Format());
     538             :             }
     539             :         }
     540             : 
     541             :         Server * mServer = nullptr;
     542             :     };
     543             : 
     544             :     /**
     545             :      * Since root certificates for Matter nodes cannot be updated in a reasonable
     546             :      * way, it doesn't make sense to enforce expiration time on root certificates.
     547             :      * This policy allows through root certificates, even if they're expired, and
     548             :      * otherwise delegates to the provided policy, or to the default policy if no
     549             :      * policy is provided.
     550             :      */
     551             :     class IgnoreRootExpirationValidityPolicy : public Credentials::CertificateValidityPolicy
     552             :     {
     553             :     public:
     554           1 :         IgnoreRootExpirationValidityPolicy() {}
     555             : 
     556           1 :         void Init(Credentials::CertificateValidityPolicy * providedPolicy) { mProvidedPolicy = providedPolicy; }
     557             : 
     558           0 :         CHIP_ERROR ApplyCertificateValidityPolicy(const Credentials::ChipCertificateData * cert, uint8_t depth,
     559             :                                                   Credentials::CertificateValidityResult result) override
     560             :         {
     561           0 :             switch (result)
     562             :             {
     563           0 :             case Credentials::CertificateValidityResult::kExpired:
     564             :             case Credentials::CertificateValidityResult::kExpiredAtLastKnownGoodTime:
     565             :             case Credentials::CertificateValidityResult::kTimeUnknown: {
     566             :                 Credentials::CertType certType;
     567           0 :                 ReturnErrorOnFailure(cert->mSubjectDN.GetCertType(certType));
     568           0 :                 if (certType == Credentials::CertType::kRoot)
     569             :                 {
     570           0 :                     return CHIP_NO_ERROR;
     571             :                 }
     572             : 
     573           0 :                 break;
     574             :             }
     575           0 :             default:
     576           0 :                 break;
     577             :             }
     578             : 
     579           0 :             if (mProvidedPolicy)
     580             :             {
     581           0 :                 return mProvidedPolicy->ApplyCertificateValidityPolicy(cert, depth, result);
     582             :             }
     583             : 
     584           0 :             return Credentials::CertificateValidityPolicy::ApplyDefaultPolicy(cert, depth, result);
     585             :         }
     586             : 
     587             :     private:
     588             :         Credentials::CertificateValidityPolicy * mProvidedPolicy = nullptr;
     589             :     };
     590             : 
     591             : #if CONFIG_NETWORK_LAYER_BLE
     592             :     Ble::BleLayer * mBleLayer = nullptr;
     593             : #endif
     594             : 
     595             :     // By default, use a certificate validation policy compatible with non-wall-clock-time-synced
     596             :     // embedded systems.
     597             :     static Credentials::IgnoreCertificateValidityPeriodPolicy sDefaultCertValidityPolicy;
     598             : 
     599             :     ServerTransportMgr mTransports;
     600             :     SessionManager mSessions;
     601             :     CASEServer mCASEServer;
     602             : 
     603             :     CASESessionManager mCASESessionManager;
     604             :     CASEClientPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_CASE_CLIENTS> mCASEClientPool;
     605             :     OperationalSessionSetupPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_DEVICES> mSessionSetupPool;
     606             : 
     607             :     Protocols::SecureChannel::UnsolicitedStatusHandler mUnsolicitedStatusHandler;
     608             :     Messaging::ExchangeManager mExchangeMgr;
     609             :     FabricTable mFabrics;
     610             :     secure_channel::MessageCounterManager mMessageCounterManager;
     611             : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
     612             :     Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient * gUDCClient = nullptr;
     613             :     // mUdcTransportMgr is for insecure communication (ex. user directed commissioning)
     614             :     // specifically, the commissioner declaration message (sent by commissioner to commissionee)
     615             :     UdcTransportMgr * mUdcTransportMgr = nullptr;
     616             :     uint16_t mCdcListenPort            = CHIP_UDC_COMMISSIONEE_PORT;
     617             : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
     618             :     CommissioningWindowManager mCommissioningWindowManager;
     619             : 
     620             :     IgnoreRootExpirationValidityPolicy mCertificateValidityPolicy;
     621             : 
     622             :     PersistentStorageDelegate * mDeviceStorage;
     623             :     SessionResumptionStorage * mSessionResumptionStorage;
     624             :     app::SubscriptionResumptionStorage * mSubscriptionResumptionStorage;
     625             :     Credentials::GroupDataProvider * mGroupsProvider;
     626             :     Crypto::SessionKeystore * mSessionKeystore;
     627             :     app::DefaultAttributePersistenceProvider mAttributePersister;
     628             :     GroupDataProviderListener mListener;
     629             :     ServerFabricDelegate mFabricDelegate;
     630             :     app::reporting::ReportScheduler * mReportScheduler;
     631             : 
     632             :     Access::AccessControl mAccessControl;
     633             :     app::AclStorage * mAclStorage;
     634             : 
     635             :     TestEventTriggerDelegate * mTestEventTriggerDelegate;
     636             :     Crypto::OperationalKeystore * mOperationalKeystore;
     637             :     Credentials::OperationalCertificateStore * mOpCertStore;
     638             :     app::FailSafeContext mFailSafeContext;
     639             : 
     640             :     bool mIsDnssdReady = false;
     641             :     uint16_t mOperationalServicePort;
     642             :     uint16_t mUserDirectedCommissioningPort;
     643             :     Inet::InterfaceId mInterfaceId;
     644             : 
     645             :     System::Clock::Microseconds64 mInitTimestamp;
     646             : #if CHIP_CONFIG_ENABLE_ICD_SERVER
     647             :     app::ICDManager mICDManager;
     648             : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
     649             : };
     650             : 
     651             : } // namespace chip

Generated by: LCOV version 1.14