Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2021 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 : #include <app/server/Server.h>
19 :
20 : #include <access/ProviderDeviceTypeResolver.h>
21 : #include <access/examples/ExampleAccessControlDelegate.h>
22 :
23 : #include <app/AppConfig.h>
24 : #include <app/EventManagement.h>
25 : #include <app/InteractionModelEngine.h>
26 : #include <app/SafeAttributePersistenceProvider.h>
27 : #include <app/data-model-provider/Provider.h>
28 : #include <app/server/Dnssd.h>
29 : #include <app/server/EchoHandler.h>
30 :
31 : #if CONFIG_NETWORK_LAYER_BLE
32 : #include <ble/Ble.h>
33 : #endif
34 : #include <inet/IPAddress.h>
35 : #include <inet/InetError.h>
36 : #include <lib/core/CHIPPersistentStorageDelegate.h>
37 : #include <lib/dnssd/Advertiser.h>
38 : #include <lib/dnssd/ServiceNaming.h>
39 : #include <lib/support/CodeUtils.h>
40 : #include <lib/support/DefaultStorageKeyAllocator.h>
41 : #include <lib/support/PersistedCounter.h>
42 : #include <lib/support/TestGroupData.h>
43 : #include <lib/support/logging/CHIPLogging.h>
44 : #include <messaging/ExchangeMgr.h>
45 : #include <platform/CHIPDeviceLayer.h>
46 : #include <platform/DeviceControlServer.h>
47 : #include <platform/DeviceInfoProvider.h>
48 : #include <platform/KeyValueStoreManager.h>
49 : #include <platform/LockTracker.h>
50 : #include <protocols/secure_channel/CASEServer.h>
51 : #include <protocols/secure_channel/MessageCounterManager.h>
52 : #if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
53 : #include <setup_payload/AdditionalDataPayloadGenerator.h>
54 : #endif
55 : #include <setup_payload/SetupPayload.h>
56 : #include <sys/param.h>
57 : #include <system/SystemPacketBuffer.h>
58 : #include <system/TLVPacketBufferBackingStore.h>
59 : #include <transport/SessionManager.h>
60 :
61 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
62 : #include <transport/raw/WiFiPAF.h>
63 : #endif
64 :
65 : #if defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT) || defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
66 : #include <lib/support/PersistentStorageAudit.h>
67 : #endif // defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT) || defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
68 :
69 : using namespace chip::DeviceLayer;
70 :
71 : using chip::kMinValidFabricIndex;
72 : using chip::RendezvousInformationFlag;
73 : using chip::DeviceLayer::PersistedStorage::KeyValueStoreMgr;
74 : using chip::Inet::IPAddressType;
75 : #if CONFIG_NETWORK_LAYER_BLE
76 : using chip::Transport::BleListenParameters;
77 : #endif
78 : using chip::Transport::PeerAddress;
79 : using chip::Transport::UdpListenParameters;
80 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
81 : using chip::Transport::TcpListenParameters;
82 : #endif
83 :
84 : namespace {
85 :
86 0 : chip::Access::DynamicProviderDeviceTypeResolver sDeviceTypeResolver([] {
87 0 : return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider();
88 : });
89 :
90 : } // namespace
91 :
92 : namespace chip {
93 :
94 : Server Server::sServer;
95 :
96 : #if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
97 : #define CHIP_NUM_EVENT_LOGGING_BUFFERS 3
98 : static uint8_t sInfoEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_INFO_BUFFER_SIZE];
99 : static uint8_t sDebugEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE];
100 : static uint8_t sCritEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_CRIT_BUFFER_SIZE];
101 : static PersistedCounter<EventNumber> sGlobalEventIdCounter;
102 : static app::CircularEventBuffer sLoggingBuffer[CHIP_NUM_EVENT_LOGGING_BUFFERS];
103 : #endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
104 :
105 1 : CHIP_ERROR Server::Init(const ServerInitParams & initParams)
106 : {
107 1 : ChipLogProgress(AppServer, "Server initializing...");
108 1 : assertChipStackLockedByCurrentThread();
109 :
110 1 : mInitTimestamp = System::SystemClock().GetMonotonicMicroseconds64();
111 :
112 1 : CASESessionManagerConfig caseSessionManagerConfig;
113 1 : DeviceLayer::DeviceInfoProvider * deviceInfoprovider = nullptr;
114 :
115 1 : mOperationalServicePort = initParams.operationalServicePort;
116 1 : mUserDirectedCommissioningPort = initParams.userDirectedCommissioningPort;
117 1 : mInterfaceId = initParams.interfaceId;
118 :
119 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
120 1 : auto tcpListenParams = TcpListenParameters(DeviceLayer::TCPEndPointManager())
121 1 : .SetAddressType(IPAddressType::kIPv6)
122 1 : .SetListenPort(mOperationalServicePort);
123 : #endif
124 :
125 1 : CHIP_ERROR err = CHIP_NO_ERROR;
126 :
127 1 : VerifyOrExit(initParams.persistentStorageDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
128 1 : VerifyOrExit(initParams.accessDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
129 1 : VerifyOrExit(initParams.aclStorage != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
130 1 : VerifyOrExit(initParams.groupDataProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
131 1 : VerifyOrExit(initParams.sessionKeystore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
132 1 : VerifyOrExit(initParams.operationalKeystore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
133 1 : VerifyOrExit(initParams.opCertStore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
134 1 : VerifyOrExit(initParams.reportScheduler != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
135 :
136 : // Extra log since this is an incremental requirement and existing applications may not be aware
137 1 : if (initParams.dataModelProvider == nullptr)
138 : {
139 0 : ChipLogError(AppServer, "Application Server requires a `initParams.dataModelProvider` value.");
140 0 : ChipLogError(AppServer, "For backwards compatibility, you likely can use `CodegenDataModelProviderInstance(...)`");
141 : }
142 :
143 1 : VerifyOrExit(initParams.dataModelProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
144 :
145 : // TODO(16969): Remove Platform::MemoryInit() call from Server class, it belongs to outer code
146 1 : Platform::MemoryInit();
147 :
148 : // Initialize PersistentStorageDelegate-based storage
149 1 : mDeviceStorage = initParams.persistentStorageDelegate;
150 1 : mSessionResumptionStorage = initParams.sessionResumptionStorage;
151 1 : mSubscriptionResumptionStorage = initParams.subscriptionResumptionStorage;
152 1 : mOperationalKeystore = initParams.operationalKeystore;
153 1 : mOpCertStore = initParams.opCertStore;
154 1 : mSessionKeystore = initParams.sessionKeystore;
155 :
156 1 : if (initParams.certificateValidityPolicy)
157 : {
158 0 : mCertificateValidityPolicy.Init(initParams.certificateValidityPolicy);
159 : }
160 : else
161 : {
162 1 : mCertificateValidityPolicy.Init(&sDefaultCertValidityPolicy);
163 : }
164 :
165 : #if defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT)
166 : VerifyOrDie(audit::ExecutePersistentStorageApiAudit(*mDeviceStorage));
167 : #endif
168 :
169 : #if defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
170 : VerifyOrDie(audit::ExecutePersistentStorageLoadTestAudit(*mDeviceStorage));
171 : #endif
172 :
173 : // Set up attribute persistence before we try to bring up the data model
174 : // handler.
175 1 : SuccessOrExit(err = mAttributePersister.Init(mDeviceStorage));
176 1 : SetSafeAttributePersistenceProvider(&mAttributePersister);
177 :
178 : {
179 1 : FabricTable::InitParams fabricTableInitParams;
180 1 : fabricTableInitParams.storage = mDeviceStorage;
181 1 : fabricTableInitParams.operationalKeystore = mOperationalKeystore;
182 1 : fabricTableInitParams.opCertStore = mOpCertStore;
183 :
184 1 : err = mFabrics.Init(fabricTableInitParams);
185 1 : SuccessOrExit(err);
186 : }
187 :
188 1 : SuccessOrExit(err = mAccessControl.Init(initParams.accessDelegate, sDeviceTypeResolver));
189 1 : Access::SetAccessControl(mAccessControl);
190 :
191 : #if CHIP_CONFIG_USE_ACCESS_RESTRICTIONS
192 : if (initParams.accessRestrictionProvider != nullptr)
193 : {
194 : mAccessControl.SetAccessRestrictionProvider(initParams.accessRestrictionProvider);
195 : }
196 : #endif
197 :
198 1 : mAclStorage = initParams.aclStorage;
199 1 : SuccessOrExit(err = mAclStorage->Init(*mDeviceStorage, mFabrics.begin(), mFabrics.end()));
200 :
201 1 : mGroupsProvider = initParams.groupDataProvider;
202 1 : SetGroupDataProvider(mGroupsProvider);
203 :
204 1 : mReportScheduler = initParams.reportScheduler;
205 :
206 1 : mTestEventTriggerDelegate = initParams.testEventTriggerDelegate;
207 1 : if (mTestEventTriggerDelegate == nullptr)
208 : {
209 0 : ChipLogProgress(AppServer, "WARNING: mTestEventTriggerDelegate is null");
210 : }
211 :
212 1 : deviceInfoprovider = DeviceLayer::GetDeviceInfoProvider();
213 1 : if (deviceInfoprovider)
214 : {
215 0 : deviceInfoprovider->SetStorageDelegate(mDeviceStorage);
216 : }
217 :
218 : // Init transport before operations with secure session mgr.
219 : //
220 : // The logic below expects that the IPv6 transport is at index 0. Keep that logic in sync with
221 : // this code.
222 2 : err = mTransports.Init(UdpListenParameters(DeviceLayer::UDPEndPointManager())
223 1 : .SetAddressType(IPAddressType::kIPv6)
224 1 : .SetListenPort(mOperationalServicePort)
225 1 : .SetNativeParams(initParams.endpointNativeParams)
226 : #if INET_CONFIG_ENABLE_IPV4
227 : ,
228 : // The logic below expects that the IPv4 transport, if enabled, is at
229 : // index 1. Keep that logic in sync with this code.
230 1 : UdpListenParameters(DeviceLayer::UDPEndPointManager())
231 1 : .SetAddressType(IPAddressType::kIPv4)
232 1 : .SetListenPort(mOperationalServicePort)
233 : #endif
234 : #if CONFIG_NETWORK_LAYER_BLE
235 : ,
236 1 : BleListenParameters(DeviceLayer::ConnectivityMgr().GetBleLayer())
237 : #endif
238 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
239 : ,
240 : tcpListenParams
241 : #endif
242 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
243 : ,
244 : Transport::WiFiPAFListenParameters(DeviceLayer::ConnectivityMgr().GetWiFiPAF())
245 : #endif
246 : );
247 :
248 1 : SuccessOrExit(err);
249 1 : err = mListener.Init(this);
250 1 : SuccessOrExit(err);
251 1 : mGroupsProvider->SetListener(&mListener);
252 :
253 : #if CONFIG_NETWORK_LAYER_BLE
254 1 : mBleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer();
255 : #endif
256 1 : SuccessOrExit(err);
257 :
258 1 : err = mSessions.Init(&DeviceLayer::SystemLayer(), &mTransports, &mMessageCounterManager, mDeviceStorage, &GetFabricTable(),
259 1 : *mSessionKeystore);
260 1 : SuccessOrExit(err);
261 :
262 1 : err = mFabricDelegate.Init(this);
263 1 : SuccessOrExit(err);
264 1 : mFabrics.AddFabricDelegate(&mFabricDelegate);
265 :
266 1 : err = mExchangeMgr.Init(&mSessions);
267 1 : SuccessOrExit(err);
268 1 : err = mMessageCounterManager.Init(&mExchangeMgr);
269 1 : SuccessOrExit(err);
270 :
271 1 : err = mUnsolicitedStatusHandler.Init(&mExchangeMgr);
272 1 : SuccessOrExit(err);
273 :
274 1 : SuccessOrExit(err = mCommissioningWindowManager.Init(this));
275 1 : mCommissioningWindowManager.SetAppDelegate(initParams.appDelegate);
276 :
277 1 : app::DnssdServer::Instance().SetFabricTable(&mFabrics);
278 1 : app::DnssdServer::Instance().SetCommissioningModeProvider(&mCommissioningWindowManager);
279 :
280 1 : Dnssd::Resolver::Instance().Init(DeviceLayer::UDPEndPointManager());
281 :
282 : #if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
283 : // Initialize event logging subsystem
284 1 : err = sGlobalEventIdCounter.Init(mDeviceStorage, DefaultStorageKeyAllocator::IMEventNumber(),
285 : CHIP_DEVICE_CONFIG_EVENT_ID_COUNTER_EPOCH);
286 1 : SuccessOrExit(err);
287 :
288 : {
289 1 : app::LogStorageResources logStorageResources[] = {
290 : { &sDebugEventBuffer[0], sizeof(sDebugEventBuffer), app::PriorityLevel::Debug },
291 : { &sInfoEventBuffer[0], sizeof(sInfoEventBuffer), app::PriorityLevel::Info },
292 : { &sCritEventBuffer[0], sizeof(sCritEventBuffer), app::PriorityLevel::Critical }
293 : };
294 :
295 3 : err = app::EventManagement::GetInstance().Init(&mExchangeMgr, CHIP_NUM_EVENT_LOGGING_BUFFERS, &sLoggingBuffer[0],
296 : &logStorageResources[0], &sGlobalEventIdCounter,
297 1 : std::chrono::duration_cast<System::Clock::Milliseconds64>(mInitTimestamp),
298 1 : &app::InteractionModelEngine::GetInstance()->GetReportingEngine());
299 :
300 1 : SuccessOrExit(err);
301 : }
302 : #endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
303 :
304 : // SetDataModelProvider() initializes and starts the provider, which in turn
305 : // triggers the initialization of cluster implementations. This callsite is
306 : // critical because it ensures that cluster-level initialization occurs only
307 : // after all necessary low-level dependencies have been set up.
308 : //
309 : // Ordering guarantees:
310 : // 1) Provider initialization (under SetDataModelProvider) must happen after
311 : // SetSafeAttributePersistenceProvider to ensure the provider can leverage
312 : // the safe persistence provider for attribute persistence logic.
313 : // 2) It must occur after all low-level components that cluster implementations
314 : // might depend on have been initialized, as they rely on these components
315 : // during their own initialization.
316 : //
317 : // This remains the single point of entry to ensure that all cluster-level
318 : // initialization is performed in the correct order.
319 1 : app::InteractionModelEngine::GetInstance()->SetDataModelProvider(initParams.dataModelProvider);
320 :
321 : #if defined(CHIP_APP_USE_ECHO)
322 : err = InitEchoHandler(&mExchangeMgr);
323 : SuccessOrExit(err);
324 : #endif
325 :
326 1 : app::DnssdServer::Instance().SetSecuredIPv6Port(mTransports.GetTransport().GetImplAtIndex<0>().GetBoundPort());
327 : #if INET_CONFIG_ENABLE_IPV4
328 1 : app::DnssdServer::Instance().SetSecuredIPv4Port(mTransports.GetTransport().GetImplAtIndex<1>().GetBoundPort());
329 : #endif // INET_CONFIG_ENABLE_IPV4
330 :
331 1 : app::DnssdServer::Instance().SetUnsecuredPort(mUserDirectedCommissioningPort);
332 1 : app::DnssdServer::Instance().SetInterfaceId(mInterfaceId);
333 :
334 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
335 : // We set the ICDManager reference betfore calling the ICDManager init due to the init ordering limitations.
336 : // DnssdServer will use the default value initially and will update advertisement once ICDManager
337 : // init is called.
338 : app::DnssdServer::Instance().SetICDManager(&mICDManager);
339 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
340 :
341 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
342 : // Enable the TCP Server based on the TCPListenParameters setting.
343 1 : app::DnssdServer::Instance().SetTCPServerEnabled(tcpListenParams.IsServerListenEnabled());
344 : #endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
345 :
346 1 : if (GetFabricTable().FabricCount() != 0)
347 : {
348 : #if CONFIG_NETWORK_LAYER_BLE
349 : // The device is already commissioned, proactively disable BLE advertisement.
350 0 : ChipLogProgress(AppServer, "Fabric already commissioned. Disabling BLE advertisement");
351 0 : DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false);
352 : #endif
353 : }
354 : else
355 : {
356 : #if CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART
357 1 : SuccessOrExit(err = mCommissioningWindowManager.OpenBasicCommissioningWindow());
358 : #endif
359 : }
360 :
361 : // TODO @bzbarsky-apple @cecille Move to examples
362 : // ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD
363 : #if !CHIP_DEVICE_LAYER_TARGET_ESP32 && !CHIP_DEVICE_LAYER_TARGET_MBED && \
364 : (!CHIP_DEVICE_LAYER_TARGET_AMEBA || !CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE)
365 : // StartServer only enables commissioning mode if device has not been commissioned
366 1 : app::DnssdServer::Instance().StartServer();
367 : #endif
368 :
369 : caseSessionManagerConfig = {
370 : .sessionInitParams = {
371 1 : .sessionManager = &mSessions,
372 1 : .sessionResumptionStorage = mSessionResumptionStorage,
373 : .certificateValidityPolicy = &mCertificateValidityPolicy,
374 1 : .exchangeMgr = &mExchangeMgr,
375 1 : .fabricTable = &mFabrics,
376 1 : .groupDataProvider = mGroupsProvider,
377 : // Don't provide an MRP local config, so each CASE initiation will use
378 : // the then-current value.
379 : .mrpLocalConfig = NullOptional,
380 : },
381 : .clientPool = &mCASEClientPool,
382 : .sessionSetupPool = &mSessionSetupPool,
383 1 : };
384 :
385 1 : err = mCASESessionManager.Init(&DeviceLayer::SystemLayer(), caseSessionManagerConfig);
386 1 : SuccessOrExit(err);
387 :
388 1 : err = mCASEServer.ListenForSessionEstablishment(&mExchangeMgr, &mSessions, &mFabrics, mSessionResumptionStorage,
389 : &mCertificateValidityPolicy, mGroupsProvider);
390 1 : SuccessOrExit(err);
391 :
392 1 : err = app::InteractionModelEngine::GetInstance()->Init(&mExchangeMgr, &GetFabricTable(), mReportScheduler, &mCASESessionManager,
393 : mSubscriptionResumptionStorage);
394 1 : SuccessOrExit(err);
395 :
396 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
397 : app::InteractionModelEngine::GetInstance()->SetICDManager(&mICDManager);
398 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
399 :
400 : // ICD Init needs to be after data model init and InteractionModel Init
401 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
402 :
403 : // Register the ICDStateObservers.
404 : // Call register before init so that observers are notified of any state change during the init.
405 : // All observers are released at mICDManager.Shutdown(). They can be released individually with ReleaseObserver
406 : mICDManager.RegisterObserver(mReportScheduler);
407 : mICDManager.RegisterObserver(&app::DnssdServer::Instance());
408 :
409 : #if CHIP_CONFIG_ENABLE_ICD_CIP
410 : mICDManager.SetPersistentStorageDelegate(mDeviceStorage)
411 : .SetFabricTable(&GetFabricTable())
412 : .SetSymmetricKeyStore(mSessionKeystore)
413 : .SetExchangeManager(&mExchangeMgr)
414 : .SetSubscriptionsInfoProvider(app::InteractionModelEngine::GetInstance())
415 : .SetICDCheckInBackOffStrategy(initParams.icdCheckInBackOffStrategy);
416 :
417 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
418 : mICDManager.Init();
419 :
420 : // Register Test Event Trigger Handler
421 : if (mTestEventTriggerDelegate != nullptr)
422 : {
423 : mTestEventTriggerDelegate->AddHandler(&mICDManager);
424 : }
425 :
426 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
427 :
428 : // This code is necessary to restart listening to existing groups after a reboot
429 : // Each manufacturer needs to validate that they can rejoin groups by placing this code at the appropriate location for them
430 : //
431 : // Thread LWIP devices using dedicated Inet endpoint implementations are excluded because they call this function from:
432 : // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.cpp
433 : #if !CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
434 1 : RejoinExistingMulticastGroups();
435 : #endif // !CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
436 :
437 : // Handle deferred clean-up of a previously armed fail-safe that occurred during FabricTable commit.
438 : // This is done at the very end since at the earlier time above when FabricTable::Init() is called,
439 : // the delegates could not have been registered, and the other systems were not initialized. By now,
440 : // everything is initialized, so we can do a deferred clean-up.
441 : {
442 1 : FabricIndex fabricIndexDeletedOnInit = GetFabricTable().GetDeletedFabricFromCommitMarker();
443 1 : if (fabricIndexDeletedOnInit != kUndefinedFabricIndex)
444 : {
445 0 : ChipLogError(AppServer, "FabricIndex 0x%x deleted due to restart while fail-safed. Processing a clean-up!",
446 : static_cast<unsigned>(fabricIndexDeletedOnInit));
447 :
448 : // Always pretend it was an add, since being in the middle of an update currently breaks
449 : // the validity of the fabric table. This is expected to be extremely infrequent, so
450 : // this "harsher" than usual clean-up is more likely to get us in a valid state for whatever
451 : // remains.
452 0 : const bool addNocCalled = true;
453 0 : const bool updateNocCalled = false;
454 0 : GetFailSafeContext().ScheduleFailSafeCleanup(fabricIndexDeletedOnInit, addNocCalled, updateNocCalled);
455 :
456 : // Schedule clearing of the commit marker to only occur after we have processed all fail-safe clean-up.
457 : // Because Matter runs a single event loop for all scheduled work, it will occur after the above has
458 : // taken place. If a reset occurs before we have cleaned everything up, the next boot will still
459 : // see the commit marker.
460 0 : PlatformMgr().ScheduleWork(
461 0 : [](intptr_t arg) {
462 0 : Server * server = reinterpret_cast<Server *>(arg);
463 0 : VerifyOrReturn(server != nullptr);
464 :
465 0 : server->GetFabricTable().ClearCommitMarker();
466 0 : ChipLogProgress(AppServer, "Cleared FabricTable pending commit marker");
467 : },
468 : reinterpret_cast<intptr_t>(this));
469 : }
470 : }
471 :
472 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT // support UDC port for commissioner declaration msgs
473 : mUdcTransportMgr = Platform::New<UdcTransportMgr>();
474 : ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
475 : .SetAddressType(Inet::IPAddressType::kIPv6)
476 : .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
477 : #if INET_CONFIG_ENABLE_IPV4
478 : ,
479 : Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
480 : .SetAddressType(Inet::IPAddressType::kIPv4)
481 : .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
482 : #endif // INET_CONFIG_ENABLE_IPV4
483 : ));
484 :
485 : gUDCClient = Platform::New<Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient>();
486 : mUdcTransportMgr->SetSessionManager(gUDCClient);
487 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
488 :
489 1 : PlatformMgr().AddEventHandler(OnPlatformEventWrapper, reinterpret_cast<intptr_t>(this));
490 1 : PlatformMgr().HandleServerStarted();
491 :
492 1 : mIsDnssdReady = Dnssd::Resolver::Instance().IsInitialized();
493 1 : CheckServerReadyEvent();
494 :
495 1 : exit:
496 1 : if (err != CHIP_NO_ERROR)
497 : {
498 0 : ChipLogError(AppServer, "ERROR setting up transport: %" CHIP_ERROR_FORMAT, err.Format());
499 : }
500 : else
501 : {
502 : // NOTE: this log is scraped by the test harness.
503 1 : ChipLogProgress(AppServer, "Server Listening...");
504 : }
505 1 : return err;
506 : }
507 :
508 2 : void Server::OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event)
509 : {
510 2 : switch (event.Type)
511 : {
512 1 : case DeviceEventType::kDnssdInitialized:
513 : // Platform DNS-SD implementation uses kPlatformDnssdInitialized event to signal that it's ready.
514 1 : if (!mIsDnssdReady)
515 : {
516 0 : mIsDnssdReady = true;
517 0 : CheckServerReadyEvent();
518 : }
519 1 : break;
520 1 : case DeviceEventType::kServerReady:
521 : #if CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
522 : // Only Trigger Check-In messages if we are not in the middle of a commissioning.
523 : // This check is only necessary for the first commissioiner since the kServerReady event
524 : // is triggered once we join the network.
525 : // We trigger Check-In messages before resuming subscriptions to avoid doing both.
526 : if (!mFailSafeContext.IsFailSafeArmed())
527 : {
528 : std::function<app::ICDManager::ShouldCheckInMsgsBeSentFunction> sendCheckInMessagesOnBootUp =
529 : std::bind(&Server::ShouldCheckInMsgsBeSentAtBootFunction, this, std::placeholders::_1, std::placeholders::_2);
530 : mICDManager.TriggerCheckInMessages(sendCheckInMessagesOnBootUp);
531 : }
532 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
533 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
534 1 : ResumeSubscriptions();
535 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
536 1 : break;
537 : #if CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
538 : case DeviceEventType::kThreadConnectivityChange:
539 : if (event.ThreadConnectivityChange.Result == kConnectivity_Established)
540 : {
541 : // Refresh Multicast listening
542 : ChipLogDetail(DeviceLayer, "Thread Attached updating Multicast address");
543 : RejoinExistingMulticastGroups();
544 : }
545 : break;
546 : #endif // CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
547 0 : default:
548 0 : break;
549 : }
550 2 : }
551 :
552 1 : void Server::CheckServerReadyEvent()
553 : {
554 : // Check if all asynchronously initialized server components (currently, only DNS-SD)
555 : // are ready, and emit the 'server ready' event if so.
556 1 : if (mIsDnssdReady)
557 : {
558 1 : ChipLogProgress(AppServer, "Server initialization complete");
559 :
560 1 : ChipDeviceEvent event = { .Type = DeviceEventType::kServerReady };
561 1 : PlatformMgr().PostEventOrDie(&event);
562 : }
563 1 : }
564 :
565 2 : void Server::OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t server)
566 : {
567 2 : reinterpret_cast<Server *>(server)->OnPlatformEvent(*event);
568 2 : }
569 :
570 1 : void Server::RejoinExistingMulticastGroups()
571 : {
572 1 : ChipLogProgress(AppServer, "Joining Multicast groups");
573 1 : CHIP_ERROR err = CHIP_NO_ERROR;
574 1 : for (const FabricInfo & fabric : mFabrics)
575 : {
576 0 : Credentials::GroupDataProvider::GroupInfo groupInfo;
577 :
578 0 : auto * iterator = mGroupsProvider->IterateGroupInfo(fabric.GetFabricIndex());
579 0 : if (iterator)
580 : {
581 : // GroupDataProvider was able to allocate rescources for an iterator
582 0 : while (iterator->Next(groupInfo))
583 : {
584 0 : err = mTransports.MulticastGroupJoinLeave(
585 0 : Transport::PeerAddress::Multicast(fabric.GetFabricId(), groupInfo.group_id), true);
586 0 : if (err != CHIP_NO_ERROR)
587 : {
588 0 : ChipLogError(AppServer, "Error when trying to join Group %u of fabric index %u : %" CHIP_ERROR_FORMAT,
589 : groupInfo.group_id, fabric.GetFabricIndex(), err.Format());
590 :
591 : // We assume the failure is caused by a network issue or a lack of rescources; neither of which will be solved
592 : // before the next join. Exit the loop to save rescources.
593 0 : iterator->Release();
594 0 : return;
595 : }
596 : }
597 :
598 0 : iterator->Release();
599 : }
600 : }
601 : }
602 :
603 : #if CHIP_CONFIG_ENABLE_ICD_CIP
604 : bool Server::ShouldCheckInMsgsBeSentAtBootFunction(FabricIndex aFabricIndex, NodeId subjectID)
605 : {
606 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
607 : // If at least one registration has a persisted entry, do not send Check-In message.
608 : // The resumption of the persisted subscription will serve the same function a check-in would have served.
609 : return !app::InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(aFabricIndex, subjectID);
610 : #else
611 : return true;
612 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
613 : }
614 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
615 :
616 0 : void Server::GenerateShutDownEvent()
617 : {
618 0 : PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().HandleServerShuttingDown(); });
619 0 : }
620 :
621 1 : void Server::PostFactoryResetEvent()
622 : {
623 1 : DeviceLayer::ChipDeviceEvent event{ .Type = DeviceLayer::DeviceEventType::kFactoryReset };
624 :
625 1 : CHIP_ERROR error = DeviceLayer::PlatformMgr().PostEvent(&event);
626 1 : if (error != CHIP_NO_ERROR)
627 : {
628 0 : ChipLogError(AppServer, "Posting kFactoryReset event failed with %" CHIP_ERROR_FORMAT, error.Format());
629 : }
630 1 : }
631 :
632 1 : void Server::ScheduleFactoryReset()
633 : {
634 1 : PostFactoryResetEvent();
635 :
636 1 : PlatformMgr().ScheduleWork([](intptr_t) {
637 : // Delete all fabrics and emit Leave event.
638 1 : GetInstance().GetFabricTable().DeleteAllFabrics();
639 1 : PlatformMgr().HandleServerShuttingDown();
640 1 : ConfigurationMgr().InitiateFactoryReset();
641 1 : });
642 1 : }
643 :
644 1 : void Server::Shutdown()
645 : {
646 1 : assertChipStackLockedByCurrentThread();
647 1 : PlatformMgr().RemoveEventHandler(OnPlatformEventWrapper, 0);
648 1 : mCASEServer.Shutdown();
649 1 : mCASESessionManager.Shutdown();
650 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
651 : app::DnssdServer::Instance().SetICDManager(nullptr);
652 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
653 1 : app::DnssdServer::Instance().SetCommissioningModeProvider(nullptr);
654 1 : Dnssd::ServiceAdvertiser::Instance().Shutdown();
655 :
656 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
657 : if (mUdcTransportMgr != nullptr)
658 : {
659 : Platform::Delete(mUdcTransportMgr);
660 : mUdcTransportMgr = nullptr;
661 : }
662 : if (gUDCClient != nullptr)
663 : {
664 : Platform::Delete(gUDCClient);
665 : gUDCClient = nullptr;
666 : }
667 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
668 :
669 1 : Dnssd::Resolver::Instance().Shutdown();
670 1 : app::InteractionModelEngine::GetInstance()->Shutdown();
671 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
672 : app::InteractionModelEngine::GetInstance()->SetICDManager(nullptr);
673 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
674 : // Shut down any remaining sessions (and hence exchanges) before we do any
675 : // futher teardown. CASE handshakes have been shut down already via
676 : // shutting down mCASESessionManager and mCASEServer above; shutting
677 : // down mCommissioningWindowManager will shut down any PASE handshakes we
678 : // have going on.
679 1 : mSessions.ExpireAllSecureSessions();
680 1 : mCommissioningWindowManager.Shutdown();
681 1 : mMessageCounterManager.Shutdown();
682 1 : mExchangeMgr.Shutdown();
683 1 : mSessions.Shutdown();
684 1 : mTransports.Close();
685 1 : mAccessControl.Finish();
686 1 : Access::ResetAccessControlToDefault();
687 1 : Credentials::SetGroupDataProvider(nullptr);
688 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
689 : // Remove Test Event Trigger Handler
690 : if (mTestEventTriggerDelegate != nullptr)
691 : {
692 : mTestEventTriggerDelegate->RemoveHandler(&mICDManager);
693 : }
694 : mICDManager.Shutdown();
695 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
696 :
697 : // TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code
698 1 : chip::Platform::MemoryShutdown();
699 1 : }
700 :
701 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
702 : // NOTE: UDC client is located in Server.cpp because it really only makes sense
703 : // to send UDC from a Matter device. The UDC message payload needs to include the device's
704 : // randomly generated service name.
705 : CHIP_ERROR Server::SendUserDirectedCommissioningRequest(Transport::PeerAddress commissioner,
706 : Protocols::UserDirectedCommissioning::IdentificationDeclaration & id)
707 : {
708 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest()");
709 :
710 : CHIP_ERROR err;
711 :
712 : // only populate fields left blank by the client
713 : if (strlen(id.GetInstanceName()) == 0)
714 : {
715 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Instance Name not known");
716 : char nameBuffer[Dnssd::Commission::kInstanceNameMaxLength + 1];
717 : err = app::DnssdServer::Instance().GetCommissionableInstanceName(nameBuffer, sizeof(nameBuffer));
718 : if (err != CHIP_NO_ERROR)
719 : {
720 : ChipLogError(
721 : AppServer,
722 : "Server::SendUserDirectedCommissioningRequest() Failed to get mdns instance name error: %" CHIP_ERROR_FORMAT,
723 : err.Format());
724 : return err;
725 : }
726 : id.SetInstanceName(nameBuffer);
727 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Instance Name set to %s", nameBuffer);
728 : }
729 :
730 : if (id.GetVendorId() == 0)
731 : {
732 : uint16_t vendorId = 0;
733 : if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetVendorId(vendorId) != CHIP_NO_ERROR)
734 : {
735 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Vendor ID not known");
736 : }
737 : else
738 : {
739 : id.SetVendorId(vendorId);
740 : }
741 : }
742 :
743 : if (id.GetProductId() == 0)
744 : {
745 : uint16_t productId = 0;
746 : if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetProductId(productId) != CHIP_NO_ERROR)
747 : {
748 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Product ID not known");
749 : }
750 : else
751 : {
752 : id.SetProductId(productId);
753 : }
754 : }
755 :
756 : if (strlen(id.GetDeviceName()) == 0)
757 : {
758 : char deviceName[Dnssd::kKeyDeviceNameMaxLength + 1] = {};
759 : if (!DeviceLayer::ConfigurationMgr().IsCommissionableDeviceNameEnabled() ||
760 : DeviceLayer::ConfigurationMgr().GetCommissionableDeviceName(deviceName, sizeof(deviceName)) != CHIP_NO_ERROR)
761 : {
762 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Device Name not known");
763 : }
764 : else
765 : {
766 : id.SetDeviceName(deviceName);
767 : }
768 : }
769 :
770 : #if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
771 : if (id.GetRotatingIdLength() == 0)
772 : {
773 : AdditionalDataPayloadGeneratorParams additionalDataPayloadParams;
774 : uint8_t rotatingDeviceIdUniqueId[DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength];
775 : MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId);
776 :
777 : ReturnErrorOnFailure(
778 : DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan));
779 : ReturnErrorOnFailure(
780 : DeviceLayer::ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter));
781 : additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan;
782 :
783 : uint8_t rotatingDeviceIdInternalBuffer[RotatingDeviceId::kMaxLength];
784 : MutableByteSpan rotatingDeviceIdBufferTemp(rotatingDeviceIdInternalBuffer);
785 : ReturnErrorOnFailure(AdditionalDataPayloadGenerator().generateRotatingDeviceIdAsBinary(additionalDataPayloadParams,
786 : rotatingDeviceIdBufferTemp));
787 :
788 : id.SetRotatingId(rotatingDeviceIdInternalBuffer, RotatingDeviceId::kMaxLength);
789 : }
790 : #endif
791 :
792 : if (id.GetCdPort() == 0)
793 : {
794 : id.SetCdPort(mCdcListenPort);
795 : }
796 :
797 : err = gUDCClient->SendUDCMessage(&mTransports, id, commissioner);
798 :
799 : if (err == CHIP_NO_ERROR)
800 : {
801 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Send UDC request success");
802 : }
803 : else
804 : {
805 : ChipLogError(AppServer, "Server::SendUserDirectedCommissioningRequest() Send UDC request failed, err: %" CHIP_ERROR_FORMAT,
806 : err.Format());
807 : }
808 : return err;
809 : }
810 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
811 :
812 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
813 1 : void Server::ResumeSubscriptions()
814 : {
815 1 : CHIP_ERROR err = app::InteractionModelEngine::GetInstance()->ResumeSubscriptions();
816 1 : if (err != CHIP_NO_ERROR)
817 : {
818 0 : ChipLogError(AppServer, "Error when trying to resume subscriptions : %" CHIP_ERROR_FORMAT, err.Format());
819 : }
820 1 : }
821 : #endif
822 :
823 : Credentials::IgnoreCertificateValidityPeriodPolicy Server::sDefaultCertValidityPolicy;
824 :
825 : KvsPersistentStorageDelegate CommonCaseDeviceServerInitParams::sKvsPersistenStorageDelegate;
826 : PersistentStorageOperationalKeystore CommonCaseDeviceServerInitParams::sPersistentStorageOperationalKeystore;
827 : Credentials::PersistentStorageOpCertStore CommonCaseDeviceServerInitParams::sPersistentStorageOpCertStore;
828 : Credentials::GroupDataProviderImpl CommonCaseDeviceServerInitParams::sGroupDataProvider;
829 : app::DefaultTimerDelegate CommonCaseDeviceServerInitParams::sTimerDelegate;
830 : app::reporting::ReportSchedulerImpl
831 : CommonCaseDeviceServerInitParams::sReportScheduler(&CommonCaseDeviceServerInitParams::sTimerDelegate);
832 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
833 : SimpleSessionResumptionStorage CommonCaseDeviceServerInitParams::sSessionResumptionStorage;
834 : #endif
835 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
836 : app::SimpleSubscriptionResumptionStorage CommonCaseDeviceServerInitParams::sSubscriptionResumptionStorage;
837 : #endif
838 : app::DefaultAclStorage CommonCaseDeviceServerInitParams::sAclStorage;
839 : Crypto::DefaultSessionKeystore CommonCaseDeviceServerInitParams::sSessionKeystore;
840 : #if CHIP_CONFIG_ENABLE_ICD_CIP
841 : app::DefaultICDCheckInBackOffStrategy CommonCaseDeviceServerInitParams::sDefaultICDCheckInBackOffStrategy;
842 : #endif
843 :
844 : } // namespace chip
|