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