Matter SDK Coverage Report
Current view: top level - app/server - CommissioningWindowManager.cpp (source / functions) Coverage Total Hit
Test: SHA:4cbce7f768f16e614f5a8ccb8cd93c92cbeae70d Lines: 57.9 % 261 151
Test Date: 2025-04-26 07:09:35 Functions: 58.8 % 34 20

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

Generated by: LCOV version 2.0-1