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/DefaultSafeAttributePersistenceProvider.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/DefaultTimerDelegate.h>
50 : #include <platform/DeviceInstanceInfoProvider.h>
51 : #include <platform/KeyValueStoreManager.h>
52 : #include <platform/KvsPersistentStorageDelegate.h>
53 : #include <protocols/secure_channel/CASEServer.h>
54 : #include <protocols/secure_channel/MessageCounterManager.h>
55 : #include <protocols/secure_channel/PASESession.h>
56 : #include <protocols/secure_channel/RendezvousParameters.h>
57 : #include <protocols/secure_channel/UnsolicitedStatusHandler.h>
58 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
59 : #include <protocols/secure_channel/SimpleSessionResumptionStorage.h>
60 : #endif
61 : #include <protocols/user_directed_commissioning/UserDirectedCommissioning.h>
62 : #include <system/SystemClock.h>
63 : #include <transport/SessionManager.h>
64 : #include <transport/TransportMgr.h>
65 : #include <transport/TransportMgrBase.h>
66 : #if CONFIG_NETWORK_LAYER_BLE
67 : #include <transport/raw/BLE.h>
68 : #endif
69 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
70 : #include <transport/raw/WiFiPAF.h>
71 : #endif
72 : #include <app/reporting/ReportSchedulerImpl.h>
73 : #include <transport/raw/UDP.h>
74 : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
75 : #include <transport/raw/NFC.h>
76 : #endif
77 :
78 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
79 : #include <app/icd/server/ICDManager.h> // nogncheck
80 :
81 : #if CHIP_CONFIG_ENABLE_ICD_CIP
82 : #include <app/icd/server/DefaultICDCheckInBackOffStrategy.h> // nogncheck
83 : #include <app/icd/server/ICDCheckInBackOffStrategy.h> // nogncheck
84 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
85 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
86 :
87 : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
88 : #include <app/server/JointFabricAdministrator.h> //nogncheck
89 : #include <app/server/JointFabricDatastore.h> //nogncheck
90 : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
91 :
92 : namespace chip {
93 :
94 : inline constexpr size_t kMaxBlePendingPackets = 1;
95 :
96 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
97 : inline constexpr size_t kMaxTcpActiveConnectionCount = CHIP_CONFIG_MAX_ACTIVE_TCP_CONNECTIONS;
98 :
99 : inline constexpr size_t kMaxTcpPendingPackets = CHIP_CONFIG_MAX_TCP_PENDING_PACKETS;
100 : #endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
101 :
102 : //
103 : // NOTE: Please do not alter the order of template specialization here as the logic
104 : // in the Server impl depends on this.
105 : //
106 : using ServerTransportMgr = chip::TransportMgr<chip::Transport::UDP
107 : #if INET_CONFIG_ENABLE_IPV4
108 : ,
109 : chip::Transport::UDP
110 : #endif
111 : #if CONFIG_NETWORK_LAYER_BLE
112 : ,
113 : chip::Transport::BLE<kMaxBlePendingPackets>
114 : #endif
115 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
116 : ,
117 : chip::Transport::TCP<kMaxTcpActiveConnectionCount, kMaxTcpPendingPackets>
118 : #if INET_CONFIG_ENABLE_IPV4
119 : ,
120 : chip::Transport::TCP<kMaxTcpActiveConnectionCount, kMaxTcpPendingPackets>
121 : #endif
122 : #endif
123 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
124 : ,
125 : chip::Transport::WiFiPAFBase
126 : #endif
127 : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
128 : ,
129 : chip::Transport::NFC
130 : #endif
131 : >;
132 :
133 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
134 : using UdcTransportMgr = TransportMgr<Transport::UDP /* IPv6 */
135 : #if INET_CONFIG_ENABLE_IPV4
136 : ,
137 : Transport::UDP /* IPv4 */
138 : #endif
139 : >;
140 : #endif
141 :
142 : struct ServerInitParams
143 : {
144 1 : ServerInitParams() = default;
145 :
146 : // Not copyable
147 : ServerInitParams(const ServerInitParams &) = delete;
148 : ServerInitParams & operator=(const ServerInitParams &) = delete;
149 :
150 : // Application delegate to handle some commissioning lifecycle events
151 : AppDelegate * appDelegate = nullptr;
152 : // device discovery timeout
153 1 : System::Clock::Seconds32 discoveryTimeout = System::Clock::Seconds32(CHIP_DEVICE_CONFIG_DISCOVERY_TIMEOUT_SECS);
154 : // Port to use for Matter commissioning/operational traffic
155 : uint16_t operationalServicePort = CHIP_PORT;
156 : // Port to use for UDC if supported
157 : uint16_t userDirectedCommissioningPort = CHIP_UDC_PORT;
158 : // Interface on which to run daemon
159 : Inet::InterfaceId interfaceId = Inet::InterfaceId::Null();
160 :
161 : // Persistent storage delegate: MUST be injected. Used to maintain storage by much common code.
162 : // Must be initialized before being provided.
163 : PersistentStorageDelegate * persistentStorageDelegate = nullptr;
164 : // Session resumption storage: Optional. Support session resumption when provided.
165 : // Must be initialized before being provided.
166 : SessionResumptionStorage * sessionResumptionStorage = nullptr;
167 : // Session resumption storage: Optional. Support session resumption when provided.
168 : // Must be initialized before being provided.
169 : app::SubscriptionResumptionStorage * subscriptionResumptionStorage = nullptr;
170 : // Certificate validity policy: Optional. If none is injected, CHIPCert
171 : // enforces a default policy.
172 : Credentials::CertificateValidityPolicy * certificateValidityPolicy = nullptr;
173 : // Group data provider: MUST be injected. Used to maintain critical keys such as the Identity
174 : // Protection Key (IPK) for CASE. Must be initialized before being provided.
175 : Credentials::GroupDataProvider * groupDataProvider = nullptr;
176 : // Session keystore: MUST be injected. Used to derive and manage lifecycle of symmetric keys.
177 : Crypto::SessionKeystore * sessionKeystore = nullptr;
178 : // Access control delegate: MUST be injected. Used to look up access control rules. Must be
179 : // initialized before being provided.
180 : Access::AccessControl::Delegate * accessDelegate = nullptr;
181 : // ACL storage: MUST be injected. Used to store ACL entries in persistent storage. Must NOT
182 : // be initialized before being provided.
183 : app::AclStorage * aclStorage = nullptr;
184 :
185 : #if CHIP_CONFIG_USE_ACCESS_RESTRICTIONS
186 : // Access Restriction implementation: MUST be injected if MNGD feature enabled. Used to enforce
187 : // access restrictions that are managed by the device.
188 : Access::AccessRestrictionProvider * accessRestrictionProvider = nullptr;
189 : #endif
190 :
191 : // Network native params can be injected depending on the
192 : // selected Endpoint implementation
193 : void * endpointNativeParams = nullptr;
194 : // Optional. Support test event triggers when provided. Must be initialized before being
195 : // provided.
196 : TestEventTriggerDelegate * testEventTriggerDelegate = nullptr;
197 : // Operational keystore with access to the operational keys: MUST be injected.
198 : Crypto::OperationalKeystore * operationalKeystore = nullptr;
199 : // Operational certificate store with access to the operational certs in persisted storage:
200 : // must not be null at timne of Server::Init().
201 : Credentials::OperationalCertificateStore * opCertStore = nullptr;
202 : // Required, if not provided, the Server::Init() WILL fail.
203 : app::reporting::ReportScheduler * reportScheduler = nullptr;
204 : #if CHIP_CONFIG_ENABLE_ICD_CIP
205 : // Optional. Support for the ICD Check-In BackOff strategy. Must be initialized before being provided.
206 : // If the ICD Check-In protocol use-case is supported and no strategy is provided, server will use the default strategy.
207 : app::ICDCheckInBackOffStrategy * icdCheckInBackOffStrategy = nullptr;
208 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
209 :
210 : // MUST NOT be null during initialization: every application must define the
211 : // data model it wants to use. Backwards-compatibility can use `CodegenDataModelProviderInstance`
212 : // for ember/zap-generated models.
213 : chip::app::DataModel::Provider * dataModelProvider = nullptr;
214 :
215 : bool advertiseCommissionableIfNoFabrics = CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART;
216 : };
217 :
218 : /**
219 : * Transitional version of ServerInitParams to assist SDK integrators in
220 : * transitioning to injecting product/platform-owned resources. This version
221 : * of `ServerInitParams` owns and initializes (via the `InitializeStaticResourcesBeforeServerInit()`
222 : * method) the persistent storage delegate, the group data provider, and the access control delegate.
223 : * This is to reduce the amount of copied boilerplate in all the example initializations
224 : * (e.g. AppTask.cpp, main.cpp).
225 : *
226 : * This version SHOULD BE USED ONLY FOR THE IN-TREE EXAMPLES.
227 : *
228 : * IMPORTANT: Instances of this class MUST outlive the Server because Server::Init()
229 : * stores pointers to resources owned by this class.
230 : *
231 : * ACTION ITEMS FOR TRANSITION from a example in-tree to a product:
232 : *
233 : * While this could be used indefinitely, it does not exemplify orderly management of
234 : * application-injected resources. It is recommended for actual products to instead:
235 : * - Use the basic ServerInitParams in the application
236 : * - Have the application own an instance of the resources being injected in its own
237 : * state (e.g. an implementation of PersistentStorageDelegate and GroupDataProvider
238 : * interfaces).
239 : * - Initialize the injected resources prior to calling Server::Init()
240 : * - De-initialize the injected resources after calling Server::Shutdown()
241 : *
242 : * WARNING: DO NOT replicate the pattern shown here of having a subclass of ServerInitParams
243 : * own the resources outside of examples. This was done to reduce the amount of change
244 : * to existing examples while still supporting non-example versions of the
245 : * resources to be injected.
246 : */
247 : struct CommonCaseDeviceServerInitParams : public ServerInitParams
248 : {
249 1 : CommonCaseDeviceServerInitParams() = default;
250 :
251 : // Not copyable
252 : CommonCaseDeviceServerInitParams(const CommonCaseDeviceServerInitParams &) = delete;
253 : CommonCaseDeviceServerInitParams & operator=(const CommonCaseDeviceServerInitParams &) = delete;
254 :
255 : /**
256 : * Call this before Server::Init() to initialize the internally-owned resources.
257 : * Server::Init() will fail if this is not done, since several params required to
258 : * be non-null will be null without calling this method. ** See the transition method
259 : * in the outer comment of this class **.
260 : *
261 : * @return CHIP_NO_ERROR on success or a CHIP_ERROR value from APIs called to initialize
262 : * resources on failure.
263 : */
264 1 : CHIP_ERROR InitializeStaticResourcesBeforeServerInit()
265 : {
266 : // KVS-based persistent storage delegate injection
267 1 : if (persistentStorageDelegate == nullptr)
268 : {
269 : chip::DeviceLayer::PersistedStorage::KeyValueStoreManager & kvsManager =
270 1 : DeviceLayer::PersistedStorage::KeyValueStoreMgr();
271 1 : ReturnErrorOnFailure(mKvsPersistentStorageDelegate.Init(&kvsManager));
272 1 : this->persistentStorageDelegate = &mKvsPersistentStorageDelegate;
273 : }
274 :
275 : // PersistentStorageDelegate "software-based" operational key access injection
276 1 : if (this->operationalKeystore == nullptr)
277 : {
278 : // WARNING: PersistentStorageOperationalKeystore::Finish() is never called. It's fine for
279 : // for examples and for now.
280 1 : ReturnErrorOnFailure(mPersistentStorageOperationalKeystore.Init(this->persistentStorageDelegate));
281 1 : this->operationalKeystore = &mPersistentStorageOperationalKeystore;
282 : }
283 :
284 : // OpCertStore can be injected but default to persistent storage default
285 : // for simplicity of the examples.
286 1 : if (this->opCertStore == nullptr)
287 : {
288 : // WARNING: PersistentStorageOpCertStore::Finish() is never called. It's fine for
289 : // for examples and for now, since all storage is immediate for that impl.
290 1 : ReturnErrorOnFailure(mPersistentStorageOpCertStore.Init(this->persistentStorageDelegate));
291 1 : this->opCertStore = &mPersistentStorageOpCertStore;
292 : }
293 :
294 : // Injection of report scheduler WILL lead to two schedulers being allocated. As recommended above, this should only be used
295 : // for IN-TREE examples. If a default scheduler is desired, the basic ServerInitParams should be used by the application and
296 : // CommonCaseDeviceServerInitParams should not be allocated.
297 1 : if (this->reportScheduler == nullptr)
298 : {
299 0 : this->reportScheduler = &mReportScheduler;
300 : }
301 :
302 : // Session Keystore injection
303 1 : if (this->sessionKeystore == nullptr)
304 : {
305 1 : this->sessionKeystore = &mSessionKeystore;
306 : }
307 :
308 : // Group Data provider injection
309 1 : if (this->groupDataProvider == nullptr)
310 : {
311 1 : mGroupDataProvider.SetStorageDelegate(this->persistentStorageDelegate);
312 1 : mGroupDataProvider.SetSessionKeystore(this->sessionKeystore);
313 1 : ReturnErrorOnFailure(mGroupDataProvider.Init());
314 1 : this->groupDataProvider = &mGroupDataProvider;
315 : }
316 :
317 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
318 1 : if (this->sessionResumptionStorage == nullptr)
319 : {
320 1 : ChipLogProgress(AppServer, "Initializing session resumption storage...");
321 1 : ReturnErrorOnFailure(mSessionResumptionStorage.Init(this->persistentStorageDelegate));
322 1 : this->sessionResumptionStorage = &mSessionResumptionStorage;
323 : }
324 : #endif
325 :
326 : // Inject access control delegate
327 1 : if (this->accessDelegate == nullptr)
328 : {
329 1 : this->accessDelegate = Access::Examples::GetAccessControlDelegate();
330 : }
331 :
332 1 : if (this->aclStorage == nullptr)
333 : {
334 : // Inject ACL storage. (Don't initialize it.)
335 1 : this->aclStorage = &mAclStorage;
336 : }
337 :
338 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
339 1 : if (this->subscriptionResumptionStorage == nullptr)
340 : {
341 1 : ChipLogProgress(AppServer, "Initializing subscription resumption storage...");
342 1 : ReturnErrorOnFailure(mSubscriptionResumptionStorage.Init(this->persistentStorageDelegate));
343 1 : this->subscriptionResumptionStorage = &mSubscriptionResumptionStorage;
344 : }
345 : #endif
346 :
347 : #if CHIP_CONFIG_ENABLE_ICD_CIP
348 : if (this->icdCheckInBackOffStrategy == nullptr)
349 : {
350 : this->icdCheckInBackOffStrategy = &mICDCheckInBackOffStrategy;
351 : }
352 : #endif
353 :
354 1 : return CHIP_NO_ERROR;
355 : }
356 :
357 : private:
358 : // Owned resources - these are instance members (not static) so each
359 : // CommonCaseDeviceServerInitParams instance owns its own copy.
360 : // They must outlive Server::Init() because that method stores pointers to them.
361 : KvsPersistentStorageDelegate mKvsPersistentStorageDelegate;
362 : PersistentStorageOperationalKeystore mPersistentStorageOperationalKeystore;
363 : Credentials::PersistentStorageOpCertStore mPersistentStorageOpCertStore;
364 : Credentials::GroupDataProviderImpl mGroupDataProvider;
365 : app::DefaultTimerDelegate mTimerDelegate;
366 : app::reporting::ReportSchedulerImpl mReportScheduler{ &mTimerDelegate };
367 :
368 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
369 : SimpleSessionResumptionStorage mSessionResumptionStorage;
370 : #endif
371 :
372 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
373 : app::SimpleSubscriptionResumptionStorage mSubscriptionResumptionStorage;
374 : #endif
375 :
376 : app::DefaultAclStorage mAclStorage;
377 : Crypto::DefaultSessionKeystore mSessionKeystore;
378 :
379 : #if CHIP_CONFIG_ENABLE_ICD_CIP
380 : app::DefaultICDCheckInBackOffStrategy mICDCheckInBackOffStrategy;
381 : #endif
382 : };
383 :
384 : /**
385 : * The `Server` singleton class is an aggregate for all the resources needed to run a
386 : * Node that is both Commissionable and mainly used as an end-node with server clusters.
387 : * In other words, it aggregates the state needed for the type of Node used for most
388 : * products that are not mainly controller/administrator role.
389 : *
390 : * This sington class expects `ServerInitParams` initialization parameters but does not
391 : * own the resources injected from `ServerInitParams`. Any object pointers/references
392 : * passed in ServerInitParams must be pre-initialized externally, and shutdown/finalized
393 : * after `Server::Shutdown()` is called.
394 : *
395 : * TODO: Separate lifecycle ownership for some more capabilities that should not belong to
396 : * common logic, such as `GenerateShutDownEvent`.
397 : *
398 : * TODO: Replace all uses of GetInstance() to "reach in" to this state from all cluster
399 : * server common logic that deal with global node state with either a common NodeState
400 : * compatible with OperationalDeviceProxy/DeviceProxy, or with injection at common
401 : * SDK logic init.
402 : */
403 : class Server
404 : {
405 : public:
406 : CHIP_ERROR Init(const ServerInitParams & initParams);
407 :
408 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
409 : CHIP_ERROR
410 : SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner,
411 : Protocols::UserDirectedCommissioning::IdentificationDeclaration & id);
412 :
413 : Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient * GetUserDirectedCommissioningClient()
414 : {
415 : return gUDCClient;
416 : }
417 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
418 :
419 : /**
420 : * @brief Call this function to rejoin existing groups found in the GroupDataProvider
421 : */
422 : void RejoinExistingMulticastGroups();
423 :
424 107 : FabricTable & GetFabricTable() { return mFabrics; }
425 :
426 0 : CASESessionManager * GetCASESessionManager() { return &mCASESessionManager; }
427 :
428 21 : Messaging::ExchangeManager & GetExchangeManager() { return mExchangeMgr; }
429 :
430 10 : SessionManager & GetSecureSessionManager() { return mSessions; }
431 :
432 0 : SessionResumptionStorage * GetSessionResumptionStorage() { return mSessionResumptionStorage; }
433 :
434 0 : app::SubscriptionResumptionStorage * GetSubscriptionResumptionStorage() { return mSubscriptionResumptionStorage; }
435 :
436 0 : TransportMgrBase & GetTransportManager() { return mTransports; }
437 :
438 0 : Credentials::GroupDataProvider * GetGroupDataProvider() { return mGroupsProvider; }
439 :
440 : Crypto::SessionKeystore * GetSessionKeystore() const { return mSessionKeystore; }
441 :
442 : #if CONFIG_NETWORK_LAYER_BLE
443 6 : Ble::BleLayer * GetBleLayerObject() { return mBleLayer; }
444 : #endif
445 :
446 18 : CommissioningWindowManager & GetCommissioningWindowManager() { return mCommissioningWindowManager; }
447 :
448 0 : PersistentStorageDelegate & GetPersistentStorage() { return *mDeviceStorage; }
449 :
450 22 : app::FailSafeContext & GetFailSafeContext() { return mFailSafeContext; }
451 :
452 0 : TestEventTriggerDelegate * GetTestEventTriggerDelegate() { return mTestEventTriggerDelegate; }
453 :
454 : Crypto::OperationalKeystore * GetOperationalKeystore() { return mOperationalKeystore; }
455 :
456 : Credentials::OperationalCertificateStore * GetOpCertStore() { return mOpCertStore; }
457 :
458 : app::DefaultSafeAttributePersistenceProvider & GetDefaultAttributePersister() { return mAttributePersister; }
459 :
460 : app::reporting::ReportScheduler * GetReportScheduler() { return mReportScheduler; }
461 :
462 : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
463 : app::JointFabricDatastore & GetJointFabricDatastore() { return mJointFabricDatastore; }
464 : app::JointFabricAdministrator & GetJointFabricAdministrator() { return mJointFabricAdministrator; }
465 : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
466 :
467 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
468 : app::ICDManager & GetICDManager() { return mICDManager; }
469 :
470 : #if CHIP_CONFIG_ENABLE_ICD_CIP
471 : /**
472 : * @brief Function to determine if a Check-In message would be sent at Boot up
473 : *
474 : * @param aFabricIndex client fabric index
475 : * @param subjectID client subject ID
476 : * @return true Check-In message would be sent on boot up.
477 : * @return false Device has a persisted subscription with the client. See CHIP_CONFIG_PERSIST_SUBSCRIPTIONS.
478 : */
479 : bool ShouldCheckInMsgsBeSentAtBootFunction(FabricIndex aFabricIndex, NodeId subjectID);
480 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
481 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
482 :
483 : /**
484 : * This function causes the ShutDown event to be generated async on the
485 : * Matter event loop. Should be called before stopping the event loop.
486 : */
487 : void GenerateShutDownEvent();
488 :
489 : void Shutdown();
490 :
491 : void ScheduleFactoryReset();
492 :
493 4 : System::Clock::Microseconds64 TimeSinceInit() const
494 : {
495 4 : return System::SystemClock().GetMonotonicMicroseconds64() - mInitTimestamp;
496 : }
497 :
498 152 : static Server & GetInstance() { return sServer; }
499 :
500 : private:
501 75 : Server() {}
502 :
503 : static Server sServer;
504 :
505 : void InitFailSafe();
506 : void OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event);
507 : void CheckServerReadyEvent();
508 :
509 : void PostFactoryResetEvent();
510 :
511 : static void OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t);
512 :
513 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
514 : /**
515 : * @brief Called at Server::Init time to resume persisted subscriptions if the feature flag is enabled
516 : */
517 : void ResumeSubscriptions();
518 : #endif
519 :
520 : class GroupDataProviderListener final : public Credentials::GroupDataProvider::GroupListener
521 : {
522 : public:
523 75 : GroupDataProviderListener() {}
524 :
525 1 : CHIP_ERROR Init(Server * server)
526 : {
527 1 : VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
528 :
529 1 : mServer = server;
530 1 : return CHIP_NO_ERROR;
531 : };
532 :
533 0 : void OnGroupAdded(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & new_group) override
534 : {
535 0 : const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
536 0 : if (fabric == nullptr)
537 : {
538 0 : ChipLogError(AppServer, "Group added to nonexistent fabric?");
539 0 : return;
540 : }
541 :
542 0 : if (mServer->GetTransportManager().MulticastGroupJoinLeave(
543 0 : Transport::PeerAddress::Multicast(fabric->GetFabricId(), new_group.group_id), true) != CHIP_NO_ERROR)
544 : {
545 0 : ChipLogError(AppServer, "Unable to listen to group");
546 : }
547 : };
548 :
549 0 : void OnGroupRemoved(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & old_group) override
550 : {
551 0 : const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
552 0 : if (fabric == nullptr)
553 : {
554 0 : ChipLogError(AppServer, "Group removed from nonexistent fabric?");
555 0 : return;
556 : }
557 :
558 0 : TEMPORARY_RETURN_IGNORED mServer->GetTransportManager().MulticastGroupJoinLeave(
559 0 : Transport::PeerAddress::Multicast(fabric->GetFabricId(), old_group.group_id), false);
560 : };
561 :
562 : private:
563 : Server * mServer;
564 : };
565 :
566 : class ServerFabricDelegate final : public chip::FabricTable::Delegate
567 : {
568 : public:
569 75 : ServerFabricDelegate() {}
570 :
571 1 : CHIP_ERROR Init(Server * server)
572 : {
573 1 : VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
574 :
575 1 : mServer = server;
576 1 : return CHIP_NO_ERROR;
577 : }
578 :
579 0 : void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override
580 : {
581 : (void) fabricTable;
582 0 : ClearCASEResumptionStateOnFabricChange(fabricIndex);
583 0 : ClearSubscriptionResumptionStateOnFabricChange(fabricIndex);
584 :
585 0 : Credentials::GroupDataProvider * groupDataProvider = mServer->GetGroupDataProvider();
586 0 : if (groupDataProvider != nullptr)
587 : {
588 0 : CHIP_ERROR err = groupDataProvider->RemoveFabric(fabricIndex);
589 0 : if (err != CHIP_NO_ERROR)
590 : {
591 0 : ChipLogError(AppServer,
592 : "Warning, failed to delete GroupDataProvider state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
593 : static_cast<unsigned>(fabricIndex), err.Format());
594 : }
595 : }
596 :
597 : // Remove access control entries in reverse order (it could be any order, but reverse order
598 : // will cause less churn in persistent storage).
599 0 : CHIP_ERROR aclErr = Access::GetAccessControl().DeleteAllEntriesForFabric(fabricIndex);
600 0 : if (aclErr != CHIP_NO_ERROR)
601 : {
602 0 : ChipLogError(AppServer, "Warning, failed to delete access control state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
603 : static_cast<unsigned>(fabricIndex), aclErr.Format());
604 : }
605 :
606 : // Remove ACL extension entry for the given fabricIndex.
607 0 : auto & storage = mServer->GetPersistentStorage();
608 0 : aclErr = storage.SyncDeleteKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(fabricIndex).KeyName());
609 :
610 0 : if (aclErr != CHIP_NO_ERROR && aclErr != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND)
611 : {
612 0 : ChipLogError(AppServer, "Warning, failed to delete ACL extension entry for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
613 : static_cast<unsigned>(fabricIndex), aclErr.Format());
614 : }
615 :
616 0 : mServer->GetCommissioningWindowManager().OnFabricRemoved(fabricIndex);
617 0 : }
618 :
619 0 : void OnFabricUpdated(const FabricTable & fabricTable, chip::FabricIndex fabricIndex) override
620 : {
621 : (void) fabricTable;
622 0 : ClearCASEResumptionStateOnFabricChange(fabricIndex);
623 0 : }
624 :
625 : private:
626 0 : void ClearCASEResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
627 : {
628 0 : auto * sessionResumptionStorage = mServer->GetSessionResumptionStorage();
629 0 : VerifyOrReturn(sessionResumptionStorage != nullptr);
630 0 : CHIP_ERROR err = sessionResumptionStorage->DeleteAll(fabricIndex);
631 0 : if (err != CHIP_NO_ERROR)
632 : {
633 0 : ChipLogError(AppServer,
634 : "Warning, failed to delete session resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
635 : static_cast<unsigned>(fabricIndex), err.Format());
636 : }
637 : }
638 :
639 0 : void ClearSubscriptionResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
640 : {
641 0 : auto * subscriptionResumptionStorage = mServer->GetSubscriptionResumptionStorage();
642 0 : VerifyOrReturn(subscriptionResumptionStorage != nullptr);
643 0 : CHIP_ERROR err = subscriptionResumptionStorage->DeleteAll(fabricIndex);
644 0 : if (err != CHIP_NO_ERROR)
645 : {
646 0 : ChipLogError(AppServer,
647 : "Warning, failed to delete subscription resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
648 : static_cast<unsigned>(fabricIndex), err.Format());
649 : }
650 : }
651 :
652 : Server * mServer = nullptr;
653 : };
654 :
655 : /**
656 : * Since root certificates for Matter nodes cannot be updated in a reasonable
657 : * way, it doesn't make sense to enforce expiration time on root certificates.
658 : * This policy allows through root certificates, even if they're expired, and
659 : * otherwise delegates to the provided policy, or to the default policy if no
660 : * policy is provided.
661 : */
662 : class IgnoreRootExpirationValidityPolicy : public Credentials::CertificateValidityPolicy
663 : {
664 : public:
665 75 : IgnoreRootExpirationValidityPolicy() {}
666 :
667 1 : void Init(Credentials::CertificateValidityPolicy * providedPolicy) { mProvidedPolicy = providedPolicy; }
668 :
669 0 : CHIP_ERROR ApplyCertificateValidityPolicy(const Credentials::ChipCertificateData * cert, uint8_t depth,
670 : Credentials::CertificateValidityResult result) override
671 : {
672 0 : switch (result)
673 : {
674 0 : case Credentials::CertificateValidityResult::kExpired:
675 : case Credentials::CertificateValidityResult::kExpiredAtLastKnownGoodTime:
676 : case Credentials::CertificateValidityResult::kTimeUnknown: {
677 : Credentials::CertType certType;
678 0 : ReturnErrorOnFailure(cert->mSubjectDN.GetCertType(certType));
679 0 : if (certType == Credentials::CertType::kRoot)
680 : {
681 0 : return CHIP_NO_ERROR;
682 : }
683 :
684 0 : break;
685 : }
686 0 : default:
687 0 : break;
688 : }
689 :
690 0 : if (mProvidedPolicy)
691 : {
692 0 : return mProvidedPolicy->ApplyCertificateValidityPolicy(cert, depth, result);
693 : }
694 :
695 0 : return Credentials::CertificateValidityPolicy::ApplyDefaultPolicy(cert, depth, result);
696 : }
697 :
698 : private:
699 : Credentials::CertificateValidityPolicy * mProvidedPolicy = nullptr;
700 : };
701 :
702 : #if CONFIG_NETWORK_LAYER_BLE
703 : Ble::BleLayer * mBleLayer = nullptr;
704 : #endif
705 :
706 : // By default, use a certificate validation policy compatible with non-wall-clock-time-synced
707 : // embedded systems.
708 : static Credentials::IgnoreCertificateValidityPeriodPolicy sDefaultCertValidityPolicy;
709 :
710 : ServerTransportMgr mTransports;
711 : SessionManager mSessions;
712 : CASEServer mCASEServer;
713 :
714 : CASESessionManager mCASESessionManager;
715 : CASEClientPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_CASE_CLIENTS> mCASEClientPool;
716 : OperationalSessionSetupPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_DEVICES> mSessionSetupPool;
717 :
718 : Protocols::SecureChannel::UnsolicitedStatusHandler mUnsolicitedStatusHandler;
719 : Messaging::ExchangeManager mExchangeMgr;
720 : FabricTable mFabrics;
721 : secure_channel::MessageCounterManager mMessageCounterManager;
722 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
723 : Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient * gUDCClient = nullptr;
724 : // mUdcTransportMgr is for insecure communication (ex. user directed commissioning)
725 : // specifically, the commissioner declaration message (sent by commissioner to commissionee)
726 : UdcTransportMgr * mUdcTransportMgr = nullptr;
727 : uint16_t mCdcListenPort = CHIP_UDC_COMMISSIONEE_PORT;
728 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
729 : CommissioningWindowManager mCommissioningWindowManager;
730 :
731 : IgnoreRootExpirationValidityPolicy mCertificateValidityPolicy;
732 :
733 : PersistentStorageDelegate * mDeviceStorage;
734 : SessionResumptionStorage * mSessionResumptionStorage;
735 : app::SubscriptionResumptionStorage * mSubscriptionResumptionStorage;
736 : Credentials::GroupDataProvider * mGroupsProvider;
737 : Crypto::SessionKeystore * mSessionKeystore;
738 : app::DefaultSafeAttributePersistenceProvider mAttributePersister;
739 : GroupDataProviderListener mListener;
740 : ServerFabricDelegate mFabricDelegate;
741 : app::reporting::ReportScheduler * mReportScheduler;
742 :
743 : Access::AccessControl mAccessControl;
744 : app::AclStorage * mAclStorage;
745 :
746 : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
747 : app::JointFabricDatastore mJointFabricDatastore;
748 : app::JointFabricAdministrator mJointFabricAdministrator;
749 : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
750 :
751 : TestEventTriggerDelegate * mTestEventTriggerDelegate;
752 : Crypto::OperationalKeystore * mOperationalKeystore;
753 : Credentials::OperationalCertificateStore * mOpCertStore;
754 : app::FailSafeContext mFailSafeContext;
755 :
756 : bool mIsDnssdReady = false;
757 : uint16_t mOperationalServicePort;
758 : uint16_t mUserDirectedCommissioningPort;
759 : Inet::InterfaceId mInterfaceId;
760 :
761 : System::Clock::Microseconds64 mInitTimestamp;
762 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
763 : app::ICDManager mICDManager;
764 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
765 : };
766 :
767 : } // namespace chip
|