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/examples/ExampleAccessControlDelegate.h>
21 :
22 : #include <app/EventManagement.h>
23 : #include <app/InteractionModelEngine.h>
24 : #include <app/server/Dnssd.h>
25 : #include <app/server/EchoHandler.h>
26 : #include <app/util/DataModelHandler.h>
27 :
28 : #if CONFIG_NETWORK_LAYER_BLE
29 : #include <ble/BLEEndPoint.h>
30 : #endif
31 : #include <inet/IPAddress.h>
32 : #include <inet/InetError.h>
33 : #include <lib/core/CHIPPersistentStorageDelegate.h>
34 : #include <lib/dnssd/Advertiser.h>
35 : #include <lib/dnssd/ServiceNaming.h>
36 : #include <lib/support/CodeUtils.h>
37 : #include <lib/support/DefaultStorageKeyAllocator.h>
38 : #include <lib/support/PersistedCounter.h>
39 : #include <lib/support/TestGroupData.h>
40 : #include <lib/support/logging/CHIPLogging.h>
41 : #include <messaging/ExchangeMgr.h>
42 : #include <platform/CHIPDeviceLayer.h>
43 : #include <platform/DeviceControlServer.h>
44 : #include <platform/DeviceInfoProvider.h>
45 : #include <platform/KeyValueStoreManager.h>
46 : #include <platform/LockTracker.h>
47 : #include <protocols/secure_channel/CASEServer.h>
48 : #include <protocols/secure_channel/MessageCounterManager.h>
49 : #if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
50 : #include <setup_payload/AdditionalDataPayloadGenerator.h>
51 : #endif
52 : #include <setup_payload/SetupPayload.h>
53 : #include <sys/param.h>
54 : #include <system/SystemPacketBuffer.h>
55 : #include <system/TLVPacketBufferBackingStore.h>
56 : #include <transport/SessionManager.h>
57 :
58 : #if defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT) || defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
59 : #include <lib/support/PersistentStorageAudit.h>
60 : #endif // defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT) || defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
61 :
62 : using namespace chip::DeviceLayer;
63 :
64 : using chip::kMinValidFabricIndex;
65 : using chip::RendezvousInformationFlag;
66 : using chip::DeviceLayer::PersistedStorage::KeyValueStoreMgr;
67 : using chip::Inet::IPAddressType;
68 : #if CONFIG_NETWORK_LAYER_BLE
69 : using chip::Transport::BleListenParameters;
70 : #endif
71 : using chip::Transport::PeerAddress;
72 : using chip::Transport::UdpListenParameters;
73 :
74 : namespace {
75 :
76 : class DeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolver
77 : {
78 : public:
79 0 : bool IsDeviceTypeOnEndpoint(chip::DeviceTypeId deviceType, chip::EndpointId endpoint) override
80 : {
81 0 : return chip::app::IsDeviceTypeOnEndpoint(deviceType, endpoint);
82 : }
83 : } sDeviceTypeResolver;
84 :
85 : } // namespace
86 :
87 : namespace chip {
88 :
89 : Server Server::sServer;
90 :
91 : #if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
92 : #define CHIP_NUM_EVENT_LOGGING_BUFFERS 3
93 : static uint8_t sInfoEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_INFO_BUFFER_SIZE];
94 : static uint8_t sDebugEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE];
95 : static uint8_t sCritEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_CRIT_BUFFER_SIZE];
96 : static ::chip::PersistedCounter<chip::EventNumber> sGlobalEventIdCounter;
97 : static ::chip::app::CircularEventBuffer sLoggingBuffer[CHIP_NUM_EVENT_LOGGING_BUFFERS];
98 : #endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
99 :
100 1 : CHIP_ERROR Server::Init(const ServerInitParams & initParams)
101 : {
102 1 : ChipLogProgress(AppServer, "Server initializing...");
103 1 : assertChipStackLockedByCurrentThread();
104 :
105 1 : mInitTimestamp = System::SystemClock().GetMonotonicMicroseconds64();
106 :
107 1 : CASESessionManagerConfig caseSessionManagerConfig;
108 1 : DeviceLayer::DeviceInfoProvider * deviceInfoprovider = nullptr;
109 :
110 1 : mOperationalServicePort = initParams.operationalServicePort;
111 1 : mUserDirectedCommissioningPort = initParams.userDirectedCommissioningPort;
112 1 : mInterfaceId = initParams.interfaceId;
113 :
114 1 : CHIP_ERROR err = CHIP_NO_ERROR;
115 :
116 1 : VerifyOrExit(initParams.persistentStorageDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
117 1 : VerifyOrExit(initParams.accessDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
118 1 : VerifyOrExit(initParams.aclStorage != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
119 1 : VerifyOrExit(initParams.groupDataProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
120 1 : VerifyOrExit(initParams.sessionKeystore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
121 1 : VerifyOrExit(initParams.operationalKeystore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
122 1 : VerifyOrExit(initParams.opCertStore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
123 1 : VerifyOrExit(initParams.reportScheduler != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
124 :
125 : // TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code
126 1 : chip::Platform::MemoryInit();
127 :
128 : // Initialize PersistentStorageDelegate-based storage
129 1 : mDeviceStorage = initParams.persistentStorageDelegate;
130 1 : mSessionResumptionStorage = initParams.sessionResumptionStorage;
131 1 : mSubscriptionResumptionStorage = initParams.subscriptionResumptionStorage;
132 1 : mOperationalKeystore = initParams.operationalKeystore;
133 1 : mOpCertStore = initParams.opCertStore;
134 1 : mSessionKeystore = initParams.sessionKeystore;
135 :
136 1 : if (initParams.certificateValidityPolicy)
137 : {
138 0 : mCertificateValidityPolicy.Init(initParams.certificateValidityPolicy);
139 : }
140 : else
141 : {
142 1 : mCertificateValidityPolicy.Init(&sDefaultCertValidityPolicy);
143 : }
144 :
145 : #if defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT)
146 : VerifyOrDie(chip::audit::ExecutePersistentStorageApiAudit(*mDeviceStorage));
147 : #endif
148 :
149 : #if defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
150 : VerifyOrDie(chip::audit::ExecutePersistentStorageLoadTestAudit(*mDeviceStorage));
151 : #endif
152 :
153 : // Set up attribute persistence before we try to bring up the data model
154 : // handler.
155 1 : SuccessOrExit(err = mAttributePersister.Init(mDeviceStorage));
156 1 : SetAttributePersistenceProvider(&mAttributePersister);
157 1 : SetSafeAttributePersistenceProvider(&mAttributePersister);
158 :
159 : {
160 1 : FabricTable::InitParams fabricTableInitParams;
161 1 : fabricTableInitParams.storage = mDeviceStorage;
162 1 : fabricTableInitParams.operationalKeystore = mOperationalKeystore;
163 1 : fabricTableInitParams.opCertStore = mOpCertStore;
164 :
165 1 : err = mFabrics.Init(fabricTableInitParams);
166 1 : SuccessOrExit(err);
167 : }
168 :
169 1 : SuccessOrExit(err = mAccessControl.Init(initParams.accessDelegate, sDeviceTypeResolver));
170 1 : Access::SetAccessControl(mAccessControl);
171 :
172 1 : mAclStorage = initParams.aclStorage;
173 1 : SuccessOrExit(err = mAclStorage->Init(*mDeviceStorage, mFabrics.begin(), mFabrics.end()));
174 :
175 1 : mGroupsProvider = initParams.groupDataProvider;
176 1 : SetGroupDataProvider(mGroupsProvider);
177 :
178 1 : mReportScheduler = initParams.reportScheduler;
179 :
180 1 : mTestEventTriggerDelegate = initParams.testEventTriggerDelegate;
181 :
182 1 : deviceInfoprovider = DeviceLayer::GetDeviceInfoProvider();
183 1 : if (deviceInfoprovider)
184 : {
185 0 : deviceInfoprovider->SetStorageDelegate(mDeviceStorage);
186 : }
187 :
188 : // Init transport before operations with secure session mgr.
189 2 : err = mTransports.Init(UdpListenParameters(DeviceLayer::UDPEndPointManager())
190 1 : .SetAddressType(IPAddressType::kIPv6)
191 1 : .SetListenPort(mOperationalServicePort)
192 1 : .SetNativeParams(initParams.endpointNativeParams)
193 :
194 : #if INET_CONFIG_ENABLE_IPV4
195 : ,
196 1 : UdpListenParameters(DeviceLayer::UDPEndPointManager())
197 1 : .SetAddressType(IPAddressType::kIPv4)
198 1 : .SetListenPort(mOperationalServicePort)
199 : #endif
200 : #if CONFIG_NETWORK_LAYER_BLE
201 : ,
202 1 : BleListenParameters(DeviceLayer::ConnectivityMgr().GetBleLayer())
203 : #endif
204 : );
205 :
206 1 : SuccessOrExit(err);
207 1 : err = mListener.Init(this);
208 1 : SuccessOrExit(err);
209 1 : mGroupsProvider->SetListener(&mListener);
210 :
211 : #if CONFIG_NETWORK_LAYER_BLE
212 1 : mBleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer();
213 : #endif
214 1 : SuccessOrExit(err);
215 :
216 1 : err = mSessions.Init(&DeviceLayer::SystemLayer(), &mTransports, &mMessageCounterManager, mDeviceStorage, &GetFabricTable(),
217 1 : *mSessionKeystore);
218 1 : SuccessOrExit(err);
219 :
220 1 : err = mFabricDelegate.Init(this);
221 1 : SuccessOrExit(err);
222 1 : mFabrics.AddFabricDelegate(&mFabricDelegate);
223 :
224 1 : err = mExchangeMgr.Init(&mSessions);
225 1 : SuccessOrExit(err);
226 1 : err = mMessageCounterManager.Init(&mExchangeMgr);
227 1 : SuccessOrExit(err);
228 :
229 1 : err = mUnsolicitedStatusHandler.Init(&mExchangeMgr);
230 1 : SuccessOrExit(err);
231 :
232 1 : SuccessOrExit(err = mCommissioningWindowManager.Init(this));
233 1 : mCommissioningWindowManager.SetAppDelegate(initParams.appDelegate);
234 :
235 1 : app::DnssdServer::Instance().SetFabricTable(&mFabrics);
236 1 : app::DnssdServer::Instance().SetCommissioningModeProvider(&mCommissioningWindowManager);
237 :
238 1 : chip::Dnssd::Resolver::Instance().Init(DeviceLayer::UDPEndPointManager());
239 :
240 : #if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
241 : // Initialize event logging subsystem
242 1 : err = sGlobalEventIdCounter.Init(mDeviceStorage, DefaultStorageKeyAllocator::IMEventNumber(),
243 : CHIP_DEVICE_CONFIG_EVENT_ID_COUNTER_EPOCH);
244 1 : SuccessOrExit(err);
245 :
246 : {
247 1 : ::chip::app::LogStorageResources logStorageResources[] = {
248 : { &sDebugEventBuffer[0], sizeof(sDebugEventBuffer), ::chip::app::PriorityLevel::Debug },
249 : { &sInfoEventBuffer[0], sizeof(sInfoEventBuffer), ::chip::app::PriorityLevel::Info },
250 : { &sCritEventBuffer[0], sizeof(sCritEventBuffer), ::chip::app::PriorityLevel::Critical }
251 : };
252 :
253 2 : chip::app::EventManagement::GetInstance().Init(&mExchangeMgr, CHIP_NUM_EVENT_LOGGING_BUFFERS, &sLoggingBuffer[0],
254 : &logStorageResources[0], &sGlobalEventIdCounter,
255 1 : std::chrono::duration_cast<System::Clock::Milliseconds64>(mInitTimestamp));
256 : }
257 : #endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
258 :
259 : // This initializes clusters, so should come after lower level initialization.
260 1 : InitDataModelHandler();
261 :
262 : #if defined(CHIP_APP_USE_ECHO)
263 : err = InitEchoHandler(&mExchangeMgr);
264 : SuccessOrExit(err);
265 : #endif
266 :
267 : //
268 : // We need to advertise the port that we're listening to for unsolicited messages over UDP. However, we have both a IPv4
269 : // and IPv6 endpoint to pick from. Given that the listen port passed in may be set to 0 (which then has the kernel select
270 : // a valid port at bind time), that will result in two possible ports being provided back from the resultant endpoint
271 : // initializations. Since IPv6 is POR for Matter, let's go ahead and pick that port.
272 : //
273 1 : app::DnssdServer::Instance().SetSecuredPort(mTransports.GetTransport().GetImplAtIndex<0>().GetBoundPort());
274 :
275 1 : app::DnssdServer::Instance().SetUnsecuredPort(mUserDirectedCommissioningPort);
276 1 : app::DnssdServer::Instance().SetInterfaceId(mInterfaceId);
277 :
278 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
279 : // We set the ICDManager reference betfore calling the ICDManager init due to the init ordering limitations.
280 : // DnssdServer will use the default value initially and will update advertisement once ICDManager
281 : // init is called.
282 : app::DnssdServer::Instance().SetICDManager(&mICDManager);
283 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
284 :
285 1 : if (GetFabricTable().FabricCount() != 0)
286 : {
287 : // The device is already commissioned, proactively disable BLE advertisement.
288 0 : ChipLogProgress(AppServer, "Fabric already commissioned. Disabling BLE advertisement");
289 : #if CONFIG_NETWORK_LAYER_BLE
290 0 : chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false);
291 : #endif
292 : }
293 : else
294 : {
295 : #if CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART
296 1 : SuccessOrExit(err = mCommissioningWindowManager.OpenBasicCommissioningWindow());
297 : #endif
298 : }
299 :
300 : // TODO @bzbarsky-apple @cecille Move to examples
301 : // ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD
302 : #if !CHIP_DEVICE_LAYER_TARGET_ESP32 && !CHIP_DEVICE_LAYER_TARGET_MBED && \
303 : (!CHIP_DEVICE_LAYER_TARGET_AMEBA || !CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE)
304 : // StartServer only enables commissioning mode if device has not been commissioned
305 1 : app::DnssdServer::Instance().StartServer();
306 : #endif
307 :
308 : caseSessionManagerConfig = {
309 : .sessionInitParams = {
310 1 : .sessionManager = &mSessions,
311 1 : .sessionResumptionStorage = mSessionResumptionStorage,
312 : .certificateValidityPolicy = &mCertificateValidityPolicy,
313 1 : .exchangeMgr = &mExchangeMgr,
314 1 : .fabricTable = &mFabrics,
315 1 : .groupDataProvider = mGroupsProvider,
316 : .mrpLocalConfig = GetLocalMRPConfig(),
317 : },
318 : .clientPool = &mCASEClientPool,
319 : .sessionSetupPool = &mSessionSetupPool,
320 1 : };
321 :
322 1 : err = mCASESessionManager.Init(&DeviceLayer::SystemLayer(), caseSessionManagerConfig);
323 1 : SuccessOrExit(err);
324 :
325 1 : err = mCASEServer.ListenForSessionEstablishment(&mExchangeMgr, &mSessions, &mFabrics, mSessionResumptionStorage,
326 : &mCertificateValidityPolicy, mGroupsProvider);
327 1 : SuccessOrExit(err);
328 :
329 1 : err = chip::app::InteractionModelEngine::GetInstance()->Init(&mExchangeMgr, &GetFabricTable(), mReportScheduler,
330 : &mCASESessionManager, mSubscriptionResumptionStorage);
331 1 : SuccessOrExit(err);
332 :
333 : // ICD Init needs to be after data model init and InteractionModel Init
334 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
335 :
336 : // Register the ICDStateObservers.
337 : // Call register before init so that observers are notified of any state change during the init.
338 : // All observers are released at mICDManager.Shutdown(). They can be released individually with ReleaseObserver
339 : mICDManager.RegisterObserver(mReportScheduler);
340 : mICDManager.RegisterObserver(&app::DnssdServer::Instance());
341 :
342 : mICDManager.Init(mDeviceStorage, &GetFabricTable(), mSessionKeystore, &mExchangeMgr,
343 : chip::app::InteractionModelEngine::GetInstance());
344 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
345 :
346 : // This code is necessary to restart listening to existing groups after a reboot
347 : // Each manufacturer needs to validate that they can rejoin groups by placing this code at the appropriate location for them
348 : //
349 : // Thread LWIP devices using dedicated Inet endpoint implementations are excluded because they call this function from:
350 : // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.cpp
351 : #if !CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
352 1 : RejoinExistingMulticastGroups();
353 : #endif // !CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
354 :
355 : // Handle deferred clean-up of a previously armed fail-safe that occurred during FabricTable commit.
356 : // This is done at the very end since at the earlier time above when FabricTable::Init() is called,
357 : // the delegates could not have been registered, and the other systems were not initialized. By now,
358 : // everything is initialized, so we can do a deferred clean-up.
359 : {
360 1 : FabricIndex fabricIndexDeletedOnInit = GetFabricTable().GetDeletedFabricFromCommitMarker();
361 1 : if (fabricIndexDeletedOnInit != kUndefinedFabricIndex)
362 : {
363 0 : ChipLogError(AppServer, "FabricIndex 0x%x deleted due to restart while fail-safed. Processing a clean-up!",
364 : static_cast<unsigned>(fabricIndexDeletedOnInit));
365 :
366 : // Always pretend it was an add, since being in the middle of an update currently breaks
367 : // the validity of the fabric table. This is expected to be extremely infrequent, so
368 : // this "harsher" than usual clean-up is more likely to get us in a valid state for whatever
369 : // remains.
370 0 : const bool addNocCalled = true;
371 0 : const bool updateNocCalled = false;
372 0 : GetFailSafeContext().ScheduleFailSafeCleanup(fabricIndexDeletedOnInit, addNocCalled, updateNocCalled);
373 :
374 : // Schedule clearing of the commit marker to only occur after we have processed all fail-safe clean-up.
375 : // Because Matter runs a single event loop for all scheduled work, it will occur after the above has
376 : // taken place. If a reset occurs before we have cleaned everything up, the next boot will still
377 : // see the commit marker.
378 0 : PlatformMgr().ScheduleWork(
379 0 : [](intptr_t arg) {
380 0 : Server * server = reinterpret_cast<Server *>(arg);
381 0 : VerifyOrReturn(server != nullptr);
382 :
383 0 : server->GetFabricTable().ClearCommitMarker();
384 0 : ChipLogProgress(AppServer, "Cleared FabricTable pending commit marker");
385 : },
386 : reinterpret_cast<intptr_t>(this));
387 : }
388 : }
389 :
390 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT // support UDC port for commissioner declaration msgs
391 : mUdcTransportMgr = chip::Platform::New<UdcTransportMgr>();
392 : ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
393 : .SetAddressType(Inet::IPAddressType::kIPv6)
394 : .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
395 : #if INET_CONFIG_ENABLE_IPV4
396 : ,
397 : Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
398 : .SetAddressType(Inet::IPAddressType::kIPv4)
399 : .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
400 : #endif // INET_CONFIG_ENABLE_IPV4
401 : ));
402 :
403 : gUDCClient = chip::Platform::New<Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient>();
404 : mUdcTransportMgr->SetSessionManager(gUDCClient);
405 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
406 :
407 1 : PlatformMgr().AddEventHandler(OnPlatformEventWrapper, reinterpret_cast<intptr_t>(this));
408 1 : PlatformMgr().HandleServerStarted();
409 :
410 1 : mIsDnssdReady = Dnssd::Resolver::Instance().IsInitialized();
411 1 : CheckServerReadyEvent();
412 :
413 1 : exit:
414 1 : if (err != CHIP_NO_ERROR)
415 : {
416 0 : ChipLogError(AppServer, "ERROR setting up transport: %" CHIP_ERROR_FORMAT, err.Format());
417 : }
418 : else
419 : {
420 : // NOTE: this log is scraped by the test harness.
421 1 : ChipLogProgress(AppServer, "Server Listening...");
422 : }
423 1 : return err;
424 1 : }
425 :
426 2 : void Server::OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event)
427 : {
428 2 : switch (event.Type)
429 : {
430 1 : case DeviceEventType::kDnssdInitialized:
431 : // Platform DNS-SD implementation uses kPlatformDnssdInitialized event to signal that it's ready.
432 1 : if (!mIsDnssdReady)
433 : {
434 0 : mIsDnssdReady = true;
435 0 : CheckServerReadyEvent();
436 : }
437 1 : break;
438 1 : case DeviceEventType::kServerReady:
439 : #if CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
440 : // Only Trigger Check-In messages if we are not in the middle of a commissioning.
441 : // This check is only necessary for the first commissioiner since the kServerReady event
442 : // is triggered once we join the network.
443 : // We trigger Check-In messages before resuming subscriptions to avoid doing both.
444 : if (!mFailSafeContext.IsFailSafeArmed())
445 : {
446 : mICDManager.TriggerCheckInMessages();
447 : }
448 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
449 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
450 1 : ResumeSubscriptions();
451 : #endif
452 1 : break;
453 : #if CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
454 : case DeviceEventType::kThreadConnectivityChange:
455 : if (event.ThreadConnectivityChange.Result == kConnectivity_Established)
456 : {
457 : // Refresh Multicast listening
458 : ChipLogDetail(DeviceLayer, "Thread Attached updating Multicast address");
459 : RejoinExistingMulticastGroups();
460 : }
461 : break;
462 : #endif // CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
463 0 : default:
464 0 : break;
465 : }
466 2 : }
467 :
468 1 : void Server::CheckServerReadyEvent()
469 : {
470 : // Check if all asynchronously initialized server components (currently, only DNS-SD)
471 : // are ready, and emit the 'server ready' event if so.
472 1 : if (mIsDnssdReady)
473 : {
474 1 : ChipLogProgress(AppServer, "Server initialization complete");
475 :
476 1 : ChipDeviceEvent event = { .Type = DeviceEventType::kServerReady };
477 1 : PlatformMgr().PostEventOrDie(&event);
478 : }
479 1 : }
480 :
481 2 : void Server::OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t server)
482 : {
483 2 : reinterpret_cast<Server *>(server)->OnPlatformEvent(*event);
484 2 : }
485 :
486 1 : void Server::RejoinExistingMulticastGroups()
487 : {
488 1 : ChipLogProgress(AppServer, "Joining Multicast groups");
489 1 : CHIP_ERROR err = CHIP_NO_ERROR;
490 1 : for (const FabricInfo & fabric : mFabrics)
491 : {
492 0 : Credentials::GroupDataProvider::GroupInfo groupInfo;
493 :
494 0 : auto * iterator = mGroupsProvider->IterateGroupInfo(fabric.GetFabricIndex());
495 0 : if (iterator)
496 : {
497 : // GroupDataProvider was able to allocate rescources for an iterator
498 0 : while (iterator->Next(groupInfo))
499 : {
500 0 : err = mTransports.MulticastGroupJoinLeave(
501 0 : Transport::PeerAddress::Multicast(fabric.GetFabricId(), groupInfo.group_id), true);
502 0 : if (err != CHIP_NO_ERROR)
503 : {
504 0 : ChipLogError(AppServer, "Error when trying to join Group %u of fabric index %u : %" CHIP_ERROR_FORMAT,
505 : groupInfo.group_id, fabric.GetFabricIndex(), err.Format());
506 :
507 : // We assume the failure is caused by a network issue or a lack of rescources; neither of which will be solved
508 : // before the next join. Exit the loop to save rescources.
509 0 : iterator->Release();
510 0 : return;
511 : }
512 : }
513 :
514 0 : iterator->Release();
515 : }
516 : }
517 : }
518 :
519 0 : void Server::GenerateShutDownEvent()
520 : {
521 0 : PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().HandleServerShuttingDown(); });
522 0 : }
523 :
524 0 : void Server::ScheduleFactoryReset()
525 : {
526 0 : PlatformMgr().ScheduleWork([](intptr_t) {
527 : // Delete all fabrics and emit Leave event.
528 0 : GetInstance().GetFabricTable().DeleteAllFabrics();
529 0 : PlatformMgr().HandleServerShuttingDown();
530 0 : ConfigurationMgr().InitiateFactoryReset();
531 0 : });
532 0 : }
533 :
534 1 : void Server::Shutdown()
535 : {
536 1 : assertChipStackLockedByCurrentThread();
537 1 : PlatformMgr().RemoveEventHandler(OnPlatformEventWrapper, 0);
538 1 : mCASEServer.Shutdown();
539 1 : mCASESessionManager.Shutdown();
540 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
541 : app::DnssdServer::Instance().SetICDManager(nullptr);
542 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
543 1 : app::DnssdServer::Instance().SetCommissioningModeProvider(nullptr);
544 1 : chip::Dnssd::ServiceAdvertiser::Instance().Shutdown();
545 :
546 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
547 : if (mUdcTransportMgr != nullptr)
548 : {
549 : chip::Platform::Delete(mUdcTransportMgr);
550 : mUdcTransportMgr = nullptr;
551 : }
552 : if (gUDCClient != nullptr)
553 : {
554 : chip::Platform::Delete(gUDCClient);
555 : gUDCClient = nullptr;
556 : }
557 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
558 :
559 1 : chip::Dnssd::Resolver::Instance().Shutdown();
560 1 : chip::app::InteractionModelEngine::GetInstance()->Shutdown();
561 1 : mCommissioningWindowManager.Shutdown();
562 1 : mMessageCounterManager.Shutdown();
563 1 : mExchangeMgr.Shutdown();
564 1 : mSessions.Shutdown();
565 1 : mTransports.Close();
566 1 : mAccessControl.Finish();
567 1 : Access::ResetAccessControlToDefault();
568 1 : Credentials::SetGroupDataProvider(nullptr);
569 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
570 : mICDManager.Shutdown();
571 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
572 1 : mAttributePersister.Shutdown();
573 : // TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code
574 1 : chip::Platform::MemoryShutdown();
575 1 : }
576 :
577 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
578 : // NOTE: UDC client is located in Server.cpp because it really only makes sense
579 : // to send UDC from a Matter device. The UDC message payload needs to include the device's
580 : // randomly generated service name.
581 : CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner,
582 : Protocols::UserDirectedCommissioning::IdentificationDeclaration & id)
583 : {
584 : ChipLogDetail(AppServer, "SendUserDirectedCommissioningRequest2");
585 :
586 : CHIP_ERROR err;
587 :
588 : // only populate fields left blank by the client
589 : if (strlen(id.GetInstanceName()) == 0)
590 : {
591 : char nameBuffer[chip::Dnssd::Commission::kInstanceNameMaxLength + 1];
592 : err = app::DnssdServer::Instance().GetCommissionableInstanceName(nameBuffer, sizeof(nameBuffer));
593 : if (err != CHIP_NO_ERROR)
594 : {
595 : ChipLogError(AppServer, "Failed to get mdns instance name error: %" CHIP_ERROR_FORMAT, err.Format());
596 : return err;
597 : }
598 : id.SetInstanceName(nameBuffer);
599 : }
600 : ChipLogDetail(AppServer, "instanceName=%s", id.GetInstanceName());
601 :
602 : if (id.GetVendorId() == 0)
603 : {
604 : uint16_t vendorId = 0;
605 : if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetVendorId(vendorId) != CHIP_NO_ERROR)
606 : {
607 : ChipLogDetail(Discovery, "Vendor ID not known");
608 : }
609 : else
610 : {
611 : id.SetVendorId(vendorId);
612 : }
613 : }
614 :
615 : if (id.GetProductId() == 0)
616 : {
617 : uint16_t productId = 0;
618 : if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetProductId(productId) != CHIP_NO_ERROR)
619 : {
620 : ChipLogDetail(Discovery, "Product ID not known");
621 : }
622 : else
623 : {
624 : id.SetProductId(productId);
625 : }
626 : }
627 :
628 : if (strlen(id.GetDeviceName()) == 0)
629 : {
630 : char deviceName[chip::Dnssd::kKeyDeviceNameMaxLength + 1] = {};
631 : if (!chip::DeviceLayer::ConfigurationMgr().IsCommissionableDeviceNameEnabled() ||
632 : chip::DeviceLayer::ConfigurationMgr().GetCommissionableDeviceName(deviceName, sizeof(deviceName)) != CHIP_NO_ERROR)
633 : {
634 : ChipLogDetail(Discovery, "Device Name not known");
635 : }
636 : else
637 : {
638 : id.SetDeviceName(deviceName);
639 : }
640 : }
641 :
642 : #if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
643 : if (id.GetRotatingIdLength() == 0)
644 : {
645 : char rotatingDeviceIdHexBuffer[RotatingDeviceId::kHexMaxLength];
646 : ReturnErrorOnFailure(
647 : app::DnssdServer::Instance().GenerateRotatingDeviceId(rotatingDeviceIdHexBuffer, ArraySize(rotatingDeviceIdHexBuffer)));
648 :
649 : uint8_t * rotatingId = reinterpret_cast<uint8_t *>(rotatingDeviceIdHexBuffer);
650 : size_t rotatingIdLen = strlen(rotatingDeviceIdHexBuffer);
651 : id.SetRotatingId(rotatingId, rotatingIdLen);
652 : }
653 : #endif
654 :
655 : if (id.GetCdPort() == 0)
656 : {
657 : id.SetCdPort(mCdcListenPort);
658 : }
659 :
660 : err = gUDCClient->SendUDCMessage(&mTransports, id, commissioner);
661 :
662 : if (err == CHIP_NO_ERROR)
663 : {
664 : ChipLogDetail(AppServer, "Send UDC request success");
665 : }
666 : else
667 : {
668 : ChipLogError(AppServer, "Send UDC request failed, err: %" CHIP_ERROR_FORMAT, err.Format());
669 : }
670 : return err;
671 : }
672 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
673 :
674 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
675 1 : void Server::ResumeSubscriptions()
676 : {
677 1 : CHIP_ERROR err = chip::app::InteractionModelEngine::GetInstance()->ResumeSubscriptions();
678 1 : if (err != CHIP_NO_ERROR)
679 : {
680 0 : ChipLogError(AppServer, "Error when trying to resume subscriptions : %" CHIP_ERROR_FORMAT, err.Format());
681 : }
682 1 : }
683 : #endif
684 :
685 : Credentials::IgnoreCertificateValidityPeriodPolicy Server::sDefaultCertValidityPolicy;
686 :
687 : KvsPersistentStorageDelegate CommonCaseDeviceServerInitParams::sKvsPersistenStorageDelegate;
688 : PersistentStorageOperationalKeystore CommonCaseDeviceServerInitParams::sPersistentStorageOperationalKeystore;
689 : Credentials::PersistentStorageOpCertStore CommonCaseDeviceServerInitParams::sPersistentStorageOpCertStore;
690 : Credentials::GroupDataProviderImpl CommonCaseDeviceServerInitParams::sGroupDataProvider;
691 : app::DefaultTimerDelegate CommonCaseDeviceServerInitParams::sTimerDelegate;
692 : app::reporting::ReportSchedulerImpl
693 : CommonCaseDeviceServerInitParams::sReportScheduler(&CommonCaseDeviceServerInitParams::sTimerDelegate);
694 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
695 : SimpleSessionResumptionStorage CommonCaseDeviceServerInitParams::sSessionResumptionStorage;
696 : #endif
697 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
698 : app::SimpleSubscriptionResumptionStorage CommonCaseDeviceServerInitParams::sSubscriptionResumptionStorage;
699 : #endif
700 : app::DefaultAclStorage CommonCaseDeviceServerInitParams::sAclStorage;
701 : Crypto::DefaultSessionKeystore CommonCaseDeviceServerInitParams::sSessionKeystore;
702 :
703 : } // namespace chip
|