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