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 1 : Transport::WiFiPAFListenParameters(static_cast<Transport::WiFiPAFBase *>(
245 1 : DeviceLayer::ConnectivityMgr().GetWiFiPAF()->mWiFiPAFTransport))
246 : #endif
247 : );
248 :
249 1 : SuccessOrExit(err);
250 1 : err = mListener.Init(this);
251 1 : SuccessOrExit(err);
252 1 : mGroupsProvider->SetListener(&mListener);
253 :
254 : #if CONFIG_NETWORK_LAYER_BLE
255 1 : mBleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer();
256 : #endif
257 1 : SuccessOrExit(err);
258 :
259 1 : err = mSessions.Init(&DeviceLayer::SystemLayer(), &mTransports, &mMessageCounterManager, mDeviceStorage, &GetFabricTable(),
260 1 : *mSessionKeystore);
261 1 : SuccessOrExit(err);
262 :
263 1 : err = mFabricDelegate.Init(this);
264 1 : SuccessOrExit(err);
265 1 : mFabrics.AddFabricDelegate(&mFabricDelegate);
266 :
267 1 : err = mExchangeMgr.Init(&mSessions);
268 1 : SuccessOrExit(err);
269 1 : err = mMessageCounterManager.Init(&mExchangeMgr);
270 1 : SuccessOrExit(err);
271 :
272 1 : err = mUnsolicitedStatusHandler.Init(&mExchangeMgr);
273 1 : SuccessOrExit(err);
274 :
275 1 : SuccessOrExit(err = mCommissioningWindowManager.Init(this));
276 1 : mCommissioningWindowManager.SetAppDelegate(initParams.appDelegate);
277 :
278 1 : app::DnssdServer::Instance().SetFabricTable(&mFabrics);
279 1 : app::DnssdServer::Instance().SetCommissioningModeProvider(&mCommissioningWindowManager);
280 :
281 1 : Dnssd::Resolver::Instance().Init(DeviceLayer::UDPEndPointManager());
282 :
283 : #if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
284 : // Initialize event logging subsystem
285 1 : err = sGlobalEventIdCounter.Init(mDeviceStorage, DefaultStorageKeyAllocator::IMEventNumber(),
286 : CHIP_DEVICE_CONFIG_EVENT_ID_COUNTER_EPOCH);
287 1 : SuccessOrExit(err);
288 :
289 : {
290 1 : app::LogStorageResources logStorageResources[] = {
291 : { &sDebugEventBuffer[0], sizeof(sDebugEventBuffer), app::PriorityLevel::Debug },
292 : { &sInfoEventBuffer[0], sizeof(sInfoEventBuffer), app::PriorityLevel::Info },
293 : { &sCritEventBuffer[0], sizeof(sCritEventBuffer), app::PriorityLevel::Critical }
294 : };
295 :
296 3 : err = app::EventManagement::GetInstance().Init(&mExchangeMgr, CHIP_NUM_EVENT_LOGGING_BUFFERS, &sLoggingBuffer[0],
297 : &logStorageResources[0], &sGlobalEventIdCounter,
298 1 : std::chrono::duration_cast<System::Clock::Milliseconds64>(mInitTimestamp),
299 1 : &app::InteractionModelEngine::GetInstance()->GetReportingEngine());
300 :
301 1 : SuccessOrExit(err);
302 : }
303 : #endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
304 :
305 : // SetDataModelProvider() initializes and starts the provider, which in turn
306 : // triggers the initialization of cluster implementations. This callsite is
307 : // critical because it ensures that cluster-level initialization occurs only
308 : // after all necessary low-level dependencies have been set up.
309 : //
310 : // Ordering guarantees:
311 : // 1) Provider initialization (under SetDataModelProvider) must happen after
312 : // SetSafeAttributePersistenceProvider to ensure the provider can leverage
313 : // the safe persistence provider for attribute persistence logic.
314 : // 2) It must occur after all low-level components that cluster implementations
315 : // might depend on have been initialized, as they rely on these components
316 : // during their own initialization.
317 : //
318 : // This remains the single point of entry to ensure that all cluster-level
319 : // initialization is performed in the correct order.
320 1 : app::InteractionModelEngine::GetInstance()->SetDataModelProvider(initParams.dataModelProvider);
321 :
322 : #if defined(CHIP_APP_USE_ECHO)
323 : err = InitEchoHandler(&mExchangeMgr);
324 : SuccessOrExit(err);
325 : #endif
326 :
327 1 : app::DnssdServer::Instance().SetSecuredIPv6Port(mTransports.GetTransport().GetImplAtIndex<0>().GetBoundPort());
328 : #if INET_CONFIG_ENABLE_IPV4
329 1 : app::DnssdServer::Instance().SetSecuredIPv4Port(mTransports.GetTransport().GetImplAtIndex<1>().GetBoundPort());
330 : #endif // INET_CONFIG_ENABLE_IPV4
331 :
332 1 : app::DnssdServer::Instance().SetUnsecuredPort(mUserDirectedCommissioningPort);
333 1 : app::DnssdServer::Instance().SetInterfaceId(mInterfaceId);
334 :
335 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
336 : // We set the ICDManager reference betfore calling the ICDManager init due to the init ordering limitations.
337 : // DnssdServer will use the default value initially and will update advertisement once ICDManager
338 : // init is called.
339 : app::DnssdServer::Instance().SetICDManager(&mICDManager);
340 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
341 :
342 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
343 : // Enable the TCP Server based on the TCPListenParameters setting.
344 1 : app::DnssdServer::Instance().SetTCPServerEnabled(tcpListenParams.IsServerListenEnabled());
345 : #endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
346 :
347 1 : if (GetFabricTable().FabricCount() != 0)
348 : {
349 : #if CONFIG_NETWORK_LAYER_BLE
350 : // The device is already commissioned, proactively disable BLE advertisement.
351 0 : ChipLogProgress(AppServer, "Fabric already commissioned. Disabling BLE advertisement");
352 0 : DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false);
353 : #endif
354 : }
355 : else
356 : {
357 : #if CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART
358 1 : SuccessOrExit(err = mCommissioningWindowManager.OpenBasicCommissioningWindow());
359 : #endif
360 : }
361 :
362 : // TODO @bzbarsky-apple @cecille Move to examples
363 : // ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD
364 : #if !CHIP_DEVICE_LAYER_TARGET_ESP32 && !CHIP_DEVICE_LAYER_TARGET_MBED && \
365 : (!CHIP_DEVICE_LAYER_TARGET_AMEBA || !CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE)
366 : // StartServer only enables commissioning mode if device has not been commissioned
367 1 : app::DnssdServer::Instance().StartServer();
368 : #endif
369 :
370 : caseSessionManagerConfig = {
371 : .sessionInitParams = {
372 1 : .sessionManager = &mSessions,
373 1 : .sessionResumptionStorage = mSessionResumptionStorage,
374 : .certificateValidityPolicy = &mCertificateValidityPolicy,
375 1 : .exchangeMgr = &mExchangeMgr,
376 1 : .fabricTable = &mFabrics,
377 1 : .groupDataProvider = mGroupsProvider,
378 : // Don't provide an MRP local config, so each CASE initiation will use
379 : // the then-current value.
380 : .mrpLocalConfig = NullOptional,
381 : },
382 : .clientPool = &mCASEClientPool,
383 : .sessionSetupPool = &mSessionSetupPool,
384 1 : };
385 :
386 1 : err = mCASESessionManager.Init(&DeviceLayer::SystemLayer(), caseSessionManagerConfig);
387 1 : SuccessOrExit(err);
388 :
389 1 : err = mCASEServer.ListenForSessionEstablishment(&mExchangeMgr, &mSessions, &mFabrics, mSessionResumptionStorage,
390 : &mCertificateValidityPolicy, mGroupsProvider);
391 1 : SuccessOrExit(err);
392 :
393 1 : err = app::InteractionModelEngine::GetInstance()->Init(&mExchangeMgr, &GetFabricTable(), mReportScheduler, &mCASESessionManager,
394 : mSubscriptionResumptionStorage);
395 1 : SuccessOrExit(err);
396 :
397 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
398 : app::InteractionModelEngine::GetInstance()->SetICDManager(&mICDManager);
399 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
400 :
401 : // ICD Init needs to be after data model init and InteractionModel Init
402 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
403 :
404 : // Register the ICDStateObservers.
405 : // Call register before init so that observers are notified of any state change during the init.
406 : // All observers are released at mICDManager.Shutdown(). They can be released individually with ReleaseObserver
407 : mICDManager.RegisterObserver(mReportScheduler);
408 : mICDManager.RegisterObserver(&app::DnssdServer::Instance());
409 :
410 : #if CHIP_CONFIG_ENABLE_ICD_CIP
411 : mICDManager.SetPersistentStorageDelegate(mDeviceStorage)
412 : .SetFabricTable(&GetFabricTable())
413 : .SetSymmetricKeyStore(mSessionKeystore)
414 : .SetExchangeManager(&mExchangeMgr)
415 : .SetSubscriptionsInfoProvider(app::InteractionModelEngine::GetInstance())
416 : .SetICDCheckInBackOffStrategy(initParams.icdCheckInBackOffStrategy);
417 :
418 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
419 : mICDManager.Init();
420 :
421 : // Register Test Event Trigger Handler
422 : if (mTestEventTriggerDelegate != nullptr)
423 : {
424 : mTestEventTriggerDelegate->AddHandler(&mICDManager);
425 : }
426 :
427 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
428 :
429 : // This code is necessary to restart listening to existing groups after a reboot
430 : // Each manufacturer needs to validate that they can rejoin groups by placing this code at the appropriate location for them
431 : //
432 : // Thread LWIP devices using dedicated Inet endpoint implementations are excluded because they call this function from:
433 : // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.cpp
434 : #if !CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
435 1 : RejoinExistingMulticastGroups();
436 : #endif // !CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
437 :
438 : // Handle deferred clean-up of a previously armed fail-safe that occurred during FabricTable commit.
439 : // This is done at the very end since at the earlier time above when FabricTable::Init() is called,
440 : // the delegates could not have been registered, and the other systems were not initialized. By now,
441 : // everything is initialized, so we can do a deferred clean-up.
442 : {
443 1 : FabricIndex fabricIndexDeletedOnInit = GetFabricTable().GetDeletedFabricFromCommitMarker();
444 1 : if (fabricIndexDeletedOnInit != kUndefinedFabricIndex)
445 : {
446 0 : ChipLogError(AppServer, "FabricIndex 0x%x deleted due to restart while fail-safed. Processing a clean-up!",
447 : static_cast<unsigned>(fabricIndexDeletedOnInit));
448 :
449 : // Always pretend it was an add, since being in the middle of an update currently breaks
450 : // the validity of the fabric table. This is expected to be extremely infrequent, so
451 : // this "harsher" than usual clean-up is more likely to get us in a valid state for whatever
452 : // remains.
453 0 : const bool addNocCalled = true;
454 0 : const bool updateNocCalled = false;
455 0 : GetFailSafeContext().ScheduleFailSafeCleanup(fabricIndexDeletedOnInit, addNocCalled, updateNocCalled);
456 :
457 : // Schedule clearing of the commit marker to only occur after we have processed all fail-safe clean-up.
458 : // Because Matter runs a single event loop for all scheduled work, it will occur after the above has
459 : // taken place. If a reset occurs before we have cleaned everything up, the next boot will still
460 : // see the commit marker.
461 0 : PlatformMgr().ScheduleWork(
462 0 : [](intptr_t arg) {
463 0 : Server * server = reinterpret_cast<Server *>(arg);
464 0 : VerifyOrReturn(server != nullptr);
465 :
466 0 : server->GetFabricTable().ClearCommitMarker();
467 0 : ChipLogProgress(AppServer, "Cleared FabricTable pending commit marker");
468 : },
469 : reinterpret_cast<intptr_t>(this));
470 : }
471 : }
472 :
473 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT // support UDC port for commissioner declaration msgs
474 : mUdcTransportMgr = Platform::New<UdcTransportMgr>();
475 : ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
476 : .SetAddressType(Inet::IPAddressType::kIPv6)
477 : .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
478 : #if INET_CONFIG_ENABLE_IPV4
479 : ,
480 : Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
481 : .SetAddressType(Inet::IPAddressType::kIPv4)
482 : .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
483 : #endif // INET_CONFIG_ENABLE_IPV4
484 : ));
485 :
486 : gUDCClient = Platform::New<Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient>();
487 : mUdcTransportMgr->SetSessionManager(gUDCClient);
488 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
489 :
490 1 : PlatformMgr().AddEventHandler(OnPlatformEventWrapper, reinterpret_cast<intptr_t>(this));
491 1 : PlatformMgr().HandleServerStarted();
492 :
493 1 : mIsDnssdReady = Dnssd::Resolver::Instance().IsInitialized();
494 1 : CheckServerReadyEvent();
495 :
496 1 : exit:
497 1 : if (err != CHIP_NO_ERROR)
498 : {
499 0 : ChipLogError(AppServer, "ERROR setting up transport: %" CHIP_ERROR_FORMAT, err.Format());
500 : }
501 : else
502 : {
503 : // NOTE: this log is scraped by the test harness.
504 1 : ChipLogProgress(AppServer, "Server Listening...");
505 : }
506 1 : return err;
507 : }
508 :
509 2 : void Server::OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event)
510 : {
511 2 : switch (event.Type)
512 : {
513 1 : case DeviceEventType::kDnssdInitialized:
514 : // Platform DNS-SD implementation uses kPlatformDnssdInitialized event to signal that it's ready.
515 1 : if (!mIsDnssdReady)
516 : {
517 0 : mIsDnssdReady = true;
518 0 : CheckServerReadyEvent();
519 : }
520 1 : break;
521 1 : case DeviceEventType::kServerReady:
522 : #if CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
523 : // Only Trigger Check-In messages if we are not in the middle of a commissioning.
524 : // This check is only necessary for the first commissioiner since the kServerReady event
525 : // is triggered once we join the network.
526 : // We trigger Check-In messages before resuming subscriptions to avoid doing both.
527 : if (!mFailSafeContext.IsFailSafeArmed())
528 : {
529 : std::function<app::ICDManager::ShouldCheckInMsgsBeSentFunction> sendCheckInMessagesOnBootUp =
530 : std::bind(&Server::ShouldCheckInMsgsBeSentAtBootFunction, this, std::placeholders::_1, std::placeholders::_2);
531 : mICDManager.TriggerCheckInMessages(sendCheckInMessagesOnBootUp);
532 : }
533 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
534 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
535 1 : ResumeSubscriptions();
536 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
537 1 : break;
538 : #if CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
539 : case DeviceEventType::kThreadConnectivityChange:
540 : if (event.ThreadConnectivityChange.Result == kConnectivity_Established)
541 : {
542 : // Refresh Multicast listening
543 : ChipLogDetail(DeviceLayer, "Thread Attached updating Multicast address");
544 : RejoinExistingMulticastGroups();
545 : }
546 : break;
547 : #endif // CHIP_SYSTEM_CONFIG_USE_OPENTHREAD_ENDPOINT
548 0 : default:
549 0 : break;
550 : }
551 2 : }
552 :
553 1 : void Server::CheckServerReadyEvent()
554 : {
555 : // Check if all asynchronously initialized server components (currently, only DNS-SD)
556 : // are ready, and emit the 'server ready' event if so.
557 1 : if (mIsDnssdReady)
558 : {
559 1 : ChipLogProgress(AppServer, "Server initialization complete");
560 :
561 1 : ChipDeviceEvent event = { .Type = DeviceEventType::kServerReady };
562 1 : PlatformMgr().PostEventOrDie(&event);
563 : }
564 1 : }
565 :
566 2 : void Server::OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t server)
567 : {
568 2 : reinterpret_cast<Server *>(server)->OnPlatformEvent(*event);
569 2 : }
570 :
571 1 : void Server::RejoinExistingMulticastGroups()
572 : {
573 1 : ChipLogProgress(AppServer, "Joining Multicast groups");
574 1 : CHIP_ERROR err = CHIP_NO_ERROR;
575 1 : for (const FabricInfo & fabric : mFabrics)
576 : {
577 0 : Credentials::GroupDataProvider::GroupInfo groupInfo;
578 :
579 0 : auto * iterator = mGroupsProvider->IterateGroupInfo(fabric.GetFabricIndex());
580 0 : if (iterator)
581 : {
582 : // GroupDataProvider was able to allocate rescources for an iterator
583 0 : while (iterator->Next(groupInfo))
584 : {
585 0 : err = mTransports.MulticastGroupJoinLeave(
586 0 : Transport::PeerAddress::Multicast(fabric.GetFabricId(), groupInfo.group_id), true);
587 0 : if (err != CHIP_NO_ERROR)
588 : {
589 0 : ChipLogError(AppServer, "Error when trying to join Group %u of fabric index %u : %" CHIP_ERROR_FORMAT,
590 : groupInfo.group_id, fabric.GetFabricIndex(), err.Format());
591 :
592 : // We assume the failure is caused by a network issue or a lack of rescources; neither of which will be solved
593 : // before the next join. Exit the loop to save rescources.
594 0 : iterator->Release();
595 0 : return;
596 : }
597 : }
598 :
599 0 : iterator->Release();
600 : }
601 : }
602 : }
603 :
604 : #if CHIP_CONFIG_ENABLE_ICD_CIP
605 : bool Server::ShouldCheckInMsgsBeSentAtBootFunction(FabricIndex aFabricIndex, NodeId subjectID)
606 : {
607 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
608 : // If at least one registration has a persisted entry, do not send Check-In message.
609 : // The resumption of the persisted subscription will serve the same function a check-in would have served.
610 : return !app::InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(aFabricIndex, subjectID);
611 : #else
612 : return true;
613 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
614 : }
615 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
616 :
617 0 : void Server::GenerateShutDownEvent()
618 : {
619 0 : PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().HandleServerShuttingDown(); });
620 0 : }
621 :
622 1 : void Server::PostFactoryResetEvent()
623 : {
624 1 : DeviceLayer::ChipDeviceEvent event{ .Type = DeviceLayer::DeviceEventType::kFactoryReset };
625 :
626 1 : CHIP_ERROR error = DeviceLayer::PlatformMgr().PostEvent(&event);
627 1 : if (error != CHIP_NO_ERROR)
628 : {
629 0 : ChipLogError(AppServer, "Posting kFactoryReset event failed with %" CHIP_ERROR_FORMAT, error.Format());
630 : }
631 1 : }
632 :
633 1 : void Server::ScheduleFactoryReset()
634 : {
635 1 : PostFactoryResetEvent();
636 :
637 1 : PlatformMgr().ScheduleWork([](intptr_t) {
638 : // Delete all fabrics and emit Leave event.
639 1 : GetInstance().GetFabricTable().DeleteAllFabrics();
640 1 : PlatformMgr().HandleServerShuttingDown();
641 1 : ConfigurationMgr().InitiateFactoryReset();
642 1 : });
643 1 : }
644 :
645 1 : void Server::Shutdown()
646 : {
647 1 : assertChipStackLockedByCurrentThread();
648 1 : PlatformMgr().RemoveEventHandler(OnPlatformEventWrapper, 0);
649 1 : mCASEServer.Shutdown();
650 1 : mCASESessionManager.Shutdown();
651 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
652 : app::DnssdServer::Instance().SetICDManager(nullptr);
653 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
654 1 : app::DnssdServer::Instance().SetCommissioningModeProvider(nullptr);
655 1 : Dnssd::ServiceAdvertiser::Instance().Shutdown();
656 :
657 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
658 : if (mUdcTransportMgr != nullptr)
659 : {
660 : Platform::Delete(mUdcTransportMgr);
661 : mUdcTransportMgr = nullptr;
662 : }
663 : if (gUDCClient != nullptr)
664 : {
665 : Platform::Delete(gUDCClient);
666 : gUDCClient = nullptr;
667 : }
668 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
669 :
670 1 : Dnssd::Resolver::Instance().Shutdown();
671 1 : app::InteractionModelEngine::GetInstance()->Shutdown();
672 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
673 : app::InteractionModelEngine::GetInstance()->SetICDManager(nullptr);
674 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
675 : // Shut down any remaining sessions (and hence exchanges) before we do any
676 : // futher teardown. CASE handshakes have been shut down already via
677 : // shutting down mCASESessionManager and mCASEServer above; shutting
678 : // down mCommissioningWindowManager will shut down any PASE handshakes we
679 : // have going on.
680 1 : mSessions.ExpireAllSecureSessions();
681 1 : mCommissioningWindowManager.Shutdown();
682 1 : mMessageCounterManager.Shutdown();
683 1 : mExchangeMgr.Shutdown();
684 1 : mSessions.Shutdown();
685 1 : mTransports.Close();
686 1 : mAccessControl.Finish();
687 1 : Access::ResetAccessControlToDefault();
688 1 : Credentials::SetGroupDataProvider(nullptr);
689 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
690 : // Remove Test Event Trigger Handler
691 : if (mTestEventTriggerDelegate != nullptr)
692 : {
693 : mTestEventTriggerDelegate->RemoveHandler(&mICDManager);
694 : }
695 : mICDManager.Shutdown();
696 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
697 :
698 : // TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code
699 1 : chip::Platform::MemoryShutdown();
700 1 : }
701 :
702 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
703 : // NOTE: UDC client is located in Server.cpp because it really only makes sense
704 : // to send UDC from a Matter device. The UDC message payload needs to include the device's
705 : // randomly generated service name.
706 : CHIP_ERROR Server::SendUserDirectedCommissioningRequest(Transport::PeerAddress commissioner,
707 : Protocols::UserDirectedCommissioning::IdentificationDeclaration & id)
708 : {
709 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest()");
710 :
711 : CHIP_ERROR err;
712 :
713 : // only populate fields left blank by the client
714 : if (strlen(id.GetInstanceName()) == 0)
715 : {
716 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Instance Name not known");
717 : char nameBuffer[Dnssd::Commission::kInstanceNameMaxLength + 1];
718 : err = app::DnssdServer::Instance().GetCommissionableInstanceName(nameBuffer, sizeof(nameBuffer));
719 : if (err != CHIP_NO_ERROR)
720 : {
721 : ChipLogError(
722 : AppServer,
723 : "Server::SendUserDirectedCommissioningRequest() Failed to get mdns instance name error: %" CHIP_ERROR_FORMAT,
724 : err.Format());
725 : return err;
726 : }
727 : id.SetInstanceName(nameBuffer);
728 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Instance Name set to %s", nameBuffer);
729 : }
730 :
731 : if (id.GetVendorId() == 0)
732 : {
733 : uint16_t vendorId = 0;
734 : if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetVendorId(vendorId) != CHIP_NO_ERROR)
735 : {
736 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Vendor ID not known");
737 : }
738 : else
739 : {
740 : id.SetVendorId(vendorId);
741 : }
742 : }
743 :
744 : if (id.GetProductId() == 0)
745 : {
746 : uint16_t productId = 0;
747 : if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetProductId(productId) != CHIP_NO_ERROR)
748 : {
749 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Product ID not known");
750 : }
751 : else
752 : {
753 : id.SetProductId(productId);
754 : }
755 : }
756 :
757 : if (strlen(id.GetDeviceName()) == 0)
758 : {
759 : char deviceName[Dnssd::kKeyDeviceNameMaxLength + 1] = {};
760 : if (!DeviceLayer::ConfigurationMgr().IsCommissionableDeviceNameEnabled() ||
761 : DeviceLayer::ConfigurationMgr().GetCommissionableDeviceName(deviceName, sizeof(deviceName)) != CHIP_NO_ERROR)
762 : {
763 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Device Name not known");
764 : }
765 : else
766 : {
767 : id.SetDeviceName(deviceName);
768 : }
769 : }
770 :
771 : #if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
772 : if (id.GetRotatingIdLength() == 0)
773 : {
774 : AdditionalDataPayloadGeneratorParams additionalDataPayloadParams;
775 : uint8_t rotatingDeviceIdUniqueId[DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength];
776 : MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId);
777 :
778 : ReturnErrorOnFailure(
779 : DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan));
780 : ReturnErrorOnFailure(
781 : DeviceLayer::ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter));
782 : additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan;
783 :
784 : uint8_t rotatingDeviceIdInternalBuffer[RotatingDeviceId::kMaxLength];
785 : MutableByteSpan rotatingDeviceIdBufferTemp(rotatingDeviceIdInternalBuffer);
786 : ReturnErrorOnFailure(AdditionalDataPayloadGenerator().generateRotatingDeviceIdAsBinary(additionalDataPayloadParams,
787 : rotatingDeviceIdBufferTemp));
788 :
789 : id.SetRotatingId(rotatingDeviceIdInternalBuffer, RotatingDeviceId::kMaxLength);
790 : }
791 : #endif
792 :
793 : if (id.GetCdPort() == 0)
794 : {
795 : id.SetCdPort(mCdcListenPort);
796 : }
797 :
798 : err = gUDCClient->SendUDCMessage(&mTransports, id, commissioner);
799 :
800 : if (err == CHIP_NO_ERROR)
801 : {
802 : ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Send UDC request success");
803 : }
804 : else
805 : {
806 : ChipLogError(AppServer, "Server::SendUserDirectedCommissioningRequest() Send UDC request failed, err: %" CHIP_ERROR_FORMAT,
807 : err.Format());
808 : }
809 : return err;
810 : }
811 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
812 :
813 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
814 1 : void Server::ResumeSubscriptions()
815 : {
816 1 : CHIP_ERROR err = app::InteractionModelEngine::GetInstance()->ResumeSubscriptions();
817 1 : if (err != CHIP_NO_ERROR)
818 : {
819 0 : ChipLogError(AppServer, "Error when trying to resume subscriptions : %" CHIP_ERROR_FORMAT, err.Format());
820 : }
821 1 : }
822 : #endif
823 :
824 : Credentials::IgnoreCertificateValidityPeriodPolicy Server::sDefaultCertValidityPolicy;
825 :
826 : KvsPersistentStorageDelegate CommonCaseDeviceServerInitParams::sKvsPersistenStorageDelegate;
827 : PersistentStorageOperationalKeystore CommonCaseDeviceServerInitParams::sPersistentStorageOperationalKeystore;
828 : Credentials::PersistentStorageOpCertStore CommonCaseDeviceServerInitParams::sPersistentStorageOpCertStore;
829 : Credentials::GroupDataProviderImpl CommonCaseDeviceServerInitParams::sGroupDataProvider;
830 : app::DefaultTimerDelegate CommonCaseDeviceServerInitParams::sTimerDelegate;
831 : app::reporting::ReportSchedulerImpl
832 : CommonCaseDeviceServerInitParams::sReportScheduler(&CommonCaseDeviceServerInitParams::sTimerDelegate);
833 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
834 : SimpleSessionResumptionStorage CommonCaseDeviceServerInitParams::sSessionResumptionStorage;
835 : #endif
836 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
837 : app::SimpleSubscriptionResumptionStorage CommonCaseDeviceServerInitParams::sSubscriptionResumptionStorage;
838 : #endif
839 : app::DefaultAclStorage CommonCaseDeviceServerInitParams::sAclStorage;
840 : Crypto::DefaultSessionKeystore CommonCaseDeviceServerInitParams::sSessionKeystore;
841 : #if CHIP_CONFIG_ENABLE_ICD_CIP
842 : app::DefaultICDCheckInBackOffStrategy CommonCaseDeviceServerInitParams::sDefaultICDCheckInBackOffStrategy;
843 : #endif
844 :
845 : } // namespace chip
|