blob: 128ccd6ed069ab9f7ed94b34e679c2bb86273ec2 [file] [log] [blame]
Song Guo750e2e62020-09-15 00:45:51 +08001/*
2 *
Jiacheng Guo735dbb02021-09-11 04:24:07 +08003 * Copyright (c) 2021 Project CHIP Authors
Song Guo750e2e62020-09-15 00:45:51 +08004 *
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
Kamil Kasperczykd05149c2021-01-05 16:05:27 +010018#include <app/server/Server.h>
Song Guo750e2e62020-09-15 00:45:51 +080019
Andrei Litvind099b0b2024-11-11 11:12:12 -050020#include <access/ProviderDeviceTypeResolver.h>
Andy Salisbury62e37a22022-02-04 11:00:00 -050021#include <access/examples/ExampleAccessControlDelegate.h>
22
Andrei Litvin994c3902024-10-04 12:41:54 -040023#include <app/AppConfig.h>
yunhanw-google6f89b9b2021-12-07 14:26:21 -080024#include <app/EventManagement.h>
Song Guoa77a6622021-01-29 13:13:02 +080025#include <app/InteractionModelEngine.h>
Andrei Litvindad97c82024-12-05 11:30:14 -050026#include <app/SafeAttributePersistenceProvider.h>
Andrei Litvin994c3902024-10-04 12:41:54 -040027#include <app/data-model-provider/Provider.h>
Kamil Kasperczykd9e02a02021-10-12 09:19:23 +020028#include <app/server/Dnssd.h>
Yufeng Wanga47019b2021-03-09 11:59:12 -080029#include <app/server/EchoHandler.h>
Song Guo750e2e62020-09-15 00:45:51 +080030
wendythewane6141d42022-03-24 05:47:29 -070031#if CONFIG_NETWORK_LAYER_BLE
Arkadiusz Bokowy99669402024-04-18 11:31:44 +020032#include <ble/Ble.h>
wendythewane6141d42022-03-24 05:47:29 -070033#endif
Song Guo750e2e62020-09-15 00:45:51 +080034#include <inet/IPAddress.h>
35#include <inet/InetError.h>
Zang MingJie53dd5832021-09-03 03:05:16 +080036#include <lib/core/CHIPPersistentStorageDelegate.h>
Kamil Kasperczykd9e02a02021-10-12 09:19:23 +020037#include <lib/dnssd/Advertiser.h>
38#include <lib/dnssd/ServiceNaming.h>
Zang MingJie53dd5832021-09-03 03:05:16 +080039#include <lib/support/CodeUtils.h>
Boris Zbarskycc3a98c2022-04-14 23:15:16 -040040#include <lib/support/DefaultStorageKeyAllocator.h>
Boris Zbarskycc3a98c2022-04-14 23:15:16 -040041#include <lib/support/PersistedCounter.h>
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -040042#include <lib/support/TestGroupData.h>
Zang MingJie53dd5832021-09-03 03:05:16 +080043#include <lib/support/logging/CHIPLogging.h>
Song Guoa77a6622021-01-29 13:13:02 +080044#include <messaging/ExchangeMgr.h>
Song Guo750e2e62020-09-15 00:45:51 +080045#include <platform/CHIPDeviceLayer.h>
Tennessee Carmel-Veilleux4e3930a2022-06-10 09:08:31 -040046#include <platform/DeviceControlServer.h>
Yufeng Wangbc7f2c32022-04-12 14:13:15 -070047#include <platform/DeviceInfoProvider.h>
Pankaj Garg9a791a82021-02-24 07:48:03 -080048#include <platform/KeyValueStoreManager.h>
Boris Zbarskyafa79de2023-02-14 09:40:13 -050049#include <platform/LockTracker.h>
Pankaj Garg8ced1a12021-05-14 06:55:59 -070050#include <protocols/secure_channel/CASEServer.h>
Zang MingJiec64d9d12021-05-13 00:09:08 +080051#include <protocols/secure_channel/MessageCounterManager.h>
chrisdecenzoc8bea782023-11-29 11:38:48 -080052#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
53#include <setup_payload/AdditionalDataPayloadGenerator.h>
54#endif
Vivien Nicolas0110e482020-12-02 19:45:41 +010055#include <setup_payload/SetupPayload.h>
Song Guo750e2e62020-09-15 00:45:51 +080056#include <sys/param.h>
57#include <system/SystemPacketBuffer.h>
Pankaj Garged287532021-02-09 14:38:31 -080058#include <system/TLVPacketBufferBackingStore.h>
Zang MingJieeca9bff2021-09-23 03:19:51 +080059#include <transport/SessionManager.h>
Tennessee Carmel-Veilleuxa45d5712022-06-29 23:18:33 -040060
crlonxp085f57f2024-07-30 11:21:28 +080061#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
62#include <transport/raw/WiFiPAF.h>
63#endif
64
Tennessee Carmel-Veilleuxa45d5712022-06-29 23:18:33 -040065#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
Damian Królik1c74a212022-03-10 10:45:52 +010069using namespace chip::DeviceLayer;
70
Pankaj Garg5d4d0732021-09-30 14:15:20 -070071using chip::kMinValidFabricIndex;
Jiacheng Guo735dbb02021-09-11 04:24:07 +080072using chip::RendezvousInformationFlag;
73using chip::DeviceLayer::PersistedStorage::KeyValueStoreMgr;
74using chip::Inet::IPAddressType;
wendythewane6141d42022-03-24 05:47:29 -070075#if CONFIG_NETWORK_LAYER_BLE
Jiacheng Guo735dbb02021-09-11 04:24:07 +080076using chip::Transport::BleListenParameters;
wendythewane6141d42022-03-24 05:47:29 -070077#endif
Jiacheng Guo735dbb02021-09-11 04:24:07 +080078using chip::Transport::PeerAddress;
79using chip::Transport::UdpListenParameters;
Pradip Dea8cfbac2024-03-26 20:59:15 -070080#if INET_CONFIG_ENABLE_TCP_ENDPOINT
81using chip::Transport::TcpListenParameters;
82#endif
Song Guo750e2e62020-09-15 00:45:51 +080083
Song Guo750e2e62020-09-15 00:45:51 +080084namespace {
Jiacheng Guo69d2d592020-09-18 12:19:38 +080085
Andrei Litvind099b0b2024-11-11 11:12:12 -050086chip::Access::DynamicProviderDeviceTypeResolver sDeviceTypeResolver([] {
87 return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider();
88});
Marc Lepagedf687052022-03-30 15:47:56 -040089
Song Guo750e2e62020-09-15 00:45:51 +080090} // namespace
91
Jiacheng Guo735dbb02021-09-11 04:24:07 +080092namespace chip {
93
94Server Server::sServer;
95
yunhanw-google6f89b9b2021-12-07 14:26:21 -080096#if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
97#define CHIP_NUM_EVENT_LOGGING_BUFFERS 3
98static uint8_t sInfoEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_INFO_BUFFER_SIZE];
99static uint8_t sDebugEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE];
100static uint8_t sCritEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_CRIT_BUFFER_SIZE];
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800101static PersistedCounter<EventNumber> sGlobalEventIdCounter;
102static app::CircularEventBuffer sLoggingBuffer[CHIP_NUM_EVENT_LOGGING_BUFFERS];
yunhanw-google6f89b9b2021-12-07 14:26:21 -0800103#endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
104
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400105CHIP_ERROR Server::Init(const ServerInitParams & initParams)
Pankaj Gargeac670e2021-02-02 18:36:52 -0800106{
Marc Lepagead2520a2022-04-29 15:17:17 -0400107 ChipLogProgress(AppServer, "Server initializing...");
Boris Zbarskyafa79de2023-02-14 09:40:13 -0500108 assertChipStackLockedByCurrentThread();
Marc Lepagead2520a2022-04-29 15:17:17 -0400109
Boris Zbarsky1d6a9582023-02-14 13:22:17 -0500110 mInitTimestamp = System::SystemClock().GetMonotonicMicroseconds64();
111
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -0400112 CASESessionManagerConfig caseSessionManagerConfig;
Yufeng Wangbc7f2c32022-04-12 14:13:15 -0700113 DeviceLayer::DeviceInfoProvider * deviceInfoprovider = nullptr;
Tennessee Carmel-Veilleux10ab5412022-03-10 18:37:47 -0500114
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400115 mOperationalServicePort = initParams.operationalServicePort;
116 mUserDirectedCommissioningPort = initParams.userDirectedCommissioningPort;
117 mInterfaceId = initParams.interfaceId;
Pankaj Garged287532021-02-09 14:38:31 -0800118
Song Guo750e2e62020-09-15 00:45:51 +0800119 CHIP_ERROR err = CHIP_NO_ERROR;
Song Guo750e2e62020-09-15 00:45:51 +0800120
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400121 VerifyOrExit(initParams.persistentStorageDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400122 VerifyOrExit(initParams.accessDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
Marc Lepage53c29b52022-05-03 19:02:43 -0400123 VerifyOrExit(initParams.aclStorage != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
Marc Lepagead2520a2022-04-29 15:17:17 -0400124 VerifyOrExit(initParams.groupDataProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
Damian Królikb07872c2023-02-17 13:56:47 +0100125 VerifyOrExit(initParams.sessionKeystore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
Tennessee Carmel-Veilleuxe5e09f52022-06-24 16:57:34 -0400126 VerifyOrExit(initParams.operationalKeystore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
127 VerifyOrExit(initParams.opCertStore != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
lpbeliveau-silabsa70d5b42023-08-04 17:12:49 -0400128 VerifyOrExit(initParams.reportScheduler != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400129
Andrei Litvin60dd7842024-11-20 11:11:48 -0500130 // Extra log since this is an incremental requirement and existing applications may not be aware
131 if (initParams.dataModelProvider == nullptr)
132 {
133 ChipLogError(AppServer, "Application Server requires a `initParams.dataModelProvider` value.");
Andrei Litvindad97c82024-12-05 11:30:14 -0500134 ChipLogError(AppServer, "For backwards compatibility, you likely can use `CodegenDataModelProviderInstance(...)`");
Andrei Litvin60dd7842024-11-20 11:11:48 -0500135 }
136
137 VerifyOrExit(initParams.dataModelProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
138
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800139 // TODO(16969): Remove Platform::MemoryInit() call from Server class, it belongs to outer code
140 Platform::MemoryInit();
Pankaj Garg9a791a82021-02-24 07:48:03 -0800141
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400142 // Initialize PersistentStorageDelegate-based storage
Jeff Tung37919a12023-01-20 17:58:51 -0800143 mDeviceStorage = initParams.persistentStorageDelegate;
144 mSessionResumptionStorage = initParams.sessionResumptionStorage;
145 mSubscriptionResumptionStorage = initParams.subscriptionResumptionStorage;
146 mOperationalKeystore = initParams.operationalKeystore;
147 mOpCertStore = initParams.opCertStore;
cbucht200a39e88a2023-06-29 14:59:11 -0400148 mSessionKeystore = initParams.sessionKeystore;
Boris Zbarskyec713462022-01-06 15:53:22 -0500149
Boris Zbarskydb47b1b2023-05-15 21:44:56 -0400150 if (initParams.certificateValidityPolicy)
151 {
152 mCertificateValidityPolicy.Init(initParams.certificateValidityPolicy);
153 }
154 else
155 {
156 mCertificateValidityPolicy.Init(&sDefaultCertValidityPolicy);
157 }
Michael Sandstedt8cc291d2022-06-07 10:02:58 -0500158
Tennessee Carmel-Veilleuxa45d5712022-06-29 23:18:33 -0400159#if defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT)
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800160 VerifyOrDie(audit::ExecutePersistentStorageApiAudit(*mDeviceStorage));
Tennessee Carmel-Veilleuxa45d5712022-06-29 23:18:33 -0400161#endif
162
163#if defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800164 VerifyOrDie(audit::ExecutePersistentStorageLoadTestAudit(*mDeviceStorage));
Tennessee Carmel-Veilleuxa45d5712022-06-29 23:18:33 -0400165#endif
166
Boris Zbarskyec713462022-01-06 15:53:22 -0500167 // Set up attribute persistence before we try to bring up the data model
168 // handler.
Boris Zbarskyad5253a2023-05-26 02:22:37 -0400169 SuccessOrExit(err = mAttributePersister.Init(mDeviceStorage));
William5dd4b062023-07-28 12:45:52 +0100170 SetSafeAttributePersistenceProvider(&mAttributePersister);
Boris Zbarskyec713462022-01-06 15:53:22 -0500171
Tennessee Carmel-Veilleuxe5e09f52022-06-24 16:57:34 -0400172 {
173 FabricTable::InitParams fabricTableInitParams;
174 fabricTableInitParams.storage = mDeviceStorage;
175 fabricTableInitParams.operationalKeystore = mOperationalKeystore;
176 fabricTableInitParams.opCertStore = mOpCertStore;
177
178 err = mFabrics.Init(fabricTableInitParams);
179 SuccessOrExit(err);
180 }
shana-apple3907f382021-05-05 08:50:42 +0200181
Marc Lepagead2520a2022-04-29 15:17:17 -0400182 SuccessOrExit(err = mAccessControl.Init(initParams.accessDelegate, sDeviceTypeResolver));
183 Access::SetAccessControl(mAccessControl);
Marc Lepage53c29b52022-05-03 19:02:43 -0400184
Thomas Lea87f62772024-08-27 13:27:10 -0500185#if CHIP_CONFIG_USE_ACCESS_RESTRICTIONS
186 if (initParams.accessRestrictionProvider != nullptr)
187 {
188 mAccessControl.SetAccessRestrictionProvider(initParams.accessRestrictionProvider);
189 }
190#endif
191
Marc Lepage53c29b52022-05-03 19:02:43 -0400192 mAclStorage = initParams.aclStorage;
193 SuccessOrExit(err = mAclStorage->Init(*mDeviceStorage, mFabrics.begin(), mFabrics.end()));
Marc Lepagead2520a2022-04-29 15:17:17 -0400194
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400195 mGroupsProvider = initParams.groupDataProvider;
196 SetGroupDataProvider(mGroupsProvider);
Ricardo Casallasa5513c22021-12-02 11:22:19 -0500197
lpbeliveau-silabsa70d5b42023-08-04 17:12:49 -0400198 mReportScheduler = initParams.reportScheduler;
199
tehampson64a3d3a2022-05-30 14:51:20 -0400200 mTestEventTriggerDelegate = initParams.testEventTriggerDelegate;
fesseha-eve522668f2024-07-16 14:33:24 +0200201 if (mTestEventTriggerDelegate == nullptr)
202 {
203 ChipLogProgress(AppServer, "WARNING: mTestEventTriggerDelegate is null");
204 }
tehampson64a3d3a2022-05-30 14:51:20 -0400205
Yufeng Wangbc7f2c32022-04-12 14:13:15 -0700206 deviceInfoprovider = DeviceLayer::GetDeviceInfoProvider();
207 if (deviceInfoprovider)
208 {
209 deviceInfoprovider->SetStorageDelegate(mDeviceStorage);
210 }
211
Song Guofba2fdc2020-11-21 04:08:24 +0800212 // Init transport before operations with secure session mgr.
Kevin Schoedel8e5eb8a2021-12-09 11:07:45 -0500213 err = mTransports.Init(UdpListenParameters(DeviceLayer::UDPEndPointManager())
214 .SetAddressType(IPAddressType::kIPv6)
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400215 .SetListenPort(mOperationalServicePort)
Jean-Francois Penven9405c202022-05-03 15:37:44 -0400216 .SetNativeParams(initParams.endpointNativeParams)
Pradip De0129a572025-01-09 13:59:41 -0800217#if INET_CONFIG_ENABLE_TCP_ENDPOINT
218 ,
219 TcpListenParameters(DeviceLayer::TCPEndPointManager())
220 .SetAddressType(IPAddressType::kIPv6)
221 .SetListenPort(mOperationalServicePort)
222#endif
Vivien Nicolas0110e482020-12-02 19:45:41 +0100223#if INET_CONFIG_ENABLE_IPV4
Kevin Schoedel8e5eb8a2021-12-09 11:07:45 -0500224 ,
225 UdpListenParameters(DeviceLayer::UDPEndPointManager())
226 .SetAddressType(IPAddressType::kIPv4)
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400227 .SetListenPort(mOperationalServicePort)
Vivien Nicolas0110e482020-12-02 19:45:41 +0100228#endif
Song Guo87142e02021-04-21 09:00:00 +0800229#if CONFIG_NETWORK_LAYER_BLE
Kevin Schoedel8e5eb8a2021-12-09 11:07:45 -0500230 ,
231 BleListenParameters(DeviceLayer::ConnectivityMgr().GetBleLayer())
Song Guo87142e02021-04-21 09:00:00 +0800232#endif
crlonxp085f57f2024-07-30 11:21:28 +0800233#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
234 ,
235 Transport::WiFiPAFListenParameters(DeviceLayer::ConnectivityMgr().GetWiFiPAF())
236#endif
Song Guo87142e02021-04-21 09:00:00 +0800237 );
238
Sam Ryan9cd8c0d2023-12-08 17:29:05 -0500239 SuccessOrExit(err);
Boris Zbarsky393b3192022-06-01 10:09:08 -0400240 err = mListener.Init(this);
mkardous-silabsde955672022-01-25 16:05:37 -0500241 SuccessOrExit(err);
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400242 mGroupsProvider->SetListener(&mListener);
mkardous-silabsde955672022-01-25 16:05:37 -0500243
Sweetyc6db3372021-09-30 06:55:02 +0530244#if CONFIG_NETWORK_LAYER_BLE
245 mBleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer();
246#endif
Song Guofba2fdc2020-11-21 04:08:24 +0800247 SuccessOrExit(err);
248
Damian Królikb07872c2023-02-17 13:56:47 +0100249 err = mSessions.Init(&DeviceLayer::SystemLayer(), &mTransports, &mMessageCounterManager, mDeviceStorage, &GetFabricTable(),
cbucht200a39e88a2023-06-29 14:59:11 -0400250 *mSessionKeystore);
Song Guo750e2e62020-09-15 00:45:51 +0800251 SuccessOrExit(err);
252
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -0400253 err = mFabricDelegate.Init(this);
Jean-Francois Penvena69fde32022-03-08 14:57:39 -0500254 SuccessOrExit(err);
255 mFabrics.AddFabricDelegate(&mFabricDelegate);
256
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800257 err = mExchangeMgr.Init(&mSessions);
Song Guoa77a6622021-01-29 13:13:02 +0800258 SuccessOrExit(err);
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800259 err = mMessageCounterManager.Init(&mExchangeMgr);
Zang MingJiec64d9d12021-05-13 00:09:08 +0800260 SuccessOrExit(err);
Pankaj Gargfad6d052021-01-20 12:26:34 -0800261
Boris Zbarsky83a08632022-06-15 20:11:04 -0400262 err = mUnsolicitedStatusHandler.Init(&mExchangeMgr);
263 SuccessOrExit(err);
264
Boris Zbarsky39e5ed22022-07-14 14:34:50 -0400265 SuccessOrExit(err = mCommissioningWindowManager.Init(this));
266 mCommissioningWindowManager.SetAppDelegate(initParams.appDelegate);
267
268 app::DnssdServer::Instance().SetFabricTable(&mFabrics);
269 app::DnssdServer::Instance().SetCommissioningModeProvider(&mCommissioningWindowManager);
270
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800271 Dnssd::Resolver::Instance().Init(DeviceLayer::UDPEndPointManager());
Andrei Litvinb4fd95f2022-03-15 17:10:11 -0400272
yunhanw-google6f89b9b2021-12-07 14:26:21 -0800273#if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
274 // Initialize event logging subsystem
Andrei Litvin59aa6b72022-11-03 15:53:41 -0400275 err = sGlobalEventIdCounter.Init(mDeviceStorage, DefaultStorageKeyAllocator::IMEventNumber(),
Boris Zbarskycc3a98c2022-04-14 23:15:16 -0400276 CHIP_DEVICE_CONFIG_EVENT_ID_COUNTER_EPOCH);
277 SuccessOrExit(err);
yunhanw-google6f89b9b2021-12-07 14:26:21 -0800278
Boris Zbarskycc3a98c2022-04-14 23:15:16 -0400279 {
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800280 app::LogStorageResources logStorageResources[] = {
281 { &sDebugEventBuffer[0], sizeof(sDebugEventBuffer), app::PriorityLevel::Debug },
282 { &sInfoEventBuffer[0], sizeof(sInfoEventBuffer), app::PriorityLevel::Info },
283 { &sCritEventBuffer[0], sizeof(sCritEventBuffer), app::PriorityLevel::Critical }
yunhanw-google6f89b9b2021-12-07 14:26:21 -0800284 };
285
Yuanyao Zhonga219ff72025-01-10 14:27:33 -0500286 err = app::EventManagement::GetInstance().Init(&mExchangeMgr, CHIP_NUM_EVENT_LOGGING_BUFFERS, &sLoggingBuffer[0],
287 &logStorageResources[0], &sGlobalEventIdCounter,
288 std::chrono::duration_cast<System::Clock::Milliseconds64>(mInitTimestamp),
289 &app::InteractionModelEngine::GetInstance()->GetReportingEngine());
290
291 SuccessOrExit(err);
yunhanw-google6f89b9b2021-12-07 14:26:21 -0800292 }
293#endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
294
Yufeng Wanga9bd0ce2024-12-17 11:26:26 -0800295 // SetDataModelProvider() initializes and starts the provider, which in turn
296 // triggers the initialization of cluster implementations. This callsite is
297 // critical because it ensures that cluster-level initialization occurs only
298 // after all necessary low-level dependencies have been set up.
299 //
300 // Ordering guarantees:
301 // 1) Provider initialization (under SetDataModelProvider) must happen after
302 // SetSafeAttributePersistenceProvider to ensure the provider can leverage
303 // the safe persistence provider for attribute persistence logic.
304 // 2) It must occur after all low-level components that cluster implementations
305 // might depend on have been initialized, as they rely on these components
306 // during their own initialization.
307 //
308 // This remains the single point of entry to ensure that all cluster-level
309 // initialization is performed in the correct order.
310 app::InteractionModelEngine::GetInstance()->SetDataModelProvider(initParams.dataModelProvider);
Jean-Francois Penvenb673df52023-09-06 14:39:47 -0400311
Yufeng Wanga47019b2021-03-09 11:59:12 -0800312#if defined(CHIP_APP_USE_ECHO)
Vivien Nicolasb58b7be2022-04-01 04:11:04 +0200313 err = InitEchoHandler(&mExchangeMgr);
Yufeng Wanga47019b2021-03-09 11:59:12 -0800314 SuccessOrExit(err);
315#endif
316
Jerry Johnsb7a77882022-07-08 15:11:24 -0700317 //
318 // We need to advertise the port that we're listening to for unsolicited messages over UDP. However, we have both a IPv4
319 // and IPv6 endpoint to pick from. Given that the listen port passed in may be set to 0 (which then has the kernel select
320 // a valid port at bind time), that will result in two possible ports being provided back from the resultant endpoint
321 // initializations. Since IPv6 is POR for Matter, let's go ahead and pick that port.
322 //
323 app::DnssdServer::Instance().SetSecuredPort(mTransports.GetTransport().GetImplAtIndex<0>().GetBoundPort());
324
Vivien Nicolasc9350f72022-04-12 06:45:34 +0200325 app::DnssdServer::Instance().SetUnsecuredPort(mUserDirectedCommissioningPort);
326 app::DnssdServer::Instance().SetInterfaceId(mInterfaceId);
327
mkardous-silabs6778d3e2023-11-28 17:39:41 -0500328#if CHIP_CONFIG_ENABLE_ICD_SERVER
329 // We set the ICDManager reference betfore calling the ICDManager init due to the init ordering limitations.
330 // DnssdServer will use the default value initially and will update advertisement once ICDManager
331 // init is called.
332 app::DnssdServer::Instance().SetICDManager(&mICDManager);
333#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
334
Pradip De0129a572025-01-09 13:59:41 -0800335#if INET_CONFIG_ENABLE_TCP_ENDPOINT
336 app::DnssdServer::Instance().SetTCPServerEnabled(mTransports.GetTransport().GetImplAtIndex<1>().IsServerListenEnabled());
337#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
338
Boris Zbarsky4d6858b2022-03-24 08:30:14 -0400339 if (GetFabricTable().FabricCount() != 0)
Pankaj Gargeac670e2021-02-02 18:36:52 -0800340 {
Yufeng Wang9afad662024-10-22 10:21:42 -0700341#if CONFIG_NETWORK_LAYER_BLE
Pankaj Gargccdffbc2021-09-24 09:10:22 -0700342 // The device is already commissioned, proactively disable BLE advertisement.
343 ChipLogProgress(AppServer, "Fabric already commissioned. Disabling BLE advertisement");
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800344 DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false);
Hui.Li-TCL360252c2022-01-05 00:04:21 +0800345#endif
Pankaj Gargeac670e2021-02-02 18:36:52 -0800346 }
Vivien Nicolas0110e482020-12-02 19:45:41 +0100347 else
Jiacheng Guodf2497d2020-09-30 21:16:57 +0800348 {
Kamil Kasperczyk6ad57112021-02-11 16:44:36 +0100349#if CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART
Pankaj Garg2815a102021-09-15 17:22:34 -0700350 SuccessOrExit(err = mCommissioningWindowManager.OpenBasicCommissioningWindow());
Kamil Kasperczyk6ad57112021-02-11 16:44:36 +0100351#endif
Jiacheng Guodf2497d2020-09-30 21:16:57 +0800352 }
Jiacheng Guodf2497d2020-09-30 21:16:57 +0800353
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800354 // TODO @bzbarsky-apple @cecille Move to examples
355 // ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD
Andrei Litvinb7924632022-03-03 15:29:54 -0500356#if !CHIP_DEVICE_LAYER_TARGET_ESP32 && !CHIP_DEVICE_LAYER_TARGET_MBED && \
pankorebab75e62021-10-28 21:48:46 +0800357 (!CHIP_DEVICE_LAYER_TARGET_AMEBA || !CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE)
chrisdecenzo515ea652021-08-18 11:27:09 -0700358 // StartServer only enables commissioning mode if device has not been commissioned
Kamil Kasperczykd9e02a02021-10-12 09:19:23 +0200359 app::DnssdServer::Instance().StartServer();
Paul Zander3510f142021-04-15 16:29:40 +0200360#endif
Kamil Kasperczyk44014022021-03-12 21:18:45 +0100361
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -0400362 caseSessionManagerConfig = {
363 .sessionInitParams = {
364 .sessionManager = &mSessions,
Zang MingJie7dede202022-04-06 11:54:50 +0800365 .sessionResumptionStorage = mSessionResumptionStorage,
Boris Zbarskyed8d5462023-05-05 12:19:38 -0400366 .certificateValidityPolicy = &mCertificateValidityPolicy,
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -0400367 .exchangeMgr = &mExchangeMgr,
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -0400368 .fabricTable = &mFabrics,
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400369 .groupDataProvider = mGroupsProvider,
Boris Zbarskyac1ebc52024-02-29 21:59:14 -0500370 // Don't provide an MRP local config, so each CASE initiation will use
371 // the then-current value.
372 .mrpLocalConfig = NullOptional,
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -0400373 },
Damian Królikffecbc12022-12-14 19:00:35 +0100374 .clientPool = &mCASEClientPool,
375 .sessionSetupPool = &mSessionSetupPool,
Tennessee Carmel-Veilleux1c03d9c2022-03-30 17:44:08 -0400376 };
377
378 err = mCASESessionManager.Init(&DeviceLayer::SystemLayer(), caseSessionManagerConfig);
379 SuccessOrExit(err);
380
Michael Sandstedt8cc291d2022-06-07 10:02:58 -0500381 err = mCASEServer.ListenForSessionEstablishment(&mExchangeMgr, &mSessions, &mFabrics, mSessionResumptionStorage,
Boris Zbarskyed8d5462023-05-05 12:19:38 -0400382 &mCertificateValidityPolicy, mGroupsProvider);
Pankaj Garg8ced1a12021-05-14 06:55:59 -0700383 SuccessOrExit(err);
384
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800385 err = app::InteractionModelEngine::GetInstance()->Init(&mExchangeMgr, &GetFabricTable(), mReportScheduler, &mCASESessionManager,
386 mSubscriptionResumptionStorage);
Jerry Johns6cd46762022-07-27 12:42:07 -0700387 SuccessOrExit(err);
388
mkardous-silabs96329ae2024-04-03 22:17:11 -0400389#if CHIP_CONFIG_ENABLE_ICD_SERVER
390 app::InteractionModelEngine::GetInstance()->SetICDManager(&mICDManager);
391#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
392
Jean-Francois Penvened891e22023-11-28 13:18:44 -0500393 // ICD Init needs to be after data model init and InteractionModel Init
394#if CHIP_CONFIG_ENABLE_ICD_SERVER
mkardous-silabs6778d3e2023-11-28 17:39:41 -0500395
396 // Register the ICDStateObservers.
397 // Call register before init so that observers are notified of any state change during the init.
398 // All observers are released at mICDManager.Shutdown(). They can be released individually with ReleaseObserver
Jean-Francois Penvened891e22023-11-28 13:18:44 -0500399 mICDManager.RegisterObserver(mReportScheduler);
400 mICDManager.RegisterObserver(&app::DnssdServer::Instance());
mkardous-silabs6778d3e2023-11-28 17:39:41 -0500401
mkardous-silabs5eba3942024-07-26 19:42:45 -0400402#if CHIP_CONFIG_ENABLE_ICD_CIP
403 mICDManager.SetPersistentStorageDelegate(mDeviceStorage)
404 .SetFabricTable(&GetFabricTable())
405 .SetSymmetricKeyStore(mSessionKeystore)
406 .SetExchangeManager(&mExchangeMgr)
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800407 .SetSubscriptionsInfoProvider(app::InteractionModelEngine::GetInstance())
mkardous-silabs5eba3942024-07-26 19:42:45 -0400408 .SetICDCheckInBackOffStrategy(initParams.icdCheckInBackOffStrategy);
409
410#endif // CHIP_CONFIG_ENABLE_ICD_CIP
411 mICDManager.Init();
mkardous-silabs845ce9b2024-04-09 20:13:38 -0400412
413 // Register Test Event Trigger Handler
fesseha-eve522668f2024-07-16 14:33:24 +0200414 if (mTestEventTriggerDelegate != nullptr)
415 {
416 mTestEventTriggerDelegate->AddHandler(&mICDManager);
417 }
mkardous-silabs845ce9b2024-04-09 20:13:38 -0400418
Jean-Francois Penvened891e22023-11-28 13:18:44 -0500419#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
420
mkardous-silabsde955672022-01-25 16:05:37 -0500421 // This code is necessary to restart listening to existing groups after a reboot
422 // Each manufacturer needs to validate that they can rejoin groups by placing this code at the appropriate location for them
423 //
Damian Królikb80df3d2022-03-30 14:33:14 +0200424 // Thread LWIP devices using dedicated Inet endpoint implementations are excluded because they call this function from:
mkardous-silabsde955672022-01-25 16:05:37 -0500425 // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.cpp
Damian Królikb80df3d2022-03-30 14:33:14 +0200426#if !CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
mkardous-silabs3c31ec72022-02-24 17:37:45 -0500427 RejoinExistingMulticastGroups();
Damian Królikb80df3d2022-03-30 14:33:14 +0200428#endif // !CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
mkardous-silabs3c31ec72022-02-24 17:37:45 -0500429
Tennessee Carmel-Veilleuxb91727b2022-06-28 20:52:02 -0400430 // Handle deferred clean-up of a previously armed fail-safe that occurred during FabricTable commit.
431 // This is done at the very end since at the earlier time above when FabricTable::Init() is called,
432 // the delegates could not have been registered, and the other systems were not initialized. By now,
433 // everything is initialized, so we can do a deferred clean-up.
434 {
435 FabricIndex fabricIndexDeletedOnInit = GetFabricTable().GetDeletedFabricFromCommitMarker();
436 if (fabricIndexDeletedOnInit != kUndefinedFabricIndex)
437 {
438 ChipLogError(AppServer, "FabricIndex 0x%x deleted due to restart while fail-safed. Processing a clean-up!",
439 static_cast<unsigned>(fabricIndexDeletedOnInit));
440
441 // Always pretend it was an add, since being in the middle of an update currently breaks
442 // the validity of the fabric table. This is expected to be extremely infrequent, so
443 // this "harsher" than usual clean-up is more likely to get us in a valid state for whatever
444 // remains.
445 const bool addNocCalled = true;
446 const bool updateNocCalled = false;
447 GetFailSafeContext().ScheduleFailSafeCleanup(fabricIndexDeletedOnInit, addNocCalled, updateNocCalled);
448
449 // Schedule clearing of the commit marker to only occur after we have processed all fail-safe clean-up.
450 // Because Matter runs a single event loop for all scheduled work, it will occur after the above has
451 // taken place. If a reset occurs before we have cleaned everything up, the next boot will still
452 // see the commit marker.
453 PlatformMgr().ScheduleWork(
454 [](intptr_t arg) {
455 Server * server = reinterpret_cast<Server *>(arg);
456 VerifyOrReturn(server != nullptr);
457
458 server->GetFabricTable().ClearCommitMarker();
459 ChipLogProgress(AppServer, "Cleared FabricTable pending commit marker");
460 },
461 reinterpret_cast<intptr_t>(this));
462 }
463 }
464
chrisdecenzoc8bea782023-11-29 11:38:48 -0800465#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT // support UDC port for commissioner declaration msgs
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800466 mUdcTransportMgr = Platform::New<UdcTransportMgr>();
chrisdecenzoc8bea782023-11-29 11:38:48 -0800467 ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
468 .SetAddressType(Inet::IPAddressType::kIPv6)
469 .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
470#if INET_CONFIG_ENABLE_IPV4
471 ,
472 Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
473 .SetAddressType(Inet::IPAddressType::kIPv4)
474 .SetListenPort(static_cast<uint16_t>(mCdcListenPort))
475#endif // INET_CONFIG_ENABLE_IPV4
476 ));
477
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800478 gUDCClient = Platform::New<Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient>();
chrisdecenzoc8bea782023-11-29 11:38:48 -0800479 mUdcTransportMgr->SetSessionManager(gUDCClient);
480#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
481
Damian Królik5a845c62023-02-02 10:51:40 +0100482 PlatformMgr().AddEventHandler(OnPlatformEventWrapper, reinterpret_cast<intptr_t>(this));
Damian Królik1c74a212022-03-10 10:45:52 +0100483 PlatformMgr().HandleServerStarted();
484
Damian Królik5a845c62023-02-02 10:51:40 +0100485 mIsDnssdReady = Dnssd::Resolver::Instance().IsInitialized();
486 CheckServerReadyEvent();
487
Song Guo750e2e62020-09-15 00:45:51 +0800488exit:
489 if (err != CHIP_NO_ERROR)
490 {
Damian Królik5e9d4132022-06-27 09:02:15 +0200491 ChipLogError(AppServer, "ERROR setting up transport: %" CHIP_ERROR_FORMAT, err.Format());
Song Guo750e2e62020-09-15 00:45:51 +0800492 }
493 else
494 {
Marc Lepagead2520a2022-04-29 15:17:17 -0400495 // NOTE: this log is scraped by the test harness.
Song Guo750e2e62020-09-15 00:45:51 +0800496 ChipLogProgress(AppServer, "Server Listening...");
497 }
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800498 return err;
499}
500
Damian Królik5a845c62023-02-02 10:51:40 +0100501void Server::OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event)
502{
503 switch (event.Type)
504 {
Damian Królik40f77172023-02-14 17:53:28 +0100505 case DeviceEventType::kDnssdInitialized:
Damian Królik5a845c62023-02-02 10:51:40 +0100506 // Platform DNS-SD implementation uses kPlatformDnssdInitialized event to signal that it's ready.
507 if (!mIsDnssdReady)
508 {
509 mIsDnssdReady = true;
510 CheckServerReadyEvent();
511 }
512 break;
513 case DeviceEventType::kServerReady:
Kamil Kasperczyk91ba8b62024-02-14 10:28:02 +0100514#if CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
mkardous-silabs3fe8ec62024-02-07 21:12:15 -0500515 // Only Trigger Check-In messages if we are not in the middle of a commissioning.
516 // This check is only necessary for the first commissioiner since the kServerReady event
517 // is triggered once we join the network.
518 // We trigger Check-In messages before resuming subscriptions to avoid doing both.
519 if (!mFailSafeContext.IsFailSafeArmed())
520 {
mkardous-silabs96329ae2024-04-03 22:17:11 -0400521 std::function<app::ICDManager::ShouldCheckInMsgsBeSentFunction> sendCheckInMessagesOnBootUp =
522 std::bind(&Server::ShouldCheckInMsgsBeSentAtBootFunction, this, std::placeholders::_1, std::placeholders::_2);
523 mICDManager.TriggerCheckInMessages(sendCheckInMessagesOnBootUp);
mkardous-silabs3fe8ec62024-02-07 21:12:15 -0500524 }
Kamil Kasperczyk91ba8b62024-02-14 10:28:02 +0100525#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && CHIP_CONFIG_ENABLE_ICD_CIP
Damian Królik5a845c62023-02-02 10:51:40 +0100526#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
527 ResumeSubscriptions();
mkardous-silabs96329ae2024-04-03 22:17:11 -0400528#endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
Damian Królik5a845c62023-02-02 10:51:40 +0100529 break;
Jean-Francois Penven41971ba2023-11-21 23:13:56 -0500530#if CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
531 case DeviceEventType::kThreadConnectivityChange:
532 if (event.ThreadConnectivityChange.Result == kConnectivity_Established)
533 {
534 // Refresh Multicast listening
535 ChipLogDetail(DeviceLayer, "Thread Attached updating Multicast address");
536 RejoinExistingMulticastGroups();
537 }
538 break;
539#endif // CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
Damian Królik5a845c62023-02-02 10:51:40 +0100540 default:
541 break;
542 }
543}
544
545void Server::CheckServerReadyEvent()
546{
547 // Check if all asynchronously initialized server components (currently, only DNS-SD)
548 // are ready, and emit the 'server ready' event if so.
549 if (mIsDnssdReady)
550 {
Shubham Patilb5cd9252023-06-03 03:47:41 +0530551 ChipLogProgress(AppServer, "Server initialization complete");
Damian Królik40f77172023-02-14 17:53:28 +0100552
Damian Królik5a845c62023-02-02 10:51:40 +0100553 ChipDeviceEvent event = { .Type = DeviceEventType::kServerReady };
554 PlatformMgr().PostEventOrDie(&event);
555 }
556}
557
558void Server::OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t server)
559{
560 reinterpret_cast<Server *>(server)->OnPlatformEvent(*event);
561}
562
mkardous-silabs3c31ec72022-02-24 17:37:45 -0500563void Server::RejoinExistingMulticastGroups()
564{
565 ChipLogProgress(AppServer, "Joining Multicast groups");
566 CHIP_ERROR err = CHIP_NO_ERROR;
567 for (const FabricInfo & fabric : mFabrics)
568 {
569 Credentials::GroupDataProvider::GroupInfo groupInfo;
570
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400571 auto * iterator = mGroupsProvider->IterateGroupInfo(fabric.GetFabricIndex());
mkardous-silabs3c31ec72022-02-24 17:37:45 -0500572 if (iterator)
573 {
574 // GroupDataProvider was able to allocate rescources for an iterator
575 while (iterator->Next(groupInfo))
576 {
577 err = mTransports.MulticastGroupJoinLeave(
Boris Zbarsky393b3192022-06-01 10:09:08 -0400578 Transport::PeerAddress::Multicast(fabric.GetFabricId(), groupInfo.group_id), true);
mkardous-silabs3c31ec72022-02-24 17:37:45 -0500579 if (err != CHIP_NO_ERROR)
580 {
andrei-menzopol57471cb2022-04-20 23:31:17 +0300581 ChipLogError(AppServer, "Error when trying to join Group %u of fabric index %u : %" CHIP_ERROR_FORMAT,
mkardous-silabs3c31ec72022-02-24 17:37:45 -0500582 groupInfo.group_id, fabric.GetFabricIndex(), err.Format());
583
584 // We assume the failure is caused by a network issue or a lack of rescources; neither of which will be solved
585 // before the next join. Exit the loop to save rescources.
586 iterator->Release();
587 return;
588 }
589 }
590
591 iterator->Release();
592 }
593 }
594}
595
mkardous-silabs96329ae2024-04-03 22:17:11 -0400596#if CHIP_CONFIG_ENABLE_ICD_CIP
597bool Server::ShouldCheckInMsgsBeSentAtBootFunction(FabricIndex aFabricIndex, NodeId subjectID)
598{
599#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
600 // If at least one registration has a persisted entry, do not send Check-In message.
601 // The resumption of the persisted subscription will serve the same function a check-in would have served.
602 return !app::InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(aFabricIndex, subjectID);
603#else
604 return true;
605#endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
606}
607#endif // CHIP_CONFIG_ENABLE_ICD_CIP
608
Boris Zbarsky336f1c52023-02-17 09:39:19 -0500609void Server::GenerateShutDownEvent()
Vivien Nicolas82976172022-02-16 11:47:52 +0100610{
Damian Królik1c74a212022-03-10 10:45:52 +0100611 PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().HandleServerShuttingDown(); });
Vivien Nicolas82976172022-02-16 11:47:52 +0100612}
613
Kamil Kasperczyk843643c2022-02-23 17:38:32 +0100614void Server::ScheduleFactoryReset()
615{
Damian Królik1c74a212022-03-10 10:45:52 +0100616 PlatformMgr().ScheduleWork([](intptr_t) {
617 // Delete all fabrics and emit Leave event.
618 GetInstance().GetFabricTable().DeleteAllFabrics();
619 PlatformMgr().HandleServerShuttingDown();
620 ConfigurationMgr().InitiateFactoryReset();
621 });
Kamil Kasperczyk843643c2022-02-23 17:38:32 +0100622}
623
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800624void Server::Shutdown()
625{
Boris Zbarskyafa79de2023-02-14 09:40:13 -0500626 assertChipStackLockedByCurrentThread();
Damian Królik5a845c62023-02-02 10:51:40 +0100627 PlatformMgr().RemoveEventHandler(OnPlatformEventWrapper, 0);
Jerry Johnsc2a869a2022-06-09 21:46:47 -0700628 mCASEServer.Shutdown();
Douglas Rocha Ferrazcbc57d62022-06-02 09:57:15 -0400629 mCASESessionManager.Shutdown();
mkardous-silabs6778d3e2023-11-28 17:39:41 -0500630#if CHIP_CONFIG_ENABLE_ICD_SERVER
631 app::DnssdServer::Instance().SetICDManager(nullptr);
632#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
Boris Zbarsky999aeae2022-03-07 08:44:13 -0500633 app::DnssdServer::Instance().SetCommissioningModeProvider(nullptr);
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800634 Dnssd::ServiceAdvertiser::Instance().Shutdown();
chrisdecenzoc8bea782023-11-29 11:38:48 -0800635
636#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
637 if (mUdcTransportMgr != nullptr)
638 {
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800639 Platform::Delete(mUdcTransportMgr);
chrisdecenzoc8bea782023-11-29 11:38:48 -0800640 mUdcTransportMgr = nullptr;
641 }
642 if (gUDCClient != nullptr)
643 {
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800644 Platform::Delete(gUDCClient);
chrisdecenzoc8bea782023-11-29 11:38:48 -0800645 gUDCClient = nullptr;
646 }
647#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
648
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800649 Dnssd::Resolver::Instance().Shutdown();
650 app::InteractionModelEngine::GetInstance()->Shutdown();
mkardous-silabs96329ae2024-04-03 22:17:11 -0400651#if CHIP_CONFIG_ENABLE_ICD_SERVER
652 app::InteractionModelEngine::GetInstance()->SetICDManager(nullptr);
653#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
Boris Zbarsky674dca82024-06-21 15:01:11 -0400654 // Shut down any remaining sessions (and hence exchanges) before we do any
655 // futher teardown. CASE handshakes have been shut down already via
656 // shutting down mCASESessionManager and mCASEServer above; shutting
657 // down mCommissioningWindowManager will shut down any PASE handshakes we
658 // have going on.
659 mSessions.ExpireAllSecureSessions();
Boris Zbarsky39e5ed22022-07-14 14:34:50 -0400660 mCommissioningWindowManager.Shutdown();
Douglas Rocha Ferrazcbc57d62022-06-02 09:57:15 -0400661 mMessageCounterManager.Shutdown();
Michael Spang63870492022-06-28 08:41:08 -0400662 mExchangeMgr.Shutdown();
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800663 mSessions.Shutdown();
664 mTransports.Close();
Douglas Rocha Ferrazcbc57d62022-06-02 09:57:15 -0400665 mAccessControl.Finish();
Michael Sandstedt5a0e3ce2022-11-03 12:00:25 -0500666 Access::ResetAccessControlToDefault();
Douglas Rocha Ferrazcbc57d62022-06-02 09:57:15 -0400667 Credentials::SetGroupDataProvider(nullptr);
Junior Martinezac060dc2023-07-10 17:31:05 -0400668#if CHIP_CONFIG_ENABLE_ICD_SERVER
mkardous-silabs845ce9b2024-04-09 20:13:38 -0400669 // Remove Test Event Trigger Handler
fesseha-eve522668f2024-07-16 14:33:24 +0200670 if (mTestEventTriggerDelegate != nullptr)
671 {
672 mTestEventTriggerDelegate->RemoveHandler(&mICDManager);
673 }
Junior Martinezac060dc2023-07-10 17:31:05 -0400674 mICDManager.Shutdown();
Junior Martinezfb5558d2023-06-15 09:29:02 -0400675#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
Andrei Litvindad97c82024-12-05 11:30:14 -0500676
Tennessee Carmel-Veilleuxdef18812022-04-04 13:12:25 -0400677 // TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800678 chip::Platform::MemoryShutdown();
Song Guo750e2e62020-09-15 00:45:51 +0800679}
Andrei Litvin7093fde2021-02-26 16:13:23 -0500680
chrisdecenzo250d5f72021-07-21 19:28:45 -0700681#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
682// NOTE: UDC client is located in Server.cpp because it really only makes sense
683// to send UDC from a Matter device. The UDC message payload needs to include the device's
684// randomly generated service name.
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800685CHIP_ERROR Server::SendUserDirectedCommissioningRequest(Transport::PeerAddress commissioner,
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800686 Protocols::UserDirectedCommissioning::IdentificationDeclaration & id)
chrisdecenzo250d5f72021-07-21 19:28:45 -0700687{
Philip Gregora2ded0f2024-05-07 12:41:05 -0700688 ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest()");
chrisdecenzo250d5f72021-07-21 19:28:45 -0700689
690 CHIP_ERROR err;
chrisdecenzo250d5f72021-07-21 19:28:45 -0700691
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800692 // only populate fields left blank by the client
693 if (strlen(id.GetInstanceName()) == 0)
chrisdecenzo250d5f72021-07-21 19:28:45 -0700694 {
Philip Gregor320f83e2024-05-17 12:43:00 -0700695 ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Instance Name not known");
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800696 char nameBuffer[Dnssd::Commission::kInstanceNameMaxLength + 1];
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800697 err = app::DnssdServer::Instance().GetCommissionableInstanceName(nameBuffer, sizeof(nameBuffer));
698 if (err != CHIP_NO_ERROR)
699 {
Philip Gregor320f83e2024-05-17 12:43:00 -0700700 ChipLogError(
701 AppServer,
702 "Server::SendUserDirectedCommissioningRequest() Failed to get mdns instance name error: %" CHIP_ERROR_FORMAT,
703 err.Format());
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800704 return err;
705 }
706 id.SetInstanceName(nameBuffer);
Philip Gregor320f83e2024-05-17 12:43:00 -0700707 ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Instance Name set to %s", nameBuffer);
chrisdecenzoc8bea782023-11-29 11:38:48 -0800708 }
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800709
710 if (id.GetVendorId() == 0)
chrisdecenzoc8bea782023-11-29 11:38:48 -0800711 {
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800712 uint16_t vendorId = 0;
713 if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetVendorId(vendorId) != CHIP_NO_ERROR)
714 {
Philip Gregor320f83e2024-05-17 12:43:00 -0700715 ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Vendor ID not known");
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800716 }
717 else
718 {
719 id.SetVendorId(vendorId);
720 }
chrisdecenzo31c62492021-08-10 11:47:15 -0700721 }
chrisdecenzo250d5f72021-07-21 19:28:45 -0700722
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800723 if (id.GetProductId() == 0)
chrisdecenzoc8bea782023-11-29 11:38:48 -0800724 {
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800725 uint16_t productId = 0;
726 if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetProductId(productId) != CHIP_NO_ERROR)
727 {
Philip Gregor320f83e2024-05-17 12:43:00 -0700728 ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Product ID not known");
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800729 }
730 else
731 {
732 id.SetProductId(productId);
733 }
chrisdecenzoc8bea782023-11-29 11:38:48 -0800734 }
735
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800736 if (strlen(id.GetDeviceName()) == 0)
chrisdecenzoc8bea782023-11-29 11:38:48 -0800737 {
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800738 char deviceName[Dnssd::kKeyDeviceNameMaxLength + 1] = {};
739 if (!DeviceLayer::ConfigurationMgr().IsCommissionableDeviceNameEnabled() ||
740 DeviceLayer::ConfigurationMgr().GetCommissionableDeviceName(deviceName, sizeof(deviceName)) != CHIP_NO_ERROR)
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800741 {
Philip Gregor320f83e2024-05-17 12:43:00 -0700742 ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Device Name not known");
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800743 }
744 else
745 {
746 id.SetDeviceName(deviceName);
747 }
chrisdecenzoc8bea782023-11-29 11:38:48 -0800748 }
749
750#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800751 if (id.GetRotatingIdLength() == 0)
752 {
chrisdecenzo31fa02f2024-03-26 09:38:19 -0700753 AdditionalDataPayloadGeneratorParams additionalDataPayloadParams;
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800754 uint8_t rotatingDeviceIdUniqueId[DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength];
chrisdecenzo31fa02f2024-03-26 09:38:19 -0700755 MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId);
chrisdecenzoc8bea782023-11-29 11:38:48 -0800756
chrisdecenzo31fa02f2024-03-26 09:38:19 -0700757 ReturnErrorOnFailure(
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800758 DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan));
chrisdecenzo31fa02f2024-03-26 09:38:19 -0700759 ReturnErrorOnFailure(
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800760 DeviceLayer::ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter));
chrisdecenzo31fa02f2024-03-26 09:38:19 -0700761 additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan;
762
763 uint8_t rotatingDeviceIdInternalBuffer[RotatingDeviceId::kMaxLength];
764 MutableByteSpan rotatingDeviceIdBufferTemp(rotatingDeviceIdInternalBuffer);
765 ReturnErrorOnFailure(AdditionalDataPayloadGenerator().generateRotatingDeviceIdAsBinary(additionalDataPayloadParams,
766 rotatingDeviceIdBufferTemp));
767
768 id.SetRotatingId(rotatingDeviceIdInternalBuffer, RotatingDeviceId::kMaxLength);
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800769 }
chrisdecenzoc8bea782023-11-29 11:38:48 -0800770#endif
771
chrisdecenzo7dbacc62024-01-18 11:57:05 -0800772 if (id.GetCdPort() == 0)
773 {
774 id.SetCdPort(mCdcListenPort);
775 }
chrisdecenzoc8bea782023-11-29 11:38:48 -0800776
777 err = gUDCClient->SendUDCMessage(&mTransports, id, commissioner);
778
chrisdecenzo31c62492021-08-10 11:47:15 -0700779 if (err == CHIP_NO_ERROR)
780 {
Philip Gregor320f83e2024-05-17 12:43:00 -0700781 ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Send UDC request success");
chrisdecenzo31c62492021-08-10 11:47:15 -0700782 }
783 else
784 {
Philip Gregor320f83e2024-05-17 12:43:00 -0700785 ChipLogError(AppServer, "Server::SendUserDirectedCommissioningRequest() Send UDC request failed, err: %" CHIP_ERROR_FORMAT,
786 err.Format());
chrisdecenzo250d5f72021-07-21 19:28:45 -0700787 }
788 return err;
789}
chrisdecenzo250d5f72021-07-21 19:28:45 -0700790#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
791
Jeff Tung37919a12023-01-20 17:58:51 -0800792#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
793void Server::ResumeSubscriptions()
794{
Yufeng Wangc2739ca2024-12-05 14:14:38 -0800795 CHIP_ERROR err = app::InteractionModelEngine::GetInstance()->ResumeSubscriptions();
Jeff Tung37919a12023-01-20 17:58:51 -0800796 if (err != CHIP_NO_ERROR)
797 {
798 ChipLogError(AppServer, "Error when trying to resume subscriptions : %" CHIP_ERROR_FORMAT, err.Format());
799 }
800}
801#endif
802
Boris Zbarskydb47b1b2023-05-15 21:44:56 -0400803Credentials::IgnoreCertificateValidityPeriodPolicy Server::sDefaultCertValidityPolicy;
804
Damian Królikb07872c2023-02-17 13:56:47 +0100805KvsPersistentStorageDelegate CommonCaseDeviceServerInitParams::sKvsPersistenStorageDelegate;
806PersistentStorageOperationalKeystore CommonCaseDeviceServerInitParams::sPersistentStorageOperationalKeystore;
807Credentials::PersistentStorageOpCertStore CommonCaseDeviceServerInitParams::sPersistentStorageOpCertStore;
808Credentials::GroupDataProviderImpl CommonCaseDeviceServerInitParams::sGroupDataProvider;
lpbeliveau-silabsa70d5b42023-08-04 17:12:49 -0400809app::DefaultTimerDelegate CommonCaseDeviceServerInitParams::sTimerDelegate;
810app::reporting::ReportSchedulerImpl
811 CommonCaseDeviceServerInitParams::sReportScheduler(&CommonCaseDeviceServerInitParams::sTimerDelegate);
Damian Królikb07872c2023-02-17 13:56:47 +0100812#if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
813SimpleSessionResumptionStorage CommonCaseDeviceServerInitParams::sSessionResumptionStorage;
814#endif
815#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
816app::SimpleSubscriptionResumptionStorage CommonCaseDeviceServerInitParams::sSubscriptionResumptionStorage;
817#endif
818app::DefaultAclStorage CommonCaseDeviceServerInitParams::sAclStorage;
819Crypto::DefaultSessionKeystore CommonCaseDeviceServerInitParams::sSessionKeystore;
mkardous-silabs5eba3942024-07-26 19:42:45 -0400820#if CHIP_CONFIG_ENABLE_ICD_CIP
821app::DefaultICDCheckInBackOffStrategy CommonCaseDeviceServerInitParams::sDefaultICDCheckInBackOffStrategy;
822#endif
Damian Królikb07872c2023-02-17 13:56:47 +0100823
Jiacheng Guo735dbb02021-09-11 04:24:07 +0800824} // namespace chip