Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2021-2022 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/icd/server/ICDServerConfig.h>
19 : #include <app/server/CommissioningWindowManager.h>
20 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
21 : #include <app/icd/server/ICDNotifier.h> // nogncheck
22 : #endif
23 : #include <app/reporting/reporting.h>
24 : #include <app/server/Dnssd.h>
25 : #include <app/server/Server.h>
26 : #include <lib/dnssd/Advertiser.h>
27 : #include <lib/support/CodeUtils.h>
28 : #include <platform/CHIPDeviceLayer.h>
29 : #include <platform/CommissionableDataProvider.h>
30 : #include <platform/DeviceControlServer.h>
31 :
32 : using namespace chip::app::Clusters;
33 : using namespace chip::System::Clock;
34 : using namespace chip::Crypto;
35 :
36 : using AdministratorCommissioning::CommissioningWindowStatusEnum;
37 : using chip::app::DataModel::MakeNullable;
38 : using chip::app::DataModel::Nullable;
39 : using chip::app::DataModel::NullNullable;
40 :
41 : namespace {
42 :
43 : // As per specifications (Section 13.3), Nodes SHALL exit commissioning mode after 20 failed commission attempts.
44 : constexpr uint8_t kMaxFailedCommissioningAttempts = 20;
45 :
46 0 : void HandleSessionEstablishmentTimeout(chip::System::Layer * aSystemLayer, void * aAppState)
47 : {
48 0 : chip::CommissioningWindowManager * commissionMgr = static_cast<chip::CommissioningWindowManager *>(aAppState);
49 0 : commissionMgr->OnSessionEstablishmentError(CHIP_ERROR_TIMEOUT);
50 0 : }
51 :
52 0 : void OnPlatformEventWrapper(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
53 : {
54 0 : chip::CommissioningWindowManager * commissionMgr = reinterpret_cast<chip::CommissioningWindowManager *>(arg);
55 0 : commissionMgr->OnPlatformEvent(event);
56 0 : }
57 : } // namespace
58 :
59 : namespace chip {
60 :
61 0 : void CommissioningWindowManager::OnPlatformEvent(const DeviceLayer::ChipDeviceEvent * event)
62 : {
63 0 : if (event->Type == DeviceLayer::DeviceEventType::kCommissioningComplete)
64 : {
65 0 : ChipLogProgress(AppServer, "Commissioning completed successfully");
66 0 : DeviceLayer::SystemLayer().CancelTimer(HandleCommissioningWindowTimeout, this);
67 0 : mCommissioningTimeoutTimerArmed = false;
68 0 : Cleanup();
69 0 : mServer->GetSecureSessionManager().ExpireAllPASESessions();
70 : // That should have cleared out mPASESession.
71 : #if CONFIG_NETWORK_LAYER_BLE && CHIP_DEVICE_CONFIG_SUPPORTS_CONCURRENT_CONNECTION
72 : // If in NonConcurrentConnection, this will already have been completed
73 0 : mServer->GetBleLayerObject()->CloseAllBleConnections();
74 : #endif
75 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
76 0 : chip::WiFiPAF::WiFiPAFLayer::GetWiFiPAFLayer().Shutdown(
77 0 : [](uint32_t id, WiFiPAF::WiFiPafRole role) { DeviceLayer::ConnectivityMgr().WiFiPAFShutdown(id, role); });
78 : #endif
79 : }
80 0 : else if (event->Type == DeviceLayer::DeviceEventType::kFailSafeTimerExpired)
81 : {
82 0 : ChipLogError(AppServer, "Failsafe timer expired");
83 0 : if (mPASESession)
84 : {
85 0 : mPASESession->AsSecureSession()->MarkForEviction();
86 : }
87 0 : HandleFailedAttempt(CHIP_ERROR_TIMEOUT);
88 : }
89 0 : else if (event->Type == DeviceLayer::DeviceEventType::kOperationalNetworkEnabled)
90 : {
91 0 : CHIP_ERROR err = app::DnssdServer::Instance().AdvertiseOperational();
92 0 : if (err != CHIP_NO_ERROR)
93 : {
94 0 : ChipLogError(AppServer, "Operational advertising failed: %" CHIP_ERROR_FORMAT, err.Format());
95 : }
96 : else
97 : {
98 0 : ChipLogProgress(AppServer, "Operational advertising enabled");
99 : }
100 : }
101 : #if CONFIG_NETWORK_LAYER_BLE
102 0 : else if (event->Type == DeviceLayer::DeviceEventType::kCloseAllBleConnections)
103 : {
104 0 : ChipLogProgress(AppServer, "Received kCloseAllBleConnections:%d", static_cast<int>(event->Type));
105 0 : mServer->GetBleLayerObject()->Shutdown();
106 : }
107 : #endif
108 0 : }
109 :
110 1 : void CommissioningWindowManager::Shutdown()
111 : {
112 1 : VerifyOrReturn(nullptr != mServer);
113 :
114 1 : StopAdvertisement(/* aShuttingDown = */ true);
115 :
116 1 : ResetState();
117 : }
118 :
119 5 : void CommissioningWindowManager::ResetState()
120 : {
121 5 : mUseECM = false;
122 : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
123 : mJCM = false;
124 : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
125 :
126 5 : mECMDiscriminator = 0;
127 5 : mECMIterations = 0;
128 5 : mECMSaltLength = 0;
129 :
130 5 : UpdateWindowStatus(CommissioningWindowStatusEnum::kWindowNotOpen);
131 :
132 5 : UpdateOpenerFabricIndex(NullNullable);
133 5 : UpdateOpenerVendorId(NullNullable);
134 :
135 5 : memset(&mECMPASEVerifier, 0, sizeof(mECMPASEVerifier));
136 5 : memset(mECMSalt, 0, sizeof(mECMSalt));
137 :
138 5 : DeviceLayer::SystemLayer().CancelTimer(HandleCommissioningWindowTimeout, this);
139 5 : mCommissioningTimeoutTimerArmed = false;
140 :
141 5 : DeviceLayer::PlatformMgr().RemoveEventHandler(OnPlatformEventWrapper, reinterpret_cast<intptr_t>(this));
142 5 : }
143 :
144 4 : void CommissioningWindowManager::Cleanup()
145 : {
146 4 : StopAdvertisement(/* aShuttingDown = */ false);
147 4 : ResetState();
148 4 : }
149 :
150 0 : void CommissioningWindowManager::OnSessionEstablishmentError(CHIP_ERROR err)
151 : {
152 0 : DeviceLayer::SystemLayer().CancelTimer(HandleSessionEstablishmentTimeout, this);
153 0 : HandleFailedAttempt(err);
154 0 : }
155 :
156 0 : void CommissioningWindowManager::HandleFailedAttempt(CHIP_ERROR err)
157 : {
158 0 : mFailedCommissioningAttempts++;
159 0 : ChipLogError(AppServer, "Commissioning failed (attempt %d): %" CHIP_ERROR_FORMAT, mFailedCommissioningAttempts, err.Format());
160 : #if CONFIG_NETWORK_LAYER_BLE
161 0 : mServer->GetBleLayerObject()->CloseAllBleConnections();
162 : #endif
163 :
164 0 : CHIP_ERROR prevErr = err;
165 0 : if (mFailedCommissioningAttempts < kMaxFailedCommissioningAttempts)
166 : {
167 : // If the number of commissioning attempts has not exceeded maximum
168 : // retries, let's start listening for commissioning connections again.
169 0 : err = AdvertiseAndListenForPASE();
170 : }
171 :
172 0 : if (mAppDelegate != nullptr)
173 : {
174 0 : mAppDelegate->OnCommissioningSessionEstablishmentError(prevErr);
175 : }
176 :
177 0 : if (err != CHIP_NO_ERROR)
178 : {
179 : // The commissioning attempts limit was exceeded, or listening for
180 : // commmissioning connections failed.
181 0 : Cleanup();
182 :
183 0 : if (mAppDelegate != nullptr)
184 : {
185 0 : mAppDelegate->OnCommissioningSessionStopped();
186 : }
187 : }
188 0 : }
189 :
190 0 : void CommissioningWindowManager::OnSessionEstablishmentStarted()
191 : {
192 : // As per specifications, section 5.5: Commissioning Flows
193 0 : constexpr System::Clock::Timeout kPASESessionEstablishmentTimeout = System::Clock::Seconds16(60);
194 0 : DeviceLayer::SystemLayer().StartTimer(kPASESessionEstablishmentTimeout, HandleSessionEstablishmentTimeout, this);
195 :
196 0 : ChipLogProgress(AppServer, "Commissioning session establishment step started");
197 0 : if (mAppDelegate != nullptr)
198 : {
199 0 : mAppDelegate->OnCommissioningSessionEstablishmentStarted();
200 : }
201 0 : }
202 :
203 0 : void CommissioningWindowManager::OnSessionEstablished(const SessionHandle & session)
204 : {
205 0 : DeviceLayer::SystemLayer().CancelTimer(HandleSessionEstablishmentTimeout, this);
206 :
207 0 : ChipLogProgress(AppServer, "Commissioning completed session establishment step");
208 0 : if (mAppDelegate != nullptr)
209 : {
210 0 : mAppDelegate->OnCommissioningSessionStarted();
211 : }
212 :
213 0 : DeviceLayer::PlatformMgr().AddEventHandler(OnPlatformEventWrapper, reinterpret_cast<intptr_t>(this));
214 :
215 0 : StopAdvertisement(/* aShuttingDown = */ false);
216 :
217 0 : auto & failSafeContext = Server::GetInstance().GetFailSafeContext();
218 : // This should never be armed because we don't allow CASE sessions to arm the failsafe when the commissioning window is open and
219 : // we check that the failsafe is not armed before opening the commissioning window. None the less, it is good to double-check.
220 0 : CHIP_ERROR err = CHIP_NO_ERROR;
221 0 : if (failSafeContext.IsFailSafeArmed())
222 : {
223 0 : ChipLogError(AppServer, "Error - arm failsafe is already armed on PASE session establishment completion");
224 : }
225 : else
226 : {
227 0 : err = failSafeContext.ArmFailSafe(kUndefinedFabricIndex,
228 0 : System::Clock::Seconds16(CHIP_DEVICE_CONFIG_FAILSAFE_EXPIRY_LENGTH_SEC));
229 0 : if (err != CHIP_NO_ERROR)
230 : {
231 0 : ChipLogError(AppServer, "Error arming failsafe on PASE session establishment completion");
232 : // Don't allow a PASE session to hang around without a fail-safe.
233 0 : session->AsSecureSession()->MarkForEviction();
234 0 : HandleFailedAttempt(err);
235 : }
236 : }
237 :
238 0 : ChipLogProgress(AppServer, "Device completed Rendezvous process");
239 :
240 0 : if (err == CHIP_NO_ERROR)
241 : {
242 : // When the now-armed fail-safe is disarmed or expires it will handle
243 : // clearing out mPASESession.
244 0 : mPASESession.Grab(session);
245 : }
246 0 : }
247 :
248 6 : CHIP_ERROR CommissioningWindowManager::OpenCommissioningWindow(Seconds32 commissioningTimeout)
249 : {
250 6 : VerifyOrReturnError(commissioningTimeout <= MaxCommissioningTimeout() && commissioningTimeout >= MinCommissioningTimeout(),
251 : CHIP_ERROR_INVALID_ARGUMENT);
252 6 : auto & failSafeContext = Server::GetInstance().GetFailSafeContext();
253 6 : VerifyOrReturnError(failSafeContext.IsFailSafeFullyDisarmed(), CHIP_ERROR_INCORRECT_STATE);
254 :
255 6 : ReturnErrorOnFailure(Dnssd::ServiceAdvertiser::Instance().UpdateCommissionableInstanceName());
256 :
257 6 : ReturnErrorOnFailure(DeviceLayer::SystemLayer().StartTimer(commissioningTimeout, HandleCommissioningWindowTimeout, this));
258 :
259 6 : mCommissioningTimeoutTimerArmed = true;
260 :
261 6 : return AdvertiseAndListenForPASE();
262 : }
263 :
264 6 : CHIP_ERROR CommissioningWindowManager::AdvertiseAndListenForPASE()
265 : {
266 6 : VerifyOrReturnError(mCommissioningTimeoutTimerArmed, CHIP_ERROR_INCORRECT_STATE);
267 :
268 6 : mPairingSession.Clear();
269 :
270 6 : ReturnErrorOnFailure(mServer->GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(
271 : Protocols::SecureChannel::MsgType::PBKDFParamRequest, this));
272 6 : mListeningForPASE = true;
273 :
274 6 : if (mUseECM)
275 : {
276 1 : ReturnErrorOnFailure(SetTemporaryDiscriminator(mECMDiscriminator));
277 1 : ReturnErrorOnFailure(mPairingSession.WaitForPairing(mServer->GetSecureSessionManager(), mECMPASEVerifier, mECMIterations,
278 : ByteSpan(mECMSalt, mECMSaltLength), GetLocalMRPConfig(), this));
279 : }
280 : else
281 : {
282 5 : uint32_t iterationCount = 0;
283 5 : uint8_t salt[kSpake2p_Max_PBKDF_Salt_Length] = { 0 };
284 5 : Spake2pVerifierSerialized serializedVerifier = { 0 };
285 5 : size_t serializedVerifierLen = 0;
286 : Spake2pVerifier verifier;
287 5 : MutableByteSpan saltSpan{ salt };
288 5 : MutableByteSpan verifierSpan{ serializedVerifier };
289 :
290 5 : auto * commissionableDataProvider = DeviceLayer::GetCommissionableDataProvider();
291 5 : ReturnErrorOnFailure(commissionableDataProvider->GetSpake2pIterationCount(iterationCount));
292 5 : ReturnErrorOnFailure(commissionableDataProvider->GetSpake2pSalt(saltSpan));
293 5 : ReturnErrorOnFailure(commissionableDataProvider->GetSpake2pVerifier(verifierSpan, serializedVerifierLen));
294 5 : VerifyOrReturnError(Crypto::kSpake2p_VerifierSerialized_Length == serializedVerifierLen, CHIP_ERROR_INVALID_ARGUMENT);
295 5 : VerifyOrReturnError(verifierSpan.size() == serializedVerifierLen, CHIP_ERROR_INTERNAL);
296 :
297 5 : ReturnErrorOnFailure(verifier.Deserialize(ByteSpan(serializedVerifier)));
298 :
299 5 : ReturnErrorOnFailure(mPairingSession.WaitForPairing(mServer->GetSecureSessionManager(), verifier, iterationCount, saltSpan,
300 : GetLocalMRPConfig(), this));
301 : }
302 :
303 6 : ReturnErrorOnFailure(StartAdvertisement());
304 :
305 6 : return CHIP_NO_ERROR;
306 : }
307 :
308 9 : System::Clock::Seconds32 CommissioningWindowManager::MaxCommissioningTimeout() const
309 : {
310 : #if CHIP_DEVICE_CONFIG_EXT_ADVERTISING
311 : /* Allow for extended announcement only if the device is uncomissioned. */
312 : if (mServer->GetFabricTable().FabricCount() == 0)
313 : {
314 : // Specification section 2.3.1 - Extended Announcement Duration up to 48h
315 : return System::Clock::Seconds32(60 * 60 * 48);
316 : }
317 : #endif
318 : // Specification section 5.4.2.3. Announcement Duration says 15 minutes.
319 9 : return System::Clock::Seconds32(15 * 60);
320 : }
321 :
322 5 : CHIP_ERROR CommissioningWindowManager::OpenBasicCommissioningWindow(Seconds32 commissioningTimeout,
323 : CommissioningWindowAdvertisement advertisementMode)
324 : {
325 5 : RestoreDiscriminator();
326 :
327 : #if CONFIG_NETWORK_LAYER_BLE
328 : // Enable BLE advertisements if commissioning window is to be opened on all supported
329 : // transports, and BLE is supported on the current device.
330 5 : SetBLE(advertisementMode == chip::CommissioningWindowAdvertisement::kAllSupported);
331 : #else
332 : SetBLE(false);
333 : #endif // CONFIG_NETWORK_LAYER_BLE
334 :
335 5 : mFailedCommissioningAttempts = 0;
336 :
337 5 : mUseECM = false;
338 :
339 5 : CHIP_ERROR err = OpenCommissioningWindow(commissioningTimeout);
340 5 : if (err != CHIP_NO_ERROR)
341 : {
342 0 : Cleanup();
343 : }
344 :
345 5 : return err;
346 : }
347 :
348 : CHIP_ERROR
349 1 : CommissioningWindowManager::OpenBasicCommissioningWindowForAdministratorCommissioningCluster(
350 : System::Clock::Seconds32 commissioningTimeout, FabricIndex fabricIndex, VendorId vendorId)
351 : {
352 1 : ReturnErrorOnFailure(OpenBasicCommissioningWindow(commissioningTimeout, CommissioningWindowAdvertisement::kDnssdOnly));
353 :
354 1 : UpdateOpenerFabricIndex(MakeNullable(fabricIndex));
355 1 : UpdateOpenerVendorId(MakeNullable(vendorId));
356 :
357 1 : return CHIP_NO_ERROR;
358 : }
359 :
360 1 : CHIP_ERROR CommissioningWindowManager::OpenEnhancedCommissioningWindow(Seconds32 commissioningTimeout, uint16_t discriminator,
361 : Spake2pVerifier & verifier, uint32_t iterations,
362 : ByteSpan salt, FabricIndex fabricIndex, VendorId vendorId)
363 : {
364 : // Once a device is operational, it shall be commissioned into subsequent fabrics using
365 : // the operational network only.
366 1 : SetBLE(false);
367 :
368 1 : VerifyOrReturnError(salt.size() <= sizeof(mECMSalt), CHIP_ERROR_INVALID_ARGUMENT);
369 :
370 1 : memcpy(mECMSalt, salt.data(), salt.size());
371 1 : mECMSaltLength = static_cast<uint32_t>(salt.size());
372 :
373 1 : mFailedCommissioningAttempts = 0;
374 :
375 1 : mECMDiscriminator = discriminator;
376 1 : mECMIterations = iterations;
377 :
378 1 : memcpy(&mECMPASEVerifier, &verifier, sizeof(Spake2pVerifier));
379 :
380 1 : mUseECM = true;
381 :
382 1 : CHIP_ERROR err = OpenCommissioningWindow(commissioningTimeout);
383 1 : if (err != CHIP_NO_ERROR)
384 : {
385 0 : Cleanup();
386 : }
387 : else
388 : {
389 1 : UpdateOpenerFabricIndex(MakeNullable(fabricIndex));
390 1 : UpdateOpenerVendorId(MakeNullable(vendorId));
391 : }
392 :
393 1 : return err;
394 : }
395 :
396 : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
397 : CHIP_ERROR CommissioningWindowManager::OpenJointCommissioningWindow(Seconds32 commissioningTimeout, uint16_t discriminator,
398 : Spake2pVerifier & verifier, uint32_t iterations, ByteSpan salt,
399 : FabricIndex fabricIndex, VendorId vendorId)
400 : {
401 : mJCM = true;
402 : return OpenEnhancedCommissioningWindow(commissioningTimeout, discriminator, verifier, iterations, salt, fabricIndex, vendorId);
403 : }
404 : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
405 :
406 4 : void CommissioningWindowManager::CloseCommissioningWindow()
407 : {
408 4 : if (IsCommissioningWindowOpen())
409 : {
410 : #if CONFIG_NETWORK_LAYER_BLE
411 4 : if (mListeningForPASE)
412 : {
413 : // We never established PASE, so never armed a fail-safe and hence
414 : // can't rely on it expiring to close our BLE connection. Do that
415 : // manually here.
416 4 : mServer->GetBleLayerObject()->CloseAllBleConnections();
417 : }
418 : #endif
419 4 : ChipLogProgress(AppServer, "Closing pairing window");
420 4 : Cleanup();
421 : }
422 4 : }
423 :
424 42 : CommissioningWindowStatusEnum CommissioningWindowManager::CommissioningWindowStatusForCluster() const
425 : {
426 : // If the condition we use to determine whether we were opened via the
427 : // cluster ever changes, make sure whatever code affects that condition
428 : // marks calls MatterReportingAttributeChangeCallback for WindowStatus as
429 : // needed.
430 42 : if (mOpenerVendorId.IsNull())
431 : {
432 : // Not opened via the cluster.
433 32 : return CommissioningWindowStatusEnum::kWindowNotOpen;
434 : }
435 :
436 10 : return mWindowStatus;
437 : }
438 :
439 12 : bool CommissioningWindowManager::IsCommissioningWindowOpen() const
440 : {
441 12 : return mWindowStatus != CommissioningWindowStatusEnum::kWindowNotOpen;
442 : }
443 :
444 0 : void CommissioningWindowManager::OnFabricRemoved(FabricIndex removedIndex)
445 : {
446 0 : if (!mOpenerFabricIndex.IsNull() && mOpenerFabricIndex.Value() == removedIndex)
447 : {
448 : // Per spec, we should clear out the stale fabric index.
449 0 : UpdateOpenerFabricIndex(NullNullable);
450 : }
451 0 : }
452 :
453 12 : Dnssd::CommissioningMode CommissioningWindowManager::GetCommissioningMode() const
454 : {
455 12 : if (!mListeningForPASE)
456 : {
457 : // We should not be advertising ourselves as in commissioning mode.
458 : // We need to check this before mWindowStatus, because we might have an
459 : // open window even while we are not listening for PASE.
460 5 : return Dnssd::CommissioningMode::kDisabled;
461 : }
462 :
463 7 : switch (mWindowStatus)
464 : {
465 1 : case CommissioningWindowStatusEnum::kEnhancedWindowOpen:
466 : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
467 : return mJCM ? Dnssd::CommissioningMode::kEnabledJointFabric : Dnssd::CommissioningMode::kEnabledEnhanced;
468 : #else
469 1 : return Dnssd::CommissioningMode::kEnabledEnhanced;
470 : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
471 6 : case CommissioningWindowStatusEnum::kBasicWindowOpen:
472 6 : return Dnssd::CommissioningMode::kEnabledBasic;
473 0 : default:
474 0 : return Dnssd::CommissioningMode::kDisabled;
475 : }
476 : }
477 :
478 6 : CHIP_ERROR CommissioningWindowManager::StartAdvertisement()
479 : {
480 : #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING
481 : // notify device layer that advertisement is beginning (to do work such as increment rotating id)
482 : DeviceLayer::ConfigurationMgr().NotifyOfAdvertisementStart();
483 : #endif
484 :
485 : #if CONFIG_NETWORK_LAYER_BLE
486 6 : if (mIsBLE)
487 : {
488 1 : CHIP_ERROR err = chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true);
489 : // BLE advertising may just not be supported. That should not prevent
490 : // us from opening a commissioning window and advertising over IP.
491 1 : if (err == CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE)
492 : {
493 0 : ChipLogProgress(AppServer, "BLE networking available but BLE advertising is not supported");
494 0 : err = CHIP_NO_ERROR;
495 : }
496 1 : ReturnErrorOnFailure(err);
497 : }
498 : #endif // CONFIG_NETWORK_LAYER_BLE
499 :
500 6 : if (mUseECM)
501 : {
502 1 : UpdateWindowStatus(CommissioningWindowStatusEnum::kEnhancedWindowOpen);
503 : }
504 : else
505 : {
506 5 : UpdateWindowStatus(CommissioningWindowStatusEnum::kBasicWindowOpen);
507 : }
508 :
509 6 : if (mAppDelegate != nullptr)
510 : {
511 0 : mAppDelegate->OnCommissioningWindowOpened();
512 : }
513 :
514 : // reset all advertising, switching to our new commissioning mode.
515 6 : app::DnssdServer::Instance().StartServer();
516 :
517 6 : return CHIP_NO_ERROR;
518 : }
519 :
520 5 : CHIP_ERROR CommissioningWindowManager::StopAdvertisement(bool aShuttingDown)
521 : {
522 5 : RestoreDiscriminator();
523 :
524 5 : mServer->GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest);
525 5 : mListeningForPASE = false;
526 5 : mPairingSession.Clear();
527 :
528 : // If aShuttingDown, don't try to change our DNS-SD advertisements.
529 5 : if (!aShuttingDown)
530 : {
531 : // Stop advertising commissioning mode, since we're not accepting PASE
532 : // connections right now. If we start accepting them again (via
533 : // AdvertiseAndListenForPASE) that will call StartAdvertisement as needed.
534 4 : app::DnssdServer::Instance().StartServer();
535 : }
536 :
537 : #if CONFIG_NETWORK_LAYER_BLE
538 5 : if (mIsBLE)
539 : {
540 : // Ignore errors from SetBLEAdvertisingEnabled (which could be due to
541 : // BLE advertising not being supported at all). Our commissioning
542 : // window is now closed and we need to notify our delegate of that.
543 1 : (void) chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false);
544 : }
545 : #endif // CONFIG_NETWORK_LAYER_BLE
546 :
547 5 : if (mAppDelegate != nullptr)
548 : {
549 0 : mAppDelegate->OnCommissioningWindowClosed();
550 : }
551 :
552 5 : return CHIP_NO_ERROR;
553 : }
554 :
555 1 : CHIP_ERROR CommissioningWindowManager::SetTemporaryDiscriminator(uint16_t discriminator)
556 : {
557 1 : return app::DnssdServer::Instance().SetEphemeralDiscriminator(MakeOptional(discriminator));
558 : }
559 :
560 10 : CHIP_ERROR CommissioningWindowManager::RestoreDiscriminator()
561 : {
562 10 : return app::DnssdServer::Instance().SetEphemeralDiscriminator(NullOptional);
563 : }
564 :
565 0 : void CommissioningWindowManager::HandleCommissioningWindowTimeout(chip::System::Layer * aSystemLayer, void * aAppState)
566 : {
567 0 : auto * commissionMgr = static_cast<CommissioningWindowManager *>(aAppState);
568 0 : commissionMgr->mCommissioningTimeoutTimerArmed = false;
569 0 : commissionMgr->CloseCommissioningWindow();
570 0 : }
571 :
572 0 : void CommissioningWindowManager::OnSessionReleased()
573 : {
574 : // The PASE session has died, probably due to CloseSession. Immediately
575 : // expire the fail-safe, if it's still armed (which it might not be if the
576 : // PASE session is being released due to the fail-safe expiring or being
577 : // disarmed).
578 : //
579 : // Expiring the fail-safe will make us start listening for new PASE sessions
580 : // as needed.
581 : //
582 : // Note that at this point the fail-safe _must_ be associated with our PASE
583 : // session, since we arm it when the PASE session is set up, and anything
584 : // that disarms the fail-safe would also tear down the PASE session.
585 0 : ExpireFailSafeIfArmed();
586 0 : }
587 :
588 0 : void CommissioningWindowManager::ExpireFailSafeIfArmed()
589 : {
590 0 : auto & failSafeContext = Server::GetInstance().GetFailSafeContext();
591 0 : if (failSafeContext.IsFailSafeArmed())
592 : {
593 0 : failSafeContext.ForceFailSafeTimerExpiry();
594 : }
595 0 : }
596 :
597 11 : void CommissioningWindowManager::UpdateWindowStatus(CommissioningWindowStatusEnum aNewStatus)
598 : {
599 11 : CommissioningWindowStatusEnum oldClusterStatus = CommissioningWindowStatusForCluster();
600 11 : if (mWindowStatus != aNewStatus)
601 : {
602 9 : mWindowStatus = aNewStatus;
603 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
604 : app::ICDListener::KeepActiveFlags request = app::ICDListener::KeepActiveFlag::kCommissioningWindowOpen;
605 : if (mWindowStatus != CommissioningWindowStatusEnum::kWindowNotOpen)
606 : {
607 : app::ICDNotifier::GetInstance().NotifyActiveRequestNotification(request);
608 : }
609 : else
610 : {
611 : app::ICDNotifier::GetInstance().NotifyActiveRequestWithdrawal(request);
612 : }
613 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
614 : }
615 :
616 11 : if (CommissioningWindowStatusForCluster() != oldClusterStatus)
617 : {
618 : // The Administrator Commissioning cluster is always on the root endpoint.
619 2 : MatterReportingAttributeChangeCallback(kRootEndpointId, AdministratorCommissioning::Id,
620 : AdministratorCommissioning::Attributes::WindowStatus::Id);
621 : }
622 11 : }
623 :
624 7 : void CommissioningWindowManager::UpdateOpenerVendorId(Nullable<VendorId> aNewOpenerVendorId)
625 : {
626 : // Changing the opener vendor id affects what
627 : // CommissioningWindowStatusForCluster() returns.
628 7 : CommissioningWindowStatusEnum oldClusterStatus = CommissioningWindowStatusForCluster();
629 :
630 7 : if (mOpenerVendorId != aNewOpenerVendorId)
631 : {
632 : // The Administrator Commissioning cluster is always on the root endpoint.
633 4 : MatterReportingAttributeChangeCallback(kRootEndpointId, AdministratorCommissioning::Id,
634 : AdministratorCommissioning::Attributes::AdminVendorId::Id);
635 : }
636 :
637 7 : mOpenerVendorId = aNewOpenerVendorId;
638 :
639 7 : if (CommissioningWindowStatusForCluster() != oldClusterStatus)
640 : {
641 : // The Administrator Commissioning cluster is always on the root endpoint.
642 2 : MatterReportingAttributeChangeCallback(kRootEndpointId, AdministratorCommissioning::Id,
643 : AdministratorCommissioning::Attributes::WindowStatus::Id);
644 : }
645 7 : }
646 :
647 7 : void CommissioningWindowManager::UpdateOpenerFabricIndex(Nullable<FabricIndex> aNewOpenerFabricIndex)
648 : {
649 7 : if (mOpenerFabricIndex != aNewOpenerFabricIndex)
650 : {
651 : // The Administrator Commissioning cluster is always on the root endpoint.
652 4 : MatterReportingAttributeChangeCallback(kRootEndpointId, AdministratorCommissioning::Id,
653 : AdministratorCommissioning::Attributes::AdminFabricIndex::Id);
654 : }
655 :
656 7 : mOpenerFabricIndex = aNewOpenerFabricIndex;
657 7 : }
658 :
659 0 : CHIP_ERROR CommissioningWindowManager::OnUnsolicitedMessageReceived(const PayloadHeader & payloadHeader,
660 : Messaging::ExchangeDelegate *& newDelegate)
661 : {
662 : using Protocols::SecureChannel::MsgType;
663 :
664 : // Must be a PBKDFParamRequest message. Stop listening to new
665 : // PBKDFParamRequest messages and hand it off to mPairingSession. If
666 : // mPairingSession's OnMessageReceived fails, it will call our
667 : // OnSessionEstablishmentError, and that will either start listening for a
668 : // new PBKDFParamRequest or not, depending on how many failures we had seen.
669 : //
670 : // It's very important that we stop listening here, so that new incoming
671 : // PASE establishment attempts don't interrupt our existing establishment.
672 0 : mServer->GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(MsgType::PBKDFParamRequest);
673 0 : newDelegate = &mPairingSession;
674 0 : return CHIP_NO_ERROR;
675 : }
676 :
677 0 : void CommissioningWindowManager::OnExchangeCreationFailed(Messaging::ExchangeDelegate * delegate)
678 : {
679 : using Protocols::SecureChannel::MsgType;
680 :
681 : // We couldn't create an exchange, so didn't manage to call
682 : // OnMessageReceived on mPairingSession. Just go back to listening for
683 : // PBKDFParamRequest messages.
684 0 : mServer->GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(MsgType::PBKDFParamRequest, this);
685 0 : }
686 :
687 : } // namespace chip
|