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